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 |
|---|---|---|---|---|---|
In this post, we will learn how to read and write JSON files using Python. In the first part, we are going to use the Python package json to create and read a JSON file as well as write a JSON file. After that, we are going to use Pandas read_json method to load JSON files into Pandas dataframe. Here, we will learn how to read from a JSON file locally and from an URL as well as how to read a nested JSON file using Pandas.
Finally, as a bonus, we will also learn how to manipulate data in Pandas dataframes, rename columns, and plot the data using Seaborn.
What is a JSON File?
JSON, short for JavaScript Object Notation, is a compact, text based format used to exchange data. This format that is common for downloading, and storing, information from web servers via so-called Web APIs. JSON is a text-based format and when opening up a JSON file, we will recognize the structure. That is, it is not so different from Python’s structure for a dictionary.
In the first Python parsing json example, we are going to use the Python module json to create a JSON file. After we’ve done that we are going to load the JSON file. In this Python JSON tutorial, we start by create a dictionary for our data:
import json data = {"Sub_ID":["1","2","3","4","5","6","7","8" ], "Name":["Erik", "Daniel", "Michael", "Sven", "Gary", "Carol","Lisa", "Elisabeth" ], "Salary":["723.3", "515.2", "621", "731", "844.15","558", "642.8", "732.5" ], "StartDate":[ "1/1/2011", "7/23/2013", "12/15/2011", "6/11/2013", "3/27/2011","5/21/2012", "7/30/2013", "6/17/2014"], "Department":[ "IT", "Manegement", "IT", "HR", "Finance", "IT", "Manegement", "IT"], "Sex":[ "M", "M", "M", "M", "M", "F", "F", "F"]} print(data)
Parsing JSON in Python
In the next Python parsing JSON example, we are going to read the JSON file, that we created above. Reading a JSON file in Python is pretty easy, we open the file using open. After this is done, we read the JSON file using the load method.
with open('data.json') as json_file: data = json.load(json_file) print(data)
Now, before going on learning how to save a JSON file in Python, it is worth mentioning that we can also parse Excel files. For example, see the post about reading xlsx files in Python for more information-
Saving to a JSON file
In this section, we will learn how to write a JSON file in Python. In Python, this can be done using the module json . This module enables us both to read and write content to and from a JSON file. This module converts the JSON format to Python’s internal format for Data Structures. So we can work with JSON structures just as we do in the usual way with Python’s own data structures.
Python JSON Example:
In the example code below, we will learn how to make a JSON file in Python. First, we start by importing the json module. After we’ve done that, we open up a new file and use the dump method to write a json file using Python.
import json with open('data.json', 'w') as outfile: json.dump(data, outfile)
It is, of course, possible to save JSON to other formats, such as xlsx, and CSV, and we will learn how to export a Pandas dataframe to CSV, later in this blog post.
How to Use Pandas to Load a JSON File
Now, if we are going to work with the data we might want to use Pandas to load the JSON file into a Pandas dataframe. This will enable us to manipulate data, do summary statistics, and data visualization using Pandas built-in methods. Note, we will cover this briefly later in this post also.
Pandas Read Json Example:
In the next example we are going to use Pandas read_json method to read the JSON file we wrote earlier (i.e., data.json). It’s fairly simple we start by importing pandas as pd:
import pandas as pd df = pd.read_json('data.json') df
The output, when working with Jupyter Notebooks, will look like this:
It’s also possible to convert a dictionary to a Pandas dataframe. Make sure to check that post out for more information.
Data Manipulation using Pandas
Now that we have loaded the JSON file into a Pandas dataframe we are going use Pandas inplace method to modify our dataframe. We start by setting the Sub_ID column as index.
df.set_index('Sub_ID', inplace=True) df
Pandas JSON to CSV Example
Now when we have loaded a JSON file into a dataframe we may want to save it in another format. For instance, we may want to save it as a CSV file and we can do that using Pandas to_csv method. It may be useful to store it in a CSV, if we prefer to browse through the data in a text editor or Excel.
In the Pandas JSON to CSV example below, we carry out the same data manipulation method.
df.to_csv("data.csv")
Pandas to JSON Example
In this section, we are going to learn how to save Pandas dataframe to JSON. If we, for instance, have our data stored in a CSV file, locally, but want to enable the functionality of the JSON files we will use Pandas to_json method:
df = pd.read_csv("data.csv") # Save dataframe to JSON format df.to_json("data.json")
Learn more about working with CSV files using Pandas in the Pandas Read CSV Tutorial
How to Load JSON from an URL
We have now seen how easy it is to create a JSON file, write it to our hard drive using Python Pandas, and, finally, how to read it using Pandas. However, as previously mentioned, many times the data in stored in the JSON format are on the web.
Thus, in this section of the Python json guide, we are going to learn how to use Pandas read_json method to read a JSON file from a URL. Most often, it’s fairly simple we just create a string variable pointing to the URL:
url = "" df = pd.read_json(url) df.head()
Load JSON from an URL Second Example
When loading some data, using Pandas read_json seems to create a dataframe with dictionaries within each cell. One way to deal with these dictionaries, nested within dictionaries, is to work with the Python module request. This module also has a method for parsing JSON files. After we have parsed the JSON file we will use the method json_normalize to convert the JSON file to a dataframe.
import requests from pandas.io.json import json_normalize url = "" resp = requests.get(url=url) df = json_normalize(resp.json()) df.head()
As can be seen in the image above, the column names are quite long. This is quite impractical when we are going to create a time series plot, later, using Seaborn. We are now going to rename the columns so they become a bit easier to use.
In the code example below, we use Pandas rename method together with the Python module re. That is, we are using a regular expression to remove “statistics.# of” and “statistics.” from the column names. Finally, we are also replacing dots (“.”) with underscores (“_”) using the str.replace method:
import re df.rename(columns=lambda x: re.sub("statistics.# of","",x), inplace=True) df.rename(columns=lambda x: re.sub("statistics.","",x), inplace=True) df.columns = df.columns.str.replace("[.]", "_") df.head()
Renaming columns is something that is quicker, and easier, done using the Python package Pyjanitor (thanks Shantanu Oak, for pointing this out in the comment section). See how to use Pandas and Pyjanitor to rename columns, among other things, using Pyjanitor:
Time Series Plot from JSON Data using Seaborn
In the last example, in this post, we are going to use Seaborn to create a time series plot. The data we loaded from JSON to a dataframe contains data about delayed and canceled flights. We are going to use Seaborns lineplot method to create a time series plot of the number of canceled flights throughout 2003 to 2016, grouped by carrier code.
%matplotlib inline import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure(figsize=(10, 7)) g = sns.lineplot(x="timeyear", y="flightscancelled", ci=False, hue="carriercode", data=df) g.set_ylabel("Flights Cancelled",fontsize=20) g.set_xlabel("Year",fontsize=20) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
Note, we changed the font size as well as the x- and y-axis’ labels using the methods set_ylabel and set_xlabel. Furthermore, we also moved the legend using the legend method from matplotlib.
For more about exploratory data analysis using Python:
- In the post 9 Data Visualization Techniques That You Should Learn in Python, you will learn 9 different data visualization methods and how to carry them out using Python and Seaborn.
- Exploratory Data Analysis using Python, Pandas, and Seaborn
Conclusion
In this post, we have learned how to write a JSON file from a Python dictionary, how to load that JSON file using Python and Pandas. Furthermore, we have also learned how to use Pandas to load a JSON file from a URL to a dataframe, how to read a nested JSON file to a dataframe.
Here’s a link to a Jupyter Notebook containing all code examples in this post.
Very informative article. I will like to mention that renaming columns is made a lot easier using “clean_names” method provided by pyjanitor.
Hey Shantanu,
Thanks for your comment and your suggestion. I will look into the clean_names method provided by pyjanitor.
Best,
Erik
Thanks again Shantanu for letting me know about Pyjanitor. I ended up writing a blog post using it,
Best,
Erik | https://www.marsja.se/how-to-read-and-write-json-files-using-python-and-pandas/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-read-and-write-json-files-using-python-and-pandas | CC-MAIN-2020-24 | refinedweb | 1,646 | 71.85 |
.
Write a Kotlin Program to Check a given number is palindrome or not.
For example,
Input: 1122 Output: 1122 is not palindrome
Input: 12321 Output 12321 is palindrome
1. Program to Check Whether Number is Palindrome
Sourcecode –
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter n:") var n = read.nextInt() val origN = n var reverseN = 0 while (n != 0) { val remainder = n % 10 reverseN = reverseN * 10 + remainder n /= 10 } val result = if(reverseN == origN) "$origN is palindrome" else "$origN is not palindrome" println(result) }
When you run the program, output will be –
Enter n: 32324 32324 is not palindrome
Explanation:
We can check whether number is palindrome or not by comparing original and it’s reversed number.
For example,
Let’s assume n = 123.
It’s reversed number will be 321.
Since 321 is not equal to 123, 123 is not palindrome.
Let’s take another example,
n = 12321
It’s reversed number will be 12321.
Since 12321 (original) is equal to 12321 (reversed number), 12321 is palindrome.
In our program, we
– stored original number in variable origN
– reversed n and stored it in variable reverseN
Then, we compared origN and reverseN to check for palindrome
Thus, we went through Kotlin Program to check number is palindrome or not. | https://tutorialwing.com/kotlin-program-to-check-number-is-palindrome-or-not/ | CC-MAIN-2020-50 | refinedweb | 213 | 72.66 |
Hi Tom; please keep these discussions on the list, thanks! On Sun, 2011-12-18 at 12:40 -0800, Tom Rosmond wrote: > I have been writing makefile for a long time, and although I am > certainly not an expert, I thought I knew what I was doing. However, I > haven't used the conditional concept very much, so I have more to learn. The thing to keep clearly in mind is which statements are makefile statements (variable assignments, rule declarations, and GNU make preprocessor statements like export, ifeq/ifneq/ifdef, define, etc. etc.) and which are shell statements. All makefile statements CANNOT be prefixed with a TAB [*], and all shell statements MUST be prefixed by a TAB. > If I remove the tabs, I get the familiar 'missing separator' message, > which usually means tabs are missing from the rule. This seems like a > catch22. I'd appreciate any suggestions on making this work. > > > all: > > > ifeq ($(HOST),cedar) > > > @echo $(HOST) > > > endif Please provide the specific example which shows the "missing separator" message when you run it. If you remove the TABs from the makefile statements then you will not see that message, so you are doing something else here; without seeing what you did we can't comment on what might be wrong. Cheers! [*] It's not technically true that makefile statements cannot be prefixed by a TAB; GNU make actually only treats TAB-indented lines as shell lines if they appear in a "rule context"; but it's much simpler to use the general rule and not rely on the special cases. -- ------------------------------------------------------------------------------- Paul D. Smith <address@hidden> Find some GNU make tips at: "Please remain calm...I may be mad, but I am a professional." --Mad Scientist | http://lists.gnu.org/archive/html/help-make/2011-12/msg00040.html | CC-MAIN-2014-41 | refinedweb | 286 | 68.7 |
#1839646, was opened at 2007-11-27 17:33
Message generated for change (Comment added) made by psr
You can respond by visiting:
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: General
Group: SQLObject release (specify)
Status: Closed
Resolution: Accepted
Priority: 5
Private: No
Submitted By: Peter Russell (psr)
Assigned to: Oleg Broytmann (phd)
Summary: SQLObject instances of same class with same ID should be ==
Initial Comment:
I've got a failing unittest in some code where I assert that:
group in member.groups
where Group and Member are InheritableSQLObject classes, related by a RelatedJoin. The test loads group and member, then calls the "add a member to a group" controller of my web app, to add the member to the group.
The assertion fails despite the controller working correctly, because SQLObject doesn't override __eq__ to ensure that two different python instances pointing at the same row are equal.
Presumably adding the following to the definition of SQLObject would work
def __eq__(self, other):
if self.__class__ == other.__class__:
if self.id == other.id:
return True
return False
This is occuring with an SQLite in-memory database, with SQLObject 0.7.7 (I know I should upgrade!)
----------------------------------------------------------------------
Comment By: Peter Russell (psr)
Date: 2008-04-10 12:51
Logged In: YES
user_id=447903
Originator: YES
Thanks Oleg, that's brilliant!
----------------------------------------------------------------------
Comment By: Oleg Broytmann (phd)
Date: 2007-12-26 12:33
Logged In: YES
user_id=4799
Originator: NO
Implemented in the trunk. I added all rich comparison methods and a test.
Committed to the trunk at the revision 3184. Will be in SQLObject 0.10. | https://sourceforge.net/p/sqlobject/mailman/sqlobject-cvs/?viewmonth=200804&viewday=10 | CC-MAIN-2017-09 | refinedweb | 286 | 60.95 |
A Python wrapper for Tokyo Cabinet database using ctypes.
Project description
Tokyo Cabinet () is a modern implementation of DBM database. Mikio Hirabayashi (the author of Tokyo Cabinet) describe the project as:.
The py-tcdb project is an interface to the library using the ctypes Python module and provides a two-level access to TC functions: a low level and a high level.
Low Level API
We can interface with TC library using directly the tc module. This module declare all functions and data types. For example, if we want to create a HDB (hash database object) we can write:
from tcdb import tc from tcdb import hdb db = tc.hdb_new() if not tc.hdb_open(db, 'example.tch', hdb.OWRITER|hdb.OCREAT): print tc.hdb_errmsg(tc.hdb_ecode(db)) if not tc.hdb_put2(db, 'key', 'value'): print tc.hdb_errmsg(tc.hdb_ecode(db)) v = tc.hdb_get2(db, 'key') print 'VALUE:', v.value tc.hdb_close(db) tc.hdb_del(db)
The low level API works with ctypes types (like c_char_p or c_int).
High Level API
For each kind of database type allowed in TC, we have a Python class that encapsulate all the functionality. For every class we try to emulate the bsddb Python module interface. This interface is quite similar to a dict data type with persistence.
Also, for HDB, DBD and FDB databases we have a simple version, designed to work only with strings. This version is faster than no-simple ones: it avoids serialization, data conversions (in Python arena) and use a different way for call C functions. Use the ‘simple’ class if you want speed and only need string management.
We also try to improve this API. For example, we can work with transactions using the with Python keyword.
Hash Database
We can use the HDB class to create and manage TC hash databases. This class behaves like a dictionary object, but we can use put and get methods in order to have more control over the stored data. In a hash database we can store serialized Python objects as a key or as a value, or raw data (that can be retrieved from the database using C, Lua, Perl or Java).
from tcdb import hdb # The open method can change other params like cache or # auto defragmentation steep. db = hdb.HDB() db.open('example.tch') # Store pickled object in the database db['key'] = 10 assert type(db['key']) == int db['key'] = 1+1j assert type(db['key']) == complex db[1+1j] = 'text' assert type(db[1+1j]) == str # If we use put/get, we can store raw data # Equiv. to use db.put_int('key', 10, as_raw=True) db.put('key', 10, raw_key=True, raw_value=True) # Equiv. to use db.get_int('key', as_raw=True) assert db.get('key', raw_key=True, value_type=int) == 10 # We can remove records using 'del' keyword # or out methods db.out('key', as_raw=True) # We can iterate over the records. for key, value in db.iteritems(): print key, ':', value # The 'with' keywork works as expected with db: db[10] = 'ten' assert db[10] == 'ten' raise Exception # Because we abort the transaction, we don't # have the new record try: db[10] except KeyError: pass
B+ Tree Database
We can use the class BDB to create and manage B+ tree TC databases. The API is quite similar to the HDB one. One thing that we can do with BDB class is that we can access using a Cursor. With range we can access to a set of ordered keys in a efficient way, and with Cursor object we can navigate over the database.
Fixed-length Database
FDB class can create and manage a fixed-length array database. In this kind of database we can only use int keys, like in a dynamic array.
Table Database
Tokyo Cabinet can use a variation of a hash database to store table-like object. In Python we can use a dict object to represent a single table. With THD we can store these tables and make queries using Query object.
from tcdb import tdb # The open method can change other params like cache or # auto defragmentation steep. db = tdb.TDB() db.open('example.tct') # Store directly a new table alice = {'user': 'alice', 'name': 'Alice', 'age': 23} db['pk'] = alice assert db['pk'] == alice assert type(db['pk']['age']) == int # If we use put/get, we can store raw data db.put('pk', alice, raw_key=True, raw_cols=True) # Equiv. to use db.get_col_int('pk', 'age', raw_key=True) schema = {'user': str, 'name': str, 'age': int} assert db.get('pk', raw_key=True, schema=schema)['age'] == 23 # We can remove records using 'del' keyword # or out methods del db['pk']
Abstract Database
For completeness, we include the ADB abstract interface for accessing hash, B+ tree, fixed-length and table database objects.
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/py-tcdb/ | CC-MAIN-2018-26 | refinedweb | 822 | 74.19 |
Magic Firewall is Cloudflare’s replacement for network-level firewall hardware. It evaluates gigabits of traffic every second against user-defined rules that can include millions of IP addresses. Writing a firewall rule for each IP address is cumbersome and verbose, so we have been building out support for various IP lists in Magic Firewall—essentially named groups that make the rules easier to read and write. Some users want to reject packets based on our growing threat intelligence of bad actors, while others know the exact set of IPs they want to match, which Magic Firewall supports via the same API as Cloudflare’s WAF.
With all those IPs, the system was using more of our memory budget than we’d like. To understand why, we need to first peek behind the curtain of our magic.
Life inside a network namespace
Magic Transit and Magic WAN enable Cloudflare to route layer 3 traffic, and they are the front door for Magic Firewall. We have previously written about how Magic Transit uses network namespaces to route packets and isolate customer configuration. Magic Firewall operates inside these namespaces, using nftables as the primary implementation of packet filtering.
When a user makes an API request to configure their firewall, a daemon running on every server detects the change and makes the corresponding changes to nftables. Because nftables configuration is stored within the namespace, each user’s firewall rules are isolated from the next. Every Cloudflare server routes traffic for all of our customers, so it’s important that the firewall only applies a customer’s rules to their own traffic.
Using our existing technologies, we built IP lists using nftables sets. In practice, this means that the wirefilter expression
ip.geoip.country == “US”
is implemented as
table ip mfw { set geoip.US { typeof ip saddr elements = { 192.0.2.0, … } } chain input { ip saddr @geoip.US block } }
This design for the feature made it very easy to extend our wirefilter syntax so that users could write rules using all the different IP lists we support.
Scaling to many customers
We chose this design since sets fit easily into our existing use of nftables. We shipped quickly with just a few, relatively small lists to a handful of customers. This approach worked well at first, but we eventually started to observe a dramatic increase in our system’s memory use. It’s common practice for our team to enable a new feature for just a few customers at first. Here’s what we observed as those customers started using IP lists:
It turns out you can’t store millions of IPs in the kernel without someone noticing, but the real problem is that we pay that cost for each customer that uses them. Each network namespace gets a complete copy of all the lists that its rules reference. Just to make it perfectly clear, if 10 users have a rule that uses the anonymizer list, then a server has 10 copies of that list stored in the kernel. Yikes!
And it isn’t just the storage of these IPs that caused alarm; the sheer size of the nftables configuration causes nft (the command-line program for configuring nftables) to use quite a bit of compute power.
Can you guess when the nftables updates take place? Now the CPU usage wasn’t particularly problematic, as the service is already quite lean. However, those spikes also create competition with other services that heavily use netlink sockets. At one point, a monitoring alert for another service started firing for high CPU, and a fellow development team went through the incident process only to realize our system was the primary contributor to the problem. They made use of the
-terse flag to prevent nft from wasting precious time rendering huge lists of IPs, but degrading another team’s service was a harsh way to learn that lesson.
We put quite a bit of effort into working around this problem. We tried doing incremental updates of the sets, only adding or deleting the elements that had changed since the last update. It was helpful sometimes, but the complexity ended up not being worth the small savings. Through a lot of profiling, we found that splitting an update across multiple statements improved the situation some. This means we changed
add element ip mfw set0 { 192.0.2.0, 192.0.2.2, …, 198.51.100.0, 198.51.100.2, … }
to
add element ip mfw set0 { 192.0.2.0, … } add element ip mfw set0 { 198.51.100.0, … }
just to squeeze out a second or two of reduced time that nft took to process our configuration. We were spending a fair amount of development cycles looking for optimizations, and we needed to find a way to turn the tides.
One more step with eBPF
As we mentioned on our blog recently, Magic Firewall leverages eBPF for some advanced packet-matching. And it may not be a big surprise that eBPF can match an IP in a list, but it wasn’t a tool we thought to reach for a year ago. What makes eBPF relevant to this problem is that eBPF maps exist regardless of a network namespace. That’s right; eBPF gives us a way to share this data across all the network namespaces we create for our customers.
Since several of our IP lists contain ranges, we can’t use a simple
BPF_MAP_TYPE_HASH or
BPF_MAP_TYPE_ARRAY to perform a lookup. Fortunately, Linux already has a data structure that we can use to accommodate ranges: the
BPF_MAP_TYPE_LPM_TRIE.
Given an IP address, the trie’s implementation of
bpf_map_lookup_elem() will return a non-null result if the IP falls within any of the ranges already inserted into the map. And using the map is about as simple as it gets for eBPF programs. Here’s an example:
typedef struct { __u32 prefix_len; __u8 ip[4]; } trie_key_t; SEC("maps") struct bpf_map_def ip_list = { .type = BPF_MAP_TYPE_LPM_TRIE, .key_size = sizeof(trie_key_t), .value_size = 1, .max_entries = 1, .map_flags = BPF_F_NO_PREALLOC, }; SEC("socket/saddr_in_list") int saddr_in_list(struct __sk_buff *skb) { struct iphdr iph; trie_key_t trie_key; bpf_skb_load_bytes(skb, 0, &iph, sizeof(iph)); trie_key.prefix_len = 32; trie_key.ip[0] = iph.saddr & 0xff; trie_key.ip[1] = (iph.saddr >> 8) & 0xff; trie_key.ip[2] = (iph.saddr >> 16) & 0xff; trie_key.ip[3] = (iph.saddr >> 24) & 0xff; void *val = bpf_map_lookup_elem(&ip_list, &trie_key); return val == NULL ? BPF_OK : BPF_DROP; }
nftables befriends eBPF
One of the limitations of our prior work incorporating eBPF into the firewall involves how the program is loaded into the nftables ruleset. Because the nft command-line program does not support calling a BPF program from a rule, we formatted the Netlink messages ourselves. While this allowed us to insert a rule that executes an eBPF program, it came at the cost of losing out on atomic rule replacements.
So any native nftables rules could be applied in one transaction, but any eBPF-based rules would have to be inserted afterwards. This introduces some headaches for handling failures—if inserting an eBPF rule fails, should we simply retry, or perhaps roll back the nftables ruleset as well? And what if those follow-up operations fail?
In other words, we went from a relatively simple operation—the new firewall configuration either fully applied or didn’t—to a much more complex one. We didn’t want to keep using more and more eBPF without solving this problem. After hacking on the nftables repo for a few days, we came out with a patch that adds a BPF keyword to the nftables configuration syntax.
I won’t cover all the changes, which we hope to upstream soon, but there were two key parts. The first is implementing struct expr_ops and some methods required, which is how nft’s parser knows what to do with each keyword in its configuration language (like the “bpf” keyword we introduced). The second is just a different approach for what we solved previously. Instead of directly formatting struct xt_bpf_info_v1 into a byte array as iptables does, nftables uses the nftnl library to create the netlink messages.
Once we had our footing working in a foreign codebase, that code turned out fairly simple.
static void netlink_gen_bpf(struct netlink_linearize_ctx *ctx, const struct expr *expr, enum nft_registers dreg) { struct nftnl_expr *nle; nle = alloc_nft_expr("match"); nftnl_expr_set_str(nle, NFTNL_EXPR_MT_NAME, "bpf"); nftnl_expr_set_u8(nle, NFTNL_EXPR_MT_REV, 1); nftnl_expr_set(nle, NFTNL_EXPR_MT_INFO, expr->bpf.info, sizeof(struct xt_bpf_info_v1)); nft_rule_add_expr(ctx, nle, &expr->location); }
With the patch finally built, it became possible for us to write configuration like this where we can provide a path to any pinned eBPF program.
# nft -f - <<EOF table ip mfw { chain input { bpf pinned "/sys/fs/bpf/filter" drop } } EOF
And now we can mix native nftables matches with eBPF programs without giving up the atomic nature of nft commands. This unlocks the opportunity for us to build even more advanced packet inspection and protocol detection in eBPF.
Results
This plot shows kernel memory during the time of the deployment - the change was rolled out to each namespace over a few hours.
Though at this point, we’ve merely moved memory out of this slab. Fortunately, the eBPF map memory now appears in the cgroup for our Golang process, so it’s relatively easy to report. Here’s the point at which we first started populating the maps:
This change was pushed a couple of weeks before the maps were actually used in the firewall (i.e. the graph just above). And it has remained constant ever since—unlike our original design, the number of customers is no longer a predominant factor in this feature’s resource usage. The new model makes us more confident about how the service will behave as our product continues to grow.
Other than being better positioned to use eBPF more in the future, we made a significant improvement on the efficiency of the product today. In any project that grows rapidly for a while, an engineer can often see a few pesky pitfalls looming on the horizon. It is very satisfying to dive deep into these technologies and come out with a creative, novel solution before experiencing too much pain. We love solving hard problems and improving our systems to handle rapid growth in addition to pushing lots of new features.
Does that sound like an environment you want to work in? Consider applying! | https://blog.cloudflare.com/magic-firewall-optimizing-ip-lists/ | CC-MAIN-2022-21 | refinedweb | 1,722 | 60.55 |
DEBSOURCES
Skip Quicknav
sources / libperl6-caller-perl / 0.100-3.1 / Changes
123456789101112131415161718192021
Revision history for Perl6-Caller
0.100 October 18, 2009
- Move author tests out of the way.
0.04 April 21, 2007
- Got rid of the alternate package altogether.
0.03 April 21, 2007
- Had to rename the 'caller' package to '_caller' because
FindBin::libs has a 'package caller' declaration and thus the author
now owns that namespace.
0.02 April 21, 2007
- First public release.
- I lied. This is the second public release, but I fixed a few doc
nits.
0.01 Date/time
First version, released on an unsuspecting world. | https://sources.debian.org/src/libperl6-caller-perl/0.100-3.1/Changes/ | CC-MAIN-2021-49 | refinedweb | 105 | 68.26 |
Type: Posts; User: LeanA
Hi Arjay, thanks for this.
I just tested it and it errors the same (0xC0000005). However, based from my post above, I tried changing the CoInitialize to CoInitializeEx(0, Multithreaded) and CTRL +...
Hi all,
I just clarified this. If I use
CoInitialize(NULL);
and press CTRL + F5, it still errors (0xC0000005).
Hi All thanks for replying,
@Igor
Okay, thank you for your help.
@Arjay
I will try that and get back to you. Thank you for this!
Hi Igor, thanks for replying;
I would just like to clarify if you mean by "COM-aware" is managed code?
So in C#, the CoInitialize and CoUinitialize is defined in a similar manner like the one...
Hi again, thanks for replying
Ok, I will do that also thank you.
I just found out something weird.
In my C++ code, if I compile and run the code using "CTRL + F5", the error does not occur!...
Hi all, thanks for replying
@itsmeandnobodyelse
I tried using HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); as well as HRESULT hr = CoInitializeEx(0, COINIT_APARTMENTTHREADED);.
...
Hi all, thanks for replying
@itsmeandnobodyelse
I tried commenting out the ones you mentioned, however, the error still occurs.
I added 0xC0000005 to the Exception in Debug->Exception....
Hello all thanks for replying,
Will try the 'cleaning' functions and get back to you.
Actually, I have seen some threads similar to the error I am experiencing with the same DLL. Microsoft said...
Hi itsmeandnobodyelse, thanks for replying.
I just tried what you suggested (add a return as well as the debug). The same error still occurs.
I was able to stop at the return breakpoint and...
Hi all:
Here is the code in order to provide more information:
#include "stdafx.h"
Hi all,
The dll I am using is from Microsoft. I already reported it to the Microsoft connect.
I am about 80% sure that the dll is what is wrong. I tried using it in 2 languages: C# and C++....
Hi all!
I am using a DLL which I am not sure if has some issues. The problem is that it always causes my application to crash right AFTER the code / application.
However, I can properly...
Hi Igor and 0xc0000005,
Thanks for replying and the solutions! What worked was:
varDate = _variant_t(mytime, VT_DATE);
Another solution (but with more lines of code):
VARIANT var;...
Hi all,
I want to insert a Date type into a VARIANT that will be used by a certain function that needs a Date, but requires a VARIANT* data type.
The function looks something like...
Hi all,
Does anyone know how to automatically register a DLL in run-time or just possible to integrate it into an exe file?
This is so I can call COM components that require that DLL...
Hi, I finally solved this problem:
Here is a link that helped me with how to use the Management Point API in C# : and...
Hi all,
I am migrating some code from C++ to a C# WebService, and specifically I use CoCreateInstance in the C++ code. I have two questions that interests me:
1) Is it possible to integrate a...
Hi oliv, thanks for replying.
Yes, I know the password of the administrator account. I can even get the username and password of a Network Access Account in case I do not know the password of any...
Hi all,
I am working with the SMS management point API, and the invoke method. The invoke method is used to send a message from a client computer to a remote computer. The remote computer will...
Hi all,
I am doing work regarding SMS 2003 Management Point API, and I use this blog as reference:
I am...
Hi hoxsiew, thanks for replying.
Yes, that seems to be the problem. Thank you for confirming.
What I did was create another Win PE, but this time, 32 bit version, since the needed dll file...
Hi all,
I am trying to do this one: and I am experiencing an error regarding CoCreateInstance. It returns the error...
Hi all, thank you all for replying.
I forgot to mention that I also tried wcout. It has the same output as in using cout.
Or does wcout not work with CStrings too?
Thank you!
Hi all,
I am experiencing a problem in converting std::string to CString, and I don't know why it occurs. I am not using MFC. I just included atlstr.h.
Here is the code I use:
string mpname...
Hi Paul, and Victor, thanks for replying.
Thankyou for those inputs! I'll keep them in mind.
Thank you very much! | http://forums.codeguru.com/search.php?s=5d4016ab092192c042afac2e8036940b&searchid=5601721 | CC-MAIN-2014-49 | refinedweb | 767 | 76.42 |
ok, I dont know what you want to call this. A bug in IIS ? Or should we just say unexpected behaviour. Unexpected behaviour obviously, atleast for me since I were not prepared for and expecting this. It was especially very hard to track down and find out why everytime a page is requested, it would also execute a call to "default.aspx" on a seperate request, executing code in default.aspx for nothing. so i'm going to blog my findings here just in case someone else experiences this. Basically when you have images on your pages, they are not going to be processed by the aspnet_isapi dll since image file extentions are not mapped to it by default. First a small simple intro :when the browser meets an <img element, it will try to make a request to the server. The request is going to be for the file in the src="" mce_src="" attribute of your <img element. However since image extentions are not mapped to the Aspnet_isapi.dll in IIS, it will completely bypass going through your application life cycle, since its the Aspnet_isapi.dll in turn which communicates the request to the worker process (aspnet_wp.exe).Ok, now imagine if for whatever reason you have an image in your page, but the src resolved to an empty string -->> src="" mce_src="" ; seems a bit unlikely you might think, but what if. What do you think is going to happen ? I am working on an opensource application and this is exactly what was happening. Basically there were image spacers being used. Image spacers are usually set to less than 10pixels in height and width so if the image were missing, it wont display that nice square box with an x in it, which made it almost impossible to notice.I was doing some work in Application_AcquireRequestState event, to which i had subscribed to in a custom httpmodule. Everytime i would run this method in debug mode and i'd see it execute an extra time! So i look at the request to why and who is making this extra request and soon enough i see its a request for "default.aspx". But the page i ran is not default.aspx. This was basically driving me nuts. Why is default.aspx running, who is calling this, who made this request and the complexity of the application made it pretty hard to find out. The best part was, even though default.aspx was being requested, it would render the page i had initially requested and render it correctly. I was freaking out! I just couldnt find a logical explaination for this and it took a while of eliminating pieces of code one by one and isolating every bit to eventually end up to the the image spacer line. I dont rem now if it were just a mere coincidence that i happened to suspect the image spacer element with the dynamic src, just luck maybe. i dont rem =)But that was it. Basically someone had introduced a piece of code like this :
<img height="85" width="1" src="<%# Globals.GetSkinPath() + "/images/spacer.gif"%>">
This piece of code was supposed to pass a dynamic path for the skin path, which was returning an empty string. The reason being that Page.DataBind was never called.Changing that piece of code to simply the following resolved :
<img height="85" width="1" src="<%= Globals.GetSkinPath() + "/images/spacer.gif"%>">
note the abscence of the databinder symbol# ; code like this was all over the application, which meant it would keep calling and re-executing default.aspx everytime it found this image spacer that resulted with a src to an empty string. Pretty expensive also because default.aspx was a pretty heavy page and almost difficult, if not impossible to notice. A couple of these spacers on each page and a call for default.aspx for each of these spacers and your application performance can be very very slow :-)So lesson to learn, if you find extra requests being made and the requested file is for default.aspx, then you know this request is being made for a file on your webserver with an empty string for the path, which will result in looking for the default.aspx file in your current page folder. So what it will do is look for default.aspx.so, why did src with an empty string resolves to Default.aspx. This is because IIS by default has "Enable default content page" set and the default page is as you maybe have guessed "Default.aspx" for an asp.net application. How beautiful, i spend a full evening debugging this :-)Here is a simple test you can all try to test this behaviour :This is page test.aspx :-------------------------------------
<%@ Page<script runat="server"> string<head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <img src="<%= DynamicSrc %>" style="height:5px;width:5px" /> </div> </form></body></html>code for the httpmodule, so we can test and verify unexpected behaviour :--------------------------------------------------------------------------using System;using System.Web;using System.Web.UI;namespace Test{ /// <summary> /// Summary description for TesterHttpModule /// </summary> public class SimpleHttpModule : IHttpModule { public SimpleHttpModule() { // // TODO: Add constructor logic here // } /// <summary> /// Initializes the HttpModule and performs the wireup of all application /// events. /// </summary> /// <param name="application">Application the module is being run for</param> public void Init(HttpApplication application) { // Wire-up application events // application.BeginRequest += new EventHandler(this.Application_BeginRequest); application.AcquireRequestState += new EventHandler(Application_AquireRequestState); } private void Application_BeginRequest(Object source, EventArgs e) { // do nothing. Just to see this event executing in debug mode } private void Application_AquireRequestState(object source, EventArgs e) { // Is this request made by the page Page page1 = HttpContext.Current.Handler as Page; string requestedUrl = HttpContext.Current.Request.Url.AbsolutePath; System.Diagnostics.Debug.WriteLine("Request made for page: " + requestedUrl); if (page1 != null) { // do nothing } } public void Dispose() { } }}
Good find and thanks for sharing. I ran into this exact behavior in my app about 6 months ago. Took me a while to figure it out.
Pingback from Finds of the Week - 10/17/2007 » Chinh Do
Good idea!
P.S. A U realy girl?
This also is a problem if your default.aspx does something like redirect you to a login page. If that login page automatically clears session state (just for saftey) then once you log in to a page, it'll send that other request which ends up logging you out.
This is an IE bug that I have seen in IE8 and 7. FireFox does NOT have this problem; it's smarter. If src="" then there obviously isn't going to be any image to get! | http://weblogs.asp.net/alessandro/archive/2007/09/30/image-element-with-an-empty-string-for-the-src-quot-quot-attribute-results-in-making-a-call-for-default-aspx.aspx | crawl-002 | refinedweb | 1,104 | 56.55 |
michaeltyson
@michaeltyson on WordPress.org
- Member Since: September 26th, 2008
Contribution Historymichaeltyson’s badges:
- Core Contributor
- Plugin Developer
- Theme Developer
Committed [1431045] to Plugins SVN:
Tagged 0.7.25: Fixed draft preview issues
Committed [1402771] to Plugins SVN:
Fixed a problem with page URLs
Committed [1402632] to Plugins SVN:
Fixed a problem with permalinks with "/" components
Committed [1402557] to Plugins SVN:
Tagged v0.7.22
Committed [1402556] to Plugins SVN:
Fixed issue with initial permalink display for new posts/pages
Committed [1325520] to Plugins SVN:
Fixed a PHP warning
Committed [1253028] to Plugins SVN:
Minor internationalization fixes
Committed [1062920] to Plugins SVN:
Tagged v0.7.20
Committed [1062917] to Plugins SVN:
Updated Roles and Capabilities from depreciated numerical to label ...
Committed [1062911] to Plugins SVN:
Converted tabs to spaces
Committed [1062908] to Plugins SVN:
Addressed a noisy warning; Revised addition of admin forms js (don't use ...
Committed [927089] to Plugins SVN:
WP 3.9 compatibility fix, thanks to Sowmedia
Committed [869003] to Plugins SVN:
0.7.18: Patch to address 404 errors when displaying a page/post that ...
Committed [851055] to Plugins SVN:
Patch to address SSL problems, thanks to Amin Mirzaee
Committed [664684] to Plugins SVN:
Security and compatibility fixes by Hans-Michael Varbaek of Sense of ...
Committed [588769] to Plugins SVN:
Permalinks are now case insensitive, thanks to @ericmann; Tagged v0.7.15
Committed [550239] to Plugins SVN:
Delete permalinks when deleting posts (v0.7.14)
Committed [532052] to Plugins SVN:
Took offline
Committed [515414] to Plugins SVN:
Fixed issue with term permalinks
Committed [511671] to Plugins SVN:
Updated readme to mention permalink/htaccess setup
Committed [510712] to Plugins SVN:
Tagged version 2.1
Committed [510706] to Plugins SVN:
Added support for post formats
Committed [510680] to Plugins SVN:
Tagged 2.0.2
Committed [510666] to Plugins SVN:
Fixed issue with uploading images with special characters in title
Committed [510340] to Plugins SVN:
Fixed issue with feed URLs in non-webroot blog installations Tagged ...
Committed [508791] to Plugins SVN:
Prefixed OAuth libraries to avoid namespace clashes with other plugins ...
Committed [505231] to Plugins SVN:
Released v2.0.1
Committed [503148] to Plugins SVN:
Fixed OAuth dependency conflict issue
Committed [501107] to Plugins SVN:
Tagged v0.7.11
Committed [501104] to Plugins SVN:
Replaced use of permalink with shortlink, even when used from API
Committed [501099] to Plugins SVN:
Use wp_get_shortlink
Committed [501042] to Plugins SVN:
Updated readme to mention Twitter Image Host 2
Committed [501018] to Plugins SVN:
Initial 2.0 release
Committed [500978] to Plugins SVN:
Fixed issue with infinite redirect with permalinks without trailing slash, ...
Committed [500254] to Plugins SVN:
Updated stable tag version
Committed [488172] to Plugins SVN:
Fixed issue with pending/draft posts
Committed [486598] to Plugins SVN:
Fixed tag messup
Committed [481453] to Plugins SVN:
Fix for 404 error on static front page with custom permalink set, by Eric ...
Committed [469102] to Plugins SVN:
Added support for custom post types, thanks to Balázs Németh Tagged v0.7.9 ...
Committed [463703] to Plugins SVN:
Tagged 0.7.8
Committed [462757] to Plugins SVN:
Don't change PATH_INFO server variable, which seems to cause problems now
Committed [460406] to Plugins SVN:
Fix issue with original permalink containing url encoded chars
Committed [460289] to Plugins SVN:
* Support for non-ASCII characters in URLs * Fixed bug where adding a ...
Committed [433343] to Plugins SVN:
Added Norwegian translation, thanks to Rune Gulbrandsøy
Committed [429098] to Plugins SVN:
Minor change to permalink saving routine to fix some possible issues Fixed ...
Committed [424830] to Plugins SVN:
Tagged 0.7.6
Committed [424803] to Plugins SVN:
Fixed permalink saving issue when not using ".../%postname%" or similar ...
Committed [424119] to Plugins SVN:
Fixed issue where changes to trailing "/" aren't saved
Committed [423886] to Plugins SVN:
Updated API key creation URL
Committed [423211] to Plugins SVN:
Fixed formatting issue in readme
Elegant Grunge
Active Installs: 900+ | https://profiles.wordpress.org/michaeltyson/ | CC-MAIN-2022-40 | refinedweb | 645 | 50.26 |
I am trying to implement virtual LEDs on a Python window. I turn the LED "on" by drawing a green oval. I then use root.after() to schedule another call that turns the LED "off" by drawing a dark green oval. I use a 250ms delay. There are 4 active LEDs on the display. When I allow them to run (I have a global boolean to indicate if I want LEDs to be active), the processor usage starts to climb, going up a percent or two a minute, steadily climbing. I know root.after() returns a handle and you can use that to delete the action, but I don't think I'm overloading the system with too many of these calls.
Location is a tuple with 2 pairs of X,Y values for bounding box. LED() draws the LED immediately. ServiceLEDs() is called at 8 Hrz, and checks the time for all active LEDs to see if the time has passed; this is my second attempt, as my first attempt did a simpler root.after() call for every LED that needed to be handled. I thought this would be faster. Commented out ScheduleLED implements setting an "after" for each LED. The active ScheduleLED sets an array entry with a True flag, the desired state and the time it should expire.
Is it the after() that is causing me time proplems? Is it the tuples? All I know, is if I set UseLEDs to False, the progam runs along at about 3 percent of CPU, and if True, it grows and grows...
Help. Please!
Kelly
Here's code snippets:
def LED(self, location, state): if (UseLEDs): self.LEDCanvas.create_oval( location, fill=LEDColors[state]) def ServiceLEDs(self): if (not UseLEDs): return FLAG = 0 STATE = 1 TIME = 2 theTime = getTime() for ii in range(0,4): if (LEDTimes[ii][FLAG]): if ( theTime > LEDTimes[ii][TIME] ): self.LEDCanvas.create_oval( LEDTuples[ii], fill=LEDColors[LEDTimes[ii][STATE]]) LEDTimes[ii] = ( False, 0, 0 ) root.after(125, self.ServiceLEDs) # def ScheduleLED(self, delay, tuple, state): # if (UseLEDs): # print "DEBUG", "LED", delay, state, tuple # root.after( delay, lambda l=tuple, s=state : self.LED( l, s )) def ScheduleLED(self, delay, theLED, state): if (UseLEDs): LEDTimes[theLED] = (True, state, getTime()+(delay/1000)) #root.after( delay, lambda l=tuple, s=state : self.LED( l, s )) | https://www.daniweb.com/programming/software-development/threads/322107/python-after-method-causing-slowdown | CC-MAIN-2018-34 | refinedweb | 386 | 75.5 |
Use nano to edit the main code, as mentioned previously in Step 2.
pi@raspberrypi:~/my_pismart $ nano my_pismart.py
It’s pretty easy to drive the car to move forward – just replace pass
in the loop() with the following code.
def loop(): my_pismart.MotorA = 60 # Set MotorA speed 60 my_pismart.MotorB = 60 # Set MotorB speed 60
Pay attention to the indent of the two lines: four spaces compared to def loop(). loop() is a function and the two lines underneath is the content. The indent indicates the affiliation between the two lines and loop().
When completed, the code will be like below:(): my_pismart.MotorA = 60 # Set MotorA speed 60 my_pismart.MotorB = 60 # Set MotorB speed 60
After the code modification is done, press Ctrl + O to save and Ctrl + X to exit.
Use python my_pismart.py to run this code like Step 3.
pi@raspberrypi:~/my_pismart $ python my_pismart.py
If you see the following error when running the code,
File "my_pismart.py", line 17 my_pismart.MotorB = 60 ^ IndentationError: unexpected indent
Find the line with error: line 17. Check whether the space quantity is right or not.
Similarly, if other error messages appear, you can check according to the prompted line number and compare it with the code above.
After the command, you will see both wheels of the car start spinning. Put the car on the ground, and then the car will move forward.
If the car does not move forward as designed, it should be the motor installation – the movement of the car is decided by both the original rotation direction of the motor and the direction in installation. You can change False to True behind MotorA_reversed andMotorB_reversed in setup(). (Only change the value of the reversely-rotating motor).
my_pismart.MotorA_reversed = True # If MotorA is reversed, change the value False to True my_pismart.MotorB_reversed = True # If MotorB is reversed, change the value False to True
The added my_pismart.MotorA = 60 and my_pismart.MotorB = 60 in loop() is to set the speed of both motors as 60, thus the car will move forward (positive value means forward).
You can try modifying the rotation speed of the motors in the code. The movement will be different due to different speed settings.
When the speed is set as 0, the motor stops rotating.
# PiSmart Car Stop my_pismart.MotorA = 0 # set MotorA speed as 0 my_pismart.MotorB = 0 # set MotorB speed as 0
When it is negative, the car will move backward and the speed range should be -100-100.
# PiSmart Car backward my_pismart.MotorA = -60 my_pismart.MotorB = -60
When the speed of two motors is different, the car will change its direction. When MotorB rotates slower than MotorA, the car will turn to the side of MotorB.
# PiSmart Car turn left my_pismart.MotorA = 60 my_pismart.MotorB = 20
On the other hand, if MotorA rotates slower than MotorB, the car will turn toward the direction of MotorA.
# PiSmart Car turn right my_pismart.MotorA = 20 my_pismart.MotorB = 60
We can also put all movements together to form a series of coherent action. Use nano to open the code:
pi@raspberrypi:~/my_pismart $ nano my_pismart.py
Then write the actions above in def loop():
def loop(): # PiSmart Car move forward my_pismart.MotorA = 60 # Set MotorA speed 60 my_pismart.MotorB = 60 # Set MotorB speed 60 sleep(3) # sleep 3 seconds # PiSmart Car stop my_pismart.MotorA = 0 my_pismart.MotorB = 0 sleep(3) # PiSmart Car backward my_pismart.MotorA = -60 my_pismart.MotorB = -60 sleep(3) # PiSmart Car turn left my_pismart.MotorA = 60 my_pismart.MotorB = 20 sleep(3) # PiSmart Car turn right my_pismart.MotorA = 20 my_pismart.MotorB = 60 sleep(3)
For better understanding, we’ve added comments (contents after #) for you to read more conveniently, which would not affect the running of the code.
sleep(3) Let the program wait for 3 seconds. Here is to keep the action for 3 seconds.
After modifying the code, press Ctrl + O to save and Ctrl + X to exit. And type in y to confirm to save, and press Enter for the file name. Now, you can use python my_pismart.py to run the code.
pi@raspberrypi:~/my_pismart $ python my_pismart.py | https://learn.sunfounder.com/6-mission-1-drive-the-car-difficulty-level/ | CC-MAIN-2021-39 | refinedweb | 687 | 69.68 |
Custom metrics in Azure Monitor (Preview)
As you deploy resources and applications in Azure, you'll want to start collecting telemetry to gain insights into their performance and health. Azure makes some metrics available to you out of the box. These metrics are called standard or platform. However, they're limited in nature.
You might want to collect some custom performance indicators or business-specific metrics to provide deeper insights. These custom metrics can be collected via your application telemetry, an agent that runs on your Azure resources, or even an outside-in monitoring system and submitted directly to Azure Monitor. After they're published to Azure Monitor, you can browse, query, and alert on custom metrics for your Azure resources and applications side by side with the standard metrics emitted by Azure.
Azure Monitor custom metrics are current in public preview.
Methods to send custom metrics
Custom metrics can be sent to Azure Monitor via several methods:
- Instrument your application by using the Azure Application Insights SDK and send custom telemetry to Azure Monitor.
- Install the Azure Monitor Agent (Preview) on your Windows or Linux Azure VM and use a data collection rule to send performance counters to Azure Monitor metrics.
- Install the Windows Azure Diagnostics (WAD) extension on your Azure VM, virtual machine scale set, classic VM, or classic Cloud Services and send performance counters to Azure Monitor.
- Install the InfluxData Telegraf agent on your Azure Linux VM and send metrics by using the Azure Monitor output plug-in.
- Send custom metrics directly to the Azure Monitor REST API,
https://<azureregion>.monitoring.azure.com/<AzureResourceID>/metrics.
Pricing model and retention
Check the Azure Monitor pricing page for details on when billing will be enabled for custom metrics and metrics queries. Specific price details for all metrics, including custom metrics and metric queries are available on this page. In summary, there is no cost to ingest standard metrics (platform metrics) into Azure Monitor metrics store, but custom metrics will incur costs when they enter general availability. Metric API queries do incur costs.
Custom metrics are retained for the same amount of time as platform metrics.
Note
Metrics sent to Azure Monitor via the Application Insights SDK are billed as ingested log data. They only incur additional metrics charges only if the Application Insights feature Enable alerting on custom metric dimensions has been selected. This checkbox sends data to the Azure Monitor metrics database using the custom metrics API to allow the more complex alerting. Learn more about the Application Insights pricing model and prices in your region.
How to send custom metrics
When you send custom metrics to Azure Monitor, each data point, or value, reported must include the following information.
Authentication
To submit custom metrics to Azure Monitor, the entity that submits the metric needs a valid Azure Active Directory (Azure AD) token in the Bearer header of the request. There are a few supported ways to acquire a valid bearer token:
- Managed identities for Azure resources. Gives an identity to an Azure resource itself, such as a VM. Managed Service Identity (MSI) is designed to give resources permissions to carry out certain operations. An example is allowing a resource to emit metrics about itself. A resource, or its MSI, can be granted Monitoring Metrics Publisher permissions on another resource. With this permission, the MSI can emit metrics for other resources as well.
- Azure AD Service Principal. In this scenario, an Azure AD application, or service, can be assigned permissions to emit metrics about an Azure resource. To authenticate the request, Azure Monitor validates the application token by using Azure AD public keys. The existing Monitoring Metrics Publisher role already has this permission. It's available in the Azure portal. The service principal, depending on what resources it emits custom metrics for, can be given the Monitoring Metrics Publisher role at the scope required. Examples are a subscription, resource group, or specific resource.
Tip
When you request an Azure AD token to emit custom metrics, ensure that the audience or resource the token is requested for is. Be sure to include the trailing '/'.
Subject
This property captures which Azure resource ID the custom metric is reported for. This information will be encoded in the URL of the API call being made. Each API can only submit metric values for a single Azure resource.
Note
You can't emit custom metrics against the resource ID of a resource group or subscription.
Region
This property captures what Azure region the resource you're emitting metrics for is deployed in. Metrics must be emitted to the same Azure Monitor regional endpoint as the region the resource is deployed in. For example, custom metrics for a VM deployed in West US must be sent to the WestUS regional Azure Monitor endpoint. The region information is also encoded in the URL of the API call.
Note
During the public preview, custom metrics are only available in a subset of Azure regions. A list of supported regions is documented in a later section of this article.
Timestamp
Each data point sent to Azure Monitor must be marked with a timestamp. This timestamp captures the DateTime at which the metric value is measured or collected. Azure Monitor accepts metric data with timestamps as far as 20 minutes in the past and 5 minutes in the future. The timestamp must be in ISO 8601 format.
Namespace
Namespaces are a way to categorize or group similar metrics together. By using namespaces, you can achieve isolation between groups of metrics that might collect different insights or performance indicators. For example, you might have a namespace called contosomemorymetrics that tracks memory-use metrics which profile your app. Another namespace called contosoapptransaction might track all metrics about user transactions in your application.
Name
Name is the name of the metric that's being reported. Usually, the name is descriptive enough to help identify what's measured. An example is a metric that measures the number of memory bytes used on a given VM. It might have a metric name like Memory Bytes In Use.
Dimension keys
A dimension is a key or value pair that helps describe additional characteristics about the metric being collected. By using the additional characteristics, you can collect more information about the metric, which allows for deeper insights. For example, the Memory Bytes In Use metric might have a dimension key called Process that captures how many bytes of memory each process on a VM consumes. By using this key, you can filter the metric to see how much memory-specific processes use or to identify the top five processes by memory usage. Dimensions are optional, not all metrics may have dimensions. A custom metric can have up to 10 dimensions.
Dimension values
When reporting a metric data point, for each dimension key on the metric being reported, there's a corresponding dimension value. For example, you might want to report the memory used by the ContosoApp on your VM:
- The metric name would be Memory Bytes in Use.
- The dimension key would be Process.
- The dimension value would be ContosoApp.exe.
When publishing a metric value, you can only specify a single dimension value per dimension key. If you collect the same memory utilization for multiple processes on the VM, you can report multiple metric values for that timestamp. Each metric value would specify a different dimension value for the Process dimension key. Dimensions are optional, not all metrics may have dimensions. If a metric post defines dimension keys, corresponding dimension values are mandatory.
Metric values
Azure Monitor stores all metrics at one-minute granularity intervals. We understand that during a given minute, a metric might need to be sampled several times. An example is CPU utilization. Or it might need to be measured for many discrete events. An example is sign-in transaction latencies. To limit the number of raw values you have to emit and pay for in Azure Monitor, you can locally pre-aggregate and emit the values:
- Min: The minimum observed value from all the samples and measurements during the minute.
- Max: The maximum observed value from all the samples and measurements during the minute.
- Sum: The summation of all the observed values from all the samples and measurements during the minute.
- Count: The number of samples and measurements taken during the minute.
For example, if there were four sign-in transactions to your app during a given a minute, the resulting measured latencies for each might be as follows:
Then the resulting metric publication to Azure Monitor would be as follows:
- Min: 4
- Max: 16
- Sum: 40
- Count: 4
If your application is unable to pre-aggregate locally and needs to emit each discrete sample or event immediately upon collection, you can emit the raw measure values. For example, each time a sign-in transaction occurs on your app, you publish a metric to Azure Monitor with only a single measurement. So for a sign-in transaction that took 12 ms, the metric publication would be as follows:
- Min: 12
- Max: 12
- Sum: 12
- Count: 1
With this process, you can emit multiple values for the same metric plus dimension combination during a given minute. Azure Monitor then takes all the raw values emitted for a given minute and aggregates them together.
Sample custom metric publication
In the following example, you create a custom metric called Memory Bytes in Use under the metric namespace Memory Profile for a virtual machine. The metric has a single dimension called Process. For the given timestamp, we emit metric values for two different processes:
{ "time": "2018-08-20T11:25:20-7:00", "data": { "baseData": { "metric": "Memory Bytes in Use", "namespace": "Memory Profile", "dimNames": [ "Process" ], "series": [ { "dimValues": [ "ContosoApp.exe" ], "min": 10, "max": 89, "sum": 190, "count": 4 }, { "dimValues": [ "SalesApp.exe" ], "min": 10, "max": 23, "sum": 86, "count": 4 } ] } } }
Note
Application Insights, the diagnostics extension, and the InfluxData Telegraf agent are already configured to emit metric values against the correct regional endpoint and carry all of the preceding properties in each emission.
Custom metric definitions
There's no need to predefine a custom metric in Azure Monitor before it's emitted. Each metric data point published contains namespace, name, and dimension information. So the first time a custom metric is emitted to Azure Monitor, a metric definition is automatically created. This metric definition is then discoverable on any resource the metric is emitted against via the metric definitions.
Note
Azure Monitor doesn't yet support defining Units for a custom metric.
Using custom metrics
After custom metrics are submitted to Azure Monitor, you can browse them via the Azure portal and query them via the Azure Monitor REST APIs. You can also create alerts on them to notify you when certain conditions are met.
Note
You need to be a reader or contributor role to view custom metrics.
Browse your custom metrics via the Azure portal
- Go to the Azure portal.
- Select the Monitor pane.
- Select Metrics.
- Select a resource you've emitted custom metrics against.
- Select the metrics namespace for your custom metric.
- Select the custom metric.
Supported regions
During the public preview, the ability to publish custom metrics is available only in a subset of Azure regions. This restriction means that metrics can be published only for resources in one of the supported regions. The following table lists the set of supported Azure regions for custom metrics. It also lists the corresponding endpoints that metrics for resources in those regions should be published to:
Latency and storage retention
Adding a brand new metric or a new dimension being added to a metric may take up to 2 to 3 minutes to appear. Once in the system, data should appear in less than 30 seconds 99% of the time.
If you delete a metric or remove a dimension, the change can take a week to a month to be deleted from the system.
Quotas and limits
Azure Monitor imposes the following usage limits on custom metrics:
An active time series is defined as any unique combination of metric, dimension key, or dimension value that has had metric values published in the past 12 hours.
Next steps
Use custom metrics from different services: | https://docs.microsoft.com/en-us/azure/azure-monitor/platform/metrics-custom-overview | CC-MAIN-2020-45 | refinedweb | 2,037 | 53.81 |
Frequent readers of this blog know that I do not like printf (see “Why I don’t like printf()“), because the standard
printf() adds a lot of overhead and only causes troubles. But like small kids, engineers somehow get attracted by troubles ;-). Yes,
printf() and especially
sprintf() are handy for quick and dirty coding. The good news is that I have added a lightweight
printf() and
sprintf() implementation to my set of components: the XFormat component. And best of all: it supports floating point formatting :-).
XFormat Processor Expert Component
The sources of XFormat have been provided to my by Mario Viara, who contacted me by email:
“Hello Erich,
My name is Mario Viara and I’m and “old” embedded software engineer, Il write for two different things the first is very simple, i know you do not like printf in your project but during debug and to log information it is very usefull we have a very tiny implementation that you can find attached to this mail and if you want you can add it to your wonderful processor expert library.”
This morning finally I have turned this into a Processor Expert component. And I have to say: that’s indeed a simple and cool
printf() and
sprintf() implementation. All what I did is doing some re-formatting, added the necessary interfaces and voilà: a new component is born 🙂
Component Methods and Properties
The component is very simple, and exposes three methods:
xvformat(): this is the heart of the module, doing all the formatting. This one uses a pointer to the open argument list.
xformat(): high level interface to
xvformat()with an open argument list.
xsprintf():
sprintf()implementation which uses
xformat()and uses a buffer for the result string
There is only one setting: if floating point have to be supported or not. This setting creates a define which can be checked in the application code.
sprintf() Usage
Using it for to do a
printf() into a provided buffer (
sprintf()) is very easy, e.g. with
char buf[64]; XF1_xsprintf(buf, "Hex %x %X %lX\r\n",0x1234,0xf0ad,0xf2345678L);
which will store the follow string into buf:
Hex 1234 F0AD F2345678
This string then can be printed or used as needed.
printf() Usage
Using
printf() and for example to print the string to a console requires that a ‘printer’ function is provided. This ‘printer’ function (actually a function pointer) needs to be provided by the application.
First, I define my function which shall output one character at a time. It uses as first argument a void parameter (arg) with which I can pass an extra argument. My example implementation below passes the command line Shell standard I/O handler I’m using in my projects (see “A Shell for the Freedom KL25Z Board“). That handler itself is a function pointer:
static void MyPutChar(void *arg, char c) { CLS1_StdIO_OutErr_FctType fct = arg; fct(c); }
Next, I implement my
printf() function I can use in my application: it uses the same interface as the normal printf(). It unpacks the variable argument list and passes it to
xvformat() function, together with the
MyPutChar() function:
unsigned int MyXprintf(const char *fmt, ...) { va_list args; unsigned int count; va_start(args,fmt); count = XF1_xvformat(MyPutChar, CLS1_GetStdio()->stdOut, fmt, args); va_end(args); return count; }
Then I can call it in my application like printf():
(void)MyXprintf("Hello %s\r\n","World");
The component creates as well a define so the application knows if floating point is enabled or not. Below is a test program which uses some of the formatting strings:
static void MyPutChar(void *arg, char c) { CLS1_StdIO_OutErr_FctType fct = arg; fct(c); } unsigned int MyXprintf(const char *fmt, ...) { va_list args; unsigned int count; va_start(args,fmt); count = XF1_xvformat(MyPutChar, CLS1_GetStdio()->stdOut, fmt, args); va_end(args); return count; } static void TestXprintf(void) { (void)MyXprintf("Hello world\r\n"); (void)MyXprintf("Hello %s\r\n","World"); (void)MyXprintf("Not valid type %q\r\n"); (void)MyXprintf("integer %05d %d %d\r\n",-7,7,-7); (void)MyXprintf("Unsigned %u %lu\r\n",123,123Lu); (void)MyXprintf("Octal %o %lo\r\n",123,123456L); (void)MyXprintf("Hex %x %X %lX\r\n",0x1234,0xf0ad,0xf2345678L); #if XF1_XCFG_FORMAT_FLOAT (void)MyXprintf("Floating %6.2f\r\n",22.0/7.0); (void)MyXprintf("Floating %6.2f\r\n",-22.0/7.0); (void)MyXprintf("Floating %6.1f %6.2f\r\n",3.999,-3.999); (void)MyXprintf("Floating %6.1f %6.0f\r\n",3.999,-3.999); #endif } static void TestXsprintf(void) { char buf[64]; XF1_xsprintf(buf, "Hello world\r\n"); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Hello %s\r\n","World"); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Not valid type %q\r\n"); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "integer %05d %d %d\r\n",-7,7,-7); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Unsigned %u %lu\r\n",123,123Lu); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Octal %o %lo\r\n",123,123456L); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Hex %x %X %lX\r\n",0x1234,0xf0ad,0xf2345678L); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); #if XF1_XCFG_FORMAT_FLOAT XF1_xsprintf(buf, "Floating %6.2f\r\n",22.0/7.0); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Floating %6.2f\r\n",-22.0/7.0); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Floating %6.1f %6.2f\r\n",3.999,-3.999); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); XF1_xsprintf(buf, "Floating %6.1f %6.0f\r\n",3.999,-3.999); CLS1_SendStr((unsigned char*)buf, CLS1_GetStdio()->stdOut); #endif }
Summary
With the XFormat Processor Expert component I have a small
printf() like implementation which is a good alternative to the bloated (and fully featured)
sprintf() and
printf() implementation. It uses a flexible callback mechanism so I can write the text to any channel (bluetooth, wireless, disk, …) I want. The new component is now a member of my components on GitHub (see “Processor Expert Component *.PEupd Files on GitHub“).
Thanks Mario!
Happy Printing 🙂
PS: for ‘normal’ string manipulation functions, see the Utility Processor Expert component, available on the same GitHub repository.
Perhaps Mario could contribute here a comparison between XFormat and the printf() subset used by newlib nano, in terms of code size, speed, etc.
Thanks for posting this – looks useful. Formatted printing has always been the bane of embedded software.
Hi, the printf example you have done in another post is not working for me in KDS 1.1.1 and I can’t seem to find the XFormat component. Has it been removed? What would be another alternative?
Great info in your web! Thanks for sharing.
Thank you!
Hi Alex,
which project are you using? I verified that is working for me with KDS v1.1.1
Erich
Hi,
I have tried to do as you explained in another post to use printf in KDS 1.1.1 but the MCU is not sending anything to the OpenSDA MCU. Also, I can’t find that XFormat component in KDS 1.1.1.
Has it been removed?
What can I do in this case?
Great info in your web site.
Thank you.
Hello,
the XFormat component is not part of Kinetis Design Studio, it is one of the McuOnEclipse components. Have you installed them from SourceForge? See
I hope this helps,
Erich
Hi,
Thank you for your quick answer. Sorry I didn’t know that. I’ve downloaded them. Great stuff. I’m planning to use Kinetis as my new working platform since Microchip has code limited compiles and no ARM core, TI has very expensive software tools, Atmel has no multiplatform software, Cypress (Has awesome platform and software which is even better than Processor Expert IMHO) but they are expensive and no multiplatform and the chose was between Freescale and NXP. Both support mbed and has free multiplatform tools which is awesome, but I prefer the Processor Expert option and the bigger selection of MCUs.
By the way, I have a FRDM-KL25Z which when I changed the firmware of the OpenSDA MCU to use it with mbed I couldn’t get KDS to recognize it so I had to change it back. Is there anyway to be able to have support for boths at the same time? I guess the K64 board can do that, right? I have an LPCXpresso V2 board and does it too. Is there any possibility to achieve the same with the KL25Z?
I really appreciate people sharing info like you. As soon as I get confortable with Freescale I will make tutorials for my youtube channel: Twistx77.
Thank you once again. Have a nice weekend.
Alex.
Hi Alex,
The FRDM-K64F has a different firmware than the FRDM-K24F. What mbed needs is a firmware which recognizes .bin (binary) files. In my view mbed would have been much better off if they would have used s19 instead of bin files, then you would not see that problem. The FRDM-KL25Z (and many other boards) accept S19 files. A solution for you would be that you convert the mbed bin files into S19 files, and then you don’t need to switch.
Erich
LikeLiked by 1 person
Hi, I tested your example and it works perfectly. I don’t see any differences from mine. I will do it again from scratch to figure out what is the problem with mine.
I also found all the examples you have in your github for CW which is awesome.
Thank you and sorry for the inconvenience.
Hello Erich,
Great component, and thank you for making it available to the public.
I am not sure if you are aware of it or not but there is a bug on the Xformat component.
if you try to print negative floating point numbers such as:
-0.56, -0.01, -0.85, etc the xformat outputs the number but not the ‘-‘ sign.
if you then try to print -1.56, -2.01, -10.85, etc it works just find.
I have floating point enable in the component.
So any number with -0.XX or -.XX fails to print the ‘-‘ character.
Any ideas?
Thank you.
Hello,
many thanks for reporting this problem, and indeed: I can reproduce it 😦
I have commited a fix for it here (which is very easy):
It will be included in the next component release. Until then, you could do that one line change on your machine too. Let me know if you need any assistance.
Hello,
Oh, that is great!
Thank you for quick Fix.
Awesome!
Erich,
i am seeing this issue:
almost same xsprintf statements, but i swap the last 2 arguments. the last %d always results in ‘0’. i tried %x as well and same result.
XF1_xsprintf(debugMess,”index %d, addr 0x%x : time %d code %d\n”,i,NVM_ERROR_PAGE+i,time,code);
//SerialPuts(Type_00_Console,debugMess);
XF1_xsprintf(debugMess,”index %d, addr 0x%x : time %d code %d\n”,i,NVM_ERROR_PAGE+i,code,time);
//SerialPuts(Type_00_Console,debugMess);
debugMess after 1st XF1_xsprintf;
Name : debugMess
Details:”index 0, addr 0x8f000 : time 19 code 0\n\070942′ ‘0x175902f4’) :\0 CAN ID: 39170942\n\n\0000, com_sp 0.000, com_v -0.011, IDLE, voc_only: algo_init, — 0.000 (0.000), [-1:4] – 0.000 (0.000)\n”, ‘\0′
Default:0x1fffbc1c
Decimal:536853532
Hex:0x1fffbc1c
Binary:11111111111111011110000011100
Octal:03777736034
debugMess after 2nd XF1_xsprintf;
Name : debugMess
Details:”index 0, addr 0x8f000 : time 2147483647 code 0\n\00x175902f4’) :\0 CAN ID: 39170942\n\n\0000, com_sp 0.000, com_v -0.011, IDLE, voc_only: algo_init, — 0.000 (0.000), [-1:4] – 0.000 (0.000)\n”, ‘\0’
Default:0x1fffbc1c
Decimal:536853532
Hex:0x1fffbc1c
Binary:11111111111111011110000011100
Octal:03777736034
Hi David,
Few ideas and questions:
Could it be that you have a possible stack overflow? Can you try with an increased stack size? Because it requires around 100 bytes on the stack.
And did you include the header file âXF1.hâ before you are using it? Because it uses an open argument list this is very important.
I hope this helps,
Erich
Pingback: McuOnEclipse Components: 30-Oct-2016 Release | MCU on Eclipse
Hi Erich,
Thank you for sharing XFormat, it’s very useful for me!
I just want to share my suggestion about this component:
(1) Add snprintf():
/*
** ===================================================================
** Method : XF_xsnprintf (component XFormat)
** Description :
** snprintf() like function
** Parameters :
** NAME – DESCRIPTION
** * buf – Pointer to buffer to be written
** max_len – Max output buffer size
** * fmt – Pointer to formatting string
** argList – Open Argument List
** Returns :
** — – number of characters written, negative for
** error case
** ===================================================================
*/
struct StrOutBuffer {
char * s;
unsigned space;
};
static void putCharIntoBufMaxLen(void *arg, char c) {
struct StrOutBuffer * buff = (struct StrOutBuffer *)arg;
if (buff->space > 0) {
buff->space–;
*(buff->s)++ = c;
}
}
static int xsnprintf(char *buf, unsigned max_len, const char *fmt, va_list args) {
int res;
struct StrOutBuffer out = { buf, max_len };
if (max_len 0) res = out.s – buf;
return res;
}
int XF_xsnprintf(char *buf, unsigned max_len, const char *fmt, …)
{
va_list args;
int res;
va_start(args,fmt);
res = xsnprintf(buf, max_len, fmt, args);
va_end(args);
return res;
}
(2) Add GCC extension:
/* GCC have printf type attribute check. */
#ifdef __GNUC__
#define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
#else
#define PRINTF_ATTRIBUTE(a,b)
#endif /* __GNUC__ */
unsigned XF_xformat(void (*outchar)(void *,char), void *arg, const char * fmt, …) PRINTF_ATTRIBUTE(3,4);
int XF_xsprintf(char *buf, const char *fmt, …) PRINTF_ATTRIBUTE(2,3);
int XF_xsnprintf(char *buf, unsigned max_len, const char *fmt, …) PRINTF_ATTRIBUTE(3,4);
Cheers,
-Engin
Hi Engin,
Could you send me that piece of source by email to my email address listed on, as posting sources like this on the web will loose things. For example your code does not include any of the parsing parts.
Thanks!
Erich
Hi Engin,
cool idea about the GNU function attributes ()!
I did not know this, always learning something new 🙂
Erich
It’s due to HTML tagging in the source code, sorry about that!
I have sent the code directly to your e-mail.
Thanks you!
Hi Engin,
thank you so much! I’m adding this to the component.
Erich
Pingback: Using FreeRTOS with newlib and newlib-nano | MCU on Eclipse
Pingback: Using the GNU Linker Script to know the FLASH and RAM Areas in the Application | MCU on Eclipse
So is this implementation thread-safe?
Yes, it is thread-safe.
Thank you, Erich! As always, you are a great help.
I believe that it is, based on the discussion that it uses the stack and quick inspection of the code, but would feel more confident if I could get confirmation.
Hi,
I’ve been having an issue formatting floating point numbers. Specifically, if I use %2.6f or %2.7f, I just get the integer part of the number, whereas using %f, I get the first six digits after the decimal point.
As an example, I tried the following code:
float Lat = 34.123456;
float Lon = 35.567891;
strlLength = XF1_xsprintf((char*) s,”GPS = %2.7f, %2.7f\r\n”,Lat,Lon);
The result is:
s = “GPS = 34, 35”
Any ideas?
Thanks!
LikeLiked by 1 person
Actually this is a bug (or missing feature) in the original XFormat code. I realize that the version on GitHub () has it fixed, so I have now updated (and fixed) the Processor Expert component for it. I applogize for that issue, and I have sent you the new component to your gmail address. Of course this fix will be in the next update from my side.
Thanks for reporting!
Erich
LikeLiked by 1 person
Pingback: McuOnEclipse Components: 1-Apr-2018 Release | MCU on Eclipse
Hi, Erich
Very interesting your alternative to printf. I’m looking for something like that. In my case, I need to print a string through UART into a Terminal. You call XF1_xvformat like that: XF1_xvformat(MyPutChar, CLS1_GetStdio()->stdOut, fmt, args);. I suppose that in MyPutChar function I should load my UART buffer with each character of my string. But what about CLS1_GetStdio()->stdOut function? What does this function do exactly and what function should I pass as the second parameter to send my data to UART transmit buffer instead of a variable?
Sorry for my question, I’m not experienced about Standard I/O functions.
Thanks and best regards!
Marco Coelho
Hi Marco,
xvformat() can be used with two parameters: the output function plus an optional argument with the output function. In my case I pass the stdio output channel (stdOut) as argument. It would be possible to do this without such an argument.
In your case using an UART: simply pass your UART putChar function as the first argument, and NULL if you don’t need the second one.
I hope this helps,
Erich
Hi Erich,
Interesting ‘bug’ came up last week. I got a Hard Fault because a xsprintf(buff,” %64s “, pchars);
incremented the pchars pointer until it was not pointing at memory.
pchars was supposed to point to a string (in flash), and this time it was pointing at erased flash memory, which is all xFF. but the xsprintf happily keeps copying pchars til it finds a x00 or generates a Hard Fault. So it also appears like it would have filled memory starting at buff with 0xff, and probably ran out of RAM at buff before it ran out of the FLASH that pchars was pointing to.
I rewrote with a memcpy – something it maybe should have been in the first place since it wasn’t really doing any formatting, but it surprised me that the xsprintf could run off the end of the buffer – I had thought you liked it better because it was safer than printf. This incident just reminded me that printf is not really safe at all, including the x varient.
Brynn
I guess the real problem is that I should always use the xsnprintf or snprintf versions in my embedded code, and never the unbounded versions. In fact, a smart coder should probably never use the unbounded versions ever.
Brynn
Yes, exactly. The ‘n’ version is always preferred and is what I’m using. the XFormat version is better compared to the normal printf()/sprintf() because it is reentrant and has a much smaller footprint.
Pingback: Tutorial: How to Optimize Code and RAM Size | MCU on Eclipse | https://mcuoneclipse.com/2014/08/17/xformat-a-lightweight-printf-and-sprintf-alternative/?like_comment=39816&_wpnonce=4a117ffd59 | CC-MAIN-2021-31 | refinedweb | 3,029 | 63.7 |
0
I have been trying to figure out for the life of me what I am doing wrong here, and I am coming up blank. My operator is returning the correct value in temp - as you can see highlighted in red, however, when I use the operator in main - it is not giving me the correct value. What is it that I am missing :-(
Implementation File
Term Term::operator +=(const Term &t) { Term temp; if (exponent == t.exponent) { temp.coefficient = coefficient + t.coefficient; temp.exponent = exponent; } cout<<"temp= "<<temp<<endl; //this is returning the correct value return (temp); }
Here is the application file
void operatorTest(Term &x) { Term y; cout<<"Enter another term: "<<endl; cin>>y; if (x != y) cout<<"The exponents are not equal. They cannot be added"<<endl; else x+=y; cout<<"The new term is: "<<x<<endl; //this is only giving me the value of x and not x+=y }
Edited by wittykitty: n/a | https://www.daniweb.com/programming/software-development/threads/273417/operator-cannot-get-this-to-return-correct-value-to-application | CC-MAIN-2017-17 | refinedweb | 158 | 51.07 |
Technical Blog Post
Abstract
Rich Text data showing in COMMLOG table and in Reports (Script Solution)
Body
When creating a communication from work order module or any other application, communication logs and email that was triggered are fine, but you may be noticing some rich text data when the record gets saved to the database (Commlog table).
You may also be noticing unwanted tags in the data in reports.
The Rich Text tags can be stripped from the field using an Object Launch point AutoScript.
1. Go to Automation Scripts app
2. Click Select Action and create a new Object Launch Point
3. The Object is COMMLOG
4. The events should be Add and Update.
5. Enter the variable as follow:
Variable -> MSG
Type -> INOUT
Binding Type -> Attribute
Binding Value -> MESSAGE
6. Add the following script
#-----------------------------------------------------------------------
from psdi.util import HTML
MSG = HTML.toPlainText(MSG)
#-----------------------------------------------------------------------
7. Save it and activate the automation script.
8. Send a new communication from Maximo and check the record in the database.
UID
ibm11112277 | https://www.ibm.com/support/pages/node/1112277?lang=en | CC-MAIN-2020-10 | refinedweb | 169 | 65.93 |
Get year from a Date in Python
In this article, we will learn how to get the year from a given date in Python. We will use the built-in module available for getting date and time information.
There are various ways in which we can get the year. We can get a year from a given input date, current date using date object. We will import
date class from
datetime module and will print the output. Look at the examples below.
Example: Get Year from the given Date
In this example, we import datetime module. Using
datetime object, we applied
today() function to extract the current date and then
year() to get only the year from the current date.
import datetime year = datetime.datetime.today().year print(year)
2021
Example: Get Year from the given Date Using now() Function
In this example, we import datetime module. Using
datetime object, we applied now
year() to get only the year from the current date.
()function to extract the current date first and then
import datetime year = datetime.datetime.now().year print(year)
2021
Conclusion
In this article, we learned to get the year from the current date using two
datetime functions. We used
now().year() and t
oday().year() to extract the year from the current date. We saw two examples of the implementation of these two functions. | https://www.studytonight.com/python-howtos/get-year-from-a-date-in-python | CC-MAIN-2022-21 | refinedweb | 227 | 75.5 |
Created on 2019-12-17 18:52 by Zectbumo, last changed 2019-12-18 02:15 by zach.ware. This issue is now closed.
import string
a = string.letters
help(int)
b = string.letters
a == b # False
I am unable to reproduce this.
Can you double check that this occurs in the plain Python interpreter or IDLE, and provide a minimum reproducible example? (No third-party IDEs or interpreters, such as Jupyter.)
These guidelines may help:
I *can* reproduce, on macOS 10.14.6, Python 2.7.17 (from macports).
Python 2.7.17 (default, Oct 20 2019, 14:46:50)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> help(int) # brings up pager; page through to the end
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
With 2.7.16 on cygwin, I get:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> help(int)
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
But given that there's only 2 weeks of support left for 2.7, I don't see this getting changed.
Here's where `string.letters` is reassigned:
That code looks like it's exercised whenever setlocale is (or possibly just when LC_CTYPE is changed). I haven't yet figured out which part of the help machinery causes that.
> But given that there's only 2 weeks of support left for 2.7, I don't see this getting changed.
Agreed: I can't reproduce on Python 3, and it looks as though the offending code is gone from the codebase in Python 3, so this is pretty much just a historical oddity at this point.
For completeness, here's the path leading to the reassignment (after hacking in a raise to the appropriate place in _localemodule.c). It's a side-effect of calling `locale.getpreferredencoding`.
>>> help(int)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mdickinson/GitHub/python/cpython/Lib/site.py", line 445, in __call__
import pydoc
File "/Users/mdickinson/GitHub/python/cpython/Lib/pydoc.py", line 202, in <module>
_encoding = locale.getpreferredencoding()
File "/Users/mdickinson/GitHub/python/cpython/Lib/locale.py", line 616, in getpreferredencoding
setlocale(LC_CTYPE, "")
File "/Users/mdickinson/GitHub/python/cpython/Lib/locale.py", line 581, in setlocale
return _setlocale(category, locale)
ValueError: about to reassign string.letters
So a minimal reproducer is something like:
Python 2.7.17 (default, Oct 20 2019, 14:46:50)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import string, locale
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> locale.getpreferredencoding()
'UTF-8'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
@Zectbumo: is this causing you any practical problem? Or is it just a curiosity?
There's no reasonable way I can see to fix this. The reassignment of those string attributes is clearly intentional (it's even documented) and there's probably code somewhere that relies on it. I think the best we can do is close as "won't fix" though "not a bug" may be more accurate: the code is clearly behaving as intended and designed, even if the design is questionable.
@eric.smith
It actually caused a problem and then turned into a curiosity. At the beginning I wanted to remind myself about the string module so I did a help(string). Then right after that I wrote a program that generated filenames from string.letters. I closed the python interpreter down and then reopened it and regenerated filenames again using string.letters. To my surprise I found the second iteration to come out with completely different results messing up my work. Once I found that help() was causing this problem and it became a curiosity because you would think help() would not modify anything. Obviously this problem is easy to work around in my case.
Since this has been this way for 22 years without a previous report that I can find, +1 to closing as "won't fix"/"not a bug" and so doing. However, I'm also adding the 2.7 release manager to make sure he knows about it and can reopen if he wants. | https://bugs.python.org/issue39079 | CC-MAIN-2021-21 | refinedweb | 701 | 60.82 |
WINC1500 Wi-Fi controller. More...
#include "core/nic.h"
Go to the source code of this file.
WINC1500 Wi-Fi controller. winc1500_driver.h.
Definition at line 44 of file winc1500_driver.h.
Definition at line 37 of file winc1500_driver.h.
Callback function that handles events in bypass mode.
Definition at line 379 of file winc1500_driver.c.
Callback function that handles Wi-Fi events.
Definition at line 329 of file winc1500_driver.c.
Disable interrupts.
Definition at line 188 of file winc1500_driver.c.
Enable interrupts.
Definition at line 178 of file winc1500_driver.c.
WINC1500 event handler.
Definition at line 220 of file winc1500_driver.c.
WINC1500 initialization.
Definition at line 79 of file winc1500_driver.c.
WINC1500 interrupt service routine.
Definition at line 198 of file winc1500_driver.c.
Send a packet.
Definition at line 235 of file winc1500_driver.c.
WINC1500 timer handler.
This routine is periodically called by the TCP/IP stack to handle periodic operations such as polling the link state
Definition at line 168 of file winc1500_driver.c.
Configure MAC address filtering.
Definition at line 285 of file winc1500_driver.c.
WINC1500 driver.
Definition at line 52 of file winc1500_driver.c. | https://oryx-embedded.com/doc/winc1500__driver_8h.html | CC-MAIN-2018-51 | refinedweb | 187 | 64.07 |
I installed cairo-dock 3.1.2-2 and cairo-compmgr-git 20130209-1. It runs without any problem. After installing cairo-dock-plug-ins 3.1.2-1 cairo-dock opens in maintenance mode.
When I try to start it in the console I get the following messages:
[phnx4@002 ~]$ warning : (/tmp/yaourt-tmp-phnx4/aur-cairo-dock/src/cairo-dock-3.1.2/src/gldit/cairo-dock-opengl.c:cairo_dock_initialize_opengl_backend:208)
couldn't find an appropriate visual, trying to get one without Stencil buffer
(it may cause some little deterioration in the rendering) ...
============================================================================
Cairo-Dock version : 3.1.2
Compiled date : Feb 9 2013 09:45:00
Built with GTK : 3.6
Running with OpenGL: 1
============================================================================
warning : (/tmp/yaourt-tmp-phnx4/aur-cairo-dock-plug-ins/src/cairo-dock-plugins-3.1.2/gvfs-integration/cairo-dock-gio-vfs.c:cairo_dock_gio_vfs_init:55)
VFS Deamon NOT found on DBus !
warning : (/tmp/yaourt-tmp-phnx4/aur-cairo-dock-plug-ins/src/cairo-dock-plugins-3.1.2/shortcuts/src/applet-drives.c:cd_shortcuts_list_drives:297)
couldn't detect any drives
warning : (/tmp/yaourt-tmp-phnx4/aur-cairo-dock/src/cairo-dock-3.1.2/src/cairo-dock.c:_cairo_dock_intercept_signal:156)
Cairo-Dock has crashed (sig 11).
It will be restarted now.
Feel free to report this bug on glx-dock.org to help improving the dock!
info on the system :
Linux 002 3.7.6-1-ARCH #1 SMP PREEMPT Mon Feb 4 10:21:12 CET 2013 i686 GNU/Linux
Couldn't guess if it was an applet's fault or not. It may have crashed inside the core or inside a thread
restarting with 'cairo-dock -w 2 -q 1'...
Traceback (most recent call last):
File "/usr/lib/cairo-dock/cairo-dock-unity-bridge", line 25, in <module>
import dbus, dbus.service
ImportError: No module named dbus
I don't know what this means.
Offline
All the plugins seem to work more or less as long as the shortcuts plugin is unchecked. It still crashes every now an then. I removed cairo-dock and returned back to tint2.
Although this is not solved should I mark this topic as solved? Or should I just leave as it is?
Offline | https://bbs.archlinux.org/viewtopic.php?pid=1229428 | CC-MAIN-2016-40 | refinedweb | 370 | 53.68 |
James Smith
Total Post:48Points:336
Hello dear,
I have a method that populate my class by loading an xml
public class Sample
{
public void loadXML(string xmlFilePath)
{
Sample smp=new Sample();
smp=(Sample)s.Desserialize(reafer); //Deserilize and populate my object from an xml file.
return;
}
}
Now I just want to call this method from another class, so I simply have.
MyClass testObj = new MyClass(); testObj.LoadXML("myFile.xml"); testObj --> is EMPTY after the function returns...
Here is my question:
How can I make my current instance (testObj) filled with the data... without having to RETURN an object from my method ? (I want my method to return void)
I want it to work similarly to the NET XmlDocument class:
XmlDocument doc = new XmlDocument();
doc.Load(..) //doc is filled with data
How can I do the same thing? Dows Anybody know how to do this?
Thank you very much in advance for any help
Post:126Points:882
Re: How to update Current object instance.
We can use it following manner | https://www.mindstick.com/forum/221/how-to-update-current-object-instance | CC-MAIN-2018-26 | refinedweb | 170 | 66.74 |
Level Up: spaCy NLP for the Win
ModelingNLP/Text AnalyticsEast 2020spaCyposted by ODSC Community February 21, 2020 ODSC Community
Kimberly is a speaker for ODSC East 2020! Be sure to check out her talk, “Level Up: Fancy NLP with Straightforward Tools,” at this upcoming.
spaCy Basics
Installation
To begin using spaCy, first download it from command line with pip:
pip install spacy
You will also need access to at least one of spaCy’s language models. spaCy may be applied to analyze texts of various languages including English, German, Spanish, and French, each with their own model. We’ll be working with English text for this simple analysis, so go ahead and grab spaCy’s small English language model, again through command line:
python -m spacy download en_core_web_sm
Tokenization
Now processing text boils down to loading your language model and passing strings to it directly. Working within a Python or a Jupyter Notebook interface, let’s see what spaCy makes of one example review:
import spacy nlp = spacy.load(‘en_core_web_sm’) review = “I’m so happy I went to this awesome Vegas buffet!” doc = nlp(review)
The resulting spaCy document is a rich collection of tokens that have been annotated with many attributes including parts of speech, lemmas, dependencies, and named entities. To see this in action, loop over each token in the document and print out the part of speech, lemma,
and whether or not this token is a so-called stop word.
for token in doc: print(token.text, token.pos_, token.lemma_, token.is_stop)
We see in the sixth line that spaCy successfully identified “went” as a verb, that “go” is the correct lemma for this word, and that “went” is not traditionally considered a stop word.
Before moving on to dependency parsing, note that spaCy tokenizes text in an entirely nondestructive manner; that is, each spaCy document contains a collection of token objects, which have their own attributes. The underlying text does not change, and calling doc.text allows us to reconstruct the original content exactly.
spaCy does not explicitly break the original text into a list, but tokens may be accessed by index span:
print(doc[:5])
print(doc[-5:-1])print(doc[-5:-1])
spaCy also performs automatic sentence detection. Iterating over the generator doc.sents yields each recognized sentence.
Dependencies
Natural language processing presents a host of unique challenges, with syntactic and semantic issues certainly among them. Consider when I write the string “bear” – am I talking about a furry animal or the struggles I need to endure? Part-of-speech tagging might help in this case, but what about “bat” – time to play baseball or watch out for that nocturnal animal? To further delineate these tricky cases, spaCy provides syntactic parsing to show word usage, thus creating a dependency tree. spaCy identifies each token’s dependencies when text passes through the language model, so let’s check the dependencies in our restaurant review:
for token in doc: print(token.text, token.dep_)
This seems somewhat interesting, but visualizing these relationships reveals an even more comprehensive story. First load a submodule called displaCy to help with the visualization:
from spacy import displacy
Then ask displaCy to render the dependency tree of our spaCy document:
displacy.render(doc)
Now, that’s impressive! Not only has spaCy picked up on the parts of speech, but it has also determined which words modify each other and how they do so. You can even traverse this parse tree by using properties like token.children, token.head, token.lefts, token.rights, etc.
This navigation is particularly useful for assigning adjectives to the nouns they modify. In our example sentence, the word “awesome” describes “buffet.” spaCy accurately labels “awesome” as an adjectival modifier (amod) and also detects its relationship to “buffet”:
for token in doc: if token.dep_ == 'amod': print(f"ADJ MODIFIER: {token.text} --> NOUN: {token.head}")
Named Entity Recognition
NLP practitioners often seek to identify key items and individuals in unstructured text. This task, known as named entity recognition, executes automatically when text funnels through the language model. To see which tokens spaCy identifies as named entities in our restaurant review, simply cycle through doc.ents:
for ent in doc.ents: print(ent.text, ent.label_)
spaCy recognizes “Vegas” as a named entity, but what does the label “GPE” mean? If you are ever unsure what one of the abbreviations mean, just ask spaCy to explain it to you:
spacy.explain(“GPE”)
Excellent – spaCy correctly identifies “Vegas” as a city because this word is a shortened form of Las Vegas, Nevada, USA.
Furthermore, displaCy’s render method can highlight named entities if the style argument is specified:
displacy.render(doc, style=‘ent’)
displaCy color codes the named entities by type. Consider this more complicated example with four different kinds of entities; displaCy provides unique colors to each:
document = nlp( “One year ago, I visited the Eiffel Tower with Jeff in Paris, France.” ) displacy.render(document, style=‘ent’)
where spaCy explains “FAC” as “Buildings, airports, highways, bridges, etc.”
Case Study: Restaurant Reviews
Let’s now leverage the techniques discussed thus far in a small case study. Continuing on the theme of restaurant reviews, we will examine this Kaggle dataset, consisting of 1,000 reviews labeled by sentiment. Exactly 500 positive and 500 negative reviews make up this perfectly balanced set, and these short reviews typically consist of just one sentence each.
Begin by loading this file into a pandas dataframe called df and rename the columns; the first five rows should appear as:
The text to be processed lives in the “text” column, so pass this entire pandas series into spaCy’s small English language model.
Pipelines
Previously, we submitted a single string of text to the language model. We will now use spaCy’s pipe method in order to process multiple documents in one go. Note that pipe returns a generator that must be converted to a list before storing in the dataframe.
df[‘spacy_doc’] = list(nlp.pipe(df.text))
spaCy’s default pipeline includes a tokenizer, a tagger to assign parts of speech and lemmas to each token, a parser to detect syntactic dependencies, and a named entity recognizer. You may customize or remove each of these components, and you can also add extra steps to the pipeline as needed. See the spaCy documentation for more details.
Parts of Speech by Sentiment
A parsed version of each review now exists within the dataframe, so let’s do a quick warm-up exercise to explore the richness of these spaCy documents. Grouping the information by sentiment label, what are the most common adjectives used in positive versus negative reviews? (A double list comprehension followed by a counter works well for this task.)
pos_adj = [token.text.lower() for doc in positive_reviews.spacy_doc for token in doc if token.pos_=='ADJ'] neg_adj = [token.text.lower() for doc in negative_reviews.spacy_doc for token in doc if token.pos_=='ADJ'] from collections import Counter Counter(pos_adj).most_common(10) Counter(neg_adj).most_common(10)
Nice! This appears about as expected. The word “good” tops both lists, but it seems likely that several negative reviews might mention something that was “not good.” We have not incorporated negations yet, but spaCy certainly provides means for doing so through dependency parsing, customized tokenization, or with negspaCy.
It seems customers use adjectives to describe the service they received slightly more frequently than the restaurant’s food: “friendly” vs “delicious” in the positive reviews, “slow” vs “bland” in the negative ones. Does this mean reviewers mostly talk about the waitstaff? Let’s check the nouns. With similar code we get:
Nope – good or bad, people overwhelming care about the food. Amazingly, both lists match exactly on the top four nouns, but after that customers more often mention the “staff” or the “menu” when they are pleased and tend to focus on “minutes” spent and lack of “flavor” when disappointed.
Dependency Parsing
Comparing the nouns and adjectives by sentiment certainly adds insight, but we probably care about the specific adjectives used to characterize each noun even more. That is, how do people describe the food? What are they saying about the service? Navigating spaCy’s dependency tree provides these valuable details.
For a given noun of interest, extract each of the adjectival modifiers that are among its children tokens. Consider an example pandas series of spaCy documents (ser) along with a particular noun string (noun_str). A simple way to produce a list of adjectives modifying this noun follows:
amod_list = [] for doc in ser: for token in doc: if (token.text) == noun_str: for child in token.children: if child.dep == amod: amod_list.append(child.text.lower())
Since sentiment labels are supplied in this dataset, we collect these adjectives from positive and negative reviews separately.
So, what are customers saying about the “food”?
A few negation issues crop up again, but overall this provides a great perspective into what customers like and dislike about “food” in these reviews. Let’s check “service” as well:
Adjectives like “good” or “poor” may not give us much insight, but we can certainly imagine what went wrong when a customer describes their service as “rude” or “slow.” This dataset contains a mere 1,000 reviews from various establishments. Given a larger corpus of feedback from a single place of business, spaCy could be applied to home in on competitive edge or customer pain points, all with a highly automated approach.
Conclusion
spaCy provides an easy-to-use framework for getting started with NLP. Tokenization, lemmatization, dependency parsing, and named entity recognition occur by simply passing text to spaCy’s basic language model, and you can leverage the resulting token attributes to more broadly understand any set of documents. spaCy is quite fast due to its Cython infrastructure and often proves performant in terms of accuracy.
spaCy encapsulates many more tools that were not covered in this post including techniques to:
- Detect noun phrases within documents
- Score the similarity of tokens or documents via word vectors
- Systemically match special character or token patterns (Matcher, PhraseMatcher)
- Train a model to classify text documents (TextCategorizer)
You can also customize just about every one of spaCy’s components, from how it performs tokenization to the steps included in its processing pipeline.
Hopefully this introduction has inspired you to give spaCy a try. You can check out the code that powers each example in this post on Google Colab. If you enjoyed this topic, learn more about spaCy and other exciting natural language processing tools in my upcoming talk at ODSC East, “Level Up: Fancy NLP with Straightforward Tools“!
Kimberly is a speaker for ODSC East 2020! Be sure to check out her talk, “Level Up: Fancy NLP with Straightforward Tools,” at this upcoming event!
Kimberly Fessel is a Senior Data Scientist and Instructor at Metis’s immersive data science bootcamp in New York City. Prior to joining Metis, Kimberly worked in digital advertising where she focused on helping clients understand their customers by leveraging unstructured data with modern NLP techniques. Her website is: | https://opendatascience.com/level-up-spacy-nlp-for-the-win/ | CC-MAIN-2021-17 | refinedweb | 1,843 | 53.51 |
by Zoran Horvat
May 14, 2013
Given a sorted array of integer numbers, write a function which returns zero-based position on which the specified value is located. Function should return negative value if requested number cannot be found in the array. If value occurs more than once, function should return position of the first occurrence.
Example: Suppose that array consists of numbers 2, 3, 5, 6, 6, 8, 9. If value 6 is searched, then result is 3, because that is the zero-based position of the first occurrence of number 6 in the array. If number 7 is searched, then result is a negative value (e.g. -1), which indicates that value 7 cannot be found in the array.
Keywords: Array, sorted, search, partitioning.
For a moment forget that array might contain the requested number more than once. If we reach a satisfactory algorithm that efficiently finds any occurrence of a number, then we will already be close to the solution. With a simple tweak we will then ensure that algorithm discovers the first occurrence of the number.
The simplest way to see if an array contains a requested value is to iterate through the array and stop as soon as the value is located. Alternatively, search fails if end of array is reached. This algorithm, with some enhancements, is demonstrated in one of the previous exercises (Finding a Value in an Unsorted Array). But this approach does not take advantage of the fact that array is sorted. In order to make the searching function faster, we will have to collect additional information about values in the array from the sort order itself.
If we take the array from example above and try to find number 6 in it, then we might inspect the first value (2) and conclude that search should continue forward because this value is less than the number we are looking for. But we are not constrained to iterate through the array too stringently. We could jump two positions ahead, where number 5 is located - still too small. Should we jump three steps ahead next time, we would find value 8, which is too large - signal to step back. And there we go - one position back and value 6 is found.
Searching tactic just demonstrated is not the most elegant one that we could come up with. But it hits the point in searching through the sorted array. We are free to jump back and forth through array as long as searching space shrinks with each step. After the first two comparisons we were sure that number 6 does not appear on any of the three leading positions. One step later, we already knew that number we are looking for doesn't appear on the last two positions either. In only three comparisons we have eliminated five out of seven elements of the array. This analysis shows that searching through the array can be much more efficient than the simple iterative approach when array is known to be sorted. Next thing to do now is to discover a better method of eliminating unwanted elements.
Suppose that we use an arbitrary method to pick a position in the array and to compare a number on that position, whichever it is, with the target number. If the two numbers are equal, then the search is over. Otherwise, we must decide on which side of the current position could the requested number be located. If current element is greater than the requested number, then searching should obviously continue on the left-hand part of the array. Otherwise, we continue searching on the right-hand part of the array. Algorithm continues recursively on the selected sub-array, completely discarding all the values on the other side of the element which was tested. Algorithm terminates either when element under test is equal to the number we are looking for, or when remaining section of the array becomes empty, in which case we simply conclude that the number was not located.
Now we are ready to ask the central question. At any given step we have a certain range within the array which we are investigating. All elements to the left and to the right have already been discarded. Without any additional information about values in the remaining section, which is the most convenient element we might choose for comparison to maximally reduce the search section?
Since requested value could be located anywhere within the array section (if it is there, in the first place), then the best we could do is to pick an element in the middle of the array, cutting the segment into equal halves (off by one, at most). That partitioning method guarantees that one half of the values will be gone once the comparison is done, whichever the comparison result.
Here is the pseudo-code which finds any occurrence of the requested value within the array:
function FindAnySorted(a, n, x) a - sorted array n - length of the array x - value searched in the array begin left = 0 right = n – 1 while left <= right begin middle = (left + right) / 2 if a[middle] = x then return middle if a[middle] > x then right = middle - 1 else left = middle + 1 end return -1 -- value was not found end
Observe how the remaining part of the array reduces by half plus the middle element in each iteration of the algorithm. This leads to a conclusion that number of comparisons needed to find a value in the sorted array with N elements is proportional to logN in the worst case.
Now we should return to the original problem statement and try to modify the solution so that it returns position of the first occurrence of a value within the array in cases when that value occurs more than once. Modified partitioning algorithm would be to search for the boundary, a location between two elements, rather than a particular element, such that all numbers to the left of the boundary are strictly less than the requested number and all elements to the right are greater or equal to the requested number. With the example array from the problem statement (2, 3, 5, 6, 6, 8, 9), when searching for value 6, this boundary would fall between positions 2 and 3.
In the simple partitioning algorithm, we tracked positions left and right, which indicated the first and the last element in the remaining segment of the array, respectively. That way of tracking the elements was natural in that case, because array had to be non-empty in each step. Should the array become empty, the search would fail. In the modified solution, however, we are forcing the algorithm to run until remaining segment is empty. Its left and right border would then be the last element less than and the first element greater or equal than the requested element. This implies that initial left and right indices are -1 and N for zero-based array. In other words, initial boundaries will be outside the array. To picture this situation, we might imagine that there exists one infinitely small element to the left of the array occupying location -1, and one infinitely large element to the right of the array occupying location N. These two fake elements will certainly be the smallest and the largest elements in the array, and array will remain sorted. Note that left and right indicator in this setting now point outside of the current array segment. Algorithm will terminate when right indicator is by one position to the right of the left indicator.
The following picture demonstrates finding the first occurrence of number 6 within an array.
Observe how left and right indicators gradually converge towards each other. Once they meet, the cutting line between them divides the array – all values to the left are strictly less than 6; all values to the right are greater or equal to 6. Now the only thing remaining is to test whether there is any element to the right (cutting line could easily fall at the end of the array) and, if there is such an element, to test whether it is equal to 6. Since right-hand elements are greater or equal to 6, the first element to the right might as well be strictly greater than 6, in which case we simply conclude that searched number does not appear in the array.
Now that we have outlined the way in which bounds of the current array segment are tracked, we are ready to produce the final algorithm. Here is the pseudo-code:
function FindFirstSorted(a, n, x) a - sorted array n - length of the array x - value searched in the array begin left = -1 right = n while right > left + 1 begin middle = (left + right) / 2 if a[middle] < x then left = middle else right = middle end if right < n and a[right] = x then return right return -1 end
There are a couple of interesting details in this solution. First of all, we might ask is the while loop going to terminate in all cases? We are supposed to prove that middle is strictly greater than left and strictly less than right. If so, then in either way one of the boundaries is going to change and array segment being searched is going to shrink in every step. Proof for this claim is very simple if we start from the condition in the while statement:
. Now we can compare the value of the middle variable with both left and right:. Now we can compare the value of the middle variable with both left and right:
right > left + 1
From this analysis we conclude that:
This proves that remaining part of the array is going to be shorter with every step of the algorithm. Middle position is strictly greater than left and strictly less than right boundary. As a result, either the left boundary is going to move to the right or the right boundary is going to move to the left. In either case, number of elements in between will reduce. Off course, once there are no more elements between the boundaries, the remaining part of the array will become empty and while loop will terminate.
Now that we know the function is going to exit at some point in time, we will examine the final part, in which return value is decided. Namely, the whole purpose of the loop was to find a dividing point in the array, a point standing in between the two elements, such that all numbers to the left are strictly less than the requested element and all numbers to the right are greater or equal to the requested element. The point to note here is that, once the loop terminates, variable right points to the first element of the array that is greater or equal to the searched number. Now there are two pitfalls out there. First one is that variable right might point outside the array (right = N). This happens if right remains with its initial value, which in turn happens when all values in the array are strictly less than the searched value. The second issue is if value at position right is not equal to the requested number. In that case, the loop has established a cutting point where smaller values end and larger values begin. There is nothing wrong with the loop, only there are no values equal to the searched number. Therefore, algorithm terminates with success only if the following combined criterion is met:
. Otherwise, function returns negative value, indicating that searched value was not found in the array.. Otherwise, function returns negative value, indicating that searched value was not found in the array.
right < n and a[right] = x
With all the previous analysis, implementation of the function that finds first occurrence of a number in the sorted array is very simple. Here is the source code:
int FindFirstSorted(int[] a, int x) { int left = -1; int right = a.Length; while (right > left + 1) { int middle = (left + right) / 2; if (a[middle] >= x) right = middle; else left = middle; } if (right < a.Length && a[right] == x) return right; return -1; }
Below is the source code of a simple console application which demonstrates use of the FindFirstSorted function.
using System; namespace FindSortedDemo { public class Program { static Random _rnd = new Random(); static int[] GenerateArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = _rnd.Next(10); Array.Sort(a); return a; } static void PrintArray(int[] a) { for (int i = 0; i < a.Length; i++) Console.Write("{0,3}", a[i]); Console.WriteLine(); } static int FindFirstSorted(int[] a, int x) { ... } static void Main(string[] args) { while (true) { Console.Write("n="); int n = int.Parse(Console.ReadLine()); if (n <= 0) break; int[] a = GenerateArray(n); PrintArray(a); Console.Write("x="); int x = int.Parse(Console.ReadLine()); int pos = FindFirstSorted(a, x); if (pos < 0) Console.WriteLine("Value not found."); else Console.WriteLine("Value found at position {0}.", pos); } Console.Write("Press ENTER to continue... "); Console.ReadLine(); } } }
When application is run, it produces output like this:
n=10 0 0 1 3 3 5 6 7 8 8 x=5 Value found at position 5. n=7 0 2 3 3 7 8 9 x=1 Value not found. n=9 0 1 2 4 4 5 6 8 8 x=9 Value not found. n=8 2 2 2 2 3 4 8 9 x=2 Value found at position 0. n=10 1 2 4 4 5 5 6 6 8 9 x=9 Value found at position 9. n=0 Press ENTER to continue...
Starting from the solution from this exercise, try to solve the following problems:. | http://codinghelmet.com/exercises/sorted-array-search | CC-MAIN-2019-04 | refinedweb | 2,295 | 59.64 |
On Tue, Feb 24, 2009 at 10:08:11PM +0000, Richard Jones wrote: > Hmmm .. I think you misunderstand what Fedora is doing. Our deps > simply take the current MD5 sums as used by the OCaml compiler, and we > map those directly into package dependencies. I think I got it correctly, even though I might have expressed it wrongly or inappropriately, let's see. > For example: Yep, that was clear to me. > These dependencies are generated and depsolved completely > automatically, without any human intervention at all, so, > > "it provides virtual package names which are not only > entirely meaningless for humans, but also hard to grasp > for people who sooner or later will have to deal with them". Let me explain what I meant with this paragraph. Paragraph that, actually, descends from an objection to the "Fedora approach" we got from our release managers. The objection was that during migration to testing someone (the release managers) will sooner or later need to face a line like: > ocaml(List) = da1ce9168f0408ff26158af757456948 because that line might be the reason why a package is uninstallable in testing (even temporarily). That someone will then have to understand which packages fix it, and doing so with a 16 characters long hash is not necessarily handy. That was the point of "meaningless for humans", where maybe "humans" can be replaced for "non-OCaml programmers" (even though even for them md5sum are not "handy" at all). But on a second though, even users can be faced with such hashes, for example due to errors in the archive which can be temporarily inconsistent or because their package manager is incomplete WRT dependency solving. In that case, the md5sums pop up in error messages and, I believe, they will confuse sensibly the user. Hence, the proposal is taking a checksum of all the checksums, which will of course increase the probability of collision, but still keep them at a reasonable level, and improving seriously upon the current status where dependencies mean nothing in terms of OCaml linkability. If you think the quoted paragraph should be rephrased to better represent what you're doing, just let me know. > (I assume dh_ocaml can generate dependencies automatically by > examining the *.cmo & *.cma files contained in the final binary > package?) Yep, that's the idea, but also including native code objects. BTW: did you notice that in OCaml 3.11 there is now an executable to inspect also implementation assumption for native code objects? AFAIR Fedora mechanism's was only based on bytecode assumptions. We plan to support both kind of assumptions and I guess it would make sense for Fedora too (even though you will need to have an extra namespace in deps to differentiate bytecode vs native code | https://lists.debian.org/debian-ocaml-maint/2009/02/msg00249.html | CC-MAIN-2016-30 | refinedweb | 454 | 50.97 |
Al is a DDJ contributing editor. He can be contacted at 71101.1262@compuserve.com.
A new book by Michael Moore, the creator of Roger and Me, TV Nation, and other works of liberal satire. I saw Mike plugging his new book, Downsize This! (Crown Publishers, ISBN 0-517-70739-X) on a couple of talk shows and, on the day he said it would be released, went directly to the local Walden Bookstore. There, in a prominent display, were several copies of Downsize This! each with a big round sticker announcing "15% Off!" just under the title. Struck by the comical irony of the discount, I sent Mike a message--his e-mail address is on the last page of the book--alerting him that he was already being downsized with an automatic paycut on his first day of publication. Being an author myself, I added that publishing one's e-mail address can be a mixed blessing for an author. I get a lot of mail, not all of it constructive. Mike replied, "I'm not yet sorry I published this address. The response is fascinating." The book's been out only a few days Mike, and you're a lot more famous than me. Just wait.
Downsizing ain't all bad. I retired from consulting several years ago to concentrate on writing, but downsizing created new opportunities for some interesting work. It wasn't easy to trade jeans, T-shirt, and flex hours for appropriate attire, an ID badge, and 9-to-5, but I did it. Judy always looks on the bright side. She likes it when I work somewhere other than at home. More money and less husband, she says.
My new consulting work results from government downsizing. I teach C and C++ classes to federal employees who need to acquire new skills in the face of drastic budget cuts. I develop and maintain C++ programs for contractors who support their government clients but cannot hire programmers because of the uncertain future. Downsizing creates opportunities for people like me. We prosper on the plight of others.
Don't misunderstand. Despite the opportunities, I'm no fan of downsizing, even when it promises to cut government waste, a promise seldom if ever kept, by the way. Politicians who promise to cut government spending never address the obvious problems associated with doing that. Whether or not a government program is productive or useful, we cannot ignore the socio-economic superstructure that it has created and sustains. When they close a base or cut the budget of a big government project, they not only add a bunch of former employees to the welfare roles, but they indirectly downsize all the local businesses, too. Real people are affected. Clerks, bartenders, plumbers, sign-painters, sales people, garbage collectors, stockbrokers, teachers, preachers, mechanics, tradesmen, cops, real estate agents. Yes, and programmers, too. All with rent or mortgages, car payments, kids to feed. The next time your favorite candidate promises you less government, ask about the side effects. Who's going to pay for them?
delete this;
In September, I addressed the advisability of coding delete this; in a class member function. I said, "It's not a good practice." I got a lot of mail from programmers about that opinion. The vote seems to be split 50/50. Nothing is more interesting than a polarizing issue. Some readers sent code showing cases where they thought the idiom was acceptable, and, in some cases, necessary. Allow me now to clarify my opinion, which has been modified somewhat by the mail I received.
If you are designing a class to publish for others to use, do not allow it to delete itself. Period. Disagree if you like and code anything the language allows to your heart's content, but I stand by that conviction and will continue to code and teach according to that guideline. I'll repeat the problems: First, the only way that delete this; works is if the object is instantiated on the heap. Second, assuming that a class could assert that an object is on the heap (which it cannot), there is no way to assert that the user does not dereference the pointer to the object after the object has deleted itself--including deleting the object a second time.
Why do I persist in this position? In my consulting work I maintain programs written by programmers who have fallen to the downsizer's axe. In virtually every case where a class uses delete this;, the usage is the source of one or more bugs, usually because the program that instantiates the object tries to use the object after it has deleted itself. Furthermore, wherever I found the idiom in use, I was able to redesign the class so that it did not need delete this;.
I wondered if the heap-only problem could be solved. After several tries, I was unable to arrive at a platform-independent, fully-portable way for an object to:
- Assert that it was indeed instantiated on the heap.
- Ascertain that it had deleted itself and intercept and suppress subsequent deletes.
- Intercept dereferences of the object's pointer after it has deleted itself.
One of those rules was a shock. I thought that by overloading the delete operator, I could determine if the object had already deleted itself. The details of that attempt are not important. What is important is what I learned when Scott said to me:
The value of a pointer may be changed by the act of deleting it. Which is why this code [Example 1] yields undefined behavior. The problem is that the full action of the delete operator (not operator delete...) is not specified by the standard. We know that for single objects, it invokes a destructor sequence and then calls operator delete, but we have no assurance that that is all it does. In particular, it remains free to change the value of the pointer being deleted, and there is no way to take control over this.
To make his point, Scott referred to the following passage in the ANSI C++ Draft Working Paper, section "5.3.5 Delete."
It is unspecified whether the deletion of an object changes its value. If the expression denoting the object in a delete-expression is a modifiable lvalue, any attempt to access its value after the deletion is undefined. [emphasis added]
Maybe it's because I don't haunt the hallowed halls of language design and standardization, but it never occurred to me that the delete operator would modify the contents of the pointer variable that is its operand. It sounds so improbable, and I've never seen that behavior implemented in a compiler. I want to believe that the explicit behavior spelled out in that passage is a mistake, but, like most such anomalies in high-level languages, it must exist because somewhere a legacy compiler does it for whatever reason.
This rule raises a red flag. You often see classes that initialize pointers to zero in their constructors and delete those pointers in their destructors. They also delete those pointers and assign to them with new elsewhere. If it is possible that a class could have the equivalent of Example 1--two subsequent deletes of a thought-to-be-zero-value pointer without an intervening assignment of something valid, an insidious bug lurks waiting to bite you when you port this program elsewhere.
From Bjarne Stroustrup
I sent Bjarne Stroustrup a message asking his opinion of delete this;. He answered:
The delete this; construct is valid in a member function. Once that is done every access to a non-static member (data or function) is undefined. Caveat emptor!
The use of the construct comes with techniques for conditionally deleting objects. For example [see Example 2(a)]: I guess someone must have misused delete this; badly for it to become an issue, but I have not personally encountered it as a serious problem in real code. On the other hand, I don't recall using delete this; recently. These days, I tend to control such objects through "handles' that tend to live on the stack and in other objects... [see Example 2(b)].
Bjarne went on to demonstrate how, if the language rules prohibited delete this;, programmers would find ways around the restriction.
Readers of the Lost Art
My attitude was adjusted not only by communications with the rich and famous. Several readers wrote to express their opinions. Esa Leskinen wrote about his usage of the idiom to implement reference counting. Adam Sapek talked about how reference-counting COM objects use the idiom to destroy themselves. John B. Williston offered this comment:
[delete this; statements] are very handy for writing classes of the CListBoxPopupEdit type. This is a class that one instantiates passing a pointer to a listbox and an item index; the edit control pops up over said item, allowing editing of the text. The edit self-destructs whenever the user presses enter, escape, or changes focus. The instantiation is controlled by a static member function that returns no pointer to the object. Without this idiom, the edit control would need to send a message off to some other window to free its own CEdit object (or something like that--it would essentially make the object less reusable).
So, given the firm stand I took at the beginning of this discussion, how have I altered my opinion about delete this;? In More Effective C++ (if you program in C++, you need both of Scott's books), Scott proposes a base class that provides reference-counting behavior to its derived classes. A reference-counted class contains data members that can be shared among several objects of the class. You cannot get the same effect with static members because there might be other objects with different values. Scott uses the ubiquitous String class to make the point. When you assign one string object to another or construct a new string object from an existing one, there is no reason that they should not share the same physical string data. A reference count specifies how many objects share the data. Copy constructors and overloaded assignment operators increment the count. Destructors decrement the count. When the count goes to zero, the destructor deletes the data.
After implementing a self-contained reference-counting String class, Scott implements a generic reference-counting base class from which new reference-counted classes can be derived. When its count goes to zero, the object deletes itself. This usage would violate my guidelines if you used it as the base for a derived class that everyone uses. Instead, Scott uses the base class to derive a specialized class that contains the shared data portion of the objects. He embeds an object of that class in his published class. Objects that delete themselves are hidden from programmers who use the published class. Presumably, the author of the published class knows enough to deal appropriately with the private suicidal object. I do not object to a usage of delete this; that hides those details from users of the class. But I doubt that I will ever use the statement in my own code.
As Bjarne says, "caveat emptor."
Undoing the Undoable
The government project I've been working on includes a downscale custom word processor that works with SGML text. SGML is the architecture upon which HTML is built. One of the editor's requirements is that it support an Undo feature similar to those on high-end text editors and word processors.
The editor's Undo class hierarchy is tailored specifically to the needs of that particular editor. Users can type text with insert or overstrike mode, they can delete characters or blocks of text, and they can insert and delete SGML tags, which define the document components. During all this, tags can be exposed or hidden behind a WYSIWYG document interface, and redlining can be on or off. Any of these actions can be undone.
There are three basic variations on the Undo scenario. The simplest is what you find in small text editors such as the Windows 95 Notepad applet. Only your most recent action can be undone. The Word for Windows Undo feature includes Undo and Redo and can Undo all the way back to the document as it was before you started making changes or until you hit the limits of its Undo buffer. Each Undo action reverses a textual change to the document. The Brief programmer's editor, and its descendent, the Borland IDE editor work with Undo and Redo down to the keystroke level. Every keystroke, including cursor movements, can be undone. The Undo feature in the custom SGML editor is more like the second variation. It would be pointless, however, to publish its source code because of its tight coupling to the editor's document format.
Decomposing
In working with a music-related program, I had to develop a custom editor that lets users change a musical score. Actually, the document is more like what musicians call a "lead sheet" because it consists of measures with quarter-note beats and chord symbols. Its editor allows the insertion of chords and the usual clipboard operations on one or more adjacent measures. After using it for a while, I realized that my music editor was in sore need of an Undo feature. Sometimes I just need to decompose.
Comparing the very specific requirements of that SGML text editor with those of the music editor, I found that they have a lot in common when viewed from a higher level of abstraction. Both must remember the insertion, deletion, and replacement of arrays of objects in order to undo those actions upon demand. Both must store those undoable actions in a stack data structure so that the most recent action is the one undone.
In the case of the SGML editor, the objects can be characters, strings, and SGML tags. This organization is typical of how a word-processing document is organized. The document is one huge array of text with interspersed commands that identify a document's organization and presentation. Users change the document by adding, changing, and deleting these elements.
In the case of the music editor, the objects can be chords, tempo changes, repeats, rests, the song title, and rhythmic style changes. Ignoring the melody for this purpose, a song is an array of beats, grouped in measures, with each beat having a particular chord and, perhaps, one or more of the other events.
I concluded that a generic Undo class library is an appropriate approach to this problem, and I set out to build one by using C++ templates. The code that accompanies this column is the implementation of that library. At the moment, I have implemented only object insertions and deletions, which satisfy the requirements of the music program as far as it has gone. I need to implement object replacement later. It is my intention that this class library could be used to implement a full Undo feature in any program that needed it.
The library uses a variation of the generic programming model that STL uses. For an application to use the feature, the application must include a document class and what I will call here an object class. The document class maintains the document's buffer of data. The document buffer consists of some mixture of objects, each identifiable as a C++ intrinsic or user-defined type. The document must include two functions (three, when replace is implemented later) that permit the Undo feature to insert and delete arrays of objects. The application must then subclass two (three later) of Undo's classes to record the insertion and deletion actions to be stored for possible later undo.
The Generic Undo Class Library
Listing One is undo.h, which contains most of the implementation of the generic class library. The first class, UndoNode, is not a template. It is the base class from which all undoable actions are derived. Since the class is not a template, a later class can instantiate an array of pointers to the class without needing template argument qualifiers.
The next class is UndoItem<D,T>, which is a template base class for the undo actions. The D argument represents the application's document class, and the T argument represents the objects that can be inserted into and deleted from the document. The class contains a reference to the document class object, and two data members that all undo actions have in common: a pointer into the document buffer where the action occurred, and a count of the number of T objects involved in the action.
Two classes derive from UndoItem<D,T>: UndoInsertNode<D,T> is a base class for insertions into the document, and UndoDeleteNode<D,T> is a base class for deletions from the document. Both are constructed with the pointer into the document, the count of items, and a bool variable that specifies whether a subsequent undo action stops after undoing this action or continues with the next action. Both classes override the pure virtual Undo function from the abstract base UndoNode class. When users choose the Undo command, the program calls the Undo function for the appropriate action class.
The UndoDeleteNode<D,T> constructor stores the document reference and the pointer and count. Then the constructor allocates a buffer and makes a copy of what is being deleted so that an undo action can restore the deleted objects. This class's Undo function calls the document's Insert function passing the pointer and count. An application that uses this class library must provide a document class with an Insert function that accepts a pointer to its object class and a count of objects to insert. After calling Insert, the Undo function deletes the memory allocated for the buffer.
The UndoInsertNode<D,T> constructor also stores the document reference and the pointer and count. Undoing an insertion does not require remembering any prior data values. This class's Undo function calls the document's Delete function passing the pointer and count. An application that uses this class library must provide a document class with a Delete function that accepts a pointer to its object class and a count of objects to delete.
The third class in Listing One declares the UndoData class. An application instantiates an object of a class derived from this class to contain the undo information. An uninitialized array of pointers to UndoNode objects constitutes the circular stack of undo actions. The m_nCurrentUndo data member is the stack pointer. The m_nUndoCount data member counts the number of undo actions stored. The m_bUndoing data member is true while the class is processing an undo request and false otherwise. Users of the class can use this value (returned by the IsUndoing member function) to prevent their Insert and Delete document functions from adding undo actions during an undo. The IsUndoDataStored function tells the application when there are any actions that can be undone. An application can use this information to enable and disable the Undo command.
The application's Undo command calls UndoData::UndoLastAction, which does what its name implies.
Listing Two is undo.cpp, which contains the member functions for the UndoData class. The destructor deletes all remaining undo actions. The AddUndoNode function adds an action to the top of the stack. UndoLastAction pops the top undo action, calls its Undo function, and pops and calls lower ones until an anchored condition is found.
Listing Three is songundo.h, which represents part of an applications implementation of the undo feature with this library. The application subclasses the UndoInsertNode<D,T> and UndoDeleteNode<D,T> classes for each insertion and deletion action. The base class specifier provides the template arguments that identify the document and object classes. These subclasses need nothing more than a public constructor that passes the object pointer, count, and the anchor indicator to the base class.
The UndoSongData class is an example of the class that you derive from UndoData and instantiate into your application. It consists mostly of member functions that add undoable actions to the stack. The application calls these member functions when an undoable delete is about to occur or an undoable insertion has just occurred.
I have not tested this class library beyond the two applications I mentioned, but every indication is that, with the addition of an UndoReplace feature and perhaps an UndoCommand feature, this library would support most of the undo requirements of any application. Adding redo would be fairly simple. Redo is the inverse of undo, and the undo system could instantiate its own undo system.
Example 1: A shocker!
char *p = 0; delete p; // fine, deletion of the null pointer delete p; // undefined, p may no longer be null
Example 2: (a) Bjarne's first example; (b) Bjarne's second example.
(a) Class Base { int user_count; // ... public: Base() : user_count(0) { connect(); } void connect() { user_count++; } void disconnect { if (--user_count==0) delete this; } // ... }; (b) void disconnect { if (--objp->user_count==0) delete objp; }
Listing One
// --------- undo.h
#ifndef UNDO_H
#define UNDO_H
#define bool BOOL
#define false FALSE
#define true TRUE
class UndoNode {
bool m_bAnchor; // undo action stream terminator
public:
UndoNode(bool bStophere = true) : m_bAnchor(bStophere)
{ }
virtual ~UndoNode() { }
virtual void Undo() = 0;
bool Anchor() const
{ return m_bAnchor; }
};
//---------------------------------------------------------------------------
template <class D, class T>
class UndoItem : public UndoNode {
protected:
D& m_rDoc;
T* m_pPosition; // document position
int m_nCount; // item count
public:
UndoItem(D& rDoc,T* pPosition = 0,int nCount = 0,bool bStophere = true) :
UndoNode(bStophere),m_rDoc(rDoc),m_pPosition(pPosition),m_nCount(nCount)
{ }
virtual ~UndoItem() { }
};
//--------------------------------------------------------------------------
template <class D, class T>
class UndoInsertNode : public UndoItem<D, T> {
public:
UndoInsertNode(D& rDoc, T* pPosition, int nCount, bool bStophere) :
UndoItem<D,T>(rDoc, pPosition, nCount, bStophere)
{ }
virtual ~UndoInsertNode() { }
virtual void Undo()
{
m_rDoc.Delete(m_pPosition, m_nCount);
}
};
//--------------------------------------------------------------------------
template <class D, class T>
class UndoDeleteNode : public UndoItem<D, T> {
protected:
T* m_pData;
public:
UndoDeleteNode(D& rDoc, T* pPosition, int nCount, bool bStophere) :
UndoItem<D,T>(rDoc, pPosition, nCount, bStophere)
{
m_pData = new T[nCount];
for (int i = 0; i < nCount; i++)
*(m_pData + i) = *pPosition++;
}
virtual ~UndoDeleteNode()
{
delete [] m_pData;
}
virtual void Undo()
{
m_rDoc.Insert(m_pPosition, m_nCount, m_pData);
delete [] m_pData;
m_pData = 0;
}
};
//---------------------------------------------------------------------------
const int maxUndos = 300;
class UndoData {
UndoNode* m_pUndoNode[maxUndos];
int m_nCurrentUndo;
int m_nUndoCount;
bool m_bUndoing;
public:
UndoData() : m_nCurrentUndo(0), m_nUndoCount(0), m_bUndoing(false)
{ }
~UndoData();
void AddUndoNode(UndoNode* pUndoNode);
void UndoLastAction();
bool IsUndoDataStored() const
{ return m_nUndoCount != 0; }
bool IsUndoing() const
{ return m_bUndoing; }
};
#endif
Listing Two
// ----- undo.cpp
#include "stdafx.h"
#include "undo.h"
UndoData::~UndoData()
{
while (m_nCurrentUndo > 0) {
delete m_pUndoNode[--m_nCurrentUndo];
--m_nUndoCount;
}
if (m_nUndoCount) {
m_nCurrentUndo = maxUndos;
while (m_nUndoCount-- > 0)
delete m_pUndoNode[--m_nCurrentUndo];
}
}
void UndoData::AddUndoNode(UndoNode* pUndoNode)
{
if (m_nCurrentUndo == maxUndos)
m_nCurrentUndo = 0;
m_pUndoNode[m_nCurrentUndo++] = pUndoNode;
if (m_nUndoCount < maxUndos)
m_nUndoCount++;
}
void UndoData::UndoLastAction()
{
if (m_nUndoCount) {
m_bUndoing = true;
bool bAnchor = true;
do {
if (m_nCurrentUndo == 0)
m_nCurrentUndo = maxUndos;
m_pUndoNode[--m_nCurrentUndo]->Undo();
bAnchor = m_pUndoNode[m_nCurrentUndo]->Anchor();
delete m_pUndoNode[m_nCurrentUndo];
--m_nUndoCount;
} while (bAnchor == false);
m_bUndoing = false;
}
}
Listing Three
// ------- songundo.h
#ifndef SONGUNDO_H
#define SONGUNDO_H
#include "undo.h"
#include "song.h"
// --------------------------------------------------------------------------
class UndoInsertEvents : public UndoInsertNode<Song, Song::Event> {
public:
UndoInsertEvents(Song::Event* pEvent, int nCount, BOOL bStophere) :
UndoInsertNode<Song, Song::Event>(theSong, pEvent, nCount, bStophere)
{ }
};
// --------------------------------------------------------------------------
class UndoDeleteEvents : public UndoDeleteNode<Song, Song::Event> {
public:
UndoDeleteEvents(Song::Event* pEvent, int nCount, BOOL bStophere) :
UndoDeleteNode<Song, Song::Event>(theSong, pEvent, nCount, bStophere)
{ }
};
// --------------------------------------------------------------------------
class UndoSongData : public UndoData {
public:
UndoSongData() { }
void AddInsertMeasureUndo(Song::Event* pEvent, int nCount,
BOOL bStophere = TRUE)
{
AddUndoNode(new UndoInsertEvents(pEvent, nCount, bStophere));
}
void AddDeleteMeasureUndo(Song::Event* pEvent, int nCount,
BOOL bStophere = TRUE)
{
AddUndoNode(new UndoDeleteEvents(pEvent, nCount, bStophere));
}
};
#endif | http://www.drdobbs.com/database/delete-this/184410022 | CC-MAIN-2016-30 | refinedweb | 3,926 | 53.71 |
if 5 < 6:
print ("error")
def standart thats doenst have functionality to directly query: what is the appdir for app 'myapp'?, but lets seek a portable solution. An old version of this recipe tells:
appdir = os.path.abspath(os.path.dirname(sys.argv[0]))
warning that sys.argv[0] its usualy the command line used to start the app, but not guaranted. By example, if the entry point for the app lies in main.py, and someone start__))
wich in the python console case will fail with NameError: __file__ is not defined
If you cannot resolve appdir, then the better is to give feedback to the user (print, a tkinter window, any that only uses python and standart woldnt bother.
Note that the python docs are unclear (or the info if burried, like do test if the new code cover more, and make explicit comments about what more it covers. The only adition to the older recipe code is the termination when a reliable appdir can not be built, and it was motivated by some misleading bug reports in pyweek6. Have a nice prog!!!
if 1 <= x <= 2:
if 1 <= x <= 2:
The Pygame draw package uses a crude, aliasing, algorithm to draw single pixel width circles. Thicker circles are composed of multiple single pixel width circles. There is not much overlapping of circles so, regrettably, it leaves holes.
Until Pygame incorporates a package like SDL_gfx (in pgreloaded already) with a filled-ellipse draw function programs will just have work around it. One solution, provided by Ian Mallett on the pygame-users, "is to draw a circle on a surface, then use pygame.draw.polygon() to clean off the parts you don't need. You can use colorkey-transparency as well to get 'cut-out' arcs." For arcs Ben Friman observed "that by making tiny adjustments to the arc angles, and re-drawing the arc, most of the holes would get covered up."
To. | http://www.pygame.org/wiki/sandbox?parent=syntax | CC-MAIN-2016-26 | refinedweb | 324 | 71.24 |
On Tue, May 19, 2009 at 12:54 AM, Miguel Mitrofanov <miguelimo38 at yandex.ru> wrote: > I. This isn't great, though. Consider this (slightly generalized) version: > newtype CpsM c t a = CpsM { unCpsM :: forall b. c b -> (a -> t b) -> t b } We can easily make this a monad for any c & t: > instance Monad (CpsM c t) where > return x = CpsM $ \_ k -> k x > m >>= f = CpsM $ \c k -> unCpsM m c $ \x -> unCpsM (f x) c k Here's a useful one: > -- reify Ord constraint in a data structure > data OrdConstraint a where > HasOrd :: Ord a => OrdConstraint a > type M = CpsM OrdConstraint S.Set along with your "casting" functions: > liftS :: S.Set a -> M a > liftS s = CpsM $ \c at HasOrd k -> S.unions $ map k $ S.toList s > runS :: Ord a => M a -> S.Set a > runS m = unCpsM m HasOrd S.singleton Now consider this code: > inner = do > x <- liftS (S.fromList [1..3]) > y <- liftS (S.fromList [1..3]) > return (x+y) > outer = do > x <- inner > y <- inner > return (x+y) If you evaluate (runS outer), eventually you get to a state like this: = let f x = inner >>= \y -> return (x+y) g x2 = liftS (S.fromList [1..3]) >>= \y2 -> return (x2+y2) h = HasOrd k = \a2 -> unCpsM (g a2) h $ \a -> unCpsM (f a) h S.singleton in S.unions $ map k [1,2,3] which, after all the evaluation, leads to this: = S.unions [S.fromList [4,5,6,7,8,9,10], S.fromList [5,6,7,8,9,10,11], S.fromList [6,7,8,9,10,11,12]] We didn't really do any better than if we just stuck everything in a list and converted to a set at the end! Compare to the result of the same code using the restricted monad solution (in this case runS = id, liftS = id): inner >>= \x -> inner >>= \y -> return (x+y) = (Set [1,2,3] >>= \x -> Set [1,2,3] >>= \y -> return (x+y)) >>= \x -> inner >>= \y -> return (x+y) = (S.unions (map (\x -> Set [1,2,3] >>= \y -> return (x+y)) [1,2,3])) >>= \x -> inner >>= \y -> return (x+y) = S.unions [Set [2,3,4], Set [3,4,5], Set [4,5,6]] >>= \x -> inner >>= \y -> return (x+y) = Set [2,3,4,5,6] >>= \x -> inner >>= \y -> return (x+y) Notice how we've already snipped off a bunch of the computation that the continuation-based version ran; the left-associated >>= let us pre-collapse parts of the set down, which we will never do until the end of the CPS version. (This is obvious if you notice that in the CPS version, the only HasOrd getting passed around is for the final result type; we never call S.unions at any intermediate type!) Of course, you can manually cache the result yourself by wrapping "inner": > cacheS = liftS . runS > inner_cached = cacheS inner A version of "outer" using this version has the same behavior as the non-CPS version. But it sucks to have to insert the equivalent of "optimize this please" everywhere in your code :) -- ryan > > >> >> > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > > | http://www.haskell.org/pipermail/haskell-cafe/2009-May/061670.html | CC-MAIN-2014-35 | refinedweb | 529 | 71.65 |
Version 1.23.0
For an overview of this library, along with tutorials and examples, see CodeQL for C/C++
.
The C/C++ void type. See 4.7.
void
void foo();
import cpp
Canonical QL class corresponding to this element.
Gets a detailed string representation explaining the AST of this type (with all specifiers and nested constructs such as pointers). This is intended to help debug queries and is a very expensive operation; not to be used in production queries.
Gets the source of this element: either itself or a macro that expanded to this element.
Holds if this element may be from a library.
Holds if this element may be from source.
Gets a specifier of this type,.
typedef
decltype
typedef const int *restrict t
volatile t
volatile
restrict
const
Gets as many places as possible where this type is used by name in the source after macros have been replaced (in particular, therefore, this will find type name uses caused by macros). Note that all type name uses within instantiations are currently excluded - this is too draconian in the absence of indexing prototype instantiations of functions, and is likely to improve in the future. At present, the method takes the conservative approach of giving valid type name uses, but not necessarily all type name uses.
Gets the alignment of this type in bytes.
Gets an attribute of this type.
Gets the closest Element enclosing this one.
Element
Gets the primary file where this element occurs.
Gets the primary location of this element.
Gets the name of this type.
Gets the parent scope of this Element, if any. A scope is a Type (Class / Enum), a Namespace, a Block, a Function, or certain kinds of Statement.
Type
Class
Enum
Namespace
Block
Function
Statement
Gets the pointer indirection level of this type.
Gets the size of this type in bytes.
Gets this type after typedefs have been resolved.
Gets this type after specifiers have been deeply stripped and typedefs have been resolved.
Holds if this type is called name.
name
Holds if this declaration has a specifier called name,.
Internal – should be protected when QL supports such a flag. Subtypes override this to recursively get specifiers that are not attached directly to this @type in the database but arise through type aliases such as typedef and decltype.
protected
@type
Holds if this type involves a reference.
Holds if this type involves a template parameter.
Holds if this element is affected in any way by a macro. All elements that are totally or partially generated by a macro are included, so this is a super-set of isInMacroExpansion.
isInMacroExpansion
Holds if this type is const.
Holds if this type is constant and only contains constant types. For instance, a char *const is a constant type, but not deeply constant, because while the pointer can’t be modified the character can. The type const char *const* is a deeply constant type though - both the pointer and what it points to are immutable.
char *const
const char *const*).
const char *const
const char * type is volatile.
Holds if this type refers to type t (by default, a type always refers to itself).
t
Holds if this type refers to type t directly.
Gets this type with any typedefs resolved. For example, given typedef C T, this would resolve const T& to const C&. Note that this will only work if the resolved type actually appears on its own elsewhere in the program.
typedef C T
const T&
const C&
Gets this type after any top-level specifiers and typedefs have been stripped.
Gets the type stripped of pointers, references and cv-qualifiers, and resolving typedefs. For example, given typedef const C& T, stripType returns C.
typedef const C& T
stripType
C
Gets a textual representation of this element. | https://help.semmle.com/qldoc/cpp/semmle/code/cpp/Type.qll/type.Type$VoidType.html | CC-MAIN-2020-24 | refinedweb | 635 | 66.44 |
how can I record the time duration, time start and time end of a method once it was executed using c#?
for example, I click a button and it will do something. Once it start, I'll get the start time, then when the execution is done, I'll get the time end and also the duration of time it take to finish.
You can use the Stopwatch, which resides in
System.Diagnostics namespace.
This has the features of a normal stopwatch, with
Start,
Stop,
Reset,
ElapsedMilliseconds and so forth.
This is great for measuring a specific code block or method. You do however state that you want both start and end time in addition to the duration of execution. You could create a custom stopwatch by inheriting the
Stopwatch class and extending it with a couple of
DateTime properties.
public class CustomStopwatch : Stopwatch { public DateTime? StartAt { get; private set; } public DateTime? EndAt { get; private set; } public void Start() { StartAt = DateTime.Now; base.Start(); } public void Stop() { EndAt = DateTime.Now; base.Stop(); } public void Reset() { StartAt = null; EndAt = null; base.Reset(); } public void Restart() { StartAt = DateTime.Now; EndAt = null; base.Restart(); } }
And use it like this:
CustomStopwatch sw = new CustomStopwatch(); sw.Start(); Thread.Sleep(2342); // just to use some time, logic would be in here somewhere. sw.Stop(); Console.WriteLine("Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2}", sw.ElapsedMilliseconds, sw.StartAt.Value, sw.EndAt.Value); | https://codedump.io/share/OeGx6nE0g5Rl/1/time-durationtime-start-and-time-end-of-a-method-in-c | CC-MAIN-2018-13 | refinedweb | 235 | 59.4 |
Super-shortcuts for apps, files, and workspace switcher
Bug Description
The recently landed application shortcuts with Super+{1..9} is a wicked way to focus and launch apps.
I quickly find that I want a way to access the files- and apps place as well, and also the workspace switcher (which will then require keyboard nav for window selection).
Maybe I am just a tiny bit biased because I am the maintainer of u-p-a and u-p-f though - so feel free to wave me off ;-)
Desired solution:
- Super+A should open the Applications Place
- Super+F should open the Files Place
- Super+T should open Deleted Items
- Super on its own should toggle the Dash
- should show all windows for the
Related branches
- Neil J. Patel (community): Approve on 2011-02-22
- Diff: 4242 lines (+1208/-1545)49 files modifiedpo/ar.po (+34/-45)
po/bg.po (+34/-45)
po/cs.po (+34/-45)
po/da.po (+34/-45)
po/de.po (+34/-45)
po/el.po (+34/-45)
po/es.po (+34/-45)
po/fi.po (+34/-45)
po/fr.po (+34/-45)
po/he.po (+34/-45)
po/hi.po (+34/-45)
po/hr.po (+34/-45)
po/hu.po (+34/-45)
po/it.po (+34/-45)
po/ja.po (+34/-45)
po/ko.po (+34/-45)
po/nb.po (+34/-45)
po/nl.po (+34/-45)
po/pl.po (+34/-45)
po/pt.po (+34/-45)
po/pt_BR.po (+34/-45)
po/ro.po (+34/-45)
po/ru.po (+34/-45)
po/sk.po (+34/-45)
po/sl.po (+34/-45)
po/sr.po (+34/-45)
po/sv.po (+34/-45)
po/th.po (+34/-45)
po/tr.po (+34/-45)
po/unity.pot (+37/-51)
po/zh_CN.po (+34/-45)
po/zh_TW.po (+34/-45)
src/DeviceLauncherIcon.cpp (+3/-3)
src/DeviceLauncherIcon.h (+1/-1)
src/Launcher.cpp (+11/-72)
src/LauncherController.cpp (+16/-1)
src/LauncherIcon.cpp (+16/-0)
src/LauncherIcon.h (+5/-0)
src/PlaceEntry.h (+3/-2)
src/PlaceEntryHome.cpp (+6/-0)
src/PlaceEntryHome.h (+1/-0)
src/PlaceEntryRemote.cpp (+18/-0)
src/PlaceEntryRemote.h (+2/-0)
src/PlaceLauncherIcon.cpp (+10/-3)
src/PlaceLauncherIcon.h (+2/-1)
src/SimpleLauncherIcon.cpp (+6/-5)
src/SimpleLauncherIcon.h (+1/-2)
src/TrashLauncherIcon.cpp (+15/-9)
src/TrashLauncherIcon.h (+1/-0)
Yes, I think these named places could well be served with shortcuts as
you describe. +1 for the moment, pending further consideration of how
the namespace might fragment with additional places.
Mark
+1
The only thing that prevents me from using Unity on my laptop on day-to-day basis is the lack of the above shortcuts. With those shortcuts implemented (apart from the "desktop expose" view it would be great to have an additional view of the windows on the current workspace, eg. super+e for 'desktop expose' and super+w for 'current workspace expose'), for me, it is the desktop of the future.
Thanks
OK, this warrants consideration for 11.04. How are such system-level
shortcuts internationalised? The words for "desktop", "workspace" and
"expose" are likely different across languages, do the shortcuts change
by language typically, or are they global?
Mark
in compiz, they are global, but customizable: super+e → expose; super+w → all windows on the current desktop; super+a → all windows. gnome-shell and unity put the expose mode together with the "all windows" view, wich is why I find both better than compiz in terms of window management; what makes unity better than gnome-shell, in my opinion, is the side bar which is just perfect in terms of usability and the alt+tab window switcher, which only shows the windows on the given workspace (in gnome-shel this is a major annoyance). I would suggest one more shortcut: super+space for the "main menu" (when you click on the ubuntu icon) & make the results browsable with the arrow keys. that would make unity a fast, responsive, out-of-your-way shell - just gorgeous.
Thanks for listening,
krzysztof
status confirmed
The design guidance on this is that:
* Super+A should open the Applications Place
* Super+F should open the Files Place
* Super+D should open Deleted Items
* Super on its own should toggle the Dash
* should show all windows for the
I'm happy to update the relevant spec with this information if one of
the Unity develoeprs points me in the right direction :-)
I'm considering the shortcuts for window reveals. We have an app reveal
(all windows in the app), and a workspace reveal (all windows in the
workspace) and then of course the maxi reveal of all windows across all
workspaces. I think a single shortcut might be enough (repeated use
zooms out). Perhaps Super+W ?
Mark
ctrl+alt+d was changed to Super+D in Maverick to show desktopf so thats a conflict.
What about super+t (Trash)??
On 06/10/10 15:08, christopher pijarski wrote:
>?
What would the shortcut be for Gnome Do?
On 06/10/10 08:25, Omer Akram wrote:
> ctrl+alt+d was changed to Super+D in Maverick to show desktopf so thats
> a conflict.
Ah, good point!
I considered Super+Del but it feels like playing with razor blades even
doing it myself :-)
Super+T would work too.
Mark
as a default, gnome-do uses super+space, so in unity you have to change to ctrl+space for example, but there is no way to get it to work, unless you have window open and focused.
>
> I considered Super+Del but it feels like playing with razor blades even
> doing it myself :-)
>
> Super+T would work too.
>
Hmm, "T" would conflict with locales which dont name it as "Trash".
example UK locale names the "Trash" as "Rubbish Bin". so using "Super+T" would be confusing there.
So, would this be configurable?.
Or we should encourage it to rarely used :)
On 06/10/10 17:33, Erlan Sergaziev wrote:
>.
For our user base, the terminal is not a priority. The fact that you
know about Ctrl-Alt-T suggests it's appropriate :-)
@Vish, I asked about internationalis
shortcuts tend to be what they are, in all languages. We can't hope to
find a single letter that maps to a concept like "Trash", there's even a
difference between the US and UK there, with Wastebasket, Trash and
Deleted Items all in common use.
Mark
Mark, Oh! i just realized your earlier suggestion:
* Super+D should open Deleted Items
might be better.
The Super+D shortcut was with metacity, and since we dont really have a Desktop in Unity. It dont think its an issue.
Also, In Gnome3 Nautilus will *not* be drawing the desktop either. So the show desktop conflict is a non-issue
/me dint cause the confusion though ;p
We need a consolidated spec for the shortcuts.
While refining this, keep in mind that a11y users are heavily relying on shortcuts and so might point out more potential conflicts and "habits" to take into account.
Ok, all the plumbings are nearly done for that, however, there is still some key shortcut to discuss.
In lucid, the compiz keys have been reviewed in length by the design team and we have conflicting ones with the new ones.
Like, Super + A -> expose all windows from all workspaces
Super + W -> expose the focused window and all window from the same application on the same workspace
Super + E -> workspace expose mode (what should become Super + W seeing above)
Note that contrary to what have been told, Super + D is doing nothing.
So, there are some conflicts with the new proposal, what should be done? Changing the experience and people upgrading from lucid or maverick will trigger false positives (habits…)? What to set to the other keybindings (for the GNOME classic session for instance, like the workspace expose mode).
Also, another question: it's quite easy to make those key localizable (like "T" or "D" for the dash make no sense in French as it's "Corbeille"). I think this is a bad idea though as we should just have one shortcut that people speaking different language can share, Just mentioning it.
I'll merge the work as soon as something has been decided :)
I should maybe add that there is no way to change the default for existing users. So, if they had Super + A for something, on upgrade, this is not an issue for the unity session as it's a new profile and Super + A will give the new shortcut we decided, but on the classic session, as it's the same old profile (gold rule, keep user configuration), Super + A will still be assigned to expose all windows from all workspaces.
Having two shortcuts doing different things on different sessions can be considered as bad.
ok, putting a design follow up on my two last comments on bug #723273. I'm keeping this one has the technical one. adding the place task as we need to set the key there.
the natty alpha3 versions still has those conflicts which means you can open the workspace expose or the application place with the keyboard since it triggers other effects at the same time, quite confusing
Shortcut for workspace switcher was implemented.
Missing shortcut for places is tracked by #732637
When you press the <super> key, the shortcuts for the applications, files places and trash are visible but not for the workspace switcher.
Well spotted Adam, this is fixed by the following pending merge request: https:/
I just downloaded and installed the latest build - bzr66 and yes it is fixed.
Bug re-opened as "Super+A" and "Super+F" seem to be broken in Oneiric
I also think it could be an interesting addition:
Super+f -> files place
Super+a -> apps place
Super+w -> workspace switcher
(btw, all of them are at the left side of the keyboard (spanish version, at least)... then easy to use shortcuts!)
The idea of having a "contacts dash" (https:/
/lists. launchpad. net/ayatana/ msg03509. html) could also be improved with the shortcut Super+c | https://bugs.launchpad.net/unity-2d/+bug/617356 | CC-MAIN-2019-39 | refinedweb | 1,683 | 75.3 |
#include "mcu_periph/pipe.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "rt_priority.h"
Go to the source code of this file.
Definition at line 42 of file pipe_arch.c.
Referenced by pipe_thread().
Definition at line 48 of file pipe_arch.c.
References pipe_thread().
Initialize the PIPE peripheral.
Allocate UdpSocket struct and create and bind the PIPE socket.
Definition at line 76 of file pipe_arch.c.
References pipe_periph::fd_read, and pipe_periph::fd_write.
Get number of bytes available in receive buffer.
Definition at line 104 of file pipe_arch.c.
References PIPE_RX_BUFFER_SIZE, pipe_periph::rx_extract_idx, and pipe_periph::rx_insert_idx.
Get the last character from the receive buffer.
Definition at line 120 of file pipe_arch.c.
References PIPE_RX_BUFFER_SIZE, pipe_periph::rx_buf, and pipe_periph::rx_extract_idx.
Read bytes from PIPE.
Definition at line 132 of file pipe_arch.c.
References pipe_periph::fd_read, pipe_char_available(), PIPE_RX_BUFFER_SIZE, pipe_periph::rx_buf, and pipe_periph::rx_insert_idx.
Send a message.
Definition at line 160 of file pipe_arch.c.
References pipe_periph::fd_write, pipe_periph::tx_buf, and pipe_periph::tx_insert_idx.
Send a packet from another buffer.
Definition at line 182 of file pipe_arch.c.
References pipe_periph::fd_write.
check for new pipe packets to receive.
Definition at line 193 of file pipe_arch.c.
References fd, get_rt_prio(), pipe_receive(), and PIPE_THREAD_PRIO.
Referenced by pipe_arch_init().
Definition at line 46 of file pipe_arch.c. | http://docs.paparazziuav.org/latest/sim_2mcu__periph_2pipe__arch_8c.html | CC-MAIN-2020-24 | refinedweb | 230 | 57.74 |
I liked this concept because it seems kind of sneaky. By that I mean, in the past I was only able to call a method from a base class via inheritance or creating an instance of the class itself. However, now by implementing a generic type parameter we can achieve the same thing.
First we create a standard interface, just like we have always done. It identifies a method called WriteCSharp and a property named BaseMessage. Both of which must be implemented in a class which implements this interface. They must have an access modifier of public too. Next we implement the generic type interface IProgramExtended which takes T as a parameter. The IProgramExtended interfaces implements the IProgram interface,
//Standard Interface
public interface IProgram
{
void WriteCSharp();
string BaseMessage { get; set; }
}
//Generic Interface which implements the standard interface
public interface IProgramExtended<T> where T : IProgram
{
void Run(T t);
string ExtendedMessage { get; set; }
}
We write a class that implements the IProgram interface. Note that is does implement the required method and property as public.
//Class which implements standard interface
public class MyProgram : IProgram
{
public void WriteCSharp()
{
Console.WriteLine(BaseMessage);
Console.ReadLine();
}
public string BaseMessage { get; set; }
}
We implement the above class with the below lines of code.
MyProgram mp = new MyProgram();
mp.BaseMessage = "Message from MyProgram";
mp.WriteCSharp();
Now the fun part. We create another class which implements the IProgramExtended interface and passes the MyProgram class we created above. We implement the required method and property of the Extended interface.
//Class which implements generic interface with
//class that implements standard interface
public class MyExtendedProgram : IProgramExtended<MyProgram>
{
public void Run(MyProgram t)
{
Console.WriteLine();
Console.WriteLine(ExtendedMessage);
Console.WriteLine();
t.BaseMessage =
"Message from MyProgram changed by MyExtendedProgram";
t.WriteCSharp();
}
public string ExtendedMessage { get; set; }
}
When we implement the above class, like the below we receive these results. We call the method in our extended class, the one which implemented the generic typed interfaces to and call its Run method. Within the run method we print out our message first. The magic here is that we can access the property and the method of a class we did not directly inherited from or instantiate. Like I said, I find that cool and sneaky…
MyExtendedProgram mp2 = new MyExtendedProgram();
mp2.ExtendedMessage = "Message from MyExtendedProgram";
mp2.Run(mp);
I stumbled on this while I was trying to find a way to return a different type from a method in a derived class. Generics are a very cool invention. | https://www.thebestcsharpprogrammerintheworld.com/2020/06/05/generic-type-parameters-parameter-interface-c/ | CC-MAIN-2020-29 | refinedweb | 412 | 56.66 |
Re: [code] [for discussion] map-trie
FWIW my intent with libTrie was always to head for an LPC Trie implementation as the only implementation. This should be faster still than the current naive trie, and faster than the std::map compression technique you've implemented. [ IIRC the LPC paper was Implementing a Dynamic Compressed Trie from Stefan Nilsson, Matti Tikkanen ]- I have the pdf floating around here somewhere, but a quick google just hit paywalls these days :(. -Rob On 12 June 2014 10:43, Kinkie gkin...@gmail.com wrote: Hi, I've done some benchmarking, here are the results so far: The proposal I'm suggesting for dstdomain acl is at lp:~kinkie/squid/flexitrie . It uses the level-compact trie approach I've described in this thread (NOT a Patricia trie). As a comparison, lp:~kinkie/squid/domaindata-benchmark implements the same benchmark using the current splay-based implementation. I've implemented a quick-n-dirty benchmarking tool (src/acl/testDomainDataPerf); it takes as input an acl definition - one dstdomain per line, as if it was included in squid.conf, and a hostname list file (one destination hostname per line). I've run both variants of the code against the same dataset: a 4k entries domain list, containing both hostnames and domain names, and a 18M entries list of destination hostnames, both matching and not matching entries in the domain list (about 7.5M hits, 10.5M misses). Tested 10 times on a Core 2 PC with plenty of RAM - source datasets are in the fs cache. level-compact-trie: the mean time is 11 sec; all runs take between 10.782 and 11.354 secs; 18 Mb of core used full-trie: mean is 7.5 secs +- 0.2secs; 85 Mb of core. splay-based: mean time is 16.3sec; all runs take between 16.193 and 16.427 secs; 14 Mb of core I expect compact-trie to scale better as the number of entries in the list grows and with the number of clients and requests per second; furthermore using it removes 50-100 LOC, and makes code more readable. IMO it is the best compromise in terms of performance, resources useage and expected scalability; before pursuing this further however I'd like to have some feedback. Thanks On Wed, Jun 4, 2014 at 4:11 PM, Alex Rousskov rouss...@measurement-factory.com wrote: On 06/04/2014 02:06 AM, Kinkie wrote: there are use cases for using a Trie (e.g. prefix matching for dstdomain ACL); these may be served by other data strcutures, but none we could come up with on the spot. std::map and StringIdentifier are the ones we came up with on the spot. Both may require some adjustments to address the use case you are after. Alex. A standard trie uses quite a lot of RAM for those use cases. There are quite a lot of areas where we can improve so this one is not urgent. Still I'd like to explore it as it's synchronous code (thus easier for me to follow) and it's a nice area to tinker with. On Tue, Jun 3, 2014 at 10:12 PM, Alex Rousskov rouss...@measurement-factory.com wrote: On 06/03/2014 08:40 AM, Kinkie wrote: Hi all, as an experiment and to encourage some discussion I prepared an alternate implementation of TrieNode which uses a std::map instead of an array to store a node's children. The expected result is a worst case performance degradation on insert and delete from O(N) to O(N log R) where N is the length of the c-string being looked up, and R is the size of the alphabet (as R = 256, we're talking about 8x worse). The expected benefit is a noticeable reduction in terms of memory use, especially for sparse key-spaces; it'd be useful e.g. in some lookup cases. Comments? To evaluate these optimizations, we need to know the targeted use cases. Amos mentioned ESI as the primary Trie user. I am not familiar with ESI specifics (and would be surprised to learn you want to optimize ESI!), but would recommend investigating a different approach if your goal is to optimize search/identification of strings from a known-in-advance set. Cheers, Alex. -- Francesco -- Robert Collins rbtcoll...@hp.com Distinguished Technologist HP Converged Cloud
Re: BZR local server?repo?
Put bzr update in cron? Or if you want an exact copy of trunk, use 'bzr branch' then 'bzr pull' to keep it in sync. On 23 January 2014 20:53, Eliezer Croitoru elie...@ngtech.co.il wrote: Since I do have a local server I want to have an up-to-date bzr replica. I can just use checkout or whatever but I want it to be be updated etc. I am no bzr expert so any help about the subject is more then welcome. Thanks, Eliezer
Re: [RFC] Tokenizer API
On 10 December 2013 19:13, Amos Jeffries squ...@treenet.co.nz wrote: The problem with comparing input strings to a SBuf of characters is that parsing a input of length N againt charset of size M takes O(N*M) time. Huh? There are linear time parsers with PEGs. Or maybe I don't understand one of your preconditions to come up with an N*M complexity here. -Rob -- Robert Collins rbtcoll...@hp.com Distinguished Technologist HP Converged Cloud
Re: Dmitry Kurochkin
On 24 July 2013 05:18, Alex Rousskov rouss...@measurement-factory.com wrote: It is with great sadness I inform you that Dmitry Kurochkin died in a skydiving accident a few days ago. Dmitry was an avid skydiver, with more than 360 jumps and some regional records behind him. He loved that sport. Dmitry's recent contributions to Squid include code related to HTTP/1.1 compliance, SMP scalability, SMP Rock Store, Large Rock, Collapsed Forwarding, and FTP gateway features. He also worked on automating Squid compliance testing with Co-Advisor and Squid performance testing with Web Polygraph. Dmitry was a wonderful person, a talented developer, and a key member of the Factory team. He was a pleasure to work with. We miss him badly. Thats extremely sad news. My condolences and sympathies to his colleagues, family, and friends. -Rob
rackspace offering free compute for open source projects - this might be useful for jenkins. -Rob
Re: Should we remove ESI?
On 11 June 2013 20:23, Kinkie gkin...@gmail.com wrote: On Mon, Jun 10, 2013 at 7:22 PM, Alex Rousskov rouss...@measurement-factory.com wrote: From what I understand (Robert, can you come to the rescue?) libTrie is a very optimized key- and prefix- lookup engine, trading memory useage for speed. It would be great to use in the Http parser to look up header keys, for instance. It is a generic trie implementation, it is very good at some forms of lookup, and it's used in ESI yes; I had planned to try it in the HTTP parser, but ETIME. I do not know much about ESI, but IMHO, if somebody has cycles to work on this, it would be best to spend them removing ESI (together with libtTrie) from Squid sources while converting ESI into an eCAP adapter. This will be a big step forward towards making client side code sane (but removing ESI itself does not require making complex changes to the client side code itself). Robert is the expert on this. My question right now is, is anyone using ESI? ESI requires a specifically-crafted mix of infrastructure and application; there are nowadays simpler ways to obtain similar results. For this reason I would launch an inquiry to our users and to the original ESI sponsors to understand whether to simply stop supporting ESI. It is ~10kLOC that noone really looks after, and they imply dependencies (e.g. on the xml libraries). We get occasional queries about it on IRC and the lists; I don't know if it's in use in production or not. I think it would be sad to remove working code, but if noone is using it, noone is using it. I think refactoring it to use eCap rather than clientStreams would be fine, but I can't volunteer to do that myself. -Rob -- Robert Collins rbtcoll...@hp.com Distinguished Technologist HP Cloud Services
Re: Should we integrate libTrie into our build system?
On 10 June 2013 08:40, Kinkie gkin...@gmail.com wrote: Hi all, while attempting to increase portability to recent clang releases, I noticed that libTrie hasn't benefited from the portability work that was done in the past few years. I can see three ways to move forward: 1- replicate these changes into libTrie 2- change libTrie to piggyback squid's configuration variables 3- fully integrate libTrie into squid's build system. Unless Robert knows otherwise, squid is the only user of this library.. I'm not aware fo it being shipped/used separately. Probably want to replace it by now, must be a tuned equivalent somewhere :) -Rob Comments? -- /kinkie -- Robert Collins rbtcoll...@hp.com Distinguished Technologist HP Cloud Services
Re: Squid SMP on MacOS
On 25 February 2013 18:24, Alex Rousskov rouss...@measurement-factory.com wrote: On 02/24/2013 10:02 PM, Amos Jeffries wrote: I'm trying to get the MacOS builds of Squid going again but having some problems with shm_open() in the Rock storage unit-tests. 1) MacOS defines the max name length we can pass to shm_open() at 30 bytes. /squid-testRock__testRockSearch being 35 or so bytes. Cutting the definition in testRock.cc down so it becomes /squid-testRock_Search resolves that, but then we hit (2). That TESTDIR name is wrong because it is used for more than just search testing. I bet the Rock name mimicked the UFS test name, but the UFS name is wrong too, for the same reason. We should use cppUnitTestRock and cppUnitTestUfs or something similarly unique and short, I guess. We should use a random name; squidtest-10-bytes-of-entropy should do it. Random because we don't want tests running in parallel to step on each other on jenkins slaves. 2) With the short string above and the current settings sent to shm_open() in src/ipc/mem/Segment.cc line 73 MacOS shm_open() starts responding with EINVAL. theFD = shm_open(theName.termedBuf(), O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR); Sounds like some of the five shm_open() flags we are using successfully elsewhere do not work on MacOS. I do not know which flag(s) do not work, and we have no MacOS boxes in the lab, so we cannot experiment or read documentation. I assume shared segment opening fails with similar symptoms when used outside of unit tests (e.g., with a shared memory cache)? If so, please feel free to disable shared memory support on MacOS (do not define HAVE_SHM?) until somebody who needs it can find the right combination of flags. +1 -Rob -- Robert Collins rbtcoll...@hp.com Distinguished Technologist HP Cloud Services
Re: some notes and help to think is needed + Test results of testing basics in store_url_rewrite.
On Thu, Sep 27, 2012 at 4:09 PM, Eliezer Croitoru elie...@ngtech.co.il wrote: Well I was reading here and there the store code and other things then started testing some theories about how store_url can be and should be implemented. If you do remember or not I refactored the source in couple places to use originalUrl and original_url to check all the places where original url is used and then decide where the store_url should be placed if needed. (memobject-original_url and has memobject-store_url) the main place of all I have seen that should be used with the store_url is the which gets requests from couple places and mainly the setPublic for store entry (Does bazaar has search option in it ?) bzr grep (if you install the bzr-grep plugin) will search all your source code. bzr search (if you install the bzr-search plugin) finds references anywhere in the project history. -Rob
Re: [RFC] or ACLs
On Tue, Sep 25, 2012 at 10:06 AM, Alex Rousskov rouss...@measurement-factory.com wrote: Hello, I would like to add support for explicit OR ACLs: On the up side i think that this would indeed give us much more flexability, and its a decent stopgap between this and a more understandable ACL language. On the downside, I think it will make things harder to explain, the current system being itself rather arcane. I'd like to see, long term, some more complete language - e.g. something with macros so you can define and reuse complex constructs without having to repeat them, which I think your OR support will only partially mitigate against. -Rob
Re: [RFC] One helper to rewrite them all
On Wed, Sep 12, 2012 at 11:05 AM, Amos Jeffries squ...@treenet.co.nz wrote: IMO the backward compatibility and easy upgrade from 2.7 overrides doing this now. It is possible to do a migration to this design later easily enough not to worry. FWIW I wouldn't worry about 2.7 compat. As of precise, squid2 isn't in Ubuntu at all. Its unlikely that folk will need to write one helper to support both 3.x and 2.7 installs. -Rob
Re: bzr unmerge
On Sat, Aug 18, 2012 at 6:58 AM, Henrik Nordström hen...@henriknordstrom.net wrote: fre 2012-08-17 klockan 19:59 +0200 skrev Kinkie: Have you considered bzr uncommit? uncommit do not cut it. uncommit simply moves the branch head to a given revision discarding any later revisions, same as git reset --hard for those familiar with git. It's ok to use on a private branch to clean up mistakes, but MUST NOT, repeat MUST NOT be used after the revisions have been pushed to a shared repository. what I want is a unmerge operation that is a commit in itself much like revert, preserving full history, but which requires attention to resolve when propagated to other branches, enabling other branches to keep the changes or revert them per user choice. bzr merge N..N-1 . will back out revision N from this branch in the way you describe.
Re: Generic helper I/O format
On Thu, Jul 5, 2012 at 4:00 PM, Amos Jeffries squ...@treenet.co.nz wrote: Why do we need backwards compat in the new protocol? As an alternative, consider setting a protocol= option on the helpers, making the default our latest-and-greatest,a nd folk running third-party helpers can set protocl=v1 or whatever to get backwards compat. This lets us also warn when we start deprecating the old protocol, that its going away. -Rob
Re: Geek fun in Squid's source code
On Fri, Jun 29, 2012 at 12:53 PM, Amos Jeffries squ...@treenet.co.nz wrote: On 29/06/2012 12:01 a.m., Kinkie wrote: from support_netbios.cc: if (p == np) { (stumbled into this while sweeping the sources changing postincrement to preincrement operators). -- /kinkie Why do you bring this up?
Re: squid md5 and fips mode
On Tue, Jun 19, 2012 at 9:10 AM, Paul Wouters pwout...@redhat.com wrote: Hi, I have been looking at FIPS issues with squid in both RHEL5 and RHEL6. In fips mode, MD5 is not allowed for securing web traffic (with some TLS exceptions) nor user authentication. It is allowed for other things, such as hashes for disk objects. The problem in older versions of squid was that the cache object code used md5, and since openssl did not allow it, it would die. This was fixed with a patch by using the squid buildin md5 functions for the cache object hashes. See Now for recent versions of squid, I have the reverse problem. The openssl md5 code is never used, so I had to patch it back to using openssl with the exception for the cache object id where I used private_MD5_Init() It basically undoes most of these commits: - Changing 'xMD5' function name to 'SquidMD5' - Changing 'MD5_CTX' typedef to 'SquidMD5_CTX' - Changing 'MD5_DIGEST_CHARS' define to 'SQUID_MD5_DIGEST_LENGTH' - Changing 'MD5_DIGEST_LENGTH' define to 'SQUID_MD5_DIGEST_LENGTH' - Removing messy #ifdef logic in include/md5.h that tries to use the system libraries if available. We'll always use the Squid MD5 routines. My request is to basically undo this change, and to use openssl again where possible, so that fips enforcement does not fail with the custom crypto code that goes undetected. A rought patch (that does not take into account systems with no crypt()) is attached at: A few quick thoughts: - We'd love patches that make squid explicitly aware of e.g. FIPS mode, so that we can enforce it ourselves. We've no idea today when we change something whether its going to impact on such external needs, and frankly, tracking it is going to be tedious and error prone, leading to the sort of flip-flop situation you have. - as we don't have an OpenSSL exception in our copyright (and its -hard- to add one today), you can't legally ship a squid binary linked against openSSL anyway.. Note that our COPYING file says 'version 2' not 'version 2 or later', though at least some source files say 'version 2 or later' - we'll need to figure out what to do about *that* in due course. So, basically every build of squid that uses openSSL has to have been built by the end user locally, anyway. Yes, this kindof sucks. That said, if the FIPS standard doesn't like MD5, there is no need for use to use it at all, we could use sha1 as a build time option for cache keys (or take the first N bits of sha1), if that helps: that would allow us to be entirely MD5 free when desired. -Rob
Re: [PATCH] fix up external acl type dumping
On Fri, Jun 15, 2012 at 4:23 AM, Alex Rousskov rouss...@measurement-factory.com wrote: On 06/14/2012 03:06 AM, Robert Collins wrote: +#define DUMP_EXT_ACL_TYPE_FMT(a, fmt, ...) \ + case _external_acl_format::EXT_ACL_##a: \ + storeAppendPrintf(sentry, fmt, ##__VA_ARGS__); \ + break I do not see Squid using __VA_ARGS__ currently. Are you sure it is portable, especially in the ## context? If you have not tested this outside Linux, are you OK with us pulling out this patch if it breaks the build? Yes, that would be fine. I'm mainly fixing this because I noticed it in passing: it has no concrete effect on me. If you are not sure, you can rework the macro to always use a single argument instead. The calls without a parameter in the format can add one and use an empty string (or you can have two macros). I do not like how this macro butchers the format code names. I could borderline agree with stripping the namespace, but stripping EXT_ACL_ prefix seems excessive. The prefix itself looks excessive (because the namespace already has external_acl in it!) but that is a different issue. I would prefer that the macro takes a real code name constant, without mutilating the name. There is an existing similar macro that does the same kind of mutilation, but there it is kind of justified because the name suffix is actually used. The true solution to this mess is to fix the names themselves, I guess. I think we should make external acls a class, no base class, and ditch the whole big case statement etc, and we can lose the macro at the same time. Thats a rather bigger change, and I wanted to fix the defect in the first instance. -Rob
Re: [PATCH] fix up external acl type dumping
On Sat, Jun 16, 2012 at 7:33 AM, Alex Rousskov rouss...@measurement-factory.com wrote: IMHO, ##__VA_ARGS__ is not worth the trouble in this particular case. However, even if you disagree, please use at least one argument (empty string with a corresponding %s if needed to prevent compiler warnings?). The ## is meant to compensate for that, according to the reading I did. I'm happy to back it out if it causes jenkins failures, but would like to at least try it as-is. -Rob
[PATCH] fix up external acl type dumping
This patch does four things: - adds a helper macro for format strings with external acl type config dumping. - uses that to add a missing type dumper for %%, which currently causes squid to FATAL if mgr:config is invoked. - refactors the SSL type dumping to use the macro as well, saving some redundant code - fixes a typo -case _external_acl_format::EXT_ACL_CA_CERT: -storeAppendPrintf(sentry, %%USER_CERT_%s, format-header); Seeking review, will land in a couple days if there is none :) -Rob === modified file 'src/external_acl.cc' --- src/external_acl.cc 2012-05-08 01:21:10 + +++ src/external_acl.cc 2012-06-14 08:58:33 + @@ -568,6 +568,10 @@ case _external_acl_format::EXT_ACL_##a: \ storeAppendPrintf(sentry, %%%s, #a); \ break +#define DUMP_EXT_ACL_TYPE_FMT(a, fmt, ...) \ +case _external_acl_format::EXT_ACL_##a: \ +storeAppendPrintf(sentry, fmt, ##__VA_ARGS__); \ +break #if USE_AUTH DUMP_EXT_ACL_TYPE(LOGIN); #endif @@ -592,28 +596,17 @@ DUMP_EXT_ACL_TYPE(PATH); DUMP_EXT_ACL_TYPE(METHOD); #if USE_SSL - -case _external_acl_format::EXT_ACL_USER_CERT_RAW: -storeAppendPrintf(sentry, %%USER_CERT); -break; - -case _external_acl_format::EXT_ACL_USER_CERTCHAIN_RAW: -storeAppendPrintf(sentry, %%USER_CERTCHAIN); -break; - -case _external_acl_format::EXT_ACL_USER_CERT: -storeAppendPrintf(sentry, %%USER_CERT_%s, format-header); -break; - -case _external_acl_format::EXT_ACL_CA_CERT: -storeAppendPrintf(sentry, %%USER_CERT_%s, format-header); -break; +DUMP_EXT_ACL_TYPE_FMT(USER_CERT_RAW, %%USER_CERT_RAW); +DUMP_EXT_ACL_TYPE_FMT(USER_CERTCHAIN_RAW, %%USER_CERTCHAIN_RAW); +DUMP_EXT_ACL_TYPE_FMT(USER_CERT, %%USER_CERT_%s, format-header); +DUMP_EXT_ACL_TYPE_FMT(CA_CERT, %%CA_CERT_%s, format-header); #endif #if USE_AUTH DUMP_EXT_ACL_TYPE(EXT_USER); #endif DUMP_EXT_ACL_TYPE(EXT_LOG); DUMP_EXT_ACL_TYPE(TAG); +DUMP_EXT_ACL_TYPE_FMT(PERCENT, ); default: fatal(unknown external_acl format error); break;
Re: Multiple outgoing addresses for squid?
On Fri, Mar 30, 2012 at 4:18 AM, Chris Ross cr...@markmonitor.com wrote: So, I suspect someone has looked at this before, but I have an edge device that is multi-homed. I have multiple WAN connections available, and what I'd really like to do is have a squid that's smart enough to learn which web sites are better out of which WAN connection. But, shy of something that advanced, is it possible to have squid know to bind to N outside addresses, and then either round-robin them, or try one always, and then try the other if there is a failure on the first? I'd be happy to help implement such a thing if it doesn't already exist, but I assume this is the sort of problem that has already been faced and hopefully solved. 'tcp_outgoing_address' in the config ;) -Rob
Re: Multiple outgoing addresses for squid?
2012/3/30 Henrik Nordström hen...@henriknordstrom.net: Can tcp_outgoing_address take multiple addresses now? Does it just round-robin through them? It can only select one per request at the moment. Thats probably something we should fix. For now though an external ACL could deliver round robin answers, one per request - and it could look a tthe log file to learn about size of objects/ estimate bandwidth etc. -Rob
Re: Which projects are most important?
Performance is a hot topic at the moment; I would love to see more time going into that through any of the performance related items you listed (or other ones you may come up with). -Rob
Re: Question regarding ESI Implementation
On Fri, Sep 30, 2011 at 7:38 PM, Jan Algermissen jan.algermis...@nordsc.com wrote: Theres no specific meta documentation that I recall. It should be pretty straight forward (but remember that squid is a single threaded non-blocking program - so its got to work with that style of programming). Ah, I did not yet know Squid had an async programming model. Even better. The current ESI Implementation is non-blocking, too? Yup, for sure. -Rob
Re: Question regarding ESI Implementation
On Thu, Sep 29, 2011 at 10:37 AM, Jan Algermissen jan.algermis...@nordsc.com wrote: Hi, I am thinking about trying out some ideas building upon ESI 1.0 and would like to extend the ESI implementation of Squid. For personal use right now, but if turns out to be valuable I am happy to share it. I downloaded the source yesterday and took a short look at the ESI parts. Is there any form of documentation about the rationale behind the code snippets and the supported parts of ESI 1.0? What is the best way to get up to speed? Theres no specific meta documentation that I recall. It should be pretty straight forward (but remember that squid is a single threaded non-blocking program - so its got to work with that style of programming). Can you remember when the development roughly took place to help me digging through the developer archives? early 2000's, uhm, I think 2003. -Rob
Re: hit a serious blocker on windows
DuplicateHandle is how its done. -Rob
Re: [RFC] Have-Digest and duplicate transfer suppression
On Thu, Aug 11, 2011 at 10:59 AM, Alex Rousskov rouss...@measurement-factory.com wrote: On 08/10/2011 04:18 PM, Robert Collins wrote: How is case B different to If-None-Match ? The origin server may not supply enough information for If-None-Match request to be possible OR it may lie when responding to If-None-Match requests. The parent squid could handle the case when the origin lies though, couldn't it ? So: client - child - parent - origin if client asks for url X, child has an old copy, child could add If-None-Match, parent could detect that origin sends the same bytes (presumably by spooling the entire response) and then satisfy the If-None-Match, and child can give an unconditional reply to client, which hadn't had the original bytes. That doesn't help with the not-enough-information case, which is I presume the lack of a strong validator. So, perhaps we could consider this 'how can intermediaries add strong validators' - if we do that, and then (in squid - no http standards violation) - honour If-None-Match on those additional validators, it seems like we'll get the functionality you want, it a slightly more generic (and thus reusable) way ? -Rob
Re: [RFC] Have-Digest and duplicate transfer suppression
(But for clarity - I'm fine with what you proposed, I just wanted to consider whether the standards would let us do it more directly, which they -nearly- do AFAICT). -Rob
Re: [RFC] Have-Digest and duplicate transfer suppression
How is case B different to If-None-Match ? -Rob
Re: FYI: http timeout headers
On Fri, Mar 11, 2011 at 6:22 AM, Mark Nottingham m...@yahoo-inc.com wrote: In a nutshell, this draft introduces two new headers: Request-Timeout, which is an end-to-end declaration of how quickly the client wants the response, and Connection-Timeout, which is a hop-by-hop declaration of how long an idle conn can stay open. I'm going to give feedback to Martin about this (I can see a few places where there may be issues, e.g., it doesn't differentiate between a read timeout on an open request and an idle timeout), but I wanted to get a sense of what Squid developers thought; in particular - 1) is this interesting enough that you'd implement if it came out? Not personally, because the sites I'm involved with set timeouts on the backend as policy: dropping reads early won't save backend computing overhead (because request threads aren't cleanly interruptible), and permitting higher timeouts would need guards to prevent excessive resource consumption being permitted inappropriately. 2) if someone submitted a patch for this, would you include it? If it was clean, sure. But again there will be an interaction with site policy. e.g. can a client ask for a higher timeout than the squid admin has configured, or can they solely lower it to give themselves a snappier responsiveness. (and if the latter, why not just drop the connection if they don't get an answer soon enough). 3) do you see any critical issues, esp. regarding performance impact? I would worry a little about backend interactions: unless this header is honoured all the way through it would be easy for multiple backend workers to be calculating expensive resources for the same client repeatedly trying something with an inappropriately low timeout. I guess this just seems a bit odd overall : servers generally have a very good idea about the urgency of things it can serve based on what they are delivering. -Rob
Re: FYI: http timeout headers
On Fri, Mar 11, 2011 at 11:16 AM, Mark Nottingham m...@yahoo-inc.com wrote: Right. I think the authors hope that intermediaries (proxies and gateways) will adapt their policies (within configured limits) based upon what they see in incoming connection-timeout headers, and rewrite the outgoing connection-timeout headers appropriately. I'm not sure whether that will happen, hence my question. I'm even less sure about the use cases for request-timeout, for the reasons you mention. I suspect that this is overengineering : scalable proxies really shouldn't need special handling for very long requests, and proxies that need special handling will still want timeouts to guard against e.g. roaming clients leaving stale connections. Simply recommending that intermediaries depend on TCP to time out connections might be sufficient, simpler, and allow room for clean layering to deal with roaming clients and the like without making requests larger. -Rob
Re: Early pre-HEAD patch testing
On Tue, Feb 8, 2011 at 10:52 AM, Alex Rousskov rouss...@measurement-factory.com wrote: The problem with branches is that you have to commit changes (and, later, fixes) _before_ you test. Sometimes, that is not a good idea because you may want to simply _reject_ the patch if it fails the test instead of committing/fixing it. I suspect it would be OK to abuse lp a little and create a garbage branch not associated with any specific long-term development but used when I need to test a patch instead. You can certainly do that, and LP won't mind at all. Note though that a parameterised build in hudson can trivially build *any* branch off of LP, so you can equally push your experiment to ...$myexistingfeature-try-$thing-out. -Rob
Re: Sharing DNS cache among Squid workers
Have you considered just having a caching-only local DNS server colocated on the same machine? -Rob
Re: Sharing DNS cache among Squid workers
On Fri, Jan 14, 2011 at 11:13 AM, Alex Rousskov rouss...@measurement-factory.com wrote: On 01/13/2011 02:18 PM, Robert Collins wrote: Have you considered just having a caching-only local DNS server colocated on the same machine? I am sure that would be an appropriate solution in some environments. On the other hand, sometimes the box has no capacity for another server. Sometimes the traffic from 8-16 Squids can be too much for a single DNS server to handle. And sometimes administration/policy issues would prevent using external caching DNS servers on the Squid box. This surprises me - surely the CPU load for a dedicated caching DNS server is equivalent to the CPU load for squid maintaining a DNS cache itself; and DNS servers are also multithreaded? Anyhow, I've no particular objection to it being in the code base, but it does seem like something we'd get better results by not doing (or having a defined IPC mechanism to a single (possibly multi-core) cache process which isn't a 'squid'. [Even if it is compiled in the squid tree]. -Rob
Re: Fwd: OpenSolaris build node for Squid to be updated
Their jobs report in subunit however, which we can thunk into hudson using subunit2junitxml, so I think needing a duplicate build farm is much more than we'd need. We would need some glue, but thats about all. _Rob
Re: Feature branch launched: deheader
On Mon, Dec 6, 2010 at 3:28 AM, Kinkie gkin...@gmail.com wrote: Hi all, Eric Raymond recently released a tool named deheader () which goes through c/c++ project looking for unneeded includes. It does so by trying to compile each source file after removing one #include statement at a time, and seeing if it builds. Thats a fairly flawed approach. Two reasons: - some headers when present affect correctness, not compilation. - on some platforms headers are mandatory, on others optional. So, if you do this, be sure to take the minimal approach after building on *all* platforms, and then still be conservative. -Rob
Re: [PATCH] [RFC] custom error pages
Also, symlinks fail on windows :(. -Rob
Re: NULL vs 0
On Wed, Sep 22, 2010 at 4:58 AM, Alex Rousskov rouss...@measurement-factory.com wrote: Squid will most likely not work if NULL is not false. 0xCDCDCDCD is not false. Consider: some_pointer = some_function_that_may_return_NULL(); if (!some_pointer) ... When compilers do that, they also translate the if expression appropriately. But they are also meant to handle NULL vs 0 transparently in that case, AIUI. -Rob
Re: new/delete overloading, why?
2010/8/21 Henrik Nordström hen...@henriknordstrom.net: Why are we overloading new/delete with xmalloc/xfree? include/SquidNew.h this is causing random linking issues every time some piece of code forgets to include SquidNew.h, especially when building helpers etc. And I fail to see what benefit we get from overloading the new/delete operators in this way. it was to stop crashes with code that had been cast and was freed with xfree(); if you don't alloc with a matching allocator, and the platform has a different default new - *boom*. There may be nothing like that left to worry about now. -Rob
Re: FYI: github
Its fine by me; we could push squid3 up as well using bzr-git, if folk are interested. -Rob
Re: Compliance: Improved HTTP Range header field validation.
+1 -Ro b
Re: Marking uncached packets with a netfilter mark value
On Tue, Jun 22, 2010 at 8:52 AM, Andrew Beverley a...@andybev.com wrote: 1. Because the marking process needs to be run as root, can this only be achieved by putting the mark function within the squid process that originally starts up, and stipulate that this has to be run as root? Consider a dedicated helper like the diskd helper - send it a fd using shm, and a mark to place, and have it make the call. This can be started up before squid drops privileges. Better still, to a patch to netfilter to allow non root capabilities here. 2. Is any such patch likely to be accepted? Yes, modulo code quality, testing, cleanliness etc etc - all the usual concerns. -Rob
Re: food for thought?
2010/6/16 Kinkie gkin...@gmail.com: Actually the thing I found the most interesting is that it suggests to use page-aware object placements so that big structures traversal is easier on the VM. Could it be useful to adopt that for some of our low-level indexes? We do have a few hashes and trees laying around which maybe could benefit from this; and adopting an alternate algorithm for those may not have a big impact code-wise.. page-aware is only part of it - really, dig up cache oblivious algorithms. Lots of use and benefits :). -Rob
Re: Bug 2957 - only-if-cached shouldn't count when we're not caching
Well it sounds totally fine in principle; I'm wondering (without reading the patch) how you define 'we are not caching' - just no cachedirs ? That excludes mem-only caching (or perhaps thats not supported now). -Rob
Re: food for thought?
Well its written in an entertaining and a little condescending style. The class of algorithmic analysis that is relevant is 'cache oblivious algorithms' and is a hot topic at the moment. Well worth reading and thinking about. -Rob
Re: How to review a remote bzr branch
2010/5/24 Alex Rousskov rouss...@measurement-factory.com: On 05/22/2010 02:41 AM, Robert Collins wrote: What I do to review is usually 'bzr merge BRANCH'; bzr diff - and then eyeball. Thats roughly what a 'proposed merge' in launchpad will show too. You could do that as an alternative. Noted. The merge command may produce conflicts that will not be immediately visible in bzr diff, right? Yes indeed. -Rob
Re: How to review a remote bzr branch
What I do to review is usually 'bzr merge BRANCH'; bzr diff - and then eyeball. Thats roughly what a 'proposed merge' in launchpad will show too. You could do that as an alternative. -Rob
Re: Poll: Which bzr versions are you using?
What OS are you using? Upgrading to 2.0.x or newer would be advantageous. If there aren't packages for it, I'm sure we can figure out who to tickle to get some. -Rob
Re: Poll: Which bzr versions are you using?
2.2 :
Re: Poll: Which bzr versions are you using?
in general No; the .bzr.log in a users homedir will contain some info, possibly the client version: the server does receive that, I think. Over HTTP bzr is just another client - the user agent field includes the bzr version, I think, if you were to look in apache logs. -Rob
Re: Upgrade repository format for trunk?
On Thu, 2010-03-25 at 15:29 -0600, Alex Rousskov wrote: Sigh. I would rather not upgrade then. I do not know how to move from bzr 1.3 to bzr 2.0.x on Red Hat box that I have to use for some of the development, and I doubt somebody here would enjoy educating me on that process... Besides, even Ubuntu 9.10 only has bzr v2.0.2 by default. Thus, we would be cutting it pretty close to bleeding edge for many. Yes, 2.0.0 was relatively recent. Bzr folks are very good at making lots of releases but the world is apparently incapable of moving with the same speed! Well, we try to balance things; and we expect to stay with 2a for quite some time as a default - probably several years, as we did with 1.0. 2a is much more compact on disk, and faster across the board. But everyone will need to upgrade their own repositories, which can take a bit of time (or delete them and pull anew). If nothing else, this will require instruction on how to upgrade the everyone repositories. I can support the upgrade once those instructions work for me :-). -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] immortal helpers
On Sun, 2010-02-21 at 22:27 +0100, Henrik Nordström wrote: lör 2010-02-20 klockan 18:25 -0700 skrev Alex Rousskov: The reasons you mention seem like a good justification for this option official existence. I do not quite get the fork bomb analogy because we are not creating more than a configured number of concurrent forks, are we? We may create processes at a high rate but there is nothing exploding here, is there? With our large in-memory cache index even two concurrent forks is kind of exploding on a large server. Consider for example the not unrealistic case of a 8GB cache index.. I actually have some clients with such indexes. I have an idea about this. Consider a 'spawn_helper'. The spawn helper would be started up early, before index parsing. Never killed and never started again. It would have, oh, several hundred K footprint, at most. command protocol for it would be pretty similar to the SHM disk IO helper, but for processes. Something like: squid-helper: spawn stderrfd argv(escaped/encoded to be line NULLZ string safe) helper-squid: pid, stdinfd, stdoutfd This would permit several interesting things: - starting helpers would no longer need massive VM overhead - we won't need to worry about vfork, at least for a while - starting helpers can be really async from squid core processing (at the moment everything gets synchronised) -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] immortal helpers
On Mon, 2010-02-22 at 02:03 +0100, Henrik Nordström wrote: mån 2010-02-22 klockan 11:44 +1100 skrev Robert Collins: command protocol for it would be pretty similar to the SHM disk IO helper, but for processes. Something like: squid-helper: spawn stderrfd argv(escaped/encoded to be line NULLZ string safe) helper-squid: pid, stdinfd, stdoutfd Which requires UNIX domain sockets for fd passing, and unknown implementation on Windows.. I thought SHM could pass around fd's. Anyhow, its doable on unix. On windows you can supply a HANDLE cross process: BOOL WINAPI DuplicateHandle( __in HANDLE hSourceProcessHandle, __in HANDLE hSourceHandle, __in HANDLE hTargetProcessHandle, __out LPHANDLE lpTargetHandle, __in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in DWORD dwOptions ) So you call that, and then the other process can use the handle. -Rob signature.asc Description: This is a digitally signed message part
Re: SMP: inter-process communication
On Sun, 2010-02-21 at 20:18 -0700, Alex Rousskov wrote: On 02/21/2010 06:10 PM, Henrik Nordström wrote: sön 2010-02-21 klockan 17:10 -0700 skrev Alex Rousskov: The only inter-process cooperation I plan to support initially is N processes monitoring the same http_port (and doing everything else). I guess there will be no shared cache then? Not initially, but that is the second step goal. I suggest using CARP then, to route to backends. -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] icap_oldest_service_failure option
+1 signature.asc Description: This is a digitally signed message part
Re: Initial SMP implementation plan
JFDI :) -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] Plain Surrogate/1.0 support
On Sun, 2010-02-07 at 00:52 +1300, Amos Jeffries wrote: According to the W3C documentation the Surrogate/1.0 capabilities and the Surrogate-Control: header are distinct from the ESI capabilities. This patch makes Squid always advertise and perform the Surrogate/1.0 capabilities for reverse-proxy requests. Full ESI support is no longer required to use the bare-bones Surrogate-Control: capabilities. A quick check though - is it still only enabled for accel ports? (It shouldn't be enabled for forward proxying). -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] log virgin HTTP request headers I don't know that the config option has to meet the code, though obviously it is nice if it does. -Rob signature.asc Description: This is a digitally signed message part
Re: Squid-3 and HTTP/1.1
On Wed, 2010-01-27 at 22:49 -0700, Alex Rousskov wrote: c) Co-Advisor currently only tests MUST-level requirements. Old Robert's checklist contained some SHOULD-level requirements as well. I see that Sheet1 on the spreadsheet has SHOULDs. Are we kind of ignoring them (and Sheet1) for now, until all MUSTs on Sheet2 are satisfied? d) I do not know who created the spreadsheet. Whoever it was, thank you! Is there a script that takes Co-Advisor results and produces a spreadsheet column for cut-and-pasting? It looks nice. It might be based on the xls spreadsheet I made, but I don't know ;) I would not worry about SHOULD's until the MUSTs are done (but if a SHOULD is in reach while doing a MUST, doing it would be good). -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] log virgin HTTP request headers
Just a small thing: can I suggest s/virgin/pristine/ ? Or s/virgin/received/ ? virgin has a sexual connotation in some cultures, and can be confusing in a way that is avoidable. -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] Cloned Range memory leak
Looks good to me. -Rob signature.asc Description: This is a digitally signed message part
Re: patch to fix debugging output
Thanks, applied to trunk. -Rob signature.asc Description: This is a digitally signed message part
Re: [RFC] Micro Benchmarking
On Tue, 2009-12-22 at 16:05 +1300, Amos Jeffries wrote: The tricky bit appears to be recovering the benchmark output and handling it after a run. If you make each thing you want to get a measurement on a separate test, you could trivially install libcppunit-subunit-dev and use subunits timing and reporting mechanisms; saving the stream provides a simple persistence mechanism. -Rob signature.asc Description: This is a digitally signed message part
Re: SMB help needed
On Sat, 2009-12-12 at 23:33 +0100, Henrik Nordstrom.. They are easier in that sense, but worse in the following: - they put more load on the domain - can't do NTLM reliably - very old, very crufty code I know we had the argument, but I'm not at all convinced that keeping them is the right answer. I think a better answer is to talk to samba to find out if winbindd can be used outside a domain, which is the only usecase these helpers are 'better' at, and if it can - or if it could be changed to do so, then do that, and get rid of the cruft as at that point it won't offer anything. -Rob signature.asc Description: This is a digitally signed message part
Re: [squid-users] 'gprof squid squid.gmon' only shows the initial configuration functions
On Tue, 2009-12-08 at 15:32 -0800, Guy Bashkansky wrote: I've built squid with the -pg flag and run it in the no-daemon mode (-N flag), without the initial fork(). I send it the SIGTERM signal which is caught by the signal handler, to flag graceful exit from main(). I expect to see meaningful squid.gmon, but 'gprof squid squid.gmon' only shows the initial configuration functions: gprof isn't terribly useful anyway - due to squids callback based model, it will see nearly all the time belonging to the event loop. oprofile and/or squids built in analytic timers will get much better info. -Rob signature.asc Description: This is a digitally signed message part
Re: SMB help needed
On Wed, 2009-12-09 at 17:40 +1300, Amos Jeffries wrote: During the helper conversion to C++ I found that the various SMB lookup helpers had a lot of duplicate code as each included the entire smbval/smblib validation library as inline code. Delete them. Samba project ships helpers that speak to winbindd and do a hellishly better job :-) -Rob signature.asc Description: This is a digitally signed message part
Re: Link convention fixes
Can you give an example of what you're talking about, and show the compiler warning you're getting too? (And what flags are needed to get it)? -Rob signature.asc Description: This is a digitally signed message part
Re: squid-smp: synchronization issue solutions
On Tue, 2009-11-24 at 16:13 -0700, Alex Rousskov wrote: For example, I do not think it is a good idea to allow a combination of OpenMP, ACE, and something else as a top-level design. Understanding, supporting, and tuning such a mix would be a nightmare, IMO. I think that would be hard, yes. See Henrik's email on why it is difficult to use threads at highest levels. I am not convinced yet, but I do see Henrik's point, and I consider the dangers he cites critical for the right Q1 answer. - If we do *not* permit multiple approaches, then what approach do we want for parallelisation. E.g. a number of long lived threads that take on work, or many transient threads as particular bits of the code need threads. I favour the former (long lived 'worker' threads). For highest-level models, I do not think that one job per thread/process, one call per thread/process, or any other one little short-lived something per thread/process is a good idea. Neither do I. Short lived things have a high overhead. But consider that a queue of tasks in a single long lived thread doesn't have the high overhead of making a new thread or process per item in the queue. Using ACLs as an example, ACL checking is callback based nearly everywhere; we could have a thread that does ACL checking and free up the main thread to continue doing work. Later on, with more auditing we could have multiple concurrent ACL checking threads. -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] logdaemon feature import from Squid-2.7
+1 signature.asc Description: This is a digitally signed message part
Re: /bzr/squid3/trunk/ r10149: skip performing C libTrie unit tests
On Fri, 2009-11-20 at 21:02 +0100, Francesco Chemolli wrote: revno: 10149 committer: Francesco Chemolli kin...@squid-cache.org branch nick: trunk timestamp: Fri 2009-11-20 21:02:00 +0100 message: skip performing C libTrie unit tests Please include motivation in commit messages. The diff shows that you skipped the C tests, but not why. And because the motivation is missing, I'm left asking 'why?' Untested code is broken code, so this really can't be the right answer. -Rob signature.asc Description: This is a digitally signed message part
Re: /bzr/squid3/trunk/ r10149: skip performing C libTrie unit tests
On Sat, 2009-11-21 at 01:19 +0100, Kinkie wrote: And because the motivation is missing, I'm left asking 'why?' Untested code is broken code, so this really can't be the right answer. Ok, I'll be more detailed in the future. As for this case: the autoconf environment is pretty messy in non-canonicalized environments such as Solaris. In particular, the C tests require linking against libstdc++, which causes two kind of issues: finding it (there's at least 6 of the buggers in the test zone), and finding the one with the right ABI (gcc/sunstudio cc). Since we're not using the C interface anyways, might as well skip the checks. I'd much rather you delete code that isn't being tested. -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] replace RFC2181 magic numbers with POSIX definitions
Seems ok at the code level. I worry a little that on damaged systems this will reduce our functionality. At the moment we have our own DNS lookup so the system host length shouldn't matter at all. -Rob signature.asc Description: This is a digitally signed message part
Re: squid-smp: synchronization issue solutions
On Wed, 2009-11-18 at 10:46 +0800, Adrian Chadd wrote: Plenty of kernels nowdays do a bit of TCP and socket process in process/thread context; so you need to do your socket TX/RX in different processes/threads to get parallelism in the networking side of things. Very good point. You could fake it somewhat by pushing socket IO into different threads but then you have all the overhead of shuffling IO and completed IO between threads. This may be .. complicated. The event loop I put together for -3 should be able to do that without changing the loop - just extending the modules that hook into it. -Rob signature.asc Description: This is a digitally signed message part
Re: squid-smp: synchronization issue solutions
On Tue, 2009-11-17 at 15:49 -0300, Gonzalo Arana wrote: In my limited squid expierence, cpu usage is hardly a bottleneck. So, why not just use smp for the cpu/disk-intensive parts? The candidates I can think of are: * evaluating regular expressions (url_regex acls). * aufs/diskd (squid already has support for this). So, we can drive squid to 100% CPU in production high load environments. To scale further we need: - more cpus - more performance from the cpu's we have Adrian is working on the latter, and the SMP discussion is about the former. Simply putting each request in its own thread would go a long way towards getting much more bang for buck - but thats not actually trivial to do :) -Rob signature.asc Description: This is a digitally signed message part
Re: squid-smp: synchronization issue solutions
On Mon, 2009-11-16 at 00:29 +0530, Sachin Malave wrote: Hello, Since last few days i am analyzing squid code for smp support, I found one big issue regarding debugs() function, It is very hard get rid of this issue as it is appearing at almost everywhere in the code. So for testing purpose i have disable the debug option in squid.conf as follows --- debug_options 0,0 --- Well this was only way, as did not want to spend time on this issue. Its very important that debugs works. 1. hash_link LOCKED Bad idea, not all hashes will be cross-thread, so making the primitive lock incurs massive overhead for all threads. 2. dlink_list LOCKED Ditto. 3. ipcache, fqdncache LOCKED, Probably important. 4. FD / fde handling ---WELL, SEEMS NOT CREATING PROBLEM, If any then please discuss. we need analysis and proof, not 'seems to work'. 5. statistic counters --- NOT LOCKED ( I know this is very important, But these are scattered all around squid code, Write now they may be holding wrong values) Will need to be fixed. 6. memory manager --- DID NOT FOLLOW Will need attention, e.g. per thread allocators. 7. configuration objects --- DID NOT FOLLOW ACL's are not threadsafe. AND FINALLY, Two sections in EventLoop.cc are separated and executed in two threads simultaneously as follows (#pragma lines added in existing code, no other changes) I'm not at all sure that splitting the event loop like that is sensible. Better to have the dispatcher dispatch to threads. -Rob signature.asc Description: This is a digitally signed message part
Re: [RFC] Libraries usage in configure.in and Makefiles signature.asc Description: This is a digitally signed message part
Re: [RFC] Libraries usage in configure.in and Makefiles
On Wed, 2009-11-11 at 19:43 +1300, Amos Jeffries wrote: Robert Collins wrote: In the on-disk binary itself yes ... yet they load into memory under the parent apps footprint. The pages for the libraries will be shared though, so it really doesn't matter. -Rob signature.asc Description: This is a digitally signed message part
Re: /bzr/squid3/trunk/ r10069: Fixed OpenSolaris build issues.
On Tue, 2009-11-03 at 13:19 +1300, Amos Jeffries wrote: Just a note on this change... I'm trying to get rid of XTRA_LIBS entirely. It's adding to the code bloat and external library dependencies in Squid. This isn't clear to me, can you expand on it please. Specifically how XTRA_LIBS - the list of additional libraries to link against - is different to COMMON_LIBS. -Rob signature.asc Description: This is a digitally signed message part
Re: WebSockets negotiation over HTTP
On Wed, 2009-10-14 at 09:59 +1100, Mark Nottingham wrote: On 13/10/2009, at 10:23 PM, Ian Hickson i...@hixie.ch wrote: I want to just use port 80, and I want to make it possible for a suitably configured HTTP server to pass connections over to WebSocket servers. It seems to me that using something that looks like an HTTP Upgrade is better than just having a totally unrelated handshake, but I guess maybe we should just reuse port 80 without doing anything HTTP-like at all. To be clear, upgrade is appropriate for changing an existing connection over to a new protocol (ie reusing it). To pass a request over to a different server, a redirect would be more appropriate (and is facilitated by the new uri scheme). Yup; and the major issue here is that websockets *does not want* the initial handshake to be HTTP. Rather it wants to be something not-quite HTTP, specifically reject a number of behaviours and headers that are legitimate HTTP. -Rob signature.asc Description: This is a digitally signed message part
wiki, bugzilla, feature requests
AIUI we use the wiki [over and above being a source of docs] to /design features/ and manage [the little] scheduling that we, as volunteers can do. I think thats great. However, we also have many bugs that are not strictly-current-defects. They are wishlist items. What should we do here? I've spent quite some time using wikis for trying to manage such things, I think its a lost cause. Use them for design and notes and so forth, but not for managing metadata. I suggest that when there is a bug for a feature that is being designed in the wiki, just link to bugzilla from that wiki page. And for management of dependencies and todos, assignees and so forth, we should do it in bugzilla, which is *designed* for that. -Rob signature.asc Description: This is a digitally signed message part
Re: wiki, bugzilla, feature requests
I'm proposing: - if there is a bug for something, and a wiki page, link them together. - scheduling, assignment, and dependency data should be put in bugs - whiteboards to sketch annotate document etc should always be in the wiki -Rob signature.asc Description: This is a digitally signed message part
Re: [MERGE] Clean up htcp cache_peer options collapsing them into a single option with arguments -Rob signature.asc Description: This is a digitally signed message part
Re: [MERGE] Clean up htcp cache_peer options collapsing them into a single option with arguments
+1 then signature.asc Description: This is a digitally signed message part
Re: Why does Squid-2 return HTTP_PROXY_AUTHENTICATION_REQUIRED on http_access DENY?
On Tue, 2009-09-15 at 16:09 +1000, Adrian Chadd wrote: But in that case, ACCESS_REQ_PROXY_AUTH would be returned rather than ACCESS_DENIED.. Right... so can we have some more details about what is happening and what you expect? deny !proxy_auth_group != allow proxy_auth_group and deny proxy_auth_group != allow !proxy_auth_group -Rob signature.asc Description: This is a digitally signed message part
Re: compute swap_file_sz before packing it
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Just a small meta point: The new function you're adding looks like it should be a method to me. - -Rob -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - iEYEARECAAYFAkquyF4ACgkQ42zgmrPGrq4kDQCeLjIz1zAP9F4nvCPz7gkrxbyw Q5cAnR8qzBjnwR97OgPa1tFxyq9Lv+5R =XS/a -END PGP SIGNATURE-
Re: Squid-smp : Please discuss
On Tue, 2009-09-15 at 14:27 +1200, Amos Jeffries wrote: RefCounting done properly forms a lock on certain read-only types like Config. Though we are currently handling that for Config by leaking the memory out every gap. SquidString is not thread-safe. But StringNG with its separate refcounted buffers is almost there. Each thread having a copy of StringNG sharing a SBuf equates to a lock with copy-on-write possibly causing issues we need to look at if/when we get to that scope. General rule: you do /not/ want thread safe objectse for high usage objects like RefCount and StringNG. synchronisation is expensive; design to avoid synchronisation and hand offs as much as possible. -Rob signature.asc Description: This is a digitally signed message part
Re: Why does Squid-2 return HTTP_PROXY_AUTHENTICATION_REQUIRED on http_access DENY?
On Tue, 2009-09-15 at 15:22 +1000, Adrian Chadd wrote: G'day. This question is aimed mostly at Henrik, who I recall replying to a similar question years ago but without explaining why. Why does Squid-2 return HTTP_PROXY_AUTHENTICATION_REQUIRED on a denied ACL? The particular bit in src/client_side.c: int require_auth = (answer == ACCESS_REQ_PROXY_AUTH || aclIsProxyAuth(AclMatchedName)) !http-request-flags.transparent; Is there any particular reason why auth is tried again? it forces a pop-up on browsers that already have done authentication via NTLM. Because it should? Perhaps you can expand on where you are seeing this - I suspect a misconfiguration or some such. Its entirely appropriate to signal HTTP_PROXY_AUTHENTICATION_REQUIRED when a user is denied access to a resource *and if they log in differently they could get access*. -Rob signature.asc Description: This is a digitally signed message part
Re: Build failed in Hudson: 3.1-amd64-CentOS-5.3 #14
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Amos Jeffries wrote: You misunderstood me. On FreeBSD from what I've seen of squid-cache the md5sum 'binary' is: /path/to/pythonversion /path/to/md5sum.py 'md5' - -Rob -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - iEYEARECAAYFAkqkyFMACgkQ42zgmrPGrq5v1gCfVg5djbsXoG+wP/fe4vecUI43 SBMAmQHm96PZ0oZAm8FtPcO7THcvM/n7 =QiDt -END PGP SIGNATURE-
Re: Build failed in Hudson: 3.1-amd64-CentOS-5.3 #14
On Sun, 2009-09-06 at 22:52 +0200, Henrik Nordstrom wrote: Yes. With no dependencies to guide it make reorders as it sees fit for the day, especially if running parallel jobs. We should be fine if we just list the dependencies. -Rob signature.asc Description: This is a digitally signed message part
Re: Build failed in Hudson: 3.1-amd64-CentOS-5.3 #14
On Sun, 2009-09-06 at 23:25 +0200, Henrik Nordstrom wrote: Not sure I am comfortable with adding dependencies to automakes own targets.. and no, we are not fine with just that. See the rest of previous response.. To repeat there is more issues here than uninstall racing, we don't even install properly if someone tries to override the default locations by make DEFAULT_CONFIG_FILE=... DEFAULT_MIME_TABLE=... We should definitely fix that :). If its plausible that automake should know and avoid the problem itself, lets file a bug. Otherwise we'll have to work around it I guess. -Rob signature.asc Description: This is a digitally signed message part
Re: WebSockets negotiation over HTTP
On Fri, 2009-09-04 at 01:44 +, Ian Hickson wrote: One very real example of this would be the web server or an fully WebSocket capable intermediary sending back bytes ... example #1 suppose there was an intermediary translating websockets-over-http to websockets-port-81 which used HTTP to format said headers of confirmation. Here is the problem I have with this: Why would we suppose the existence of such an intermediary? Why would anyone ever implementa WebSocket-specific proxy? Welcome to the internet :). Seriously, Why would we suppose the existence of an intermediary that intercepts and MITM's SSL connections? Or HTTP - its even got a defined proxy facility, there is no need to take over and insert different behaviour, is there? We *should* assume that firewall vendors and ISP's will do arguably insane things, because they have time and again in the past. example #2 is where the traffic is processed by an HTTP-only intermediary which sees the 'Upgrade:' header and flags the connection for transparent pass-thru (This by the way is the desirable method of making Squid support WebSockets). Being a good HTTP relay it accepts these bytes: HTTP/1.1 101 Web Socket Protocol Handshake Upgrade: WebSocket Connection: Upgrade It violates HTTP by omitting the Via and other headers your spec omits to handle. And passes these on: HTTP/1.1 101 Web Socket Protocol Handshake Connection: Upgrade Upgrade: WebSocket then moves to tunnel mode for you. Why would it violate HTTP in all the ways you mention? If it goes to such extreme lengths to have transparent pass-through to the point of violating HTTP, why would it then go out of its way to reorder header lines? Because sysadmins do this! Don't ask us to justify the weird and wonderful things we run into. Nearly daily we have users asking for help doing similar things in #squid. From my perspective, such a proxy would raise all kinds of alarm bells to me, and I would be _glad_ that the connection failed. If it didn't, I wouldn't be sure we could trust the rest of the data. Again, welcome to the internet :P. Seriously, if its not digitally signed, you *can't* trust the rest of the data. The MITM isn't the WebSocket client. In this situation, it's a (non-compliant, since it forwarded by-hop headers) HTTP proxy. What's more, in this scenario the server isn't a WebSocket server, either, it's an HTTP server. So what Web Socket says is irrelevant. Note that there are *still* HTTP/1.0 proxies in deployment that don't know about hop by hop headers. ... WebSockets, even when initiating the connection by talking to an HTTP server and then switching to WebSockets, isn't layered on HTTP. It's just doing the bare minimum required to allow the HTTP server to understand the request and get out of the way. Once the handshake is complete, there is no HTTP anywhere on the stack at all. Its not doing the bare minimum. The bare minimum would be to accept the valid HTTP transforms which the Internet _will_ perform on the handshake. Discard those useless transforms and validate the handshake status line. The bare minimum is the least amount of processing possible. What you describe is _more_ processing, not less. Therefore it's not the minimum. The bare minimum would be to just start the tcp connection with 'websocket/1.0\r\n' Stop pretending to be HTTP: use port 80. Our whole point has been, if you want to Use HTTP Upgrade, Do It Correctly. If you want to Use port 80, just do that. On Thu, Jul 30 2009, Henrik Nordstrom wrote: But for 2 you need to use HTTP, which essentially boils down to defining that one may switch a webserver to use WebSockets by using the HTTP Upgrade mechanism as defined by HTTP. I understand that you disagree with my interpretation, but my interpretation is that this is exactly what the spec does already. At this point I think we need to go to the HTTP-WG and discuss further. Most of us are already there... 5) Specific mention is made to ignore non-understood headers added randomly by intermediaries. So long as that happens after the handshake, that's ok, but we can't allow that inside the handshake, it would allow for smuggling data through, If having this view then you CAN NOT use HTTP for the Upgrade handshake, and MUST use another port and other protocol signatures. IANA expert review has informed me that I must use ports 80 and 443, so there I don't have a choice here. Whats the message id what list? I'm extremely happy to jump into that conversation. -Rob signature.asc Description: This is a digitally signed message part
Re: R: Squid 3 build errors on Visual Studio - problem still present
On Sun, 2009-08-30 at 09:48 +0200, Guido Serassio wrote: c:\work\nt-3.0\src\SquidString.h(98) : error C2057: expected constant expression The offending code is: const static size_type npos = std::string::npos; Can you find out what std::string::npos is defined as in your compiler's headers? Thanks, Rob signature.asc Description: This is a digitally signed message part
Re: R: R: Squid 3 build errors on Visual Studio - problem still present
On Sun, 2009-08-30 at 18:13 +0200, Guido Serassio wrote: Hi, I don't know what is std::string::npos, and so I don't know what to look for It should be a static const, which is why I'm so surprised you're getting an error about it. -Rob signature.asc Description: This is a digitally signed message part
Re: [PATCH] DiskIO detection cleanup.
I haven't read the patch yet, but I concur with Henrik. We should default-enable as much as possible: An unused DiskIO module has almost no footprint - simply a registration entry and a link dependency on $whatever was needed. Rebuilding your squid because it doesn't have what you need is _much_ more painful. Even the smallest embedded devices are pretty huge these days, so the extra libs don't concern me. -Rob signature.asc Description: This is a digitally signed message part
Re: Alternate http repository for squid3. -Rob signature.asc Description: This is a digitally signed message part
Re: Alternate http repository for squid3
On Tue, 2009-08-25 at 11:09 +1200, Amos Jeffries wrote: On Tue, 25 Aug 2009 04:20:31 +1000, Robert Collins robe...@robertcollins.net wrote:. Or at least hourly before the SCM polling happens. That frequency has worked so far for the SourceForge CVS copy. The lower the latency the better. That allows change-test cycles to be short, when dealing with build environments we don't locally have. -Rob signature.asc Description: This is a digitally signed message part
Re: Alternate http repository for squid3
On Thu, 2009-08-20 at 14:07 +0200, Kinkie wrote: As part of the ongoing buildfarm work, I've published onto http the (read-only) repository mirror that's hosted on eu. It's available at How often is this synced? -Rob signature.asc Description: This is a digitally signed message part
RFC: infrastructure product in bugzilla
I think we should have an infrastructure product in bugzilla, for tracking list/server/buildfarm etc issues. -Rob -- signature.asc Description: This is a digitally signed message part
Re: RFC: infrastructure product in bugzilla
On Thu, 2009-08-20 at 11:33 +1200, Amos Jeffries wrote: On Thu, 20 Aug 2009 09:00:15 +1000, Robert Collins robe...@robertcollins.net wrote: I think we should have an infrastructure product in bugzilla, for tracking list/server/buildfarm etc issues. What sort of extra issues exactly are you thinking need to be bug-tracked? We already have websites as a separate 'product' for tracking content errors. Oh hmm, perhaps just renaming websites - infrastructure. We have a bunch of services: - smtp - lists - backups? - user accounts on squid-cache.org machines (eu, us, test vms, others?) - VCS - code review And a wide range of webbish services - the CDN - bugzilla (currently xlmrpc doesn't work) - the main site content - patch set generation - wiki -Rob signature.asc Description: This is a digitally signed message part
Re: separate these to new list?: Build failed...
On Sun, 2009-08-16 at 04:05 +0200, Henrik Nordstrom wrote: sön 2009-08-16 klockan 10:23 +1000 skrev Robert Collins: If the noise is too disturbing to folk we can investigate these... I wouldn't want anyone to leave the list because of these reports. I would expect the number of reports to decline significantly as we learn to check commits better to avoid getting flamed in failed build reports an hour later.. combined with the filtering just applied which already reduced it to 1/6. But seriously, it would be a sad day if these reports becomes so frequent compared to other discussions that developers no longer would like to stay subscribed. We then have far more serious problems.. Discussion on this list can be quite sporadic, and its easy for build message volume to be a significant overhead - at least thats my experience in other projects - lists which have unintentional traffic feel hard to deal with. This includes bug mail, build mail, automated status reports and so on. Secondly, I wager that many folk on this list are not regular committers and are unlikely to hop up and fix a build failure; so its not really the right balance for them to be hearing about failures. I think it makes sense to have a dedicated list (squild-bui...@squid-cache.org) for build status activity. I probably won't be on it, for instance. (I prefer to track such data via rss feeds - they don't grab my attention when I'm in the middle of something else, but the data is there and I can still look at and fix things). -Rob signature.asc Description: This is a digitally signed message part
buildfarm builds for squid-2?
I thought I'd just gauge interest in having 2.HEAD and 2.CURRENT tested in the buildfarm. For all that most development is focused on 3, there are still commits being done to 2.x, and most of the hard work in the buildfarm is setup - which is now done. -Rob signature.asc Description: This is a digitally signed message part
Re: separate these to new list?: Build failed...
We do have other options though: - we could have a separate list - we have the RSS feed anyone can subscribe too - we could cause failing builds to file bugs. If the noise is too disturbing to folk we can investigate these... I wouldn't want anyone to leave the list because of these reports. -Rob signature.asc Description: This is a digitally signed message part | https://www.mail-archive.com/search?l=squid-dev%40squid-cache.org&q=from:%22Robert+Collins%22&o=newest&f=1 | CC-MAIN-2022-33 | refinedweb | 12,084 | 62.58 |
24 March 2010 09:43 [Source: ICIS news]
SINGAPORE (ICIS news)--Crude futures fell more than $1/bbl on Wednesday, undermined by the strengthening of the US dollar and an unexpectedly large build in US crude inventories.
At 09:05 GMT, May Brent on ?xml:namespace>
At the same time, May NYMEX light sweet crude futures were trading at $80.76/bbl, down $1.15/bbl from the previous close and off an intra-day low of $80.70/bbl.
The US dollar continued to strengthen against the Euro on Thursday amid ongoing worries over
Crude prices were pressured after industry data released on Tuesday by the American Petroleum Institute (API) revealed a much larger-than-expected 7.5m bbl build in crude stocks.
Meanwhile, declines in gasoline inventories were less than expected but there was a substantial decline in distillate stocks of 2.5m bbls, which had initially helped to stabilise the market late on Tuesday.
Traders now await the release of the more widely followed official
($1 = €0.74) | http://www.icis.com/Articles/2010/03/24/9345223/crude-falls-1bbl-on-stronger-dollar-rise-in-us-crude-stocks.html | CC-MAIN-2014-35 | refinedweb | 171 | 64.3 |
Code Focused
In this article I describe how to work with events in your Blazor applications. I cover two types of events, DOM events and custom or user-defined events. DOM events are things such as onclick or onchange and are triggered by a user interaction of some kind. User-defined events are defined by the developer based on the needs of the app.
DOM Events
Way back in the Blazor 0.1 days events were extremely limited; we had to make do with only three: onclick, onchange and onkeypress. The event data available was also rather basic -- in fact I'm not even sure if we could access any event-specific information. But with the release of Blazor 0.2 things changed dramatically.
In Blazor 0.2 the way events were handled was given an overhaul. Now any event was available to developers and there was even specific event data available (depending on the event). Since then, more event-specific data has been added, and it's a pretty good experience working with events in Blazor now.
In the current version of Blazor developers can access any event by using the on<event> attribute with an HTML element. The attribute's value is treated as an event handler. In the following example the LogClick() method is called every time the button is pressed:
<button onclick=@LogClick>Press Me</button>
@functions {
private void LogClick()
{
Console.WriteLine("Button Clicked!");
}
}
It is also possible to use Lambda expressions, so the example above could be written as follows:
<button onclick="@(() => Console.WriteLine("Button Clicked!");)">
Press Me
</button>
Event DataWhile it is great to have access to all these events, some are not much use without some data to go with them. For example, we may want something specific to happen when a user presses the "r" key in an input. So we go ahead and wire up the event as below:
<input type="text" onkeypress=@KeyWasPressed />
@functions {
private void KeyWasPressed()
{
Console.WriteLine("r was pressed");
}
}
But there's a problem. The event is going to fire every time any key is pressed. We only wanted to print the message when the "r" key was pressed. This is where we need some data on the event.
Blazor provides a set of event argument types that map to events. Below is a list of event types and the event argument type they map to. If you want to see which specific event argument type each event has you can view them here.
To solve our problem, we need to make use of the UIKeyboardEventArgs. To gain access to this event data, we need to make a small change to the code:
<input type="text" onkeypress="@(e => KeyWasPressed(e))" />
@functions {
private void KeyWasPressed(UIKeyboardEventArgs args)
{
if (args.Key == "r")
{
Console.WriteLine("R was pressed");
}
}
By changing to a Lambda expression we can now pass the event data to the event handler. With this data we are able to access the Key property, which contains a string of the key that was pressed to fire the event. A simple if statement is all that is needed and we are now only getting messages in the console when the "r" key is pressed.
User-Defined Events
Now that we've covered DOM events, let's talk about defining our own events. Like many things in software development, the need for defining your own events will very much depend on your situation.
As an example I'm going to use a state store, a pattern becoming common in modern single-page applications (SPA). For those who are not familiar, the idea is to have a single place that stores and performs operations on the state of your application.
Let's take an expense tracking app that records money spent and gives a running total. We can define a simple state store like this:
public class AppState
{
private readonly List<Expense> _expenses = new List<Expense>();
public IReadOnlyList<Expense> Expenses => _expenses;
public event Action OnExpenseAdded;
public void AddExpense(Expense expense)
{
_expenses.Add(expense);
StateChanged();
}
private void StateChanged() => OnExpenseAdded?.Invoke();
}
In the code above, the key part for us is the custom OnExpenseAdded event. Whenever a new expense is added to the collection, this event is going to be invoked. Now let's build a couple of components that can use the store.
The first is just a simple component that records the expense data and then adds that to the collection on the state store:
@inject appState
<h2>Add Expense</h2>
<div class="row">
<div class="col-md-4">
<input class="form-control" bind="@expense.Description" placeholder="Enter Description..." />
</div>
<div class="col-md-2">
<input class="form-control" bind="@expense.Amount" placeholder="Enter Amount..." />
</div>
<div class="col-md-6">
<button onclick="@AddExpense" class="btn btn-primary">
Add
</button>
</div>
</div>
@functions {
private Expense expense = new Expense();
private async Task AddExpense()
{
await appState.AddExpense(expense);
expense = new Expense();
}
}
With that in place, all that we need is a component to display the total of our expenses:
@inject appState
<h2>Current Total: £@totalExpenses</h2>
@functions {
private decimal totalExpenses => appState.Expenses.Sum(x => x.Amount);
protected override void OnInit()
{
appState.OnExpenseAdded += StateHasChanged;
}
}
As you can see, I've registered the components StateHasChanged method to our custom event in the state store. Now whenever an expense is added, this component will update itself and show the new total for the expenses.
Before I sign off I just wanted to point out some great news for Blazor fans. At .NET Conf it was officially announced that Blazor's server-side model will be shipped as part of ASP.NET in .NET Core 3! [see article here] I do want to point out though that the team is still committed to delivering the client-side model. However, it will be staying in an experimental state for now while work on running .NET on WebAssembly continues.
As a reminder, I explained how to consume Web APIs in Blazor in last month's article. | https://visualstudiomagazine.com/articles/2018/10/01/blazor-event-handling.aspx | CC-MAIN-2019-13 | refinedweb | 997 | 64.2 |
SIAL Paris
is a big
challenge!
Easy to say but takes painstaking efforts through tens of years to
realize such a success! It is not a regular show nor a normal success…
7200 exhibitors come from 105 countries to meet with
around 164,000 visitors from 194 countries. It is an unaccustomed
and extraordinary event. It is legendary SIAL Paris 2018!
Group Chairman
Publisher
Managing Editor
Editor
H.Ferruh ISIK
ISTMAG Magazin Gazetecilik
Yayıncılık İç ve Dış Ticaret Ltd. Şti.
Mehmet SOZTUTAN
(mehmet.soztutan@img.com.tr)
Ayça SARIOĞLU
(ayca.sarioglu@img.com.tr)
In SIAL 2018, Turkey will be represented by over 300 exporters,
a number which is bigger than total exhibitor numbers of more
than half of world fairs.
Turkey is a good food exporting country with a wide variety of
products. It is outstanding in quality and competitive in price. It
is a country which adds value in many industries and the food
industry is no exception.
The young and growing population provides opportunities for
growth and new product introductions in Turkey which has a
well-developed food processing sector that is producing good
quality food items for the Turkish market and for exports. The
share of household expenditure allocated to food, beverages,
and tobacco will remain high by western standards. It was 23.5
percent of household spending in 2017.
In addition to local production, products from European countries
are also important. EU has a customs union with Turkey
where many European processed food items have low or no
customs tariffs to Turkey. Furthermore, proximity is a major benefit
for lower freight and shorter deliver times from Europe.
Trucks are often used for transportation between Europe and
Turkey. European Free Trade Association (EFTA) countries
which are Switzerland, Norway, Iceland, and Liechtenstein also
have a joint FTA with Turkey, giving them preferential customs
advantages as well. In addition, Turkey has FTAs with 19 other
countries with many including preferential tariff rates on food
and agriculture products.
The competitive Turkish presence will be in Dubai for Gulfood
Manufacturing and Food Turkey magazine will be hand-delivered
from its stand for free. We wish lucrative business for all involved.
Responsible
Editor-in-Chief:
Advertisement Manager
Correspondent
Communications Manager
Art Director
Finance Manager
Accounting Manager
Subscription
HEAD OFFICE
Güneşli Evren Mah. Bahar Cad.
Polat İş Merkezi B Blok No:3,34197
Güneşli-İstanbul/TURKEY
Tel: +90 212 604 50 50
Cüneyt AKTÜRK
(cuneyt.akturk@ihlasfuar.com.tr)
Emir Omer OCAL
(emir.ocal@img.com.tr)
Omer Faruk GORUN
(fgorun@ihlas.net.tr)
Enes KARADAYI
(enes.karadayi@img.com.tr)
Ebru PEKEL
(ebru.pekel@voli.com.tr)
Tolga ÇAKMAKLI
(tolga.cakmakli@img.com.tr)
Mustafa AKTAŞ
(mustafa.aktas@img.com.tr)
Zekayi TURASAN
(zturasan@img.com.tr)
İsmail ÖZÇELİK
(ismail.ozcelik@img.com.tr)
LIAISON OFFICE:
Buttim Plaza A. Blok
Kat:4 No:1038
Bursa/TURKEY
Tel: +90. 224 211 44 50-51
4 FOOD TURKEY September/October 2018
Mehmet Söztutan
It is an inevitable element of dining tables equipped
with the most delicious dishes to share with the
loveliest friends… It is Kilikya Şalgam, It is
Kilikya Turnip…
No matter what you have on the menu, the dining
tables without Kilikya are savorless and the dishes
are unhappy. Because Kilikya Turnip is the taste
friend of all dishes!
taste
friend
/kilikyatr
CONTENTS
8
Chinese investment
potential continues to
focus on agribusiness
sector in Turkey
10
Global halal food
market prospers
more than ever
16
Turkey’s organic
agricultural products
diversified
20
Turkey to dodge the
brunt of global trade
wars
22 48
Turkey’s poultry
production on rise
26
Factory investment
worth of TL 400
million in Kadirli by
Senpiliç
30
Erpiliç wings and flies to
success
36
Tu
Akanlar
Chocolate&Drink
on the way be a
preferred and leading
world brand
52
Candied Chestnut
sweetens the world
58
Turkey offers significant
investment
opportunities in agribusiness
subsectors
66
Visitor flow to
WorldFood Istanbul
in its 26th year
70
Feel the change with
the new image of 26th
edition of ANFAS Food
Product!
74
SIAL Paris opens for
new records
82
Aegean fruits and
vegetable exporters
raised targets
92
Turkey ready to
be a key halal food
exporter
6 FOOD TURKEY September/October 2018
Chinese investment
potential continues to focus
on agribusiness sector in
Turkey
China is keen to
import fruits and
vegetables from
Turkey. Cherry
imports from Turkey
and the Shanghai
Food port can be
entry points for
Turkish cherries to the
Chinese market.. number of Chinese firms
operating in Turkey had neared 1,000
by April, according to data from the
Economy Ministry.
10 FOOD TURKEY September/October 2018
Global halal food
market prospers more
than ever
The halal food market has grown quickly over the past
decade, and is now worth an estimated $632 billion
annually on a global scale
According to a recent global market
research, Muslims represent an
estimated 25% of the world’s population,
with around 1.6 billion consumers.
This large consumer market
presents several opportunities for
halal food products. Not only is the
Muslim population growing, but Muslim
consumers are increasingly better
educated, with higher household incomes,
paving the way for a worldwide
demand for mainstream products
and services that conform to
Islamic values. Halal food is prepared
following a set of Islamic dietary laws
and regulations that determine what
is permissible, lawful and clean.
The halal food market has grown
quickly over the past decade, and is
now worth an estimated $632 billion
annually. As such, it represents close
to 17% of the entire global food industry.
In order to conform to Islamic
standards; all Muslims must ensure
that they are only consuming halal
approved food, drink and medicine.
The large population of Muslims
adhering to halal requirements has
fuelled increased global demand for
halal products.
The global halal food market was not
significantly affected by the global financial
recession. Major growth in
Asia has been driven by changing lifestyles
that allow for higher incomes.
The largest contributors to the halal
market in Asia are Indonesia, China,
India, Malaysia and the Gulf Cooperation
Council (GCC) members,
including the United Arab Emirates,
Bahrain, Saudi Arabia, Oman, Qatar
and Kuwait. These countries have all
seen substantial growth in the halal
12 FOOD TURKEY September/October 2018
food industry that is unlikely to be
curbed in the near future.
There is also strong potential for halal
certified products in non-majority
Muslim markets, where consumers
are looking for safe and ethical products.
The increasing popularity of the
halal market in Europe is driven by
Russia, France and the United Kingdom.
The halal market in these countries
has continued growing since
2004, albeit at a slower pace than
Asian markets. A major opportunity
can be found in the Australia/Oceania
region, where the halal food market
saw growth of 33.3% in recent
years.
The most promising halal markets
span over a range of different
countries. As the largest populations
of Muslim’s are located in the
Asia-Pacific region, both majority and
non-majority Muslim countries in this
region would have high demand for
halal products. However, markets in
North Africa and the Middle East are
particularly lucrative markets, as several
countries have majority-Muslim
populations.
The halal food industry is also growing
in countries that have smaller
populations of Muslims, but that have
food quality and safety concerns,
such as Australia, the United States
and European countries.
Key halal markets include Indonesia,
United Arab Emirates, Algeria, Saudi
Arabia, Iraq, Morocco, Iran, Malaysia,
Egypt, Turkey, Tunisia, Kuwait, Jordan,
Lebanon, Yemen, Qatar, Bahrain, Syria,
Oman and Pakistan. Emerging halal
markets with relatively large Muslim
populations include India (177
million Muslims), China (23 million),
Russia (16 million), the Philippines (5
million), France (5 million), Germany
(4 million) and the United Kingdom
(3 million).
To sum up:
- 25% of the world’s population is
Muslim, nearly 1.6 billion people.
- Food products prepared following
a set of Islamic dietary laws and
regulations, which determine what is
permissible, lawful and clean, are classified
as halal.
- The halal food market has grown
quickly over the past decade, and is
now worth an estimated $632 billion
annually on a global scale.
- Strong economic growth and rising
per capita incomes have fuelled demand
for diversified halal products,
enabling higher consumption levels
and more opportunities for halal
food producers.
- Halal consumption is not limited
only to the Muslim population; other
consumer goods are seeking halal
food due to halal food’s excellent
reputation for healthy and safe food
products, and the humane treatment
of animals.
14 FOOD TURKEY September/October 2018
Turkish exporters urge
for building stronger food
brands in Japan
“Turkish bulgur
may replace rice in
Japan.”
Turkish exporters are determined
to strengthen their brand perception
in Japan, said Chairman of the
Mediterranean Exporters’ Association.
“Our aim is to be chosen for our
quality, not for our cheap price. So
we want to strengthen the image of
Turkish goods,” Ali Can Yamanyilmaz
told during the Turkish Food Festival
held in the Japanese capital Tokyo.
Yamanyilmaz said tough markets
such as Japan are an important opportunity
for Turkish food brands to
improve themselves.
“The packaging and presentation
of products is as important as the
product itself in Japanese markets,
which have tight controls and standards,”
he said.
Stating that no country consumes
more rice than Japan, Yamanyilmaz
added: “Turkish bulgur may replace
rice in Japan.”
Yamanyilmaz noted that among Turkey’s
most-exported food products
to Japan are fishery and aquaculture
products, cereals, fresh fruits and
Ali Can Yamanyılmaz,
Chairman of the Mediterranean Exporters’ Association
vegetables, olive oil, juice, and sugar
products. Underlining that foreign
trade between the two countries
is not balanced, he stated that the
ratio of Turkey’s exports to imports
from Japan should be increased to
25 percent from its current figure of
around 10 percent.
In 2017, Turkey’s exports to Japan
stood at $411.5 million, versus imports
from Japan at $4.3 billion, according
to the Turkish Statistical Institute
(TurkStat).
During Turkish Food Festival, some
27 members of the Mediterranean
Exporters’ Association met with
Japanese caterers and supermarket
representatives. More than 300
B2B meetings were held during the
festival, which hosted 44 prominent
Japanese food importers.
16 FOOD TURKEY September/October 2018
Turkey’s organic
agricultural products
diversified
Due to its rich plant variety, Turkey is one of the countries
best suited for organic cultivation. Today, nearly 250 kinds of
agricultural products are organically produced efficiently.
Nowadays consumers are becoming
increasingly interested in environmentally
sound products, as a result
of continuously expanding awareness.
Thus, the desire for healthy
life has oriented consumers toward
healthy food and organic agricultural
products. The movement towards
healthy food has started in 1960’s in
developed countries, spread all over
the world. In line with,
growing demand, organic agricultural
activities began in Turkey in 1985
based on demand of importing
countries. Due to its rich plant variety,
Turkey is one of the countries
18 FOOD TURKEY September/October 2018
est suited for organic cultivation.
Today, nearly 250 kinds of agricultural
products are organically produced
in Turkey and shipped abroad pioneering
with dried fruits and nuts,
olive and olive oil, pulses and spices.
Industrial products such as cotton,
textiles and essential oils have also
be started to be produced organically.
In the Turkish agricultural and food
industry, production is realized in
conformity with all rules of hygiene
in order to produce high quality and
sanitary products. In this regard,
many firms in Turkey have started
to apply internationally recognized
quality and food safety systems like
ISO 9000, ISO 22000, HACCP, BRC,
IFS, SQF or GLOBALGAP. This enables
the Turkish food industry to
export to all countries in the world.
In addition, the similarity of consumers’
preferences with Muslim countries
and the geographic and cultural
proximity to many European markets
allow Turkish food exporters
to penetrate international markets
easily.
However, the Turkish agriculture
and food industry export potential
is not limited with these products.
There are many other products that
are worth experiencing and these
are recommended to all consumers
in the world.
From all of the described products
above, it can be easily seen that Turkey
has become a big potential supplier
of various agricultural and food
products. It is apparent that Turkey
is likely to continue to develop her
trade with world markets as her
products become known and preferred
more and more in the future.
In the meantime, trade between
Turkey and the world markets must
not be solely limited to export and
import business; Foreign investment
is always welcome to Turkey. Joint
ventures in Turkey and other countries
are potential activities, which
are expected to be the major promoting
tool for enhancing trade relations
of Turkey.
20 FOOD TURKEY September/October 2018
Turkey to dodge the
brunt of global trade
wars
Turkey will not bear the brunt of
U.S.-instigated trade wars and could
stand to benefit, according to Ali
Osman Akat, chairman of the Turkish
American Business Association
(TABA).
“Compared with the great actors
of this crisis, as well as import and
export figures of major parties, Turkey
will be among the less affected
countries in trade wars,” Akat said., U.S. President Donald
Trump imposed a 25-percent tariff
Ali Osman Akat, Chairman of TABA
on imported iron and steel, and a
10-percent tariff on aluminum --
since then the issue has been discussed
heatedly between the U.S.
and its major trade partners.
As a result,.
Trump’s eagerness to spark 7.4
billion-worth of EU exports and of
this amount; the EU will rebalance
on $3.2 billion worth of exports immediately.
The U.S. government officially began
implementing tariffs worth $34
billion on Chinese imports, signaling
the start of a trade war.
The U.S.’ trade deficit with China
was around $375 billion in 2017.
22 FOOD TURKEY September/October 2018
Turkey’s poultry
production on rise
Turkey’s seasonally and calendar-adjusted poultry production
grew, year-on-year according to Turkish Statistical Institute
(TurkStat) data.
24 FOOD TURKEY September/October 2018
Turkey ranks eighth in the world for
chicken meat production. Approximately
2.1 million tons of chicken
meat and 54,000 tons of turkey meat
were produced in Turkey in 2016. All
poultry meats totaled 2.3 million tons
of poultry meat. The 2025 production
target is set at 3.5 million tons.
Turkey is established on an area of
783 thousand square kilometers connecting
Asia and Europe. Both climatic
conditions and geographical position
is convenient for agriculture and animal
breeding. In Turkish animal breeding,
poultry is the leading one of the
fastest growing industries.
The poultry industry started to develop
since 1950s and was dominated by
family businesses with expensive and
limited production capacities in 1970s.
In 1980s, it underwent a significant
structural change with the increase
in the number of the integrated facilities
and the implementation of contract
manufacturing model. This paved
the way to poultry industry to be a
major industry capable of carrying
out production planning and meeting
the national demand. In 1990s,
thanks to the big investments made,
poultry industry achieved the world
standards and came to the current
modern and developed situation with
the continuous increase in production.
Starting in 1995, the investments
in turkey breeding were completed
in a short time and made a breakthrough
in 1998. In early 2000s, the
poultry industry started EU harmonization
studies and in 2005 came to
a phase of the resolution to include
Turkey in the list of third world countries
from which the EU States may
import poultry products. 80 percent
(in the figures of 2004) of the white
meat and egg production of the country
is processed in modern facilities,
most of which are twenty year younger
than their peers in the developed
countries. Poultry industry ensures,
by way of export, a significant inflow
of foreign currency to the country
while it, as the healthiest and
cheapest protein, meets
the nutrition needs in
the country.
September/October 2018 FOOD TURKEY 25 poultry production - including
eggs, slaughtered chicken, and
chicken meat -- fell in June this year
on a yearly basis, the country’s statistical
authority announced..
26 FOOD TURKEY September/October 2018
Some 1.23 billion chickens and 5.1
million turkeys were slaughtered in
2017, according to the data.
In June, hen egg production in the
country inched down 0.7 percent
compared to the same month last
year, reaching 1.51 billion units, according
to the Turkish Statistical Institute
(TurkStat).
The institute stated that the number
of slaughtered chickens and turkeys
topped 102 million and 572,000
units, respectively. “The number of
slaughtered chickens decreased by
2.5 percent compared with the same
month of the previous year,” it said.
“The number of slaughtered turkeys
increased by 33.3 percent compared
with the same month of the previous
year.”
TurkStat said while chicken meat production
in June was nearly 179,000
tons, turkey meat production was
6,200 tons.
The institute noted that chicken meat
production fell by 1.3 percent in June
year-on-year, adding that turkey meat
production rose 37.8 percent on a
yearly basis.
September/October 2018 FOOD TURKEY 27
Factory investment
worth of TL 400 million in
Kadirli by Senpiliç
One of the biggest producers of Turkey, Senpiliç gets ready
for an investment of a slaughterhouse with 450,000 piece/
day capacity and a day feed factory of 579,500 meter annual
production capacity in Kadirli, Osmaniye.
One of the leader firms of Turkey in
the chicken manufacture, Şenpiliç exports
its annual 30 thousand tons of
production. Attaching importance of
growing healthy people of the future,
the firm possesses Halal Certificate
and all certificates that authorize to
export to European Union, Russian
Federation and Saudi Arabia. We talked
to İpek Üstündağ, Chairwoman of
the Board of Şenpiliç about details of
their new investment. Pointing out
that this investment would be followed
by hatchery farms as parts of
the integrated plant Üstündağ made it
clear that the investment would total
TL 400 million.
Where does Turkey stand in
the world poultry industry?
Turkey is in the major league of poultry
meat sector. The poultry meat sector
grows with the increase in population,
income and education level, and
urbanization. With an annual chicken
meat production around 1,8 million
tons, Turkey ranks 10th in the world.
We predict that this will increase to
a level of 2,5 million tons by 2025,
and the chicken meat consumption
per person will increase from 20,28
kilograms today to 27,8 kilograms by
2025. Export is booming in our sector.
Turkey’s name is now among the
major countries in international chick-
28 FOOD TURKEY September/October 2018
en meat trade. Turkey’s chicken meat
sector is expected to reach an export
figure of 1,5 billion USD over the next
5 years.
Can you tell us about
structure of Şenpiliç?
Şenpiliç is Turkey’s biggest chicken
meat producer with 18% market share
and its 320,000 tons/year production
quantity. As a pioneering brand in the
chicken sector of Turkey, we operate
with 24 breeding farms, 2 hatcheries,
2 feed plants, Söğütlü and Alifuatpaşa
slaughterhouses equipped with cutting-edge
technologies, and further
processing plant. Also have 800 contracted
producers, and contributes to
the Turkish economy by providing employment
to 3,074 people directly and
10,000 people indirectly.
İpek Üstündağ, Chairwoman of the Board of Şenpiliç
We carry out daily chicken meat distribution
and sales to 81 cities of Turkey
with its wide sales network. Distribu-
September/October 2018 FOOD TURKEY 29
tion is performed throughout Turkey
with GPRS vehicle tracking system to
19 regional directorates and 60 dealers
by Senpiliç frigorific fleet.
What is the export share in
your total sales?
Acceleration of exports in Turkey’s
poultry industry and international
trade of chicken meat no longer passes
among the big name, Şenpiliç also
raises its export figures. Currently
exporting 10% of our production, we
export over 30 thousand tons annually
to Iraq, Libya, Russia, Georgia, Africa,
Far East, Gulf countries and Turkic Republics.
Are your products halal
certified?
For the customers who demand ritual
slaughter of meat, requiring halal
certification, is strictly supervised in
Senpiliç slaughterhouses and exports
are made predominantly to Libya, Iran,
Iraq Africa and Azerbaijan. We have all
documents that authorize our company
to export to the EU, Russian Federation
and Saudi Arabia.
We always pay great attention in every
stage from production to the sale
point to provide healthy nutrition for
families.
What are your plans for 2019?
We continue with our growth for further
contributing to our country and
our sector, and strategically developing
ourselves with smart integration.
We are realizing our most recent 400
million TL investment at Kadirli, Osmaniye.
The increase in our export
momentum, the proximity of the region
to maize which is used as the raw
material for feed, and the logistics advantages
both in domestic market and
export have been influential in choosing
this location. In Kadirli, we are
planning to establish a slaughterhouse
with a capacity of 450,000 pieces/day,
as well as a feed plant with an annual
production capacity of 579,500 metric
tons in the first stage. This investment
will be followed with hatcheries and
breeding farms as a requirement of
integrated facility. The total amount of
investment will reach to 400 million
TL. Our Kadirli investment will generate
an ecosystem at a radius of 200
kilometers. We will make agreements
with 840 farms and provide a direct
employment to 3,500 people. As Şenpiliç,
we will continue to grow with
our producers and business partners.
And our Kadirli investment will have
a positive contribution to our steady
growth.
30 FOOD TURKEY September/October 2018
Erpiliç
wings and
flies to
success
One of the biggest
100 industrial
companies of
Turkey, Erpiliç
renders services
in compliance
with European
standards through
its modern
integrated
production
facilities as the 4th
largest chicken
manufacturer of
Turkey.
Erpiliç is one of the most respectful
names in the Turkish
chicken production business.
The brand is known for its
healthy and tasty products. That’s the
main factor lying on the success story
of placing the company among 100-
ten industrial companies in the country.
We learned more details for our
readers by asking some key questions
to Ömer Temel, Corporate Communication
and Advertising Manager of
Erpiliç.
Could you furnish our readers
with details about Erpiliç
which is among 100 largest
industrial firms of Turkey?
Chicken production and sales of Erpiliç
meet approximately 10% of the
market share. Having the first industrial
‘dry-plucking’ technology Erpiliç
makes 100% hand-slaughtering in
accordance with Islamic rules under
the supervision of food engineers
and expert veterinarians and now
produces 500 thousand tons of feed
at its 3 feed factories. Having a wide
portfolio in growing breeder pullet
Erpiliç has 3 growing and 15 breeding
pullet production facilities in three
different regions as Göynük, Mudurnu
and Bolu. These plants realize 1 million
100 thousand breeding pullets in
115 chicken coops on a covered area
of 179,000sqm. With these facilities
Erpiliç offers 2 million 560 thousand
chicks to the grower in the field.
Aiming at becoming one of the leading
poultry producers worldwide by
offering only the best quality products
to consumers, Erpiliç began its
production process with 200 chicks
in 1969 and continued its operations
from 1991 through 1994 under Er
Civciv Inc. Subsequently, in 1995 the
32 FOOD TURKEY September/October 2018
first steps of the integration were
taken with establishment of ERYEM
SAN. a feed company. Currently, Erpiliç
trades with a strong workforce of
3000 employees, 1400 producers and
71 dealers.
Erpilic, the 4th largest chicken producer
in Turkey, operates in modern
integrated facilities in Bolu / Gönyük
and Bolu / Merkez, completely within
nature.
Breeders, Hatcheries, Feed Factories
and Slaughterhouses combine
quality and taste with high technological
infrastructure and structure
in EU standards. Erpilic adds social
and economic value to Turkey with
its 1414 contract manufacturers, 210
subcontractor subcontractors, 93 frigrophic,
117 livestock transport, high
quality standards with ISO 22000, ISO
18001-2008, ISO 14001, ISO 9001-
September/October 2018 FOOD TURKEY 33
2008, TSE Certificate, TSE HELAL
Certificate, GIMDES Halal Food certificates,
61 fodder transport and fleet
of 3000 people consisting of young
and qualified staff.
Could you mention about
the product range of
Erpiliç? Please give us some
information your capacity and
plant?
integrated production facilities are
a giant organization with 400 thousand
chick cutting capacity per day. In
Erpiliç, all 400 thousand chickens are
produced with 100% Dry Pluck and
100% cutting by hand process. It offers
its consumers 100% health, flavor,
hygiene, quality and confidence in its
products in 70 national dealers and
many sales points as well as in big national
chain markets and local market
chains in Turkey.
What are your basic criteria
and the system you apply in
production?
Our production plant has been certified
with HACCP Food Safety Certification
in addition to ISO 9001-2000
Quality Management System Certificate,
ISO 22000-2005 Food Safety
System Certificate, compliance certificates
with TSE Standards and the Export
Advance-Fixing Certificates
Our production facilities possess
HACCP Food Safety certificate in
addition to ISO 9001-2000 Quality
Management System Certificate, ISO
22000-2005 Food Safety System Cer-
34 FOOD TURKEY September/October 2018
tificate, TSE Certificate, and Export
Prior Consent documents.
Our never gives up on its high quality
approach, and thus, regularly invests
on technology and human resources;
and as a result carries on its business
activities while increasing its market
share coupled with a consistent
growth trend. By making quality and
safe production in hygienic conditions,
personnel health and education continues
to operate with the policy of
continuingIt contributes to the country's
economy by producing in rural
areas with environmentalist approaches
and adopts universal food safety
principles.
Ömer Temel, Corporate Communication and Advertising Manager of Erpiliç
What will you say about halal
slaughtering?
In Dry Pluck method, applied by Erpilic
for the first time in Turkey, hot water
boiler is no longer used to soften the
hair of chicks. In the new Dry Pluck
method, instead of being immersed in
the hot water boiler, the chicks feathers
are loosened by passing through
moist hot air tunnels. The softened
feathers are cleaned with the help of
automatic pluck machines without a
human contact.
In the method of Dry Pluck, since
the chickens are not immersed in the
same hot water boiler, bacteria, dusts
and necassets which may cause cross
contamination between the chickens
by contaminating each other with
September/October 2018 FOOD TURKEY 35
water, do not lead to negative transitions
and a more hygienic product is
obtained.
Due to the low formation of bacterial
burdens, chickens reach their final
destination before carrying any health
risks within the cold chain conditions.
Which countries do you
export?
We are exporting mainly to Libya, Syria,
Qatar, Georgia, Turkmenistan, Tajikistan,
Iraq, Saudi Arabia, Oman, Jordan,
United Arab Emirates, Kyrgyzstan, Liberia,
Ghana, Azerbaijan, TRNC, Angola,
Gabon, Guinea, Democratic Congo,
Hong Kong, Vietnam, Benin, Bosnia
Herzegovina and Haiti.
Which fairs do you attend at
home and abroad?
We participate two largest international
fairs of the World such as
in SIAL Paris and Anuga Cologne. In
domestic market you can find us at
OSMED Antalya, Yerel Zincirler Buluşuyor
Istanbul.
Turkey consumption is
rather lower than chicken
consumption in Turkey. What
are you planning to do to
increase this rate?
Having 24 years of experience in the
sector to produce an annual average
of 1 million turkeys representing 27%
market share Bolca Hindi was acquired
by Erpiliç and now Erpiliç reaches
to the consumers with this production
power, logistic infrastructure and
widespread dealer network in healthy
turkey industry. Erpiliç’s investing in a
domestic brand in its own geography
with an approach of “national capital,
national growth” at a time when economic
stagnancy prevailed has been
considered very important for the national
economy, for the poultry meat
sector and for the consumers.
36 FOOD TURKEY September/October 2018
Bolca turkey products are now
under Erpiliç halal quality.
Bupiliç stands
for poultry
meat
Bupiliç offers not
only products but
also health and
safety with a wide
supply network
from Bosnia
Herzegovina to
Hong Kong.
Taking part among the 500
largest companies Bupiliç pulls
attention with its investment
decision as well as its grow rate in the
poultry sector. Mehmet Yavuz, Member
of the Board of Bupiliç, underlined
that they set sails to big targets by saying,
“Conscious of realities of the industry
Bupiliç is aware of the fact that
growth is only possible by standing
straight and being permanent in the
sector. The 100% growth we realized
during last 4 years our guarantee to
accomplish our plan of growing 100%
next tree years.” We listened details
of their success story from Mehmet
Yavuz.
Could you furnish our readers
with details about Bupiliç
which is among the first
largest 500 companies of
Turkey?
Mehmet Yavuz, Member of the Board of Bupiliç
Bupiliç kurulduğu 2004 yılından itibaren
büyüme yolunda attığı emin
adımlarla kanatlı sektöründe adından
sıkça söz ettiren 180 bin adet kesim
kapasitesine sahip Türkiye’nin 396’ncı
büyük sanayi kuruluşudur. İstihdam
ettiği 810 personel ile bulunduğu
bölgenin en ciddi işverenlerinden bir
38 FOOD TURKEY September/October 2018
tanesidir. Aynı zamanda %44 bayan
istihdamımızla bölgemizde dikkat
çekiyoruz. Damızlık tesislerinden
sofralarınıza tam bir entegre yapıya
sahip, 60 ton/saat kapasiteli bir yem
fabrikası sektördeki en kaliteli yemlerden
birini üretmekte olup en ucuz
hayvansal protein kaynağı olan piliç
etini, en hijyenik ve güvenli yollarla
tüketime arz etmektedir.
Since its foundation in 2004, Bupiliç
has always made its presence felt with
safety steps in the way to growth is
396th largest industrial establishment
of Turkey with a slaughtering capacity
of 180 thousand. It is one of the most
curious establishment of the region
with 810 personnel it employees.
At the same time we pull attention
with employing 44% woman. Having
all necessary integrated facilities from
breeding plants to the dining tables
of the consumers our company has a
feed factory with a capacity of 60 ton/
hour to produce most quality feeds.
We offer the least expensive protein
source as chicken to the consumer at
most hygienic and safety ways.
What will you say about halal
slaughtering policy of Bupiliç?
Bupiliç is a company whose compliance
with halal slaughtering has been
certified with Halal Production Documents
and has been a sought after
brand in Muslim countries.
What do you do to offer
healthy products?
Alanında uzman veteriner kadrosuyla
sürekli olarak hayvanlarının sağlığını
gözeten tüketici sağlığını en üst sırada
tutan Bupiliç, Avrupa Standartlarındaki
hijyen koşullarıyla %100 güvenli
gıda mottosuna sahiptir. Bu konuda
tüketicilerimize üst düzey güven veren
bir firma olmanın haklı gururunu
yaşıyoruz.
Taking maximum care for the health
of the animals with expert veterinari-
September/October 2018 FOOD TURKEY 39
ans and prioritizing human health Bupiliç
has 100% safety food motto with
hygiene conditions at European standards.
We take pride of our well-established
utmost confidence by the
consumers.
Which countries do you
export? What are your target
markets?
We are an active actor of the white
meat industry with our wide supply
network from Bosnia Herzegovina to
Hong Kong. Our top tree export customers
are Iraq, Libya and the UAE.
What will you say about
growing policy of your
company?
We have a goal of fulfilling our mission
in Turkish economy with an export
volume of reaching around 25 million
dollars by the end of 2018. We are taking
secure steps for our future goals
with an infrastructure investment of
TL 20 million and a second slaughtering
line of 12,000 pcs/hour. With this
new slaughtering line, which is planned
to be operational by the end of 2020,
we blink to the upper levels of the industry.
Consumer habits direct
the food sector. Are you
considering to add new
products to your product
range portfolio?
Bupiliç is one of the firms that will play
an important role in the development
of Turkey with the new investment initiations
on its agenda. Proceeding with
the purpose of realizing further processing
production in the near future,
Bupiliç will secure its position in view
of consumer with its new products
soon.
How do you evaluate Turkey’s
position in the poultry sector
and location of Bupiliç in the
industry?
Positioning itself as the 8th largest
chicken producer, Turkey is one of
the most leading countries supplying
the region with protein with 1 million
958 thousand tons of chicken meat. It
is clear fact that the country will go
up to better level step by step with
ever continuing new investments. We
take pride of observing the demands
for this protein source we offer to our
nation and for surrounding nations on
the way we, as Bupiliç, set up in 2004.
40 FOOD TURKEY September/October 2018
Tavuk Dünyası is
‘recommended to all
consumers’
Tavuk Dünyası is
‘Recommended to All
Consumers’ within the scope
of the “Golden Brand Awards”
of EU Consumers Protection
Foundation. Tavuk Dünyası
had been deemed worthy of
the same award back in 2013,
too.
42 FOOD TURKEY September/October 2018
Tavuk Dünyası, which created a difference
in the food & beverage industry
and opened a brand-new field, is
named as ‘the brand to be recommended
to all consumers’ by the EU
Consumers Protection Foundation
(TTKD). Thus, Tavuk Dünyası is certified
with ‘Golden Brand’ title and ‘Recommended
to All Consumers’ label.
At the end of the assessments, Tavuk
Dünyası took its place among ‘the
brands that receive least or none
complaints’ in 2017. And since Tavuk
Dünyası is qualified to be recommended
to all consumers in this sense
and it is aimed to contribute to its
brand value, TTKD jury declared it
a brand to be ‘Recommended to All
Consumers’ in the restaurant category
for ‘September 2018’.
Thus, “Tavuk Dünyası” gained the
right to use the logo and certificate
of “2018 Golden Brand” and “Recommended
to All Consumers.”
In the “Respectful Brand Awards” ceremony
held in the 32nd anniversary
of TTKD, the brands producing high
quality products in various industries
such as food, clothing, cosmetics and
furniture were rewarded with ‘Recommend
to All Consumers’ logo and
certificate. Tavuk Dünyası was awarded
in the restaurant category with this
logo and certificate.
Volkan Mumcu, CEO of Tavuk Dünyası,
made a brief statement regarding this
honor: “Tavuk Dünyası that opened a
brand-new field for itself in the food
& beverage industry managed to attract
the attention of everyone within
a short time frame like 6 years with
its unique concept. With the flavors
that we prepare and present based
on taken from the different cuisines
of the world and the services that
we offer in the pleasant restaurant
atmosphere making our guests feel
comfortable and special, we have carried
our customer satisfaction level to
96%. With this award that we won in
the ‘Respectful Brand Awards’, we are
pleased to prove this success once
again.”
September/October 2018 FOOD TURKEY 43
New
logo and
packaging
of Kilikya
The human-oriented production
concept of Kilikya is highlighted by the
moving human form used in the letter
“i”. Kilikya crowned its brand journey
that started in 2006 and renewed its
logo and packaging in 2018 and presented
its products to its customers
in new packages. While the packaging
that has already taken its place
in the shelves has received positive
feedback from the consumers, the
new logo and packaging labels have
attracted the interest of the consumers.
The letters i in the newly designed
Kilikya logo and the human-oriented
production concept of Kilikya were
brought to the fore with the moving
human form used in the letters i. The
essence of the design of the Kilikya
bottle label was the brand’s leading
feature. A label design was developed
that reflects the vision of the company
that is beyond the borders of
Kilikya. A portion of the Kilikya logo
appears on the label, while the other
part that does not fit the label carries
the new horizons like dreams.
Since its establishment in Turkey and
meet the expectations of customers
around the world Kilikya continues to
develop its product portfolio.
Kilikya is moving towards becoming
the leading beverage company with
its superior quality and taste to produce
100% customer satisfaction by
producing high quality and delicious
products that the customer always
trust.
Kilikya Turnip has been offering a wonderful
drink experience for consumers
made of purple carrots, varieties
of peppers, garlic and red pepper in
its renewed packaging. In addition to
glass and pet bottles, it also offers you
a healthy gift alternative that you can
give to your friends in the form of a
group of stylish gift packages.
Exporting to more than 30 countries,
Kilikya Turnip has renewed all the packaging
of nearly 100 products including
Organic turnip, Special turnip, Lemonade,
Ice tea, Lemon Sauce, Grape Vinegar,
Apple Vinegar, Balsamic Vinegar,
Pomegranate Vinegar, White Vinegar,
Turşukur, 100% Natural Pomegranate
Sour, Pomegranate Sauce, Hot Pepper
Sauce, Vinegar Sauce, Soy Sauce, etc.
44 FOOD TURKEY September/October 2018
and they are ready to take their place
on the shelves with a brand new image.
Since 2007, Kilikya Turnip has been operating
in Adana Organized Industrial
Zone in a factory having 16,000 sqm.
open area and 7,500 sqm. closed area
with a monthly production capacity of
3 million liters.
In addition to the leadership in the
production of turnips, sauce and beverage
industry, Kilikya Turnip, one of
the leading manufacturers with its
production capacity, with plants and
export potential, is among the major
companies in Turkey.
Having annual production capacity
of 36 million liters and an extensive
distribution network that organized
in 9 distribution center Kilikya serves
to 95% of the market in Turkey. Products
are exported to more than 30
countries around the world such as
Europe, America, Russia and Far East.
Kilikya Turnip, having high quality standards,
customer satisfaction, leadership
position in the market, innovative
perspective, technological infrastructure,
R & D investment, high-quality
and safe products continues to produce
an indispensable beverage consumption
habit of turnips.
September/October 2018 FOOD TURKEY 45
Safya never
compromises on
purity
With the motto “pure sunflower
oil”, Safya reinforces its place
in the market by increasing its
sales in the domestic market
and exports by more than 50%
compare d to the data of the
previous year.
Aves is one of the most
leading sunflower oil suppliers
of Turkey known-for
its healthy and tasty product
Safya is attending SIAL Paris to
display its competitive products. We
conducted an exclusive interview
with Kemal Güven, Sales and Marketing
Director of Aves, for details
of their success story. Full text of the
interview follows:
Aves only assumes %35 of
oil supply of Turkey. What
would you say about the
development of the company
in the sector?
Kemal Güven,
Sales and Marketing Director of Aves
With more than 20 years of experience
in international commodity
trade, AVES Inc. operates in the
production and international trade
of vegetable oils, biodiesel production,
warehousing, and real estate
sectors. From 2012, focusing entirely
on agricultural commodities, particularly
oil seeds and the trading of
vegetable oil, Aves has completed the
installation of a fully integrated oilseed
processing and biodiesel plant
of Turkey in 2013. With multiple oilseed
processing, refining, filling and
biodiesel plants, being the sole plant
established in an integrated structure
rarely seen even in Europe, Aves undertakes
the 35% of raw oil supply
of Turkey. Within the framework of
this integration, Aves continues its
domestic and export packaged, bulk,
branded, subcontracted and PL sales
without losing its pace, shows growing
trend in the sales graphs since
the day it was established. According
to the data of 2017, the company
has ranked 225th in the ranking of
ISO500 with a growth rate of over
30% in product sales.
Could you mention about
your product range,
production capacity and your
facilities?
The plant working fully integrated
with crushing, refining and filling facilities,
high protein value oilseeds such
as soybean, sunflower seeds, canola,
safflower, flax, and cottonseed are
processed. Besides edible crude oil,
being one of Turkey’s leading biodiesel
producers, Aves produces renewable
46 FOOD TURKEY September/October 2018
energy from oilseeds such as canola,
soybean, and safflower. Equipped with
the state-of-the-art Desmet Ballestra
technology, the plant produces
450,000 tons of crushing, 210,000
tons of refining, 300,000 tons of filling
and 50,000 tons of biodiesel with a
total annual production capacity of 1
million tons.
Could you give us information
about oil production
processes? Which processes
do they go through?
With the motto Safya “pure sunflower
oil”, reinforcing its place in the marbant-foodturkey-BSK.pdf
1 16/10/2018 16:25
In the plant operating with the “Field
to Table” principle, the raw material
is processed according to TSE and
AOCS methods, and then the products
are stored for production. Refining
processes such as neutralization,
bleaching, wintering, and deodorization
are applied to the crude oil obtained
by breaking and pressing the
stored oilseeds. After the filling process,
the oils are packed and ready
to be presented to the consumer. At
the last stage, Aves Inc. performs biodiesel
production in its fully integrated
plant with the waste oil collected
from the consumers.
When you look at the current
situation of your brand what
would you say about its
position and its share in the
industry?
ket by increasing its sales in the domestic
market and exports by more
than 50% compared to the data of
the previous year. Safya brand, which
is sold in more than 50 countries and
registered in more than 20 countries,
is increasing its place and availability in
the domestic market. With the commissioning
of Erbil Plant in 2015, Safya,
which is a sought after brand in the
Middle East, is taking firm steps towards
branding.
Could you mention about
your R&D activities? What
do you think about add new
products to your product
range?
At the beginning of this year, Aves Inc.
allocated a budget of approximate-
September/October 2018 FOOD TURKEY 47
ly TL 2 million for the R&D center,
where 22 engineers continue to develop
their projects within the scope
of zero waste target. These projects
are very important projects to reduce
carbon footprint, increase competitiveness
and increase energy efficiency
in terms of both the country and
company resources.
In the largest capacity oilseed processing
plant in Turkey, we have no new
product target where we process
almost all oilseeds such as soy, soybean,
sunflower seeds, flax, safflower,
cottonseed. Our goal is “Zero waste”.
In other words, to obtain by-products
from everything with high added value
and to increase energy efficiency.
Which countries do you
export? How many countries
do you export in total and
which regions dominate?
AVES Inc. which mainly sells to the
Middle East and the Asia Pacific regions
and the United Nations, develops
its export network day by day
with the same quality guarantee offered
in the first and one-millionth
bottle. Exports are made to more
than 50 countries.
Which fairs do you attend at
home and abroad? Do you
have any surprises for your
visitors in SIAL 2018?
In order to diversify the market and
develop our customer portfolio, we
attend 6 fairs abroad each year. Trade
fairs in different geographies such as
China, Ethiopia, and Paris are contributing
significantly to the increase in
brand awareness, the realization of
big sales and to our goal of becoming
an international brand. At SIAL Paris,
we aim to meet our vast experience
in sunflower oil sector and our products
that we never compromise on
purity and quality with our customers.
You raise the bar in the
Turkish sunflower oil industry
day by day. What are your
goals to increase your market
share in short, medium and
long terms?
Our next target will be branding. To
increase the awareness and availability
of Safya, distinguished as a pure,
additive-free, light, affordable brand,
in the Turkey market. We will not
leave a city that Safya has not reached
by strengthening our distribution in
all channels. Our goal is to be the 3rd
brand in the sunflower oil industry
within 3 years.
48 FOOD TURKEY September/October 2018
Akanlar
Chocolate&Drink
on the way be a
preferred and leading
world brand
Akanlar Chocolate
& Drink’s products
are demanded by
many countries.
The company
aims to be a
preferred brand at
7 continents.
Having the respectful position with
various products at home, Akanlar
Chocolate&Drink products are quite
liked at abroad also. The firm grows
its product portfolio and increases an
international success bar day by day.
We interviewed about developments
and innovations within the firm with
Ramazan Akan, General Manager of
Akanlar Chocolate & Drink prior to
SIAL Paris.
Could you brief us about
sectoral trip of Akanlar Gıda?
Having started our business activities
with food wholesaling at home in
1978, we continued to start to foreign
trade in 1992. We, as Akanlar Chocolate&Drink,
produce chocolates,
coffee, bullion and fruit aromatized
powdered beverages and export to
35 countries in total. We adapt to
emerging markets day by day.
Could you mention about
your product range and
production capacity?
50 FOOD TURKEY September/October 2018
We produce chocolates, powdered
beverages, coffees, bullions and fruit
aromatized powdered beverages. Our
annual chocolate production is 9000
tons, powdered beverage is 2500 tons
and coffee production is 1000 tons.
What are your main criteria
in production?
We produce by using quality raw materials
and latest technology with our
experienced technic and experienced
team without compromising on quality
under completely hygienic conditionals.
We adopt it a principle to satisfy
the customer by empowering our
capacity and to provide confidence to
our customer in domestic and international
markets.
Are you considering to add
new products to your product
portfolio? What are the
innovations waiting for us on
the shelves?
You will especially see our spreadable
cream cholate products such as Akella
Carob and Akella Macha Tea (Japanese
Tea).
What are the main points
differing from others?
We adapt a modern management,
continuous improvement and innovations
with an understanding of prioritizing
consumer satisfaction and
accept the quality as a part of our life
to achieve big goals quickly. The main
condition in all of our products and
services is to reach the maximum level
on the quality in the direction of total
quality management standards. We
believe that we can obtain our competitive
power with mass and high
quality manufacturing. The success will
be of all of our personnel.
Which countries do you
export?
We export to the USA, Romania,
Chad, Nigeria, Niger, Jordan, Palestine,
Ramazan Akan, General Manager of Akanlar Chocolate & Drink
Iraq, Syria, etc. We produce by combining
a modern production system
and qualified, improving power of
ourselves with our experiences coming
from the past. Our goal is to be a
preferred leader brand at 7 continents
with quality and delicious products
that are produced adding our love.
Could you mention about
your R&D activities?
We won Tubitak Award with Akella
Spreadable Cream Cholate. Our activities
on this and developing similar
products are underway.
September/October 2018 FOOD TURKEY 51
Which fairs do you attend at
home and abroad? What are
the surprises awaiting your
visitors in Sial Paris?
We attend to CNR Food Istanbul,
Gulfood Dubai, ISM Cologne, Sial Paris,
etc. We have new activities and we
have developed new products. We will
display them at the fair for our visitors.
How do you evaluate the
Turkish food industry in
general?
Production of food materials is an
important part of Turkey’s economy.
Almost 20% of the gross domestic
products of Turkey comprise of the
food and beverage industry and this
rate seems to increase more. When
examined on local basis the food industry
of Turkey is quite strong. If you
look at the world food industry in a
wide perspective, international brands
have a big rate in the market.
What are your targets for
expanding your market share?
Adopting “Quality food is the right of
everyone” as a mission our firm, which
uses top-quality raw materials and latest
technologic machinery and equipment
and produces the most delicious
foods, aims to have a part of happiness
of people.
Are there any developments
to highlight you have realized
recently?
We will work to move our brand
up to among the leading ones in the
chocolate world with our Macha Tea
and Akella Carod spreadable cream
cholate.
52 FOOD TURKEY September/October 2018
Candied
Chestnut
sweetens the
world
Chestnut sweet is
one of the symbolic
products produced
locally in Bursa and
sold globally. One of
the major producers of
chestnut based sweets
and desserts in Bursa is
Kardelen (Cardelion)
Company of which
official name is Ilka
Sekerleme.
54 FOOD TURKEY September/October 2018
"32 years with apron!"
Mümin Akgün, General Manager of Cardelion
İlka Şekerleme Mamulleri ve Gıda
Sanayi is one of the leading producers
of candied chestnuts and
chestnut by-products in Turkey
having attained the first ISO 22000-
2005 certification in the sector. The
company has recorded domestic and
international successes and built up a
respectful brand. We asked the details
of their success story to Mümin Akgün,
General Manager of Cardelion:
While the chestnut is not a
product peculiar to Bursa it
has been one of the tastes
that are identified with Bursa.
Contribution of Cardelion
Candied Chestnut in adding
value to Bursa is tremendous.
Could you brief us about
your firm for our readers get
familiar with your company?
In fact, chestnut is a fruit peculiar to
Bursa. Chestnut trees in Bursa have
dried in the last 30 years due to a
bacterial disease. In the meantime, instead
of tending the rest of the trees
in their villages, young farmers living
in the area have moved to newly
emerging industries in the city, at the
end of it, population of chestnut trees
went down. The bacterium has killed
itself while killing our trees, so nature
has found its own solution. We hope
that chestnut trees will be proliferated
in the future and sufficient amount
of fruits will be available in Bursa. Candied
Chestnut is a natural result of this
cultural element. In the past, chestnut
had been preserved and consumed in
villages, as in all other fruits, either directly
or as a jam-like sweeties made
by using grape molasses instead of
sugar. This centuries old tradition has
turned into an industry in the 80’s. In
1991, our company was established
for the production and sale of chestnut
sweetie. In 2007, we moved to
our new facility in the Yaylacik neighborhood
of Nilufer, Bursa. Here we
produce a labor-intensive production
in a very decent and hygienic environment
where we blend traditional production
and technology. Apart from
the classic candied chestnuts, we also
produce various chestnut and other
industrial crushes and purees. The
products we produce are offered to
the appreciation of our valuable consumers
in our retail stores in Turkey
and Saudi Arabia.
September/October 2018 FOOD TURKEY 55
What would you say about
Turkey’s position in candied
chestnut production?
As I have already said at the beginning
Turkey has Europe’s largest chestnut
reserves. However, the market
for chestnut candies is controlled by
French companies worldwide. Italian
companies and some French companies
produce candied chestnut. Of
course, the chestnut processing technology
and raw chestnut and peeled/
frozen chestnut market is still in the
hands of Italians. Turkey, unlike the
world markets, has an active market
for 12 months. Classic Turkish chestnut
candy is sold fresh in the refrigerator
if it is not canned. French products
are relatively durable due to the
higher sugar level but they have not a
genuine chestnut flavor. By considering
the scale of our differences, we can
say that the chestnut market in Turkey
is comparable to Europeans but unfortunately
we have to improve our
technology and marketing skills and
abilities.
Could you mention about
your product range,
production capacity and your
facilities?
Our company is the first company in
Turkey having the food safety certificate
among chestnut producers. We
received our ISO22000: HACCP certificate
in 2008. This is normal for our
success, when the hygiene and the
quality of our production. We have
been fully complying with the requirements
of this document since 2008
and we have been well known among
our peer businesses in terms of hygiene
conditions of our production
facility even and even landscape gardens
we have at the factory. The fact
that every product coming out of this
facility is produced with right is the basic
and absolute priority for us. So this
is reflected in our rich product range;
we currently have chestnut candy,
chocolate chestnut candies, chestnuts,
porridge and boiled chestnut products
for homes. We have a wide range
of packaging suitable for every purse,
serving various purposes. Our consumers
and the public can easily check
our products and prices from our virtual
store can order at costs including
the shipping fee. Finally, let’s talk about
our capacity; capacity issue is not a
situation that can be fully explained
because the machines from different
fields are able to produce only limited
amount of chestnut products.
What are your main
strategies in production and
management? What kind of a
policy have you applied during
your production period?
There are two main topics in terms
of production; the first is to work
whole year around with restricted
raw material. The chestnuts that we
buy in November-December season
are peeled and put in the freeze, that
are processed all year round. First of
all, we should be aware of this because
we can replace every chestnut
we waste only the following year. The
second main subject is very simple;
Price is forgettable but quality always
remembered! I think we can base our
growth in Turkey on these two major
topics. Although production of chestnut
candies is a labor-intensive activity
we have brought all the technology
56 FOOD TURKEY September/October 2018
and machinery necessary for the production
to our company. Still, we have
a heavy investment plan by the year
2021. We want to be a more powerful
brand in retail side as well.
Could you give us information
about candied chestnut
production processes? Which
processes do they go through?
The priority of this process is to start
with the right raw material to suit this
job. The physical properties of raw
chestnut as well as its natural chemical
content; that is, the altitude of the tree,
shell thickness and ease of peeling, are
important. We sort them according to
their size and keep them in our refrigerated
facilities. The first chestnut is
robbed and frozen in our own structure
and frozen and then the cycle of
process is spread to the days up to
the end of the confectionery process.
Even if we use machinery 30 people
are working on this line. Confectionery
process is extremely hard and
labor intensive. The big chestnuts are
selected one by one carefully, 4-5 of
them are put in the cheesecloth then
boiled several times in these swaddles
and boiled water for a long time in a
thin sugar syrup in industrial pressure
cooker. Chestnut candy, which has
been rested for 2-3 days in its own
syrup, is then ready to eat. This can be
a simple explanation for classic chestnut
candy production. Of course, there
are also packaging processes. Even the
food manufacturers who come to visit
us, are admirable and concerned.
Timely delivery of right
product is important as much
as production. Which way do
you usually ship your products
to export market?
In recent years, the product is becoming
far from being a commodity. The
production facility of the product, the
documents that the plant holds and
the requirements it has fulfilled, the
fulfillment of the social responsibilities,
the store where the product is
displayed, the visual elements in the
presentation, the costume of the personnel,
the design of the package and
even the packaging used back suitability
for conversion, fashion colors and
color palette uses, the paper and the
derivative of the sachet you use is nature
friendly, smiling face during and
after sales, etc. all mean the value offered
to the customers as a whole. Believe
me that the product is not only
a simple manufactured material, but is
much more. Service side is also extremely
important including the shipping
and delivery. Logistics companies
that we work with praise us for even
the regular compilation of the load,
even the care we paid while ordering
in the list of delivery documents. Export
is not only the key to economic
growth but is the gate itself. Our department
of exports is working with
this awareness; we are struggling to
overcome the negative perception of
Turkish products. Thankfully, we have
always been proudly successful in this
struggle. Shipping is very sensitive and
risky business. We prefer the highway
transportation on the European route,
and we ship products by air to almost
September/October 2018 FOOD TURKEY 57
all the remaining routes. We are also
sending products to our stores in Saudi
Arabia on air as refrigerated.
Which countries do you
export? How many countries
do you export in total and
which regions dominate?
Total countries that we export are
approached 40, including Saudi Arabia,
USA, Canada, Switzerland, and France.
There is also an spontaneous buyers;
We sent goods to Malaysia in this way.
In recent years, I can say that, Western
Europe and Gulf countries come
fore, we have surprise markets such
as Brazil and Australia, which receive
products once a year. Of course, a
considerable amount of our exports
are delivered to our stores in Saudi
Arabia. We will continue to expand
in Gulf countries, but under economic
conditions, this is not an urgent project.
Are there any new markets
your aiming with a special
policy?
I have said that French products dominate
the world market, so, we have
decided to increase the share of our
Cardelion brand in the global market.
Cardelion is a brand whose main language
is French and has European visual
elements in its brand conception.
There are sales in the Gulf countries,
of course, but emphasis is on Cardelion
and we address more easily to
Western markets. Another strategy is
our Private Label works. We see that
we have successfully grown with discipline
and diligence.
Is candied chestnut suitable
for R & D activities? Do you
need to consider adding new
products to your portfolio?
Frankly I do not want to give too much
detail about our R&D works. Chestnut
candies are now traditional products
both in Turkey and in Europe. It is as
much an innovative product as others
such as baklava, shobiyet, dry beans,
and rice. I hope I can tell what I mean.
Packaging technology and automation
are another matter. We’ve recently
launched several products, I think now
it is the time to evaluate their performance,
not the time to make new
products.
Which fairs do you attend at
home and abroad? You have
been participating in Sial Paris
for many years. What are your
expectation from Sial 2018?
Do you have any surprises for
your visitors?
Yes, we have attended many fairs for
many years, Sial Paris is one of the fairs
as if we were married. We have a very
pleasant surprise at this fair; Kirpis will
meet the consumer. Kirpis Kardelen
is a mascot of our brand of chestnut
candies. For a long time in the media,
the Hedgehog Family has come to life
with our cartoon stuffed toy. Let’s not
boil down the surprise and talk about
the surprise we’ve had; costs of overseas
exhibitions have risen remarkably
because of the incredible rise in
exchange rates. In my opinion, UIB,
BTSO, TIM, IGEME, KOSGEB and related
media should be taken in certain
measures in this regard.
What are your goals and plans
for short run?
In the near future we want to complete
our investment program with
most efficiently and successfully. Unfortunately,
in the following economic
conditions, we must focus on maintenance
and sustainability.
Anything would you like to
highlight?
I wish everyone a lasting and endless
success in the SIAL Paris exhibition
and export markets. We should not
forget that the regaining the health of
our economy depends on our efforts
in exports.
58 FOOD TURKEY September/October 2018
Turkey offers significant
investment opportunities
in agribusiness subsectors
As part of its
targets set for the
agriculture sector
by 2023 Turkey
aims to be among
the top five overall
producers globally.
Turkey has a robust agriculture and
food industry that employs almost
20 percent of the country’s working
population and accounts for 6.1 percent
of the country’s GDP.
The strengths of the industry include
the size of the market in relation to
the country’s young population, a
dynamic private sector economy,
substantial tourism income and a favorable
climate.
Turkey is the world’s 7th largest agricultural
producer overall, and is the
world leader in the production of
dried figs, hazelnuts, sultanas/raisins,
and dried apricots. The country is
also one of the leading honey producers
in the world. The recent data
indicate that Turkey boasted production
of 18.5 million tons of milk,
making it the leading milk and dairy
producer in its region. The country
also saw production totals of 35.3
million tons of cereal crops, 30.3
million tons of vegetables, 18.9 million
tons of fruit, 1.9 million tons of
poultry, and 1.2 million tons of red
meat. In addition, Turkey has an estimated
total of 11,000 plant species,
whereas the total number of species
in Europe is 11,500.
This bountiful production allows Turkey
to maintain a significantly positive
trade balance thanks to its position
as one of the largest exporters
of agricultural products in the Eastern
Europe, Middle East, and North
60 FOOD TURKEY September/October 2018
ZEYTİN, ZEYTİNYAĞI,
SÜT ÜRÜNLERİ, ŞARAP VE
TEKNOLOJİLERİ FUARI
Olive, olive oil, dairy products
wine & technologies fair
6-9 MART
MARCH 2019
Yer / Meeting point:
fuarizmir
DESTEKLEYENLER (SUPPORTERS)
THIS FAIR HAS BEEN ARRANGED ACCORDING TO THE LAW OF 5174 BY TOBB (TURKISH UNION OF STOCK EXCHANGES AND CHAMBERS)
Africa (EMENA) region. Globally,
Turkey exported 1,781 kinds of agricultural
products to more than 190
countries accounting for an export
volume of USD 16.9 billion.
Turkey is looking to position itself as
the preferred option for being the
regional headquarters and supply
center of top global players in the
agricultural sector. To encourage
investment in the sector, Turkey:
•USD 150 billion gross agricultural
domestic product
•USD 40 billion agricultural exports
•8.5 million hectare irrigable area
(from 5.4 million)
•Ranking number one in fisheries as
compared with the EU
62 FOOD TURKEY September/October 2018
Aktaşlar Lezzet Grubu
introduces Turkish pitta
bread to the world
Established in 1981 Aktaslar Lezzet Grubu keeps it’s
growing with Nelipide in restaurant concept, with Pideor
in fast food concept and with frozen foods in exports.
Shipping its products under the names Nelipide, Aktaslar
and Pidemiss to many parts of the world, Aktaslar Lezzet
Grubu takes the pride of welcoming demands from many
countries
64 FOOD TURKEY September/October 2018
Tamer Aktaş, Chairman of the Board of Aktaşlar
Aktaşlar overflows its domestic
success to foreign
markets by directly exporting
and through its
branches opened abroad. Broadening
its markets every day Aktaşlar has a
major aim to promote Turkish pitta
bread to the world as a known and
sought after taste. We conducted an
exclusive interview with Tamer Aktaş,
Chairman of the Board of Aktaşlar, prior
to SIAL Food Fair.
You, as Aktaşlar Lezzet Grubu,
have been going through a
new structural process. How
is that process going and
how many branches have you
already set up?
As you know, Aktaşlar Lezzetler Grubu
was founded in 1981. We started
to produce various kind of the pitta
breads with branching works and
various investments after 2001. We
manufacture our non-additive products
in Ordu, Turkey. Currently we
have 3 branches in Ordu and 2 in
Istanbul. Our two branches are located
in Beşiktaş and Bomonti with our
fast food and franchise brand Pideor.
We’ll open our new branch in Ankara
in a month. When it comes to abroad
our construction works have started
in Saudi Arabia. Our discussions with
Qatar and Cyprus are in progress.
How many branches do
you aim to open in the new
period?
We have just started to open new
branches in abroad. We are planning
to achieve 6 branches in Saudi Arabia
in 2019. We continue to grow as
decided to go towards new countries
for the new period. We have a target
to reach 25 branches in total with
Pideor at home and abroad by the
end of 2019. We are planning to open
a branch in Ankara with our brand
Nelipide.
What are your expectations
from SIAL Paris?
As firm, our basic point is that we focus
on producing frozen foods products
and selling them to supermarkets,
retail points and HoReCa markets.
We attend to SIAL Paris with
these products.
September/October 2018 FOOD TURKEY 65
“Our goal is to turn the pitta bread to
a global food such as pizza and hamburger.”
What are the new period
goals of Aktaşlar?
We aim to transform the pitta bread
to a global meal such as pizza and
hamburger. We now export our pitta
bread to 13 countries. We want to increase
it to 20 by the yearend and to
40 by the end of 2019. We reach to
an agreement with everyone that we
offer our products.
You said that you want to
make Turkish pitta bread
inured by the world such as
hamburger and pizza. How
is the approach of foreigners
to Turkish pitta bread? We
have a lot of pitta bread types;
are our traditional products
preferred?
We export our pitta bread as 6 kinds.
These are made of cheese, vegetable,
spinach, sheep cheese, mixed and
chocolate types.
Are you planning to open a
dealership in France?
We opened our dealerships in different
countries such as Germany,
Holland and Saudi Arabia. We believe
that we will be active and complete
this work in France with SIAL Paris.
We will complete our next works and
open master franchising at European
countries.
What’s your priority target? Is
it to export or to open a new
place?
Our priority target is to export. Firstly,
we want to open stores afterwards we
want to spread the franchise network.
There are a lot of pastry types made
with dough added cheese or meat in
the world. Only their names change.
The taste of the pitta bread is good
for every palate. So, our pitta breads
“We are
the biggest
pitta bread
producer of
Turkey.”
find room for themselves in all countries
that we go and are spread quickly
in our target markets. Transform of
the pitta bread to a global meal will
not take a long time. Our progresses
and export activities signal this result.
Which countries demand
your pitta breads more?
Germany and USA demand quite a
lot of our pitta breads. England seems
like to come to the fore. Our distributor
made a successful deal with a big
chain store in Germany. We have also
a distributor in the USA. We distribute
to all places of the
USA through our store in
California. We ship products
to the USA almost every
month. Our pitta breads are much
loved in the USA. We already have
NATO code on our products; so,
they can be sold in NATO countries.
We can say that we are a supplier of
NATO in food. Besides, we ship our
products to Belgium. They tasted and
liked very much. We are expecting
orders from there too.
You are in all of chain stores
and airports. What is the
current situation in the place
that you are a supplier?
Our works at home are going very
well. We expand our market share
in domestic market everyday. We
are the biggest pitta bread producer
of Turkey and we continuously grow.
We have various projects about taking
part in different places such as
new chain stores and cafes. We made
a deal with hotels, too. Our products
will be used at most hotels in the Aegean
and Mediterranean regions in
the forthcoming season. Our products
are also used at various airports.
66 FOOD TURKEY September/October 2018
Visitor flow to
WorldFood Istanbul
in its 26th year
This year 16,085
people visited
the International
Food Products
& Processing
Technologies
Exhibition –
WorldFood
Istanbul, organized
for the 26th time
by ITE Turkey.
During the exhibition, sector-related
business and market-oriented seminars
were held within the scope of
‘Food 360 Experience’, and more
than 200 domestic and foreign professional
buyers were hosted within
the framework of the hosted buyer
program. The exhibition was also
home to colorful scenes with plate
presentations and food and beverage
tastings.
During the exhibition, WorldFood
Istanbul, organized for the 26th time
this year from September 5th to 8th,
hosted an exhibitor profile which
included many products, especially
beverages, milk and dairy products,
meat and poultry products, fresh
fruits and vegetables, seafood, frozen
products, basic foods and oils, sugary
products, bakery products and nuts
and food additives.
Supported by the Turkish Ministry
of Agriculture and Forestry, Turkish
Ministry of Trade, Small and Medium
Enterprises Development Organization
(KOSGEB), Gastronomy
Tourism Association (GTD), Federation
of Turkish Retailers (TPF),
All Food Foreign Trade Association
(TÜGİDER), Grain, Legumes and
Agricultural Products Process and
Package Industrialist Association
(PAKDER), Marmara Regional Purchasing
Executives Platform (MAR-
SAP), Private Label Association of
68 FOOD TURKEY September/October 2018
Turkey (PLAT) and Turkish Cooks
Association Association; this exhibition
creates a platform where the
suppliers, retailers and consumers
come together as the links on the
food chain.
During WorldFood Istanbul, which
opened its doors for the 26th time
on September 5th, hosted buyer
programs were implemented by
both ITE Turkey and the Turkish
Ministry of Trade, and more than
200 domestic and foreign professional
buyers from many countries
including Turkey, Saudi Arabia, Qatar,
Russia, Germany, the United Arab
Emirates (UAE), Azerbaijan, Iraq,
Belgium, Kazakhstan and Colombia
were hosted within the scope of the
exhibition this year. During the exhibition,
nearly 1,500 meetings were
held between the exhibitors and
professional buyers, and new cooperations
were developed.
Kemal Ülgen, ITE Group Regional
Director: “We have brought together
over 400 exhibitors from 30
countries with 16,085 visitors”
“WorldFood Istanbul hosted 354
exhibitors and 13,198 visitors from
29 countries last year, and we are
glad to go beyond this number this
year. We have brought together over
September/October 2018 FOOD TURKEY 69
400 exhibitors from 30 countries
with 16,085 visitors in WorldFood
Istanbul this year. There was a huge
participation in the exhibition, and
we are very pleased with this interest.
In the same way, we are also
receiving positive feedback from
our exhibitors and visitors. During
the 4 days, we addressed plenty of
sector-related issues with experts
in their fields. We are very pleased
with the result we have achieved
thanks to the Hosted Buyer Programs
that we have implemented
with the Turkish Ministry of Trade,
being supported by the ITE Group’s
global strength as well.”
Gürkan Boztepe, President of Gastronomy
Tourism Association: “We
will continue our work and cooperation
with WorldFood Istanbul”
“As Gastronomy Tourism Association,
WorldFood Istanbul is a crucial
exhibition for us, and we believe it
is important to support this exhibition.
Next year, our support will
further increase. This exhibition is
unrivalled; maybe we can consider
it together with Sirha, the most
important gastronomical exhibition
held in France’s Lyon region. At the
same time, expert chefs performed
wonderful shows.”
70 FOOD TURKEY September/October 2018
Feel the change with the new
image of 26 th edition of ANFAS
Food Product!
The 26th ANFAS Food Product – International Food and
Beverage Specialized Fair; which will make the change wind
feel the participants and visitors with its renewed image, is
preparing to open its doors under the same roof at the same
time with ANFAS Hotel Equipment, the biggest organization of
the accommodation and entertainment field in Turkey, 16-19
January 2019
72 FOOD TURKEY September/October 2018
26th Food Product by ANFAS - Antalya
Fuarcılık İşletme ve Yatırım A.Ş.
- which contributes to the growth
of the food and beverages sector for
over a quarter of century continues to
work full-fledged on the International
Food and Beverage Specialized Fair.
COMES IN 2019 WITH A
NEW IMAGE!
ANFAS Food Product, which has left
25 years behind in the sector, is preparing
to open the door with a brand
new image this year. 26.Food Product,
which will make feel the participants
and visitors the difference this year,
through new target markets, new synergies,
new events, a new image and
new experience; aims to create leaps
in the industry by signing new and effective
business relationships.
UNDER ONE ROOF WITH
THE BIGGEST HOTEL
EQUIPMENT FAIR IN
TURKEY
26.Food Product – International Food
and Beverage Specialized Fair performs
participant and visitor requests,
with the opportunities given by the
growth of the fair center. 26. Food
Products perform this year as like
the last year simultaneously with the
30.ANFAŞ Hotel Equipment- International
Accommodation and Entertainment
Equipment Specialized Fair,
which is the biggest in its own field in
Turkey.
Through the fairs at Antalya Expo
Centre between 16-19 January 2019,
participants of Food Product will be
able to reach simultaneously all visitors
of Hotel Equipment from tourism
professionals to purchases of hotels.
ALL STAKEHOLDERS ARE
HERE
In result of the visitor works of ANFAŞ
for the 26.Food Product, participants
will come together with domestic hotel
investors from 81 counties, hotel
September/October 2018 FOOD TURKEY 73
managers, buyers, spa centers, interior
architects, contractors, public authorities,
chef and cooks, chain market authorities,
café and restaurant owners,
food wholesalers, retailers, teacherages,
police houses, official institutions
and social facility managements.
EXPORT ROUTE IS
EXPANDING
Food Product brought its participants
especially with distinguished
procurement committees of the
Middle East and Asian market,
in international visitor activities,
together last year. Cooperation
agreements with Germany, Azerbaijan,
Netherlands, Hong Kong, England,
Italy, Poland, Thailand and Ukraine
continue to be carried out, in addition
to the last year.
26th ANFAŞ Food Product, which
will make feel the change to its participants
with their innovator image,
offers them a new start in 2019.
74 FOOD TURKEY September/October 2018
SIAL Paris
opens for new records
7,020 exhibitors
come from 105
countries to meet
with around
164,000 visitors
from 194 countries.
Turkey will be
represented by a
huge number of
exhibitors over 300
companies.
Food innovation is dynamic and new
products emerge every day. SIAL Innovation
selects the most innovative
products displayed for professionals
by SIAL exhibitors.
You can
76 FOOD TURKEY September/October 2018
more…
Alter’Native Food: a place
apart at the upcoming SIAL
Paris Alter’Native Food Sector, a show
within a show... and multiple events.
What is it exactly?
Today, artisans and manufacturers, the
creators and inventors of the food of
tomorrow, are brimming with ideas
and notions around the concept of
Alternative Food. Basically, it's simple:
you can find it more or less everywhere
and to suit every taste. Example
of this are the shelves of food
stores, which are now full of products
containing plant proteins (wheat, soya,
pulse proteins, etc.), with the desire
September/October 2018 FOOD TURKEY 77
for healthy eating inextricable from
eating pleasure, and manufacturers
focusing in particular on how food
looks and how it tastes. As a result, the
number of innovations based on meat
substitutes now exceeds the number
of meat-based innovations. And consumers
keep coming back for more:
the very essence of popular demand!
Another typical example is the case of
fermented foods, such as Kombucha,
Kefir and Kimchi: foods known since
ancient times and which have once
again become newly-popular among
consumers for their natural properties
and health virtues. Alternative Food:
planetary phenomenon
Health concerns, therefore, may be
what predominantly underlie the
success of Alternative Food. After
the major food crises of the '90s and
early 2000's, consumers are turning
toward food that is perceived, rightly
or wrongly, as healthier and more ethical.
For these consumers, it is not a
question of taking care of their health
through their diet, but rather of taking
care of themselves while taking
pleasure in what they eat! Hence the
success of products with original flavours
and textures, incorporating a
well-being dimension. Plant- based
milks or yoghurts, "free-from" products,
enriched with super fruits or super
vegetables, natural energy drinks:
Alternative Food can be found on the
menu, any time and any place! Worldwide,
one-third of consumers believe
that the presence of organic-origin
products plays a large part in their
purchasing decisions (source: Food
360° Kantar TNS).
The Alter’Native Food Sector,
a show within a show... and
multiple events
Such a phenomenon certainly merited
special attention. SIAL Paris is
therefore giving Alternative Food the
space it deserves. With the creation
78 FOOD TURKEY September/October 2018
of a dedicated sector and events, SIAL
2018, which takes place from 21 to 25
October at Paris- Nord Villepinte, will
be proposing a unique showcase for
Alternative Food stakeholders! This
will be a show within the show, which
will have its own signposting and its
own decor, in a quite simply unique
environment!
A unique pot-pourri of
experiences
As the event highlight, the Sector
will be welcoming many exhibitors
from the Alternative Food planet, renowned
experts on healthy eating,
and the stars of innovation in this field,
whatever their country of origin. "It is
a unique pot-pourri of experiences
that we will be proposing for the first
time in 2018," explains."
Alter’Native Food Forum
Over the 5 days of the exhibition,
retail and foodservice professionals,
along with manufacturers, will be able
to exchange with each other and find
out about everything that Alternative
Food has to offer them, in terms of
both innovation and opportunity, by
way of conferences and roundtables.
The Alter’Native Food Forum is also
planned to include bilingual guided
visits to the sector from two perspectives:
alternative ingredients (conducted
by experts from NutriMarketing)
and health (conducted by experts
from Atlantic Santé). The topics proposed
include an overview of superfoods,
the "clean label", agriculture 2.0,
sustainable development, and animal
well-being.
September/October 2018 FOOD TURKEY 79
Future in focus
as innovative
end-to-end
solutions come
to the fore at
5th Gulfood
Manufacturing
Spanning 80,000 square meters of exhibition space across
16 halls, the three-day show will welcome more than 1600
local, regional and international suppliers and industry
service providers from 60 countries including a big national
participating from Turkey, 6-8 November 2018.year
since launching in 2014, Gulfood
Manufacturing will once again be categorized
into five dedicated industry
sectors:
•Ingredients, showcasing essential ingredients
that improve taste, aroma,
colour, texture, nutrition, production,
storage, transport and shelf life
80 FOOD TURKEY September/October 2018
•Processing, covering everything from
general cross-industry processing lines
and technologies, to industry-specific
equipment
•Packaging, featuring equipment and
machinery for packaging, printing, labeling,
weighing, sorting and decorating
for large, mid and small-scale industries
•Automation & Controls, presenting
technological innovation in automation
– from Robotics, Smart manufacturing
and Digitalization, to Industry
4.0 and Industrial Internet of Things
(IIOT)
•Supply Chain Solutions, showcasing
end-to-end solutions for the food industry
Spanning 80,000 square meters of
exhibition space across 16 halls, the
September/October 2018 FOOD TURKEY 81.
82 FOOD TURKEY September/October 2018.
Gulfood Manufacturing 2018 will be
open from 10 am – 6 pm on 6-7
November, and 10 am – 5 pm on 8
November. The show is only open to
food and beverage industry professionals
and visitor attendance is free
of charge. For more information, visit
September/October 2018 FOOD TURKEY 83
Aegean fruits and
vegetable exporters
raised targets
One of the major regions that farm
several produces including lemon, orange,
pomegranate, and tomato, Ortaca
seemed the right venue for the
meeting.
Regional
meeting of Aegean
Fruit and Vegetable Exporters Association
was held in Ortaca town of
Mugla to decide on the long-term targets
and strategies for 2023, centennial
of the Turkish Republic.
Aegean Fresh Fruit and Vegetable
Exporters Association
Chairman Hayrettin AYDEN, General
Director of Food and Control
Ministry of Agriculture and Forestry
General Manager Muharrem SELCUK,
Provincial Director of Agriculture and
Forestry Directorate Firat ERKAL,
Deputy Director of Forestry Department
Okan BİLGİC, Prof. Dr. Fatih
ŞEN of Aegean University, Faculty of
Agriculture, Department of Horticul-
84 FOOD TURKEY September/October 2018
6- 8 Nov 2018
DUBAI WORLD TRADE CENTRE
Discover innovative
solutions shaping global
food & beverage production
REGISTER FREE!
gulfoodmanufacturing.com
Organised by Powered by
Strategic Partner Official Logistics Partner
Official Airline Partner
Official Courier Handler
Official Publisher
ture, and Higher Agricultural Engineer
and Agriculture Consultant Huseyin
GULTEKİN attended the meeting.
Hayrettin Ucak, Chairman of Aegean
Fresh Fruit and Vegetable Exporters
Association, said in the meeting, “Our
producers and exporters are our
problem, your problem is our problem.
As the board of directors, we carry
out all our work with this principle,
and we will proceed.” Ucak expressed
his appreciation to the Provincial Directorate
of Agriculture in Mugla, and
Muharrem SELÇUK, Director General
of Food and Control, Ministry of Agriculture
and Forestry, who participated
in the meeting from Ankara, for his
support they provided to both farmers
and exporters.
Muharrem Selcuk stated that the right
methods of production are important
but that the use of the rightful implementations
of the producers alone
does not solve the problems. He said,
“In addition to your traditional knowledge
that you have learned from the
your fathers and grandfathers, we have
to pass on new production methods.
But we must do it all of us together.
If the next neighboring farmer is not
doing right it is useless. That means the
problems are not solved individually.”
Hayrettin Ucak,
Chairman of Aegean Fresh Fruit and Vegetable
Exporters Association
Several problems were discussed in
the meeting; among them are, the reduction
of wastes after harvests, need
for planned farming and farming analysis,
the alternative solutions for improving
quality and productivity.
86 FOOD TURKEY September/October 2018
We love eating
dried fruits with our
beloved ones!
Born in Turkey and exporting to
over 40 countries, Peyman has been
continuing to enrich its product range
in line with trends and consumer
preferences. According to a consumer
research conducted by Peyman 60%
of dried fruit consumption is done by
friend, family or guest groups in Turkey
and it was regarded as an important
social activity.
Peyman prepared a series of mixed
dried fruits upon the fact that was
revealed in the research as consumers
prefer enjoying mixed dried fruits,
which is the third largest segment of
the dried fruit market after sunflower
seed and peanuts, and a fast growing
one, with tea while watching TV, and
with cold drinks while sitting with
friends. The mixed dried fruit series
of Peyman includes four different
contented series namely Klasik
(Classic) İkramlık (To Offer), Soslu
(With Sauce), and Çiğ (Unroasted), all
packed with airproof package system
to keep its freshness and taste of the
first day for a long time.
Peyman Klasik Mix was prepared for
those who love consuming dried fruits
while watching TV with their beloved
ones, İkramlık is for those who would
like to offer the best to their guests
who met for tea hour. Soslu mix stands
for spicy addicts who love enjoying
dried fruits with cold drinks and Çiğ
mix packages for those who care for
healthy nourishment as a snack.
“The consumer prefer plainness
and net offers by seeing and reading
88 FOOD TURKEY September/October 2018
product names easily and they want
to see many choices rather than
packaging intricacy on shelves.
Pointing out that they directed their
new product development R&D
studies with consumer attitudes and
market researches, Nazlı Tandoğan,
Marketing Category Manager of
Peyman, said, “Consumer’s demands
and expectations are of utmost
importance to us. We produce new
tastes and serving systems by listening
them at every occasion. According
to our most recent market research,
the consumer prefers plainness and
many choices rather than packaging
intricacy on shelves. Especially our
target audience who loves mixed
dried fruits wants mixes according
to their own choices among different
choices. When adding sharing desire
of dried fruits with others, that’s how
Peyman Mixed Dried Fruit series was
born. We made the packaging plain in
this series and finished perception and
confusion problems. We developed
4 mixtures by providing plain net
appearance design to respond what
the consumer demands. It is possible
to find a mixture appealing to every
moment and to every atmosphere.
We believe that we will respond
consumer demands and expectations
with our new series in addition to
curren brands as Bahçeden, Dorleo
and Nutzz.”
According to a research conducted
by Peyman 60% of dried fruit
consumption is done by friend, family
or guest groups in Turkey. We prefer
enjoying mixed dried fruits, which is
the third largest segment of the dried
fruit market and a fast growing one,
with tea while watching TV, with cold
drinks while sitting with friends.
September/October 2018 FOOD TURKEY 89
ISM
provides
trendoriented
innovative
young
companies
with a
stage
Herzhafter Snackriegel Mediterranean Style PaPicante
Attractive
participation
models for startups,
newcomers
or companies with
snack alternatives
comprising of
fruit, vegetables
or jerkies - an
interview with
the snack bar
manufacturer
PaPicante
As the leading global trade fair for
sweets and snacks, ISM not only sees
itself as a presentation and networking
platform for companies from the
industry, but also as a trendsetter with
the aim of promoting innovative, future-oriented
ideas from the industry.
Whether a start-up, trade fair newcomer
or supplier in the ISM sections
“Coffee, tea and cocoa” or “New
Snacks” - as the largest and most international
trade fair for sweets and
snacks, ISM 2019 offers numerous
presentation options for young and
also established trend-oriented companies
from the industry.
Start-up Area
The Start-Up Area offers companies
that have been founded within the last
five years a favorably-priced possibility
of presenting their products and
concepts at ISM at a stand measuring
four square meters. The entire startup
area is located in the Trend Section
of Hall 5.2 and is the place for innovations.
ISM additionally offers startups
the opportunity to take part in a
speed-dating or present themselves in
the scope of a start-up pitch on the
Trend Stage.
Newcomer Area
The Newcomer Area is open to firms
of all product categories and ages. The
only prerequisite: The company has
to be exhibiting for the first time at
ISM or have not been represented at
the trade fair for a longer period of
time. For companies that would like
90 FOOD TURKEY September/October 2018
Gründer und Geschäftsführer Nadja Schoser, Tobias Zinßer
to present their products to a larger
audience for the first time, ISM offers
a good opportunity to establish contacts
within the industry with a central
placement in the Newcomer Area of
Hall 11.1. and an attractive stand measuring
six square meters.
New Snacks Area
The young “New Snacks” section at
ISM has its fixed place in Hall 5.2 and
will have a central location in the foyer
in 2019. The suppliers of fruit and
vegetable snacks, breakfast snacks,
jerkies and meat snacks will find precisely
the right environment for their
trade fair participation in the “New
Snacks Area”. Located in a well-visible
place on the central axis of the hall,
the visitors can’t possibly overlook the
“New Snacks Area”. Special marketing
and promotional measures will attract
the visitors’ attention even more. 35
companies from 16 countries will be
exhibiting in this section at ISM 2019
with products like:
- Protein and energy bars
- Beef jerkies
- Fish chips in the flavours chili, sea salt
or BBQ
- Dried fruit and vegetables, compotes
- Raw food bars
- Cereal and oat bars
- Sandwich spreads
- Vegan ice cream and organic ice
cream
- Snacks made of raw cocoa
- Biological, gluten and lactose-free
chocolate snacks
All three areas cover the significant
trends of the international sweets and
snacks industry and offer the visitors
the opportunity to inform themselves
about new trends and establish contacts
to the new companies.
Interview with PaPicante
The ISM exhibitor, PaPicante, underlines
the advantages participation can
have for young start-ups. The company
founded by Nadja Schoser and Tobias
Zinßer in 2017 is already participating
at the leading global trade fair for
sweets and snacks for the third time
in 2019 and as an ISM professional for
the young segment reports about its
experiences at the trade fair in the following
interview.
September/October 2018 FOOD TURKEY 91
Herzhafte Snackriegel PaPicante im Überblickory counterpart
to the well-known sweet cereal bar,
seemed to be an excellent addition.
The name is a direct reference to the
“savory revolution” in the snack bar
section and that is why we came up
with the idea of combining the Spanish
word “Papi”, which means a cool
dude, with picante, i.e. spicy. In other
words, PaPicante is a cool, spicy snack
bar that want simply wants to sink
one’s teeth into.
What is the special feature
about your products?
Tobias Zinßer: As a savory snack bar
PaPicante is based on pea protein
crisps in three international flavors
- American Style, Asian Style & Mediterranean
Style. We didn’t want to
just create an everyday snack bar. It is
much more about producing “international
cuisine in pocket format” - i.e. a
novel lifestyle product with actual added
value, which among others follows
the current food trends and customer
wishes thanks to implementing the domestic
green ‘superfood’ pea protein
crisps as its innovative basic ingredient.
In principle, the bars are the perfect
snack for in-between meals - whether
as a small lunch between strenuous
business meetings, as a healthy foodfor
having participated in the
Newcomer Area (2017) and
in the Start-up Area (2018)
have taken advantage of
the options of exhibiting
for newcomers or young
companies. one only has to bring
along one’s sample products and the
deco material and you can get going.
Furthermore, all of the stands get the
same amount of attention, which is a
real advantage as a newcomer. Furthermore,
the ISM visitors know that
new products are presented in the
Newcomer Area, so initial good contacts
can definitely be made here. In
2018, we then opted for the Start-Up
Area, first of all to try out a different
section and secondly, because this presentation
option was interesting for us
due to the favorably-priced conditions.
Here too, one more or less just brings
one’s products and some stand design
elements along, which means there is
also little logistical effort involved. This
section is definitely recommendable
for young companies that would like
92 FOOD TURKEY September/October 2018
to present themselves to the industry
for the first time.
What difference has
participating at ISM made for
you and your business?
Tobias Zinßer: After our first participation
we received clear, open feedback
to.
Herzhafte Snackriegel Zutaten PaPicante one can build up
good relations. Furthermore, as a food
company specializing in snack items
one gets very good, precise feedback
on one’s own products. And of course
by participating at ISM, but also in
other trade events too, one achieves
more visibility and extends one’s own
level of recognition. In addition to observing
trends, personal networking
and getting to know potential new
business contacts is a real bonus.
September/October 2018 FOOD TURKEY 93
Turkey ready to be
a key halal food
exporter
The officials of the UN
Food and Agriculture Organization
(FAO) Turkey
have said in their report
that Turkey has the capacity
to become a significant halal
food exporter in the region.
“Turkey, as a country with a Muslim
population and high food safety standards,
is a good candidate for exporting
halal food products to neighboring
and other Muslim countries,” they said.
Halal food, food permitted under Islamic
law, is a growing sector around the
world and Muslim consumers globally
spent
$ 1.1 tril- lion in
halal food and beverage consumption
in 2012, which represents 16.6 percent
of the global expenditure for food and
beverage. This expenditure is expected
to grow into a $1.6 trillion market by
2018.
They said that the top
countries in annual food
spending with Muslim
consumers are Indonesia,
with $197 billion; Turkey,
with $100 billion; Pakistan,
with $93 billion; and Egypt, with
$88 billion, based on 2012 data. He
added that the collective global Muslim
food and beverage market is larger
than the biggest single national market
of China.
“We know that certification activities
for halal food started in Turkey. Since
then, hundreds of companies have
knocked on the door of the Turkish
94 FOOD TURKEY September/October 2018
Standards Institute [TSE]. Today, more
than 400 companies have halal food
certificates provided by the TSE. Companies
operating in Iraq, the Gulf States
and the rest of the Middle East are applying
for halal certificates,” they added
Commenting on the increasing importance
of the concepts of food security
and food safety all around the world,
they stated that it is a natural and very
important step to include food security
among the agenda items.
“There is an urgent need for decisive
action to free humankind from hunger
and poverty. Food security, nutrition
and sustainable agriculture must remain
a priority issue on the political agenda,
to be addressed with a cross-cutting
and inclusive approach, involving all
relevant stakeholders at the global, regional
and national levels. Effective food
security actions must be coupled with
adaptation and mitigation measures in
relation to climate change, sustainable
management of water, land, soil and
other natural resources, including the
protection of biodiversity,” added the
FAO representative.
They noted that Turkey is a food-secure
country, considering the data on
per capita food supply in Turkey (3,700
kcal/per capita/per day) and the absence
of records of food aid shipments
to Turkey.
A recent Organization for Economic
Cooperation and Development
(OECD) report shows that Turkey is
a world leader in a number of crops,
with high product diversity and strong
exports that contribute to food security
at the global level. According to the
OECD report, Turkey is the world’s
sixth largest agricultural producer and
a top producer and exporter of crops
ranging from hazelnuts and chestnuts
to apricots, cherries, figs, olives, tobacco
and tea.
As known, the FAO and the Turkish
government, through the Ministry of
Agriculture, concluded a host country
agreement (HCA) in mid-2006 that
also set up a partnership framework
agreement (PFA). Turkey contributed
$10 million over an initial period of
five years from 2007 to 2011 to benefit
the countries assisted by the FAO
Sub¬-Regional Office for Central Asia
(Azerbaijan, Kazakhstan, Kyrgyzstan,
Tajikistan, Turkey, Turkmenistan and Uzbekistan)
through the FAO¬/Turkey
Partnership Program (FTPP).
Regarding Turkey’s efforts in the region,
the FAO officials said that though it is
situated in a disaster-prone region, Turkey
has a strong tradition of responding
to those in need, not only in times
of natural disaster, but also on a periodic
basis. Turkey’s policy has been that
comprehensive development can only
be achieved through a sustainable and
collective strategy.
“With this understanding, Turkey, indiscriminate
of race, religion, language
and gender, strives to rapidly channel
humanitarian assistance to those countries
in dire straits and supports international
efforts to this end. Especially in
recent years, humanitarian assistance
from Turkey has been diversified and
significantly increased. Its participation
in various humanitarian assistance operations
has steered certain international
organizations to name Turkey
as an ‘emerging donor country’,” they
added.
The primary objective of the FTPP is to
provide a substantive financial and operational
framework for active cooperation
in the areas of food security and
rural poverty reduction in beneficiary
countries.
96 FOOD TURKEY September/October 2018
Meet key buyers at the Kingdom’s
premier event for the food and
hospitality industry
21 – 23 April 2019
Jeddah Centre for Forums & Events
To book a stand please contact:
thehotelshowksa@dmgevents.com
or call +971 4 4453721
thehotelshowsaudiarabia.com
JOIN YOUR PEERS
Supported by Host venue Endorsed by
Hygiene Partner
Organised by | https://www.yumpu.com/en/document/view/62153527/foodturkey-september-october-2018 | CC-MAIN-2022-33 | refinedweb | 16,070 | 50.87 |
Can't run NUnit tests. I created the new console application, added c# class library for .net 4, installed following NuGet packages into the library:
- NUnit
- NUnit Test Adapter for VS2012.
And added the code:
using NUnit.Core;
using NUnit.Framework;
[TestFixture]
public class Class1
{
[Test]
public void Test()
{
NUnitFramework.Assert.AreEqual(true, true);
}
}
I can successfully run the test in Test Explorer (standard VS runner).
But if I run it in Resharper, I get the yellow icon and the message "Test wasn't run".
I have attached the related fragment from the log file.
Looks like xUnit extension is not working either (but works in VS Runner).
I am using ReSharper 8. Upgrade to 8.0.1 and settings reset doesn't help.
Is it a known issue?
Thank you. | https://devnet.jetbrains.com/thread/449398 | CC-MAIN-2015-22 | refinedweb | 131 | 71.21 |
what a wonderful forum!!! light speed replies and very useful tips!! thank you again!!
Printable View
sorry but what about reallocating matrix?
for example...
a matrix of an HWND array can be declared like that?
if it's right... for adding a line i doif it's right... for adding a line i doCode:
typedef std::vector<HWND> HWNDArray;
typedef std::vector<HWNDArray> HWNDMatrix;
anyway when i try to access to an element it crash...anyway when i try to access to an element it crash...Code:
HWNDMatrix hCheckBox;
hCheckBox.reserve(hCheckBox.size() + 1);
HWND foo = CreateWindowEx ( 0L, "BUTTON", "", BS_AUTOCHECKBOX | WS_VISIBLE | WS_CHILD | BS_CENTER, left, top, right, bottom, hWnd, NULL, GetModuleHandle(NULL), 0);
hCheckBox[hCheckBox.size()].push_back(foo);
The error is simple -- the vector has size 0. You can't access an element of a vector that is out of bounds.
As a quiz, you tell us what this line does. One clue -- it does not give you hCheckBox.size() elements. Given that you do not have those elements, the next line is an illegal memory access.As a quiz, you tell us what this line does. One clue -- it does not give you hCheckBox.size() elements. Given that you do not have those elements, the next line is an illegal memory access.Code:
hCheckBox.reserve(hCheckBox.size() + 1);
There is no such element as hCheckBox[hCheckBox.size()]. That's why you get an error.There is no such element as hCheckBox[hCheckBox.size()]. That's why you get an error.Code:
hCheckBox[hCheckBox.size()].push_back(foo);
There are 4 general ways to add elements to a vector.
1) On construction of the vector.
2) Using vector::push_back()
3) Using vector::insert()
4) using vector::resize().
Look at item 4. Note that the name of the function is resize(), not reserve().
Regards,
Paul McKenzie
Well just for fun I decided to fix your reallocating issue and give you a few pointers ( hopefully valid :) ) First of all you have no need of the static variable and no need to save the length of strings because what you are reallocating is just an array of pointers to the malloced strings, you dont need to reallocate the strings just the array of pointers so all you need to save is count of elements inside which you already use the n parameter for :P Second mistake you have was the dereferencing of the list pointer , *list[n] which in fact dereferences list[n] but you actually need to dereference list and get its n-th element so a pair of brackets can be very useful here (*list)[n]. So the final code should look like this:
Hope I helped :)Hope I helped :)Code:
#include <iostream>
using namespace std;
void add(char ***list, int n, char *person)
{
*list=(char**)realloc(*list,(n+1)*sizeof(char**));
(*list)[n] = (char*) malloc (strlen(person) + 1);
strcpy((*list)[n], person);
}
int main()
{
char **list = NULL;
int n = 0;
add(&list, 0, "jack");
printf("list[0]: %s\n", list[0]);
n++;
add(&list, 1, "jeff");
printf("list[1]: %s\n", list[1]);
free(list[0]);
free(list[1]);
free(list);
return 0;
}
There we go fixed in previous post for your viewing pleasure :)
I just fixed it because he wanted to see how it would look while using realloc and his original snippet didnt bother with freeing memory, and 'huge' is quite an overstatement there.
Just for fun: realloc() can be used in place of free() by specifying a new size of 0.
personally I hate working with dyn mem because I ever feel there's some leak somewhere...
the realloc for the string has been made because at the beginning I wanted to make an insert possible but (unfortunately / fortunately) std::vector.insert() took all the fun away XD
about my last post I solved declaring a support single var and "push_back"ed it into a support vector and then "push_back"ed the vector in the matrix...
std::vector make me feel much quiet about memory :P
thank you all again!
When you need a matrix of dynamic size which won't *change* size often, you should consider using boost::multi_array. | http://forums.codeguru.com/printthread.php?t=481909&pp=15&page=2 | CC-MAIN-2016-22 | refinedweb | 691 | 62.68 |
Answered by:
Accessing Azure Management APIs from within Azure Websites
I'm trying to access the Azure Management APIs from within an Azure Website, however the moment I make a web request in Azure, I get an error which bypasess any logic I have for the catch block surrounding the code making the web request..
You can repro this with by clicking the button on the below ASPX page. When run locally, ASP.Net prints out an error (see below). In Azure websites however, I get back a 502 error (below) which confuses me for two reason:
- The web call is made in a try/catch block. Therefore the exception should have been handled
- If the error was in making a web request, I would have expected a 500 error from asp.net, rather than a 502 from IIS.
I am sure this issue is caused specifically by making a call to management.core.windows.net, because making either of the below two changes stops the 502 response, and I instead get the WebException output on the page itself.
- Change the url on line 21 to another domain
- Change the contents of the try block on line 29 to return a hardcoded string.
Local Response
ERROR: System.Net.WebException: The remote server returned an error: (403) Forbidden. at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address) at ASP.default_aspx.AzureManagementCall(String endpoint, String method, String body) in d:\Telligent\SVN\AzureManageTest\AzureManageTest\default.aspx:line 37
(This error is expected because I didn't provide a valid certificate to. I excluded the code for adding the certificate as it adds a lot of code, and isn't strictly nessescary to reproduce the issue)
Response in Azure Websites
Server Error<fieldset style="padding:0px 15px 10px;">.</fieldset>
Sample Code
<%@ Page private readonly Guid _subscriptionId = new Guid("0b23da9e-640a-4683-b7c6-7509eb10f68e"); protected void Button1_Click(object sender, EventArgs e) { var siteInfo = AzureManagementCall("locations", "GET"); Response.Write("<pre>"); Response.Write(HttpUtility.HtmlEncode(siteInfo)); Response.Write("</pre>"); } private string AzureManagementCall(string endpoint, string method, string body = null) { var requestUri = new Uri("" + _subscriptionId.ToString() + "/services/" + endpoint); var client = new WebClient(); try { return client.DownloadString(requestUri); } catch (Exception ex) { return "ERROR: " + ex.ToString(); } } </script> <form runat="server"> <h2>Azure Management Test</h2> <asp:Button </form>
- Edited by Alex Crome Sunday, July 29, 2012 7:13 PM
Question
Answers
All replies
A few other things to add
- After enabling Failed Trace REquest Logging, nothing shows up for the 502 error
- After enabling Detailed error logging, again nothing shows up
- The POST requests for the button click are not even logged in the HTTP Logs
- If you repeat the request a few times in a short period, you start getting 503 errors.
I'm now suspecting that somehow accessing the Azure Management APIs from within Azure Websites is causing the worker process to crash:
- the 'Rapid Failure protection settings in IIS mean that repeated worker process crashes within a short time interval cause 503 errors.
- A crash would likely prevent the failed request being logged in the HTTP Logs (3)
- A crash would also explain why the catch logic around the http request gets ignored
Hi, Alex. I looked up the exception using your subscription ID, and the problem you're having is caused by a failed network connection to one of the back-end servers. I'm not sure what's causing that, but I suspect it may be caused because you aren't authenticated. You are required to be authenticated in order to make this request.
Ultimately, I think you're going to have to resolve the issue with the certificate before you can move forward. Have you reviewed the documentation and sample code for authenticating Azure Management requests?
Jim Cheshire | Microsoft
Hi Alex,
I have reproduced and debugged this issue. To keep the technical details short, Website virtual machines are sandboxed. We block bunch of system level APIs to enhance the security of dense hosting. It seems like we are blocking SEC_I_RENEGOTIATE calls on Websites virtual machines. This is resulting in access violation inside w3wp.exe process and hence the issue. I have engaged the developers to further investigate this issue and update you with the results as soon as I hear from them.
Thanks much for reporting this issue.
AJ
Apurva Joshi, This posting is provided "AS IS" with no warranties, and confers no rights.
I appear to be having the same issue with a request to a payment provider from inside an azure website.
All the OP points about catch blocks and error logs being skipped are the same. It works locally fine but crashes out with 502 causing the website to restart when on azure.
Please let me know if this is azure blocking the provider.
I have posted more information about the bug here
public class TestController : BaseController { public string test() { try { var webClient = new WebClient(); var stream = webClient.OpenRead(""); var streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); } catch (Exception exp) { errorResult(exp); } return formattedResult(result); } }
The the test method of this controller when deployed to azure websites causes the site to crash and restart.
Whilst the adyen url requires basic auth the crash happens before that is required and whether it is provided or not.
Presumably adyen (like many other sites?) requires part of the HTTP protocol like SEC_I_RENEGOTIATE which MS has left out.
What can be done about this.
Do i have to run my site as a web role? will this method work in a web role?
- Edited by Jules Bonnot1 Thursday, August 23, 2012 2:32 PM | https://social.msdn.microsoft.com/Forums/azure/en-US/636c6f0b-1229-429a-9566-66272b462ab8/accessing-azure-management-apis-from-within-azure-websites?forum=windowsazurewebsitespreview | CC-MAIN-2016-40 | refinedweb | 937 | 54.63 |
Prelude
This is the second post from my series dedicated to modern programming languages for the Java platform. Last time we’ve discussed the Groovy programming language, which is a member of the ever expanding family of dynamic programming languages. The Scala programming language, that is the object of today’s discussion, is different beast entirely - not only it uses static typing(like Java & C# amongst others), but it also puts a heavy emphasis on the type system, functional and parallel programming.
In theory Scala runs both on the JVM and on the CLR(the .NET VM). The Java port, however, receives a lot more attention by Scala’s developers and it probably accounts for close of to all of Scala’s deployments(especially in production).
This article is extremely hard to write for me. Unlike Groovy, I’m deeply familiar with the language and would like to share quite a lot with you. For obvious reasons I cannot go into much detail (otherwise I’d have written an on-line book). You’re encourage to follow up this article by reading some of the excellent resources, mentioned near its end.
A brief history of Scala (though we should mention that it was C# that first brought generic programming to the masses).. The first official version was released in late 2003. This year it celebrates its first anniversary in a way (depending on what do you consider the birthday).
Scala stands for a SCAlable LAnguage. What does this mean? Scala is designed to tackle solutions of wildly varying sizes - from small scripts (programming in the small) to massive distributed enterprise applications (generally programming in the large). Scala also means steps in Italian and this is the reason why most Scala books have some form of steps on their covers (arguably this is the reason why Scala is very popular in Italy and particularly in Milan).
The current production version of Scala is 2.8.1 with 2.9.0 being in the release candidate stages.
Installing Scala
Universal installer
Scala has an universal installer that could be ran on every platform with Java installed. You can run it from the console like this:
$ java -jar scala-2.8.1.final-installer.jar
Alternatively, on most systems simply double clicking the installer jar will run it(assuming you have a GUI environment and assuming that the java command is associated with jar files - something that is usually so by default).
Installing from binary archive
Just download the Scala distribution for Unix, OS X and Cygwin or the one for Windows and extract it somewhere. I’m a GNU/Linux user and I tend to extract all third party apps in the /opt folder:
$ sudo tar xf scala-2.8.1.final.tgz -C /opt
You’d also want to add the folder containing the Scala binaries (compiler, REPL, etc) to your PATH environmental variable. Unix users might add something like this to their shell startup script (like .bashrc):
export JAVA_HOME=/usr/java/latest export SCALA_HOME=/opt/scala-2.8.1 export PATH=$SCALA_HOME/bin:$PATH
You should now have Scala installed properly. You can test this by typing the following in a command shell:
$ scala
Which should create an interactive Scala shell where you can type Scala expressions.
To run a specific Scala script type:
$ scala SomeScript.scala
Linux installation
Most Linux distributions provide Scala through their integrated package management system. On Debian(and derivatives like Ubuntu) you can install it like this:
$ sudo apt-get install scala
On Red Hat systems the magic incantation looks like this:
$ sudo yum install scala
Personally I’d prefer the platform-independent installation method, since some distribution package Scala in a non-standard manner, which confuses IDEs for instance.
Scala at a glance
If I were to pick a language to use today other than Java, it would be Scala…
–James Gosling, creator of Java
If Java programmers want to use features that aren’t present in the language, I think they’re probably best off using another language that targets the JVM, such a Scala and Groovy.
–Joshua Bloch, author of “Effective Java” and many of Java’s core libraries
Scala basically is:
- SCAlable LAnguage
- Pure OO language
- Functional language
- Statically typed language
- A language that integrates seamlessly with existing Java code
- A great community
Scala’s more prominent features are:
- Type inference
- Advanced type system
- Improved OO model
- Improved imports system
- Simplified visibility rules
- Suitable for scripting, GUI, enterprise
- Relies on immutable data structures by default
- Great support for building parallel applications
- Pimps (improves) a lot of standard Java classes using a technique called implicit conversion.
Static vs Dynamic typing
This is one of the oldest debates in computing and everyone with a little bit of common sense knows that there is no definitive answer to this so fundamental question. Both approaches have merits and drawbacks. In recent years we saw a rapid explosion in the rate of growth of dynamic languages which lead many people to believe that static typing is something of the past and is headed down on the road to oblivion. I , however, very much doubt such a possibility. So, without further ado here’s my take on their pros and cons:
Dynamic typing
- Pros
- Less verbose
- Better metaprogramming capabilities - it’s very easy in a language like to Ruby to modify a class at runtime for instance. Java developers, on the other side, can only dream for such things…
- Duck typing allows to reduce immensely the coupling between your classes
- Reduced development and deployment cycles - most dynamic languages are implemented as interpreters and this way you’re spared the tedious compilation/redeployment cycles
- Cons
- Some might argue that type declarations serve as an additional documentation and their lack (arguably) make the code harder to read. Of course, when you’re following a decent naming convention (and by that I mean that you’re using sensible identifiers) that hardly matters.
- Slower performance - knowing all the types in advance, naturally, allows the compilers to generate faster code for static languages than for dynamic ones. Some Lisp compilers, however, offer performance that rivals that of statically typed programs, so it’s reasonable to expect that the situation in this department will improve over time.
- It’s hard to create IDEs for dynamic languages that offer the same level of assistance as those for static languages. The problem stems from the simple fact that in a dynamic language the type of an object is known only at runtime and an IDE will have a pretty hard type guessing the types because of this fact. In my humble opinion the lack of all the fancy IDE features like reliable code completion and refactorings is one of the central reasons why statically type languages like Java, C# and C++ are still enjoying higher popularity than dynamic languages.
- You need to write more unit tests, because many of the simple errors that the compiler of statically typed language will detect will manifest themselves only at runtime.
Static typing
- Pros
- Mighty development environments, capable of compensating for a lot of the languages deficiencies. You always get correct completion suggestions (in a decent IDE that is), all type errors are caught as you type (except the runtime errors that is).
- Reliable refactoring - you make some changes, you recompile the project, you instantly see whether everything is OK after the refactoring. One of the key reasons why enterprise projects are often implemented in Java and C#.
- Maximum performance - when you know all the types in advance it’s not particularly hard to generate the most efficient in terms of performance bytecode/binary code.
- You don’t need to write unit tests for errors that will be caught by compiler.
- The type declarations arguably serve as an up-to-date documentation on which you can always rely.
- Cons
- Poor metaprogramming support - statically typed system limit very much the magic you can do in you programs. Metaprogramming is actually considered a black art in many statically type languages. In a functional statically typed language higher-order functions can compensate a lot in that department. Scala happens to be one such language, Haskell - another.
- Generally statically type languages are a bit more verbose - mostly because the code is full of type annotations (languages like Scala and Haskell, however, have found the cure for this ailment - type inference)
- No support (in most statically typed languages) for duck typing causes you to often link classes in hierarchies that you’d rather avoid if you had the chance to. I should point out that languages supporting structural types are not suffering from these problems. Scala happens to support them from version 2.6.0.
A whirlwind tour of Scala
Scala is expressive
scala> val romanToArabic = Map("I" -> 1, "II" -> 2, "III" -> 3, "IV" -> 4, "V" -> 5) romanToArabic: scala.collection.immutable.Map[java.lang.String,Int] = Map((II,2), (IV,4), (I,1), (V,5), (III,3)) scala> romanToArabic("I") res2: Int = 1 scala> romanToArabic("II") res3: Int = 2
Scala removes the incidental complexity
Scala removes the incidental complexity and cut right to the core of the problem. Imagine that you want to find whether or not a string contains uppercase characters. In Java you’d write something like this:
public boolean hasUpperCase(String word) { if (word == null) { return false; } int len = word.length(); for (int i = 0; i < len; i++) { if (Character.isUpperCase(word.charAt(i))) { return true; } } return false; }
So much boilerplate code (loop, if) to express such a basic idea. In Scala you’d simply write:
def hasUppercase(word: String): Boolean = { if (word != null) word.exists(c => c.isUpperCase) else false } // or more compactly def hasUppercase(word: String) = if (word != null) word.exists(_.isUpperCase) else false
Scala’s code actually reads a lot like English language that makes sense to humans - check if in word there exists an uppercase character. Notice that is Scala if is an expression yielding a return value, unlike in many other languages.
Scala is concise
Consider this simple JavaBean (well, not exactly JavaBean to be precise - it lacks a no param constructor) definition:
class Person { private String name; private int age; Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
In Scala the equivalent definition looks like this:
class Person(var name: String, var age: Int)
This is what I call a good signal-to-noise ratio.
Scala supercharges OO programming
Scala is pure OO language - everything is an object, operators are actually methods, everything yields some result(even constructs such as if), there are no static field and methods
Scala is power overwhelming
Want to implement a thread-safe mathematical service in Scala? No problem!
import scala.actors.Actor._ case class Add(x: Int, y: Int) case class Sub(x: Int, y: Int) val mathService = actor { loop { receive { case Add(x, y) => reply(x + y) case Sub(x, y) => reply(x - y) } } } mathService !? Add(1, 3) // returns 4 mathService !? Sub(5, 2) // returns 3
Case classes are out of the scope of this post, but I guess you get the basic idea.
Scala is duck friendly
Duck typing is nothing new for developers familiar with dynamic languages. Its the concept that an objects type is defined not by the objects class, but by the objects interface. This allows us to write very flexible code that works on unrelated types (in the inheritance hierarchy) that happen to share common methods. For instance in Ruby we could write this code:
class Duck def walk puts "The duck walks" end def quack puts "The duck quacks" end end class Dog def walk puts "The dog walks" end def quack puts "The dog quacks" end end def test_animal(animal) animal.walk animal.quack end test_animal(Duck.new) test_animal(Dog.new)
It will work just fine - trust me. Few statically typed languages can boast something similar… and Scala happens to be one of them:
class Duck { def quack = println("The duck quacks") def walk = println("The duck walks") } class Dog { def quack = println("The dog quacks (barks)") def walk = println("The dog walks") } def testDuckTyping(animal: { def quack; def walk }) = { animal.quack animal.walk } scala> testDuckTyping(new Duck) The duck quacks The duck walks scala> testDuckTyping(new Dog) The dog quacks (barks) The dog walks
This is point in the article when Ruby and Python are starting to get impressed. (I should know - I’ve learnt about this feature after I’ve written the first draft and got some negative feedback due to my oversight).
Pimp my library
Want to make the compiler convert between types from time to time to get access to some richer functionality? Nothing is easier in Scala:
scala> implicit def intarray2sum(x: Array[Int]) = x.reduceLeft(_ + _) intarray2sum: (x: Array[Int])Int scala> val x = Array(1, 2, 3) x: Array[Int] = Array(1, 2, 3) scala> val y = Array(4, 5, 6) y: Array[Int] = Array(4, 5, 6) scala> val z = x + y z: Int = 21
Scala arrays don’t have a + method, but Scala Ints do. When the compiler sees that the + method is invoked on an object that doesn’t have it, it starts searching for an implicit conversion to a type that has it - like Int. Both arrays are converted to their sums and the sums are added together in the end.
Playing around
A good way to start exploring Scala is the REPL. Fire it up and type along:
scala> println("Hello, Scala") Hello, Scala scala> val name = "Bozhidar" name: java.lang.String = Bozhidar scala> Predef.println("My name is "+name) My name is Bozhidar scala> var someNumber: Int = 5 someNumber: Int = 5 scala> var names = Array("Superman", "Batman", "The Flash", "Bozhidar") names: Array[java.lang.String] = Array(Superman, Batman, The Flash, Bozhidar) scala> names.filter(name => name.startsWith("B")) res6: Array[java.lang.String] = Array(Batman, Bozhidar) scala> names.length res7: Int = 4 scala> name.length() res8: Int = 8 scala> import java.util.Date import java.util.Date scala> var currentDate = new Date currentDate: java.util.Date = Wed May 11 15:03:20 EEST 2011 scala> println("Now is " + currentDate) Now is Wed May 11 15:03:20 EEST 2011 scala> currentDate.toString res10: java.lang.String = Wed May 11 15:03:20 EEST 2011 scala> currentDate.toString() res11: java.lang.String = Wed May 11 15:03:20 EEST 2011 scala> currentDate toString res12: java.lang.String = Wed May 11 15:03:20 EEST 2011
The REPL has an excellent TAB completion - I used it ofter. You’ll note from these examples the flexibility and the brevity of Scala’s syntax - no ; to terminate statements (though you’ll have to use ; to separate more than one expression on a single line). The types of the variables are inferred by the context, without the need to specifically specify them - if you assign a string literal to some variable the compiler will figure out on its own that the variable must of type String (also note that Scala strings are Java strings - at least on the JVM). You’ve got a lot of flexibility when you’re calling methods - you can omit the braces and the dot in some scenarios - this makes it easy to create Domain Specific Languages in Scala.
The REPL outputs both the result of the expression you’ve evaluated and the output from the evaluation (if any). The result from the evaluation is assigned to automatically generated variables named resX (res0, res1, res3) and you can refer to them later on.
Object orientation purification
- Everything is an object - there are no primitive types in Scala, though the compiler will map some Scala types to primitive Java types for performance whenever possible
- No operators, just methods
1 + 2 === 1.+(2)
No static fields & methods - replaced by companion objects (a singleton object named the same way as the class). What would be a static field of a static method in Java will be a companion object field/method in Scala. This makes the Scala OO model purer than that of some other languages (of course in languages like Ruby where classes are objects class variables and methods have more or less the same meaning and the model is just a pure if not purer).
- Traits - the evolution of interfaces
- Traits are interfaces on steroids
- They can contain state as well as behaviour
- Think of them more as Ruby’s mixins than Java’s interfaces
- They can be implemented on the fly by objects
- They are too complex to be properly explained in one short blog post
Functional programming
Functional programming has many aspects, but to get the bulk of it you need just two magical ingredients - support for functions as objects and a nice array of immutable data structures. Scala, naturally, has both. Traditionally OOP languages have rarely had much support for functional programming, which makes it awkward to express some problems in them. Steve Yegge wrote an excellent article on the subject some time ago - “Execution in the kingdom of the nouns”.
Return of the verbs
- Functions are first class objects
- val inc = (x: Int) => x + 1
- inc(1) // => 2
- Higher-order functions
- List(1, 2, 3).map((x: Int) => x + 1) // => List(2, 3, 4)
- Sugared functions
- List(1, 2, 3).map(x => x + 1)
- List(1, 2, 3).map(_ + 1)
Closures
Closures are basically functions that have captured variables from an external scope (variables that were not parameters of the functions). Closures are often used as the parameters of higher-order functions (functions that take functions as parameters):
scala> var x = 10 x: Int = 10 scala> val addToX = (y: Int) => x + y addToX: (Int) => Int = <function1> scala> addToX(2) res0: Int = 12 scala> addToX(6) res1: Int = 16 scala> x = 5 x: Int = 5 scala> addToX(10) res2: Int = 15
Functional data structures
Functional programming revolves around the concept of immutability - nothing is ever changed - we have some input, we get some output and the input is not changed in the process. Consider a simple operation like an addition of an element to a list:
- the operation could modify the list to which the element is being added
- the operation can return a new list that is the same as the original, but has the additional element
Functional programming favours the second approach and Scala as a functional programming language provides data structures with the desired behaviour.
- List - think here of Lisp lists and not Java lists(unless you’re thinking of Java linked lists that is)
- Maps
- Sets
- Trees
- Stacks
Scala doesn’t force you into functional programming, though. Apart from the List, which is always immutable, we have two types of all the core data structures mentioned - immutable and mutable. The immutable data structures are those imported by default to promote a more functional programming style, but you can easily switch to the mutable versions and program in an imperative manner.
scala> import scala.collection.mutable.Map import scala.collection.mutable.Map scala> val phoneBook = Map("Bozhidar" -> 123, "Ivan" -> 456) phoneBook: scala.collection.mutable.Map[java.lang.String,Int] = Map((Ivan,456), (Bozhidar,123)) scala> phoneBook += "Maya" -> 53434 res13: phoneBook.type = Map((Maya,53434), (Ivan,456), (Bozhidar,123))
List almighty
The list is a core data structure in functional programming because it is recursively defined and therefore it’s very suitable for use in recursive algorithms. A list is composed of cons cells, each having two components - the value it holds and a reference to a next cons cell. The last cell points to a special value - Nil (which happens to represent an empty list).
1 | -> 2 | -> 3 | -> Nil
Here’s some things you can do with Scala’s lists:
scala> 1 :: 2 :: 3 :: 4 :: 5 :: Nil res3: List[Int] = List(1, 2, 3, 4, 5) scala> val names = List("Neo", "Trinity", "Morpheus", "Tank", "Dozer") names: List[java.lang.String] = List(Neo, Trinity, Morpheus, Tank, Dozer) scala> names.length res4: Int = 5 scala> names.foreach(println) Neo Trinity Morpheus Tank Dozer scala> names.map(_.toUpperCase) res6: List[java.lang.String] = List(NEO, TRINITY, MORPHEUS, TANK, DOZER) scala> names.forall(_.length > 5) res7: Boolean = false scala> names.forall(_.length > 2) res8: Boolean = true scala> names.filter(_.startsWith("T")) res9: List[java.lang.String] = List(Trinity, Tank) scala> names.exists(_.length == 3) res10: Boolean = true scala> names.drop(2) res11: List[java.lang.String] = List(Morpheus, Tank, Dozer) scala> names.reverse res12: List[java.lang.String] = List(Dozer, Tank, Morpheus, Trinity, Neo) scala> names.sortBy(_.length) res13: List[java.lang.String] = List(Neo, Tank, Dozer, Trinity, Morpheus) scala> names.sort(_ > _) res14: List[java.lang.String] = List(Trinity, Tank, Neo, Morpheus, Dozer) scala> names.slice(2, 4) res16: List[java.lang.String] = List(Morpheus, Tank)
Pattern matching
You can think of Scala’s pattern matching as a super charged version of switch, capable of matching on a variety of criteria and of destructuring that matched objects. Here’s a simple example:
scala> def testMatching(something: Any) = something match { | case 1 => "one" | case "two" => 2 | case x: Int => "an integer number" | case x: String => "some string" | case <xmltag>{content}</xmltag> => content | case head :: tail => head | case _ => "something else entirely" | } testMatching: (something: Any)Any scala> testMatching(1) res18: Any = one scala> testMatching("two") res19: Any = 2 scala> testMatching(2) res20: Any = an integer number scala> testMatching("matrix") res21: Any = some string scala> testMatching(<xmltag>this is in the tag</xmltag>) res22: Any = this is in the tag scala> testMatching(List(1, 2, 3)) res23: Any = 1 scala> testMatching(3.9) res24: Any = something else entirely
Pattern matching gives you a new way to implement common programming task. For instance consider the following trivial problem - computing the length of a list:
def length(list: List[Any]): Int = list match { case head :: tail => 1 + length(tail) case Nil => 0 }
Sure, it’s not tail-recursive, but it’s pretty neat. Now that I mentioned tail-recursion I should probably say a bit more about it. Recursive solutions generally look very nice in source form, but performance-wise are not that great because each recursive call creates a new stack frame and what’s even worse is that stack frames are limited - create too many of them and your program will blow up. This doesn’t mean that we should start coding everything imperatively, of course. Some compilers have the ability to optimize away recursive calls if the last thing that happens in the recursive function is a call to the function itself. In the case of our function length, unfortunately, the last call happens to be of the method + of the object 1 (of class Int). We can improve the solution this way:
def length(list: List[Any]): Int = { def lengthrec(list: List[Any], result: Int): Int = list match { case head :: tail => lengthrec(tail, result + 1) case Nil => result } lengthrec(list, 0) }
Notice that we now have a nested helper method with a second parameter, an accumulator value. This pattern often recurs when dealing with tail recursion - we take the original recursive definition and introduce a helper method using accumulator that is tail recursive. The outer method just calls the helper method and waits for the result. The Scala compiler will translate internally this recursive function into a something like a loop and the performance will be greatly improved, while preserving the clarity of the recursive approach.
Some languages (like Scheme) will always optimize tail calls. Because of limitations in the JVM not all tail calls can be optimized in Scala (for now), but some tails recursion is better than none.
Parallel programming
With. Actors are not a new idea - Scala’s actor library draws heavy inspiration from Erlang - a programming language notable for its support for the development of distributed highly parallel systems.
The Scala Actors library provides both asynchronous and synchronous message sends (the latter are implemented by exchanging several asynchronous messages). Moreover, actors may communicate using futures where requests are handled asynchronously, but return a representation (the future) that allows to await the reply.
All actors execute in parallel by their nature. Each actor acts as if it contains its own dedicated thread of execution.
Here’s a very simple actor example. The echoActor runs forever and waits for messages:
import scala.actors.Actor._ val echoActor = actor { while (true) { receive { case msg => println("received: "+msg) } } } echoActor ! "Chuck Norris is the only real actor!" echoActor ! "You don't find Chuck Norris - Chuck Norris finds you!"
Here the actor just waits for messages and responds to them by printing them to the console. Since the article’s size is already quite impressive I won’t go into any further details about the actors.
I want you to know that actors are not the only way to write parallel programs in Scala. You still have access to the native Java (or .Net) primitive like threads, locks, executors, etc. Another option is the Scala implementation of Software Transactional Memory(STM) - a parallel programming model made recently popular by the Clojure programming language. Scala’s implementation is a work in progress and you can have a look a it here. STM is basically a programming technique that lets you model concurrent operations in a way similar to db transactions - you combine the critical code in a transaction and if possible execute it and commit the transaction, otherwise just rollback it and maybe try again after a while. Note that this is a great oversimplification of what’s actually happening - for all the gory details you should read the exhaustive documentation.
Tools
We all know that even the best programming language can be rendered useless by the lack of good development tools for it - powerful text editors, integrated development environments, profilers, build tools, etc. Scala is a relatively young programming language that became really popular just recently and as a result there are still no development environments for Scala as powerful as those for Java (although since both languages use static typing eventually the environments will be on par). Most popular Java IDEs features feature some form of Scala support and most Java build tools as well.
- IDE
IntelliJ IDEA - the ultimate Scala IDE at the moment. It works quite well, but it’s a bit buggy that the moment (which is to be expected of something with some many beta features).
Eclipse - the most popular Java IDE has a Scala plug-in that until recently was mostly useless, but currently is being totally reworked and the next stable version will bring usable Scala support to the Eclipse users. The development of the new Scala plug-in is headed by none other than Martin Odersky himself. Don’t bother using the older version at all - just grab the latest beta.
NetBeans - Presently the Scala support in NetBeans is a bit basic, but it’s usable.
Emacs ENSIME - Ok, I admit - Emacs is not actually an IDE per se, but it’s still much more powerful than most IDEs. Emacs happens to have an excellent Scala mode, called ENSIME that gives you code completion, instant feedback, an integrated REPL, SBT integration, refactorings and other goodies in an Emacs package. The project attempts to be the equivalent of the legendary SLIME ( an Emacs mode for Common Lisp) for Scala. ENSIME is integrated into the Emacs Dev Kit(maintained by yours truly).
- Scala distribution
scala - A Scala REPL for exploratory programming; it’s also the Scala “interpreter” and the Scala class runner
scalac - the Scala compiler
fsc - fast Scala compiler. The Scala compiler is notoriously slow to start and fsc is a partial solution to this problem. The fsc runs as a daemon and waits to receive files to compile. Maven’s scala:cc and sbt’s ~compile continuous compilation task use fsc internally.
sbaz -.
- Build tools
Killer apps
Scala presently doesn’t have that many killer apps. Here are the most prominent:
- Lift web framework - Lift is a web framework that has cherry-picked some of the best ideas from existing frameworks and added some novelties of its own to harness the capabilities of the Scala programming language.
- Lazy page loading
- Parallel rendering
- Comet & Ajax
- Wiring
- Designer friendly templates
- Wizard
- Security
Play framework - Play focuses on developer productivity and targets RESTful architectures. It has both a Java and a Scala API. It’s considered by many to be the first Java web framework that was actually made by web developers.
Akka - A powerful library for writing concurrent applications using Actors, STM & Transactors. It has both Scala and Java API.
- SBT - a powerful build tool
Success stories
- Twitter - you remember how often Twitter used to go down because of overloads and suddenly the problems stopped - no, this was the moment in which Twitter’s backend was rewritten in Scala (that moment never actually came)… I have it on good authority that the problem was actually resolved by great improvements in their Ruby code base. But they use Scala there - Twitter had a Ruby-based queueing system that we used for communicating between the Rails front ends and the daemons that often crashed under heavy loads, and they ended up replacing that with one written in Scala.
- Four square - Four square uses Lift as well
- SAP
- Guardian.co.uk
Comparison to Java
It’s only natural that Java developers are interested in how Scala stacks up to Java:
- Pros
- Scala is fast, just as fast as Java. Some might wonder why this is a feature - they should take a look at the performance of the most of the other JVM langs and they’ll understand. Granted, all of the performance benefits come from the use of static typing in Scala, but Scala’s code is often as concise as the code written in a dynamic language like Ruby or Groovy.
- Great Java interoperability
- Scala removes a lot of the incidental complexity of programming and let’s you express your thoughts directly in the source code
- The syntax of Scala is mostly uniform and you can usually easily create new abstractions that look like language built-ins.
- Scala features great support for parallel programming.
- Runs on both Java and .Net (at least in theory)
- Cons
- Some aspects of the language are fairly complex like the subtyping rules for instance. This will probably scare off some people, but I can assure you that this complexity is superficial and once you’ve grasped enough of Scala everything will fall into place and seem to you the most natural thing in the world.
- Calling Scala from Java is not as easy as calling Java from Scala.
- The core API is still subject to constant changes and most new Scala version are not backward compatible with the old ones (unlike in Java).
- Scala’s community (albeit very friendly and helpful) is current tiny compared to Java’s. You might not get an assistance from the community as quickly as you’d get it for Java related problems.
Resources
- Books
- Programming Scala
- great free on-line book
- Programming in Scala - the holy bible of Scala. The first edition is available for free on-line.
- Blogs & Websites
- Exercises
Epilogue
Scala’s future is nothing but bright. It uses static typing, which is familiar to so many Java and C# developers, and is also the prerequisite for creating very helpful IDEs. Scala runs on the venerable Java platform and easily leverages all of its power while adding a lot of magic of its own - implicits, type inference, pattern matching, functional programming support, actors and others.
It’s my personal opinion that if any language has the chance to displace Java as the king of the world - that might be Scala. In all likelihood this will never happen - rarely has the greatest solutions enjoyed the greatest popularity (remember the Betamax vs VHS?). I do believe, however, that Scala will capture a significant market share in the coming years - mainly due to it excellent support for building distributed systems.
Until next time and the next chapter of the story, dedicated to the rising star of the JVM world - Clojure. | https://batsov.com/articles/2011/05/08/jvm-langs-scala/ | CC-MAIN-2020-24 | refinedweb | 5,374 | 59.13 |
Aros/User/DOS
Contents
- 1 The AROS shell
- 2 Beginners Tutorial / Basic Usage
- 3 AROS dos script scripting
- 4 Escape Codes
- 5 Drives, Files, Assigns, Directories
- 6 AROS DOS Commands Reference
- 7 Examples
The AROS shell[edit]
In Wanderer (AROS Desktop / GUI), hit RightAROS + w (or F12 + w) (or use right mousebutton to access Wanderer's menu on the top of the screen) to open a shell window. To close the shell window, click on the top left X of the shell window or type in
endcli
Beginners Tutorial / Basic Usage[edit]
By default, the current directory is being displayed as part of your shell prompt. By default, your starting point is 'System:', the OS' root directory.
System:>
Type 'dir' and hit return. You will see the contents of the current directory.
System:>dir
You can run an executable or enter a directory just by typing it's name (and hitting return). Enter the 'C' directory simply by typing 'c' (AROS DOS is case insensitive):
System:>c
Now press the up-arrow button twice. AROS shell has got a command history, which allows you to repeat or re-use commands quickly. Now you should see the 'dir' command again, so hit return. You will see the contents of the 'c' directory you've just entered.
System:c>dir
This directory is AROS' primary location for executables which can be run from any directory. Now type '/' (just a slash) and hit return. You've just moved up one directory, back to 'System:'
System:>
Now try another 'dir' like command (which resides in the 'c' directory), 'list':
System:>list
The output is quite the same as 'dir'. But you can control the 'list' output with options. AROS DOS command line options are recognized by their name, and eventually their position on the command line. Try this:
System:>list sub d
The output will now consist of all the directories contents which names contain the substring 'd'. Another example, another option:
System:>list sub d all
This will list the contents matching 'd' recursively.
AROS dos script scripting[edit]
IF <condition>
these commands are executed if the condition is true
ELSE
these commands are executed if the condition is false
ENDIF
<condition> can be one of
WARN - return code of the previous command is 5 or higher.
ERROR - return code of the previous command is 10 or higher.
FAIL - return code of the previous command is 20 or higher.
EXISTS <filename> - check if file or directory exists.
<a> EQ <b> - string comparison.
<a> EQ <b> VAL - numeric comparison.
<a> GT <b> - same as EQ, just means "greater than".
<a> GE <b> - same as EQ, just means "greater or equal".
any of the above can be negated by NOT. e.g. use NOT GT for "less or equal" or NOT GE for "less than".
Escape Codes[edit]
07 Bell - Flash screen and sound bell 08 Backspace - move cursor back one position 09 vertical tab - move cursor up one line 10 line feed - move cursor down one line 11 is not listed in my book 12 form feed - clear screen 13 Carriage return - move cursor to start of line 14 Set MSB of each character. (Print extended chars) 15 Clear MSB of each character. *e[c - Clear window and turn all modes off *e[0m - All modes turned off *e[1m - Bold text enabled *e[3m - Italic enable *e[4m - Uderline *e[7m - Inverted text enable *e[8m - text becomes invisible (grey on grey) *e[3xm - Text colour becomes colour x (0-7) *e[4xm - Background colour becomes colour x (0-7) *e[n@ - Insert n spaces at cursor position. *e[nA - Cursor up n lines. Default 1 *e[nB - Cursor down n lines. Default 1 *e[nC - Cursor forward n characters. Default 1 *e[nD - Cursor back n characters. Default 1 *e[nE - Cursor next n lines(to column 1). Default 1 *e[nH - Cursor to row n (Y position) *e[;nH - Cursor to column n (X position) *e[y;xH - Cursor to position X,Y *e[J - Erase from cursor to end of display *e[K - Erase from cursor to end of line *e[I - Insert line above line at cursor *e[M - Delete line at cursor *e[nS - Scroll up n lines *e[nT - Scroll down n lines *e[nt - set page length to n lines (in current font) *e[nu - Set line length in characters of current font *e[nx - Set left offset in characters *e[ny - Set top offset in lines *e[0 p - Disable cursor: Note space between zero and p *e[ p - Enable cursor. Note space
Example of coloured text in the shell
prompt "*E[>1m*E[1;37;41m%n.%s> *E[0;32;41m" echo "*E[0;0H*E[J"
*E[>1m
Is a so called SGR command that omits the first few parameters. It turns BOLD ON.
*E[1;37;41m%n.%s>
SGR command that tells: - boldface (1) - foregroundcolor 7 (37). Which means it is using pencolor #7 (which is black by default on aros, hence the setpencolor command). - use background color 1 (41). Which means it is using pencolor #1 (which is black by default on aros). - %n means printing the current opened cli/shell-number - %s means printing the current path - > print a nice pipe token after all the above (and also a space-character).
*E[0;32;41m
SGR command that tells: - plain text (0) - foregroundcolor 2 (32). Which means it is using pencolor #2 (which is white by default on aros). - backgroundcolor 1 (41). Which means it is using pencolor #1 (which is black by default on aros).
*E[0;0H
command 'Cursor position' - set row to 0 (0) - set column to 0 (0) Please note that this does not seem to work on AROS as on classic (not checked). it seems that the lowest nr for AROS to use is 1 (for both left and top).
*E[J
command 'erase in display' (no additional parameters used in this command).
Drives, Files, Assigns, Directories[edit]
A certain set of directories and files needed by the operating system will be present in every AROS distribution. Additionally, "assigns" (logical, not physical, drives) point to physical drive's partitions or locations in the partition's directory structure.
Physical drives[edit]
- By default harddrives on the IDE bus are assigned the drive names "DH0:", "DH1:", etc.
- By default USB pendrives are assigned the drive names "DU0:", "DU1:", etc.
- By default CD / DVD drives on the IDE bus are assigned the drive names "CD0:", "CD1:", etc.
Logical drives, "assigns"[edit]
SYS: Extras: DEVS: Development: L: S: LIBS: C: ENV: RAM: ENVARC: MUI: T:
Directories and files[edit]
SYS:Prefs[edit]
...contains all system preferences programs, like "Screenmode", "Locale", "Time", "Trident" (USB), etc. Is part of default path, thus entering "screenmode" in shell will bring up "Screenmode" prefs program.
SYS:Devs[edit]
...contains device drivers and datatypes. Move a file to the corresponding subdirectory of "SYS:Storage" to disable it (after reboot). More (currently disabled) device drivers or datatypes may be found unter "SYS:Storage", move to "Devs:" to enable (after reboot).
SYS:Storage[edit]
...is a directory meant to store optional or currently unused devices and datatypes. Move contents of "Devs:" (see above) here to disable device drivers (after reboot).
S:startup-sequence[edit]
...is a script that will be run when starting up the operating system. It is also used by some applications to store their individial requirements (if any - mosty this will be a line like "assign PROGRAMNAME: SYS:path/to/installation/of/PROGRAMNAME")
S:user-startup[edit]
...is a script that will be run by S:startup-sequence. It's the place to put your own stuff. Imagine you have some executable programs installed in a different directory than "C:" (or any other in default "path") but still want to access them without typing their full paths, you may add a line like this: "path WORK:path/to/my/program/ add".
It is also used by some applications to store their individial requirements (see above).
S:shell-startup[edit]
...is a script that will be run when starting up a new shell. By default, it contains commands that define the look of your shell prompt. See description of 'prompt' command.
AROS DOS Commands Reference[edit]
Additional DOS commands[edit]
DMS Format: DMS Read file[.DMS] [FROM dev:] [TEXT filetext] [CMODE mode] [LOW lowtrack] [HIGH hightrack] [NOVAL] [NOZERO] [ENCRYPT password] DMS Write file[.DMS],,, [TO dev:] [LOW lowtrack] [HIGH hightrack] [NOVAL] [NOTEXT] [NOPAUSE [DECRYPT password] DMS Repack file[.DMS] [TO dev:] [LOW lowtrack] [HIGH hightrack] [CMODE mode] DMS View file[.DMS],,, [FULL] DMS Text file[.DMS],,, DMS Test file[.DMS],,, DMS Help Purpose: To read, write or view Disk Masher disk images of floppy disks. Example: DMS Write MyDisk.DMS FROM DF0: Installer Format: Installer [SCRIPT] filename <[APPNAME] name> <[MINIUSER] level> <[DEFUSER] default> <[LOGFILE] logname> <[LANGUAGE] language> <NOPRETEND> <NOLOG> <NOPRINT> Purpose: To install an application via a installer script. Usually provided as a default tool for script files in icon. Example: Installer SCRIPT InstallApp APPNAME MyProgram LOGFILE DH0:MyProgram.log LHA Format: LHA [-options] <command> <archive[.LZH|LHA]> [[homedir] <filespec...] [@file] [destination] Purpose: To create, modify or list LHA or LZH files Examples: LHA a pictures.lha #?.jpg (archives all jpg files into pictures.lha) LHA l pictures.lha (lists all files in pictures.lha) LHA x pictures.lha (extracts all files from pictures.lha) LZX Format: LZX [-options] <command> <archive> [<file> ...] [<destdir>] Purpose: To create, modify or list LZX archive files. Examples: LZX a documents.lzx #?.doc (archives all doc files into documents.lzx) LZX l documents.lzx (lists all files in documents.lzx) LZX x documents.lzx (extracts all files from documents.lzx)
Additional DOS Information[edit]
Clear Screen Example: Echo "*E[0;0H*E[J" Purpose: Clears the screen. Uses printer commands to control text formatting in CLI, so *E is equivalent to ESC character.The command clear is normally defined using an Alias or an AmigaDOS script in S: folder. Text in Italics Example: Echo "*E[3mItalics*E[23m" Purpose: *E[3m turns on italics and *E[23m turns off italics Text in Bold Example: Echo "*E[1mBold*E[22m" Purpose: *E[1m turns on bold, and *E[22m turns off bold. Underline Text Example: Echo "*E[4mUnderline*E[24m" Purpose: *E[4m turns on underline, and *E24m turns off underline. Coloured Text Example: Echo "*E[32mRed Text*E[0m" Purpose: *E[nm where n=30-39 for foreground color or n=40-49 for background colour. *E[0m resets to normal character set.
Seems that Amiga shell allows an escape sequence to begin with just the 0x9B character, OR it allows the more traditional 0x1B character (033 in octal) followed the [ character. For sake of clarity, I will represent it by the C string \033[
AROS does not understand the \033[0m sequence, therefore you need to reset it using another colour sequence (on the assumption that the user has not changed the default Shell colours). This turns out to be \033[31;40m . It makes sense to play it safe, and follow it by the (ignored on AROS) \033[0m sequence.
Therefore my final highlight code looks like this:
printf("Before\033[32;43mDuring\033[31;40m\033[0mAfter\n");
Or if you code in E (like me) then it is this:
PrintF('Before\e[32;43mDuring\e[31;40m\e[0mAfter\n')
DOS commands only present in AROS[edit]
}
Examples[edit]
Is there a way to unzip more say 10 zipped archived at a time
list #?.zip lformat "unzip %N" >script execute script Resident >NIL: C:RequestChoice PURE Resident >NIL: C:RequestFile PURE ; $VER: DMSMaker v1.0 (11.7.96) Richard Burke lab Start if EXISTS ENV:Choice delete ENV:Choice >NIL: endif if EXISTS ENV:Tst delete ENV:Tst >NIL: endif if EXISTS ENV:V delete ENV:V >NIL: endif if EXISTS ENV:Re delete ENV:Re >NIL: endif if EXISTS ENV:DMS delete ENV:DMS >NIL: endif if EXISTS ENV:De delete ENV:De >NIL: endif if EXISTS ENV:DeDev delete ENV:DeVol >NIL: endif if EXISTS ENV:Cr delete ENV:Cr >NIL: endif if EXISTS ENV:CrSv delete ENV:CrSv >NIL: endif if EXISTS ENV:Mode delete ENV:Mode >NIL: endif if EXISTS ENV:Mode1 delete ENV:Mode1 >NIL: endif which DMS all >ENV:DMS RequestChoice >ENV:Choice "Welcome!" "Welcome to the DMSMaker! Choose an action" "Crunch" "Decrunch" "Repack" "View" "Test" "Quit" if $Choice EQ 1 lab Dev RequestFile >ENV:Cr DRAWERSONLY TITLE "Choose DEVICE to crunch" POSITIVE "Crunch" NEGATIVE "Return to menu" if WARN skip Start BACK endif if NOT EXISTS $Cr echo "DEVICE does not exist! Choose again!" skip Dev crunched file as..." ACCEPTPATTERN "#?.dms" FILE ".dms" POSITIVE "Save" NEGATIVE "Return to menu" if WARN skip Start BACK endif $DMS read $CrSv FROM $Cr CMODE $Mode echo "File crunched!" endif if $Choice EQ 2 lab Dec RequestFile >ENV:De TITLE "Choose FILE to decrunch" ACCEPTPATTERN "#?.dms" POSITIVE "Decrunch" NEGATIVE "Return to menu" if WARN skip Start BACK endif if NOT EXISTS $De echo "FILE does not exist! Choose again!" skip Dec BACK endif lab DecDev RequestFile >ENV:DeDev TITLE "Choose DEVICE to decrunch TO" DRAWERSONLY POSITIVE "Write" NEGATIVE "Return to menu" if WARN skip Start BACK endif if NOT EXISTS $DeDev echo "DEVICE does not exist! Choose again!" skip DecDev BACK endif $DMS write $De TO $DeDev echo "File decrunched!" endif if $Choice EQ 3 lab Rep RequestFile >ENV:Re TITLE "Choose FILE to repack" ACCEPTPATTERN "#?.dms" POSITIVE "Repack" NEGATIVE "Return to menu" FILE ".dms" if WARN skip Start BACK endif if NOT EXISTS $Re echo "File does not exist! Choose again!" skip Rep repacked file as..." ACCEPTPATTERN "#?.dms" FILE ".dms" POSITIVE "Save" NEGATIVE "Return to menu" if WARN skip Start BACK endif $DMS repack $Re TO $CrSv CMODE $Mode echo "File repacked!" endif if $Choice EQ 4 lab View RequestFile >ENV:V TITLE "Choose DMS FILE to view" POSITIVE "View" NEGATIVE "Return to menu" ACCEPTPATTERN "#?.dms" FILE ".dms" if WARN skip Start BACK endif if NOT EXISTS $V echo "FILE does not exist! Choose again!" skip View BACK endif $DMS view $V endif if $Choice EQ 5 lab Test RequestFile >ENV:Tst TITLE "Choose FILE to test" ACCEPTPATTERN "#?.DMS" POSITIVE "Test" NEGATIVE "Return to menu" FILE ".dms" if WARN skip Start BACK endif if NOT EXISTS $Tst echo "FILE does not exist! Choose again!" skip Test BACK endif $DMS test $Tst endif if $Choice EQ 0 skip End endif skip Start BACK lab End quit
resident >nil: c:search PURE resident >nil: c:requestfile PURE resident >nil: c:requestchoice PURE resident >nil: c:echo PURE resident >nil: c:copy PURE resident >nil: c:type PURE ; $VER: HappySearch v1.0 (25.4.97) Richard Burke requestchoice >env:int "HappySearch" "HappySearch searches the specified device/drawer*nto see if any files have been infected with the*n'Happy New Year 96!' virus, and informs of any*ninfected files it finds. Such files will have the*nvirus name printed below them in the scanned file*nlisting." "Okay" "Quit" if $int EQ 0 quit endif lab beg requestfile >env:dev TITLE "Choose drawer to search:" POSITIVE Search DRAWERSONLY if warn quit endif requestchoice >env:disp "Save?" "Results will be printed to screen.*nSave results to file too?*n(This is recommended)" "Yes" "No" if $disp EQ 1 requestfile >env:sav TITLE "Location:" POSITIVE Save DRAWER RAM: FILE Happy.tmp echo $sav >env:sav1 endif requestchoice >env:rec "Recurse?" "Search sub-directories recursively?" "Yes" "No" if $rec EQ 1 echo "Scanning files . . ." search $dev "Happy New Year 96!" ALL >env:hap else echo "Scanning files . . ." search $dev "Happy New Year 96!" >env:hap endif echo "Files scanned:" type env:hap if $disp EQ 0 delete >nil: env:hap else copy >nil: env:hap $sav1 echo "File listing saved as *e[33m$sav1*e[0m" endif requestchoice >env:mo "More?" "Scan another drawer?" "Yes" "No" if $mo EQ 1 skip beg back endif quit | https://en.wikibooks.org/wiki/Aros/User/DOS | CC-MAIN-2017-13 | refinedweb | 2,668 | 63.59 |
How To Setup A Stripe Checkout Page From Scratch
Aman Mittal—
June 17, 2019
Crowdbotics App Builder platform has a lot to offer when it comes to building an application. It helps both developers and non-developers to build, deploy, and scale applications by providing maintainable templates to make either your web or mobile application. Current web technologies such as Django, Nodejs, React, as well as to build a mobile app, React Native, and Swift templates are all supported as templates.
In this tutorial, you are going to learn how to setup a React and Nodejs template using Crowdbotics platform. Using that template project, we will setup a Stripe Payments Checkout Page from scratch. Make sure you checkout the requirements section before proceeding with the rest of the tutorial.
Table of Contents
- Requirements
- Setting up a Web with Crowdbotics App Builder Platform
- Enable Test Mode in Stripe
- Setting up the server
- Creating a Stripe Route
- Build a Checkout Component
- Testing the Checkout Component
- Conclusion
Requirements
To follow this tutorial, you are required to have installed the following on your local machine:
- Nodejs
v8.x.xor higher installed along with npm/yarn as the package manager
- Postgresql app installed
- Crowdbotics App builder Platform account (preferably log in with your valid Github ID)
- Stripe Developer Account and API key Access
What are we building? Here is a short demo.
Setting up a Web with Crowdbotics App Builder Platform
To setup, a new project on Crowdbotics app builder platform, visit this link and create a new account. Once you have an individual account, access the app building platform with those credentials, and the dashboard screen will welcome you like below.
If this is your first time using Crowdbotics platform, you might not be having any projects as shown above. Click on the button Create New Application. You will are going to be directed to the following screen.
This screen lets you select a template to create an application. For our current requirement, we are going to build a web application that is based on Nodejs and Reactjs. Select the Nodejs template in the Web App, scroll down the bottom of the page and fill in the name
stripe-checkout-demo and click on the button Create App.
Once the project is setup by the platform, you will be redirected back to the dashboard screen, as shown below. This screen contains all the details related to the new application you are setting up right now.
The reason I told you earlier to login with your Github account is that you can directly manage Crowdbotics app with your Github account. In the above image, you can see that even in the free tier, there many basic functionalities provided by Crowdbotics. Once the Github project is created, you will be able to either download or clone that Github repository to your local development environment.
After you have cloned the repository, execute the commands below in the order, they are specified but first, navigate inside the project directory from the terminal window. Also, do not forget to rename the file
.env.example to
.env before you run below commands in the project directory.
# navigate inside the project directorycd stripe-checkout-demo-4738# install dependenciesnpm install# open postgresql.app first# even though we only require the database for user login# for non-mac userspsql -f failsafe.sql# for mac userspsql postgres -f failsafe.sql# to run the applicationnpm start
The Crowdbotics scaffolded Nodejs project uses a custom a webpack server configuration to bootstrap the web app. Visit from a browser window to see the application in action.
Create a new account if you want and login in the app as a user, you will get a success toast alert at the bottom of the screen.
This section completes, how to setup a Nodejs and React app with Crowdbotics.
Enable Test Mode in Stripe
Before you start with the rest of this tutorial, please make sure you have a Stripe account. Login into the account and go to the dashboard window. From the left sidebar menu, make sure you have enabled the test mode like below.
In Stripe, you have access to two modes. Live and test. When in test mode, you will only see payments that were from the test application (like the app we are going to build in this tutorial). The developer menu gives you access to API keys that required to create the test application. These two types of API keys are:
- Publishable Key: used on the frontend (React client side of the application).
- Secret Key: used on the backend to enable charges (Nodejs side of the application).
Also, note that these API key changes when you change modes between live and test.
Setting up the server
To start building the server application, all we need are the following packages.
express
body-parser
cors
stripe
The first,
express and
body-parser are already available with current Crowdbotics generated the project. For more information, what
npm dependencies this project comes with, go through
package.json file. We need to install the other two. Make sure you run the following command at the root of your project.
npm install -S cors stripe
At the server side, we are going to create a RESTful API endpoint. The package
stripe will help us communicate with the Stripe Payment API. The
cors package in scenarios where your server and front-end are not sharing the same origins.
Inside
server/config folder create a new file called
stripe.js. This file will hold the configuration and secret key for the Stripe API. In general terms, this file will help to enable the configuration between the server side part of the application and the Stripe API itself.
const configureStripe = require('stripe')const STRIPE_SECRET_KEY = 'sk_text_XXXX'const stripe = configureStripe(STRIPE_SECRET_KEY)module.exports = stripe
In the above snippet, just replace the
sk_text_XXXX with your secret key. Lastly, to make the server work to add the following snippet of code by replacing the default middleware function as shown below. Open
app.js in the root of your project directory.
// ...app.use(bodyParser.json())app.use(bodyParser.urlencoded({extended: true}))// ...
Add this line of code will help to parse the incoming body with an HTTP request. The incoming body will contain the values like token, the amount, and so on. We do not have to get into details here since we are going to take a look at the Stripe dashboard which logs everything for us. But we will do this later after the frontend part is working.
Creating a Stripe Route
The second missing part in the backend of our application is route configuration for the payments to happen. First, create a new file called
payment.js inside
routes folder. Then, add the following snippet of code to it.
const stripe = require('../server/config/stripe')const stripeCharge = res => (stripeErr, stripeRes) => {if (stripeErr) {res.status(500).send({ error: stripeErr })} else {res.status(200).send({ success: stripeRes })}}const paymentAPI = app => {app.get('/', (req, res) => {res.send({message: 'Stripe Checkout server!',timestamp: new Date().toISOString})})app.post('/', (req, res) => {stripe.charges.create(req.body, stripeCharge(res))})return app}module.exports = paymentAPI
In the above snippet, we start by importing stripe instance that is configured with the secret key. Then, define a function that has a callback with one argument
res called
stripeCharge. This function is responsible for handling any incoming post request that will come from the client side when the user makes an official payment using Stripe API. The incoming request contains a payload of user's card information, the amount of the payment, and so on. This function further associates to a callback that runs only when the request to charge the user either fails or succeeds.
The post route uses this function with the argument
res. Next, inside the already existing
index.js file, import the
paymentAPI as shown below.
var express = require('express')var router = express.Router()var path = require('path')var VIEWS_DIR = path.resolve(__dirname, '../client/public/views')// import thisconst paymentAPI = require('./payment')module.exports = function(app) {// API Routesapp.use('/api/user', require(path.resolve(__dirname, './api/v1/user.js')))/* GET home page. */app.route('/*').get(function(req, res) {res.sendFile(path.join(VIEWS_DIR, '/index.html'))})// after all other routes, add thispaymentAPI(app)}
The configuration part required to make the backend work is done.
Build a Checkout Component
In this section, let us build a checkout component that will handle the communication by sending payment requests to the server as well as represent a UI on the client side of the application. Before you proceed, make sure you have installed the following dependencies that will help to build this checkout component. Go the terminal window, and execute the following command.
npm install -S axios react-stripe-checkout
axios is a promised based library that helps you make AJAX requests from the browser on the frontend side. This library is going to be used to make the payment request to the backend.
react-stipe-checkout is a ready-to-use UI component to capture a user's information at the time of the payment. The gathered information here which include user's card number and other details is then sent back to the backend.
Now, create a new component file called
client/app/components/. Add the following code to that file.
import React from 'react'import axios from 'axios'import StripeCheckout from 'react-stripe-checkout'const STRIPE_PUBLISHABLE = 'XXXX'const PAYMENT_SERVER_URL = ''const CURRENCY = 'USD'const successPayment = data => {alert('Payment Successful')console.log(data)}const errorPayment = data => {alert('Payment Error')console.log(data)}const onToken = (amount, description) => token =>axios.post(PAYMENT_SERVER_URL, {description,source: token.id,currency: CURRENCY,amount: amount}).then(successPayment).catch(errorPayment)const Checkout = ({ name, description, amount }) => (<StripeCheckoutname={name}description={description}amount={amount}token={onToken(amount, description)}currency={CURRENCY}stripeKey={STRIPE_PUBLISHABLE}/>)export default Checkout
In the above snippet, we import the required components from different libraries, but the most notable is
StripeCheckout. This is a UI component that
react-stripe-checkout consist. It accepts props such as
amount,
token,
currency and most importantly the
stripeKey. This stripe key is different from the one we used in the server side part of the application. The in the above snippet
STRIPE_PUBLISHABLE is the publishable key provided by the Stripe Payment API. This type of key used on the client side of an application irrespective of the framework you are using to build one.
You are also required to declare a
PAYMENT_SERVER_URL on which
axios will make a post request with different user information on the checkout. The methods
successPayment and
errorPayment are for testing purposes to see if things work the way we want them. The
token prop is an important one. It has its own method
onToken inside which the payment request is made. It gets triggered in both the cases whether the payment is successful or not.
react-stripe-checkout library creates this token on every request.
Testing the Checkout Component
The last piece of the puzzle is to make this whole application work is to import the Checkout component inside
App.jsx and the following snippet.
// ... after other importsimport Checkout from './Checkout.jsx'// ...render() {console.log(this.state.isLoading);return (<div><NavBar {...this.state} /><main className="site-content"><Checkout name='Crowdbotics' description='Stripe Checkout Example' amount={1000} /><div className="wrap container-fluid">{this.state.isLoading ? "Loading..." : this.props.children && React.cloneElement(this.props.children, this.state)}</div></main><Footer {...this.state} /><MainSnackbar {...this.state} /></div>);}
Once you have added the snippet and modified the render function as shown, go back to the terminal window and run the command
npm start. Visit the URL from your browser window, and you will notice that there is a new button, as shown below. Notice the
amount prop. The value of
1000 here represents only
$10.00. Fun fact, to make a valid stripe payment, you least amount required is more than 50 cents in American dollars.
Now, click on the the button Pay With Card and enter the following test values.
- Card number: 4242 4242 4242 4242 (Visa)
- Date: a future date
- CVC: a random combination of three numbers
On completion, when hit the pay button, there will be an alert message whether the payment was successful or not. See the below demo.
If you go to the Stripe Dashboard screen, in the below screen, you can easily notice the amount of activity logged.
There are proper logs generated with accurate information coming this web application.
Conclusion
This completes the step-by-step guide to integrate Stripe Payment API in a web application built using Reactjs and Nodejs. In this tutorial, even though we used Crowdbotics generated project to focus more on the topic rather than building a complete fullstack application from scratch. You can easily use the code snippets and knowledge gained in your own use cases.
Originally published at Crowdbotics | https://amanhimself.dev/how-to-setup-a-stripe-checkout-page-in-a-crowdbotics-app/ | CC-MAIN-2020-10 | refinedweb | 2,144 | 56.55 |
Style your Pandas DataFrame and Make it Stunning
This article was published as a part of the Data Science Blogathon
Introduction
Pandas is an important data science library and everybody involved in data science uses it extensively. It presents the data in the form of a table similar to what we see in excel. If you have worked with excel, you must be aware that you can customize your sheets, add colors to the cells, and mark important figures that need extra attention.
While working with pandas, have you ever thought about how you can do the same styling to dataframes to make them more appealing and explainable? Generating reports out of the dataframes is a good option but what if you can do the styling in the dataframe using Pandas only?
That’s where the Pandas Style API comes to the rescue. This detailed article will go through all the features of Pandas styling, various types of built-in functions, creating our custom functions, and some of its advanced usages.
Introduction to Pandas Styling
A pandas dataframe is a tabular structure with rows and columns. One of the most popular environments for performing data-related tasks is Jupyter notebooks. These are web-based platform-independent IDEs. In Jupyter notebooks, the dataframe is rendered for display using HTML tags and CSS. This means that you can manipulate the styling of these web components.
We will see this in action in upcoming sections. For now, let’s create a sample dataset and display the output dataframe.
import pandas as pd import numpy as np np.random.seed(88) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[3, 3] = np.nan df.iloc[0, 2] = np.nan
Output Dataframe (Without Styling)
Doesn’t this look boring to you? What if you transform this minimal table to this:
The transformed table above has:
- Maximum values marked yellow for each column
- Null values marked red for each column
- More appealing table style, better fonts for header, and increased font size.
Now, we will be exploring all the possible ways of styling the dataframe and making it similar to what you saw above, so let’s begin!
Styling the DataFrame
To access all the styling properties for the pandas dataframe, you need to use the accessor (Assume that dataframe object has been stored in variable “df”):
df.style
This accessor helps in the modification of the styler object (df.style), which controls the display of the dataframe on the web. Let’s look at some of the methods to style the dataframe.
1. Highlight Min-Max values
The dataframes can take a large number of values but when it is of a smaller size, then it makes sense to print out all the values of the dataframe. Now, you might be doing some type of analysis and you wanted to highlight the extreme values of the data. For this purpose, you can add style to your dataframe that highlights these extreme values.
1.1 For highlighting maximum values: Chain “.highlight_max()” function to the styler object. Additionally, you can also specify the axis for which you want to highlight the values. (axis=1: Rows, axis=0: Columns – default).
df.style.highlight_max()
1.2 For highlighting minimum values: Chain “.highlight_min()” function to the styler object. Here also, you can specify the axis at which these values will be highlighted.
df.style.highlight_min()
Both Min-Max highlight functions support the parameter “color” to change the highlight color from yellow.
2. Highlight Null values
Every dataset has some or the other null/missing values. These values should be either removed or handled in such a way that it doesn’t introduce any biasness. To highlight such values, you can chain the “.highlight_null()” function to the styler object. This function doesn’t support the axis parameter and the color control parameter here is “null_color” which takes the default value as “red”
df.style.highlight_null(null_color="green")
set_na_rep(): Along with highlighting the missing values, they may be represented as “nan”. You can change the representation of these missing values using the set_na_rep() function. This function can also be chained with any styler function but chaining it with highlight_null will provide more details.
df.style.set_na_rep("OutofScope").highlight_null(null_color="orange")
3. Create Heatmap within dataframe
Heatmaps are used to represent values with the color shades. The higher is the color shade, the larger is the value present. These color shades represent the intensity of values as compared to other values. To plot such a mapping in the dataframe itself, there is no direct function but the “styler.background_gradient()” workaround does the work.
df.style.background_gradient()
There are few parameters you can pass to this function to further customize the output generated:
- cmap: By default, the “PuBu” colormap is selected by pandas You can create a custom matplotlib colormap and pass it to the camp parameter.
- axis: Generating heat plot via rows or columns criteria, by default: columns
- text_color_threshold: Controls text visibility across varying background colors.
4. Table Properties
As mentioned earlier also, the dataframe presented in the Jupyter notebooks is a table rendered using HTML and CSS. The table properties can be controlled using the “set_properties” method. This method is used to set one or more data-independent properties.
This means that the modifications are done purely based on visual appearance and no significance as such. This method takes in the properties to be set as a dictionary.
Example: Making table borders green with text color as purple.
df.style.set_properties(**{'border': '1.3px solid green', 'color': 'magenta'})
5. Create Bar charts
Just as the heatmap, the bar charts can also be plotted within the dataframe itself. The bars are plotted in each cell depending upon the axis selected. By default, the axis=0 and the plot color are also fixed by pandas but it is configurable. To plot these bars, you simply need to chain the “.bar()” function to the styler object.
df.style.bar()
6. Control precision
The current values of the dataframe have float values and their decimals have no boundary condition. Even the column “A”, which had to hold a single value is having too many decimal places. To control this behavior, you can use the “.set_precision()” function and pass the value for maximum decimals to be allowed.
df.style.set_precision(2)
Now the dataframe looks clean.
7. Add Captions
Like every image has a caption that defines the post text, you can add captions to your dataframes. This text will depict what the dataframe results talk about. They may be some sort of summary statistics like pivot tables.
df.style.set_caption("This is Analytics Vidhya Blog").set_precision(2).background_gradient()
(Here, different methods have been changed along with the caption method)
8. Hiding Index or Column
As the title suggests, you can hide the index or any particular column from the dataframe. Hiding index from the dataframe can be useful in cases when the index doesn’t convey anything significant about the data. The column hiding depends on whether it is useful or not.
df.style.hide_index()
9. Control display values
Using the styler object’s “.format()” function, you can distinguish between the actual values held by the dataframe and the values you present. The “format” function takes in the format spec string that defines how individual values are presented.
You can directly specify the specification which will apply to the whole dataset or you can pass the specific column on which you want to control the display values.
df.style.format("{:.3%}")
You may notice that the missing values have also been marked by the format function. This can be skipped and substituted with a different value using the “na_rep” (na replacement) parameter.
df.style.format("{:.3%}", na_rep="&&")
Create your Own Styling Method
Although you have many methods to style your dataframe, it might be the case that your requirements are different and you need a custom styling function for your analysis. You can create your function and use it with the styler object in two ways:
- apply function: When you chain the “apply” function to the styler object, it sends out the entire row (series) or the dataframe depending upon the axis selected. Hence, if you make your function work with the “apply” function, it should return the series or dataframe with the same shape and CSS attribute-value pair.
- apply map function: This function sends out scaler values (or element-wise) and therefore, your function should return a scaler only with CSS attribute-value pair.
Let’s implement both types:
Target: apply function
def highlight_mean_greater(s): ''' highlight yellow is value is greater than mean else red. ''' is_max = s > s.mean() return ['background-color: yellow' if i else 'background-color: red' for i in is_max]
df.style.apply(highlight_mean_greater)
Target: apply map function
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val < 0 else 'black' return 'color: %s' % color
df.style.apply(color_negative_red)
Table Styles
These are styles that apply to the table as a whole, but don’t look at the data. It is very similar to the set_properties function but here, in the table styles, you can customize all web elements more easily.
The function of concern here is the “set_table_styles” that takes in the list of dictionaries for defining the elements. The dictionary needs to have the selector (HTML tag or CSS class) and its corresponding props (attributes or properties of the element). The props need to be a list of tuples of properties for that selector.
The images shown in the beginning, the transformed table has the following style:
styles = [ dict(selector="tr:hover", props=[("background", "#f4f4f4")]), dict(selector="th", props=[("color", "#fff"), ("border", "1px solid #eee"), ("padding", "12px 35px"), ("border-collapse", "collapse"), ("background", "#00cccc"), ("text-transform", "uppercase"), ("font-size", "18px") ]), dict(selector="td", props=[("color", "#999"), ("border", "1px solid #eee"), ("padding", "12px 35px"), ("border-collapse", "collapse"), ("font-size", "15px") ]), dict(selector="table", props=[ ("font-family" , 'Arial'), ("margin" , "25px auto"), ("border-collapse" , "collapse"), ("border" , "1px solid #eee"), ("border-bottom" , "2px solid #00cccc"), ]), dict(selector="caption", props=[("caption-side", "bottom")]) ]
And the required methods which created the final table:
df.style.set_table_styles(styles).set_caption("Image by Author (Made in Pandas)").highlight_max().highlight_null(null_color='red')
Export to Excel
You can store all the styling you have done on your dataframe in an excel file. The “.to_excel” function on the styler object makes it possible. The function needs two parameters: the name of the file to be saved (with extension XLSX) and the “engine” parameter should be “openpyxl”.
df.style.set_precision(2).background_gradient().hide_index().to_excel('styled.xlsx', engine='openpyxl')
Conclusion
In this detailed article, we saw all the built-in methods to style the dataframe. Then we looked at how to create custom styling functions and then we saw how to customize the dataframe by modifying it at HTML and CSS level. We also saw how to save our styled dataframe into excel files.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2021/06/style-your-pandas-dataframe-and-make-it-stunning/ | CC-MAIN-2022-27 | refinedweb | 1,868 | 55.34 |
In this article, we will briefly learn what React Hooks are, the types of hooks, and also basic examples of using some of these hooks in your React app.
What Are React Hooks?
React Hooks are built-in functions that allow you to use state within function components. Introduced as special APIs in the React 16.8 version released in 2019, Hooks will allow you to ‘hook into’ React features such as lifecycle methods. A feat that was previously only possible using class components.
React Hooks are incredibly powerful because they allow React developers to transform stateless functional components from just rendering reusable UIs to being capable of saving and maintaining state and logic. Before that, developers found it hard to reuse logic and share state between class components without using even more complex react abstractions. React Hooks made it possible to extract both stateful logic between components.
In summary, here are benefits that developers gained from the introduction of React Hooks.
- More straightforward code structure that does away with the ‘this and binds’ keywords.
- Easier to reuse logic and share state without dealing with complex React abstractions that are hard to test and manage.
- A more precise top-down one-way data flow is possible without disrupting your existing components’ order.
- When optimally used, React Hooks can help you do away with the need to integrate a state management library.
Common React Hooks
There are various types of in-built react hooks. You can even create your own Custom Hooks containing your own desired functional logic, which you can reuse across different components.
The React 16.8 release came with ten built-in hooks categorized into two: Basic Hooks and Additional Hooks. Of these hooks, we will examine two hooks that are the most commonly used: useState and useEffect.
UseState React Hook
The useState Hook is the most popular React hook. It allows you to ‘use state’ in a function component. This means you can read, manipulate and update state using the useState Hook.
A basic rendition of the useState Hook is shown below:
const [state, setState] = useState(initialState);
For example, the sample above has a state which is initially the same value as initialState. The initialState can take a number, string, or even an array depending on the data type at hand. setState is a function that’s used to update the state value. E.g. setState(updatedState).
Let’s use the useState Hook in a simple, functional component.
function Age() { const [age, setAge] = useState(10); return ( <div> <p>I am {age} Years Old</p> <div> <button onClick={() => setAge(age + 1)}>Increase my age! </button> <button onClick={() => setAge(age - 1)}>Decrease my age! </button> </div> </div> ) }
Let’s quickly explain how the above code works:
- We have the basic rendition of the hook:
const [age, setAge] = useState(10);
age has an initial state of 10 which we then call between the <p> tag.
- The buttons have an onClick handler which calls the setAge function, which will increase and or decrease our initial age state depending on the button clicked.
UseEffect React Hook
The useEffect Hook accepts a function that it runs after each render. It’s commonly used for performing side effects. This can range from manipulating the DOM or Browser APIs or even fetching data from external APIs. The useEffect hook also helps us achieve capabilities in a function component previously done by React lifecycle methods. Think of the useEffect Hook as the combination of the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods. Besides, we can also set the useEffect hook to render based on specific value changes.
Here’s a basic rendition of the useEffect Hook.
useEffect(functionToRun);
For example, let’s use the useEffect Hook more elaboratively using the previous functional component sample.
function Age() { const [age, setAge] = useState(10); useEffect(() => { setAge(20) },[]); return ( <div> <p>I am {age} Years Old</p> <div> <button onClick={() => setAge(age + 1)}> Increase my age! </button> <button onClick={() => setAge(age - 1)}> Decrease my age! </button> </div> </div> ); }
The useEffect at render sets the new age value to 20. We also passed an empty array which will let the useEffect hook run once only.
I’ve placed a console.log in the display above. We can see how the value of age state changed from the initial 10 to 20, caused by the useEffect hook. We then see how the state changes as we click the button.
Other React Hooks
There are also other Hooks such as useContext(), useMemo(), amongst others. You can have a look at the rest in the official documentation.
There are, however, two rules you should follow when using React Hooks.
- Always call hooks at the top level, as shown in the examples we’ve used. This means that we can’t call hooks inside loops, conditions, or nested functions.
- Only use Hooks from inside React function components.
Many Code IDEs like VSCode have an inbuilt linter that enforces these rules and more.
Users App
Finally, let’s create a more complex app using all we’ve learned about React, useState, and useEffect Hooks.
We will be fetching data from an external API with fake users data. As we’ve learned, this is a perfect use case for the useEffect Hook.
function Users(){ const [users, setUsers] = useState([]); useEffect(() => { fetch("") .then(res => res.json()) .then(data => setUsers(data)) }, []) return ( <ul> {users.map(user => ( <li key={user.id}> {user.name}lives in {user.address.city} </li> ))} </ul> ); }
In the sample above, you can see how we’ve used:
- The useState hook to set and update state including inside the useEffect Hook.
- The useEffect hook interacts with the Browser API called Fetch, which allows us to cull data from external APIs. We also passed an empty array to make sure it ran once.
Again in the video above, I’ve placed a console.log so you can see how we pulled out specific data to display.
Summary
We had fun! React Hooks are really powerful when used correctly. In conclusion, we learned what React Hooks are and the immense benefits they bring to developers. In addition, we also briefly examined the various types of hooks and the rules guiding their usage. Lastly, we created a simple React app that demonstrated how to use the useState and useEffect hooks.
If you’re feeling adventurous and want to build more apps with React hooks, check out our Stripe Checkout Integration with React article.
Unimedia Technology
Here at Unimedia Technology we have a team of React Developers that can help you develop your most complex react Applications. | https://www.unimedia.tech/2021/09/12/a-quick-introduction-to-react-hooks/?lang=ca | CC-MAIN-2022-27 | refinedweb | 1,094 | 56.86 |
InExclude list python plugin?
On 29/07/2016 at 14:51, xxxxxxxx wrote:
Hellooo,
I feel like I'm asking a lot this week, buuut does anyone have an example of a python plugin (this one is CommandData, but I don't think that'll matter) that has a functional InExclude list with it? I got one to show up with a simple
self.AddCustomGui(PLA_OBJECTS, c4d.CUSTOMGUI_INEXCLUDE_LIST, "PLA Objects", c4d.BFH_LEFT, 300, 50)
but I'm having trouble properly using/initializing it (no objects can be added to it in c4d; I suspect because I haven't attached any InExcludeData, yet).
I'm trying to make some of the scripts that get passed around here at work into proper plugins to make things less janky, but UserData setups can be a crutch...
Thanks a million
On 29/07/2016 at 21:20, xxxxxxxx wrote:
You probably just need to set up the containers for it.
Here's an example:
def CreateLayout(self) : res = self.LoadDialogResource(ResBasedMenu) #Loads GUI stuff from the .res file if desired ###### An InExclude gizmo created here in the .pyp code (not in the .res file) ####### #First create a container that will hold the items we will allow to be dropped into the INEXCLUDE_LIST gizmo acceptedObjs = c4d.BaseContainer() acceptedObjs.InsData(c4d.Obase, "") #accept all objects (change as desired) acceptedObjs.InsData(c4d.Tbase, "") #accept all tags (change as desired) .IEList = self.AddCustomGui(6666, c4d.CUSTOMGUI_INEXCLUDE_LIST, "", c4d.BFH_SCALEFIT|c4d.BFV_CENTER, 0, 0, IEsettings) return res
-ScottA
On 30/07/2016 at 10:22, xxxxxxxx wrote:
Awesome, Scott, thanks so much!
It seems obvious, now, but I was having a hard time doing it right. Here's to the weekend warriors ^^ | https://plugincafe.maxon.net/topic/9626/12928_inexclude-list-python-plugin | CC-MAIN-2020-40 | refinedweb | 282 | 65.32 |
Glossary of terms
polymorphism
- The quality or state of assuming different forms (or shapes)
Tips and cautions
These tips and cautions will help you write better programs and save you from agonizing over error messages produced by the compiler.
Tips
- Don't call class methods via object reference variables. Doing so clouds the fact that those methods are class methods.
Cautions
- If a class declares an abstract method, the class signature must include the
abstractkeyword. Otherwise, the compiler reports an error.
- If a subclass inherits an abstract method from an abstract superclass and does not provide a code body for that method, the compiler regards the subclass as abstract. Attempts to create objects from that subclass will cause the compiler to report errors.
Miscellaneous notes and thoughts.
Homework:
- All entries must be submitted no later than 12:00 p.m. Central Daylight Time on October 15, 2001.
- Please email your answers to Java 101 Challenge (no attachments). You can include either a copy of the questions with your answers or just the answers. However, I must be able to associate your answers with the respective questions.
- You must answer all questions.
- I will sort entries by submission date/time stamp. The first three individuals to achieve a score of 100 percent will receive sweatshirts. If only one person gets 100 percent, the first two individuals who achieve 99 percent will each receive a t-shirt. If no one achieves 100 percent, the first three individuals who achieve 99 percent will receive t-shirts. This process will continue until I find the first three individuals with the highest scores.
- Entries will not be returned.
- Winners will be contacted.
- The names of the three winners will appear in the November Java 101 column.
- This challenge is open to anyone.
- Neither JavaWorld nor Jeff Friesen will be held liable for any misunderstanding of challenge rules.
I've divided the quiz into four sections:
- Fill in the blanks (1-20): To submit answers in this section, simply specify each question's number followed by either a single word/phrase or a comma-delimited list of word/phrases (for those questions that have more than one blank).
- Multiple choice (21-25): To submit answers in this section, simply specify each question's number followed by the letter a, b, c, or d.
- True or false (26-50): To submit answers in this section, simply specify each question's number followed by the word true or false.
- Short answer (51-65): To submit answers in this section, simply specify each question's number followed by a brief paragraph or a few words.
- The object-oriented programming ________________ principle promotes the integration of state with behavior.
- A ________________ is a source code blueprint.
- Another name for a class instance is ________________.
- Java supports ________________ access levels for fields and methods. (Enter a number.)
- Another name for a read-only variable is ________________.
- Values passed to a method during a method call are known as ________________.
- ________________ passes a value to a method, and ________________ passes a reference.
- When only a single object can be created from a class, that class is known as a ________________ class.
- ________________ is a synonym for composition.
- The object-oriented programming ________________ principle promotes layered objects.
- Composition promotes ________________ relationships.
- A ________________ inherits fields and methods from a ________________.
- If class
Aextends class
B, and class
Adeclares a method that has the same name, return type, and parameter list as class
B's method, class
A's method is said to ________________ class
B's method.
- ________________ is Java's ultimate superclass.
- Arrays are ________________ cloned.
- The object-oriented programming ________________ principle promotes many forms.
- Class methods are ________________ to classes, and instance methods are ________________ to objects.
- Classes situated near the top of a class hierarchy represent ________________ entities, and classes lower in the class hierarchy represent ________________ entities.
- The
equals()method defaults to comparing object ________________.
- The
clone()method throws a ________________ if it cannot clone an object.
When declaring a field, which of the following access-level specifier keywords would you use so that only classes in the same package as the class that declares the field can access that field?
a)
public
b)
private
c)
protected
d) none of the above
Which keyword has something to do with object serialization?
a)
transient
b)
volatile
c)
synchronized
d)
native
Which of the following keywords do you use to achieve implementation inheritance?
a)
implements
b)
extends
c)
super
d)
this
Which method returns an object locked (behind the scenes) by static synchronized methods?
a)
toString()
b)
finalize()
c)
getClass()
d)
wait()
According to Sun's Java 2 SDK, how many public classes can be declared in a source file?
a) 1
b) 0
c) as many as desired
d) no more than 1 public class and 1 public interface
- True or false: Object-oriented programming emphasizes separating a program's data from its functionality.
- True or false: You must declare class fields with the
statickeyword.
- True or false: The integration of state and behaviors into objects is known as information hiding.
- True or false: When the JVM creates an object, it zeroes the memory assigned to each instance field.
- True or false: You can access local variables prior to specifying their declarations.
- True or false: You must initialize local variables before accessing them.
- True or false: Subclasses can override a superclass's final methods.
- True or false: An enumerated type is a reference type with an unrestricted set of values.
- True or false: When returning a value from a method, that method must not have a void return type.
- True or false: A class method cannot access an object's instance fields.
- True or false: The keyword
thiscan be used in any method to call a constructor that resides in the same class as that method.
- True or false: If a class declares no constructors, the compiler generates an empty no-argument constructor.
- True or false: You cannot extend final classes.
- True or false: You can use the keyword
superto call a superclass constructor from any method.
- True or false: You cannot make a field or method's access level more restrictive in a subclass.
- True or false: Java supports multiple implementation inheritance.
- True or false: A subclass can directly access a superclass's private fields.
- True or false: You can legally place code ahead of a constructor call (via either
thisor
super) in a constructor.
- True or false: Arrays are objects.
- True or false: You can declare read/write variables in an interface.
- True or false: All method signatures in an interface have a public access level.
- True or false: A class that inherits an abstract method from a superclass and does not override that method is also abstract.
- True or false: You can declare field variables in methods.
- True or false: Java's
newkeyword allocates memory for an object, and Java's
deletekeyword releases that memory.
- True or false: The
Objectclass declares 11 methods.
- If a subclass constructor does not include a call to a superclass constructor (via
super) or another subclass constructor (via
this), what happens?
What is wrong with the following code fragment?
class Sup { Sup (int x) { } } class Sub extends Sup { }
Is there anything wrong with the following code fragment?
abstract void hello () { System.out.println ("Hello") }
- Why would you use interfaces?
- List the four polymorphism categories.
- Suppose you create an object from a superclass and assign that object's reference to a superclass variable. Suppose you cast that variable's type from the superclass type to a subclass type before accessing a subclass field or calling a subclass method. What happens?
- Must a subclass constructor always call a superclass constructor?
- Explain two uses for the
superkeyword.
- A class can only extend one superclass. Is an interface subject to the same restriction (that is, can an interface only extend a single superinterface)?
- By default, what does an object's
toString()method return?
- What are hash codes?
- When does method overloading fail?
- Describe the difference between shallow cloning and deep cloning.
Why can't a class signature include both the
abstractand
finalkeywords?
- If you do not declare a class to be
public, must you declare it in a file whose filename matches the class name? For example, must you declare
class Account {}in
Account.java?
Part 6's homework answers
Below you will find the homework questions for "Object-Oriented Language Basics, Part 6," followed by their answers:
Why is it unwise to place the
NOT_STARTEDand
STARTEDconstants and the
isstarted()method in the
StartStopinterface? Placing the
NOT_STARTEDand
STARTEDconstants in the
StartStopinterface can lead to compiler error messages. Those error messages describe ambiguous constant references when a class implements multiple interfaces and one interface already declares
NOT_STARTEDand
STARTED, but with different types and/or initial values. If you recompile legacy classes that implement the new
StartStopinterface instead of the old
StartStopinterface, and one class implements an additional interface with different
NOT_STARTEDand
STARTEDconstants, you have a problem.
Don't place the
isStarted()method in the
StartStopinterface because recompilations of source code to legacy classes that implement
StartStopwill fail. The compiler will complain about those classes not providing code bodies for
isStarted(). Attempting to fix the problem by adding to each affected class an
isStarted()method that returns a default value only adds redundancy to those legacy classes -- and might require you to distribute new versions of the legacy classes. Furthermore, you might find that future source code/class maintenance will prove more difficult.
If an interface introduces a type into source code, and if a type consists of a set of data items in addition to a set of methods, where are the interface's data items? (Hint: constants are not the data items.)
The interface's data items are those objects whose classes implement the interface. A program applies the interface's methods to objects, just as a program applies a primitive type's operations to values of that type -- such as the integer type's addition operation to integer values. | http://www.javaworld.com/article/2075700/core-java/java-101-study-hall.html | CC-MAIN-2014-49 | refinedweb | 1,674 | 56.55 |
Have downloaded VLC.py, and placed it in my VLC install directory, where libvlc.dll is also present
On typing
import vlc
Traceback (most recent call last):
File "C:\Program Files
(x86)\VideoLAN\VLC\vlc.py", line 88,
in
dll = ctypes.CDLL('libvlc.dll') File
"C:\Python27\lib\ctypes__init__.py",
line 353, in init
self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is
not a valid Win32 application
Reposting my comment as an answer, since it fixed the problem:
I'm going to guess that the problem is trying to load a 32-bit DLL from a 64-bit process. You may be able to fix it by using a 32-bit Python build. | https://codedump.io/share/rcVaOTzBksna/1/vlc-python-bindings----error-193 | CC-MAIN-2017-09 | refinedweb | 116 | 67.86 |
This site uses strictly necessary cookies. More Information
When I try to change the color, in the console it "works" correctly.It shows the rbg values I picked, but in the scene and game views the text color stays white.
I also noticed that if I look at the color in the inspector (with the scene running) the color is white and the rgb values are - (65025, 46410, 22440, 255).These values are always the same every time I play the scene.
public class DotControl : MonoBehaviour
{
string curMenu;
// Use this for initialization
void Update()
{
GameObject start = GameObject.FindGameObjectWithTag("Start");
GameObject load = GameObject.FindGameObjectWithTag("Load");
GameObject exit = GameObject.FindGameObjectWithTag("Exit");
if (Input.GetAxisRaw("Vertical") > 0.9)
{
// get position
float posY = gameObject.transform.position.y;
// move dot
if (posY == 0)
{
iTween.MoveTo(gameObject, iTween.Hash("y", -4, "time", 0.1));
curMenu = "Exit";
Color oldExit = exit.renderer.material.color;
Color newExit = new Color(255,182,88,255);
Debug.Log(exit.renderer.material.color); //255,255,255,255
exit.renderer.material.SetColor("_Color", newExit);
Debug.Log(exit.renderer.material.color); //255,182,88,255
I tried using Red (255,0,0,255) and it worked properly."Named" color work apparently - red, blue, yellow, etcThe others don't.
Answer by Dxter
·
Sep 22, 2016 at 01:49 PM
Each color component is a floating point value with a range from 0.
Dropdown menu: how to make colour change across multiple scenes
0
Answers
My code has some invalid arguments
1
Answer
Changing My Sprites in Code
0
Answers
blocks coloring like in game The Stack?
1
Answer
Inventory Master DragItem.cs Error Cant change transform parent of a object that resides in a prefab?
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/318261/problem-change-3dtext-color-with-c-script.html | CC-MAIN-2021-43 | refinedweb | 284 | 52.87 |
Recently I started playing with Facebook’s awesome view library React . Once I have done with my experiments, I decided to publish a reusable component in NPM. Initially, I thought it was very easy but later I got into many problems, So I thought of writing it as a blog.
In this blog post, We will be creating a simple React component followed by publishing it into NPM.
Creating a React component
First, Let’s starts with creating a simple hello-world component in React. The source code is available in GitHub and check NPM for the updated package.
Before Starting the actual development ensure you have installed Node and NPM in your machine. I am not gonna cover how to install Node and NPM. Please check the official Node webbsite for more details.
Initilizing Node project
Use the below command to initialize node project in a folder.
npm init
It will ask some questions, complete it to generate a package.json file or copy paste the below into your package.json file.
{ "name": "react-hello-world", "version": "1.0.1", "description": "Simple package to learn how to publish react component into NPM", "main": "index.js", "author": "Raja Sekar
()", "license": "ISC" }
Installing dependencies
So before starting our development, we have to install dependencies for our project. In our case the only dependency is React.
npm install react —save
Installing development dependencies
For our development, we will be using ES6 and JSX syntax. Its is not possible to import or require the package if the consumer did to convert those JSX and ES6 into vanilla JavaScript. The component should be easy to use like just install, import it and use it. No one will sit and debug the issue in your component.
So we need to convert ES6 and JSX into vanilla JavaScript, So that the component works across in all the environment. So we will be using babel and couple of presets to transpile the ES6 and JSX code into pure vanilla JavaScript.
npm install babel-cli babel-preset-es2015 babel-preset-react babel-preset-stage-0 --save-dev
First React component
We are done with the environment setup, Let’s start writing out first react component.
//helloworld.js import React from 'react'; class ReactHelloWorld extends React.Component { render() { return ( <div>Hello world!!</div> ) } } export default ReactHelloWorld;
The above component will just print “Hello World” in the page. We have done with the component, now we have to convert our ES6/JSX into vanilla JavaScript to make sure it works in across all environment.
Configuring babelrc
Since we’re using babel to convert JSX/ES6 into vanilla JavaScript we have to configure babelrc file in root of our project. Create .bablerc file into our project root and copy paste the below code into it.
{"presets": ["es2015", "stage-0", "react"]}
Build Script
Now we will be using babel to convert our JSX/ES6 into vanilla javascript.
babel helloworld.js -o index.js
So the above script will convert the ES6/JSX code into plain vanilla javascript. But we have to run the script every time when we publish the component into NPM. So NPM provides many hooks which helps to make the publishing work easier.
NPM pre-publishing script
In package.json add the below script which runs every time when we publish the component into npm.
"scripts": { "build": "./node_modules/.bin/babel helloworld.js -o index.js", "prepublish": "npm run build" }
Committing to GitHub
Before publishing it into NPM, we have to make sure the component works fine. SO commit it into GitHub and check by installing it from the GitHub source.
git add . git commit -m ‘first compinet' git push
Now install the component from github source using,
npm install git://git@github.com/rajzshkr/react-hello-world.git —save
Importing and using the component
Once the component is installed, we have to check the behavior of the component by importing it.
import React from 'react'; import ReactDOM from 'react-dom'; import ReactHelloWorld from 'react-hello-world’; ReactDom.Render( <ReactHelloWorld />, document.getElementById(‘app’);
It should simply display “Hello world!!” on your page.
Publishing into NPM
Our component is ready to publish into NPM. Use the below commands to publish the component into NPM.
npm login // It will prompt for NPM credentials npm publish
Now you can install the component directly from the NPM using,
npm install react-hello-world
If you have any changes in your component, make sure you change the version number before publishing it.
Hope you enjoyed reading my blog, Let me know if you have any » Publishing React component in NPM
评论 抢沙发 | http://www.shellsec.com/news/13693.html | CC-MAIN-2017-04 | refinedweb | 767 | 56.66 |
//**************************************
// Name: Base10 Convertor
// Description:A small project that converts decimal numbers to 6 different bases. Hope it maybe usfull.
// By: Ben
//**************************************
// Base convert
// By DreamVB 00:01 19/10/2016
#include <iostream>
using namespace std;
using std::cout;
using std::endl;
string BaseConvert(int decimal, int radix){
//Base convertor
char hexmap[16] = { '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
string Ret = "";
int n = decimal;
int base = 0;
while (n >= radix){
base = (n % radix);
n /= radix;
Ret += hexmap[base];
}
//Add last hexmap char
Ret += hexmap[n];
//Reverse string
std::reverse(Ret.begin(), Ret.end());
return Ret;
}
int main(int argc, char *argv[]){
int dec = 0;
system("title Base10 Converting");
cout << "Enter a decimal number : ";
cin >> dec;
cout << endl;
cout << "Binary : " << BaseConvert(dec, 2).c_str() << endl;
cout << "Ternary : " << BaseConvert(dec, 3).c_str() << endl;
cout << "Quinary : " << BaseConvert(dec, 5).c_str() << endl;
cout << "Octonary: " << BaseConvert(dec, 8).c_str() << endl;
cout << "Decimal : " << BaseConvert(dec, 10).c_str() << endl;
cout << "Hexidecimal : " << BaseConvert(dec, 16).c_str() << endl;
system("pause");
return 0;
}
Other. | http://planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=13934&lngWId=3 | CC-MAIN-2017-47 | refinedweb | 173 | 65.32 |
Pretty much everybody who has ever tried to write a non-trivial template library met the problem of organizing template source code. Led by inertia, many C++ programmers try to organize template code the same way they did it with non-template code: declarations in header files, and definitions in CPP files. This attempt leads to linker errors when the point of instantiation is reached. For instance:
// swap.h template <typename T> void swap (T& left, T& right); //swap.cpp template <typename T> void swap (T& left, T& right) { T temp = left; left = right; right = temp; } // main.cpp #include "swap.h" int main() { int a = 1, b = 2; swap(a, b); }
will result in:
main.obj : error LNK2019: unresolved external symbol "void __cdecl swap<int>(int &,int &)" (??$swap@H@@YAXAAH0@Z) referenced in function _main Debug/Nonstandardvc71.exe : fatal error LNK1120: 1 unresolved externals
with MSVC 7.1.
Generally, there are two ways to organize template source code[1]:
The inclusion model is widely used within C++ community. I have written about it in my Code Project article: How to Organize Template Source Code, and I am sure there are also other good on-line resources that cover it. Here, I am going to concentrate on the separation model.
To use the separation model, we need the keyword
export:
// swap.h export template <typename T> void swap (T& left, T& right);
Function template
swap is now considered to be exported, and can be used without its definition being visible [2].
To be exported, a template definition must be in the same translation unit in which it was declared as exported [3]. In practice, it means that
export can be added to the definition [1]:
// swap.h template <typename T> void swap (T& left, T& right); // swap.cpp export template <typename T> void swap (T& left, T& right) { T temp = left; left = right; right = temp; } // main.cpp #include "swap.h" int main() { int a = 1, b = 2; swap(a, b); }
to a declaration preceding the definition in the same translation unit:
// swap.h export template <typename T> void swap (T& left, T& right); // swap.cpp template <typename T> void swap (T& left, T& right) { T temp = left; left = right; right = temp; } // main.cpp #include "swap.h" int main() { int a = 1, b = 2; swap(a, b); }
or even to both places, if you feel it improves the readability [2]:
// swap.h export template <typename T> void swap (T& left, T& right); // swap.cpp export template <typename T> void swap (T& left, T& right) { T temp = left; left = right; right = temp; } // main.cpp #include "swap.h" int main() { int a = 1, b = 2; swap(a, b); }
Note that I could not find the samples for the first case (
export added directly to the definition, but not to any declaration in header files) either on Comeau website or in the Vandevoorde-Josuttis book [2], and therefore I somewhat suspect this scenario not to be supported in practice. However, Stroustrup explicitly shows this technique in [1] and I could not find anything in the Standard [3] that would prevent it.
In any case, if a template is exported, its definition can be looked up across translation units. It is up to the compiler to ensure that exported definition is found in the point of instantiation.
Strictly speaking, only non-inline function templates, non-inline member function templates, non-inline member functions of class templates, and static data members of class templates can be exported. Class templates cannot be exported; however,
export keyword can be added to a class template declaration. This means that all its exportable members defined in that translation unit are exported:
export template<typename T> class C { public: //exported void NonInlineMemberFunction(); static int staticDataMember; class MemberClass {}; template <typename T2> void NonInlineFuncMemberTemplate(); // implicitely declared with export template <typename T1> class MemberClassTemplate {}; // not exported void InlineMemberFunction(){} int nonStaticDataMember; template <typename T3> void InlineFuncMemberTemplate(){} };
Templates defined in an unnamed namespace are not exported [3]. In fact, the next piece of code:
namespace { export template <typename T> void f(T value) {} }
will trigger a compiler error:
3: error: a member of an unnamed namespace cannot be declared "export"
when compiled on the Comeau online compiler.
The main problem with
export seems to be that it is a complicated feature to implement. Consequently, today there is only one commercially available compiler that supports it (EDG 3.3 based Comeau 4.3.3), and no indications that any other compiler vendor will include it any time soon. The cost of implementing
export seems to be so high that Herb Sutter and Tom Plum officially recommended removing it from the Standard, arguing that wide adoption of
export would set C++ back for up to two years [4]. As far as I know, the C++ standard committee voted against this proposal, and export is going to remain a part of standard C++.
Another problem is not really a problem but more an unrealistic expectation. Namely, some developers believe that
export would enable them to ship their template libraries without implementation source code, just as with non-template libraries. This belief is unfounded: when a library user instantiates a template, they still need access to the source (or, theoretically speaking, its equivalent in some form) to generate a template specialization. This is a nature of templates, and exporting does not change it. Therefore, even if
export was more widely available, it might have disappointed the template libraries writers.
If I am allowed to have any opinion on
export, (I have never had a chance to work with a compiler that supports this feature), I would like to see it implemented in Visual C++. Granted, if my job was developing C++ compilers, I would probably hate it, and if I was just a user of template libraries (most of the time I am, actually) I couldn�t care less about it. However, since I occasionally write some template code, I feel that
export would help me organize my source in a nicer, more readable and maintainable manner.
Microsoft Visual C++ 7.1 does not recognize
export keyword. The �swap� example gives the following two compiler errors:
error C2143: syntax error : missing ';' before ''template<'' error C2501: 'export' : missing storage-class or type specifiers
Herb Sutter, a Visual C++ architect, in his earlier interviews promised to push for 100% standard conformance, including
export. However, it seems that VC++ team has had other priorities lately (C++/CLI). Since
export is expensive to implement and there is no big demand for it, I would be surprised to ever see this feature in Microsoft C++ compilers. Of course, this is only my personal opinion � I have never heard such statements from anyone within Microsoft.
Microsoft Visual C++ 7.1 is among the vast majority of C++ compilers that do not support
export keyword, and there is no sign it will change in a near future. Most developers will probably never notice lack of
export unless they try to write some template code on their own. For template libraries developers,
export may have some value, but it is not clear how much at this point, since it has been implemented on only one compiler so far.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/mcpp/stdexport.aspx | crawl-002 | refinedweb | 1,206 | 60.95 |
..
An abstract view of some signals and slots connections
In Qt we have an alternative to the callback technique. We use signals and slots. A signal is emitted when a particular event occurs..
An example of signals and slots connections desire. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)
Together, signals and slots make up a powerful component programming mechanism.
A minimal C++ class declaration might read:
class Foo { public: Foo(); int value() const { return val; } void setValue( int ); private: int val; };
A small Qt class might read:
class Foo : public QObject { Q_OBJECT public: Foo(); int value() const { return val; } public slots: void setValue( int ); signals: void valueChanged( int ); private: int val; };
This class has the same internal state, and in their declaration.
Slots are implemented by the application programmer. Here is a possible implementation of Foo::setValue():
void Foo::setValue( int v ) { if ( v != val ) { val = v; emit valueChanged(v); } }
The line emit valueChanged(v) emits the signal valueChanged from the object. As you can see, you emit a signal by using emit signal(arguments).
Here is one way to connect two of these objects together:
Foo a, b; connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int))); b.setValue( 11 ); // a ==. If the signal is interesting to two different objects you just connect the signal to slots in both objects.
When a signal is emitted, the slots connected to it are executed immediately, just like a normal function call. The signal/slot mechanism is totally independent of any GUI event loop. The emit will return when all slots have returned.RangeControl::Range, it could only be connected to slots designed specifically for QRangeControl. Something as simple as the program in Tutorial meta object contains additional information such as the object's class name. You can also check if an object inherits a specific class, for example:
if ( widget->inherits("QButton") ) { // yes, it is a push button, radio button etc. }
Here is a simple commented example (code fragments from qlcdnumber.h ).
#include "qframe.h" #include "qbitarray.h" class QLCDNumber : public QFrame
QLCDNumber inherits QObject, which has most of the signal/slot knowledge, via QFrame and QWidget, and #include's the relevant declarations.
{ Q_OBJECT
Q_OBJECT is expanded by the preprocessor to declare several member functions that are implemented by the moc; if you get compiler errors along the lines of "virtual function QButton::className not defined" you have probably forgotten to run the moc or to include the moc output in the link command.
public: QLCDNumber( QWidget *parent=0, const char *name=0 ); QLCDNumber( uint numDigits, QWidget *parent=0, const char *name=0 );
It's not obviously relevant to the moc, but if you inherit QWidget you almost certainly want to have the parent and name arguments in your constructors, and pass them to the parent constructor.
Some destructors and member functions are omitted here; the moc ignores member functions.
signals: void overflow();
QL char *str ); void setHexMode(); void setDecMode(); void setOctMode(); void setBinMode(); void smallDecimalPoint( bool );
A slot is a receiving function, used to get information about state changes in other widgets. QLCDNumber uses it, as the code above indicates, to set the displayed number. Since display() is part of the class's interface with the rest of the program, the slot is public.
Several of the example programs connect the newValue().
}; | http://doc.trolltech.com/3.3/signalsandslots.html | crawl-001 | refinedweb | 569 | 53.81 |
A bridge between UFOs and FontTools.
Project description, which work exactly the same way:
from defcon import Font from ufo2ft import compileOTF ufo = Font('MyFont-Regular.ufo') otf = compileOTF(ufo) otf.save('MyFont-Regular.otf')
In most cases, the behavior of ufo2ft should match that of ufo2fdk, whose documentation is retained below (and hopefully is still accurate).
Naming Data.
Additionally, if you have defined any naming data, or any data for that matter, in table definitions within your font’s features that data will be honored.
Feature generation
If your font’s features do not contain kerning/mark/mkmk features, ufo2ft will create them based on your font’s kerning/anchor data.
In addition to Adobe OpenType feature files, ufo2ft also supports the MTI/Monotype format. For example, a GPOS table in this format would be stored within the UFO at data/com.github.googlei18n.ufo2ft.mtiFeatures/GPOS.mti.
Fallbacks
Most of the fallbacks have static values. To see what is set for these, look at fontInfoData.py in the source code.
In some cases, the fallback values are dynamically generated from other data in the info object. These are handled internally with functions.
Merging TTX
If the UFO data directory has a com.github.fonttools.ttx folder with TTX files ending with .ttx, these will be merged in the generated font. The index TTX (generated when using using ttx -s) is not required.
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/ufo2ft/ | CC-MAIN-2018-30 | refinedweb | 261 | 58.99 |
So last week a co-worker came to me and said he needed a “quick and dirty” application for keeping track of assets internally. I told him that I didn’t have enough time to do a full scale .Net web app but that perhaps RoR could give us what we were looking for. Within 30 minutes we had a pretty good looking model setup and was entering dummy data into it with the help of scaffolding. My co-worker assured me that this would be fine for now pending a handful of changes and validations to perform when entering data. That being said I set off to get a production server up and running. That’s where I left my sanity.
This post will just go over the steps I took to setup a RoR production server and getting deployment to work. The article that helped get everything setup was this blog posting here by Urbanpuddle. That post gets you pretty much 99% of the way there and walks you through setting up almost everything in Ubuntu. There were a couple of quirks near the end that I will go over.
Now, I am a RoR newbie so I really can’t complain about the language at all. I find it to be very easy to use with a huge support community. My pain point is getting a darn production server up and running. The amount of steps that you must take is just absolutely ridiculous. As far as a *nix production server goes, it needs ALOT of work. Just to give you a small taste of what you need to setup on your production server:
Step 1. Supporting Libraries
- ruby, ri, rdoc
- mysql-server
- libmysql-ruby
- ruby1.8-dev
- irb1.8
- libdbd-mysql-perl
- libdbi-perl
- libmysql-ruby1.8
- libnet-daemon-perl
- libplrpc-perl
- libreadline-ruby1.8
- libruby1.8
- mysql-client-5.0
- mysql-common
- mysql-server-5.0
- ruby1.8
Now this is just absolutely crazy. The ruby guys really need to include all of this in one single package like they recently did for the BitNami RubyStack. I think this is where they are heading with it. There is a spot for Linux and Mac x86 but only for available for windows at the moment. When they do complete this it will allow a lot of people to keep all of their hair.
Step 2. Install RubyGems & Ruby on Rails
So now we can get down to the meat and potatoes. Once you install the exhaustive list of apps above you can install Ruby Gems and then install rails. No problems there. This is pretty well documented on how to install so I won’t dive into this.
Step 3. Web Server (Nginx and Mongrel)
Before I describe the steps here, I will give credit to Greg Benedict for his blog post on Nginx/Mongrel as this is what I used to get it working. I had to modify how the configuration is setup to suit my needs but his post got me almost all the way there. You can find his detailed post here.
First let me describe how all of this fits together. I was a little confused at first and would have liked a description as to how everything works. I found this picture on the net to give a basic overview of how Nginx and Mongrel fit together.
User requests a page and nginx is dispatched. The configuration file is checked and then the request is forwarded to an available mongrel in the cluster.
In the picture to the left we have 3 mongrels in the cluster. Pretty straight forward.
Now, I chose nginx as a web server this time around. About 6 months ago I attempted to get apache to work with Mongrel clusters and I could never get it to work so I gave up. This time around I figured I would give something else a try. After looking around I found that Nginx was really easy to configure and a VERY small memory footprint, like 10mb or something around there. That’s what sold me on it.
So first you need to install Nginx (pronounced engine x) and once thats done, you install fastcgi. Fastcgi is used for parsing php pages like phpMyAdmin for managing the mysql databases. If you are comfortable managing mysql from the command line, then don’t bother with phpMyAdmin.
Next is the nginx configuration file. The way I was setting up my server is to have multiple named virtual hosts so that I could host multiple ruby apps from the same machine name. The first thing I had to do was add a CNAME wildcard into DNS so that anything.myservername.com would get forwarded to the same IP address. Next you setup a generic nginx.conf file to handle the general configuration. This will apply whether you are doing multiple named virtual hosts or not.
Here is the configuration that I am using. It is located at /etc/nginx/nginx.conf
user www-data www-data; worker_processes 1; pid /var/run/nginx.pid; # Valid error reporting levels are debug, notice and info error_log /var/log/nginx/error.log debug; events { worker_connections 1024; } /var/log/nginx_access.log main; # main error log error_log /var/log/nginx_error.log debug; # no sendfile on OSX sendfile on; # These are good default values. tcp_nopush on; keepalive_timeout 65; tcp_nodelay on; # output compression saves bandwidth gzip on; gzip_min_length 1100; gzip_buffers 4 8k; gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascr$ gzip_http_version 1.0; gzip_comp_level 2; gzip_proxied any; server_names_hash_bucket_size 64; # The following includes are specified for virtual hosts include /var/www/app1/current/config/nginx.conf; include /var/www/app2/current/config/nginx.conf;
include /var/www/app3/current/config/nginx.conf }
Pay attention to the last 3 lines in the nginx.conf. These lines include an external configuration that is located under the apps config directories. What this does for us is it allows you to just add one line in your /etc/nginx/nginx.conf, and thats all that needs to be done in nginx when adding another application to your server. Pretty nifty.
And here is the configuration for my app1 which is located in /var/www/app1/current/config/nginx.conf
# The name of the upstream server is used by the mongrel # section below under the server declaration upstream app1 { server 127.0.0.1:8000; server 127.0.0.1:8001; server 127.0.0.1:8002; } server { # port to listen on. Can also be set to an IP:PORT listen 80; # Set the max size for file uploads to 50Mb client_max_body_size 50M; # sets the domain[s] that this vhost server requests for. server_name app1.myservername.com; # doc root root /var/www/app1/current/public; # vhost specific access log access_log /var/www/app1/current/log/nginx.access.log main; # this rewrites all the requests to the maintenance.html # page if it exists in the doc root. This is for capistrano.s # disable web task if (-f $document_root/system/maintenance.html) { rewrite ^(.*)$ /system/maintenance.html last; break; } location / { # Uncomment to allow server side includes so nginx can # post-process Rails content ## ssi on; # needed to forward user.s IP address to rails proxy_set_header X-Real-IP $remote_addr; # needed for HTTPS #proxy_set_header X_FORWARDED_PROTO; } # Look for existence of PHP index file. # Don.t break here.just rewrite it. if (-f $request_filename/index.php) { rewrite (.*) $1/index.php; } #; } # You.ll need to change this proxy_pass to match what # what you specified above. It must be unique to each vhost. if (!-f $request_filename) { proxy_pass; break; } } error_page 500 502 503 504 /500.html; location = /500.html { root /var/www/app1/current/public; } }
First pay attention at the top where you have the upstream section. Note the name as it is used further in the config file to state what mongrel cluster nginx should forward to for this servername.
The thing to nice is that most of this configuration is encapsulated in a server {} tag. This is the section that holds a virtual host. You can have as many of these as you want per nginx. I have just seperated them out into seperate files to facilitate easier configuration.
Second, make note of “server_name” and change that to the server name that will be handling requests for this app. This can be myserver.com, or you can have it setup as a subdomain as I do.
Last, change all other references to app1 to whatever your app is named, then at the bottom you will notice the proxy_pass. This portion is what forwards requests to your mongrel cluster. Change to whatever you had for the upstream at the top. They need to the same otherwise you will receive 502 errors.
Ok, now that we have the nginx configuration out of the way we can go on to your Mongrel cluster.
The mongrel cluster is pretty easy to configure. Here is the mongrel_cluster.yml file that you can drop into yourapp/config/mongrel_cluster.yml
cwd: /var/www/app1/current port: 8000 environment: production user: produser group: produser address: 127.0.0.1 pid_file: /var/www/app1/shared/pids/mongrel.pid servers: 3
Pretty straightforward. Grab the Restart script found here. And place that in /etc/init.d/. This will allow you to do ”sudo /etc/init.d/mongrel_cluster start|stop|restart”
Your mongrel_cluster.yml file needs to be linked to /etc/mongrel/app1_cluster.yml. This way, when you use the restart script. It will look in /etc/mongrel to restart all clusters that are running on the machine. You can create the link like so:
sudo ln -s /var/www/app1/current/config/mongrel_cluster.yml app1.yml
Now that you have that out of the way you can get to deployment with capistrano.
Step 4. Deployment with Capistrano
First I would note that if you install the latest version of Capistrano it will be version 2.1. For some reason the RoR documentation is outdated and references the old version of capistrano. Before you would do “rake deploy” but now you run capistrano commands like so: “cap deploy”. This was a bit of a pain but there are people out there using it so the documentation should be updated soon.
Capistrano is a standalone utility much like nant. You can run different tasks, deploy in different configurations etc.. The difference is that capistrano can do a lot more stuff than nant can. I only scratched the surface so I employ you to dive further into capistrano.
The really cool part of capistrano deployment is the ability to rollback a deployment. Basically what happens is upon deploying via capistrano, it first exports from subversion to a folder that is named the UTC datetime of the deployment. Then it creates a link from that folder to the current folder that is referenced above. Previous deployments still live in their datetime folder but are no longer symlinked to the current directory. When you want to rollback a deployment type “cap rollback” and everything is undone including your database migrations. Pretty neat eh?
Ok, so you have your app built, you have created a subversion repository for it and have checked in your changes to your repository. Now you want to deploy it to your brand new shiny deployment server.
This is the part where I slipped into the seventh level of hell.
There is A LOT of different blog posts on how to accomplish this. After trying multitude of different ways I settled on this deployment script that lives in app1/config/deploy.rb
set :application, "My App" set :repository, "" set :user, "username" set :password, "password" set :deploy_to, "/var/www/app1" set :deploy_via, :export set :mongrel_conf, "#{deploy_to}/current/config/mongrel_cluster.yml" role :app, "username@mydeploymentserver.com" role :web, "username@mydeploymentserver.com" role :db, "username@mydeploymentserver.com", :primary => true namespace :deploy do desc "Restart mongrel servers" task :restart, :roles => [:web] do run "cd #{release_path} && sudo /etc/init.d/mongrel_cluster restart" do |ch, steam, out| ch.send_data "#{password}n" if out =~/password/ end run "sudo chown -R www-data:www-data #{release_path}/tmp" do |ch, steam, out| ch.send_data "#{password}n" if out =~/password/ end end end
Ok so most of the deployment file is self explanatory. :repository should be set to your repository address, Set :user and :password to the sudo user and password on your deployment server. Now, if you are deploying over the web, I would strongly suggest looking for another way to transmit this data, perhaps an SSL deployment or something. I am running this server on my internal network with limited usage so I didn’t care if all this information was sitting in my repsoitory but this is bad! bad! bad! =)
The :deploy_via is how you want to perform the deployment from subversion. This states that subversion will perform an export to the deployment server. You can also do a :co which will perform a checkout. Export seemed like the more logical way.
:app, :web and :db are your deployment servers. I am using all the same server so they are all the same. If you wanted to you could break out your application to seperate servers for performance. Pretty neat that it has that option ready to go in there.
The next portion is a little different. This is where you can define commands to run, tasks to perform on the remote server. First I tell it to cd to the apps root directory and then restart the mongrel_cluster. The ONLY thing you need to restart after a deployment is your mongrel_cluster. There is no need to restart nginx.
Let me clarify here. In your /etc/init.d/mongrel_cluster script it states who the mongrel clusters should run as. BE SURE that the user you defined there has access to the shared/pids folder otherwise mongrel cannot write the pid files and will fail to start. I bounced around with this problem for a couple of hours banging my head on the wall between attempts.
Next I added in a chown command as I noticed that after everything completed successfully, the nginx user could not write the ruby sessions to the tmp directory. That command fixed the problem, everything was working and there was much rejoicing.
Now, there were quite a few bumps in the road throughout the process that I failed to document but after searching on google for awhile and poking I was able to get around all of them. As a result if I setup another server I know what to expect now and hopefully so will you!
I hope this helps at least one person avoid the insanity that I endured for a couple of days. Good luck!
Post Footer automatically generated by Add Post Footer Plugin for wordpress. | http://lostechies.com/seanchambers/2007/12/04/setting-up-a-ruby-on-rails-production-server-with-minimal-insanity/ | CC-MAIN-2013-20 | refinedweb | 2,471 | 66.64 |
Last (Java Message Service) is a standard Java API for sending asynchronous messages. When we think about JMS, we immediately see a client sending a message to a server (broker) in a fire and forget manner. But it is equally common to implement request-reply messaging pattern on top of JMS. The implementation is fairly simple: you send a request message (of course asynchronously) to an MDB on the other side.
MDB processes the request and sends a reply back either to hardcoded reply queue or to an arbitrary queue chosen by the client and sent along with the message in
JMSReplyTo property. The second scenario is much more interesting. Client can create a temporary queue and use it as a reply queue when sending a request. This way each request/reply pair uses different reply queue, this there is no need for correlation ID, selectors, etc.
There is one catch, however. Sending a message to JMS broker is simple and asynchronous. But receiving reply is much more cumbersome. You can either implement
MessageListener to consume one, single message or use blocking
MessageConsumer.receive(). First approach is quite heavyweight and hard to use in practice. Second one defeats the purpose of asynchronous messaging. You can also poll the reply queue with some interval, which sounds even worse.
Knowing the
Future abstraction by now you should have some design idea. What if we can send a request message and get a
Future<T> back, representing reply message that didn’t came yet? This
Future abstraction should handle all the logic and we can safely use it as a handle to future outcome. Here is the plumbing code used to create temporary queue and send request:
private <T extends Serializable> Future<T> asynchRequest(ConnectionFactory connectionFactory, Serializable request, String queue) throws JMSException { Connection connection =(queue), session, requestMsg); return new JmsReplyFuture<T>(connection, session, tempReplyQueue); }
asynchRequest() method simply takes a
ConnectionFactory to JMS broker and arbitrary piece of data. This object will be sent to
queue using
ObjectMessage. Last line is crucial – we return our custom
JmsReplyFuture<T> that will represent not-yet-received reply. Notice how we pass temporary JMS queue to both
JMSReplyTo property and our
Future. Implementation of the MDB side is not that important. Needless to say it is suppose to send a reply back to designated queue:
final ObjectMessage reply = session.createObjectMessage(...); session.createProducer(request.getJMSReplyTo()).send(reply);
So let’s dive into the implementation of
JmsReplyFuture<T>. I made an assumption that both request and reply are
ObjectMessages. It’s not very challenging to use a different type of message. First of all let us see how receiving messages from reply channel is set up:
public class JmsReplyFuture<T extends Serializable> implements Future<T>, MessageListener { //... public JmsReplyFuture(Connection connection, Session session, Queue replyQueue) throws JMSException { this.connection = connection; this.session = session; replyConsumer = session.createConsumer(replyQueue); replyConsumer.setMessageListener(this); } @Override public void onMessage(Message message) { //... } }
As you can see
JmsReplyFuture implements both
Future<T> (where
T is expected type of object wrapped inside
ObjectMessage) and JMS
MessageListener. In the constructor we simply start listening on
replyQueue. From our design assumptions we know that there will be at most one message there because reply queue is temporary throw away queue. In the previous article we learned that
Future.get() should block while waiting for a result. On the other hand
onMessage() is a callback method called from some internal JMS client thread/library. Apparently we need some shared variable/lock to let waiting
get() know that reply arrived. Preferably our solution should be lightweight and not introduce any latency so busy waiting on
volatile variable is a bad idea. Initially I though about
Semaphore that I would use to unblock
get() from
onMessage(). But I would still need some shared variable to hold the actual reply object. So I came up with an idea of using
ArrayBlockingQueue. It might sound strange to use a queue when we know there will be no more that one item. But it works perfectly, utilizing good old producer-consumer pattern:
Future.get() is a consumer blocking on an empty queue’s
poll() method. On the other hand
onMessage() is a producer, placing reply message in that queue and immediately unblocking consumer. Here is how it looks:
public class JmsReplyFuture<T extends Serializable> implements Future<T>, MessageListener { private final BlockingQueue<T> reply = new ArrayBlockingQueue<>(1); //... ) { final ObjectMessage objectMessage = (ObjectMessage) message; final Serializable object = objectMessage.getObject(); reply.put((T) object); //... } }
The implementation is still not complete, but it covers most important concepts. Notice how nicely
BlockingQueue.poll(long, TimeUnit) method fits into
Future.get(long, TimeUnit). Unfortunately, even though they come from the same package and were developed more or less in the same time, one method returns
null upon timeout while the other should throw an exception. Easy to fix.
Also notice how easy the implementation of
onMessage() became. We just place newly received message in a
BlockingQueue reply and the collection does all the synchronization for us. We are still missing some less significant, but still important details – cancelling and clean up. Without going much into details, here is a full implementation:
public class JmsReplyFuture<T extends Serializable> implements Future<T>, MessageListener { private static enum State {WAITING, DONE, CANCELLED} private final Connection connection; private final Session session; private final MessageConsumer replyConsumer; private final BlockingQueue<T> reply = new ArrayBlockingQueue<>(1); private volatile State state = State.WAITING; public JmsReplyFuture(Connection connection, Session session, Queue replyQueue) throws JMSException { this.connection = connection; this.session = session; replyConsumer = session.createConsumer(replyQueue); replyConsumer.setMessageListener(this); } @Override public boolean cancel(boolean mayInterruptIfRunning) { try { state = State.CANCELLED; cleanUp(); return true; } catch (JMSException e) { throw Throwables.propagate(e); } } @Override public boolean isCancelled() { return state == State.CANCELLED; } @Override public boolean isDone() { return state == State.DONE; } ) { try { final ObjectMessage objectMessage = (ObjectMessage) message; final Serializable object = objectMessage.getObject(); reply.put((T) object); state = State.DONE; cleanUp(); } catch (Exception e) { throw Throwables.propagate(e); } } private void cleanUp() throws JMSException { replyConsumer.close(); session.close(); connection.close(); } }
I use special
State enum to hold the information about state. I find it much more readable compared to complex conditions based on multiple flags,
null checks, etc. Second thing to keep in mind is cancelling. Fortunately it’s quite simple. We basically close the underlying session/connection. It has to remain open throughout the course of whole request/reply message exchange, otherwise temporary JMS reply queue disappears. Note that we cannot easily inform broker/MDB that we are no longer interested about the reply. We simply stop listening for it, but MDB will still process request and try to send a reply to no longer existing temporary queue.
So how does this all look in practice? Say we have an MDB that receives a number and returns a square of it. Imagine the computation takes a little bit of time so we start it in advance, do some work in the meantime and later retrieve the results. Here is how such a design might look like:
final Future<Double> replyFuture = asynchRequest(connectionFactory, 7, "square"); //do some more work final double resp = replyFuture.get(); //49
Where
"square" is the name of request queue. If we refactor it and use dependency injection we can further simplify it to something like:
final Future<Double> replyFuture = calculator.square(7); //do some more work final double resp = replyFuture.get(); //49
You know what’s best about this design? Even though we are exploiting quite advanced JMS capabilities, there is no JMS code here. Moreover we can later replace
calculator with a different implementation, using SOAP or GPU. As far as the client code is concerned, we still use
Future<Double> abstraction. Computation result that is not yet available. The underlying mechanism is irrelevant. That is the beauty of abstraction.
Obviously this implementation is not production ready (by far). But even worse, it misses some essential features. We still call blocking
Future.get() at some point. Moreover there is no way of composing/chaining futures (e.g. when the response arrives, send another message) or waiting for the fastest future to complete. Be patient!
Reference: Implementing custom Future from our JCG partner Tomasz Nurkiewicz at the NoBlogDefFound blog.
Hi,
awesome stuff, especially the NoBlogDefFound blog!
I landed here in the search of ‘Future vs. Serialization’ because I’m currently implementing a Scala-like Future/Promise implementation for Java 8.
From what I can see, it does not seem to be a good idea to serialize a FutureTask. It may contain an executor, which has to be serializable, etc ().
Have you thought of serializing Futures/FutureTasks?
Regards,
Daniel | https://www.javacodegeeks.com/2013/02/implementing-custom-future.html | CC-MAIN-2017-09 | refinedweb | 1,429 | 50.02 |
The new .NET technologies, Remoting and Web Services has made life much easier than the days of trying to get DCOM to work. Although with anything that has been made easier there are some details that have been made too easy. In the case of Remoting or calling a web service, the Microsoft .NET Framework includes an automatic feature that converts all returned
DataTables with
DateTime values to the caller's time zone. So if you're in Seattle and need to find out a certain
DateTime value in a database table row (let's say
sale_date) on a server that runs in New York City you can make a web service call to find out. What happens is the
sale_date value may have a value of 8/22/2004 9:05 am on the server in New York, but your web service call will result in a value of 8/22/2004 6:05 am. Which is clearly wrong. This article will tell you how to fix this problem.
The problem seems to only occur whenever you send a
DataTable as a return value. This is because .NET Framework will automatically serialize the
DataTable into xml using it's
System.Xml.Serialization.XmlSerializer class. The
XmlSerializer will convert the DateTime values upon deserialization on the client. The idea here is to take control of the xml serialization process and manipulate the xml using regular expressions to give us the correct result.
1. In the web service we first need to convert the
DataTable to an xml string and send back the string. We use the
System.IO.StringWriter class to write out the xml string:
using System.Data; using System.IO; using System.Web.Services; ... namespace NYDataServices { ... // Web service is running in New York City public class MyWebService : System.Web.Services.WebService { ... [WebMethod] public string GetData() { DataTable dataTable = null; // Get data from database as a DataTable ... // Now convert the DataTable to an xml string and return it to client return convertDataTableToString( dataTable ); } private string convertDataTableToString( DataTable dataTable ) { DataSet dataSet = new DataSet(); dataSet.Tables.Add( dataTable ); StringWriter writer = new StringWriter(); dataSet.WriteXml( writer, XmlWriteMode.WriteSchema ); return writer.ToString(); }
2. On the client side we make the call to get the data and receive the data as an xml string.
using System.Data; using System.Text.RegularExpressions; ... namespace SeattleClient { ... // Client program running in Seattle public class MyClient : System.Windows.Form { ... public void GetDataFromServer() { NYDataServices.MyWebService ws = new NYDataServices.MyWebService(); string xmlString = ws.GetData(); DataTable dataTable = convertStringToDataTable( xmlString ); // Do something with dataTable ... }
3. Converting the xml string back to a
DataTable requires the use of regular expressions to search, adjust time values and replace. The
DateTime values take on the form of 2004-08-22T00:00:00.0000000-05:00. The last 5 characters in the string indicate the UTC (Universal Time Coordinate) time. During xml deserialization back into a
DataTable, the
XmlSerializer class reads this value and creates an offset value based on the client's UTC time. It then adds this offset into all
DateTime values upon deserialization. The kicker here is that if the
DateTime value happens to be on DST (Daylight Savings Time) and the client is not on DST it will adjust for this too. We use some of the magic of the
System.Text.RegularExpression namespace such as the
Regex.Replace() function,
Match class and
MatchEvaluator delegate.
private DataTable convertStringToDataTable( string xmlString ) { // Search for datetime values of the format // --> 2004-08-22T00:00:00.0000000-05:00 string rp = @"(?<DATE>\d{4}-\d{2}-\d{2})(?<TIME>T\d{2}:\d{2}:\d{2}."+ "\d{7}-)(?<HOUR>\d{2})(?<LAST>:\d{2})"; // Replace UTC offset value string fixedString = Regex.Replace( xmlString, rp, new MatchEvaluator( getHourOffset ) ); DataSet dataSet = new DataSet(); StringReader stringReader = new StringReader( fixedString ); dataSet.ReadXml( stringReader ); return dataSet.Tables[ 0 ]; } private static string getHourOffset( Match m ) { // Need to also account for Daylights Savings // Time when calculating UTC offset value DateTime dtLocal = DateTime.Parse( m.Result( "${date}" ) ); DateTime dtUTC = dtLocal.ToUniversalTime(); int hourLocalOffset = dtUTC.Hour - dtLocal.Hour; int hourServer = int.Parse( m.Result( "${hour}" ) ); string newHour = ( hourServer + ( hourLocalOffset - hourServer ) ).ToString( "0#" ); string retString = m.Result( "${date}" + "${time}" + newHour + "${last}" ); return retString; }
I know this problem happens when sending back DataTables. I'm not sure if the same applies to custom classes, although I suspect it does.
Here are links that I found very useful --
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/datetimeissuexmlser.aspx | crawl-002 | refinedweb | 735 | 59.3 |
Using a schedulerVassili Dzuba Oct 28, 2005 10:55 AM
Hello,
I would appreciate if somebody could tell me what i do wrong
(i'm quite a newbie with jBPM).
I want to make a process that checks a directory until a given file
is present, and then perform some work.
My process definition starts with :
< process-definition>
< start-state>
< event
< script>
import com.lnf.testjbpm.Supervision;
Supervision.put("Let's start !");
< /script>
< /event>
< transition
< /start-state>
< state
< timer
< action
< /timer>
< transition
< transition
< /state>
........
The idea is that the action checks if the file is available and if it is good.
If the answer to both questions is yes, it fires "ok";
if the file is available but bad, it fires "ko". If there is no file,
it returns without firing any transition.
In the Java application i do the following :
Token token = processInstance.getRootToken();
token.signal();
[ some DB stuff skipped, including creating a new transaction ]
new Scheduler().start();
The problem as i understand it is :
- when signaling theroot token, it enters state S1 and creates the timer
- when starting the scheduler, it executes the timer, which fires the
transition and the process completes and thenreturns to the
executeTimers function.
However that function does the following :
- executing the timer
- saving the timer if repeat is specified.
Now, the timer should be deleted when leaving the state s1 and recreating it
does not seem a good idea.
The result is that the timer is called when the process is in its end state,
and fails miserably when trying to signal a transition that doesn't exist
in that state.
Is it really a bug, or is the way i tried to solve the problem
aberrant ?
Thanks for any advice,
Vassili Dzuba
1. Re: Using a schedulerRonald van Kuijk Oct 28, 2005 11:03 AM (in response to Vassili Dzuba)
First of all, I woud *not* code this in a scheduled thing in jBPM. I would do the checking somewhere else but that is my opinion.
Secondly there is a known issues with timers after process ends. See the jira
2. Re: Using a schedulerVassili Dzuba Oct 28, 2005 12:55 PM (in response to Vassili Dzuba)
Thanks for the answer.
Is your opinion about not coding this in a scheduled thing in jBPM
of methodological nature with respect to workflow in general,
or simply technical with respect to the current state of jBPM ?
Vassili
3. Re: Using a schedulerRonald van Kuijk Oct 29, 2005 1:45 PM (in response to Vassili Dzuba)
It's of the methodological nature (although others might and may disagree and this is my opinion, not necessarily the jBPM/JBoss one)
. I'd put that logic e.g. in a service bus or eai layer which polls messages, files, ws calls or whatever and signals the workflow | https://developer.jboss.org/thread/112462 | CC-MAIN-2018-39 | refinedweb | 470 | 60.95 |
(Im using VS C++ EE 2008)
Hi people, i have had a strange problem today. Im currently programming something to do with Physics. I have searched the Internet already for the answer, including this site. The problem is:
error C2064: term does not evaluate to a function taking 1 arguments
For the other topics i saw this in, it seemed to be that they had a variable with the same name as a function or similar, and they all were with user-defined functions.
My problem is slightly different, the functions I am trying to use are predefined. (Trignometry functions: cos and sin) I have checked the variables, and i have not used any with the same name. Here's the code:
double accelerate(double t_a,double t_f) { return -9.8(sin(t_a) + (t_f * cos(t_a))); }
Thats where the error occurs, includes:
#include <iostream> #include <windows.h> #include <math.h> #include "physics.h" using namespace std;
Only use (so far) of function:
double angle = atan2(track[(int)position].e_height-track[(int)position].s_height,1); cout << "\nAngle: " << radtodeg(angle); // Now, work out acceleration and it's direction acceleration = accelerate(angle,0.06); speed += acceleration / 33; position += speed / 33;
(I have no where near finished this, but i cannot continue to i can get this working)
Thanks for any help, and sorry if i missed something, or there is another post about this, i didn't see it! :D
EDIT: So sorry, very stupid mistake on my part :P I was using 9.8( as you would in math, instead of 9.8 * (
Sorry for your time :D | https://www.daniweb.com/programming/software-development/threads/194404/please-help-me-with-strange-error | CC-MAIN-2017-47 | refinedweb | 266 | 64.81 |
Try/Catch Blocks
You will notice throughout our application the use of try/catch blocks. Since we're working with handling exceptions, it's important to note that try/catch block(s) are the basic fundamental building base to handling exceptions. Anytime your application does the following operations, you should use them:
- Connecting to a database.
- Executing a query against a database, whether its select, update, delete or insert.
- When checking for certain query string parameters, specifically guides
Build or Run-Time Errors
Another annoyance with building Web applications, or applications in general are build and run-time errors. The difference between them is subtle but important. A build error is when your application can't compile because of the following:
- Incorrect variable declarations, or assigning a variable an incorrect data type.
- References to DLL files.
A couple examples might include the following:
namespace ExceptionHandling { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<ExceptionHandlingGetData> person = ExceptionHandlingGetData.GetParticipants(); rpPerson.DataSource = person; rpPerson.DataBind(); } } }
As you can see from the above, we're casting a person object as a generic list so we can call its static method, and then binding that object to our repeater control. However, if we comment or take out the reference to the cast, leave the last two lines of code, and then build, you will get the following error message:
Scenario 2: Another type of build error that happens frequently for developers is when you create a variable with a data type of string but assign it a value of another data type. You might be thinking that's crazy, but it does happen. Examples in our application might include first and last name and email, which are all created as string variables. However, in our while loop, if you assign the object property to another data type, such as integer, you will receive a build error as shown below:
A run-time error occurs when your application encounters an exception that a developer didn't anticipate. It's different because you can build (compile) your solution, but once you hit the exception, your application is non-responsive and your user can't complete the tasks they need. An example of this occurs when viewing our participant's detailed information. Our default.aspx page shows the number of people in our database, but our viewentry.aspx will show detailed information for each participant.
From the project downloads section, take a look at viewentry.aspx. In the file you will see the following:
- Two place holder controls, with the following:
- First one contains our form for showing existing entries via our query string.
- Second place holder contains a failure message.
From the solution explorer, do the following:
- Left click the plus (+) sign next to viewentry.aspx.
- Double click viewentry.aspx.
In this file you will see the following:
- In page load, a try catch block which checks to see if a query string with a parameter of guide is supplied:
- If it IS, we query our data.
- If it IS NOT, we catch the exception, and show our failure place holder message.
With this in place, you can successfully prevent a run-time error from occurring. If you want to see the run-time error occur, simply comment out the try/catch and run the application.
Incorrectly Supplying Parameters to a Stored Procedure
Another common type of exception error developers run across is when working with stored procedures through application logic. For example, our view entry page passes a query string so we can view individual participants and update their information. Once we collect their information, we call an update method and supply our stored procedure. However, if we forget to do that, we'll get a run time error. To reproduce, do the following from the solution explorer:
- Left click the plus (+) sign next to classes.
- Double click ExceptionHandlingActions.cs.
Between lines 30-33, if you were to comment out one of those parameters (
@FName), run the solution, and then try and update one of the participants, you will get the following run-time error:
Handing Exceptions Gracefully for the Visitor, While Supplying Enough Information to the Developer
We have come to one of the most useful features of ASP.NET 2.0 and above. While we have uncovered many types of exceptions that can occur in an application, a developer's ability to predict all of them is simply impossible. With ASP.NET 2.0 and above, we can configure our configuration file to show a custom error message to our user, while allowing us to view the specific details of the error, which is great for both parties involved. From the solution explorer, do the following:
- Double click web.config.
Inside system.web, add the following:
<customErrors mode="RemoteOnly" defaultRedirect="error.htm" />
As you can see from the code above, we added a custom errors tag, with the following properties:
- Mode: can be On, Off, RemoteOnly
- On: Means custom errors will show.
- Off: Means everyone will receive detailed error messages.
- Remote only: Means end users will receive our custom page, and developers will receive the detailed error message.
- defaultRedirect: error.htm: This page is our custom error page. It can be any Web page you want.
In order to test this, you will need to cause a run-time error on a Web server.
Summary
In this article you learned how to work with and handle exceptions. Furthermore, you learned the following:
- How to diagnose and correct database connection issues with your application.
- Use of try/catch blocks through applications when you are connecting to a database or executing queries.
- Difference between a build and run-time error.
- How to use a try/catch block to handle query strings that are not passed through the URL.
- How to identify when you haven't supplied a parameter to a stored procedure in the application.
- How to gracefully show users a custom error message from a Web page, while allowing developers the ability to see the detailed error message.
Code Download
About the AuthorRyan Butler is the founder of Midwest Web Design. His skill sets include HTML, CSS, Flash, JavaScript, ASP.NET, PHP and database technologies.
Original: Apr. 11, 2011 | http://www.webreference.com/programming/asp-net-exception-handling/2.html | CC-MAIN-2015-48 | refinedweb | 1,042 | 53.92 |
”
Enable the selection of the issuer claim per OpenID relying party
AD FS publishes two different issuer values in the public https://<domain>/adfs/.well-known/openid-configuration : One is called 'issuer' the other is 'accesstokenissuer' - the accesstokenissuer is optional in the standard. The value that is issued in the access token iss claim is always the 'accesstokenissuer' some clients (.Net ones) validate the access token against the 'accesstokenissuer' others (using open source libraries) will only validate against the 'issuer'
It would be great if I could select per relying party which value is returned in the access token iss claim.5 votes
integrate professionally sharepoint search connection native in Windows Explorer and make it the preferred choice in its search applet“ with the OpenSearch 1.1 Provider interface. But you do not search on sharepoint and provide a huge I/O utilization on the fileserver node unless you hit the search icon that you created with the „osdx-File“ first.
But there are negative Points for OpenSearch. OpenSearch Provider is an old interface and the sharepoint does not consider the whole bunch of search functions for that small feature set.
Actually we placed an enterprise developing order and closed some advisory cases for that problematic around sharepoint and indexing dfs namespaces.
But you can do it better and professionally in next server releases and for all you customers around the world!
We request with this post
that you integrate sharepoint search native into the windows explorer as the preferred search engine – no need to import an osdx, the search bar uses directly the sharepoint search cluster address .
That you provide an set of group policies and the possibility to configure it also with powershell.
f.e. one or several URLs for Search Center Adress on a per user level.
that you give as soon as possible the ability to hide the search bar in all contexts in the windows explorer unless a registered search provider is chosen (group policy setting).
That you replace windows search with sharepoint search as the search provider in outlook in order to avoid indexing personal folder files on a network drive.
Create a „Sharepoint Search Client“ for Desktops and RDS, so the administrators can decide if there has to be a centralized sharepoint search farm or a client can index locally (default).
But also it is important that you can set several parameters in group policies or via powershell – f.e. for setting the indexing database path.
We know that you can develope a professional new search approach for the future and delight your customer.“…4 votes
Improve
Regarding SFTP support out of the box in Windows servers
Dear Microsoft, Can you please add out of the box support for SFTP in Windows server. It will make our lives really easy.
Thank you.1 vote
Fix Offline WSUS Export Process potential errors when copying files to import. Please work to improve and modernize this process to make it simple and efficient / less painful!
Even a well documented process to include well written PowerShell scripts would be a great improvement over what currently "doesn't exist" would be super!
Thank you!
Complete Server Architecture change.
Rube Goldberg is best known for his popular cartoons depicting complicated gadgets performing simple tasks in indirect, convoluted ways. If only he had lived in our times... Windows Server and RDS1 vote
Reduced
Powershell bug with parameter set and Resolve-DnsName triggered -Debug prompt
Expect non-interactive execution of script
Result get debug prompt despite no -Debug flag
It is so strange you have to see it to understand
param (
[Parameter(Mandatory=$True, ParameterSetName='defaults')]
[ValidateSet('world', 'people')]
[string]$Thing
)
Write-Host "Hello $Thing"
Resolve-DnsName google.com -Server 8.8.8.8
Try it:
.\Test.ps1 -Thing world -Debug
Hello world
DEBUG: 196616
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):1 vote
Fix .NET-incompatibility with Essentials Dashboard on Server 2016
With the latest .Net updates the dashboard is not useable anymore: Warnings can't be ignored or deleted, computers can't be removed...
Only the progressbar appears, cpu usage rises to 100% and dashboard gets stuck or crashes.50 votes
Storage Migration Service - Quotas and File Screens
I would like to see the Storage Migration Service include the ability to bring over share Quotas and File Screens.3 votes
MultiPoint
Please add back MultiPoint Service role to Server 20196 votes
Fix
Provide basic support for Vmware .vmdk
Provide basic support for Vmware .vmdk.
It is weird that I am able to open a .vmdk file with 7zip but not from within Windows.
Provide support to mount .vmdk disks (and others like VDI) and at least read access to copy files from other virtual disk formats. Mounting should include mounting in virtual guests as well.2 votes
This browser hijacker keeps redirecting me to yahoo.com1 vote
Arial Unicode MS font not supported while generating PDF file through Crystal Report (SAP) in IIS 10 (Windows Server 2019)
In my server has installed Windows Server 2019 Standard Edition , VS2010, VS 2017 crystal report (SAP)CRFORVS21. When i deployed the application in IIS server then crystal report does not support Arial Unicode MS font while generating PDF document but when execute the application through Asp.net server (VS) then working (Arial Unicode MS font displayed).
Why IIS 10 not supported Arial Unicode font while generating PDF document file.
Please help me1 vote
Server 2016 updates MUCH too slow!
I've never seen Windows hosts take so long to update as Server 2016 does. Between taking sometimes over an hour to download 15MB updates on an extremely fast connection, to the sometimes HOURS-long process, something is BROKEN! And yet all I see in eventvwr is "Installation started" with null detail as to what's taking so bloody forever.
FIX THIS MICROSOFT. People have been complaining about this for YEARS.2 votes
Show file extensions by default
Show file extension by default on Windows Server. I can understand why the extension is hidden by default on the Desktop OS but for server it should be visible.44 votes
- Don't see your idea? | https://windowsserver.uservoice.com/forums/295047-general-feedback/filters/hot?page=9 | CC-MAIN-2020-16 | refinedweb | 1,034 | 62.88 |
Analysis of Land Tenders in Singapore
Embed Size (px)
DESCRIPTIONERES Conference 2012. Analysis of Land Tenders in Singapore. Lawrence Chin, PhD & Yu Kok Soon Dept of Real Estate National University of Singapore. Outline. Introduction Objectives of paper Literature review Research methods Findings of study Conclusion. SINGAPORE: Size and Skyline. - PowerPoint PPT Presentation
TRANSCRIPT
Analysis of Land Tendersin SingaporeLawrence Chin, PhD & Yu Kok SoonDept of Real EstateNational University of SingaporeERES Conference 2012
OutlineIntroductionObjectives of paperLiterature reviewResearch methodsFindings of studyConclusion
SINGAPORE:Size and Skyline
IntroductionAbout 90% of the land in Singapore is owned by the government and one major source of land supply for real estate developers is through the government land sale (GLS) programme. The release of land by the government is made in a steady manner so as to ensure that the needs of the society like housing, commercial and industrial development are adequately met. Land parcels under the GLS programme are typically sold on a leasehold tenure of 99 years.
MotivationLand acquisitions made by the listed firms will directly affect their shareholders wealth. The response of the shareholders on the successful land acquisitions can be observed through the movement of the stock prices when the announcements are made.
ObjectiveObjective of this paper is to examine the market reaction following the announcements of successful land tender bids by property companies listed on the Singapore Stocks Exchange (SGX) using the event study methodology. Study also seeks to understand the factors that explain for the existence of the abnormal return, if any arises.
Past WorksGlascock et al. (1991) found that firms that engaged in acquisition of real estate assets do not experience positive abnormal return. This means that there is no value enhancement for the buyers as most, if not all of the wealth that exists will be effectively captured by the sellers. It would be expected that in a competitive land market, there will be little or no significant wealth effects that will be enjoyed by the successful tenderers upon the announcement of the land tender win
Past WorksThese findings differ because of the different sampling of firms selected for their studies. Allen and Sirmans (1987) and Hite et al. (1984) used a sample which focused primarily on property firms, while Glascock et al. (1991) studied the acquisition and disposal of real estate assets by non-property firms from year 1981 to 1986.
Past WorksIn an earlier study on government land sale programme in Singapore, Ooi and Sirmans (2004) use a unique set of public auction data. Their analysis shows that there exist positive excess returns associated with the announcements of successful land acquisition. This paper differs from Ooi and Sirmans (2004) as it considers a timelier window period and the impact of a series of different important events which have affected the real estate market in Singapore. During the study period of this paper, there is a recent increase of inflow foreign companies which participated in Singapores government land sale tenders, as well as the onset of the global financial crisis in 2007.
Research MethodThe sample selection process began with the compilation of the data pertaining to the events of GLS tender announcements. The information such as the government agency responsible for the sale of the site, date of tender launch, date of closing and date of the award were collected along with the relevant site information and name of the successful tenderers were also taken down.Next, a background study of the winning tenderers was conducted to identify the true identity of the bidder. This is because the GLS programme requires the bidding companies to submit their bids through separate company. The parent companies are then categorized into either private or public listed corporations after the verification.
Data CollectionThe raw data collection resulted in finding 138 development sites sold during the period between 2003 and 2010. The total selling price of the development sites amounted to SGD $28.25 billion. Land sales for places of worship, heavy vehicle parks, petrol stations, car showrooms, and nursing homes were excluded from the study as the small sale prices are unlikely to have any significant impact on the stock prices of the winning companies. After the data filtration, the final sample size is reduced to 46 bidding events. Of these events, 35 sites were designated for private residential development, 6 for commercial development, 4 for industrial development and 1 is designated as white site development
The total value of the final sample of 46 sites is SGD $10.56 billion which constituted about 38 percent of the total GLS sales. As the sample sale value constituted quite a significant proportion of the total selling price, it is taken that the study sample is sufficiently large to be a representative of the GLS auction bidding behavior.
Table .1: Development Sites Sold by URA and HDB through GLS Program from 2003 to 2010
YearNo. of Development Sites SoldSale Price SGD millionsURAHDBTotal2003303$447.682004213$112.1020058210$2,184.32200611112$1,925.39200727835$9,232.44200816521$3,084.5720099312$1,743.822010222042$9,521.32Total9840138$28,251.65
Event Study MethodologyThis paper adopted the methodology developed by Fama, Fisher, Jensen and Roll (1969) called event study methodology in investigating the effect of announcement of land tender win on the stock prices of winning companies. The data on the stock prices of these companies before and after the announcements will be gathered and analyzed. The change in stock prices that is beyond expectation, abnormal return, during the event window will be noted and will be attributed to the effects of the event. The event will be said to have an impact on the stock price of the companies if there is a significant abnormal return found during the event window.
Window PeriodThe first step in carrying out the event study is to decide on the event of interest which in this case is the announcement of the land tender win, and also the window period to carry out the examination of the security prices of the winning firms. The window period selected is similar to that in Ooi and Sirmans (2004) where an estimation window of -100 days to +30 trading days was employed. As shown in Figure 1, abnormal returns are examined over a window of five consecutive trading days around the event (-1, 0, +1, +2, +3 days) with the closing date of the land auction designated as day 0.
Announcement Effects of Successful BidsAs shown in Table 3, the highest abnormal return was achieved on day +1, in which the gain recorded was 0.780 percent and is found to be statistically significant using the J statistic at a 2 percent significant level or higher. On the average, the gains recorded for day -1 is -0.272 percent, -0.163 percent on the event day, +0.433 percent on day +2 and 0.035 percent on day +3. However, the abnormal returns for the day -1, 0, +2 and +3 were found to be poorly significant. The mean cumulative average abnormal return (CAR) for window period (0, +3) was given as 1.015 percent. The highest incidence of positive abnormal returns occurred on day +1 at 56.5 percent with the second highest incidence of positive abnormal returns registered on day +2 at 54.3 percent
In sum.The winning bidders for the GLS sites reaped positive abnormal returns. Although the effect of these returns occurred on day +1 and day +2, the overall return is found to be +0.743 percent. This suggests that the winning tenderers were bidding in a fashion that enabled them to capture the wealth effects and also is able to avoid the ill effects of excessively high bids resulting in the winners curse.
Multivariate Regression AnalysisA multivariate regression model (MVRM) is applied to the cumulative abnormal return (CAR) to help investigate the possible explanatory factors for the existence of the abnormal return. As the announcement effect may spread out over a long period of time, it more suitable to use the CAR as an indicator of the existence of abnormal return.
FindingsAs shown in Table 5, the first explanatory variable shows a negative sign which implies that companies that have real estate as their core business produced a negative abnormal return as compared to those which are non-real estate focus. This finding differs from that in Ooi and Sirmans (2004), which yielded a positive result for property-focused companies. It appears that the focus of the companys business is not as important as the track record and experience of the company.For example, some multi-industry firms like Tuan Sing Holdings and Guthrie GTS Limited are involved in several types of business activities, but they also managed to achieve high returns in property development.
LimitationsOverall, the regression model has an R-square value of 0.244, which is not a strong fit as this indicates that only 24.4% of the changes in the abnormal return on D+1 are explained by the set of chosen explanatory variables. All the coefficients are also found to be insignificant. Hence, there could other significant determinants which are not included in the model. They should be identified in further studies and included for analysis.
CONCLUSIONSProperty firms need land to carry out their primary activities. It is thus expected that land acquisitions made by these firms will directly affect their shareholders wealth. The response of the shareholders on the successful land acquisitions can be observed through the movement of the stock prices when the announcements are made. Event study provides a useful tool to measure the effects of an economic event on the value of the firms. This research methodology exploit the fact, given rationality in the marketplace, the effects of an event will be reflected immediately in stock prices.
Thank you!
*******
Recommended | https://vdocuments.site/analysis-of-land-tenders-in-singapore.html | CC-MAIN-2020-10 | refinedweb | 1,632 | 50.36 |
libunbound man page
libunbound, unbound.h, ub_ctx, ub_result, ub_callback_type, ub_ctx_create, ub_ctx_delete, ub_ctx_set_option, ub_ctx_get_option, ub_ctx_config, ub_ctx_set_fwd, ub_ctx_set_stub, ub_ctx_resolvconf, ub_ctx_hosts, ub_ctx_add_ta, ub_ctx_add_ta_autr, ub_ctx_add_ta_file, ub_ctx_trustedkeys, ub_ctx_debugout, ub_ctx_debuglevel, ub_ctx_async, ub_poll, ub_wait, ub_fd, ub_process, ub_resolve, ub_resolve_async, ub_cancel, ub_resolve_free, ub_strerror, ub_ctx_print_local_zones, ub_ctx_zone_add, ub_ctx_zone_remove, ub_ctx_data_add, ub_ctx_data_remove — Unbound DNS validating resolver 1.6.8 functions.
Synopsis
#include <unbound.h>
struct ub_ctx * ub_ctx_create(void);
void ub_ctx_delete(struct ub_ctx* ctx);
int ub_ctx_set_option(struct ub_ctx* ctx, char* opt, char* val);
int ub_ctx_get_option(struct ub_ctx* ctx, char* opt, char** val);
int ub_ctx_config(struct ub_ctx* ctx, char* fname);
int ub_ctx_set_fwd(struct ub_ctx* ctx, char* addr);
int ub_ctx_set_stub(struct ub_ctx* ctx, char* zone, char* addr,
int isprime);
int ub_ctx_resolvconf(struct ub_ctx* ctx, char* fname);
int ub_ctx_hosts(struct ub_ctx* ctx, char* fname);
int ub_ctx_add_ta(struct ub_ctx* ctx, char* ta);
int ub_ctx_add_ta_autr(struct ub_ctx* ctx, char* fname);
int ub_ctx_add_ta_file(struct ub_ctx* ctx, char* fname);
int ub_ctx_trustedkeys(struct ub_ctx* ctx, char* fname);
int ub_ctx_debugout(struct ub_ctx* ctx, FILE* out);
int ub_ctx_debuglevel(struct ub_ctx* ctx, int d);
int ub_ctx_async(struct ub_ctx* ctx, int dothread);
int ub_poll(struct ub_ctx* ctx);
int ub_wait(struct ub_ctx* ctx);
int ub_fd(struct ub_ctx* ctx);
int ub_process(struct ub_ctx* ctx);
int ub_resolve(struct ub_ctx* ctx, char* name,
int rrtype, int rrclass, struct ub_result** result);
int ub_resolve_async(struct ub_ctx* ctx, char* name,
int rrtype, int rrclass, void* mydata,
ub_callback_type callback, int* async_id);
int ub_cancel(struct ub_ctx* ctx, int async_id);
void ub_resolve_free(struct ub_result* result);
const char * ub_strerror(int err);
int ub_ctx_print_local_zones(struct ub_ctx* ctx);
int ub_ctx_zone_add(struct ub_ctx* ctx, char* zone_name, char* zone_type);
int ub_ctx_zone_remove(struct ub_ctx* ctx, char* zone_name);
int ub_ctx_data_add(struct ub_ctx* ctx, char* data);
int ub_ctx_data_remove(struct ub_ctx* ctx, char* data);
Description
Unbound is an implementation of a DNS resolver, that does caching and DNSSEC validation. This is the library API, for using the -lunbound library. The server daemon is described in unbound(8). The library can be used to convert hostnames to ip addresses, and back, and obtain other information from the DNS. The library performs public-key validation of results with DNSSEC.
The library uses a variable of type struct ub_ctx to keep context between calls. The user must maintain it, creating it with ub_ctx_create and deleting it with ub_ctx_delete. It can be created and deleted at any time. Creating it anew removes any previous configuration (such as trusted keys) and clears any cached results.
The functions are thread-safe, and a context an be used in a threaded (as well as in a non-threaded) environment. Also resolution (and validation) can be performed blocking and non-blocking (also called asynchronous). The async method returns from the call immediately, so that processing can go on, while the results become available later.
The functions are discussed in turn below.
Functions
- ub_ctx_create
Create a new context, initialised with defaults. The information from /etc/resolv.conf and /etc/hosts is not utilised by default. Use ub_ctx_resolvconf and ub_ctx_hosts to read them. Before you call this, use the openssl functions CRYPTO_set_id_callback and CRYPTO_set_locking_callback to set up asynchronous operation if you use lib openssl (the application calls these functions once for initialisation). Openssl 1.0.0 or later uses the CRYPTO_THREADID_set_callback function.
- ub_ctx_delete
Delete validation context and free associated resources. Outstanding async queries are killed and callbacks are not called for them.
- ub_ctx_set_option
A power-user interface that lets you specify one of the options from the config file format, see unbound.conf(5). Not all options are relevant. For some specific options, such as adding trust anchors, special routines exist. Pass the option name with the trailing ':'.
- ub_ctx_get_option
A power-user interface that gets an option value. Some options cannot be gotten, and others return a newline separated list. Pass the option name without trailing ':'. The returned value must be free(2)d by the caller.
- ub_ctx_config
A power-user interface that lets you specify an unbound config file, see unbound.conf(5), which is read for configuration. Not all options are relevant. For some specific options, such as adding trust anchors, special routines exist.
- ub_ctx_set_fwd
Set machine to forward DNS queries to, the caching resolver to use. IP4 or IP6 address. Forwards all DNS requests to that machine, which is expected to run a recursive resolver. If the proxy is not DNSSEC capable, validation may fail. Can be called several times, in that case the addresses are used as backup servers. At this time it is only possible to set configuration before the first resolve is done.
- ub_ctx_set_stub
Set a stub zone, authoritative dns servers to use for a particular zone. IP4 or IP6 address. If the address is NULL the stub entry is removed. Set isprime true if you configure root hints with it. Otherwise similar to the stub zone item from unbound's config file. Can be called several times, for different zones, or to add multiple addresses for a particular zone. At this time it is only possible to set configuration before the first resolve is done.
- ub_ctx_resolvconf
By default the root servers are queried and full resolver mode is used, but you can use this call to read the list of nameservers to use from the filename given. Usually "/etc/resolv.conf". Uses those nameservers as caching proxies. If they do not support DNSSEC, validation may fail. Only nameservers are picked up, the searchdomain, ndots and other settings from resolv.conf(5) are ignored. If fname NULL is passed, "/etc/resolv.conf" is used (if on Windows, the system-wide configured nameserver is picked instead). At this time it is only possible to set configuration before the first resolve is done.
- ub_ctx_hosts
Read list of hosts from the filename given. Usually "/etc/hosts". When queried for, these addresses are not marked DNSSEC secure. If fname NULL is passed, "/etc/hosts" is used (if on Windows, etc/hosts from WINDIR is picked instead). At this time it is only possible to set configuration before the first resolve is done.
- ub_ctx_add_ta
Add a trust anchor to the given context. At this time it is only possible to add trusted keys before the first resolve is done. The format is a string, similar to the zone-file format, [domainname] [type] [rdata contents]. Both DS and DNSKEY records are accepted.
- ub_ctx_add_ta_autr
Add filename with automatically tracked trust anchor to the given context. Pass name of a file with the managed trust anchor. You can create this file with unbound-anchor(8) for the root anchor. You can also create it with an initial file with one line with a DNSKEY or DS record. If the file is writable, it is updated when the trust anchor changes. At this time it is only possible to add trusted keys before the first resolve is done.
- ub_ctx_add_ta_file
Add trust anchors to the given context. Pass name of a file with DS and DNSKEY records in zone file format. At this time it is only possible to add trusted keys before the first resolve is done.
- ub_ctx_trustedkeys
Add trust anchors to the given context. Pass the name of a bind-style config file with trusted-keys{}. At this time it is only possible to add trusted keys before the first resolve is done.
- ub_ctx_debugout
Set debug and error log output to the given stream. Pass NULL to disable output. Default is stderr. File-names or using syslog can be enabled using config options, this routine is for using your own stream.
- ub_ctx_debuglevel
Set debug verbosity for the context. Output is directed to stderr. Higher debug level gives more output.
- ub_ctx_async
Set a context behaviour for asynchronous action. if set to true, enables threading and a call to ub_resolve_async creates a thread to handle work in the background. If false, a process is forked to handle work in the background. Changes to this setting after ub_resolve_async calls have been made have no effect (delete and re-create the context to change).
- ub_poll
Poll a context to see if it has any new results. Do not poll in a loop, instead extract the fd below to poll for readiness, and then check, or wait using the wait routine. Returns 0 if nothing to read, or nonzero if a result is available. If nonzero, call ub_process to do callbacks.
- ub_wait
Wait for a context to finish with results. Calls ub_process after the wait for you. After the wait, there are no more outstanding asynchronous queries.
- ub_fd
Get file descriptor. Wait for it to become readable, at this point answers are returned from the asynchronous validating resolver. Then call the ub_process to continue processing.
- ub_process
Call this routine to continue processing results from the validating resolver (when the fd becomes readable). Will perform necessary callbacks.
- ub_resolve
Perform resolution and validation of the target name. The name is a domain name in a zero terminated text string. The rrtype and rrclass are DNS type and class codes. The result structure is newly allocated with the resulting data.
- ub_resolve_async
Perform asynchronous resolution and validation of the target name. Arguments mean the same as for ub_resolve except no data is returned immediately, instead a callback is called later. The callback receives a copy of the mydata pointer, that you can use to pass information to the callback. The callback type is a function pointer to a function declared as
void my_callback_function(void* my_arg, int err,
struct ub_result* result);
The async_id is returned so you can (at your option) decide to track it and cancel the request if needed. If you pass a NULL pointer the async_id is not returned.
- ub_cancel
Cancel an async query in progress. This may return an error if the query does not exist, or the query is already being delivered, in that case you may still get a callback for the query.
- ub_resolve_free
Free struct ub_result contents after use.
- ub_strerror
Convert error value from one of the unbound library functions to a human readable string.
- ub_ctx_print_local_zones
Debug printout the local authority information to debug output.
- ub_ctx_zone_add
Add new zone to local authority info, like local-zone unbound.conf(5) statement.
- ub_ctx_zone_remove
Delete zone from local authority info.
- ub_ctx_data_add
Add resource record data to local authority info, like local-data unbound.conf(5) statement.
- ub_ctx_data_remove
Delete local authority data from the name given.
Result Data Structure
The result of the DNS resolution and validation is returned as struct ub_result. The result structure contains the following entries.
struct ub_result { char* qname; /* text string, original question */ int qtype; /* type code asked for */ int qclass; /* class code asked for */ char** data; /* array of rdata items, NULL terminated*/ int* len; /* array with lengths of rdata items */ char* canonname; /* canonical name of result */ int rcode; /* additional error code in case of no data */ void* answer_packet; /* full network format answer packet */ int answer_len; /* length of packet in octets */ int havedata; /* true if there is data */ int nxdomain; /* true if nodata because name does not exist */ int secure; /* true if result is secure */ int bogus; /* true if a security failure happened */ char* why_bogus; /* string with error if bogus */ int ttl; /* number of seconds the result is valid */ };
If both secure and bogus are false, security was not enabled for the domain of the query. Else, they are not both true, one of them is true.
Return Values
Many routines return an error code. The value 0 (zero) denotes no error happened. Other values can be passed to ub_strerror to obtain a readable error string. ub_strerror returns a zero terminated string. ub_ctx_create returns NULL on an error (a malloc failure). ub_poll returns true if some information may be available, false otherwise. ub_fd returns a file descriptor or -1 on error.
See Also
unbound.conf(5), unbound(8).
Authors
Unbound developers are mentioned in the CREDITS file in the distribution.
Referenced By
unbound-host(1).
The man pages ub_cancel(3), ub_ctx(3), ub_ctx_add_ta(3), ub_ctx_add_ta_file(3), ub_ctx_async(3), ub_ctx_config(3), ub_ctx_create(3), ub_ctx_data_add(3), ub_ctx_data_remove(3), ub_ctx_debuglevel(3), ub_ctx_debugout(3), ub_ctx_delete(3), ub_ctx_get_option(3), ub_ctx_hosts(3), ub_ctx_print_local_zones(3), ub_ctx_resolvconf(3), ub_ctx_set_fwd(3), ub_ctx_set_option(3), ub_ctx_trustedkeys(3), ub_ctx_zone_add(3), ub_ctx_zone_remove(3), ub_fd(3), ub_poll(3), ub_process(3), ub_resolve(3), ub_resolve_async(3), ub_resolve_free(3), ub_result(3), ub_strerror(3) and ub_wait(3) are aliases of libunbound(3). | https://www.mankier.com/3/libunbound | CC-MAIN-2018-13 | refinedweb | 2,014 | 56.96 |
Dart Runtime for AWS Lambda
A 🎯 Dart Runtime for ƛ AWS Lambda
Read Introducing a Dart runtime for AWS Lambda
🚀 Experimental support for ⚡️ serverless framework
If you need to access AWS APIs in your Lambda function, please search on pub.dev for packages provided by Agilord
Features
- Great performance
< 10mson event processing and
< 50MBmemory consumption
- No need to ship the Dart runtime
- Multiple event handlers
- Typed events
- Custom events
this package requires Dart
>= 2.6currently
dart2nativeonly supports building for the platform it is run on, so you must either build on a
Linuxmachine or use
docker
🚀 Introduction
Dart is an unsupported AWS Lambda runtime language. However, with a custom runtime you can support virtually every programming language.
There are two ways in which you could use Dart. You could bundle the Dart Runtime in a Lambda layer and use JIT compilation within the lambda execution to run a Dart program. The other is to compile a shippable binary of the Dart program.
Dart
>= 2.6 introduced
dart2native. The tool uses AOT (ahead-of-time) to compile a Dart program to native x64 machine code. This standalone executable is native machine code that's compiled from the specific Dart file and its dependencies, plus a small Dart runtime that handles type checking and garbage collection.
We decided to use the latter approach rather then the just-in-time compilation of Dart files. The main reason for this decision is that we wanted to avoid having to ship and maintain a standalone Dart runtime version. We would eventually have to deprecate versions, or always update the version when moving forward. Furthermore, shipping a binary has the advantage of having an always runnable version of your function in addition to performance benefits.
We want to highlight Firecracker open-source innovation from re:Invent 2019 which gives you a brief overview of Firecracker which is the underlying technology of AWS Lambda.
📦 Use
Add the following snippet to your pubspec file in
pubspec.yaml.
dependencies: aws_lambda_dart_runtime: ^1.0.3+2
Docs are available. They are also accessible in the
docs folder.
# access the docs local pub global activate dhttpd dhttpd --path docs
you can generate the docs with
dartdoc --output docs
Build and deploy the Dart functions by the serverless framework or by custom deployment.
🧪 Serverless Framework (experimental)
You can start your next project using the serverless-aws-dart template.
$ npx serverless install \ --url \ --name hello
Every serverless workflow command should work out of the box. The template also includes an example GitHub actions configuration file which can unlock a virtuous cycle of continuous integration and deployment ( i.e all tests are run on prs and every push to master results in a deployment).
Custom deployment
The deployment is a manual task right now. We have a
example/build.sh script which makes the process a bit easier. There are three steps to get your code ready to be shipped.
- Compile your Dart program with
dart2native main.dart -o bootstrap
- Create a
.zipfile with
zip lambda.zip bootstrap
- Upload the
lambda.zipto a S3 bucket or use the AWS CLI to upload it
again, you have to build this on Linux, because
dart2nativedoes not support cross-compiling
When you created your function and upload it via the the console. Please, replace
arn:aws:iam::xxx:xxx with the role you created for your lambda.
aws lambda create-function --function-name dartTest \ --handler hello.apigateway \ --zip-file fileb://./lambda.zip \ --runtime provided \ --role arn:aws:iam::xxx:xxx \ --environment Variables={DART_BACKTRACE=1} \ --tracing-config Mode=Active
Updating a function is a fairly easy task. Rebuild your
lambda.zip package and execute the following command.
aws lambda update-function-code --function-name dartTest --zip-file fileb://./lambda.zip
Events
There are a number of events that come with the Dart Runtime.
- Application Load Balancer
- Alexa
- API Gateway
- AppSync
- Cloudwatch
- Cognito
- DynamoDB
- Kinesis
- S3
- SQS
You can also register custom events.
import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; class MyCustomEvent { factory MyCustomEvent.fromJson(Map<String, dynamic> json) => MyCustomEvent(json); const MyCustomEvent(); } void main() async { final Handler<MyCustomEvent> successHandler = (context, event) async { return InvocationResult(context.requestId, "SUCCESS"); }; Runtime() ..registerEvent<MyCustomEvent>((Map<String, dynamic> json) => MyCustomEvent.from(json)) ..registerHandler<MyCustomEvent>("doesnt.matter", successHandler) ..invoke(); }
Example
The example in
main.dart show how the package is intended to be used. Because
dart2native does not support cross-platform compilation, you can use the
google/dart (:warning: if you are on
Linux you can ignore this) container to build the project. The
build.sh script automates the build process in the container.
# will build the binary in the container cd example; docker run -v $PWD:/app --entrypoint app/build.sh google/dart && zip lambda.zip bootstrap && rm bootstrap
You will see the
lambda.zip which you can upload manually, or use the client of your choice.
What you see in the example is an example of the interface to the Dart Runtime that we created.
You will have to make
aws_lambda_dart_runtime a dependency of your project.
... dependencies: aws_lambda_dart_runtime: ...
We support using multiple handlers in one executable. The following example shows to register one handler.
import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; void main() async { /// This demo's handling an API Gateway request. final Handler<AwsApiGatewayEvent> helloApiGateway = (context, event) async { final response = {"message": "hello ${context.requestId}"}; /// it returns an encoded response to the gateway return InvocationResult( context.requestId, AwsApiGatewayResponse.fromJson(response)); }; /// The Runtime is a singleton. You can define the handlers as you wish. Runtime() ..registerHandler<AwsApiGatewayEvent>("hello.apigateway", helloApiGateway) ..invoke(); }
This example registers the
hello.apigateway handler with the function to execute for this handler. The handler function is typed to receive a Amazon API Gateway Event and it returns a response to the invoking gateway. We support many other events. Handler functions get a
Context injected with the needed information about the invocation. You can also register your own custom events via
Runtime.registerEvent<T>(Handler<T>) (see events).
Limitations
Development
If you want to use the Repository directly you can clone it and overwrite the dependency in your
pubspec.yaml as follows.
dependency_overrides: aws_lambda_dart_runtime: path: <path_to_source>
The
data folder contains examples of the used events. We use this to run our tests, but you can also use them to implement new features. If you want to request the processing of a new event, you may provide a payload here.
# run the tests pub run test
License
We :blue_heart: Dart. | https://pub.dev/documentation/aws_lambda_dart_runtime/latest/ | CC-MAIN-2022-33 | refinedweb | 1,064 | 50.02 |
Each variable has a storage class which defines the features of that variable. It tells the compiler about where to store the variable, its initial value, scope ( visibility level ) and lifetime ( global or local ).
There are four storage classes in C.
- auto
- extern
- static and are by default assigned some garbage value. <stdio.h> int sum(int n1, int n2){ auto int s; //declaration of auto(local) variable s = n1+n2; return s; } int main(){ int i = 2, j = 3, k; k = sum(i, j); printf("sum is : %d\n", k); <stdio.h> int g; void print(){ g = 10; printf("g = %d\n", g); } int main(){ g = 7; printf("g = %d\n", g); print(); return 0; }
extern keyword as shown below.
firstfile.c
int g = 0;
In the first program file
firstfile.c, we declared a global variable
g.
Now, we will declare this variable 'g' as extern in a header file
firstfile.h and then include it in the second file in which we want to use this variable.
firstfile.h
extern int g;
Now in the second program file
secondfile.c, in order to use the global variable 'g', we need to include the header file in it by writing
#include "firstfile.h". Here we assigned a value 4 to the variable 'g' and thus the value of 'g' in this program becomes 4.
secondfile.c
#include "firstfile.h"
main(){
g = 4;
printf("%d", g);
}
static
A variable declared as static once initialized, exists till the end of the program. If a static variable is declared inside a function, it remains into existence till <stdio.h> static int g = 5; void fn(){ static int i = 0; printf("g = %d\t", g--); printf("i = %d\n",i++); } int main(){ while(g >= 2) fn(); return 0; }
g = 4 i = 1
g = 3 i = 2
g = 2 i = 3
Here,
g and
i are the static variables in which 'g' is a global variable and 'i' is a local variable. If we had not written
static before the declaration of 'i', then everytime.
We cannot access the address of such variables since these do not have a memory location as which becomes clear by the following example.
#include <stdio.h> int main() { register int n = 20; int *ptr; ptr = &n; printf("address of n : %u", ptr); return 0; }
main(){
^
prog.c: In function 'main':
prog.c:5:1: error: address of register variable 'n' requested
ptr = &n;
^ | https://www.codesdope.com/c-storage-classes/ | CC-MAIN-2020-24 | refinedweb | 406 | 71.24 |
Modifying Records Part 2
Senior Editor, TheScripts.com
I told you all that after we get started, it just makes sense. Now onto the third part of editing.......
elsif ($form{'action'} eq "edit_three") {
&edit_three;
}
&edit_three.... how ingenious of a name.
sub edit_three {
&header("Edit Record");
The header part of the page. We are sending it the title "
Edit Record"
print qq~
<CENTER><TABLE border=1 bgcolor="#FFFFFF" cellpadding=3 cellspacing=0>
<TR bgcolor="#C0C0C0"><TD>
<CENTER>
<FORM METHOD=POST>
<INPUT TYPE="hidden" NAME="action" VALUE="edit_four">
<INPUT TYPE="hidden" NAME="key" VALUE="$form{'key'}">~;
This part was mainly just simple html, but notice the two hidden fields. The first one is our infamous action field, with a value of edit_four (guess what the next sub will be named :-) ), and the other hidden field is '
key', with the value of
$form{'key'} in it.
$form{'key'} is the ID number, or whatever you set
$db_key to be as the record identifier.
my (%result) = &get_record($form{'key'});
Into the hash
%result goes the returned value of
&get_record after feeding into it the value of
$form{'key'}, the database entry identifier.
Since I did not explain
&get_record in the adding record section of this tutorial, I promised to explain it here.
sub get_record {
my ($exist) = 0;
Set this my variable to a null value
my ($key) = shift;
This my variable will now have the data sent to it (the database entry identifier) as its value.
open(DATA, $file);
Here we open the database file with a handle of DATA
while (<DATA>) {
As long as DATA has a value and did not reach the end of file mark yet, this loop will repeat.
(/^\s*$/) and next; # Looks for blank lines and skip them.
Just as the comment tag states, here we look for blank lines and skip them, going to the next line.
chomp $_;
$_ has a newline attached at the end, so here we ourselves of it.
@record = &grab_data($_);
Here we do our usual line processing.
&grab_data splits the line into an array,
@record;
%dat = &process_record(@record);
&process_record in turn changes
@record to a hash for easy use.
if ($dat{$db_key} eq $key) {
$exist = 1;
}
If the database link identifier is equal to the
$key we are requesting,
$exist is set to a non-null value, and we break out of the while loop.
}
End of While Loop
close (DATA);
Here we close our read-only copy of DATA.
$exist ? return (%dat) : return;
Here comes our new friend, the ternary operator, making yet another appearance. If
$exist has a non-null value, the contents of our hash
%dat is returned. Otherwise, we return no value at all.
}
End of get_record | http://bytes.com/serversidescripting/perl/tutorials/asimpledatabaseprogram/page14.html | crawl-002 | refinedweb | 449 | 70.63 |
Line data Source code
1 : //===- FunctionComparator.h - Function Comparator ---------------*- C++ -*-===//
2 : //
3 : // The LLVM Compiler Infrastructure
4 : //
5 : // This file is distributed under the University of Illinois Open Source
6 : // License. See LICENSE.TXT for details.
7 : //
8 : //===----------------------------------------------------------------------===//
9 : //
10 : // This file defines the FunctionComparator and GlobalNumberState classes which
11 : // are used by the MergeFunctions pass for comparing functions.
12 : //
13 : //===----------------------------------------------------------------------===//
14 :
15 : #ifndef LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
16 : #define LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
17 :
18 : #include "llvm/ADT/DenseMap.h"
19 : #include "llvm/ADT/StringRef.h"
20 : #include "llvm/IR/Attributes.h"
21 : #include "llvm/IR/Instructions.h"
22 : #include "llvm/IR/Operator.h"
23 : #include "llvm/IR/ValueMap.h"
24 : #include "llvm/Support/AtomicOrdering.h"
25 : #include "llvm/Support/Casting.h"
26 : #include <cstdint>
27 : #include <tuple>
28 :
29 : namespace llvm {
30 :
31 : class APFloat;
32 : class APInt;
33 : class BasicBlock;
34 : class Constant;
35 : class Function;
36 : class GlobalValue;
37 : class InlineAsm;
38 : class Instruction;
39 : class MDNode;
40 : class Type;
41 : class Value;
42 :
43 : /// GlobalNumberState assigns an integer to each global value in the program,
44 : /// which is used by the comparison routine to order references to globals. This
45 : /// state must be preserved throughout the pass, because Functions and other
46 : /// globals need to maintain their relative order. Globals are assigned a number
47 : /// when they are first visited. This order is deterministic, and so the
48 : /// assigned numbers are as well. When two functions are merged, neither number
49 : /// is updated. If the symbols are weak, this would be incorrect. If they are
50 : /// strong, then one will be replaced at all references to the other, and so
51 : /// direct callsites will now see one or the other symbol, and no update is
52 : /// necessary. Note that if we were guaranteed unique names, we could just
53 : /// compare those, but this would not work for stripped bitcodes or for those
54 : /// few symbols without a name.
55 51 : class GlobalNumberState {
56 : struct Config : ValueMapConfig<GlobalValue *> {
57 : enum { FollowRAUW = false };
58 : };
59 :
60 : // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
61 : // occurs, the mapping does not change. Tracking changes is unnecessary, and
62 : // also problematic for weak symbols (which may be overwritten).
63 : using ValueNumberMap = ValueMap<GlobalValue *, uint64_t, Config>;
64 : ValueNumberMap GlobalNumbers;
65 :
66 : // The next unused serial number to assign to a global.
67 : uint64_t NextNumber = 0;
68 :
69 : public:
70 51 : GlobalNumberState() = default;
71 :
72 26 : uint64_t getNumber(GlobalValue* Global) {
73 : ValueNumberMap::iterator MapIter;
74 : bool Inserted;
75 78 : std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
76 26 : if (Inserted)
77 11 : NextNumber++;
78 26 : return MapIter->second;
79 : }
80 :
81 : void erase(GlobalValue *Global) {
82 4 : GlobalNumbers.erase(Global);
83 : }
84 :
85 : void clear() {
86 : GlobalNumbers.clear();
87 : }
88 : };
89 :
90 : /// FunctionComparator - Compares two functions to determine whether or not
91 : /// they will generate machine code with the same behaviour. DataLayout is
92 : /// used if available. The comparator always fails conservatively (erring on the
93 : /// side of claiming that two functions are different).
94 : class FunctionComparator {
95 : public:
96 : FunctionComparator(const Function *F1, const Function *F2,
97 : GlobalNumberState* GN)
98 392 : : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
99 :
100 : /// Test whether the two functions have equivalent behaviour.
101 : int compare();
102 :
103 : /// Hash a function. Equivalent functions will have the same hash, and unequal
104 : /// functions will have different hashes with high probability.
105 : using FunctionHash = uint64_t;
106 : static FunctionHash functionHash(Function &);
107 :
108 : protected:
109 : /// Start the comparison.
110 : void beginCompare() {
111 204 : sn_mapL.clear();
112 204 : sn_mapR.clear();
113 : }
114 :
115 : /// Compares the signature and other general attributes of the two functions.
116 : int compareSignature() const;
117 :
118 : /// Test whether two basic blocks have equivalent behaviour.
119 : int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const;
120 :
121 : /// Constants comparison.
122 : /// Its analog to lexicographical comparison between hypothetical numbers
123 : /// of next format:
124 : /// <bitcastability-trait><raw-bit-contents>
125 : ///
126 : /// 1. Bitcastability.
127 : /// Check whether L's type could be losslessly bitcasted to R's type.
128 : /// On this stage method, in case when lossless bitcast is not possible
129 : /// method returns -1 or 1, thus also defining which type is greater in
130 : /// context of bitcastability.
131 : /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
132 : /// to the contents comparison.
133 : /// If types differ, remember types comparison result and check
134 : /// whether we still can bitcast types.
135 : /// Stage 1: Types that satisfies isFirstClassType conditions are always
136 : /// greater then others.
137 : /// Stage 2: Vector is greater then non-vector.
138 : /// If both types are vectors, then vector with greater bitwidth is
139 : /// greater.
140 : /// If both types are vectors with the same bitwidth, then types
141 : /// are bitcastable, and we can skip other stages, and go to contents
142 : /// comparison.
143 : /// Stage 3: Pointer types are greater than non-pointers. If both types are
144 : /// pointers of the same address space - go to contents comparison.
145 : /// Different address spaces: pointer with greater address space is
146 : /// greater.
147 : /// Stage 4: Types are neither vectors, nor pointers. And they differ.
148 : /// We don't know how to bitcast them. So, we better don't do it,
149 : /// and return types comparison result (so it determines the
150 : /// relationship among constants we don't know how to bitcast).
151 : ///
152 : /// Just for clearance, let's see how the set of constants could look
153 : /// on single dimension axis:
154 : ///
155 : /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
156 : /// Where: NFCT - Not a FirstClassType
157 : /// FCT - FirstClassTyp:
158 : ///
159 : /// 2. Compare raw contents.
160 : /// It ignores types on this stage and only compares bits from L and R.
161 : /// Returns 0, if L and R has equivalent contents.
162 : /// -1 or 1 if values are different.
163 : /// Pretty trivial:
164 : /// 2.1. If contents are numbers, compare numbers.
165 : /// Ints with greater bitwidth are greater. Ints with same bitwidths
166 : /// compared by their contents.
167 : /// 2.2. "And so on". Just to avoid discrepancies with comments
168 : /// perhaps it would be better to read the implementation itself.
169 : /// 3. And again about overall picture. Let's look back at how the ordered set
170 : /// of constants will look like:
171 : /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
172 : ///
173 : /// Now look, what could be inside [FCT, "others"], for example:
174 : /// [FCT, "others"] =
175 : /// [
176 : /// [double 0.1], [double 1.23],
177 : /// [i32 1], [i32 2],
178 : /// { double 1.0 }, ; StructTyID, NumElements = 1
179 : /// { i32 1 }, ; StructTyID, NumElements = 1
180 : /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
181 : /// { i32 1, double 1 } ; StructTyID, NumElements = 2
182 : /// ]
183 : ///
184 : /// Let's explain the order. Float numbers will be less than integers, just
185 : /// because of cmpType terms: FloatTyID < IntegerTyID.
186 : /// Floats (with same fltSemantics) are sorted according to their value.
187 : /// Then you can see integers, and they are, like a floats,
188 : /// could be easy sorted among each others.
189 : /// The structures. Structures are grouped at the tail, again because of their
190 : /// TypeID: StructTyID > IntegerTyID > FloatTyID.
191 : /// Structures with greater number of elements are greater. Structures with
192 : /// greater elements going first are greater.
193 : /// The same logic with vectors, arrays and other possible complex types.
194 : ///
195 : /// Bitcastable constants.
196 : /// Let's assume, that some constant, belongs to some group of
197 : /// "so-called-equal" values with different types, and at the same time
198 : /// belongs to another group of constants with equal types
199 : /// and "really" equal values.
200 : ///
201 : /// Now, prove that this is impossible:
202 : ///
203 : /// If constant A with type TyA is bitcastable to B with type TyB, then:
204 : /// 1. All constants with equal types to TyA, are bitcastable to B. Since
205 : /// those should be vectors (if TyA is vector), pointers
206 : /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
207 : /// be equal to TyB.
208 : /// 2. All constants with non-equal, but bitcastable types to TyA, are
209 : /// bitcastable to B.
210 : /// Once again, just because we allow it to vectors and pointers only.
211 : /// This statement could be expanded as below:
212 : /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
213 : /// vector B, and thus bitcastable to B as well.
214 : /// 2.2. All pointers of the same address space, no matter what they point to,
215 : /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
216 : /// So any constant equal or bitcastable to A is equal or bitcastable to B.
217 : /// QED.
218 : ///
219 : /// In another words, for pointers and vectors, we ignore top-level type and
220 : /// look at their particular properties (bit-width for vectors, and
221 : /// address space for pointers).
222 : /// If these properties are equal - compare their contents.
223 : int cmpConstants(const Constant *L, const Constant *R) const;
224 :
225 : /// Compares two global values by number. Uses the GlobalNumbersState to
226 : /// identify the same gobals across function calls.
227 : int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const;
228 :
229 : /// Assign or look up previously assigned numbers for the two values, and
230 : /// return whether the numbers are equal. Numbers are assigned in the order
231 : /// visited.
232 : /// Comparison order:
233 : /// Stage 0: Value that is function itself is always greater then others.
234 : /// If left and right values are references to their functions, then
235 : /// they are equal.
236 : /// Stage 1: Constants are greater than non-constants.
237 : /// If both left and right are constants, then the result of
238 : /// cmpConstants is used as cmpValues result.
239 : /// Stage 2: InlineAsm instances are greater than others. If both left and
240 : /// right are InlineAsm instances, InlineAsm* pointers casted to
241 : /// integers and compared as numbers.
242 : /// Stage 3: For all other cases we compare order we meet these values in
243 : /// their functions. If right value was met first during scanning,
244 : /// then left value is greater.
245 : /// In another words, we compare serial numbers, for more details
246 : /// see comments for sn_mapL and sn_mapR.
247 : int cmpValues(const Value *L, const Value *R) const;
248 :
249 : /// Compare two Instructions for equivalence, similar to
250 : /// Instruction::isSameOperationAs.
251 : ///
252 : /// Stages are listed in "most significant stage first" order:
253 : /// On each stage below, we do comparison between some left and right
254 : /// operation parts. If parts are non-equal, we assign parts comparison
255 : /// result to the operation comparison result and exit from method.
256 : /// Otherwise we proceed to the next stage.
257 : /// Stages:
258 : /// 1. Operations opcodes. Compared as numbers.
259 : /// 2. Number of operands.
260 : /// 3. Operation types. Compared with cmpType method.
261 : /// 4. Compare operation subclass optional data as stream of bytes:
262 : /// just convert it to integers and call cmpNumbers.
263 : /// 5. Compare in operation operand types with cmpType in
264 : /// most significant operand first order.
265 : /// 6. Last stage. Check operations for some specific attributes.
266 : /// For example, for Load it would be:
267 : /// 6.1.Load: volatile (as boolean flag)
268 : /// 6.2.Load: alignment (as integer numbers)
269 : /// 6.3.Load: ordering (as underlying enum class value)
270 : /// 6.4.Load: synch-scope (as integer numbers)
271 : /// 6.5.Load: range metadata (as integer ranges)
272 : /// On this stage its better to see the code, since its not more than 10-15
273 : /// strings for particular instruction, and could change sometimes.
274 : ///
275 : /// Sets \p needToCmpOperands to true if the operands of the instructions
276 : /// still must be compared afterwards. In this case it's already guaranteed
277 : /// that both instructions have the same number of operands.
278 : int cmpOperations(const Instruction *L, const Instruction *R,
279 : bool &needToCmpOperands) const;
280 :
281 : /// cmpType - compares two types,
282 : /// defines total ordering among the types set.
283 : ///
284 : /// Return values:
285 : /// 0 if types are equal,
286 : /// -1 if Left is less than Right,
287 : /// +1 if Left is greater than Right.
288 : ///
289 : /// Description:
290 : /// Comparison is broken onto stages. Like in lexicographical comparison
291 : /// stage coming first has higher priority.
292 : /// On each explanation stage keep in mind total ordering properties.
293 : ///
294 : /// 0. Before comparison we coerce pointer types of 0 address space to
295 : /// integer.
296 : /// We also don't bother with same type at left and right, so
297 : /// just return 0 in this case.
298 : ///
299 : /// 1. If types are of different kind (different type IDs).
300 : /// Return result of type IDs comparison, treating them as numbers.
301 : /// 2. If types are integers, check that they have the same width. If they
302 : /// are vectors, check that they have the same count and subtype.
303 : /// 3. Types have the same ID, so check whether they are one of:
304 : /// * Void
305 : /// * Float
306 : /// * Double
307 : /// * X86_FP80
308 : /// * FP128
309 : /// * PPC_FP128
310 : /// * Label
311 : /// * Metadata
312 : /// We can treat these types as equal whenever their IDs are same.
313 : /// 4. If Left and Right are pointers, return result of address space
314 : /// comparison (numbers comparison). We can treat pointer types of same
315 : /// address space as equal.
316 : /// 5. If types are complex.
317 : /// Then both Left and Right are to be expanded and their element types will
318 : /// be checked with the same way. If we get Res != 0 on some stage, return it.
319 : /// Otherwise return 0.
320 : /// 6. For all other cases put llvm_unreachable.
321 : int cmpTypes(Type *TyL, Type *TyR) const;
322 :
323 : int cmpNumbers(uint64_t L, uint64_t R) const;
324 : int cmpAPInts(const APInt &L, const APInt &R) const;
325 : int cmpAPFloats(const APFloat &L, const APFloat &R) const;
326 : int cmpMem(StringRef L, StringRef R) const;
327 :
328 : // The two functions undergoing comparison.
329 : const Function *FnL, *FnR;
330 :
331 : private:
332 : int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
333 : int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
334 : int cmpAttrs(const AttributeList L, const AttributeList R) const;
335 : int cmpRangeMetadata(const MDNode *L, const MDNode *R) const;
336 : int cmpOperandBundlesSchema(const Instruction *L, const Instruction *R) const;
337 :
338 : /// Compare two GEPs for equivalent pointer arithmetic.
339 : /// Parts to be compared for each comparison stage,
340 : /// most significant stage first:
341 : /// 1. Address space. As numbers.
342 : /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
343 : /// 3. Pointer operand type (using cmpType method).
344 : /// 4. Number of operands.
345 : /// 5. Compare operands, using cmpValues method.
346 : int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
347 : int cmpGEPs(const GetElementPtrInst *GEPL,
348 : const GetElementPtrInst *GEPR) const {
349 35 : return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
350 : }
351 :
352 : /// Assign serial numbers to values from left function, and values from
353 : /// right function.
354 : /// Explanation:
355 : /// Being comparing functions we need to compare values we meet at left and
356 : /// right sides.
357 : /// Its easy to sort things out for external values. It just should be
358 : /// the same value at left and right.
359 : /// But for local values (those were introduced inside function body)
360 : /// we have to ensure they were introduced at exactly the same place,
361 : /// and plays the same role.
362 : /// Let's assign serial number to each value when we meet it first time.
363 : /// Values that were met at same place will be with same serial numbers.
364 : /// In this case it would be good to explain few points about values assigned
365 : /// to BBs and other ways of implementation (see below).
366 : ///
367 : /// 1. Safety of BB reordering.
368 : /// It's safe to change the order of BasicBlocks in function.
369 : /// Relationship with other functions and serial numbering will not be
370 : /// changed in this case.
371 : /// As follows from FunctionComparator::compare(), we do CFG walk: we start
372 : /// from the entry, and then take each terminator. So it doesn't matter how in
373 : /// fact BBs are ordered in function. And since cmpValues are called during
374 : /// this walk, the numbering depends only on how BBs located inside the CFG.
375 : /// So the answer is - yes. We will get the same numbering.
376 : ///
377 : /// 2. Impossibility to use dominance properties of values.
378 : /// If we compare two instruction operands: first is usage of local
379 : /// variable AL from function FL, and second is usage of local variable AR
380 : /// from FR, we could compare their origins and check whether they are
381 : /// defined at the same place.
382 : /// But, we are still not able to compare operands of PHI nodes, since those
383 : /// could be operands from further BBs we didn't scan yet.
384 : /// So it's impossible to use dominance properties in general.
385 : mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
386 :
387 : // The global state we will use
388 : GlobalNumberState* GlobalNumbers;
389 : };
390 :
391 : } // end namespace llvm
392 :
393 : #endif // LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H | http://llvm.org/reports/coverage/include/llvm/Transforms/Utils/FunctionComparator.h.gcov.html | CC-MAIN-2018-34 | refinedweb | 2,787 | 64.61 |
10580/android-ble-gatt_error-getting-often-with-samsung-devices
I am working on BLE Applications, I have tested with different devices like Nexus, Moto, Samsung, LG. I am getting the GATT Error 133 in Samsung Devices alone(Samsung A5 2016). Trying to connect 10 times it gets connected only 2 or 3 times.Please Help me out.
I tried the following code
#!/usr/bin/python
import ibmiotf.device
from time import sleep
options = {
"org": "uguhsp",
"type": "iotsample-raspberry",
"id": "00aabbccde03",
"auth-method": "token",
"auth-token": "MASKED"
}
def myCommandCallback(cmd):
print('inside command callback')
print cmd
def main():
client = ibmiotf.device.Client(options)
client.connect()
client.commandCallback = myCommandCallback
while True:
sleep(1)
if __name__ == "__main__":
main()
which is essentially similar code as yours.
And I am able to publish the commands to reach the device.
Can you please confirm if only 1 device (or simulated device) is using the device credentials and that the credentials are not being shared by multiple devices (either physical device or simulated device)?
Not fully sure if you are wanting ...READ MORE
Use IP address instead of http ...READ MORE
Although high-level APIs like Qt5, which also ...READ MORE
Binding the network using ConnectivityManager.setProcessDefaultNetwork() will help ...READ MORE
I think that's because of the way ...READ MORE
Oh man, that was a heck of ...READ MORE
I solved this issue by updating my ...READ MORE
If I'm not wrong, it could be ...READ MORE
Why dont you create two Interfaces, one ...READ MORE
This is possible. I have been able ...READ MORE
OR | https://www.edureka.co/community/10580/android-ble-gatt_error-getting-often-with-samsung-devices | CC-MAIN-2019-30 | refinedweb | 261 | 61.22 |
Case Insensitive in D
Jesse Phillips
Updated on
・1 min read
Python (13 Part Series)
Let me begin with the naive approach before I tell you to go with the naive approach.
import std.string; assert("I be Big".toLower == "i be big");
As I mentioned last time unicode isn't simple. Well it isn't easier with changing characters and this mostly isn't a unicode problem. The upper/lowercase of a character in one language changes in another. This is where localization comes into play.
I'm actually not very well verse in this area so question my advice. If you're not working in data that crosses language boundaries then this change is mostly moot.
I haven't seen a solution in D for handling this. I only briefly looked into it for this article. So continue using toLower as was recommended to me for Python.
How to Improve Writing Skills as a Non-Native Speaker
Let me begin by saying, that writing a new post either on technical or soft skill topics is always a challenge for me. Why? Because I am not a native English speaker.
| https://practicaldev-herokuapp-com.global.ssl.fastly.net/jessekphillips/case-insensitive-in-d-2ogg | CC-MAIN-2019-43 | refinedweb | 191 | 65.93 |
The Oracle JVM turned out to the be clear winner in this speed test.
See the full details here: ... marks.html
Code: Select all
wiringPiSetup()
thanks for this post I missthanks for this post I missh. ...
Hi Robert,Hi Robert
Code: Select all,Trouch.
I was just wondering where was the overhead to explain the difference between oracle jvm and native c code starting from the groundI was just wondering where was the overhead to explain the difference between oracle jvm and native c code starting from the groundsavage?
Thanks for that link! I had not seen that article.Thanks for that link! I had not seen that article.trouch wrote:Thanks for your post and blog article, it's a great complement to ... pio-speed/
at this line:at this line:java.io.IOException: No matching device found
at sun.nio.ch.FileChannelImpl.map0(Native Method)
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:835)
Code: Select all
memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 8);
Code: Select all"); };
Code: Select all
Code: Select all
Code: Select all
Just got a RPi oscilloscope as well, looking forward to posting my benchmarks!Just got a RPi oscilloscope as well, looking forward to posting my benchmarks
Code: Select all
fdMem = open("/dev/gpiomem", O_RDWR | O_SYNC | O_CLOEXEC); gpioAddr = (uint32_t *)mmap(NULL, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fdMem, 0); return (*env)->NewDirectByteBuffer(env, gpioAddr, BLOCK_SIZE);
Code: Select all
public static native ByteBuffer initialise(); public static void main(String[] args) { ByteBuffer gpioReg = initialise(); }
Code: Select all
int i; for (i=0; i<4; i++) { printf("gpioAddr[0]=0x%x\n", gpioAddr[0]); }
Code: Select all
for (int i=0; i<4; i++) { System.out.format("gpioReg[%d]=0x%x%n", i, gpioReg.getInt(i*SIZE_OF_INT)); } | https://www.raspberrypi.org/forums/viewtopic.php?f=81&t=29026&p=255521 | CC-MAIN-2019-39 | refinedweb | 290 | 57.57 |
This post is based on the text of my GolangUK keynote delivered on the 18th of August 2016.
A recording of the talk is available on YouTube.
This post has been translated into Simplified Chinese by Haohao Tian. Thanks Haohao!
How many Go programmers are there in the world?
How many Go programmers are there in the world? Think of a number and hold it in your head, we’ll come back to it at the end of this talk.
Code review
Who here does code review as part of their job? [the entire room raised their hand, which was encouraging]. Okay, why do you do code review? [someone shouted out “to stop bad code”]
If code review is there to catch bad code, then how do you know if the code you’re reviewing is good, or bad?
Now it’s fine to say “that code is ugly” or ”wow that source code is beautiful”, just as you might say “this painting is beautiful” or “this room is beautiful” but these are subjective terms, and I’m looking for objective ways to talk about the properties of good or bad code.
Bad code
What are some of the properties of bad code that you might pick up on in code review?
- Rigid. Is the code rigid? Does it have a straight jacket of overbearing types and parameters, that making modification difficult?
- Fragile. Is the code fragile? Does the slightest change ripple through the code base causing untold havoc?
- Immobile. Is the code hard to refactor? Is it one keystroke away from an import loop?
- Complex. Is there code for the sake of having code, are things over-engineered?
- Verbose. Is it just exhausting to use the code? When you look at it, can you even tell what this code is trying to do?
Are these positive sounding words? Would you be pleased to see these words used in a review of your code?
Probably not.
Good design
But this is an improvement, now we can say things like “I don’t like this because it’s too hard to modify”, or “I don’t like this because i cannot tell what the code is trying to do”, but what about leading with the positive?
Wouldn’t it be great if there were some ways to describe the properties of good design, not just bad design, and to be able to do so in objective terms?
SOLID
In 2002 Robert Martin published his book, Agile Software Development, Principles, Patterns, and Practices. In it he described five principles of reusable software design, which he called the SOLID principles, after the first letters in their names.
- Single Responsibility Principle
- Open / Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
This book is a little dated, the languages that it talks about are the ones in use more than a decade ago. But, perhaps there are some aspects of the SOLID principles that may give us a clue about how to talk about a well designed Go programs.
So this is what I want to spend some time discussing with you this morning.
Single Responsibility Principle
The first principle of SOLID, the S, is the single responsibility principle.
A class should have one, and only one, reason to change.
–Robert C Martin
Now Go obviously doesn’t have classes—instead we have the far more powerful notion of composition—but if you can look past the use of the word class, I think there is some value here.
Why is it important that a piece of code should have only one reason for change? Well, as distressing as the idea that your own code may change, it is far more distressing to discover that code your code depends on is changing under your feet. And when your code does have to change, it should do so in response to a direct stimuli, it shouldn’t be a victim of collateral damage.
So code that has a single responsibility therefore has the fewest reasons to change.
Coupling & Cohesion
Two words that describe how easy or difficult it is to change a piece of software are coupling and cohesion.
Coupling is simply a word that describes two things changing together–a movement in one induces a movement in another.
A related, but separate, notion is the idea of cohesion, a force of mutual attraction.
In the context of software, cohesion is the property of describing pieces of code are naturally attracted to one another.
To describe the units of coupling and cohesion in a Go program, we might talk about functions and methods, as is very common when discussing SRP but I believe it starts with Go’s package model.
Package names
In Go, all code lives inside a package, and a well designed package starts with its name. A package’s name is both a description of its purpose, and a name space prefix. Some examples of good packages from the Go standard library might be:
net/http, which provides http clients and servers.
os/exec, which runs external commands.
encoding/json, which implements encoding and decoding of JSON documents.
When you use another package’s symbols inside your own this is accomplished by the `import` declaration, which establishes a source level coupling between two packages. They now know about each other.
Bad package names
This focus on names is not just pedantry. A poorly named package misses the opportunity to enumerate its purpose, if indeed it ever had one.
What does
package server provide? … well a server, hopefully, but which protocol?
What does
package private provide? Things that I should not see? Should it have any public symbols?
And
package common, just like its partner in crime,
package utils, is often found close by these other offenders.
Catch all packages like these become a dumping ground for miscellany, and because they have many responsibilities they change frequently and without cause.
Go’s UNIX philosophy
In my view, no discussion about decoupled design would be complete without mentioning Doug McIlroy’s Unix philosophy; small, sharp tools which combine to solve larger tasks, oftentimes tasks which were not envisioned by the original authors.
I think that Go packages embody the spirit of the UNIX philosophy. In effect each Go package is itself a small Go program, a single unit of change, with a single responsibility.
Open / Closed Principle
The second principle, the O, is the open closed principle by Bertrand Meyer who in 1988 wrote:
Software entities should be open for extension, but closed for modification.
–Bertrand Meyer, Object-Oriented Software Construction
How does this advice apply to a language written 21 years later?
package main type A struct { year int } func (a A) Greet() { fmt.Println("Hello GolangUK", a.year) } type B struct { A } func (b B) Greet() { fmt.Println("Welcome to GolangUK", b.year) } func main() { var a A a.year = 2016 var b B b.year = 2016 a.Greet() // Hello GolangUK 2016 b.Greet() // Welcome to GolangUK 2016 }
We have a type
A, with a field
year and a method
Greet. We have a second type,
B which embeds an
A, thus callers see
B‘s methods overlaid on
A‘s because
A is embedded, as a field, within
B, and
B can provide its own
Greet method, obscuring that of
A.
But embedding isn’t just for methods, it also provides access to an embedded type’s fields. As you see, because both
A and
B are defined in the same package,
B can access
A‘s private
year field as if it were declared inside
B.
So embedding is a powerful tool which allows Go’s types to be open for extension.
package main type Cat struct { Name string } func (c Cat) Legs() int { return 4 } func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n", c.Legs()) } type OctoCat struct { Cat } func (o OctoCat) Legs() int { return 5 } func main() { var octo OctoCat fmt.Println(octo.Legs()) // 5 octo.PrintLegs() // I have 4 legs }
In this example we have a
Cat type, which can count its number of legs with its
Legs method. We embed this
Cat type into a new type, an
OctoCat, and declare that
Octocats have five legs. However, although
OctoCat defines its own
Legs method, which returns 5, when the
PrintLegs method is invoked, it returns 4.
This is because
PrintLegs is defined on the
Cat type. It takes a
Cat as its receiver, and so it dispatches to
Cat‘s
Legs method.
Cat has no knowledge of the type it has been embedded into, so its method set cannot be altered by embedding.
Thus, we can say that Go’s types, while being open for extension, are closed for modification.
In truth, methods in Go are little more than syntactic sugar around a function with a predeclared formal parameter, their receiver.
func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n", c.Legs()) } func PrintLegs(c Cat) { fmt.Printf("I have %d legs\n", c.Legs()) }
The receiver is exactly what you pass into it, the first parameter of the function, and because Go does not support function overloading,
OctoCats are not substitutable for regular
Cats. Which brings me to the next principle.
Liskov Substitution Principle
Coined by Barbara Liskov, the Liskov substitution principle states, roughly, that two types are substitutable if they exhibit behaviour such that the caller is unable to tell the difference.
In a class based language, Liskov’s substitution principle is commonly interpreted as a specification for an abstract base class with various concrete subtypes. But Go does not have classes, or inheritance, so substitution cannot be implemented in terms of an abstract class hierarchy.
Interfaces
Instead, substitution is the purview of Go’s interfaces. In Go, types are not required to nominate that they implement a particular interface, instead any type implements an interface simply provided it has methods whose signature matches the interface declaration.
We say that in Go, interfaces are satisfied implicitly, rather than explicitly, and this has a profound impact on how they are used within the language.
Well designed interfaces are more likely to be small interfaces; the prevailing idiom is an interface contains only a single method. It follows logically that small interfaces lead to simple implementations, because it is hard to do otherwise. Which leads to packages comprised of simple implementations connected by common behaviour.
io.Reader
type Reader interface { // Read reads up to len(buf) bytes into buf. Read(buf []byte) (n int, err error) }
Which brings me to
io.Reader, easily my favourite Go interface.
The io.Reader interface is very simple;
Read reads data into the supplied buffer, and returns to the caller the number of bytes that were read, and any error encountered during read. It seems simple but it’s very powerful.
Because
io.Reader‘s deal with anything that can be expressed as a stream of bytes, we can construct readers over just about anything; a constant string, a byte array, standard in, a network stream, a gzip’d tar file, the standard out of a command being executed remotely via ssh.
And all of these implementations are substitutable for one another because they fulfil the same simple contract.
So the Liskov substitution principle, applied to Go, could be summarised by this lovely aphorism from the late Jim Weirich.
Require no more, promise no less.
–Jim Weirich
And this is a great segue into the fourth SOLID principle.
Interface Segregation Principle
The fourth principle is the interface segregation principle, which reads:
Clients should not be forced to depend on methods they do not use.
–Robert C. Martin
In Go, the application of the interface segregation principle can refer to a process of isolating the behaviour required for a function to do its job. As a concrete example, say I’ve been given a task to write a function that persists a
Document structure to disk.
// Save writes the contents of doc to the file f. func Save(f *os.File, doc *Document) error
I could define this function, let’s call it
Save, which takes an
*os.File as the destination to write the supplied
Document. But this has a few problems.
The signature of
Save precludes the option to write the data to a network location. Assuming that network storage is likely to become requirement later, the signature of this function would have to change, impacting all its callers.
Because
Save operates directly with files on disk, it is unpleasant to test. To verify its operation, the test would have to read the contents of the file after being written. Additionally the test would have to ensure that
f was written to a temporary location and always removed afterwards.
*os.File also defines a lot of methods which are not relevant to
Save, like reading directories and checking to see if a path is a symlink. It would be useful if the signature of our
Save function could describe only the parts of
*os.File that were relevant.
What can we do about these problems?
// Save writes the contents of doc to the supplied ReadWriterCloser. func Save(rwc io.ReadWriteCloser, doc *Document) error
Using
io.ReadWriteCloser we can apply the Interface Segregation Principle to redefine
Save to take an interface that describes more general file-shaped things.
With this change, any type that implements the
io.ReadWriteCloser interface can be substituted for the previous
*os.File. This makes
Save both broader in its application, and clarifies to the caller of
Save which methods of the
*os.File type are relevant to its operation.
As the author of
Save I no longer have the option to call those unrelated methods on
*os.File as it is hidden behind the
io.ReadWriteCloser interface. But we can take the interface segregation principle a bit further.
Firstly, it is unlikely that if
Save follows the single responsibility principle, it will read the file it just wrote to verify its contents–that should be responsibility of another piece of code. So we can narrow the specification for the interface we pass to
Save to just writing and closing.
// Save writes the contents of doc to the supplied WriteCloser. func Save(wc io.WriteCloser, doc *Document) error
Secondly, by providing
Save with a mechanism to close its stream, which we inherited in a desire to make it look like a file shaped thing, this raises the question of under what circumstances will
wc be closed. Possibly
Save will call
Close unconditionally, or perhaps
Close will be called in the case of success.
This presents a problem for the caller of
Save as it may want to write additional data to the stream after the document is written.
type NopCloser struct { io.Writer } // Close has no effect on the underlying writer. func (c *NopCloser) Close() error { return nil }
A crude solution would be to define a new type which embeds an
io.Writer and overrides the
Close method, preventing
Save from closing the underlying stream.
But this would probably be a violation of the Liskov Substitution Principle, as
NopCloser doesn’t actually close anything.
// Save writes the contents of doc to the supplied Writer. func Save(w io.Writer, doc *Document) error
A better solution would be to redefine
Save to take only an
io.Writer, stripping it completely of the responsibility to do anything but write data to a stream.
By applying the interface segregation principle to our
Save function, the results has simultaneously been a function which is the most specific in terms of its requirements–it only needs a thing that is writable–and the most general in its function, we can now use
Save to save our data to anything which implements
io.Writer.
A great rule of thumb for Go is accept interfaces, return structs.
–Jack Lindamood
Stepping back a few paces, this quote is an interesting meme that has been percolating in the Go zeitgeist over the last few years.
This tweet sized version lacks nuance, and this is not Jack’s fault, but I think it represents one of the first piece of defensible Go design lore.
Dependency Inversion Principle
The final SOLID principle is the dependency inversion principle, which states:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
–Robert C. Martin
But what does dependency inversion mean, in practice, for Go programmers?
If you’ve applied all the principles we’ve talked about up to this point then your code should already be factored into discrete packages, each with a single well defined responsibility or purpose. Your code should describe its dependencies in terms of interfaces, and those interfaces should be factored to describe only the behaviour those functions require. In other words, there shouldn’t be much left to do.
So what I think Martin is talking about here, certainly the context of Go, is the structure of your import graph.
In Go, your import graph must be acyclic. A failure to respect this acyclic requirement is grounds for a compilation failure, but more gravely represents a serious error in design.
All things being equal the import graph of a well designed Go program should be a wide, and relatively flat, rather than tall and narrow. If you have a package whose functions cannot operate without enlisting the aid of another package, that is perhaps a sign that code is not well factored along package boundaries.
The dependency inversion principle encourages you to push the responsibility for the specifics, as high as possible up the import graph, to your
main package or top level handler, leaving the lower level code to deal with abstractions–interfaces.
SOLID Go Design
To recap, when applied to Go, each of the SOLID principles are powerful statements about design, but taken together they have a central theme.
The Single Responsibility Principle encourages you to structure the functions, types, and methods into packages that exhibit natural cohesion; the types belong together, the functions serve a single purpose.
The Open / Closed Principle encourages you to compose simple types into more complex ones using embedding.
The Liskov Substitution Principle encourages you to express the dependencies between your packages in terms of interfaces, not concrete types. By defining small interfaces, we can be more confident that implementations will faithfully satisfy their contract.
The Interface Substitution Principle takes that idea further and encourages you to define functions and methods that depend only on the behaviour that they need. If your function only requires a parameter of an interface type with a single method, then it is more likely that this function has only one responsibility.
The Dependency Inversion Principle encourages you move the knowledge of the things your package depends on from compile time–in Go we see this with a reduction in the number of
import statements used by a particular package–to run time.
If you were to summarise this talk it would probably be; interfaces let you apply the SOLID principles to Go programs.
Because interfaces let Go programmers describe what their package provides–not how it does it. This is all just another way of saying “decoupling”, which is indeed the goal, because software that is loosely coupled is software that is easier to change.
As Sandi Metz notes:
Design is the art of arranging code that needs to work today, and to be easy to change forever.
–Sandi Metz
Because if Go is going to be a language that companies invest in for the long term, the maintenance of Go programs, the ease of which they can change, will be a key factor in their decision.
Coda
In closing, let’s return to the question I opened this talk with; How many Go programmers are there in the world? This is my guess:
By 2020, there will be 500,000 Go developers.
-me
What will half a million Go programmers do with their time? Well, obviously, they’ll write a lot of Go code and, if we’re being honest, not all of it will be good, and some will be quite bad.
Please understand that I do not say this to be cruel, but, every one of you in this room with experience with development in other languages–the languages you came from, to Go–knows from your own experience that there is an element of truth to this prediction.
Within C++, there is a much smaller and cleaner language struggling to get out.
–Bjarne Stroustrup, The Design and Evolution of C++
The opportunity for all Go programmers to make our language a success hinges directly on our collective ability to not make such a mess of things that people start to talk about Go the way that they joke about C++ today.
The narrative that derides other languages for being bloated, verbose, and overcomplicated, could one day well be turned upon Go, and I don’t want to see this happen, so I have a request.
Go programmers need to start talking less about frameworks, and start talking more about design. We need to stop focusing on performance at all cost, and focus instead on reuse at all cost.
What I want to see is people talking about how to use the language we have today, whatever its choices and limitations, to design solutions and to solve real problems.
What I want to hear is people talking about how to design Go programs in a way that is well engineered, decoupled, reusable, and above all responsive to change.
… one more thing
Now, it’s great that so many of you are here today to hear from the great lineup of speakers, but the reality is that no matter how large this conference grows, compared to the number of people who will use Go during its lifetime, we’re just a tiny fraction.
So we need to tell the rest of the world how good software should be written. Good software, composable software, software that is amenable to change, and show them how to do it, using Go. And this starts with you.
I want you to start talking about design, maybe use some of the ideas I presented here, hopefully you’ll do your own research, and apply those ideas to your projects. Then I want you to:
- Write a blog post about it.
- Teach a workshop about it what you did.
- Write a book about what you learnt.
- And come back to this conference next year and give a talk about what you achieved.
Because by doing these things we can build a culture of Go developers who care about programs that are designed to last.
Thank you. | https://dave.cheney.net/2016/08 | CC-MAIN-2018-09 | refinedweb | 3,794 | 62.17 |
1.15 anton.14 anton 88: require search-order.fs.1 anton 107: \ the: 1.5 anton 114: slowvoc @ 115: slowvoc on \ we want a linked list for the vocabulary locals 1.1 anton 116: vocabulary locals \ this contains the local variables 1.3 anton 117: ' locals >body ' locals-list >body ! 1.5 anton 118: slowvoc ! 1.1 anton 1.3 anton 128: aligned dup adjust-locals-size ; 1.1 anton 129: 130: : alignlp-f ( n1 -- n2 ) 1.3 anton 131: faligned dup adjust-locals-size ; 1.1 anton -- ) 1.3 anton 156: -1 chars compile-lp+! 1.1 anton 157: locals-size @ swap ! 158: postpone lp@ postpone c! ; 159: 160: : create-local ( " name" -- a-addr ) 1.9 anton 161: \ defines the local "name"; the offset of the local shall be 162: \ stored in a-addr 1.1 anton 163: create 1.12 anton 164: immediate restrict 1.1 anton 165: here 0 , ( place for the offset ) ; 166: 1.3 anton 167: : lp-offset ( n1 -- n2 ) 168: \ converts the offset from the frame start to an offset from lp and 169: \ i.e., the address of the local is lp+locals_size-offset 170: locals-size @ swap - ; 171: 1.1 anton 172: : lp-offset, ( n -- ) 173: \ converts the offset from the frame start to an offset from lp and 174: \ adds it as inline argument to a preceding locals primitive 1.3 anton 175: lp-offset , ; 1.1 anton 176: 177: vocabulary locals-types \ this contains all the type specifyers, -- and } 178: locals-types definitions 179: 1.14 anton 180: : W: ( "name" -- a-addr xt ) \ gforth w-colon 181: create-local 1.1 anton 182: \ xt produces the appropriate locals pushing code when executed 183: ['] compile-pushlocal-w 184: does> ( Compilation: -- ) ( Run-time: -- w ) 185: \ compiles a local variable access 1.3 anton 186: @ lp-offset compile-@local ; 1.1 anton 187: 1.14 anton 188: : W^ ( "name" -- a-addr xt ) \ gforth w-caret 189: create-local 1.1 anton 190: ['] compile-pushlocal-w 191: does> ( Compilation: -- ) ( Run-time: -- w ) 192: postpone laddr# @ lp-offset, ; 193: 1.14 anton 194: : F: ( "name" -- a-addr xt ) \ gforth f-colon 195: create-local 1.1 anton 196: ['] compile-pushlocal-f 197: does> ( Compilation: -- ) ( Run-time: -- w ) 1.3 anton 198: @ lp-offset compile-f@local ; 1.1 anton 199: 1.14 anton 200: : F^ ( "name" -- a-addr xt ) \ gforth f-caret 201: create-local 1.1 anton 202: ['] compile-pushlocal-f 203: does> ( Compilation: -- ) ( Run-time: -- w ) 204: postpone laddr# @ lp-offset, ; 205: 1.14 anton 206: : D: ( "name" -- a-addr xt ) \ gforth d-colon 207: create-local 1.1 anton 208: ['] compile-pushlocal-d 209: does> ( Compilation: -- ) ( Run-time: -- w ) 210: postpone laddr# @ lp-offset, postpone 2@ ; 211: 1.14 anton 212: : D^ ( "name" -- a-addr xt ) \ gforth d-caret 213: create-local 1.1 anton 214: ['] compile-pushlocal-d 215: does> ( Compilation: -- ) ( Run-time: -- w ) 216: postpone laddr# @ lp-offset, ; 217: 1.14 anton 218: : C: ( "name" -- a-addr xt ) \ gforth c-colon 219: create-local 1.1 anton 220: ['] compile-pushlocal-c 221: does> ( Compilation: -- ) ( Run-time: -- w ) 222: postpone laddr# @ lp-offset, postpone c@ ; 223: 1.14 anton 224: : C^ ( "name" -- a-addr xt ) \ gforth c-caret 225: create-local 1.1 anton 1.3 anton 249: drop nextname 250: ['] W: >name ; 1.1 anton 1.14 anton 265: : { ( -- addr wid 0 ) \ gforth open-brace 1.1 anton 266: dp old-dpp ! 267: locals-dp dpp ! 268: also new-locals 269: also get-current locals definitions locals-types 270: 0 TO locals-wordlist 271: 0 postpone [ ; immediate 272: 273: locals-types definitions 274: 1.14 anton 275: : } ( addr wid 0 a-addr1 xt1 ... -- ) \ gforth close-brace 1.1 anton 276: \ ends locals definitions 277: ] old-dpp @ dpp ! 278: begin 279: dup 280: while 281: execute 282: repeat 283: drop 284: locals-size @ alignlp-f locals-size ! \ the strictest alignment 285: set-current 286: previous previous 287: locals-list TO locals-wordlist ; 288: 1.14 anton 289: : -- ( addr wid 0 ... -- ) \ gforth dash-dash 1.1 anton 290: } 1.9 anton 291: [char] } parse 2drop ; 1.1 anton: 1.3 anton 383: \ Implementation: migrated to kernal.fs 1.1 anton: 1.3 anton 398: \ explicit scoping 1.1 anton 399: 1.14 anton 400: : scope ( compilation -- scope ; run-time -- ) \ gforth 1.3 anton 401: cs-push-part scopestart ; immediate 402: 1.14 anton 403: : endscope ( compilation scope -- ; run-time -- ) \ gforth 1.3 anton 404: scope? 1.1 anton 405: drop 1.3 anton 406: locals-list @ common-list 407: dup list-size adjust-locals-size 408: locals-list ! ; immediate 1.1 anton 409: 1.3 anton 410: \ adapt the hooks 1.1 anton 411: 1.3 anton 412: : locals-:-hook ( sys -- sys addr xt n ) 413: \ addr is the nfa of the defined word, xt its xt 1.1 anton 414: DEFERS :-hook 415: last @ lastcfa @ 416: clear-leave-stack 417: 0 locals-size ! 418: locals-buffer locals-dp ! 1.3 anton 419: 0 locals-list ! 420: dead-code off 421: defstart ; 1.1 anton 422: 1.3 anton 423: : locals-;-hook ( sys addr xt sys -- sys ) 424: def? 1.1 anton 425: 0 TO locals-wordlist 1.3 anton 426: 0 adjust-locals-size ( not every def ends with an exit ) 1.1 anton: 1.14 anton 476: : (local) ( addr u -- ) \ local paren-local-paren 1.3 anton 477: \ a little space-inefficient, but well deserved ;-) 478: \ In exchange, there are no restrictions whatsoever on using (local) 1.4 anton 479: \ as long as you use it in a definition 1.3 anton 480: dup 481: if 482: nextname POSTPONE { [ also locals-types ] W: } [ previous ] 483: else 484: 2drop 485: endif ; 1.1 anton 486: 1.4 anton [ ' bits 1.13 anton 502: swap [ 1 invert ] literal and does-code! 1.4 anton 503: else 504: code-address! 505: then ; 506: 507: \ !! untested 1.14 anton 508: : TO ( c|w|d|r "name" -- ) \ core-ext,local 1.4 anton 509: \ !! state smart 510: 0 0 0. 0.0e0 { c: clocal w: wlocal d: dlocal f: flocal } 511: ' dup >definer 512: state @ 513: if 514: case 515: [ ' locals-wordlist >definer ] literal \ value 516: OF >body POSTPONE Aliteral POSTPONE ! ENDOF 517: [ ' clocal >definer ] literal 518: OF POSTPONE laddr# >body @ lp-offset, POSTPONE c! ENDOF 519: [ ' wlocal >definer ] literal 520: OF POSTPONE laddr# >body @ lp-offset, POSTPONE ! ENDOF 521: [ ' dlocal >definer ] literal 522: OF POSTPONE laddr# >body @ lp-offset, POSTPONE d! ENDOF 523: [ ' flocal >definer ] literal 524: OF POSTPONE laddr# >body @ lp-offset, POSTPONE f! ENDOF 1.11 anton 525: -&32 throw 1.4 anton 526: endcase 527: else 528: [ ' locals-wordlist >definer ] literal = 529: if 530: >body ! 531: else 1.11 anton 532: -&32 throw 1.4 anton 533: endif 534: endif ; immediate 1.1 anton 535: 1.6 pazsan 536: : locals| 1.14 anton 537: \ don't use 'locals|'! use '{'! A portable and free '{' 538: \ implementation is anslocals.fs 1.8 anton 539: BEGIN 540: name 2dup s" |" compare 0<> 541: WHILE 542: (local) 543: REPEAT 1.14 anton 544: drop 0 (local) ; immediate restrict | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/glocals.fs?annotate=1.16;sortby=rev;only_with_tag=MAIN | CC-MAIN-2020-45 | refinedweb | 1,184 | 62.75 |
Detailed Guide to creating your own Create react App template
Tl,dr: Since December '19 Create React App (also known as CRA) allows you to write custom templates. That can help you to quickly create projects with your preferred stack. Templates can be published as npm modules and are used to create a new React project.
Motivation
CRA (Create React App) is a tool from Facebook helping you building modern React applications, without having to worry about configuring the dev environment. Up until recently, they created a small 'Hello World' like application to help getting you started. You then had to install and integrate most of the libraries you wanted to use. Think of adding a CSS-in-JS styling library, your State Management solution and the like.
Nowadays they added the possibility to write and use your own custom template. This allows you, to bootstrap your CRA project with exactly the stack you prefer and go from there. CRA templates can be used with
npx create-react-app your-app --template your-published-template.
How can we write our own template? Take a look at the two official templates in their repo for inspiration: CRA template and CRA template typescript.
The official documentation is still kind of barebones, but will give you a good overview.
Keep reading, if you want a more detailed writeup, of how to create your custom Create React App template.
Start building your next React project. Photo by 贝莉儿 DANIST on Unsplash.
What's needed
A custom Create React App template is a module on npm which has to use a certain folder structure:
your-app/ README.md template.json package.json template/ README.md gitignore public/ index.html src/ index.js
The
template.json file contains the dependencies as well as potential new scripts for the created projects. The
/template folder basically becomes the created application, it will be copied during the initialisation phase of Create React App.
Custom templates also have to follow a certain naming convention, they have to use the format
cra-template-[your-custom-template]. This comes in the
package.json. Quite long? Luckily, we can omit the
cra-template prefix and just use the
your-custom-template name in the CRA command, like in
npx create-react-app your-app --template your-custom-template.
Did you note the missing dot before the
template/gitignore file? This is on purpose, the dot will be added by CRA. They also switch all occurrences of
npm run with
yarn in your scripts and Readme, if you are using yarn. Good to know, right?
Also note that you can add more files and dependencies to your template project as you wish. Keep in mind, that everything in
/template will be part of the created project, everything else not.
Create your new template
Alright, time to see how to write our own template.
To start writing a custom Create React App template I find it easiest to bootstrap it with CRA itself. So let's
npx create-react-app cra-template-your-custom-template and CRA will do its' thing (substitute your-custom-template with however you want to name your project). The default template will be used.
Now the fun part begins. You can remove stuff you never use (like the rotating logo) and add all your preferred libs, as you would in a plain React app. Want a router? A CSS-in-JS lib? A state management tool? Animation? Something? Let's install whatever you want and import it in your application. My recommendation is to do that in the
src folder. Doing that, you can test and run your app normally with
npm run test and
npm run start. The goal is to get your project to the point you would love to start your future React projects at.
As soon as you consider your project to be at a nice 'starting point', you have to make it a template. For that create the
template.json file at your project root:
{ "dependencies": { "styled-components": "^4.4.1" }, "scripts": { "custom-start": "npm run start" } }
Copy all dependencies you need from your
package.json into the dependencies field, and all custom scripts into the scripts field. All the dependencies here will be installed on the bootstrapped projects.
react,
react-dom and
react-scripts are CRAs' default dependencies, you don't have to include them. Right now, devDependencies are not supported. If you don't have any new dependencies or scripts you can omit the corresponding block. BMake sure you add at least an empty
template.json file (with content
{}).
Then, create the
/template folder and copy your
/src and
/public folder into it, as well as the
.gitignore (and remove the dot from
gitignore in the template folder). You should also consider adding a
/template/README.md, this will become the initial README of the created projects.
Lastly, we have to make some changes to our
package.json file. At the very least, make sure that
name starts with
cra-template-, remove the
private field and add
"main": "template.json",. Without these, Create React Apps' template creation will fail. You may also consider adding more fields for a nice npm package, like
author,
repository,
description etc.
Publishing to npm is a topic of its own. To keep the scope small: After registering at npm and authorising on the CLI, you could publish the project with
npm publish --access public.
Wow, congratulations, you should now have created and published a Create React App custom template. Bootstrap a new React application with
npx create-react-app your-app --template your-custom-template.
Enjoy.
Tips
Create React App can use a local template (on your filesystem). This is useful for development, or if you don't want to publish. Use
npx create-react-app your-app --template file:. in your template root folder.
You can also use npm scopes to namespace your template. Then you have to prepend your package name with your scope
@your-scope/cra-template-your-custom-template. You can still omit
cra-template from the Create React App command like in
npx create-react-app your-app --template @your-scope/your-custom-template.
Hope this helps you to create your own CRA template. Feel free to let me know about your templates or if you get stuck along the way. Tweet at me or leave a comment.
First published as Write your own Create React App template.
Discussion (0) | https://dev.to/kriswep/detailed-guide-to-creating-your-own-create-react-app-template-3djd | CC-MAIN-2021-21 | refinedweb | 1,077 | 67.15 |
Back to the Index Page
The Adventures
of Timothy
Peacock by Daniel P. Thompson
Esquire; or,
Freemasonry
Practically
PREFACE.
There may be such a thing as conferring on folly a sort of
dignity— nay, even a dangerous importance, by treating it too
seriously. There may also be such a thing as pursuing vice and crime
so far with one unvaried cry of denunciation as to give them a
temporary advantage by the more easily eluding the pursuit, or by
adroitly crying, "martyr," "persecution," &c., so far to enlist
the sympathies of the spectator, who has thus seen but one of the
aspects of "the frightful mien," as to induce him to say, "forbear
— enough!"
If the following pages shall succeed in presenting the various and
motley features of Freemasonry in their proper light—show where it
is most effectual to laugh, where to censure and denounce, and where
to (not praise—that word would be a white sheep in such fellowship,)
where to let it alone—the aims of the author will have been
accomplished. His views of that extraordinary, strangely compounded
and certainly very powerful institution, are not dissimilar to those
of many others at the present day; but he may differ from them in the
manner in which he believes it most expedient and politic to serve up
for the public many of the materials of which it is composed.
THE AUTHOR.
April, 1835.
Acknowledgment
TO HIS INEFFABLE POTENCY, -
EDWARD LIVINGSTON,
General Grand High Priest of the General Grand Royal Arch
Chapter of the Celestial Canopy of the United States of America:
This feeble attempt at a practical illustration of the Beauties of
Freemasonry is humbly dedicated, as a suitable tribute to the Man and
the Mason, whose matchless wisdom, so admirably adapted to the genius
of that institution of which he is the exalted head in this thus
honored country, has successfully foiled its most formidable
assailants by the unanswerable arguments of his Dignified Silence
.
By THE AUTHOR.
Anno Lucis, 5835.
CHAPTER I.
"Come let us prepare,We brethren that are."—
Our Hero, the present Thrice Illustrious TIMOTHY PEACOCK, Esquire,
was born in a small village in the interior of Rhode Island. His
father and mother were deserters from a British fleet. They had,
however, once seen brighter days than this circumstance might seem to
imply; for Mr. Peacock, at one time, had the honor to write himself
Chief Butcher to His Majesty George III., London. Mrs. Peacock, before
she united her destinies to those of the honored father of our
hero—that union which was to bestow upon the New World the brightest
masonic star that ever illumined the wondering hemisphere of the
West—Mrs. Peacock, I say, was called the Billingsgate Beauty. They
very mackerels she sold might shrink from a comparison with the
plumpness of her person, and the claws of her own lobsters were
nothing in redness to the vermillion of her cheeks. She made, as may
well be supposed, sad devastation among the hearts of the gallant
young fish-mongers.—Oystermen, clam-cryers, carpers, shrimpers and
all—all fell before the scorching blaze of her optical artillery.
But she would have mercy on none of them; she aspired to a higher
destiny; and her laudable ambition was rewarded with the most
flattering success; for she soon saw herself the distinguished lady of
Peletiah Peacock, Chief Butcher to His Majesty. But how she became
the envy of many a dashing butcheress, by the splendor of her
appearance,—how her husband flourished, and how he fell, and was
driven from the stalls of royalty,—how he took leave of the baffled
bum-bailiffs of his native city, enlisted on board a man of war, and
sailed for America, with permission for his loving rib to accompany
him,—how they both deserted at a New England port, at which the
vessel had touched, and were housed in a friendly hay-stack in the
neighborhood till the search was over and vessel departed,—and,
finally, how they travelled over land till they reached the smiling
village where they found their abiding domicil, belongs, perhaps, to
the literati of Britain to relate. They have, and of right ought to
have, the first claim on the achievements of their countrymen with
which to fill the bright pages of their country's biography; and to
them then let us graciously yield the honor of enshrining his memory
with those of their Reverend `Fiddlers' and truth-telling
`Trollopes.' Far be it from me to rob them of the glory of this
theme.—Mine is a different object; and I shall mention no more of
the deeds of the father than I conceive necessary to elucidate the
history of the son, whose brilliant career I have attempted, with
trembling diffidence, to sketch in the following unworthy pages.
The place where the Peacocks had fixed their permanent residence
was, as before intimated, a small village in the state of Rhode
Island. This village, I beg leave to introduce to the reader, under
the significant appellation of Mugwump, a word which being duly
interpreted means (unless my etymology is sadly at fault) much the
same as Mah-hah-bone—which last, after a most laborious and
learned research, I have fortunately discovered to signify nothing
in particular; though, at the same time, I am perfectly aware
that both these terms are used at the present day, vulgarly and
masonically, as synonymous with greatness and strength. But to our
story: Mr. Peacock had no sooner become fairly settled than he began
to devise the ways and means for a future independence; and such was
his assiduity to business, and such his financial wisdom derived from
lessons of sad experience in the old world, that his exertions in the
new soon began to count brightly; and the third anniversary of his
entry into Mugwump found him the owner of a snug little establishment
devoted to public entertainment, under the sign of a bull-dog, which
he lucklessly selected in memory of a faithful animal of that species
that had once backed a writ for him, that is, had given him bail by
holding back a sheriff by the tail of the coat till his master could
shift for himself—I say lucklessly, for the malicious and unfriendly
took occasion from this circumstance to christen Mr. Peacock's inn by
the name of the Doggery; and hence unjustly sprung that epithet
now extensively applied to low grog-shops, sluttish taverns, &c. In
this situation, however, notwithstanding these attempted
disparagements of the envious, Mr. Peacock soon had thriven to such a
degree as to be able to bid defiance to all the constables and
sheriffs this side of London.—Indeed he now began to be reckoned a
man of some pecuniary consequence. This was indeed a source of much
pride and gratification to Mrs. Peacock, who began, both by precept
and example, to enlighten her ignorant neighbors in matters of London
gentility; but was it sufficient to satisfy the mind of one of Mr.
Peacock's endowments—of one whose honored name and avocation was
once coupled with the Majesty of England? By no means!—He wished
only a competence; and this attained, his ambition began to soar to
higher honors than the mere possession of sordid lucre, in this land
of republican simplicity, will bestow. But how to gain these honors
and arrive at his former dignity of station was a subject that often
sadly puzzled his mind. The people of his adopted country entertained
such singular notions respecting the qualifications they required of
those who should ask promotion at their hands, that he soon perceived
that any attempt to gain their civil distinctions would be fruitless,
and he turned his attention to a different object. He had heard much,
both in this and his own country, of the sublime order of
Freemasonry—of its titles, its grades, its honors, its talismanic
powers in ensuring escapes from pursuing enemies, its advantages in
putting its possessors directly into the highway of office and power,
and, above all, its wonderful secret, which the brotherhood had so
often defied the whole world to discover. "Ah! this must be
something," said he, as he pondered on the subject, "this is
something that these leveling Yankees have not yet laid their hands
on.—This looks indeed a little like old England." In short his
curiosity became awakened, his ambition fired to possess the key to
this labyrinth of mystery, this great secret treasury of honors and
advantages, and he firmly resolved to become a member of this
wonderful fraternity. With this determination he applied for admission
into a lodge in a neighboring village, it being the only one then in
the vicinity. But here alas! his commendable ambition was doomed to
suffer defeat and disappointment.—When the important day arrived on
which he expected to be initiated, great indeed was his mortification
and surprize to be informed that he could not be admitted, as "all
was not clear." "It is all very clear to me," replied Mr. Peacock,
after the first shock of his surprize was a little over, "it is all
very clear to me; but you are all most wilfully out of your wits I can
tell ye. I have led as honest a life, both in this country and
England, as the fattest of ye, and as to knuckling to a pack of scurvy dimecrats, I'll let ye know I sha'nt;—so, good bye, and be
d—d to ye!" After giving these aproned heralds of his defeat this
spirited reply, he went home to sleep off his indignation. Sleep
however could do but little towards assuaging so bitter a
disappointment; and the next day he set off to visit a neighboring
farmer, with whom he was intimate, for the purpose of unburdening his
troubled feelings. This person, who was called Bill Botherem,
on account of his propensity for hoaxing, (his real name being
William Botherworth) had been a sailor till about the age of twenty,
when, after having seen considerable of the world, and made something
handsome in several lucky ventures at sea, he relinquished that kind
of life, and purchasing a farm in the vicinity of Mugwump, settled
down, and now led a jolly life, keeping bachelor's hall to board
himself and his workmen. Mr. Peacock, who had contracted a sort of
confidential intimacy with Bill, because he could talk about London,
or because he had been a liberal customer, or both, having heard from
his own lips that he had been a Mason, though afterwards expelled for
some trick or other played off on a brother Mason—Mr. Peacock, I
say, considered that he would be the most suitable person to whom he
could communicate his difficulties, and at the same time the most
capable adviser in putting him in a way of overcoming them, and
accomplishing his still ardent desire of becoming a Mason. With this
purpose in view, he called on his merry friend, and, withdrawing him a
little from his workmen, he candidly related the whole story of his
troubles and wishes. Botherem listened to the tale of Mr. Peacock's
wrongs with deep attention—sympathized with him in his
disappointment, and bestowed many hearty curses on the stupidity of
those who could reject a man who would have been such an honor to
their society. And, after musing awhile, he told Mr. Peacock that he
should advise him not to go near the fellows any more, or make
application to any other lodge, but if he wished to become a Mason he
had better be initiated privately by some friendly Mason. "Privately!"
said Peacock, "I did not know it could be managed in that way." "O,
nothing easier," rejoined Botherem, (his eyes beginning to dance in
anticipation of the sport of such a process) "nothing easier, Mr.
Peacock—you may as well be taken in privately as publicly;
and when you have once received the secret by a private initiation, I
will venture to say you will be as wise as the best of them." Mr.
Peacock, overjoyed at this information, sprang up and exclaimed,
"Then, Bill, you shall be the man what shall do it, by the Lord
Harry!" Botherem, with some hesitation, consented to the proposition;
and it was soon arranged that the ceremony should be performed that
very evening at Botherem's house, where no women or other evesdroppers
or cowans would be about to pry into their proceedings. Botherem was
to send off his workmen and call in such masonic friends as he might
wish to assist him in the performance; and the candidate was to come
alone about dark, when every thing should be in readiness for the
ceremony. All things being thus settled, Mr. Peacock departed,
exulting in the thought that the wish nearest his heart was now so
near its accomplishment. When Botherem was left alone, he began to be
somewhat startled at his own project, lest it be productive of
serious consequences to himself should he really initiate the man into
the secrets of Masonry; for he well understood the fiery vengeance of
the fraternity in case of detection. But his desire to see so fine a
piece of sport, as he conceived this would be, at length prevailed
over his scruples, and he determined to proceed; varying, however, by
way of caution, the usual ceremonies of a regular initiation so far,
that while he gave the candidate the full spirit of Freemasonry, he
would keep from him so much of the letter as would exonerate him from
the charge of divulging the true secrets, which he believed to consist
of grips, pass-words, &c. By pursuing this course, he supposed he
should be doing ample justice to the candidate, while he could himself
escape with impunity, should the transaction ever reach the ears of
the fraternity,—a supposition, alas! in which the sequel well shows
how fatally he was mistaken.
After having digested his plan of operations, Botherem called his
men together, (having no notion of calling in other aid) and swearing
them to secrecy, revealed to them his whole scheme. Entering with
great spirit into the project of their leader, they went to work with
all their might to finish their tasks in time to make the necessary
preparations for the interesting occasion. As the nature of these
preparations will best be learned in a description of the ceremonies,
it will be needless here to detail them.
At the appointed hour, Mr. Peacock, with a heart beating high with
expectation, and fluttering at the thought of the lofty honors about
to be conferred upon him, made his appearance at the house where the
ceremonies were to be performed. A man, with a white birch bark mask
on his face, and an old dried sheep-skin apron tied round his waist,
and holding in his hands a pole into one end of which was fastened
part of an old scythe-blade, stood at the door officiating as Tyler;
and, hailing the approaching candidate, bade him wait at a distance
till all was ready for his reception. At length a loud voice within
the house was heard exclaiming— "Give a word and a blow, that the
workmen may know, There's one asks to be made a Freemason!" A heavy
blow from an axe or falling block, and a sharp report of a pistol
instantly followed, and a man, masked, and otherwise strangely
accoutred, soon issued from the door midst the smoke of gunpowder,
and, approaching the wondering candidate, took him by the hand and led
him into a dark room to prepare him for initiation. Here Botherem, as
Most Worshipful Master of the ceremonies, was immediately in
attendance.—"Deacon Dunderhead," said he, "place the candidate so
that his nose shall point due east, while I propound the usual
questions."—
"Do you sincerely desire to become a Mason?"
`To be sure—why, that is just what I come for, you know, Bill.'
"Call me Worshipful!" thundered the Master.
`Worshipful, then,' muttered the abashed candidate.
"Will you conform to all our ancient usages?" continued the master:
"Will you cheerfully submit yourself to our established and dignified
custom of blindfolding the candidate and stripping him even to the
nether garment?"
`Why, I should not much mind about your stopping my blinkers
awhile,' replied the candidate; `but as to being put under bare poles,
that's too bad, by a d—d sight, Mr. Worshipful!'
"Silence!" exclaimed the Master; "for as the sun riseth in the
east, and as a man sticketh an axe in a tree, so do I forbid all
profane language on this solemn occasion: will you conform to this our
indispensable regulation also?"
`Unless it comes too hot, Mr. Worshipful,' said the rebuked
candidate, `that and all the rest on't.'
"Deacon," said the Master, "prepare the candidate for the sublime
mysteries of Masonry, and let him take heed to curb his unruly member,
for if he swears during the ceremonies, it will be necessary to stop
and go over with every thing again." So saying, he left the room.
The candidate was now stripped to his shirt, blindfolded, and, to
guard against any rising of a refractory spirit, his hands strongly
tied behind him. Thus prepared, he was led to the door of the
initiating room, when, after the customary raps within and without, he
was admitted, and stationed on one side of the door. There the Master
and his men, all masked and duly aproned, stood arranged round the
room in a circle, some holding old tin pails, some brass kettles, some
loaded pistols, and one an old drum.
The Master now stepped forward and said, "Brother, you are now in
the sanctorum totororum of Solomon's temple, but you are not yet
invested with the secrets of Masonry, nor do I know whether you ever
will be, till I know how you withstand the amazing trials and dangers
that await you—trials, the like of which, none but our Grand
Master, Hiram Abiff, ever experienced." Saying this, he turned to the
man stationed as Warden at the south gate, and exclaimed,
"Now Jubelo! now Jubelo! Be ready with your first dread wo, Which
those who'd win must never shun,— So now for Number One!"
These words were no sooner uttered than whang! went an old
horse-pistol, followed by such a tremendous din from the rattling of
old tin pails, brass kettles, and drum, as made the house ring again,
and the poor candidate shook in every joint like a man in an ague fit.
All was soon still, however; and an open pan filled with hot embers,
with a grid-iron over it, was now placed on the floor; when four of
the acting brethren, taking the candidate by the arms and legs, held
him over the pan, and gradually lowered him down till his seat touched
the grid-iron, which in the mean while had become somewhat too warm
for parts of so sensitive a nature; for they no sooner came in contact
with the iron than the candidate floundered and leaped from the arms
of the brethren, exclaiming, "Zounds and fury! do ye want to scorch a
fellow's t'other end off? I will wait till h-ll is burnt down before
I'll be a Mason, if this is the way!" "The spell is broken," cried the
Master, "the candidate has uttered unseemly and profane language; and
the ceremony must be repeated.—It is necessary he should feel the
torture before he can be permitted to behold the glorious light of
Masonry." They then took the struggling candidate in hand again, and
by dint of coaxing, induced him to submit himself once more to the
fiery ordeal of masonic purification. But, alas! this attempt was
attended with no happier results than the other; for, on touching the
grid-iron, his old habit (I regret to say it) again beset him, and
bounding like a parched pea, he once more broke out into the most
unmasonic expressions. The ceremony of course had to be yet again
repeated; and it was not till the fourth trial that he was brought to
the use of such exclamations as were adjudged not inconsistent with
the rule adopted on the occasion. This part of the ceremony being
concluded, the candidate was put in motion on his journey round the
lodge-room; and when, as they approached the Warden at the west gate,
the Worshipful Master stepped forth and exclaimed,
"O Jubela! O Jubela! The man you wanted here survey— Approaching
for the second wo! So now for Number Two!"
In an instant two pistols were let off in rapid succession, and the
mingled din of pails, kettles, drum, and the shouts of the brethren
were still louder than before on the stunned ears of the affrighted
candidate, who at the same time received the usual blow from the
acting Jubela of the performance; nor was this all or the worst part
of Number Two, which he was doomed to encounter: For after the noise
had ceased, he was again taken in hand.—His last remaining garment
was now stripped off, and he was placed on his hands and knees on the
floor, with his rearwards pointed due west, to symbolize the winds,
doubtless, that after the deluge, wafted the glorious art westward,
till it at length reached our own favored hemisphere. As soon as the
candidate's position was duly adjusted in this manner, the Deacon,
stationed and prepared for the purpose, dashed a full pail of cold
water directly on the premises that had just suffered so cruelly from
an opposite element, (these being the parts for which Masonry is
supposed to entertain a particular predilection.) Starting from the
shock, the poor candidate leaped, howling like a shot mastiff, to the
wall, and gave vent to his feelings in some of those unmasonic
exclamations which had already cost him so much to subdue. This,
according to the rigid rules of the Worshipful Master, led to a
repetition of the watery wo, till the hapless victim of this mystic
deluge, sighing and gasping for breath like a drowning puppy, became
so subdued by the water-cooling process, that he most piteously begged
for mercy;—when the rule, though violated to the last drenching,
was graciously dispensed with. The candidate was then rubbed down with
a cloth, and dressed in all his clothes—still, however, remaining
blindfolded. He was then led up to the old drum, placed in the middle
of the floor to serve for an altar, when, being made to kneel beside
it, an old copy of Gulliver's Travels was duly placed under his hands
and properly adjusted on the drum-head: After which, he was made to
repeat, while the Worshipful Master administered, the following
obligation:
"You solemnly swear, that you will never divulge the mighty secret
which has been, and is about to be revealed to you. You swear without
equivocation, hesitation, mental reservation, or explanation, that you
will never tell, spell, sell, hint, print or squint it, nor the same
ever write, indict, or recite, whatever your plight, whether placed
under locks, put in the stocks, or reduced to starvation. In short,
you swear never to reveal these, the great mysteries of Masonry, which
are equalled only in truth and wisdom by the wonderful Book on which
you swear to preserve them. You sacredly and solemnly swear it—you
swear it singly, you swear it doubly and trebly—you swear it up hill
and down hill, forward and backward, slanting and perpendicular,
side-ways, end-ways, and all ways—you swear it by your eyes, nose,
mouth, ears, tongue, gizzard and grunnet,— yea, by every part,
piece, portion and parcel of your body, singed or unsinged, washed or
unwashed—you swear it by the sun, moon, stars, earth, fire, water,
snow, rain, hail, wind, storm, lightning and thunder.—All this, by
all these, you swear, under no less penalty than to be drawn, naked
and tail foremost, forty-nine times through dry crabtree fences—be
shut up a month in a den of skunks, hedgehogs and rattlesnakes, with
clam-shells and vinegar for your only food and drink—run fourteen
miles barefoot in January, and be tarred and feathered and kicked and
cowskinned from Mugwump to Passamaquoddy and back again. So help you
Nebuchadnezzar and St. Nicholas, and keep you steadfast in the same.
So mote it be—so mote it be. Amen."
After this oath was administered, the candidate was ordered to
rise, and proceed to the east gate of the temple, when the Master once
more proclaimed—
"O Jubelum! O Jubelum! The third and last wo now must come, Before
the light reveal'd can be! So now for Number Three!"
On which Jubelum, or the Warden of this station, who stood prepared
for the emergency, with an old saddle-pad in his uplifted hand, gave
the candidate such a blow on the side of the head, as sent him reeling
across the room; while at the same instant, whang! whang! bang! went
three pistols, with the old accompaniment of jangling instruments,
now tasked to their utmost for noise and racket, together with the
falling of blocks, kicking over of chairs, and the deafening cheers of
the company. The bandage had been snatched from the eyes of the
candidate in the confusion, and he now stood bewildered, stunned and
aghast amidst the tumult, staring wildly on the strange, masked
figures around him, scarcely knowing where he was, or which end he
stood on. But being of that happy temperament on which nothing less
than dry knocks and actual applications of fire and water make any
very alarming impressions, all of which being now over, he soon
recovered in a good degree his self-possession. The Master then
proceeded to instruct and lecture him as follows:
"Brother, I greet you: You are now a free and acceped Mason. You
have now received the principal mysteries of the first degrees of
Masonry. In your trials by fire and water, you represented in the one
case, Grand Master Lot, and in the other Grand Master Noah, who both
outlived the two devouring elements that respectively threatened
them, and were more honored than all the multitudes that perished by
the fire and the flood. And in the third wo you represented Old Adam,
who, as traditions known only to the craft inform us, was at first
only a shapeless mass of clay, which, becoming accidentally disengaged
from the top of a high hill, rolled down, and was thus reduced to
something like human shape, but was still senseless and dark, till,
like yourself in the last trial, it was knocked into the light of
existence by a blow from some unseen hand. But let me now instruct you
in some of the arts of our illustrious order. There are the square and
compass," he continued, producing a common iron square and compass.
"By the square you must square your actions towards your masonic
brethren—though as to all others, the d—l take the hindmost. By
this also you are taught to move squarely, or in right lines and
directly in all your comings and goings, except in going from a lodge
meeting, when the rule does not always apply. And here is the compass:
By this you are taught to divide out your favors to your brethren,
and draw such circles as shall endow them and them only for your
charities. By this also you are taught the art of making a new centre
with one foot of the compass, und thus drawing a new circle when the
old one fails to enclose the right number of friends, or otherwise
does not answer your purpose: This is called pricking anew.
These are the great emblems of Masonry, and they are full of wisdom
and profit, brother; for there is scarce an act which a Mason may
perform that cannot be satisfactorily measured and squared by them,
which could never be done perhaps by the rules of the vulgar.
"Now for the signs and tokens.—If you would wish to discover
whether any one is a Mason for the purpose of requiring his
assistance, you must bring your right hand to the rear, where you have
just received the mark of Masonry; and at the same time put the little
finger of your left hand in your mouth, and vice versa. This is
the sign by which one Mason may know another: Make this, and a
brother seeing it, is bound to help you, vote for you, and do what you
require. Thus you see, brother, the value and advantage of our
glorious art. And now, having finished my instructions, I pronounce
you a good, well-made, and worthy Mason."
The lectures being now finished, the lodge was closed, and spirits
and other refreshments brought in, when all hands, after saluting
brother Peacock with the most flattering greetings, sat down to the
cheer; and long and merrily did the joke and bottle pass in honor of
that memorable evening.
Not a little elated were the feelings of Mr. Peacock, when he awoke
the next morning, by the proud consciousness of his newly acquired
dignity. Though it must be confessed that these feelings were
subjected to no small draw-back, in consequence of a certain soreness
experienced about those parts which had been more immediately exposed
to the visitation of Masonic honors. But the skillful applications of
his loving partner soon relieved him of troubles of this kind, except
scars which remained as lasting mementoes of his honorable service. He
often spoke in praise of Masonry, and enlarged in admiration on its
mysterious sublimities, which he likened to the terrors of a thunder
storm, in which fire, water and thunder came mingling together in
awful grandeur. Nor was he less impressed with the opinion of the
advantages of the art. He was heard to say, that he would not take his
best horse for the secret. So highly indeed did he estimate the value
of this exalted mystery, that he firmly resolved that his expected
son should one day become a Mason.—His expected son! But that
important subject demands a new chapter.
CHAPTER II.
Fer opem, Lucina.
The 17th of April, 1790, was the day made memorable in the annals
of American Masonry, by the birth of our hero, Timothy Peacock. The
seal of future greatness having been stamped by destiny on the brow of
the infantile Timothy, it is no marvel, therefore, that many incidents
of a peculiarly singular and ominous character marked his birth and
childhood. The day on which he was born, being the very day that
terminated the earthly career of the illustrious Franklin, was of
itself a circumstance worthy of particular notice; and it operated
with much force on the astute mind of his doating father, who, being a
firm believer in the doctrine of transmigration of souls, had a deep
impression that the spirit of the departed philosopher had taken up
its residence in his infant son. Again, a very remarkable potato had
grown in Mr. Peacock's garden the previous season. This singular
vegetable, which had grown in the form of an accute triangle, or a
pair of open dividers, had been hung up in the cellar the fall before,
as nothing more than a mere natural curiosity; but the moment Mr.
Peacock cast his eyes upon it, a few days after the birth of Timothy,
he instantly became sensible that things of far deeper import were
involved in the formation of this mysterious production; and the
truth, with intuitive rapidity, at once flashed across his mind: It
was the well-known masonic emblem, the compass, and an undoubted omen
that his house was about to be honored with a human production that
was to become distinguished in the mysteries of that art thus
strikingly designated. But these conclusions of Mr. Peacock, as well
warranted as they were by that remarkable omen, were confirmed by a
fact that he conceived could admit of no cavil or speculation. The
child came into the world with the mark of a grid-iron clearly and
palpably impressed, and that too, on those very parts which he knew,
from experience, masonry particularly delighted to honor. I am aware
that there are many among the would-be medico-philosophers of the
present day, who would perhaps attribute the existence of this
striking mark upon the infant, to the imagination of the mother,
whose kind assiduities, as I have before intimated, had been put in
requisition a few months before, on the occasion of her husband's
initiation into the secrets of Masonsonry; but in reply to such
conceited opinionists, I need only observe, that facts can never be
outweighed by visionary speculations; and it was upon facts such as I
have related, that Mr. Peacock founded his prophetic belief that his
son was destined to future excellence, and that this excellence was to
be more especially conspicuous in the path of masonic honors. Nor were
the signs of future intellect at all wanting still further to confirm
and justify his parents in the opinion they had formed of his
brilliant destiny. Such indeed was the child's mental precocity, that
new fears began to take possession of Mrs. Peacock, lest his
extraordinary forwardness might be the forerunner of premature decay.
But happily for the interests of Masonry, these maternal fears were
never realized. The boy grew apace in body and mind. Before he was
eight years old, he had nearly mastered all the intricacies of the
English alphabet; and such was his progress in natural history, as
illustrated in his horn book, that before he was ten he could readily
tell the picture of a hog from that of a horse without any prompting
or assistance whatever. Such wonders indeed may have since been
witnessed under the system of infant schools lately brought into
vogue, but it must be recollected that our hero at that day was
deprived of the advantages of that incomparable method of hot-bed
instruction. Mrs. Peacock, when viewing this unparalelled improvement
of her darling son, would often heave a sigh of regret that she was
doomed to bring up a child of such promise in this publican
land, as she termed it, where he could never become a lord or a
lord's gentleman, or wear any of those great titles to which his
abilities would doubtless raise him in England. But Mr. Peacock was
wont to soothe her grief on these occasions by suggesting that
Timothy might, and unquestionably would, become a great Mason, and
thus acquire all the grand titles of this order, which was no doubt
introduced into this country as the only way of conferring titles and
distinctions in this land of ragamuffinous dimecrats.
It was reflections like these, probably, that operated on Mr.
Peacock about this time, and rendered him unusually anxious to advance
still further himself in the higher degrees of Masonry, in which, as
yet, he had made no other progress than that which we have already
described in the preceding chapter. Botherworth had been applied to
for this purpose, but that gentleman informed Mr. Peacock that he had
already imparted all that was useful or instructive in all the degrees
which he himself had taken, and that whoever wished for any more of
the mystery, must obtain it from a regular lodge in which it could
alone be conferred. Mr. Peacock accordingly made application to sundry
Masons to obtain their intercession with the lodge in his behalf, but
these applications, though backed by a frequent use of those signs and
tokens which Botherworth had told him were so omnipotent, were never
heeded, and all his attempts therefore to gratify his ambition in this
line of preferment were entirely fruitless. This was a source of
great mortification as well as of much perplexity to Mr. Peacock, who
could by no means satisfactorily account in his own mind for these
unexpected failures after having made so much progress in the art. He
sometimes began to entertain serious doubts whether he had been
properly initiated, and whether his masonry was of the legitimate
kind. And in this, perhaps, he may be joined by some of my masonic
readers. I cannot think, however, that these scruples of Mr. Peacock
were well-grounded: At least, I do not consider that he had reason to
complain of any injustice done him by the Worshipful Master, who
initiated him, in withholding any useful masonic knowledge; for if he
did not impart all those secrets, or perform in strictness all the
ceremonies usual on such occasions, he substituted as many others as
were a fair equivalent, and those too of a character which would not
derogate from the decency or dignity of a legitimate initiation. But
to return from this digression: Mr. Peacock finally gave up his doubts
respecting the genuineness of his masonry, and attributed his want of
success to the circumstance of his being a foreigner, which he
supposed was sufficient to awaken the envy and provoke the hostility
of even the fraternity in this land of titulary barrenness. This,
however, was a disability to which his son would not be subject, and
he concluded therefore to centre his hopes on Timothy for
distinguishing his family by the reflected honors of that illustrious
order. Accordingly he early endeavored to impress his young mind with
reverence to the institution, and for that purpose had a little apron
made for the boy, beautifully over-wrought with masonic emblems. His
dog was named Jubelo, his cat Jubela, and his pet-lamb Jubelum. And thus, by keeping these rudiments of mystic knowledge
continually before his youthful mind, those impressions were doubtless
implanted, to which may be attributed the subsequent direction of
mental energies that raised our hero to such a pinnacle of glory on
the ladder of Jacob.
But as it may not be interesting to the reader to follow my hero
through a minute detail of his various improvements to the completion
of his education, I shall pass lightly over this period of his life,
and content myself with observing that his progress in science,
literature, and all the various branches of knowledge which he
attempted, fully made good the promise of his childhood at the age
when, as before mentioned, he accomplished his abecedarian triumph.
It may be proper, however, here to notice one prevailing taste which
he early manifested in the course of his education: This was a strong
predilection for the study and exercise of the art of oratory, and
that part of it more especially which, seeking the most dignified and
sonorous expressions, constitutes what is called the Ciceronian flow.
So high, indeed, was the standard of his taste in this particular,
that he rarely condescended, when he attempted any thing like a
display of his powers, to use any words, (except the necessary
adjuncts and connectives) short of polysyllables.—And these, with
the intuitive quickness of genius, he at once seized upon and
appropriated to his use, selecting them from the great mass of those
undignified cumberers of our language, monosyllables, by the same rule
by which the acute farmer, in purchasing his scythe or his cauldron,
or by which, in selecting his seed potatoes from his ample bin, he is
accustomed to make choice of the largest and the longest. It was this
trait, probably, in the intellectual character of our hero—this
gift, so peculiarly adapted to give expression to the lofty dictums of
masonic philosophy, that contributed mainly in rearing him to that
eminence among the fraternity for which he was afterwards so
conspicuous.
But these juvenile years flew rapidly away, and time rolling on,
and bringing about many other events of moment to the world, brought
also our hero to the age of twenty-one,— that important period which
so often gives a turn to our destinics for life. It did so to Timothy.
Mr. Peacock, who had long deliberated on the course of life most
advantageous for his son to pursue, at last concluded, as he had no
employment suitable for one of his genius at home, to send him abroad
to seek his fortune. And although he could furnish but a small
allowance of the needful for such an enterprize, his means having been
sadly impaired of late years, not only in the education of Timothy,
who had been sent one quarter to a neighboring academy by way of
adding the finishing polish to his acquirements, but by the heavy
drafts of Mrs. Peacock on the bar-box of the Doggery for the support
of her show of the family dignity, yet he had little doubt but
Timothy's talents and education would command for him both emolument
and honor. This course having been once settled and confirmed by all
parties in interest, arrangements were soon completed for his
departure. The important day fixed on for this purpose at length
arrived; and our hero having buckled on his pack for his pedestrian
excursion, went to receive the adieus and blessings of his parents
before leaving their kind roof for the broad theatre of the world,
when Mr. Peacock, with the characteristic frankness of the high-minded
English, thus addressed him:
"As you are now about to go abroad into the world, in the first
place, remember, my son, that all men are scoundrels by nature, and
especially in this country of dogs and dimecrats. But you have
an Englishman's blood beneath your hide, which should make you hold up
your head in any country. But blood, I know, won't do every thing for
you without tallow; and as I have but little of the solid lucre to
give you, why, you must cut and carve out a fortune for yourself. They
will tell you that this rippublercan government is the best in
the world; but they lie as fast as a dog will trot, except the fast
trotting dogs. I see nothing here that compares with England, but
masonry, which you must join as soon as you get settled, as I have
often told you; then you will have titles that the dimecrats
can't get away from you, do what they will. Then go, my son, and
become a great man, and do something in the world that will make your
ancestors proud of you till the last day of eternity, so mote it be,
amen and good by to ye."
CHAPTER III.
"'Tis a rough land of rock, and stone, and tree,Where breathes no castled lord nor cabined slave;Where thoughts, and hands, and tongues are free,And friends will find a welcome—foes a grave."
It was a pleasant morning in the month of May, when our hero
shouldered his well-stored knapsack, and, with the blessings of his
father and mother on his head, and their meagre outfit in his pocket,
went forth into the wide world to seek his fortune wherever he might
find it.
Such was the obscure and lowly beginning of the renowned hero of
Mugwump!—Such the inauspicious and rayless rising of that masonic
star which was destined soon to mount the mystic zenith, and irradiate
the whole canopy of America with its peerless effulgence! But not
wishing to anticipate his subsequent distinction, or waste words in
bestowing that panegyric which a bare recital of his deeds cannot but
sufficiently proclaim, I shall endeavor to follow my hero through the
bright mazes of his eventful career, giving an unvarnished narration
of his exploits, and leaving them to speak their own praise and
receive from an unbiassed posterity, if not from this perverse and
unmasonic generation, the meed of unperishable honor.
Steering his course westward, Timothy arrived at the end of his
first day's walk at a little village within the borders of
Massachusetts. Here he put up at a respectable looking tavern for the
night. After a good substantial supper had somewhat settled the
inquietudes of the inner man, he began to cast about him for
companionship; and hearing those who came in address the landlord by
the various titles of 'Squire, Colonel, &c., and concluding therefore
that the man must be the principal personage of the village, he
determined to have some conversation with him, and this for two
reasons,—first, because he wished to make enquiries respecting the
road to the State of New York, to which it had been settled he should
proceed as a place well suited to give full scope to his splendid
talents, and, secondly, because he thought it doing the landlord
injustice to suffer him to remain any longer in ignorance of the
great Genius with whose presence his house was now honored. He
therefore opened the conversation in a manner which he deemed suitable
to the occasion.—
"Landlord," said he, "comprehending you to be a man of superlative
exactitude, I take the present opportunity for making a few nocturnal
enquiries."
`Oh, yes; yes, Sir,' replied the landlord, with a bow at every
repetition; `yes, Sir, I thank you,—may ben't, however, I don't
exactly understand your tarms; but I'll answer your enquiries in the
shake of a sheep's-tail.'
"I am now," rejoined the former, "meandering my longitude to the
great State of New-York, where I contemplate the lucid occupation of
juvenile instruction, or some other political aggrandizement, and I
would more explicitly direct my enquiries respecting the best road to
that sequestered dominion."
`Oh, yes, yes Sir, I thank you,' said the other— speaking of
political matters—I have had some experience in that line, and about
the road too; why, let me see—it is just four year agone coming
June, since I went representative to the General Court in
Boston.—They would make me go to the Legislature, you see.—Well,
my speech on the Road Bill of that session as to the best rout to
New-York; but may ben't you havn't read my speech.—Well, no
matter.—But, my friend, don't you miss it to go to New-York? Now
I'll tell you jest what I would do: I would go right to Old Varmount
at once.—They are all desput ignerant folks there.—They must want
a man of your larnen shockingly I guess.—Now spose you jest think
on't a little.'
"Should you advise me then," observed Timothy, happy in perceiving
his talents were beginning to be appreciated by the landlord, "should
you advise me to concentrate to that dispensation?"
`Go there, do you mean?' replied the polished ex-representative—
`why, to be sure I should.—These poor out-of-the-world people must
be dreadfully sunk. You wouldn't find any body there that could hold a
candle to you: and besides teaching, which you are a person I conclude
every way fitting for it, I shouldn't wonder if you got to be governer
in two year.'
Much did Timothy, on retiring to rest, revolve in mind the advice
of the sage landlord. He could not but admit that the argument for
going to Vermont was a very forcible one, and coming as it did from so
candid a man, and one who had been a representative to the
legislature, it seemed entitled to great weight;—so after mature
deliberation, he concluded to follow the 'Squire's enlightened
suggestions—go to Vermont, become a chief teacher of the poor
barbarians of that wild country, till such time as they should make
him their governor.
The next morning Timothy rose early, and under the fresh impulse of
his late resolution, eagerly resumed his journey.
Nothing worthy particular notice occurred to our hero during the
three next succeeding days of his pilgrimage for fame and fortune.
Untroubled by any of those doubts and fears of the future which so
often prove troublesome attendants to minds of a different mould, he
pressed on in the happy consciousness that merit like his must soon
reap its adequate reward. Emoluments and civil distinctions would
await him as matters of course, but an object of a higher character
more deeply engrossed his mind, and formed the grateful theme of his
loftiest aspirations. This was the sublime mysteries of Masonry; and
to the attainment of its glorious laurels he looked forward with a
sort of prophetic rapture as a distinction which was to cap the
climax of his renown and greatness.
With such bright anticipations of the future beguiling many a
lonely hour, and shortening many a weary mile, he arrived at the
eastern bank of the beautiful Connecticut— that river of which the
now almost forgotten Barlow sings or says with as much truth as
felicity of expression— "No watery gleams through happier vallies
shine, Nor drinks the sea a lovelier wave than thine." Fearlessly
passing this Rubicon, for such it was to one of his preconceived
notions of the country beyond, supposing, as he did, its eastern
borders to be the very Ultima Thule of civilization, Timothy
found himself, as a certain literary dandy, who is now receiving "
Impressions" among the naked Venuses of Italy, has been pleased to
express it, "out of the world and in Vermont."
Vermont! Ah, Vermont! calumniator of the heavenborn Handmaid! How
the mind of every true brother sickens at thy degenerate name!—How
deeply deplores thy fallen condition!—How regrets and pities thy
blindness to that light which, but for thy perverseness, might still
have gloriously illuminated thy mountains, and soon have shone the
ascendant in all thy political gatherings, thy halls of legislation
and thy courts of justice—overpowering in each the feebler rays of
uninitiated wisdom, and filling them with the splendors of mystic
knowledge! What unholy frenzy could have seized thy irreverent sons
thus to lay their Gothlike hands on the sacred pillars of that
consecrated fabric, in which we behold accomplished the magnificent
object for which the less favored projectors of ancient Babel labored
in vain,—the construction of a tower reaching from earth to heaven,
by which the faithful, according to the assurance of their wise ones,
"Hope with good conscience to heaven to climb, And give Peter the
grip, the pass-word and sign!" What high-handed presumption, thus to
assail that institution which, as its own historians, as learned as
the Thebans and as infallible as the Pope, have repeatedly informed
us, commenced in Eden, (whether before or after the gentleman
with the blemished foot made his appearance in the garden, they have
not mentioned,) and which has since continued, from age to age,
advancing in greatness and glory, till it has at length arrived at the
astonishing excellence of nineteen degrees above perfection!
What blind infatuation and unappreciating stupidity, thus to pursue
with obloquy and proscription that heaven-gifted fraternity, who are,
we are again informed, so immeasurably exalted above the grovelling
mass of the uninitiated, that,
"As men from brutes, distinguished are, A Mason other men excels!"
No wonder this daughter of heaven is indignant at thy ungrateful
rebellion to her celestial rule! No wonder her Royal Arch sons of
light mourn in sackcloth and ashes over thy disgrace! No wonder her
yet loyal and chivalrous Templars are so anxious to see thy "lost
character redeemed!"
But from this vain lament over a country once honored and
blest—by that glorious Light she has since so blindly strove to
extinguish—over a country once happy and unsuspected in her fealty
to those who, like the sun-descended Incas, are thus endowed with the
peculiar right to govern the undistinguished multitude—over a land
thus favored, but now, alas! forever fallen, and become a by-word and
reproach among her sister states—let us return to those halcyon days
of her obedience in which transpired those brilliant adventures which
it has become our pleasing task to delineate.
After crossing the river, our hero entered a thriving village
situated around those picturesque falls where this magnificent
stream, meeting a rocky barrier, and, as if maddened at the
unexpected interruption after so long a course of tranquil
meanderings, suddenly throws itself, with collected strength, headlong
down through the steep and yawning chasm beneath, with the delirious
desperation of some giant maniac hurling himself from a precipice.
After a brief stay at this place, which, to his surprise, wore the
marks of considerable civilization, and which he concluded therefore
must be the strong out-post of the frontier, and the largest town of
the Green-Mountain settlement, he pushed boldly into the interior.
Taking a road leading north-westerly, with a view of passing through
the mountains into some of the western counties of the state, which
he had been told comprised the best part of Vermont, he travelled on
several hours with increasing wonder in finding the country cultivated
like other places he had been accustomed to see—the farm-houses
comfortable, and not made of logs; and the inhabitants much like other
people in appearance. In pondering on these, to him unaccountable
circumstances, as he diligently pursued his way through a variety of
scenery which was continually arresting his attention, he wholly
forgot to acquaint himself with the relative distances of the houses
of public entertainment on the road. At length, however, the setting
sun, slowly sinking behind the long range of Green-Mountains, which
now, with broad empurpled sides, lay looming in the distance, reminded
him of his inadvertence, and warned him that he must speedily seek out
a lodging for the night. But now no inn, or, indeed, any other
habitation was in sight; and to add to his perplexity the road became
more woody, and he was now evidently approaching a wilder part of the
country. Undismayed, however, he pressed onward with a quickened pace,
and after travelling some distance he came to a small farm-house.
Determined to make application for a night's lodging at this cottage,
as it was now nearly dark, he approached it and rapped for admittance.
The rap was instantly answered from within, and at the same time a
host of white-headed urchins crowded to the door, headed by the
house-cur, yelping at the very top of his cracked voice. Presently,
however, the owner of this goodly brood made his appearance, loudly
vociferating, "Fraction! get out, get out, you saucy scamp! you have
no more manners than a sophomore in vacation.—Number One, take a
stick and baste the dog to his heart's content; and you, Number Two,
Three, and the rest of ye, to your seats in a moment!" After thus
stilling the commotion around him, the farmer cordially invited
Timothy into the house, where the latter was soon made welcome for the
night to such fare as the house afforded. As soon as the common-place
remarks usual on such occasions were a little over, our hero, whose
curiosity was considerably excited by the specimen of Green-Mountain
manners which this family presented, began to make his observations
with more minuteness; and taking what he here saw, as many other
learned travellers in a strange country have done, for a fair sample
of the rest of the inhabitants, he could not but marvel much on the
singularity of this people. Every thing about the house exhibited a
strange mingling of poverty, and what he had been taught to believe
could only be the results of some degree of affluence. The family
appeared to be in possession of the substantials of living in
abundance, and yet rough benches were about their only substitute for
chairs: Indeed, the usual conveniences of furniture were almost wholly
wanting.— Again, there were two or three kinds of newspapers in the
room, one of which two of the boys, each as ragged as a young Lazarus,
were reading together by fire-light, with one hand holding up the
tattered nether garments, and the other grasping a side of the sheet
whose contents they seemed to devour with the eagerness of a young
candidate for Congress on the eve of an election, occasionally making
their sage comments, till one, coming to some partisan prediction or
political philippic with which the newspapers at that period were
teeming, suddenly let go the paper and exclaimed, "Hurra for Madison
and the Democrats! Dad, we shall have a war, and I'll go and fight
the British!"—while, "so will I!" "and I too!" responded several of
the younger boys, starting up, and brandishing their sturdy little
fists. While these tiny politicians were thus settling the destinies
of the nation, an embryo Congress-member, the oldest boy, or Number
One, (as his father called him) a lad of about fifteen, lay quietly on
his back, with his head to the fire, studying a Greek Grammar, and
furnishing himself with light by once in a while throwing on a pine
knot, a pile of which he had collected and laid by his side for the
purpose. These circumstances, particularly the latter, filled our hero
with surprise, and he asked the farmer how he `contrivified,' in a
place with no more `alliances for edifercation,' to bring his boys to
such a `length of perfecticability' as to be studying Greek? To this
the man replied, that they had a school in every neighborhood that
furnished as many, and indeed more advantages than common scholars
would improve; and he did not suppose boys in any country, whatever
might be said of its advantages, could be very well taught much faster
than they could learn. As to his own boys, he did not consider the
smaller ones any great shakes at learning; but with regard to Number
One, it came so natural for him to learn, that he did not believe the
boy could help it. A college school-master, he said, teaching in their
school the year before, had put the child agoing in the dead lingos
and lent him some books;—since which, by digging along by himself
nights, rainy days, and so on, and reciting to the minister, he had
got so far that he thought of going to college another year, which he
was welcome to do, if he could `hoe his own row.'
Timothy then asked him the reason of his `designifying' his
children by such odd `appliances.' To this question, also, the farmer
(who was one of those compounds of oddity and shrewdness who have
enough of the latter quality to be able to give a good reason for the
same) had his ready answer, which he gave by saying, that he never
gave names to any of his children, for he thought that his method of
numbering them as they came, and so calling them by their respective
numbers, altogether preferable to giving them the modern fashionable
double or treble names; because it furnished brief and handy names by
which to call his children, and possessed the additional advantage of
giving every body to understand their comparative ages, which names
could never do; besides, there could be no danger of exhausting the
numeral appellatives, which the other course, in this respect, was not
without risk in the Green-Mountains; though as to himself, he said he
did not know that he ought to feel under any great apprehensions of
running out the stock of names, as he had as yet but seventeen
children, though to be sure he had not been married only about
fifteen years.
Our hero now retired to rest for the night, and, after a sound
sleep, rose the next morning to resume his journey, when to his great
joy a waggoner came along and kindly gave him a passage over the
mountains, landing him at night at an inn in the open country several
miles to the west of them.
[1] The expression of Hon. Ezra Meech, a Knight Templar Mason, in a
letter written by him to certain gentlemen in Windsor County, after
his nomination by the Jackson and National Republican parties, as a
candidate for Governor, in opposition to the Anti-Masons.
[2] Allusion is doubtless here made to the starting career of a
distinguished member of Congress from Vermont, now deceased, who is
said to have commenced his classical studies under the auspices, and
in the manner here described.—Editor.
[3] The following anecdote probably refers to some of the neighbors
of the above mentioned individual. A boy being asked his name, replied
that he had none. The reason being asked, he said his father was so
poor he could not afford him one.—Ed.
CHAPTER IV.
"Thirty days hath September,April, June and November,—All the rest have thirty-oneBut February alone."
The above, reader, I consider the best verse of poetry of modern
production: the best, because the most useful, that has been given to
the world by the whole tribe of poets of the present century, whether
born or made so, from Byron, intellectual giant of lofty imaginings,
down to N. P. Willis, puny prince of poetical puppyism. Don't stare
so: I am in earnest; and make my appeal, not to finical critics, but
to the great mass of the people, learned and unlearned, for a
confirmation of my opinion. What man, woman or child, in their daily
reckoning of the days in the different months, for the calculations of
business, profit or pleasure, does not instantly recur to this verse,
which is fixed in the memory of all, or a majority of all, who speak
the English language, as the readiest way of ascertaining at once
what would otherwise require a considerable exertion of the memory, or
perhaps an inconvenient recurrence to the almanac to determine. And
what is modern poetry?— what is its real utility, and what are its
effects? Metal refined to dross—a crazy man's dreams—a combination
of vague, mystified, and unmeaning imagery, containing scarcely one
natural simile—one sensible thought, or one sound maxim of moral
instruction; and calculated only to enervate and undiscipline the
mind, without bettering the heart by awakening one commendable
sensibility or by fostering one virtue. Such at least is too much the
character of the productions of our mistaken poets. The above lines,
however, are obviously an exception to these remarks; and thus
viewing them, I thought I would quote them in compliance with the
custom of heading chapters with a catch of poetry; and as to their
applicability to the subject matter of the chapter over which they are
placed, I have little fear of violating the precedents of many of my
superiors in authorship.
I left my hero, lodged for the night in a tavern situated in a town
some miles west of the Green-Mountains. This town, as he found on
enquiry, contained a village of considerable size lying about three
miles distant from the tavern of which he was then an inmate. After a
night's selfconsultation, Timothy concluded he would make his debut
in this village without further wanderings. Whether he came to this
determination just at this time, because he considered it a public
duty to try to enlighten the inhabitants of this particular town, or
whether the diminished gravity of his purse admonished him that he
could not proceed any farther without replenishing it, is a matter of
no consequence; but certain it is, he was now making an inroad on his
last guinea.
I mention these trifling circumstances, because I am aware that
even trifles become invested with interest and importance when
connected with subsequent greatness. Timothy was informed by the
landlord that there was an academy, or town school in the village,
which having no funds, was supported by subscription, and taught by
such preceptors as could, from time to time, be obtained; some of
whom instructed in the dead languages, and all the classics, and some
only in English branches, and that this academy was at present
destitute of a teacher. For this station our hero now resolved to
offer himself, not in the least doubting his qualifications to
instruct the children of a people so rude and ignorant, as he had been
taught in his own country to believe the Vermonters. For this purpose
he proceeded directly to the village, and calling on one of the
trustees or committee, who, he was told, superintended the hiring of
instructors, promptly offered himself for the vacant situation. The
gentleman, as soon as he was made to understand this proposal of
Timothy, eyed its author a moment with keen attention—then took out
his spectacles, rubbed the glasses, put them on, and took a second
look, surveying from head to foot the goodly dimensions of the young
six-footer before him, (our hero stood just six feet high in his
cowhides, reader,) his looks seeming to say, "a sturdy fellow, truly!
but does he look like a preceptor?" For a while he appeared puzzled
what answer to make to Timothy. At last however he observed, that
perhaps they had better walk over to Esquire Hawkeye's office, as the
Squire was also a committee-man, and usually took the main management
of the establishment. Accordingly he led our hero to the office of the
'Squire, and introduced him by observing, "A gentleman, who wishes to
engage as teacher of our academy, 'Squire.—I always leave cases
of this kind to your management, you know, 'Squire," he
added, with a kind of half grin. After all the necessary introductory
nods, &c. had been made by the parties, the 'Squire, who was a lawyer,
laid aside the writs and executions which were ostentatiously
displayed on the table before him, and proceeded to put a few general
questions to Timothy, who promptly answered them in the way he thought
best calculated to produce a favorable impression of his abilities.
The 'Squire listened with great attention to every answer, rolling his
tobacco quid at the same time in his mouth with increased rapidity.
"What say you," at length he said, addressing the man who introduced
Timothy, "what say you, Deacon Bidwell, shall we proceed to examine
into the gentleman's qualifications, or does he bring with him
sufficient credentials?" The Deacon looked to Timothy for an answer to
the last question, but not receiving any, he observed, "The 'Squire
means to ask you whether you have brought any credentials, or letters
of recommend with you." To this our hero, conceiving the question
implied a doubt of his qualifitions, and feeling indignant that any
doubts should be entertained of him by a people whom he considered so
much his inferiors, rather haughtily replied, that he "never carried
about with him such superfluous superfluities; and that, if they were
not already satisfied with his blandishments, they might proceed to invistigate them." The 'Squire now rolled his quid faster than
before. At this moment, a little thin, sallow-faced, important-looking
fellow came bustling in, who was saluted as Doctor Short, and who was
a no less important personage than the village physician, and a third
member of the august board who were about to sit in judgement on the
literary and scientific qualifications of our hero. The Doctor having
been informed of what was on the carpet, and invited to take a part
in the examination, the 'Squire now observed, "Perhaps we may as well
proceed to invistigate the gentleman a little, as he expresses
it.—So, I will propound a question or two, with his leave:—And in
the first place, What is grammar?"
`That part of speech,' replied Timothy, with the utmost
promptitude, `which teaches us to express our ideas with propriety
and dispatch.'
"How would you parse this sentence," said the 'Squire, holding up
in his hand an old book of forms, "This book is worth a dollar?"
`Pass!' replied Timothy, with a sneer, `pass it? why, I should pass
it as a very absurd incongruity, for the book evidently is not worth
half that sum!'
"Ah, well, Sir, we will take another branch," said the 'Squire, in
an apologetic tone—"What histories have you read?"
`Robinson Cruso, George Barnwell, Pilgrim's Progress, Thaddeus of
Warsaw, Indian Wars, Arabian Nights, the account of the Great
Gunpowder Plot, and a multitudinous collection of others, too numerous
to contemplate.'
"At what time did the Gunpowder Plot take place—how, and in what
country?"
`In England, in the dark ages of ancestry, when it blew up the
King, whose name was Darnley, into the immeasurable expanse of the
celestial horizon—shook the whole of Europe, and was heard even into
France and Scotland.'
"What is Geography?"
`It is a terraqueous description of the circumambular globe.'
"The gentleman really seems to answer the questions with great
promptitude," said the 'Squire, with well-supported gravity. "Doctor,
will you take your turn in a few interrogatories?"
The Doctor now assuming a wise look, and taking a new pinch of
snuff by way of sharpening his faculties for the occasion, asked
Timothy if he had ever studied the Latin language.
Our hero hesitated; but thinking it would not do to be thought
deficient in any branch of education, and having caught the
signification of a few words from having heard the recitations of a
Latin scholar or two in a school which he once for a short time
attended, he concluded to risk the consequence of giving an
affirmative answer: Accordingly, he told the Doctor that he did
profess to know something about that language.
"Well, then," said the Doctor, "What is the English meaning of this
sentence—Varium et mutabile semper femina?"
`Why,' replied Timothy, `it means, I opinionate, that simpering
females will mutiny without variety.'
"Not so wide from the mark, by the shade of old Virgil!" said the
other, laughing: "but let us try another—a famous quotation from
Horace: it is this—Poeta nascitur, non fit?"
`O, that is plain enough,' quickly replied our hero, `and I agree
with that Mr. Horace—he says that a nasty poet is not fit—that is,
not fit for any thing.'
The Doctor and 'Squire now laughed outright—the Deacon looked
round to see what was the matter, and smiled faintly through sympathy,
but said nothing. "I will now," said the Doctor, after having
recovered from his fit of merriment, "I will now give you a sentence
in prose, with which you, being a teacher, will of course be
familiar:— Bonus doctor custos populorum."
`Why,' replied Timothy, with a look of mingled doubt and wicked
triumph glancing at the lean visage of the other, `seeing you put it
out to me, I will explanitate it: It says and signifies, that bony
doctors are a curse to the people.'
The laugh was now against the Doctor, in which even the Deacon
joined heartily; while the somewhat discomfited object of the joke,
after a few shrugs of the shoulders, hastily proceeded to say,
"Well, well, let us drop the Latin,—other studies are more
important,—let us take some of the higher branchos of English
education. What, Sir, is Chemistry?"
`Chemistry!' said our hero, `why, that I take to be one of your
physical propensities which has nothing to do with education.'
"Well, then," said the Doctor, "we will take a view of the higher
branches of Mathematics—algebraical, geometrical or trigonometrical
principles, if you please."
But Timothy, thinking he had answered enough of their impertinent
questions, replied, that `as to algymetry and trygrimetry, and such
other invented abstrusities,' he considered too insignificant to
monopolize his internal consideration: He therefore wished them to
tell him at once whether or not they would employ him. This unexpected
request rather disconcerted the learned trio, and they appeared much
at a loss what to say. After some shuffling of feet, spitting and
looking down upon the floor, the Deacon and Doctor both turned their
eyes imploringly on the 'Squire, as much as to say, "you must be the
man to smooth the answer as well as you can."
The 'Squire then told Timothy, that they were not exactly prepared
at present to give any answer. But our hero was not to be put off in
this manner, and desired to know when they would be ready to answer
him. The 'Squire replied that it was extremely difficult to tell, but
if at any time hence they should wish to employ him, they would send
him word. Timothy, however, was determined to bring them to something
definite, and therefore insisted on their naming a day when they would
let him know their decision. On this, the 'Squire finding himself
likely to be baffled in his plan of indefinite postponement, as the
legislators say, very gravely proposed that Timothy should call in
one year from that day, at half past four o'clock in the afternoon,
precisely, when he should have the answer which he so much desired.
Our hero hearing this strange proposition, and observing them
exchange sundry winks, instantly rose, and, with becoming indignation
declaring that he had no sort of desire to enter the employment of men
too ignorant to appreciate his talents, abruptly left the office.
Pausing not a moment to look either to the right or left, he strode on
with rapid steps till he was fairly out of the village; when he
turned round and gave vent to his smothered resentment in a torrent
of anathemas against those conceited and impudent fellows, who, with
such astonishing stupidity, had failed to discover his capacities in
an examination in which he had, in his own opinion, acquitted himself
so honorably. But he was now clear of them, and he determined to
trouble them no more. Indeed, he began now to entertain a
contemptible opinion of school-keeping altogether, and he therefore
concluded to make no more applications for this kind of employment, at
least among the conceited Vermonters. "But where am I going?" he now
for the first time thought to ask himself. He revolved several things
in his mind, and at last resolved, as it was now nearly night, to
return to the tavern where he lodged the last night, and consult with
the landlord, who had treated him with much kindness, relative to the
course he had better pursue in his present unpleasant circumstances.
CHAPTER V.
"Romans, countrymen and lovers!"
—Brutus.
Vexed, cross, discomfitted and sullen, our hero arrived at the
tavern he had left in the morning with such high hopes, nay, with such
certainty of success in the application, the fate of which is recorded
in the last chapter.
Think not, reader, that I am admitting any thing derogatory to the
talents of my hero by describing his failure, or rather want of
success, in his attempt to get employed by a paltry school committee.
By no means. Who is to say that it was not a fit of sheer caprice in
these conceited wights of village greatness, that led to his
rejection? Again, as "it requires wit to find out wit," who shall
decide that it was not their ignorance instead of his that produced
that hapless result? But, admit that it was not,—admit that they
were right in considering Timothy not well calculated for the business
of instruction, does it follow that this must necessarily go in
disparagement of his abilities— of his genius—of his heroic
qualities? Why, Marlborough, whose military achievements constitute so
bright an era in England's glory—even the great Marlborough, could
never have made a school-master. And Newton,—think you Newton could
have ever become a Garrick in theatrics— a Sheridan in eloquence, or
a Burns in poesy? Greatness does not consist in being great or
excellent in every thing, nor does talent, to be of the highest order,
require that its possessor should excel in all he may happen to
undertake. The farmer, the mechanic, or even the horse-jockey, who
displays uncommon dexterity or superior management in the business of
his occupation, may be said to be a man of talents.
Having now disposed of this point to my own satisfaction, and to
yours also, I presume, gentle reader, I will proceed with my narrative.
No sooner had Timothy entered the bar-room of the inn above
mentioned, than he was hailed by the landlord, who was called Captain
Joslin. "Well, friend," said he, "what luck? Have you got the place,
and come back to practice at the school-master's walk, &c. awhile
before you appear among your scholars?" Timothy at first felt a little
disinclined to relate the result of his journey to the village, but
finding his host kindly anxious to know what had befallen him to
cause such dejection in his looks, he at length frankly related the
whole proceeding, attributing his failure to a cause which few, I
think, who rightly appreciate his capacities, will doubt to be the
true one, viz: the inability of the committee to comprehend the depth
and bearing of his answers and observations, adding that he had
become so perfectly disgusted with school committee-men that he
doubted whether he could ever again bring his mind to make another
application of the kind. "Ah," said the Captain, "I was rather fearful
when you went from here that you would not be able to do much with the
big-bugs there in the village; besides, people are mighty particular
in these parts about their school-masters: It an't here as it is in
Massachusetts and York State. Why, they turned off our master last
winter only because my boy, Jock, who was fourteen last sugarin'-time,
treed him in a sum in Double Position—though to be sure we don't
often get taken in so.—But as to yourself, what do you propose to
drive at now for a living?"
This question brought matters to the point on which Timothy had
determined to consult the landlord: He therefore candidly told his
host his exact situation, and asked his advice on the subject.
"I thought likely," observed the landlord, "that this might be the
case with you; and I have been thinking, friend, as you appear to be a
kind of honest, free-spoken fellow, besides being stout and
able-bodied for business, that you are about such a chap as I should
like myself to employ a few months—say till after next harvesting. I
have a farm and keep a team, as you see. Now what say you to hiring
out to me for about ten dollars a month or so, to work mostly on the
farm, but tend bar when I am absent, or at other times, perhaps, when
business is not very pressing?"
This kind proposal, although not quite a fair equivalent for a
salaried professorship, or the gubernatorial chair of Vermont, came
nevertheless at this dark hour of his prospects, as the sun of light
and comfort to the soul of our hero; and with that facility, with
which great minds always conform to circumstances, he cheerfully
acceded to the proposition of Captain Joslin. All the articles of the
compact were then discussed and ratified on the spot; and both
parties appeared well satisfied with the bargain. It is unnecessary,
perhaps, to detail the events of the few first days in which Timothy
was introduced into the business of his employer; suffice it to say,
that after becoming an inmate in the Captain's family, he soon began
to feel cheerful and contented, and such was his alacrity in business,
and his sprightliness and buoyancy in companionship, that he shortly
became a favorite, not only in his employer's family, but in all the
immediate neighborhood. But capacities like his could not long remain
concealed by the obscurity of such employment. In this situation he
had lived about a month, when one day he received an invitation to go
to the raising of a large barn frame in an adjoining town. He
accordingly attended the raising; and during the performance, often
attracted the attention of the company by his activity in handling the
light timbers, as well as by the free good will with which he put his
shoulder to the broad-side. After the raising of the building was
completed, and the bottle had several times circulated, the company
broke from the drinking circle, and gathering into small clubs about
in different places, commenced telling stories, singing songs,
cracking jokes, and discussing various subjects according to the age
and tastes of the parties. Our hero happening to be passing one of
these little collections, heard them discussing the subject of
Freemasonry— some ridiculing it as a "great big nothing," as
they were pleased to term it—others denouncing it as a dangerous
institution, and yet others defending it. This was enough to arrest
his attention, and arouse his feelings; for he was born, it may be
said, with an innate sympathy for that noble institution; and he
immediately pushed his way into the circle, and so earnestly took up
the cudgels in defence of the slandered order, that he soon
triumphantly vanquished his opponents, and was left master of the
field. Having, by this time, drawn a considerable crowd about him,
and being still full of the subject on which he had now become
thoroughly excited, his natural inclination for spouting came upon him
too strong to be resisted; and mounting a bunch of new shingles that
lay near him, he elevated his fine form, and after pitching his voice
by the usual h-e-ms and h-a-ms, thus addressed the listening crowd
around him:
"Friends, Countrymen, and Fellow Barn-Raisers:
"In all my longitudinal meanderings from the town of Mugwump, the
place of my native developement, to the territorial summits of the
Green-Mountain wilderness, I have never heard such scandalous
exasperations and calumniated opinions protruded against the
magnificent marvelosity of Masonry. Having been instilled from the
earliest days of my juvenile infancy to look upon that celestial
transportation of Masonry with the most copious veneration, is it any
wonderful emergency that I am filled with the most excruciating
indignation in hearing these traducities against an institution of
such amphibious principles and concocted antiquity? And here I exalt
my prophecy that unless you expunge such disgusting sentimentalities,
and put down such illiterate falsifications, they will hetrodox the
whole popular expansion, till they entirely stop the velocity of
civilization: For there is no other preparative that can exalt a
people from their heathenish perplexities, and confer rank and
distinguishment like the luminous invention of Freemasonry. Then
again, behold its useful commodity! Look at that compendious
barn-frame! Was it not conglemerated by the square and compass? and
are not these emblements extracted from the intelligence of Masonry?
Let me then concentrate my propensities to warn you to lay aside your
reprobate infringements, lest you, and all your cotemporary posterity,
be deprived of the civilized embellishments and incomprehensible
advantages of that superfluous fraternity."
He ceased, and his speech was followed with bursts of applauding
laughter by many, by exclamations of admiration by some, and by
expressions of wonder and surprise by all. It will be said, perhaps,
by those astute antimasonic carpers, who, in these degenerate days,
scruple not to condemn the choicest specimens of masonic composition
because they are often wholly incapable of comprehending them,—it
will be said, perhaps, by such, that this impassioned little burst of
eloquence is not original in my hero; that it is borrowed from some
masonic orator. This I wholly deny; but while I claim entire
originality for this impromptu effort, I am free to confess the
resemblance which might lead to such a conclusion; and, indeed, not a
little proud should our hero feel of a performance which, by its
similarity of style, diction, and lucid and conclusive manner of
argumentation, is liable to be mistaken for one of those monuments of
extraordinary eloquence that, in the shape of twenty-fourth of June
orations, have thrown such a halo of light and glory around the mystic
temple.
But the temporary applause which Timothy received on this occasion,
was of little consequence compared with the subsequent honors of which
this little performance seemed to be the moving cause. Scarcely had he
descended from his rustic rostrum when he was eagerly seized by the
hand by a person who heartily congratulated him on his speech.
Timothy having before seen the man, whose name was Jenks, at
Joslin's, and become somewhat acquainted, soon fell into a low,
confidential sort of conversation with him on the subject of the
speech, when the latter observed, that from a certain circumstance
(not returning the grip probably) he concluded that Timothy was not a
Mason; and, on being told that such was the case, enquired why he did
not join the lodge, at the same time adding that he had never before
met with a person who, he thought, would make a brighter Mason.
Timothy then asked Jenks if he should advise any one to join. "Why,"
replied the latter, "we never advise any body to join us; but I
can tell you that you little dream of what you will lose if you
don't." To this Timothy replied that he had long been determined on
becoming a Mason as soon as his circumstances would admit, but at
present he had no money to spare for the purpose, besides he had
certain objections to appearing in the village where he supposed he
should have to go if he joined at this time. Jenks however removed all
these objections by informing Timothy that they had a lodge in that
town, and that a note would answer as well as money for the
initiation fee. On hearing this, our hero at once accepted the offer
that the other now made, to propose him at the next lodge meeting,
which was that very night. Jenks then went and procured pen, ink and
paper, and writing a note of the required sum, and an application in
due form, brought them to Timothy to sign, at the same time
explaining the necessity of this measure. These being signed, it was
arranged that Timothy should come in just four weeks, and calling on
Jenks at his residence, they should both proceed together to the place
at which the proposed initiation was to take place. When this
interesting negociation was concluded, our hero proceeded homewards
with a bosom swelling with pride and expectation. His step was
lighter, his head was held higher, and a new impulse seemed to have
been given to his whole energies; for he felt conscious that the
coming occasion was to constitute a new era in his destinies.
How slowly to our hero the tedious days of the next month rolled
away! It seemed to him that the eventful day that was to unfold to his
view the mighty mysteries of Masonry, would never arrive. Long before
the time came he had procured the sum requisite for his initiation,
and being now fully prepared for that important event, he ardently
longed to see the hour at hand. His whole soul became engrossed in
the overwhelming subject by day, and by night it was the burden of his
dreamy imaginings. Once, in particular, his dream became a vision of
striking distinctness, and prophetic import. He saw a vast throne in
the clouds, on each side of which extended a broad vapory parapet. A
mighty King sat upon the throne, with a shining mitre, covered with
mystic symbols, on his head, while an innumerable host of aproned
worshippers stood around him ready to do his bidding. While our hero
gazed on the splendid spectacle, a ladder was let down to his feet;
and he mounted it step by step, till he reached the very seat of the
Great Puissant, there enthroned in light and glory ineflable. When the
King, taking the crown from his own head, placed it on the head of our
hero and descended, exclaiming, "Hail, O Grand King! High and mighty
art thou among our followers on earth! Let the faithful worship thee!
So mote it be—So mote it be, forever amen, amen!" While the last
word was canght up by the multitude of surrounding worshippers, till
the long echoes, reverberating through the welkin in peals of vocal
thunder, returned to the ears of our enthroned dreamer, and dispelled
the magnificent vision from his enraptured senses.
CHAPTER VI.
"Wunder-wurkeinge."
Old Masonic Manuscript.
The long wished day, which was to reveal to our hero those hidden
wonders so impenetrably concealed from the profane and vulgar, at
length arrived. With restless impatience and quivering anxiety did he
wait the proper hour for his departure to meet his appointment at the
place of his proposed initiation. And no sooner had it arrived than
he mounted his nag, and, with his initiation fee snugly deposited in
his pocket, rode off for the residence of Jenks, the friend, who, as
before mentioned, had agreed to introduce him. The distance was about
five miles; but his horse, although it was a murky evening in July,
either through consciousness that he was bound on an errand of no
ordinary import, or in consequence of those birchen incentives to
speed that were freely administered at almost every step by his
impetuous rider, flew over the rough road with the velocity of the
wind, and in one half hour stood reeking in sweat at the place of his
destination. Jenks, already in waiting at the door, received Timothy
with all the kindness of anticipated brotherhood. As soon as the
mutual greetings were over, the two immediately set out for the house
where the lodge was to hold its meeting. This was a new two-story
wooden building, into which the owner had lately moved. Although the
house was only partially finished, yet a `rum pole,' as it is
sometimes called, had been raised, and the building was already
occupied as a tavern. The landlord, himself a Mason, had agreed to
consecrate his hall to the use of his brethren, and the approaching
meeting was the first opportunity they had found to dedicate it to its
mystic purposes. The members of the lodge having mostly assembled when
Timothy and Jenks arrived, the former was left alone in the bar-room,
while the latter went into the hall, proposing to return for the
candidate as soon as all was ready for his reception. This was a
moment of the most thrilling and fearful suspense to our hero,
tremblingly alive as he was to the overwhelming interests of the
occasion. He tried to occupy his mind during the absence of his
friend, which seemed an age, by now looking out of the window and
watching the movements of the gathering clouds as they came over,
deepening the shades of the approaching evening,— now vacantly
gazing at the turkies, taking roost in the yard,—now pacing the room
and pulling up his well starched collar, and now hurriedly counting
his fingers, to kill the lagging moments, and allay the fever of his
excited expectation.
At last, however, Jenks came, and informed him, that the committee
appointed to consider his case had reported faverably; the vote of the
lodge had been taken, and "all was found clear:" he might therefore
now follow to the preparation room. This room was no other than the
kitchen garret, which, being on a level with the hall, and
communicating with the same by a door at one end of it, was now to be
used for this purpose through necessity, as that part of the hall
originally designed for a preparation room was not yet sufficiently
finished to answer for the present initiation. To this garret the
candidate was now conducted, through the kitchen, and up the kitchen
stairs— that being the only way of getting into the room without
going through the hall, which the candidate must not yet be permitted
to enter. The garret having been darkened for the occasion, the
candidate and his conductor, after getting up stairs, groped along,
feeling their way by taking hold of the rafters above them, towards
the hall door, frequently stumbling over the loose boards of which the
floor, in some places single, in some double or treble, was composed,
placed there for the double purpose of seasoning and answering for a
temporary flooring. The masonic reader may here perhaps pause to demur
to the fitness of our preparation room as being too liable to attract
the attention of the inmates of the kitchen below, and thus lead to
an exposure to the eyes of prying curiosity; but all this had been
prudently foreseen, and the difficulty obviated, by the landlord who
had contrived to have his wife and daughter, the only females of the
family, go out on a visit that afternoon, with the intimation that
they need not return till dark, before which it was supposed the
ceremonies of the preparation room would be over.
As soon as Timothy had been stationed near the door leading into
the lodge-room, he was left to himself. In a short time however Jenks
returned, accompanied by several others, one of whom was the Senior
Deacon of the lodge, who now approached the candidate, and questioned
him as follows:
"Do you sincerely declare upon your honor, before these gentlemen,
that unbiassed by friends, uninfluenced by unworthy motives, you
freely and voluntarily offer yourself a candidate for the mysteries of
Masonry?"
`I say yes,' replied Timothy, `to all but that about being biassed
by friends—my father advised me to join, and Mr. Jenks here'—
"Why, Sir," hastily interrupted the Deacon, "you don't pretend that
your friends used improper influence to induce you to join, do you?"
`O, no,' replied Timothy; `but falsifications are
exceptionabilities, and I thought you was going to make me say'—
"Ah, Sir," again interrupted the Deacon, "you said no, I think, to
the last question: The answer will do, will it not, Brethren?" `We
conclude so, Brother,' was the reply. The Deacon then proceeded.—
"Do you sincerely declare upon your honor that you are prompted to
solicit the principles Masonry by a favorable opinion conceived of the
institution—a desire of knowledge, and a sincere wish of being
serviceable to your fellow-creatures?"
`Yes, I do,' eagerly replied Timothy. Here Jenks seeing the
probability that the candidate would need considerable prompting,
stepped up to his side and jogged him to be quiet.
"Do you," continued the Deacon, "sincerely declare that you will
cheerfully conform to all the ancient established usages and customs
of the fraternity?"
`Why, yes—it is conjecturable I shall,' replied Timothy, in a
half hesitating, half jocular tone and manner, `though the d—l a bit
do I know what they are: Suppose you first explicate and expound them
a little.' "Say you do," impatiently whispered Jenks in his ear. `I do
then,' said Timothy.
The Deacon then went into the lodge to report the answers of the
candidate, while those remaining proceeded to strip him of his
clothes; but not understanding the meaning of the movement, and not
much relishing being taken in hand in this manner, he suddenly started
and twisted himself out of their hands, demanding what they were going
to do, & bidding them beware of putting tricks upon one who could
throw any two of them at a back-hug, side-hold, rough-and-tumble, or
any other way—a threat which he probably could, and would have made
good, (for he was no slouch at athletics) had they persisted at that
moment while under the impression, as he was, that this movement was
no part of the ceremony, but a mere trick or joke attempted by way of
interlude to pass away the time till the Deacon returned. But Jenks
again interfered, and after many persuasions and the most positive
assurances that this was really part of the ceremonies, induced him to
consent to let them proceed. He then rather grumblingly submitted
himself again into their hands, observing that he "supposed it was
all right, but what the sublime art of masonry could possibly have to
do with pulling down a fellow's breeches, was beyond the expansion of
his comprehensibilities to discover." He was then divested of all his
clothing except his shirt, which was turned down round the neck and
shoulders so that the left breast was left bare. They then incased his
legs in an old pair of woolen drawers, which, on account of the
candidate's unusual crural dimensions, reached no farther down than
about midleg; and bound a black silk handkerchief so snugly about his
eyes as to make an impervious blindfold. His right foot was next
placed into an old shoe, which in masonic parlance is called "the
slipper;" while a rope, of several yards in length, was tied with a
noose around his neck. These important ceremonies being in due form
completed, all the attendant brethren retired into the lodge-room,
except the Senior Deacon, who was here left in charge of the
candidate. This officer then taking hold of the end of the rope, or
cable-tow, as it is termed in the technics of masonry, made towards
the hall door, and reaching out his right hand, while with his left
pulling upon the rope round the neck of the candidate, he gave with
his mallet, or gavel, three loud knocks on the door, which were
instantly answered by three still louder knocks from within; while at
the same moment the door was partly opened, and a harsh, sharp voice
hurriedly cried out, "Who comes there, who comes there, who comes
there?" All this was the work of an instant, and the noise thereby
produced falling so suddenly, so unexpectedly, and with such a rapid
succession of confused and startling sounds on the ears of the
candidate, he involuntarily bolted with the quickness of thought,
several feet backwards;—which movement straightening the rope, and
causing the Deacon to hang on stiffly at the other end, at once threw
the two into a position much resembling two boys pulling sticks. As
soon as the poor blind and alarmed candidate had time to rally his
scattered ideas, after being brought into this situation, a sudden
fancy shot through his brain that they were going to hang him; and,
like a led pig, that has hung back almost to choaking, he suddenly
made another desperate lunge backwards, when, as the evil genius of
masonry would have it, the Deacon unluckily let go his hold, and the
poor candidate came down on his rearwards on a place in the floor,
which happened to be of but one thickness of boards, with such
violence, that every thing gave way before him, and he was
precipitated with a loud crash down into the kitchen, and landed, with
the shock of thunder, on the floor. Just at that moment, as bad luck
would again have it, Susan, the landlord's daughter, a sturdy girl of
sixteen, had come home, and was in the act of hanging up her bonnet
when this strange vision fell on her astounded senses. She turned
round and gave one wild, fixed stare upon Timothy, who with a loud
grunt had floundered on to his feet, and now stood in his red drawers,
with his face concealed by the black bandage, and so tied with large
bows behind as to resemble horns, with his cable-tow hanging down his
back, and with his mouth distended with the grin of a baboon thrown
into the air. She gave one wild look on this appalling figue, and
bolted like an arrow through the door. Scarcely, however, had she
reached the yard, when some movement of our hero striking her ear, and
leading her to suppose the monster was at her heels, fear seized her
afresh, and deprived the poor girl of all power of getting forward,
and, like a sheep or a rabbit frightened by a dog, she continued for
some time leaping up with prodigious bounds into the air without
gaining an inch in advance, throwing up her hands with a pawing kind
of motion towards the heavens, and eagerly exclaiming, "O Lord! take
me right up into the skies! O, Lordy! O, Lordy!" She soon however
recovered her powers of progression, and with all her speed made
towards the barn where her two brothers were pitching off a load of
hay, screaming at every step, "O, murder! murder! save me! save me,
Ben! The devil is come! The devil is in the house! O, save me—save
me!"
The boys hearing this outcry, leaped from the load, and ran out
eagerly crying, "What's the matter—what's the matter?" "Oh, Ben!"
replied the breathless and affrighted girl, "Oh, Ben, the devil is in
our house! Oh! Oh! Oh!" "What the darnation do you mean?" exclaimed
Ben.— "Suke, you are crazy!" "O, I ain't—I ain't nother," she
cried with histerical sobs—"it is the devil—I seed him
with his black face, and horns, and tail a rod long! How he looked!
Oh! oh! boo-hoo-hoo!" "I snore!" exclaimed the youngest boy, with
glaring eyes, and teeth chattering like a show-monkey in January, "I
snore! Ben, where's dad?" "Jock!" said the oldest boy, flourishing
his pitchfork and courageously making towards the house, "you come on
with your fork—by golly! we'll fix him!" So saying, Ben, followed by
his brother, pushed forward to the scene of action, both proceeding
with their forks presented, ready to receive his majesty of the black
face and long tail upon the tines as soon as they should meet him.
When they came near the door they proceeded more cautiously, stopping
to peep in at a distance; but seeing nothing, they soon grew bolder,
and the elder one fairly put his head within the door. Here all was
quiet and nothing to be seen. They then went in, searched about the
room, looked out of the windows, and passed into the lower rooms of
the other part of the house, without finding any breach or hole where
his majesty could have come in or gone out, or indeed discovering any
thing that could in the least account for their sister's fright. The
Masons they knew were in the hall; but they never dreamed that the
apparition could have had any connexion with the proceedings of the
lodge room. They therefore concluded that it was all poor Susan's
imagination that had caused such a fuss, and getting her in, they
called her a darn fool to be scart at nothing. But she still
persisting strongly in her story, they soon gave it up that it must
have been the devil; and their mother coming home soon after, and
hearing the story, still added to their fears by expressing her
belief that it was a bona fide satanic visitation; and as soon
as it was dusk, they lit up a candle, and all sat down close together
in fear and wonderment, without going out of doors till the Masons
broke up; and even then they received no new light on the subject; for
the landlord was silent on the affair, being quite willing to let it
go as it stood, lest the truth might be discovered. It therefore
became the settled opinion of not only the family but the
neighborhood, except the brethren, that the devil actually made his
appearance on that eventful evening, and thousands were the
conjectures as to the nature of his errand. So much for the devil in
red drawers, hoodwinked and cable-towed. Let us now return to the
lodge-room.
No sooner had the accident just related happened, than several of
the brethren rushed out of the hall, and, while some carefully took up
and replaced the broken board by another so as to leave no clue to the
disaster, others ran down, and seizing the candidate, now bruised,
sore and bewildered, hastily forced him up stairs and hurried him
into the lodge-room, where they were on the point of receiving him,
when this luckless interruption took place.
After a short pause, to see whether the candidate was hurt, as well
as to recover from the fright and confusion into which they had been
thrown, they, on finding that no serious damage had been done, now
repaired to their respective stations that the ceremony might proceed.
The Worshipful Master then bid the candidate "enter with heed and in
God's name." A short prayer was next repeated, when the candidate,
after a few unimportant questions and answers, was again taken in hand
for the purpose of performing the customary ceremony of being led by
the cable-tow three times round the lodge-room. The brethren by this
time having fairly recovered from their alarm, were now, as they
thought of the late affair, and looked on the poor blind candidate,
beginning to be seized with much merrier emotions. And as he was led
along, his wo-begone countenance wincing at every step, as if he
expected every instant some new calamity to befal him, and lifting
high his feet, like a new-yoked hog, in fear of more accidents from
faithless floors, his shirt sadly torn, and his drawers so disordered
as to lead to some corporeal developements of masterly conformation,
his appearance produced no little sensation among the assembled
brotherhood.—Some were seen compressing their mouths and screwing
their lips together to prevent the escape of the threatened explosion
of laughter,—some snapping their fingers in silent glee, and some
holding their sides, and writhing and bending nearly double through
the convulsive effects of suppressed risibility: and in a moment more,
the contagion seizing the whole company, the hall shook and resounded
with a universal burst of half-smothered laughter. Even the Right
Worshipful Master, who was then reading a passage from the open Bible
before him, found such difficulty in commanding the tones of his
quavering voice, that he was forced to run hurriedly over the
remainder of the passage, and no sooner had he reached the last word
than he bro't the book together with a hasty slap, and gave himself up
to the uncontrolable gust of emotions that was every where raging
around him. As soon, however, as the Master could succeed in assuming
a face of sober dignity, and in quelling the tumult, the Junior Deacon
brought the candidate, now blushing almost through the black
handkerchief over his face at his own degradation, to a station near
the altar. The sharp points of the compass were then presented to his
naked breast, accompanied with some other of the usual ceremonies,
previous to administering the oath. He was next ordered and assisted
to kneel on his left knee, while his hands were placed in due form,
one under, and the other on the open Bible, on which were laid the
square and compass. After this, the Worshipful Master approached, and
told him that he was now in the proper place and situation to receive
the oath of Entered Apprentice, and desired him, if willing to take
it, to say over the words, repeating them exactly as they were given
off to him. The Master then proceeded to tell over the first clause of
the oath, which Timothy, after some hesitation, repeated. They then
went on with the rest of the obligation, which was in the like manner,
told over and repeated, until they came to the last clause, "Binding
myself under no less penalty than to have my throat cut across from
ear to ear, my tongue torn out by the roots, and my body buried in the
rough sands of the sea, at low-water mark, where the tide ebbs and
flows twice in twenty-four hours—so help me God;" when the
candidate, who, after all that had befel him, was not so much
bewildered as to quite lose his own notions about things, or so
subdued as to be ready to submit to any thing which he might think for
the moment to be of questionable propriety, suddenly started upon his
feet, and in a sort of desperate and determined tone exclaimed, "What!
have my own throat cut! and ask God to help do it? I'll be exploded
first!" This unexpected scrupulousness and refusal of the candidate,
whom they supposed to have been too much tamed by the events of the
evening to cause them any further trouble, occasioned a momentary
confusion among the brethren, and brought Jenks, his old prompter,
immediately to his side. The latter then used and exhausted all his
powers of coaxing to induce the still stubborn and determined
candidate to repeat the clause in question; but, finding that his
entreaties were of no effect, he resorted to menaces, threatening to
turn him out naked into the street if he refused to complete the oath.
But this, instead of producing the desired effect, only made the
candidate more turbulent, and he instantly retorted, "Do it, if you
want to smell my fist!—I can abolish a dozen of you!" At the same
time suiting the action to the word, he sprang forward, flourishing
his clenched fist with such fearful violence, that all hands, for the
safety of their heads, were obliged to leap out of his reach, while
with his left hand he made a desperate pull on the bandage over his
eyes. But the quick eyes of the brethren catching this last movement,
a half dozen of them sprang upon him in an instant, and, forcibly
holding his arms, put him down in his former position, in despite of
his furious struggles to get free. Here they held him down by force
till his breath and strength were fairly exhausted by the violence of
his efforts. They then, with the sharp points of the compass and
sword, began to prick him, first on one side, then on the other,
until, through pain, exhaustion and vexation, he sunk down and burst
out into a loud boo-hoo—blubbering like a hungry boy for his bread
and butter. Jenks, now taking advantage of this softened mood,
immediately renewed his exertions, and by a little soothing and
persuasion, soon brought the poor subdued candidate to consent to
take the remainder of the oath, which was instantly administered, lest
with recovering strength he should renew his opposition; and thus
ended this troublesome part of the ceremony.
The Master now addressing the candidate, said, "Brother, to you the
secrets of Masonry are about to be unveiled; and a brighter sun never
shone lustre on your eyes. Brother, what do you now most desire?" `I
should like a drink of water, and then to be let out,' sobbed Timothy,
taking the last question literally, and being now quite willing, in
his present state of feelings, to forego any more of the secrets of
masonry if he might be suffered to depart. But he soon found that this
was not to be permitted; for the prompter bid him answer the question
properly, and say he desired light. The question then being repeated,
he submissively answered as he was bid; when the Master, giving a
loud rap, and raising his voice, said, "Brethren, stretch forth your
hands and assist in bringing this newmade brother from darkness to
light!" This last order being followed with much bustle, and sounds
portending busy preparation for some important movement, the candidate
became alarmed, fearing that some other terrible trial, yet in
reserve for him, was now to be experienced; and he began to breathe
short, and tremble violently. The members having formed a circle
around the agitated candidate, the Master, after a few moments of the
most profound stillness, now broke the portentous silence by loudly
exclaiming, "And God said let there be light, and there was light!
" Instantly all the brethren of the lodge furiously clapped their
hands; and, with one united stamp brought their uplifted feet to the
floor with such a thundering shock as made the whole house tremble to
its lowest foundations: while, at the same time, the bandage, which
had been gradually loosened for the purpose, was suddenly snatched
from the eyes of the candidate, who, shuddering with terror at the
astounding din around him, and dazzled by the intenseness of the
bright flood of light that burst, from total darkness, at once upon
his unexpecting and astonished senses, now stood aghast with dismay
and consternation; his fixed and glassy eyes glaring in dumb
bewilderment on the encircled group of figures, which, to his
distempered and distorting vision, seemed some strange, grim and
unearthly beings, and which his wandering imagination soon converted
into a band of fiends, standing ready to seize, and pitch him about
in torments. Gazing a moment in mute amazement on this terrible array,
he became suddenly agitated, and, rising to his full height, and
collecting all his delirious energies, he, with one prodigious bound,
sent himself, like a rocket, completely over the shoulders of the
encircled brotherhood, and fell in a swoon at full length on the
floor, leaving an atmosphere behind him but little improved by his
ærial transit. All for a while was now bustle and confusion in the
lodge-room.—Some were seen running to take up the prostrate
candidate—some hurrying for water and spirits to revive him—some,
with one hand holding the organs of their mutinnous olfactories, to
work in clearing the floor of the sad effects of masonic principles
operating the wrong way; and others no less busily engaged in the
process of disaromatizing, or removing their own clothes and
emblematical adornments; for I grieve to say, that many a gay sash,
and many a finely figured apron, here fell a sacrifice to this hapless
result of the ennobling mysteries of Masonry.
At length all was again in a fair way to be restored to order. The
candidate was soon brought to his senses, and finding himself not
dead, and being assured moreover that the storm had now entirely
passed by, he began to revive rapidly. His clothes were then brought
him, and he was assisted to dress. This being done, and a glass of
spirits administered by way of a restorative, the Master proceeded to
complete the ceremonies, which were here made to consist only of the
grip, signs and pass-words, the lecture of instructions being
dispensed with for this time, owing to the weak condition of the
candidate; for he was still a little wild, and occasionally visited
with sudden starts and slight convulsive shudders, sometimes breaking
out into a loud laugh, and at other times shedding tears.
The lodge was now closed with a prayer by the Worshipful Master;
after which, the brethren were called from labor to refreshment.
Bottles were then brought on, and all freely partaking, soon relaxed
into cheerful chit-chat and social gaiety—some occasionally breaking
out into parts of those chaste, animating, and lofty breathing songs,
so peculiar to this moral and soul-gifted fraternity, and so worthy
withal of that classical origin of organized Freemasonry which the
learned Lawrie and other historians of the order, have, with great
appearance of truth, we think, traced to the mysteries of Bachus. And
while strains like the following, "Come let us prepare, We brethren
that are Assembled on merry occasion; Let's drink, laugh and sing—
Our wine has a spring— Here's health to an accepted Mason," with
the exhilarating effects of the now rapidly circulating bottle,
co-operating in their genial influences on both body and mind, the
feelings of the company were soon exalted to the highest pitch of
joyous excitement. A thousand lively jokes and sallies of wit,
together with many a hearty laugh over the romantic events of the
evening, enlivened the scene; and even the pale and exhausted
candidate began to mingle slightly in the prevailing mirth, and feel,
as they now broke up, that Richard would soon be himself again.
CHAPTER VII.
"Tityre, tu patulæ recubans sub tegmine fagi."
—Virgil.
Dark and fearful were the troubled visions of our hero after he had
retired to his pillow for rest on that memorable night when the awful
mysteries of Masonry were uncurtained to his view. Scenes of the most
thrilling horror, in their thousand rapid and startling mutations,
were continually rising, with terrible vividness, to his mind, and
haunting his distracted fancy. He now seemed falling, for days and
months, down, down, some bottomless abyss— now suddenly arrested in
his swift descending course by a tremendous jerk from a rope, which,
fastened around his neck, had run out its length, and now brought him
to the end of his tether—now slowly hauled up through the same
gloomy passage, attended by winged monsters, flapping their great
pinions about his head, as they labored upwards along this vault of
darkness and terror; and now quickly transported to the middle of a
vast, interminable plain, where the sky was immediately
overcast—storms arose—his ears were stunned by frightful peals of
thunder—streams of vivid lightning overpowering his vision, and
scorching his hair and garments, were flashing around him, and
kindling up the combustible plain to a general conflagration; while
he was beset on every side by a troop of tormenting fiends, who, armed
with sharp spears, and clothed with aprons woven, warp and woof, with
living serpents, and fringed with their hissing heads, thronged
thickly about him—some stripping off all his clothes, dancing on
before him and holding them up to his grasp, yet forever eluding it;
and others constantly running by his side, howling, goading and
stinging him in every part; while bleeding and blistered, he vainly
endeavored to escape, and strove on, in unutterable agony, through the
scorching and burning regions, hoarsely crying for water, and begging
for his clothes,—for his shirt—even a shirt!—
"I have brought you a shirt, Brother Peacock," said a voice at his
bed-side. He started from his disturbed slumbers at the word, which,
in seeming echo to his own deep mutterings, now fell on his ear.
"Where—where am I? Who are you?" he hurriedly and fiercely
exclaimed, looking wildly around him.—"Are they gone?" `What gone?'
said the voice. "Them awful—Oh!—Ah!—Why, it is only
Jenks—Yes, yes, I remember now, I went home with you last night;
but O, Jenks, what a dream I have had! And then, to think of last
night at the lodge-room!" `Come, come,' said Jenks, `you are like a
puppy with his eyes just opened,—every thing looks strange and
terrible,— a cat seems to him as big as a yearling, and the little
fool will bristle up and yelp at his own shadow. But never mind; we
will make a man of you yet. I will explain all to you in good time. I
have got a decentish sort of shirt here, which I rather guess you had
better put on,' he continued, looking down on the stained remnant of
what was yesterday our hero's best India cotton shirt, the choice
freedom gift of his mother, still pertinaciously clinging in shreds
to the limbs of the owner, as if loath to break off so old a
friendship: `and I think I could tie up that old one you have on in
your handkerchief, and throw it into the swamp going home, or burn it
or something, so it should not lead to any discoveries of what we do
in the lodge-room. But come, rouse up, man! Our breakfast is about
ready. I have got to be off to-day; but I shall be going by Joslin's
in a day or two, when I will call, and we will have some talk
together.' So saying, he left the room.
Timothy now attempted to rise, but so sore and stiff was he in
every joint, from what he had last night gone through in the masonic
gymnastics of initiation, that he found himself somewhat in the
condition of that hapless South-American animal, whose movements are
so painful, that it is said to utter a scream of agony at every feeble
bound it makes in its progress. After several trials, however, with as
many interjectional grunts, he succeeded in getting on to the floor
and dressing himself: after which, he found way to a cool spring in
the door-yard:—its pure bubbling waters seemed to his parched throat
sweet as the Pierian fountain to the thirsty aspirants of Parnassus;
and had it been that consecrated spring, Pope's direction, "Drink
deep," would never have been more faithfully followed. He then went
into the breakfast-room where the family were already assembled and
waiting his presence.
"Is the gentleman unwell this morning?" asked Mrs. Jenks, glancing
from the pale, haggard features of Timothy to her husband. Jenks
smiled and said nothing. "O, ho! I had forgotten," said she—"you
were both at the lodge last night—that accounts for all—I have
seen newmade Masons before, I believe."
`My wife,' observed Jenks, with a knowing wink to Timothy, `my wife
don't like masonry very well.'
"And what woman would?" she tartly replied. "You go to your
lodge-meetings every few nights, leaving your families alone and
unprotected—your wives and children perhaps sick, or suffering for
the want of the money you are squandering in your midnight carousals;
and when you come reeling home, the only comfort they receive for a
long and lonely night of tears and anxiety, is to be told, in answer
to their inquiries, concerning the employment of your cruel absence,
`You can't know—you are not worthy to be made acquainted with this
part of your husband's secrets!"'
`My wife,' said Jenks, `don't appear to know that masonry takes the
wives of Masons under its special protectection, and that their poor
widows are always provided for by her charities.'
"Charity! Poor widows!" retorted she,—"they may well be called
poor; for Mason's widows generally are poor enough. And what is the
amount of the mighty charities they receive at your hands? After their
husbands have spent all their property by neglecting their business to
attend to their masonry, paying out their money, or by bad habits
they first acquire at the lodge-room, then if they die and leave
penniless widows—well, what then? Why, the lodge will be so very
charitable as to pay back to those widows, perhaps, one tenth
part of what they have been the sole means of robbing them: And this
they call charity!"
`O wonderful!' replied Jenks—`And then the horrors of being left
alone a few hours, and the tears'—
"Yes!" retorted the nettled dame—"yes, the tears: If there is any
affection between a man and his wife, masonry does more to destroy it,
and break up that mutual confidence which is necessary to preserve it,
than any one thing I can mention. And if all the tears that have been,
and will be, shed by Masons' wives, on account of their husbands'
masonry, could be collected into a running stream, it would carry a
saw-mill from this hour to the day of judgement!"
`Come, come, wife,' said Jenks, `I think you have said quite enough
for once.'
"Enough of truth for
your conscience, I presume," replied
the fair belligerent, determined to have the last word in the
argument.
Timothy wondered much to hear such irreverent invectives against
masonry so boldly expressed by the wife of a brother Mason. He had
supposed that all wives were proud of the honor of having masonic
husbands; for he knew his mother was so. Still there were some of the
observations he had just heard which tallied so well with what he had
already seen of masonry, that he felt a little staggered, and could
not prevent his conscience from secretly giving a response to many of
the lady's remarks. But the sneering way in which Jenks laughed off
these remarks of his wife, soon convinced him that there was no truth
in them, and that they were the effects of the woman's ignorance, or
arose from some freak or prejudice she had taken against masonry, so
the matter passed off without again entering his mind.
After breakfast was over, and brotherly adieus had been exchanged
between Jenks and Timothy, the latter mounted his horse and rode
homeward. Many, and somewhat sober were his reflections, as he slowly
pursued his solitary way over the same road which he yesterday passed
with feelings as different from what they now were as the speed of
his horse in the two cases. His thoughts recurred to the fearful
trials he had gone through, and all the strange scenes of the
lodge-room. To his yet darkened mind, they seemed to him nothing but
vague mysteries, strangely blending the trivial and odd with the
solemn and terrible. The sun had indeed shone out, but the dark
rolling clouds had not yet passed entirely from the field of his
fancy, and the ravages of the storm were yet too recent on his
feelings to allow him to contemplate the late scenes of the lodge-room
with much pleasure.
On the following day Jenks called at Joslin's, but being somewhat
in a hurry, he proposed to Timothy that they should meet in a certain
field, about equidistant from their respective residences, on the next
Sunday, when the promised explanations and instructions in Masonry
should be given. Timothy, however, rather objected to a meeting on
Sunday; for his mother, who was a church woman, and a strict observer
of the Sabbath, notwithstanding her odd notions about rank and family
distinction, had always taught him that the seventh day of the week
should never be devoted to worldly matters; and never having been
taught any better since he left his paternal roof, the proposal to
spend this day in the manner contemplated struck him unfavorably. He
accordingly stated his objections candidly, and proposed another day
for the intended meeting.
Jenks, however, firmly combatted these fastidious scruples of our
hero, as he termed them, and told him he had hoped he was above
minding these old womanish superstitions. Still Timothy could not
entirely conquer his doubts on the subject; and in this I think he
was, in a good degree, excusable; for it must be recollected he had
but just been initiated, and had not enjoyed as yet scarcely any
opportunity of being enlightened by the true principles of masonic
philosophy; and when it is considered how deeply early impressions,
however erroneous, become engrafted on the heart, I do not think it at
all strange that he could not divest himself at once of all these
notions which he had been taught to believe correct. Finding his
companion still in hesitation on the subject, Jenks, therefore, to
remove all further scruples, now informed him that masonry was the
very handmaid of religion—indeed it was religion itself, and all the
religion that was needed to give a man a passport to heaven;
consequently, whatever time was spent in studying masonry, was, in
fact, devoted to religious employment, which was the object of the
Sabbath, aswas admitted by all the most rigidly pious. But what was
more than all, he said, the control of this day peculiarly belonged to
the craft, as it was a day of their own establishing; for to masonry,
and to masonry alone, the world were indebted for the consecration of
the Sabbath. This was put beyond all dispute by the unerring records
of masonic history, which, in the words of the learned Preston,
Brother Webb, and many other great Masons, expressly says, that "In
six days God made the world, and rested on the seventh: the
seventh, therefore, our ancient brethren consecrated." Of course
this day, being one of their own making, must be the rightful
property of the order, and, although they could do what they pleased
with it, yet it could be spent no way so suitably as in the study of
their art.
Such were the forcible arguments used, and the unanswerable facts
cited by Jenks, in enlightening his pupil in the path of his mystic
duties, and teaching the extent of his privileges as regarded the
observance of the Sabbath. And, although these were abundantly
sufficient to enforce conviction on all except the most obdurate of
uninitiated heretics, yet there is another curious fact relative to
the ancient history of this day, thus clearly traced to masonic
origin, which he might have added, and which I cannot persuade myself
here to pass unnoticed, it being, as I conceive, a fact of the most
momentous import to the glory of the institution, as not only showing
the connexion between masonry and the Sabbath, but figuring forth the
greatness and divine exaltation of the former, more strikingly
perhaps, than any one occurrence related within the whole compass of
its marvelous history: Josephus, that authentic ancient historian,
informs us that there was a certain river in Palestine that stayed its
current and rested on the seventh day, in observance, as he supposed,
of the Sabbath. Now if this day was established and consecrated by
masonry alone, does not the plainest reason dictate that it was the
institution itself, and not the day it had established, that this
pious and considerate river thus stayed its course to reverence? Or
was not this worship in fact, thus apparently bestowed on the object
created, clearly intended for the creator? Nothing, it appears to me,
can be more certain than that such was the fact. How stupendous the
thought! To what a magnificent pitch of exaltation then has that
institution arrived, to which the works of nature thus bow in
reverence,—to which the otherwise forever rolling rivers of the
earth are held in quiet subjection, resting in their rapid courses at
her omnipotent behests!
But to return from this digression—Timothy no sooner learned that
such was the case with regard to the connexion between Masonry and the
Sabbath than he magnanimously yielded his scruples, and, handsomely
apologizing for his ignorance of the facts just stated by his superior
in the art, cheerfully consented to the proposed meeting.
Accordingly, on the following Sunday, he repaired on foot and alone
to the appointed place of meeting. Jenks was already on the ground
awaiting his arrival. After the customary greetings were exchanged,
they seated themselves on the grass under the spreading branches of a
large beach tree which grew on the margin of the field, affording an
excellent shade to screen them from the sultry rays of a July sun. The
field which they had thus selected for their masonic rendezvous
adjoined a deep piece of woods which extended back unbroken to the
mountains, and, being more than a half mile distant from any
dwelling-house, furnished a secure retreat against all cowans and
evesdroppers, without the aid of a Tyler. Here in this silent and
sequestered spot, our two friends, stretched on their grassy bed
beneath their cooling covert, proceeded to the business of their
appointment. Jenks then producing an old worn pamphlet, went on to
read and explain the ceremonies of initiation, which, he said, in its
main outlines, represented, as was supposed by the learned men of
their order, the creation of the world; because when all was darkness,
God said "Let there be light, and there was light." The candidate, he
concluded, represented Adam, who came out of the darkness naked, and
was admitted to the light, and became endowed with noble faculties, as
was the case with all admitted to the glorious light of Masonry.
"But do you suppose, Jenks," said Timothy, "that God led Adam round
with a rope tied to his neck, before he let him see the light?"
`I know not how that may have been, Brother Timothy,' replied
Jenks, `but at all events, I think there is a striking resemblance
between the events of the creation and the ceremonies of an
initiation; and we have it from our ancient books that Adam was made a
Mason almost as soon as he was created.'
"Our first father Adam, deny it who can, A Mason was made, as soon as
a man."
This proving satisfactory to the mind of Timothy, Jenks then
proceeded to explain all the grips and tokens of the first degree;
after which he taught our hero the art or mystery of halving and
spelling Boaz. He next explained the meaning of the several emblems of
this degree, such as the three great lights of masonry, representing
the sun, moon, and Master of the lodge.—The square and compass,
which teach the brethren in such a beautiful and definite manner to
square their actions towards one another, whatever sharp corners may
thus be made to jostle against the ribs of the luckless uninitiated—
to circumscribe their conduct within due bounds, allowing such extent
to be fixed to that convenient epithet as their own good judgement and
circumstances shall dictate,—all of which thus furnish a great moral
guide to the man as well as the Mason—far superior, as many pious
and intelligent of the brethren aver, to the Savior's golden rule,
"Do unto others," &c., the latter being, as they say, too indefinite
for a practical guide by which to regulate their conduct, or rather,
we suppose, too general in its application to suit the system of
ethics peculiar to this exalted fraternity. And finally he took up the
lectures at large, by which Timothy obtained the valuable information
that the sun rises in the east and sets in the west, as beautifully
shadowed forth in the respective stations of the Master and Senior
Warden of the lodge,—that the twenty-four inch gauge, or rule,
properly represents the twenty-four hours of the day, and was for that
reason made just of that length, and not, as is supposed by the
unenlightened, because twelve inches make a foot, and a measure of an
even or unbroken number of feet is most convenient,—that Chalk,
Charcoal and Earth, represent Freedom, Fervency and Zeal, because chalk is free to be broken, or rubbed off—charcoal
is hot when it is burning, and the earth is zealous to bring forth,
&c. &c. All this, and a thousand other equally striking and
instructive emblematical illustrations of this degree were impressed
on his understanding in the course of these scientific lectures,
expanding his mind with a new stock of useful knowledge.
Having in this manner gone through his explanations of the more
prominent points of the lectures, Jenks now took a general view of the
principles they inculcated, and the important instruction they
afforded to the young aspirant of this noble science. In short, he so
eloquently portrayed the many beauties of this degree, that Timothy
began to catch some bright gleams of the true light of masonry.
Although, to be sure, he had always supposed that the sun rose in the
east and set in the west, and that charcoal was apt to be hot when it
was burning, yet he never before dreamed that meaning of such deep
import lay hidden under these simple facts; but the veil of his
natural blindness being now removed, he perceived the great wisdom
they contained—a wisdom which was impenetrably concealed from the
world, and, consequently, of which he must have forever been deprived,
had he never been admitted into the portals of this glorious temple of
light, and put in possession of the "art of finding out new arts, and
winning the faculty of Abrac."
It now occurring to our hero that he had promised, under the most
dreadful penalties, never to reveal, by writing, printing, or
otherwise, any of the secrets of masonry, he asked Jenks how the book
they then were reading came to be printed, as it appeared to contain
most of the secrets and ceremonies of the degree he had taken.
Jenks replied, that this book, which was called Jachin and Boaz,
was doubtless a correct and perfect system of masonry at the time it
was first published, although not strictly so in all respects now, as
many improvements, and some alterations in their signs and pass-words,
to prevent the uninitiated from getting into the lodge, had since been
made: still, being mainly correct, it was often used in the lodges in
lecturing, and might be profitably studied by all young Masons. As to
its publication, it was done by a perjured wretch who had violated his
oath by writing and publishing it; and it was generally understood
among the craft that he had paid the just forfeit by the loss of his
life.
This last remark led Timothy to ask if all who revealed the secrets
of masonry were served in the same way.
To this Jenks replied, that any mason who divulged the secrets
would undoubtedly die for the crime; for, if he did not kill himself,
as their traditions informed them some ancient traitors had had the
good conscience to do when guilty of this crime, means would soon be
taken to put such a wretch out of existence. But, he said, Timothy
would much better understand these things when he was exalted to the
higher degrees, which, it was to be hoped, he would soon take; for as
yet he had seen comparatively nothing of the glories of masonry which,
at every degree as the candidate advanced along this great highway of
light and knowledge, were more and more brightly unfolded to his
view. Jenks then drew such a glowing picture of the honors and
advantages of the higher degrees, that our hero, who confessed to
himself that his mind was not wholly filled with what he had seen in
the first degree, soon resolved to make another attempt to advance in
this bright road to perfection, and especially so when he was informed
that he had passed through the worst of the terrors, while all the
pleasures of the mystic Paradise, since he was now fairly within its
gates, remained to be enjoyed.
It was therefore arranged between them that Timothy, at the next
lodge meeting, should make application for taking the two next higher
degrees, provided he could raise the requisite fees for the purpose;
and he was to take home the book, and carefully keeping it from all
eyes, make it his study till the next meeting of the lodge, that he
might be the better prepared for his intended exaltation.
Having spent many hours under this delightful shade, in this
pleasing and instructive manner, the two friends were now about to
separate, when an incident occurred, which, having an immediate
bearing on the subsequent destinies of our hero, we shall proceed to
relate, as is our duty to do in every thing that has conspired to
affect his remarkable fortunes, however trivial it may appear at this
stage of our narrative, or unworthy the dignity of the historian of
so renowned a personage.
When our friends were on the point of separating, as I have
mentioned, they were suddenly startled by a loud cracking of the
bushes behind the old brush-fence that extended along the border of
the woods, at the distance of about ten rods from the tree under which
they were standing. The noise was soon repeated, and now plainly
appeared to proceed from the irregular steps or bounds of some heavy,
slow-going quadruped on the approach towards them, while the sounds of
the cracking brush were followed, as the creature occasionally paused
in his course, by a sort of wheezing grunt, or blowing, not unlike
that of a hog suddenly falling into the water. Now, although
cowardice was no part of our hero's character, yet possessing, in
common with all other men, the instinct of selfpreservation, he soon
felt a queer sensation of the blood creeping over him as these ominous
sounds struck his ear— his hair, too, suddenly grew refractory, and
began to rise in rebellion against the crown of his hat, and he
prudently suggested to Jenks, in the firmest terms that he was able
to command, the propriety of losing no time in putting a little more
distance between them and such suspicious noises. The latter, however,
who was more accustomed to the animals of the woods, only uttered an
impatient `pshaw!' at our hero's timely suggestions, and bidding him
remain where he was, went forward to reconnoitre that part of the
woods from which these singular sounds proceeded. After creeping up to
the fence and peering thro' awhile, Jenks quickly retreated, and
cutting, with his jackknife, a couple of good shelalahs on his way
back, he came up to Timothy, and with great glee told him that there
was an old bear with two small cubs slowly making their way towards
the clearing, with the intention, doubtless, of entering the field,
which was covered with wheat, then in the milk. At this intelligence
our hero's all-overishness alarmingly increased, and like a good
general, he quickly cast his eyes round to discover and fix upon the
best way by which to effect a safe retreat, and seizing his friend by
the arm, pulled him along several steps, eagerly pointing towards the
nearest house, while his teeth (his tongue just at that time being
strangely forgetful of its office) made a most chattering appeal to
the obdurate heart of the other, and did their best to second their
owner's pantomimic request for immediate flight. "Pooh! pooh!" coolly
replied Jenks, "a pretty story if two such chaps as you and I should
run for an old bear and two little scary cubs! Here, take one of these
clubs, and stand by like a man.—They will soon be over the fence,
and if we can frighten off the old one, perhaps we can catch or kill
one or both the young ones.—Follow me, and make no noise." So
saying, Jenks, with Timothy following almost mechanically at his
heels, led the way into the grain to a station from which they could
sally out and cut off the retreat of the bears. Here stooping down,
they awaited the approach of the foe in silence. In a few moments a
loud cracking was heard in the old fence; and immediately after, a
rustling among the grain told them that the objects of their
solicitude were fairly in the field. "Keep cool, Tim," whispered
Jenks, carefully raising himself till he could peep over the grain,
"keep perfectly cool—wait till they get a little further into the
field. There, then! come on now, and do as you see me!"
With this he rushed furiously forward, swinging his hat and
screaming at the top of his voice, and came close upon the astonished
animals before they could discover, over-topped as they were by the
tall, thick-standing wheat, whence this terrible out-cry came from,
and on what side the storm was about to burst upon them. The old bear,
however, quickly rallied, and throwing herself on her haunches, and
flourishing her broad boxers, tendered battle to her antagonist in a
style that would have done honor to the most eminent pugilist of
christianized England. The poor cubs were immensely frightened, and,
taking different directions, bounded off with all their might, one
towards the beech tree, and the other, as fate would have it,
directly towards Timothy, who stood like a statue, in the very place
where Jenks had left him. But the instant he saw this horrid young
monster making towards him, his faculties immediately rose with the
occasion, and uttering such a yell as scarce ever did a hero before
him, he struck a line in the direction his eye had before marked out
for a retreat, and, throwing one hasty glance over his shoulder, in
which he saw his friend engaged with the old bear, one cub climbing
the beech, and the other close to his heels, run like a deer from the
scene of action, clearing the top of the grain at every leap, and
crying `help!' and `murder!' at every breath.
Meanwhile the battle was waged with manful courage on both sides by
the combatants still on the field; and the issue might have been
doubtful perhaps, but for the sudden movement of our hero just
described: for the cub that ran towards him receiving a fresh fright
from the sturdy outcries of the latter in his retreat, quickly halted,
and after making several confused tacks about in the grain, finally
came round in sight of its dam, and ran off into the woods. The old
bear seeing this, and being satisfied with saving one of her family,
or supposing both to have escaped, at once relinquished the battle,
and fled in the same direction. Jenks being thus relieved in this
hazardous contest, immediately bethought himself of the cub in the
tree, and at once determined to secure it. With this purpose in view,
he stripped some strong pieces of elm bark from a neighboring tree,
and began to climb the beech, near the top of which he could soon
perceive the motionless form of the cub firmly grappling the forking
branches. After considerable difficulty, he came within sight of the
animal, which suffered him to approach without starting, when
carefully working a bark noose round its hinder legs, he firmly tied
them to the trunk of the tree, and then soon succeeded in getting a
pocket-handkerchief over its head, and thus finally so blinded and
muffled the creature as to render it nearly harmless. This achieved,
Jenks untied its legs from the tree and commenced his descent,
leaving it the use of its fore paws to cling around the body of the
tree as he gradually pulled it down backwards.
While Jenks was thus engaged in this slow and somewhat difficult
process of bringing down his sable captive, Timothy, who had reached a
neighboring house, and borrowed a gun and ammunition, hove in sight,
now gallantly returning to the rescue, advancing with a sort of
desperate determination in his looks, with his piece snugly bro't to
his shoulder, levelled and cocked for instant aim. When within thirty
or forty rods of the tree where he had left one of the enemy lodged,
he halted, and shutting his eyes, boldly pulled away at the top; but
his faithless gun only flashed in the pan, and he was coolly preparing
to try it again, when taking a hasty glance at the tree, he perceived
a rustling among the branches. No time was now to be lost; and he
fell to priming and flashing with all his might, till the clicking of
the lock arrested the attention of Jenks, who at the same time
catching a glimpse of his friend's motions, became alarmed, and sung
out lustily to him to forbear. Timothy was horror-struck at this
discovery, and he began most bitterly to reproach himself for
suffering his courage to carry him to such a pitch of rashness as to
lead him into such a dreadful risk of killing his friend; and that
friend too a masonic brother!—The thought was distracting! He was
soon consoled, however, by the information that the battle was now
over, and the enemy driven into the woods, except one cub which, now
disabled, remained as the trophy of the victory.
Jenks soon got safely down with the cub, and secured it at the foot
of the tree, when feeling curious to know by what lucky cause he had
so narrowly escaped being shot at for a bear, he unloaded the musket,
and found, to his surprise and amusement, that our hero had, in
making some amends for this oversight however by the quantity of
balls he had put in, no less than four of which Jenks found snugly
wadded down at the bottom of the barrel.
The exploits of this eventful day being now brought to a close,
Jenks shouldered his ursine trophy, and the two friends separated for
their respective homes, both pleased with their achievements, and both
thankful, though for different reasons, that they had outlived the
dangers of the battle.
CHAPTER VIII.
"Still louder, Fame! thy trumpet blow;Let all the distant regions know Freemasonry is this:"—
Our hero, after the romantic meeting, and the attendant occurrences
mentioned in the last chapter, sat down in good earnest to the study
of Masonry. His whole soul became gradually enlisted in the subject,
and his every leisure moment was devoted, with unremitting ardor, to
treasuring up the mystic beauties of this celestial science. No
longer troubled with those absurd scruples relative to the Sabbath,
which he entertained before he became enlightened by the liberal
principles of masonry, he now every Sunday rode over to the residence
of his friend, Jenks, and spent the day with him in secret communion
on that theme in which they in common delighted—the one in giving
and the other in receiving instruction. These meetings were also
enlivened by recounting over their late adventure in cub-catching, and
amusing themselves in teaching the now docile trophy of that heroic
achievement such various pranks and feats as they considered necessary
to a genteel ursine education. His master, perceiving in him signs of
his making a bear of uncommon talents, had honored him with the
dignified name of Boaz—an appellation at first suggested by
the title of the book under consideration at the time of his capture,
and more especially by the strength of a powerful grip which he gave
Jenks on his way homeward, which he likened to the masonic grip of
that name. And besides conferring the honor of a masonic name, they
taught him many accomplishments peculiar to the craft.—He would
stand erect on his haunches—cross his throat with one paw, or cross
his paws on his breast, after the fashion of the sign and due-guard of
the first degree, as readily, when the same motions were made to him,
as the most expert Entered Apprentice in Christendom.— Nor were his
masonic attainments limited to one degree only: the due-guard & sign
of the Fellow-Crafts, and the Master's sign of distress, were also
familiar to him—the latter of which he was wont to make whenever he
wanted an ear of green-corn, or an apple. In short, Boaz was fast
becoming a bright Mason, and would doubtless soon have made a great
adept in the mysteries of the craft, could he have taken the
obligations, and have been made to understand the preference which is
due to the brotherhood. In no other respects need he have been
deficient; for none certainly could be better calculated by nature for
many of the high and active duties of the order than he. In the
execution of the penalties, he would have been justly eminent.—
Jeremy L. Cross himself, would not have been able to rip open the
left breast of a traitor, pluck out his heart, or tear open his bowels
and scatter them on all sides to the four winds of heaven, with more
masonic accuracy.
But to return to our hero: Such was his intense application to the
task of perfecting himself in the study of Freemasonry, that before
the next lodge-meeting he had committed to memory the whole of Jachin
and Boaz, which, with the instructions received from Jenks, had made
him master of the first degree, and given him considerable insight
into the two next succeeding. Jenks became proud of his pupil, and
began to prophecy bright things of his future usefulness and eminence
among the order. His progress was indeed unrivalled, but no greater
perhaps than might have been anticipated from one of his retentive
memory, and from one whose mighty genius was so well calculated by
nature to grasp the peculiar sublimities of the mystic science. The
next lodge-meeting therefore found him fully prepared to meet his
intended exaltation. He had taken up his wages at Joslin's to the
present time, which furnished him with the means not only of paying
the additional fees required for taking the two next degrees, but of
getting a new coat and several other articles of dress that were
required, as he conceived, by the dignity of the important station to
which he was about to be exalted, and at the same time leaving a few
dollars for the usual disbursements of the lodge-room. Thus every way
prepared, he once more set out for the tavern where he had lately
encountered the appalling scenes of his initiation. He did not,
however, proceed at this time with the same urgent speed as when he
passed over the road before; nor were his feelings raised to the same
pitch of excitement. The first sight of the house, as he approached,
to be sure caused a chill and shudder to run over him, as it brought
fresh to mind the trials and terrors he had there passed through; but
these sensations quickly vanished as he recollected the cheering light
which there burst upon him at last in rereward for those fearful
trials; and more especially as he cast his thoughts forward to the
still brighter glories and honors before him.
He now entered the lodge-room, and not a little gratified and
elated were his feelings at the warm and cordial greetings with which
he was received by the assembled brotherhood. The lodge having been
apprised of his wish to take the next degrees in order, he now
retired, while they proceeded to the balloting; and all being again
announced clear, they now immediately commenced the ceremonies of
raising him to the degree of Fellow-Craft, or passing him, as it is
technically termed. But as the ceremonies of taking this degree are,
in many respects, similar to those which I have already described in
the account given to Timothy's initiation, and besides being now
performed on one who was in a measure prepared to meet them without
surprise so as to produce no very remarkable effects on his mind, I
shall pass lightly over this degree— mentioning only a few of the
most prominent acquisitions in knowledge which our hero made in the
interesting and beautiful lectures of the Fellow-Craft, which I deem
of too much importance to be omitted. He here was taught that
important fact in physiology that that there are five human senses,
viz: hearing, seeing, feeling, smelling and tasting,—the three first
of which are considered the most essential among Masons, though the
last, I opine, is not considered to be altogether superfluous. He
likewise was instructed into the learned intricacies of lettering and
halving Jachin, and was greeted by that appellation of wisdom in
reward for his triumph over the arduous difficulties of the task. And
lastly, the uses of that beautiful moral emblem, the plumb, were
illustrated to his understanding, and its monitory suggestions
impressed on his heart: for that instrument, he was told, which
operative masons use to raise perpendiculars, taught, or admonished
free and accepted Masons to walk uprightly, or perpendicularly in
their several stations before God and man. This last hieroglyphical
maxim of moral duty which masonry, in her astute sagacity, has so
naturally deduced from that instrument, forcibly reminded our hero of
an epitaph which he had somewhere read:— "Here lies Jemmy Tickiler
Who served God perpendicular." And although he never before could see
the force of this epitaph, yet he now at once saw its beautiful
application, and immediately knew that it must have originated from
the genius of masonry. But as important and interesting as these
discoveries were—as much as these, and the thousand other beauties
of this instructive degree were calculated to expand the mind, and
awaken the admiration of our hero, still they were
nothing—comparatively nothing, to the treasures of knowledge which
were opened to his wondering view in the next, or Master Mason's
degree. The ceremonies of raising were, in the first place, peculiarly
solemn and impressive: And connected as they are with an account of
the death of the traitors, Jubelo, Jubela, Jubelum, and the murder of
the Grand Master, Hiram Abiff, thus furnishing many historical facts,
a knowledge of which can be obtained only through the medium of
masonry, these ceremonies of themselves unfolded to his mind
information of the utmost importance. The circumstance, too, that the
body of Hiram had lain fourteen days without corruption, in the hot
climate where the incident occurred, particularly excited his wonder,
as the event could be attributed only to a miracle, thus furnishing
proof to his mind that this institution, like the Christian religion,
was founded in miracles. To this marvellous circumstance, which
struck our hero so forcibly, another not less curious and wonderful, I
think might be added—I mean the singular coincidence involved in the
fact that three men, as above mentioned, should happen to come
together—be of the same fraternity, and all traitors, whose names,
all of one beginning, should so nearly furnish the grammatical
declination of a Latin adjective! Nor need our admiration stop here;
for when we consider that these men were all Hebrews, whose language
is so dissimilar to that of the Latin, and that they lived in an age
too when the Romans and their language were unknown at Jerusalem, our
surprise is still more excited; and being unable, by the help of our
own limited faculties, to comprehend these miraculous circumstances,
we are compelled to stop short, and pause in wonder over the
extraordinary events which are connected with the early history of
this ancient institution. But however important the ceremonies of this
august degree may be considered as establishing the divine origin of
Freemasonry, and as throwing new light over some passages in the
history of antiquity, they still yield in importance to the moral
beauties, the lofty sentiment, and the scientific knowledge
illustrated and enforced in the lectures. Here a grand fountain of
wisdom is opened to the candidate; and it was here that our hero
revelled in intellectual luxury.—It was here for the first time in
his life that he became acquainted with that interesting philological
fact that masonry and geometry are synonymous terms, a discovery to
which the world is undoubtedly indebted to the light of masonry; for
Crabbe, (a shame on him!) notwithstanding his learned industry in
collecting the synonymes of our language, appears to be wholly
ignorant of this curious fact. Here he learned, while receiving an
account of the construction of Solomon's Temple, another fact in
history entirely new to him, "that it never rained in the day-time
during the seven years in which the temple was building,"—a fact
which can be considered none other than a miracle; and, as the temple
is known to have been the production of masonry solely, goes still
further to prove that the institution is divine, and under the
immediate protection of Heaven. Here too he learned the reason and
justice of inflicting the penalties of the obligations on traitors,
as illustrated in the example of the great and good Solomon, the
acknowledged father of organized Freemasonry. But time, and the narrow
limits of this brief work, will not allow me to proceed any farther in
recounting the various scientific discoveries which our hero here
made— the many moral maxims that were impressed on his heart, and
the thousand instances of the sublime and beautiful that burst on his
mind. Suffice it to say, that all were equally instructive, important
and wonderful with those I have enumerated. But not only all these
important acquisitions in knowledge did our hero make on this eventful
evening, but he won the unanimous applause of his brethren by the
becoming manner in which he bore himself through the whole
ceremonies, and which more than atoned for his wayward obstinacy and
awkwardness at his initiation, and, in the minds of all present, gave
bright promise of his future masonic eminence:—while the hearty good
humor with which he entered into the convivialities of the evening,
in time of refreshment, began to render him the favorite of the
lodge-room, and he was universally voted a bright Mason.
Being now clothed with his apron and the badges of a Master Mason,
and greeted, as he continually was, with the dignified title of
Worshipful, he began to feel the responsibilities of his station, and
the importance with which his existence had become invested. He
assumed a more manly step—a more lofty mien; and conscious worth and
consequence gave the air of majesty to his whole demeanor.
Thus ended the important events of this evening, which constituted
a bright era in the life of our hero, and implanted in his bosom a
love for this noble institution which was never eradicated.
Nothing of any particular interest occurred to our hero till the
next lodge-meeting, when the Senior Warden having left the town, he
was almost unanimously elected to fill that important and honorable
station. And a candidate having been presented for initiation, he
found an opportunity to display his masonicac quirements, which he did
with such brilliancy and promptitude as to draw forth repeated
applause from his admiring brethren. An extra meeting of the lodge
was, a few days after, holden, at which he rose still higher, and took
the three next degrees, viz: Mark, Past, and Most Excellent Master,
which carried him to the seventh round in the ladder of Masonry. Such
was the unparalleled progress, and such the starting career of the
man who was destined to become so proud a pillar in this glorious
fabric.
About this time Joslin, Timothy's employer, sought an interview
with him, and told him that a settlement would be agreeable. Timothy
could see no necessity for such a measure; but Joslin, without heeding
our hero's observations to this effect, opened his account-book, and
began to figure up the amount due after deducting what had been
received; and after he had ascertained the sum, he turned to Timothy
and asked him if it was correct? "I presume it may be," replied
Timothy, "but"—`But what?' said Joslin—`You have become a great
man since I employed you, Mr. Peacock, and I cannot any longer see you
stoop to labor which is so much beneath a person of your consequence:
Here is your money." So saying, he threw down the few dollars now
Timothy's due, and, whirling on his heel, left the house.
This was an unexpected affair; and Timothy scarcely knew what to
make of it.—After musing however about half an hour, he came to the
conclusion that Joslin wanted he should go: But what had he done to
render his employer dissatisfied?—He could think of nothing. To be
sure, when alone in the field, he had often marked out a lodge-room
on the ground, and taking a stump, and supposing it a candidate, had
lectured to it several hours at a time. He had sometimes yoked the off
ox the nigh side, when his mind was deeply engrossed with this
subject; and he had that morning turned the horse into the oat-field
instead of the pasture. But what of these trifling errors? And were
they not caused too by the intenseness of those studies which were
infinitely more important than the insignificant drudgeries which had
been saddled upon him by a man whose ignorance could never admit of
his appreciating things of a higher character?
Our hero began to grow indignant as he thought over these things;
and he determined he would have nothing more to do with Joslin, but
leave his house that very day; and, in revenge for his narrow-minded
views, and base conduct, forever deprive him and his family of those
services and that society with which he had been too long benefited,
and his house too much honored.
Our hero was a person of great decision of character; and what he
resolved to do, he scarcely ever failed of carrying into immediate
effect. Accordingly, in one hour from the time Joslin left him, as
above mentioned, he had packed his bundle and was making tracks
towards the residence of his friend, Jenks, for consultation and
advice, and perhaps a temporary home, not knowing where else to go in
this unexpected emergency.
Having arrived at the house of Jenks, and informed him of what had
happened at Joslin's, and that he had left that gentleman's employ
forever, the two friends walked out into a field, and spent the
remainder of the day in deep and confidential consultation. Many plans
for our hero's future course were suggested and discussed, and as
many, on weighing them, rejected. But a project was at length hit
upon by Jenks, which was finally adopted.—This was an excursion to
the city of New-York to see what could be made out of Boaz by
exhibiting him as a show, or selling him to some caravan. In this
enterprise they both were to embark and become joint partners in all
profits or losses that might arise out of the adventure. Jenks owned a
stout horse and waggon, half of which Timothy was to purchase, paying
down what he could spare, and giving a note for the rest; while Boaz,
being a kind of joint trophy, was generously thrown into the company
by Jenks, notwithstanding his greater claims to the animal, without
any charge to Timothy whatever. Jenks was a notable schemer.— He
having but a small farm, which did not require all his time to manage
it, had generally, for the last several years, taken two or three
trips a year in pedling goods for a neighboring merchant; and he was
now calculating to take one of these pedling voyages as soon as he had
finished his harvesting.—But as soon as he thought of the above
mentioned plan, he concluded to forego his ordinary fall pedling trip,
and engage in this, where he believed there would be a chance of
greater gain, though he knew there would be considerable hazard: and
for this reason he rather undertake the enterprise with some one who
would run the risk of loss with him, and believing that Timothy's
personal appearance and gifts of speech might make him highly
serviceable to the company, he now entered heartily into this scheme,
ostensibly for the benefit of our hero— privately for his own.
The next day the bargain was matured in all its parts, and all the
necessary writings drawn. Timothy gave Jenks twelve dollars for half
of the waggon, and twenty-five for an equal share of the horse—the
latter, though an excellent stout horse, was lacking of an eye, and
for that reason had been named Cyclops by the late
school-master of the district, who being a Freshman at Burlington
University, when he taught the school the winter before, had drawn
this name from the vast depths of his classic lore, and bestowed it
on the old horse in reward for his good service in carrying him and
his girl ten miles to a quilting.
The time for starting was now fixed by our two friends at just one
fortnight ahead; and for the interim Timothy agreed to work for Jenks
to enable him to complete his harvesting, and be ready at the time.
While making these preparations for the intended journey, the
regular monthly meeting of the lodge came round, when Jenks told
Timothy that there was one degree in Masonry to which he was now
entitled, and which might prove of great advantage to him on their
contemplated journey; and he would advise our hero to take it—it was
called the Secret Monitor, or Trading Degree.—He, himself, had
found it of great service. Accordingly, at the lodge-meeting, after
the lodge was closed, this degree was privately conferred upon
Timothy, the obligation of which, as it discloses the principles and
eminent advantages of this invaluable step in masonry, I must beg
leave to insert at length. It is as follows:
"I, A. B., of my own free will and accord, in presence of Almighty
God, do hereby and hereon, most solemnly and sincerely promise and
swear, that I will keep and conceal all the secrets belonging to the
Secret Monitor; that I will not communicate this to any one except it
be to a true and lawful brother, Master Mason or Masons, whom I shall
have reason to believe will conform to the same. I further promise
that I will caution a brother Secret Monitor by word, token or sign,
when I shall see him do, or about to do, or say anything contrary to
the true principles of Masonry. I further promise that I will caution
a brother Secret Monitor by word, token or sign, when I shall see him
do, or about to do, or say anything contrary to his own interest,
either in buying or selling, or any other way. I further promise,
that when so cautioned, I will pause and deliberate upon the course I
am about to pursue. I further promise, that I will help, aid and
assist a brother Secret Monitor, by introducing him into business,
sending him custom, or any other manner in which I may cast a penny
in his way. I further promise, that I will commit this obligation
to memory immediately, or as soon as possibly consistent.—All which
I promise and swear, with a firm and steadfast resolution to perform
the same; binding myself under no less penalty than to have my heart
pierced through by the arrow of an enemy, or to be left alone without
a friend to assist in the day of trouble.—So help me God, and keep
me steadfast to perform the same."
Such were the matchless beauties of this honorary degree of a
Master Mason, which our hero now received with no less pride than
admiration! Nor was this the only honor conferred on him that
evening.—About the middle of the evening the Master of the lodge was
called home by the sudden illness of his wife, when the unexpected
honor of presiding over the lodge devolved on Timothy; and nobly did
he sustain himself in discharging the functions of that high station.
After this meeting Jenks and Timothy proceeded to more immediate
preparations for their expedition. At the suggestion of Jenks, they
run up about twenty pounds of tallow and bees-wax into black-balls,
using wheat-smut to give the tallow a coloring. They then put up
about a dozen junk-bottles of common water, squeezing the juice of a
few elder-berries into one, wild turnip into another, and peppermint
or wild annis into a third, and so on, to give them some peculiar tint
or taste, no matter what; and labelling these bottles all with
different names and epithets, such as "certain cure for
consumption,"— "cure for corns," &c. &c. These and various other
domestic manufactures were prepared and put up for pedling on the way.
A large box fitted to the waggon, and properly aried with
gimblet-holes, was made to accommodate Boaz; while due care was
bestowed upon him to perfect his accomplishment before introducing him
into the world: all of which, having now become nearly grown to the
size of ordinary bears, and well nurtured in intellect, he acquired
with surprising readiness and docility.
CHAPTER IX.
"Love's but an ague that's revers'd,—Whose
hot fit takes the patient first;—That after burns with
cold as muchAs iron in Greenland does the touch."
Nature, it is sometimes said, often smiles auspiciously on those
undertakings which are fraught with important benefactions to man.
When the birds flew to the right, the chickens fed well, and Sol
unveiled his smiling features, then, and then only would the sagacious
old Romans commence any important undertaking. In what direction the
birds flew, on the morning that our two friends set forth on their
journey, it was not noticed; but certain it is, that the numerous
brood of dame Jenks' chickens manifested no lack of appetite on that
memorable occasion: and a bright October's sun burst smilingly through
the thick and humid mantle of mist and fog that had closely wrapt,
through the night, the head waters of the sluggish Otter, as they
applied the string to the back of old Cyclops, and rattled off on
their intended enterprise. The learned Boaz had been duly boxed and
shipped aboard their partnership vehicle, and a stock of provisions
laid in, consisting of baked meats and bread for the biped, and soft
corn, sweet apples, and oats, for the quadruped portion of this
distinguished party, which might have served a company of Bedouins
for crossing the great desert of Africa. They did not strike
immediately into the main road leading to the west, but by common
consent took a by-road which passed through a thinly inhabited part of
the country, and, after a circuit of some half dozen miles, came into
the direct road to New-York. This aberation, indeed, cost old Cyclops
four or five additional miles' travel, but it enabled them wholly to
avoid the village of examination-memory, which our hero had resolved
should never again enjoy the light of his presence, and thus saved him
from the violation of vows that both he and his friend, in the present
instance, seemed equally anxious to preserve inviolate.
Nothing of particular interest happened to our travellers during
their first day's journey. Having their provisions with them, and not
expecting to reap any emoluments by the exhibition of Boaz while in
Vermont, or accumulate much by their exertions as pharmacopolists till
they had reached a more gullable people than those jacks-at-alltrades
and professions, the inhabitants of the Green-Mountains, they stopped
at neither private house or tavern during the day; and at night, after
a diligent day's drive, they found themselves in the vicinity of the
Hudson, and many miles within that great political bee-hive, the State
of New-York, where a numerous array of proud and luxurious queen-bees
are generously allowed all the honey for governing the `workies.'
About dark they hauled up at the door of a kind of farmer's tavern,
situated adjacent to a pine plain, which was now on fire, while the
country for some miles round was enveloped in a dense cloud of smoke,
through which a thousand lights from stump and tree were beginning to
twinkle with the gathering shades of the approaching evening. The
landlord, an easy, though rather of a sneaking looking personage, came
out, with his pipe in his mouth, and greeted our travellers as they
drove up to the door. Our hero immediately leaped out of the waggon,
and, with a dignity of demeanor suitable to his elevated standing in
masonry, returned the salutation of the host, while at the same time,
seizing the hand of the latter, he gave him a hearty grasp. "What a
d—l of a grip you have, stranger!" said the landlord, as wincing
with pain he withdrew his own passive hand from the vice-like squeeze
of Timothy's fingers—"You must be a southerner, I guess, for they
always shake hands with a fellow whether they have ever seen him
before or not; but they don't knudge in among a body's knuckles so, as
I knows of."— `Ah! he has never been admitted to the glorious light
of masonry,' thought Timothy, with a sigh.
"Landlord," said Jenks, now taking upon himself the character of
spokesman, "we should like to put up with you to-night provided we can
pay you in our way, and we are willing to give you an excellent
bargain."
`Your way?' asked the other, giving a suspicious glance at the
waggon, `your way!—what mought that be, if I may be so bold?'
"Why," replied Jenks, "we have a live bear for show, and"—
`A live bear!' peevishly interrupted the man—`Pho! pish! pshaw!'
"Yes, a fine one! but hear me," said Jenks, somewhat abashed at the
other's sneers—"hear me through: we ask twenty-five cents a person
for a sight, and if you will keep us, you, and all your family, shall
see the animal, which, I presume, will amount to much more than the
reckoning; so you will be making quite a spec!"
`A curious spec that!' said the landlord—`I would give about
three skips of a flea to see your bear—I was out to a great hunt on
the mountains the other day, and help'd kill four as loud bears as
ever was seen: But I won't ax any thing better than money for your
keeping; and that you have enough of, I'll warrant.—Come, come, none
of your Yankee tricks for me—I used to be a Yankee myself once, and
understand a thing or two about their contrivances to get along on the
road.'
At this declaration, which conveyed the startling intelligence that
their host was a fellow-countryman, our travellers concluded to say no
more about Boaz by way of paying their fare, but to put up on the
offered conditions; so, after seeing Cyclops well stabled and fed, and
Boaz safely locked up in the barn, they all went into the house, and
entered into conversation.
"Would it not," said Timothy, as the landlord left the room for a
moment, "would it not, Brother Jenks, be more complaisant with the
dignity of our station to take some hot digestibles to-night? My
appetite begins to be somewhat excruciating, and I propound that we
take a supper like gentlemen."
`My appetite, under such circumstances, would have been as keen as
yours before I was married, I presume, Timothy,' replied the other,
glancing, with a comical smile, at a rosy-cheeked girl in the next
room, on whom our hero's eyes had been all the while rivited, `and as
it is, I have no objection to what you say.'
The landlord then entering the room, a supper was accordingly
bespoken, and while it was in preparation the garrulous host took a
seat with his guests, and resumed his discourse.
"So, you are from old Varmount, you say," began mine host. "Well, I
was original born in Cornetercut."
`Ah!' said Jenks, `then I don't wonder you understand so much about
Yankee contrivances, as you call them: Did you ever follow the
business of pedling?'
"Not by a jug-full, Mister," replied the other—"I never was one
of your wooden nutmeg fellers, I'll warrant it.— But I peddled love
and larnin to some purpose when I fust come to York State, I tell
ye—he-he he!"
`Why, how was that?' asked Jenks.
"I was goin' to tell you," said the host.—"As soon as I got my
edifercation parfect, I steered for York State, and teached in one of
the low counties among the Dutch till I got acquainted with a young
wider with an only darter, when we soon struck up a bargain, and moved
up to this farm, which fell to her as her portion out of her father's
estate, and here we all are, pretty well to do in the world, as you
may say."
`We don't make our fortunes quite so easy as that in Vermont,'
observed Jenks.
"No," rejoined the other, "I never could see how you all contrive
to live in that cold, barren, out-of-the-way region. Why, I once
travelled a piece into the Green-Mountains about the middle of June,
and going by a log-hut, I saw a man planting potatoes with his great
coat on,—it was then about ten oclock in the forenoon.—At sundown
I returned by the same place, & found the man to work digging his
potatoes up again.—So, thinking this was rather queerish, I stopped
and axed him what he was doing that for, when he said he didn't dare
to trust his potatoes in the ground over night for fear they would
freeze! he did, as true as my name is Jonas Bidwell—he-he he!"
`Was that,' retorted Jenks, somewhat nettled at the taunt thus
thrown at his native state, as well as at the boisterous and
self-applauding laugh of the landlord at his happy delivery of this
witty story, `was that about the time when the Yorkers were so anxious
to possess `this cold, barren, out-of-the-way place,' that they came
on in large numbers and tried to drive the owners from their farms, so
that they could live there themselves, but getting handsomely basted
with beech clubs, or beech-sealed as it was called, retreated as fast
as their legs would carry them, leaving the Green-Mountain Boys to
enjoy the sour grapes to themselves?'
"I don't know any thing about that," said the landlord, still
chuckling at his own story—"but the potatoes—he-he he!"
`But the Beech-Sealers,' rejoined Jenks, imitating the tone of the
other—`what a cold, barren place Vermont has ever since been with
the Yorkers!—ha-ha ha!'
Just at this moment the landlady, a short, fat, chubby figure, that
would have rolled down a hill one way as well as the other, came
waddling into the room, stopping every two or three steps to take
breath, or a fresh puff at her pipe,—"Shonas!" said she, addressing
her husband, as she dropped into her chair with a force that shook the
whole house,—"Shonas! Pe Cot! You look tam vell here in ter house
ven ter vire ish purnin all mine vinter crain up! I can take care dese
Cot tam Yankee petlars ash petter ash you.—So pe off to vatch ter
vire all night, or ter hell take yer!"
The obedient husband, who had sunk into silence the moment his
bigger half made her appearance, no sooner heard the promulgation of
this ukase than he took his hat and sneaked out of the house to his
appointed task. The landlady then entertained our travellers with many
a story about her farm, which "Shonas," she said, "a coot fellow
enough, help her carry on;" and enlarged with much apparent interest
on her stock of cattle, giving even the pedigree of her calves and
colts, and finally wound up the history of her prospects by saying,
"Tank mine Cot, I havn't seen ter pottom of mine milk-tup dese twenty
years!"
This last observation our travellers better understood when they
sat down to supper, which in the meanwhile had been announced as
ready, and which consisted, among other things, of bonnyclabber, a
favorite dish with the Dutch. They, it is said, always keep a tub in
one corner of the pantry, for the purpose of making and keeping this sine qua non of their tables; it being manufactured by adding
every day a quantity of new milk, always leaving, when they use out
of it, (unless forced by necessity to use the whole) a portion of the
old in the bottom of the tub to turn these daily additions into this
delectable beverage. Hence the Dutchman's thermometer of prosperity is
his milk-tub.
At supper, our travellers were attended by the landlady's daughter,
to whom allusion has before been made.— Nature, as regarded the
family stock, here seemed to be in a process of rapid improvement,
without being very badly cramped for room for her operations; for the
daughter, in features, was to the mother, after making every
reasonable allowance for the ravages of time, as Hebe to Hecate. But
aside from this, and difference of diameter, if a gauger's term be
admissible in this connection, the girl was a chip of the old block,
which she abundantly proved by retorting all the jokes cracked upon
her by her guests with a spirit equalled only by the refinement and
delicacy of her language. Our hero being the young man of the party,
and having been somewhat smitten from the first by her appearance
withal, particularly attempted to display his gallantry; all of which
she met with such jocose freedom that he proceeded with her to the
highest pitch of sociability; and, by the time that supper was over,
and the table cleared off, he began to feel, as she turned her little
twinkling black eyes upon him, rather queer about the inwards. Jenks
now going out to see to old Cyclops and Boaz, left our enamored swain
to the enjoyment of more privacy with his spanking sweetheart—an
opportunity which he did not fail to improve; and soon getting into a
romp with her, he became emboldened to throw out hints which most
damsels, who reckon themselves among the household of Diana, might
have perhaps resented. Not so, however, with the lively Katreen; for
she, like most of her country-women, I believe, not holding to
restricting the liberty of debate on one subject more than another,
met Timothy more than half way in all his advances; and, as far as
words were concerned, fairly beat him on his own ground. By the time
they had been performing their domestic waltz half an hour or so, our
hero could have sworn he was in love, with as clear a conscience as
Uncle Toby had done before him, after the rubbing operation by the
soft hand of Widow Wadman. By the way, I wonder if the fashionable
dances, known by the appellation of waltzes, did not originate in a
hint taken from Uncle Toby's courtship. I can think of no other
supposition so probable when the similar operations and results of the
two performances are fairly considered.
Jenks now coming in, deprived Timothy of further opportunity of
prosecuting his suit at this time, and of making some direct
propositions which he was about to do when thus interrupted in his
amorous parlance, and which, he had no doubt would be favorably
received.
It was now bed-time, and our hero was reluctantly compelled to
retire with Jenks, leaving his conquest, as he believed, on the very
point of its achievement. Their sleeping apartment was one of the
front rooms of the house, the other front room being used as the
bar-room, while a long room in the rear of these, answering the
purpose of kitchen, bed, and dining-room, completed the ground work of
the building, which was of one story with a Dutch roof, and a long,
low piazza in front.
As soon as our travellers were by themselves in their
sleeping-room, Jenks at once proceeding to disrobe himself, began
talking on the subject of their journey, while Timothy, taking a
chair, and, without seeming to heed the observations of his companion,
sat some time silent and abstracted. On perceiving this, the former
inquired the cause; and, after pumping and rallying him awhile,
succeeded in reviving his usual ingenuousness, and making him confess
the reason of his sudden entrancement. Just at this time, our hero,
with the quick ears of love, caught the sounds of the footsteps of his
fair one in the chamber above him bustling about in preparation for
bed. The ancients represented the god of love as blind—a wight, of
course, who never looked before he leaped. By this, nothing more was
intended, doubtless, than that he was considered a rash, short-sighted
and foolish fellow; but I have frequently suspected, from his so often
deliberately instigating his devotees to acts which result in their
total discomfiture, and from the design so often apparent in the
mischief which he seems to delight in occasioning, that this deity is
much more of a knave than a numb-skull; and that this, after all, is
the only reason why
"The course of true love never did run smooth."
Timothy, having noticed that there were several windows in the roof
of the house within reaching distance of the top of the piazza, and
knowing that one of these must open from the chamber of his charmer,
now formed the chivalrous project of scaling the outward walls which
enclosed the bright prize of his affections. This resolution was no
sooner taken than communicated to his companion.
"These Dutch minxes," coolly observed the latter, "are clear
pepper-pots for grit; and if this one should happen to take a snuff at
your climbing up to her window, Tim, I would not warrant your pate
from all damage short of money."
`O, no trouble there,' said the other eagerly, `for I have
ascertained for an intense certainty that she has taken a most
amorous conviction for me.'
"It may be as you suppose," rejoined Jenks, "for I saw that you and
she were as thick as two cats in a bag, in the supper-room; but have
you thought, Brother Timothy, of the possibility of your violating
your masonic obligations if you go on in this affair? How do you know
that this girl is not a Master Mason's daughter?"
`Why!' replied our hero, `I gave the old man as derogatory a grip
as ever was given to a brother, when we first met him at the door, and
he returned it no more than the most dormant cowan in existence!'
"Well, but her own father," said Jenks, "is dead—perhaps he was a
Mason."
`Allowing your conjectural supposition to be true,' observed the
other, somewhat staggered, `do you think the obligation was meant to
be amplified and distended to a Mason's wife or daughter after he is
dead?'
"I rather think," replied the elder votary of mystic morality,
"that the obligation does not bind us, in this respect, after a
brother's death; though it doubtless would extend to a brother's widow
in a matter of charity. But you are on sure ground for another reason,
which I guess you never thought of, Timothy.—The oath says, `you
shall not violate a brother Master's wife, sister or daughter, knowing them to be such.'—Now, when you don't
know that a
woman is a relation to a brother of such a degree, you can't of course
infringe on your obligation, whatever you may do. So you see you are
safe in this case; but I thought I would see how you would get along
with my questions. Thus you see that our obligations, when you come
to look at their true meaning, are not so rigid after all; for even at
the worst, this caution applies only to Masters' relations; and as to
the female connections of Entered Apprentices and Fellow-Crafts, I
know of nothing in masonry that forbids us to meddle with them if we
wish,— much less as regards all the rest of the sex who have not
the honor to be related to Masons of any degree; for to enjoy
ourselves with these is, I take it, one of the privileges that masonry
bestows on her trusty followers."
Timothy, who had been somewhat startled by the naming of his
masonic obligations, and once or twice perplexed by the questions thus
unexpectedly put to him on the subject which occupied his mind, was
now happily relieved from his doubts and misgivings by the explanation
of his more experienced masonic friend, and, entirely coinciding with
the latter in opinion respecting the latitude which his obligations
implied, began in earnest to think of his nocturnal enterprise.
As soon, therefore, as all was quiet below, of which he was soon
assured by hearing the old lady pitch the pipes of her nasal melody,
he crept carefully out of the front door, and, after taking a hasty
observation at the heights to be surmounted, and the situation of the
window that opened into his fancied Elysium, he began to climb a post
of the piazza. This, after a hard struggle, he happily effected.
Being now on the top of the piazza, which was almost flat, he found
no difficulty in walking along till he came under the window in
question. Here he paused to consider what might be the most suitable
manner of making known his presence to the fair object of his visit.
As soon as he had made up his mind upon this delicate, though
important subject, and screwed up his courage to the sticking point,
he reached up, and, taking hold of the window stool, and bracing his
feet against the steep slant of the roof beneath it as he mounted,
raised himself till he could look into the window, which, it being a
warm night, the unsuspicious occupant had fortunately left open.
"Now," said Timothy, in a whispered ejaculation, "now may the gods of
love and masonry inspire me." And, for the double purpose of awakening
the respectful admiration of his charmer by making known his masonic
quality, and at the same time enrapturing her with the melody of
verse, he commenced chanting, in the soft, winning accents of love,
one of those delicate and beautiful little stanzas of masonic poesy
which are forever the pride and boast of mystic minstrelsy—
"To Masons and to Masons' bairns, And women both with wit and charms
Who love to lie in Masons' arms."
"The bitches! I wish they were dead—caterwauling round the house
all night," muttered the half-roused sleeper, between dreaming and
thinking.
Our hero, feeling somewhat mortified in finding that his own sweet
notes should be mistaken by his drowsy inamorata for the music of some
nocturnal band of feline performers, and perceiving by her snoring
that she was again relapsing into slumber, resolved to regale her ears
with a livelier strain, though with a text no less beautiful and
appropriate:—
"Then round the circle let the glass, Yet in the square, convivial
pass; And when the sun winds o'er the lea Each lass shall have her
jubilee."
"That aint the cats!" exclaimed the damsel in tones of alarm,
starting up in her bed,—"what's that in the window! Who are you?"
`O it is I,' replied Timothy, with a most affectionate simpering of
voice—`it is only I, the gentleman who had the connubial
conversation with you in the supper-room, and could not rest for
thinking of the pelucid embellishments of your charms.'
"And what," replied the girl, who had become thoroughly awake
during this gallant speech, "and what, Mr. Pelucid Embellishment, do
you want here? It strikes me that you won't be much more apt to rest,
if you stay here long, than you would in your own room where you ought
to be."
`O, celestial charmer!' exclaimed our hero, `do not cause my
extraction forever! I know your internals must bleed with the most
amorous propensities for my anxious condition! I am a high Mason; and
"We're true and sincere— We all love the fair— They'll trust us
on any occasion."—
"Well, Sir," said Katreen coolly, "if you are one of those wise
fellers that strut about with aprons as solemn as a pack of old women
at a granny-gathering, I will trust you on this occasion with a
secret: do you want I should tell it?"
`O, I should be extremely extatic to hear it,' replied Timothy,
overjoyed at this supposed symptom of her relenting.
"Well, then," said she, in no very mild accents, "if you, Sir,
don't make yourself scarce in two minutes, I'll give you something
that will make you keep as long as a pickled lobster!—that's all."
`O, you lily of cruelty!' exclaimed our swain, `O, don't retard my
congenial anxieties, but let me come in: I shall propagate no noise.'
"No, nor any thing else, I guess," said she, tartly; "but I shall
though," she continued, leaping out of bed, "I shall though—scamp of
impudence! Will you be gone?"
But Timothy, notwithstanding the ominous tones of her voice, and
the rather unloving nature of her remarks, which might, perhaps, have
discouraged one of a less gallant and sanguine disposition, still
persisted in thinking that she was merely joking, and not believing
that she could seriously be otherwise than enraptured with him, became
the more emboldened as he beheld this fearless daughter of Amsterdam
standing in her night-clothes beside her bed, apparently waiting his
approach; and he began to make a movement to climb into her window.
Perceiving this, she sharply bid him desist, or he should repent it.
Timothy begged her not to speak so loud, lest she should raise the
folks in the house.
"I can help myself, I thank you," she replied, "without calling any
assistance; and I will do it too, to your sorrow."
Our hero hearing that she did not wish to alarm the house, and
feeling no great apprehensions on any other score, now boldly began to
mount the window; but scarcely had he thrust his head over the
threshold of his fancied paradise, when, (shade of Dean Swift, inspire
me to tell it!) the hidden reservoirs of that paradise were suddenly
uncapt—a masked battery was unexpectedly opened upon the
unconscious victim, and its projected torrent of liquid wrath, coming
with fatal aim, met him full in the face with a force that nearly
swept him from the window-stool with the shock!
"There! take that, stupid puppy!" exclaimed the gentle angel
within, "and if that an't enough, I've got another in store for you.
It will be quite an addition to your pelucid embellishments, I
apprehend."
"Then Cupid shriek'd, and bade the house farewell."
Reader! did you ever shoot a squirrel in a tree-top? If you have,
and noticed how suddenly he fell from his hold as the messengers of
death reached his heart, then you may form some idea how quickly our
hero dropped from the window on to the piazza below on receiving this
deadly shot from the fortress of his charmer.
Almost all diseases, in this age of physiological research, have
their specific remedies: and why not love among the rest? But when
Byron, in his wicked wit, while treating of the antidotes of this
complaint, said or sung— "But worst of all is nausea or pain About
the lower regions of the bowels, Love who breathes heroically a vein,
Shrinks from the application of hot towels," he must have been wholly
ignorant, I think, of the efficacy of that potion which was thus
promptly administered to our hero—a potion no sooner taken than his
Cyprian fever, with all its hallucination and burning agonies, left
him instantly and forever. The lovely and the loved one, whom, one
moment before, his fancy had invested with all the charms and graces
of the Houri, was now to his disenthralled senses....bah! he could not
endure to think of her. His first thoughts were involuntarily employed
in making this metamorphose—his second were turned to his own
condition: and for the next half hour, a dark object, in form much
resembling our hero, might have been seen standing in the neighboring
brook, busily engaged in something, the accompanying motions of which
seemed not much unlike those attending the ordinary process of
washing clothes. But why longer dwell on this sad and singular
catostrophe? Misapprehensions will often occur among the wisest and
best; and how then could it be expected, in the present cese, that a
mere country girl could perfectly understand the rights and privileges
to which our hero was duly entitled by the liberal principles and
blessed spirit of masonry?
Some physicians have recommended, I believe, salt water bathing for
promoting sound and healthy slumbers. I much incline to second the
opinion of its efficacy in this respect; and had he, who discovered
this remedy, have wished to extend his fame in this particular, our
hero would have freely given him a certificate in favor of the
practice; for he never slept more soundly than on the night of his
adventure with the lovely Katreen, the heroine of the Dutch tavern.
CHAPTER X.
At the first streak of day light the next morning, our hero jogged
his companion to awake, that they might rise and prepare for their
departure. But Jenks, although an early riser, and generally first on
such occasions, yet seeing no particular necessity for so very early a
start, begged for a little more repose. The impatience of Timothy
however would admit of no delay, and again rousing his friend, and
hastily dressing himself, he proceeded with wonderful alacrity to get
out and harness the team and put every thing in readiness for
immediate departure; all of which he had accomplished by the time that
Jenks, who was all the time wondering at the unaccountable anxiety of
his friend to be off at such an early hour, had dressed himself and
came out into the yard. The reckoning having been paid the evening
previous, the two friends now mounted their carriage and drove off
from the house, leaving all its unconscious inmates still wrapt in
their unbroken slumbers.
For the first few miles of their ride they were mutually silent, as
people generally are, or are inclined to be, during the first hours of
the morning. Whoever has been much at the public schools in his youth,
and seen a host of these wayward disciples of Minerva reluctantly
turning out at day-light for prayers and recitation, cannot but
remember the sour and lugubrious countenances there every morning
exhibited—the mumping taciturnity, and the cold and unsocial manner
with which each marched on doggedly to the task: While, after their
morning duties were over, and the mounting sun, aided perhaps by a
smoking cup of their favorite Batavia, had warmed up their sluggish
blood to action, the same fellows were invariably seen returning to
their rooms locked arm in arm as amiable and smiling as the face of
spring, and as chatty as the black-bird in her sunny meadows.
So with our adventurers during the first part of their morning's
ride. The sun however now began to glimmer through the heavy column of
fog that lay brooding over the noble Hudson; and its vivifying effects
were soon perceptible.
"What do you suppose is the reason, Brother Jenks," said Timothy,
gaping and stretching out his arms at full length, "what do you
suppose is the reason that women have never been allowed to
incorporate into our privileges of masonry?"
`Why, Brother Peacock,' replied the other, `you know that the
faculty of keeping secrets is one of the greatest and most essential
virtues of masonry: and don't you recollect a passage on this subject
in one of the songs in the Book of Constitutions, which runs in these
words— "The ladies claim right to come into our light, Since the
apron they say is their bearing— Can they subject their will—can
they keep their tongues still, And let talking be chang'd into
hearing?" Here you see how naturally their claims are urged, and at
the same time how strong are the reasons against their ever being
admitted.'
"True," observed Timothy, "but still I have some instigations for
wishing that there was some method to extinguish their wilful
functions towards us, and, if they cannot be admitted to infest their
minds with a proper understanding of the rights and privileges which
belong to us Masons, and which you know it is their duty to extend and
yield to us in every case that requires the least emergency."
`I have sometimes wished the same,' observed Jenks, `my wife,
besides forever teasing me to tell her the secret, always makes a
great fuss because I am out one night in a month or so, which all, no
doubt, comes from her not being able to understand the true nature and
value of masonry. But I don't suppose there is any help for this
grievance, for, as to their ever being worthy of being admitted into
the lodge, and this is the only way any thing could be done for them,
that business, I take it, was settled at the beginning of the world;
for there is another place in the Book of Constitutions which fully
explains this matter. It is in a piece called the Progress of Masonry,
and goes on in this way— "But Satan met Eve when she was a gadding,
And set her, as since all her daughters, a madding— To find out the
secrets of Freemasonry, She ate of the fruit of the forbidden tree.
Then as she was fill'd with high flowing fancies, As e'er was fond
girl who deals in romances, She thought with her knowledge
sufficiently cramm'd, And said to her spouse, My dear, eat and be
damn'd! But Adam, astonish'd like one struck with thunder, Beheld
her from head to foot over with wonder— Now you have done this
thing, madam, said he, For your sake no women Freemasons shall be."
Now in this history of the matter given by this book, which you know
is the Mason's Bible, and no more to be doubted than the other Bible,
you see why women in the first place were cut off from the privileges
of masonry; and although the reasons mentioned in the first verse I
repeated are enough to prevent their being admitted, yet you see if
those reasons did not exist, they could never come to this honor,
because it was forbidden almost as soon as the world was made; and
this I take to be one of the heaviest curses that was bestowed upon
Eve for eating the forbidden fruit, (which was pretty much the same, I
suppose, as unlawfully trying to get into the secrets of masonry) that
her whole sex should forever be denied the honors and privileges of
our blessed institution.'
"These verses," said Timothy, "are indeed sublimely transcendant;
but there is one incomprehension about them which I should like to
hear you diffuse upon. They say that Satan meeting Eve, set her mad to
find out the secrets of masonry, and so she eat of the forbidden fruit
to get these secrets. Now is it not consequential that Satan was a
Mason himself wrongfully trying to initiate her in this way?"
`I don't exactly see how it was myself,' replied the other, `but
these things are no doubt explained in the high degrees which I have
not taken. I suppose however that Satan might once have been an
accepted Mason, but you know he was expelled from heaven, which is no
doubt the Great Grand Lodge of the Universe, and made up wholly of
Masons.'
"Then you do not suppose," said Timothy, "that any of the feminine
extraction ever go to heaven?"
`Why, as to that,' replied Jenks, `we cannot certainly tell, but I
think it a very doubtful case. If they have no souls, as our brethren
in Turkey and some other parts of the old world believe, then of
course they cannot go to heaven. But if they have souls, as all in
this country, except Masons, believe, then it seems rather a hard case
that they should be shut out. Still there are so many reasons against
their ever being admitted, allowing they have souls, that I scarcely
know how to do them away as I could wish, out of the pity I feel for
this unfortunate part of the human race. You know we take a most
solemn oath in the Master's degree never to initiate women, idiots,
and the like; now if women cannot be initiated on earth, and it seems
to be a divine command that they shall not, for masonry is divine,
how can they ever enter heaven, which, I am persuaded is, as I said
before, all masonry, and the very perfection of masonry? But you don't
appear to pay any attention to what I am saying, Timothy,' continued
the speaker, looking round on the former, who had been, for some
time, engaged in slyly reaching one arm round back of their seat, and
pulling out of their chest a wet shirt, cravat, &c., and spreading
them out to the sun—`you don't appear—why! what in the name of the
Old Nick is all this?—when did you wet these clothes, Timothy?' The
latter blushed to the gills, and began to stammer out something about
bringing them from home in that condition.
"Come, come, Tim, none of your locklarums with me: you got them wet
in your last night's scrape, which by the way, as I was asleep when
you came in, I forgot to ask you about this morning.—Did you fall
into the brook while blundering about in the dark?"
`Worse than that,' whimpered the confused Timothy, finding it of no
use to attempt concealment.
"Worse than that!" exclaimed the other, "what, then, did you
stumble into some filthy ditch?"
`Worse than that,' again replied our hero.
"Worse than that!!" reiterated Jenks in surprise, raising his voice
to a sort of howl—"what the d—l do you mean, Tim?—speak
out—don't act so like a fool!"
`Why—I got up—to her window,' said Timothy, hesitating and
stammering at every word—`and I went to'—
Jenks here burst out into loud, continued peals of laughter, while
our hero hung down his head in silence till his companion's merriment
had measurably subsided, when he sheepishly observed, "I am glad you
are a Mason, Brother Jenks, because I know that now you will never
divulge this transacted dilemma."
Our travellers now pushed on rapidly, and about noon reached the
flourishing town of Troy—
"Place of the free Hart's friendly home,"
whose inhabitants they had heard possessed a sprinkling of that
gullible credulity which induced the luckless wights of its ancient
namesake to let the wooden horse into their renowned city. They
determined therefore to give Boaz an opportunity of making his debut
before a public whose cash and curiosity might qualify them to
appreciate his merits. But they reckoned, it seems, without their
host; for after sojourning in this place about twenty-four hours, and
offering Bruin for exhibition with all the recommendations they could
invent, they realized barely enough to pay their expenses. Finding
that there was but small prospect of making much out of the Trojans,
our travellers now proceeded down the river. At the capital they
paused only long enough to test the virtues of the Albany beef, that
great natural benefice of this famine-proof city, for the bestowment
of which I wonder the citizens in their gratitude have not raised from
the bottom of the river a monumental water-god a hundred feet high,
with something like the following inscribed on his head: Here hungry
wights, tho' oft their cake be dough, While Hudson rolls no
lack of beef shall know.
Proceeding diligently on their journey, they arrived about dark at
the city of Hudson. This night brought them a little piece of good
luck from a source on which they had hitherto placed but small
reliance: For putting up at an inn in the outskirts of the city, where
there happened to reside one of your comfortably funded single ladies,
who, having been in the post-meridian of life without receiving an
offer, long enough to give her the hypochondria, imagined herself in a
consumption, and, having dismissed all her physicians for blockheads,
was now on the inquiry for some specific for her fancied malady. Our
travellers, on learning this history of her case from her own lips
during their meal, began to bethink them of turning to some account
the bottled nostrums, which, as a forlorn hope, they had stowed away
in their waggon. Accordingly Jenks, after having listened to her
remarks and lamentations long enough to satisfy himself pretty well
how the wind set with her, enquired with apparent indifference, if she
had ever tried the celebrated medicine lately discovered in the
Eastern States which had cured so many consumptions.
She replied in the negative, and, with a countenance brightening up
with joy and excited curiosity, eagerly enquired where any of this
medicine was to be had.
On which, Jenks told her that he had charge of a few bottles which
had been sent by him to a gentleman in New York, one of which perhaps
might be spared; but so very valuable was this medicine considered,
that no one, he presumed, would be willing to give the price demanded.
This only inflamed the invalid's curiosity the more, and she became
very anxious to see this elixir of life. Jenks then, with some
seeming hesitation, went out and brought in a bottle, which, having
been ingeniously tinctured by the juice of the elder-berry, and
rendered aromatic by wild annis and the like, furnished a liquid both
agreeable to the taste and the sight; and turning out a small
quantity, he descanted largely on its virtues, and prescribed the
manner in which it was to be taken. Charmed by the taste and
appearance of the beautiful liquid, and her faith keeping pace with
her imagination in the growing idea of its sanative qualities, her
desire to possess it soon became uncontrollable, and she demanded the
price of the bottle. And, while the cautious vender was hesitating
whether it was his best policy to say one dollar, or two, she, taking
this hesitation for a reluctance to part with such a treasure,
observed she must have it if it cost ten dollars. This remark gave
Jenks a clue of which he was not slow to avail himself, and
accordingly he told her that ten dollars was just the price of one
bottle, which was considered sufficient to effect a complete cure in
the most obstinate cases. This she said was indeed a great price, but
still money was not to be put in competition with life. Thus
observing, she rose, and forgetting the cane with which she usually
walked, bustled out of the room. Jenks now began to fear that his
avarice had led him to overshoot his mark, and he regretted that he
had not set his price lower, as she had left him in doubt whether she
intended to become a purchaser. He had not however much time allowed
him for regrets; for his patient soon returned, and, planking ten
dollars, took possession of her invaluable medicine, and proceeded to
administer to herself the specified does on the spot. After this her
spirits soon became exhilarated, and she declared that she already
felt much better.
Faith will remove mountains, saith the Scripture in substance. I
have often considered how peculiarly applicable is this scriptural
sentiment to the case of those laboring under that, by no means the
least terrible of diseases, hypochondriacal affection. The poor
afflicted dupe, in the present instance, no sooner gave herself up to
the full influence of that wonder-working attribute, than she felt,
it would seem, the mountain rolling from her oppressed feelings.
The next morning, as our travellers were about to resume their
journey, she came to the door with the bright look and elastic step of
a girl of fifteen, and expressed the most unbounded gratitude to them
for having been the means of saving her life: She had not felt so well
for two years, and she was certain she should be entirely cured by
the time she had taken the whole bottle of her charming medicine.
Our travellers drove off almost holding their breaths till they had
got fairly past the last house in the city, when they began to
snicker, and soon to laugh and roar outright at the strange and
ludicrous manner in which dame fortune had been pleased to visit them
in this unexpected little piece of success. "I have often heard it
observed, Brother Tim," said Jenks, after his fit of merriment had
been indulged in to his satisfaction, "I have often heard it observed,
that mankind were always prone to measure the value of every thing by
the price that was attached to it; but I confess I never saw this
trait so strikingly exhibited before. Had I put the price of that
bottle at fifty cents, the old hypoey squab, I will warrant you, would
not have looked at it. Let us then take a hint from this affair for
governing our future operations."
They then fell to contriving in accordance with this suggestion;
the result of which was, that the same price, which they had just so
miraculously obtained, was to be affixed to each of their remaining
bottles of tinctured water. Their black-balls were to be cried up as
perpetual leather-preservers, at a dollar a piece; and Boaz was to be
passed off as some unknown animal, if possible, with terms for his
exhibition sufficiently high to comport with their new scale for the
graduation of prices.
After this weighty business had been well discussed and definitely
settled, they concluded it best to embrace every probable chance of
putting their scheme into operation. Accordingly they stopped at
almost every house on the road for the commendable purpose of
searching out the sick, and administering to their distresses. But
unfortunately it never fell to their lot to find any more cases of
consumption, either in fancy or fact, or any other disease indeed
that required the aid of any of their list of infallibles. With their
black-balls, however, they met with a little more success among the
Dutch farmers, who considered that the preservation of their shoes, so
that they might pass as heir-looms from one generation to another,
was an object by no means to be sneezed at, declaring, in their
honest credulity, "none but a Cot tam Yankee would have found out
dat." But with Boaz they found it impossible to succeed in this way.
At Poughkeepsie they spent one day, and Timothy made a learned speech
to the multitude to prove their bear an unknown and newly discovered
animal. But as soon as two or three had been admitted to the sight,
the game was up. Boaz was pronounced a bona fide bear as ever
sucked his claws. Whereupon, symptoms of a mob began to be among the
crowd. One fellow stepped up to and offered him half a crown,
observing, and to our hero instead of the bear, that he for one was
well satisfied that the creature was an unknown animal, and worth the
money for the sight, and concluded by asking where he was caught.
Others said something about those implements of the low and vulgar,
tar and feathers. In short, matters began to wear rather a squally
appearance.
Quoe cum ita sint—"since things go on at such a deuced
rate," thought our travellers, it is no more than prudent to be a
jogging. They therefore packed up their duds without further loss of
time, and took a French leave of these impertinent Poughkeepsians, who
were growing quite too familiar to suit their notions of genteel
intercourse.
The next day, while diligently wending their way towards the great
city, they came to a little village containing a tavern, store and
meeting-house, those three grand requisites of village greatness. Here
they stopped at the tavern for a little rest and refreshment. When
they were about to depart, Timothy stepped up to the bar, and offered
the landlord a small bank note out of which to pay their reckoning.
The latter took the note in hand, and, giving it a long scrutinizing
look, observed that he had some doubts about that bill; and at the
same time casting a glance of suspicion at our friends, asked Timothy
how he came by the paper. The latter could only say that it was handed
him by his friend Jenks, and Jenks affirmed that he took it on the
road; and although he knew it to be good, yet to save all dispute, he
would pay the reckoning in other money. Having done this, they
requested the landlord to deliver up the questioned bill; but he
declined, and said he should first like to know whether it was
counterfeit or not; and as there was a good judge of money in the
place, they would submit it to his inspection. To this Jenks demurred,
as causing them a foolish and unnecessary detention. But the
landlord, without beeding his remarks, sent out his boy for the
gentleman in question. In a few moments a little dapper, pug-nosed
fellow, with a huge cravat round his neck, reaching up over his chin
to his mouth, and looking as if he had been trying to jump through
it—while a large bunch of gold seals were appended to his waist to
keep the balance of his watch true, (provided he had one) came
bustling into the room swelling with the conscious importance of his
character as village merchant. "Here, Mr. Nippet," said the landlord,
reaching out the bill, "please to give us your opinion of that paper."
Mr. Nippet accordingly took the bill, and, after having squinted at
it side-ways and all ways with a severe and knowing air, laid it
down, and, with a tone that plainly told that there could be no appeal
from his judgement, pronounced it counterfeit. All eyes were now
instantly turned upon our travellers with looks of the darkest
suspicion; and not doubting the correctness of the decision of their
counterskipper oracle any more than a good Catholic would that of the
Pope, they already beheld our travellers, in imagination, snugly
immured within the walls of the Penitentiary. They, however, showing
the rest of their money, which proved to be good, and taking much
pains to convince the company of the honesty of their intentions,
succeeded so far in allaying these suspicions, that no opposition was
made to their departing. Nippet, however, who had preserved a
dignified silence during this process of examination & acquittal, now,
as they drove off, pulled up his cravat and said, "Dem me! if them are
fellers aint as prime a pair of Yankee counterfeiters as ever went
uncaged, I will agree to forfeit the best double-twilled looking-glass
in my store."
The effect of this malediction was soon manifested among the crowd
by eager inquiries for the village lawyer and the sheriff. But let us
follow our travellers, who, having got too far off from the scene of
action to perceive any thing of this new movement, were now quietly
pursuing their journey, wholly unaware of the storm that was brewing
in the village they had just left. Perhaps, however, I should not
omit to state that Jenks, for reasons best known to himself, often
cast an uneasy glance behind him, and as often put up old Cyclops to
considerable more than his wonted jog. After they had travelled about
two hours, and while passing over an uneven and woody country,
somewhere in the vicinity of `Sleepy Hollow,' that secluded region,
which would forever have remained in its own quiet and inglorious
obscurity, but for the classic pens of Washington Irving and the
author of these memorable adventures: the one having already rendered
it famous as the scene of the exploits of the immortal Ichabod Crane,
and the other now adding the climax of its celebrity by connecting it
with the masonic achievements of the no less immortal Timothy
Peacock,—while passing these regions, I say, the attention of our
trayellers was suddenly arrested by the clattering of hoofs on the
road behind them; and looking round, they saw a man riding at full
speed coming after them.
"What can that fellow want?" hurriedly exclaimed Jenks—"something
about that bill, I fear—I wish I had never tried the experiment of
putting"—
"You are the gentlemen, I conclude, with whom I have some
business," said the man, riding up and addressing our travellers, and
at the same time taking out a warrant, "you are the persons, I think,
who put off a certain bank bill at our village a few hours since," he
continued, motioning them to stop their horse. Here was a dilemma
inindeed! Our travellers were thunderstruck. But it was here, O
divine Masonry! that thy transcendant genius shone triumphant! Here
the omnipetence of thy saving and precious principles was displayed in
its true glory for the protection of thy faithful children! And it was
here thy supreme behest, in obedience to which, "Supporting each
other Brother helps brother," was kindly interposed between thy sons
in difficulty and the cruel and less sacred exactions of civil law,
and set the rejoicing captives free! Quick as thought our hero rose
from his seat, and looking the officer full in the face, made the
Master Mason's hailing sign of distress. The officer hesitated, and
seemed to be in great perplexity how to act. On which, Jenks, who had
been thrown into more confusion than Timothy, now regaining his
assurance in perceiving they were in the hands of a brother, also rose
and made another masonic sign to the officer which our hero did not
at that time understand. But its potency was instantly acknowledged by
a corresponding token, and its redeemnig efficacy as quickly visible.
"Here must be some mistake," said the officer, "no two persons in a
waggon have passed you on the road, gentlemen?" he continued, with a
look which seemed to say, we must invent some excuse for this.
`None whatever,' replied Jenks, fully comprehending the drift of
the question, `none whatever, but perhaps they were considerably
behind us, and might have turned off at a road which I noticed several
miles back, and which leads I conclude to some ferry over the Hudson.'
"Nothing more likely," rejoined the sheriff, "but to put the matter
beyond dispute, and enable me to give a safe answer to my employers, I
will ride on to the next house, and enquire if any travellers, at all
answering the description of the fugitives, have passed the road, and
if informed in the negative, I shall of course be exonerated from any
further pursuit in this direction. So, good bye, Brethren," he
continued, pointing to a thick wood behind a hill on the right, "good
bye—caution and moonlight will ensure a safe journey to the city."
So saying, he clapped spurs to his horse, and dashing by the waggon of
our travellers, was soon out of sight.
"Brother Peacock," said Jenks, "there is no time to lose; we must
drive out into the woods and conceal ourselves and team behind yonder
hill till dark." They then jumped out of their waggon, and taking
their horse by the head, led him out of the road into a partial
opening at the right, and picking their way through the bushes and
round fallen trees and logs, soon arrived at a situation where the
intervening hill cut off all view from the road, and where a small
grass plot and spring furnished an excellent place for halting and
refreshment. Being now in a place of safety, they unharnessed old
Cyclops, and gave him the last peck of oats now remaining of the stock
which they had brought from home. Our travellers now taking a seat,
Jenks proceeded to explain to Timothy, as far as his oath would
permit, the nature of the sign which he had made to the officer, and
which had so effectually ensured their escape from arrest. The token
he had used he said was the Royal Arch sign of distress, which no
Mason of that degree ever dare pass unheeded, whatever might be his
opinion of being bound to answer the Master's sign of distress in
circumstances like those in which they had just been placed. As to
the latter obligation, he remarked, there was a difference of opinion
among Masons,—some believing they were bound to afford relief,
protection or liberty, as the case might require, whenever the
Master's sign was made; others considering that this sign only
extended to relief in certain cases. Among the latter class, he
presumed, stood this officer, by his hesitation when this sign was
made, since he appeared to have no doubts what was his duty when he
saw the sign of the Royal Arch degree,—that sign which was never
known to fail a brother in distress,— that sign, indeed, whose
potency can palsy even the iron arm of the law—bid defiance to the
walls of the deepest dungeons, and rend the strongest fetters that
ever bound the limbs of a captive brother.
Timothy could not here refrain from bursting forth into the most
rapturous exclamations in praise of the glorious institution that
could effect such wonders. Its advantages, its value, and its
protective power, were now to him no longer a matter of hypothesis. He
had seen them exemplified. He had experienced their glorious fruits.
He blessed the auspicious hour that first brought the precious light
to his soul, and he resolved that he would never rest till he had
taken not only the Royal Arch, but every higher degree, till he had
reached the very summit of the Ladder of Jacob.
It was now about noon, and our travellers, beginning to feel the
demands of appetite, went to their waggon, and after making a pretty
heavy draft on their remaining stock of provisions, repaired to a
little bed of moss near a spring which was overshadowed by a large
chesnut tree, and commenced their sylvan meal.
"Brother Timothy," said Jenks, tossing a half-eaten biscuit in his
hand and giving a momentary respite to his masticators, "I have been
thinking about trying an experiment. You know you preached like a
philosopher there at Poughkeepsie to make them believe that Boaz was
no bear, but some strange and unknown animal, but failed to make the
fellows trust one word of all you told them; and for the reason no
doubt that when they came to see him with his long black hair, and
every way in his natural trim, their common sense told them that he
could be nothing but a bear. Well, as I was looking on to notice how
matters went, and hearing you talk with so much high learning about
the unknown animal as you called him, a thought struck me that if it
had not been for the creature's black coat, you might have made them
believe your story; and if he could be sheared or shaved, it would be
nearly all that would be wanting to make him pass for what you
cracked him up to be."
`What an ingenious contrivability!' excaimed the other. `Brother
Jenks, what a fundament of inventions is always exasperating the
dimensions of your perecranium! Who else would have ever cogitated
such a comical designment? '
"Now, Tim," continued Jenks, without seeming to heed the
exclamations of his companion, "we have all the afternoon before us,
as it will not do to start till dark, and I put a pair of sheers into
our chest, and several kinds of paint, thinking I might want them
perhaps to fix old Cyclops for market. So you see we have leisure and
tools—now what say you to trying the experiment of taking off the
bear's coat close to his skin, and otherwise fixing him as we shall
think expedient?"
`By all muchness and manner of means, let us condense the
experiment into immediate operation,' replied our hero, adding the
most sanguine anticipations of its success.
The project was then discussed in all its bearings, and becoming
more and more confirmed in the opinion that it must succeed, the
projectors rose for the purpose of patting it into execution without
further delay. It was arranged that Timothy should take a bag, and
going out of the woods to the back side of an orchard which they had
noticed about half a mile back, procure a quantity of sweet apples to
feed Boaz and make him more quietly submit to the operation; while
Jenks was to remain behind and make all necessary preparations for the
performance.
Accordingly, Timothy steered off with his bag, and the other
proceeded to get out his old shears and sharpen them upon a piece of
slate stone, then to prepare his shaving tools with which it was
proposed to go over the animal after shearing by way of putting on the
finish to the work; and finally to get out poor Boaz, the unconscious
object of these preparations, who little dreamed that his masters
were about to deprive him of the only coat he had to his back, and
that too when cold winter was rapidly approaching.
By the time these preparations were completed, Timothy came
staggering along over the logs under a load of nearly two bushels of
apples, and reaching the spot, threw them down at the feet of his
companion.
"Stolen fruit is sweet," said Jenks, taking out and tasting several
of the apples, "this makes the Scripture good; for I never tasted
sweeter apples in my life."
`I declare to Jehoshaphat and the rest of the prophets,' said
Timothy, `the idea never once entered my conscience that I was
breaking the commandments by taking these apples without the liberty
of licence.'
Jenks now perceiving the uneasiness that his remark had caused his
too scrupulous friend, at once relieved his feelings by telling him,
in the language of the Jesuitical Fathers, whose learned and logical
reasoning bears so striking a resemblance to that of masonic writers
in support of their institution, that, as he was calculating to
devote his share of the avails of their project to the study of
masonry, whatever was done in furtherance of so noble an object could
not be blameable; for the end always justified the means, and
therefore this act which appeared to trouble his mind so
unnecessarily, was in fact a virtue instead of a crime.
They now proceeded to the shearing operation—one plying the
shears, while the other slowly administered pieces of apples to the
animal, and thus kept him quiet during the performance. In about an
hour they completed this first part of their task, having deprived
Bruin of the whole of his sable wardrobe as far as it could be
effected with shears. Next was the more difficult and tedious process
of shaving. They beat up a large supply of lather, and diligently
betook themselves to this novel exercise of the barber's profession.
This part of their undertaking proved indeed to be a slow and
troublesome business. But Boaz, either because he was conscious of the
important objects which the operation involved, or because the razor,
in passing over his skin, produced, by its light and gentle friction,
those pleasurable sensations which are said to be so highly
appreciated in Scotland as to lead to the erection of rubbing-posts in
that country, bore up through the whole with the patience of a
philosopher, and, with the exception of a little wincing and snapping
as occasionally the razor happened to graze the skin, suffered the
operators to complete their task without offering the slightest
opposition. This process being at length finished, they smeared over
his skin with some light paint mixed with earth so as to give him an
ashy appearance.
"There Boaz!" exclaimed Jenks, laughing at the comical appearance
of the animal, as he stood before them completely metamorphosed, his
body as smooth as the head of a shorn Carmelite, and his whole figure
comparatively as light and spruce as a Broadway dandy, and with organs
of ideality quite as well developed, (though with a little more
destructiveness to be sure,) "there Boaz, if you wont betray us by
your bearish breeding, we may defy the Old Nick himself to discover
your true character."
It was now past sunset, and the deepening shadows of evening
beginning to fall thick and fast into the deep glens of the highlands,
reminded our travellers that they might soon depart in safety.
Accordingly, having harnessed their team, and wrapped their shorn
friend in an old blanket, to compensate him for the loss of his
natural covering, they retraced their way to the road by the last
lingering gleams of the fading twilight, and immediately commenced
their journey at a pace which seemed to indicate a mutual impatience
between horse and owners to bid adieu to this part of the country
with as little delay as possible. Passing rapidly on and meeting with
no molestation, they travelled till about midnight without stopping;
when observing a field of unharvested corn beside the road, they
halted, and borrowed a quantity of ears sufficient to furnish old
Cyclops with a good supper. Having rested here about an hour, they
again put forward and drove with the same speed and diligence for the
remainder of the night; and such was their progress in this nocturnal
journey, that, as the rising sun began to gild the tops of the distant
mountains, they entered the great city of New-York, having travelled
in about twelve hours of hazy moonlight nearly forty miles without
but once halting.
[4] A term used for Sturgeon, caught in great plenty near Albany.
CHAPTER XI.
"Lobsters are not fleas, damn their souls."
Peter Pindar, for Sir Joseph Banks.
New-York!—London of America—vast depot of the agricultural
riches of the West, and the proud haven into whose open and welcoming
bosom the winged canvass, laden with merchandize, comes drifting from
every clime before the four winds of heaven! City of fashions!—whose
hundred sacred spires rise over congregations there weekly assembled,
punctual to the dictate of this fickle goddess, who is even there
presiding mistress of the ceremonies! Congregations whose devotions
would be disturbed by the appearance of one coat out of date—whose
feelings would be shocked by the sight of one ribbon too much or too
little in a dress, and whose sensibilities would be thrown into agony
by the daring intrusion of one unfashionable bonnet! City of puffs and
exaggeration! where there is no medium— where every thing —"Is
like to Jeremiah's figs,— The good were very good—the bad not fit
to give the pigs." Where literature, if fashionable, is celestial—if
not, damnable.— Where an author becomes at once a Magnus Apollo
, or a dunce.—Where every thing is cried up to the clouds, or
hissed into infamy.—Where every performance or exhibition, of
whatever kind or character, is all the go, the rage, the roar; and the
exhibitors or performers are received with shouts of applause,
clapped, encored, honored, worshipped; or spurned, hissed, spit at,
and mobbed from the city.—Where every thing, in short, goes by steam
on the high pressure principle.—Where every thing is done in a
fury, a whirlwind; and where those who would succeed must raise the
wind to the same pitch and power of the surrounding tempest, and ride
fearlessly on the gale; for if they fall short of this, or pause one
moment to resist the current, they are overthrown and trod and
trampled under foot by the rolling mass of life, and lost forever!
Jenks had several times before been in this city, and having
noticed the peculiarities of the place, and learned how things were
done there, and concluding withal that whatever was done, "it were
better if it were done quickly," now shaped his course accordingly.
Near the centre of the city stood a livery stable with a capacious
yard which the owner, whom I shall call Stockton, had been accustomed
to let to the keepers of caravans for the exhibition of their
animals. This Stockton being a masonic acquaintance of Jenks, the
latter, on arriving at the city, immediately drove to his stand, and
as his yard was then luckily unoccupied, found excellent
accommodations for the intended exhibition of Boaz. Having for a
reasonable sum obtained these accommodations, and seen Boaz safely
locked up in the high enclosure which constituted the exhibition
room, Jenks immediately went in search of a painter to take a full
sized portrait of his Bruinship to display for a sign, while Timothy
was despatched to a printing-office to get a hundred or two of
handbills struck off describing Boaz as the new and wonderful animal
lately caught in a cave among the Green-Mountains, and setting forth
the time, place and terms of his exhibition. The painter with his
implements, and a large piece of canvass, was soon on the ground, and
after wondering awhile over this strange subject for his pencil,
diligently proceeded to the task of taking his likeness. While these
things were doing, Jenks and Timothy took the opportunity of dressing
before they made their appearance before the public, and of taking
their dinner. After which, at the suggestion of their friend,
Stockton, they employed an old ex-officio crier, remarkable for the
power of his lungs, and the aptitude of his hyperboles,to distribute
their handbills and cry up Boaz in such manner as he thought best
calculated to catch the attention of the multitude.
By three o'clock in the afternoon, every thing was prepared for
this wonderful exhibition. The painter had completed his task, having
given a rough, but striking picture of Boaz standing on the limb of a
tree, about to spring upon a deer that was making his appearance in
the bushes below; and the handbills having come, `Thundering Tom,' as
their new crier was called, had already begun his work of distributing
them, making the very pavements tremble as he passed along the
streets, crying with stentorian voice the exhibition of the "new!
strange!! wonderful!!! and unknown animal!!!! caught in the
Green-Mountains!!!!!"
"Now Brother Tim," said Jenks, "it is neck or nothing with us. It
will be no half-way business here. Our pockets will be filled with
cash before to-morrow night, or our backs will be tarred and
feathered, just according as how the thing takes; but we must act our part well or all is lost to a certainty. I have done the
contriving, and you must do the talking, Tim: You have learning, and
can philosophize and explain to the visitors. But mind you, Tim, if
you get up any wonderful stories about Boaz, be careful not to cross
yourself by telling different ones, especially till a new set of
visitors come in, and you are sure that all those who heard your first
story are gone. And above all, Tim, be very careful that you don't let
the cat out of the bag."
After these hasty injunctions, Jenks, with a heart palpitating with
the mingled emotions of hope and fear, went out and took his station
at the door. It was obvious that public curiosity had been awakened,
and that the wind was now fairly raised. A crowd was already collected
round the door, gazing at the picture, and listening to the marvellous
stories that Thundering Tom, who having gone the rounds in
distributing the handbills and returned, was now administering to them
by wholesale. As soon as Jenks made his appearance, they became
clamorous for admission— when he nothing loath, though trembling at
the uncertainty of the result, threw open the door, and, as fast as
he could pocket the half dollars, (fifty cents being the terms of
admission) let in the eager multitude. This was a moment of intense
anxiety to our travellers, wholly uncertain as they were, what
impressions would be produced by the first sight of Boaz—whether he
would maintain his assumed character, or whether detection and its
supposed consequence, a mobbing, would immediately ensue. They were
soon relieved, however, from all apprehensions of any trouble at
present, by the concurrent voice of the visitors, who after carefully
examining the monster round from head to tail, all broke out in
exclamations of wonder and admiration at the appearance of this
singular animal, and declared themselves highly gratified with the
sight. Timothy now believing it was time for him to take a part in the
scene, proceeded to relate to the gaping crowd the manner of taking
the animal, which he said was effected by a steel-trap that he and his
companion had set near a small lake surrounded by woods and mountains,
where they had observed the creature's tracks, which they took for
those of a catamount. And on going to the trap the next day, they
found it was gone, and the stone to which it was chained, weighing
about five hundred pounds, had been dragged off with it. Following the
track which was plainly marked by the trap and stone, they pursued on,
and soon came to a young deer with his throat torn open, lying dead
beside the way; and knowing that the animal must have caught this
deer before he got into the trap, and carried it so far where he had
dropped it owing to his failing condition, they followed on now
certain of soon overtaking him. After going about half a mile, they
found he had gone into a dark and frightful cavern in the side of a
steep mountain. They then raised a band of hunters, and went in with
torches, and after incredible difficulty and danger, they succeeded,
with ropes, in taking the monster alive, and tying and muzzling him
so securely that they got him home; and after taming him as much as
his ferocious nature would admit of, they had now brought him to the
city to let the people see him and find out from the learned men what
animal he was.
This account still increased the general wonder, and the ferocious
character which Timothy had given to Boaz was now confirmed by his
present appearance; for owing to the soreness produced by the shaving,
and the jolting of his rapid ride immediately after, he was unusually
cross and snappish, and kept in one continual snarl as the visitors
punched him with their canes through the railing within which he was
chained.
Various were the conjectures as to what kind of animal he could be;
and many the sage remarks that were uttered on the occasion. One
thought he must be some relation to the elephant—a kind of Tom Thumb
elephant, he said, since he knew of no animal of the four-footed kind
but what had hair except the elephant and this monster; and asked if
there were not a small kind of elephants somewhere in a country called
Lilliputia, where, as he had read in some history, all the animals
were excessively diminutive: Another said he had been to see all the
caravans that ever came into the city for twenty years, and he had
seen all the animals in the world, he believed, except the unicorn,
which he never could happen to come across, and according to the idea
he had formed of that animal, he thought it must be very like this
monster, and he rather expected the same thing: And yet another, a
spruce and intelligent clerk from Broadway, observed, that he was
perfectly satisfied what the creature was—it was one of that class
of animals called non-descripts, found in great numbers in Siberia and
other parts of the torrid zone: he had often heard Doctor Mitchel, in
his lectures, speak of the animal; though he did not know before that
any of this class were ever found in America; but he was not at all
surprised that they should be discovered in such a cold, rough and
desolate wilderness as the Green-Mountains.
These and a thousand other observations of the kind were made by
this, and each succeeding set of visitors that were continually coming
and going in great numbers for the whole of the afternoon and
evening—during all of which, Boaz maintained his character of an
unknown animal unimpeached; and notwithstanding the most rigid
scrutiny and learned inspection, which he was constantly undergoing,
all except the learned Broadway clerk, gave up that they had never
seen or heard of the like of him before, and that he was truly an
unknown animal, and a great curiosity.
Thus went matters gloriously on for our travellers till nine
o'clock in the evening, when, although the crowd seemed rather to
increase than diminish, they were forced to close the exhibition and
shut up for the night. As soon as they were alone and all still
without, they fell to rejoicing over their good fortune, and counting
their money, which to their agreeable surprise amounted, from the
receipts of the exhibition alone, to something over three hundred
dollars. Jenks' eyes glistened like stars in a frosty night: and
Timothy snapped his fingers and capered about the room like a mad-man,
uttering a thousand extravagancies. Concluding to sleep on blankets in
an apartment in the building adjoining the exhibition room, and
communicating with it, that they might better see to the safety of
Boaz, it was arranged that Timothy should now go to some neighboring
victualling-cellar for some provisions for their supper, while Jenks
went to one or two printing-offices to get a notice of to-morrow's
exhibition inserted in the morning papers. This business finished, and
the parties having returned, they now sat down to their meal spread
on the lid of their travelling-chest, and recounted, with great glee,
the many little incidents that had fallen under the observation of
each during the hours of exhibition. "But Timothy," said Jenks, after
they had indulged a while in dwelling on the scenes of the afternoon,
"Timothy, I fear me that this run of luck can't last long: This
afternoon and evening we have had scarcely any to see Boaz, as I
observed, but the more ignorant class; and although many of them were
dressed so neat, they were mostly lounging dandies, and merchants'
clerks, that havn't three ideas above a jackass, except it is about
the business behind their counters. But to-morrow, as this thing gets
more noised through the city, we may expect more knowing company. And
when those prying lawyers, and doctors with their glasses, come
examining and squinting about Boaz, then we may look out for breakers.
And at the best, I have little hope of keeping up the farce beyond
to-morrow night, as the hair on his back will begin to start so as to
be seen by the next day at farthest; and I don't suppose that he would
let us shave him again, as he is so sore and cross with the effect of
the last operation. Now I have been thinking that we had better be
prepared for the worst; so if a blow-up should happen, we shall have
nothing to do to prevent our leaving the city at a moment's warning.
I think we had better sell our horse and waggon if we can do it to
advantage; for if any thing should happen, we can get away better
without our team than with it; and if there should not, we can never
do better with Cyclops than here; besides, if we sell out and go home
by water, we shan't have to pass through that blackguard village where
they made such a fuss about that bill. And as to Boaz, we can leave
him with Stockton to sell for us."
Timothy agreeing to these propositions, it was decided that Jenks
should go out next morning before the hour arrived for opening the
door to visitors, and taking Thundering Tom along to assist him,
should try to find a sale for the team. This being settled, they began
to prepare for sleep. The cautious Jenks, however, did not lay down
till he had searched round the yard and building and found a window
through which they might retreat into a back alley and get off, in
case a mob should attack them. After this, they wrapped their blankets
round them, and laying down on the floor, with their coats for
pillows, were soon lost in slumber.
Bright and early the next morning our travellers aroused themselves
from their golden dreams, and harnessing up old Cyclops, and going out
and getting Thundering Tom, the latter and Jenks drove towards the
lower part of the city to find a sale for the establishment, leaving
Timothy to feed Boaz and prepare for the coming exhibition. As luck
would have it, while on their way they came across a man whose horse
had just taken fright, and, running against a stone post at the corner
of the street, had dashed the waggon to which he was harnessed into a
thousand pieces, and broke and torn the harness so as to render it
wholly useless for the present purposes of the owner, who now stood
over the ruins, lamenting his misfortune, which was the greater he
said as he was compelled to return immediately into the country with a
small load, while he had not enough money to pay for a new harness and
waggon, and he did not suppose he could get any other without
considerable delay. Jenks having halted and heard the man tell this
story, at once offered to sell his own waggon and harness on the most
reasonable terms; and as the man was as eager to buy as Jenks to sell,
a bargain was soon concluded to the satisfaction of all parties. It
now only remaining to dispose of old Cyclops, Jenks then proceeded
onward, leading him with a halter, while Thundering Tom took a
parallel street for the purpose of inquiring out a purchaser. In a
short time, however, the latter came puffing along after Jenks, and
overtaking him told him he had just learned that the master of the
Jersey horse-boat wanted to purchase a horse, and he had no doubt but
old Cyclops would suit, as eyes or no eyes it was all the same for
that business, provided the horse was stout enough. "But," said he,
"I think you had better leave the management of parleying with the old
fellow to me: I know him well, and what is better he don't know
me,—a free, bold speech, and a price that will do to fall upon, is
all that is wanting for your success."
With quickened pace they then took their route to the ferry. They
no sooner had arrived at the landing than they called out for the
master of the boat, which had not yet commenced its trips for the day.
Presently an old thick-set, rough-looking fellow came swaggering along
towards the stern of the boat, and demanded what they wanted.
"A horse to sell, your honor—just from the country— dog cheap!"
replied Thundering Tom.
`What are his points and bottom?' asked the master.
"He will trot you," said the other, "he will trot you, Sir, to the
New Jerusalem in three hours!"
`But I want one,' said the master, `that will trot slow— not
fast.'
"Well then," replied Tom, "my horse will trot as slow as common
horses will stand still!"
`You are a musical fellow,' said the master—`I will come out
there and look at your horse—Sound?'
"As a roach," replied Tom, "except an eye that he let a catamomount
have one day to pay him for a broken skull."
`You lie like the devil,' said the other—`nevertheless, I like
your horse: What is your price?'
"One hundred dollars," replied Tom.
`Hundred satans!' exclaimed the master: `however, put that
red-headed woodpecker of yours on to him,' he continued, pointing to
Jenks, whom he evidently took for a servant of Tom's, `and let us see
him move. I will give seventy-five if I like him as well as I think I
shall.'
Jenks now biting his lip in silent vexation at this taunt on his
personal appearance, mounted old Cyclops, and rode back and forth some
time,—after which, and considerable bantering, the bargain was
struck at seventy-five dollars, when Jenks and Thundering Tom returned
to their lodgings, chuckling at the thought of their good bargain; for
the former had instructed the latter to take fifty dollars if he
could get no more. Jenks now giving his companion ten dollars for the
great assistance he had rendered him in this sale, and in getting Boaz
into notice, now dismissed him, and returned to Stockton's to tell
Timothy of his unexpected luck in disposing of their establishment so
well and so quickly.
At nine o'clock, Boaz having been well fed, and then switched into
a suitable degree of soreness and ferocity, and Timothy instructed to
keep a bright look-out for squalls, Jenks took his post and opened the
exhibition. The morning papers had been distributed over the city, and
given notice of the exhibition to the more domestic and retired
citizens. And this, with the floating rumors that they had heard the
evening before from the rabble in the streets concerning the strange
animal for show at Stockton's, so inflamed their curiosity, that they
soon came flocking to see him. Among these, a band of that class which
is called the cream of society, being made up of the wealthy, and
those at the same time distinguished by family, having made their
appearance with their wives and daughters, one of them, after
examining the animal a few minutes, asked Timothy if Dr. Mitchel had
been to see the monster. And being answered in the negative, he, with
several others, proposed going after the Doctor immediately, as he
could at once settle the question whether the creature was an unknown
animal or not. So saying, two of the gentlemen went off in quest of
the great walking library of New-York, leaving their daughters to
remain till they returned. The latter, freed from the restraint which
they felt in the presence of their fathers, soon manifested a
disposition to make the most of their liberty, and began to quiz and
question our hero, whose good looks and ruddy cheeks seemed to
attract their notice. One asked him whether his sweetheart did not
cry when he came away—another whether the girls in the
Green-Mountains rode side-ways when they rode horseback; and whether
they worked in the field with the men ploughing and reaping: And a
third asked him whether they had meeting-houses and state-houses in
Vermont. To all these questions Timothy made gallant answers, lugging
in some compliment on every occasion. One of these fashionables of the
cream at length seeing an opportunity when the rest had moved off to
one side of the apartment to listen to some discussion going on there,
approached close to our hero, and asked him in a half whisper if he
should know her in the dark. "Only by that breath of Arabian
perfumery," he replied. `O you rogue, you must not know me by any
thing; so you wont find me to-night at Mrs. — assignation house, —
street, No. —, precisely at 8 o'clock,' said she, tipping him a
wink, as she twirled off talking loudly about the strange animal. In
a few minutes more another made a kind of circuit round the room, and
passing near him, dropped a small piece of paper into his hand, and
scarcely had he put away the first before another billet was dropped
at his feet as a gay lass brushed by him, saying she was going to peep
out the door to see if papa was coming. Timothy was rather at a loss
what to make of all this; and he took the first opportunity to inspect
the billets; and on reading them, he found to his surprise that that
they both named places and a time of meeting him. "What can this
mean?" thought he—"a second act of the play of that Dutch trollop on
the road? or have I at length got among ladies that are capable of
appreciating my character?" Every thing, as he looked round on the
rich and fashionable dresses of these ladies, conspired to tell him
that the latter must be the case, and he pulled up his cravat and
stepped about with an air of manly dignity which showed that he
considered justice was done him. While Timothy was absorbed in these
pleasing reflections, the citizens returned in company with the Magnus Apollo of the city. Jenks, who had over-heard enough to
learn that some one had now come who was a great critic about animals,
felt rather uneasy when the Doctor went in, and even Timothy was not
altogether without apprehensions when he saw the learned man
scrutinize Boaz so closely. Taking out paper and pencil, the Doctor
proceeded to make minutes—speaking or humming over to himself as he
wrote, "Strange animal—caught among the
Green-Mountains.....Appearance—entire destitution of the capillary
characteristic, short, thick and swinish..... Habits—cynic and
irascible.....Food—`what does he eat, Sir?' said the Doctor, looking
up at Timothy— `Flesh and fruit,' replied the latter, somewhat
overawed by the presence of the great man—`He was caught when he
had just killed a deer, and we have fed him on apples and such kind
of viands'—"Apples, viands! "hastily interrupted the other—"The
carneous and pomaceous are distinct and disconnected; but ah! I
understand now—it was the deer that you meant by the appellative of
viand; but to the animal—wonderful! carniverous and pomiverous," &c.
&c. He then examined Boaz over, and asked Timothy a thousand
questions about him—after which, he recapitulated his notes, and
pronouncing the animal a non-descript in natural history, he gave his
cane a twirl, and saying "I will drop a line to my friend of the
Journal at Albany concerning this valuable discovery," bowed
gracefully to the company and departed.
No sooner was the decision of the great oracle of the city
promulgated, than hundreds came crowding to see the non-descript, as
he was now termed. Among the rest the Broadway clerk came in to boast
of his sagacity in discovering the name of the animal even before the
Doctor had seen him. Nearly all day nothing was heard or talked of in
the city but the non-descript at Stockton's. The street leading to the
place of exhibition was thronged by one continual stream of visitors,
eager to get a sight of the lion of the day. Timothy and Jenks
pocketed the money in handfuls, and began to think they were made
forever. But alas! who can count on the continuance of the favors of
the changeful goddess of fortune! Our travellers were now doomed to
experience in common with all others the effects of her fickleness and
caprice. Towards night, while yet reaping the golden harvest, and now
lulled into security by their unexpected and unparalleled success, all
their prospects were ruined in a moment by the sagacity of a
New-England drover, who, having been a hunter in early life, and now
being in the city and hearing of the wonderful animal, had stepped in
to see what it was. After this man had leisurely surveyed Boaz awhile,
he all at once started up and exclaimed, "a shaved bear, as I live!"
The words no sooner struck the ear of Timothy, who happened to be
standing near, than he sprang before the man, and made a masonic
sign—the drover luckily was a Mason, and returned the sign. Timothy
then very appropriately made the sign of the Secret Monitor's degree:
This was also understood and heeded; for the man curling his lip with
a suppressed smile, left the room in silence. Timothy immediately
stepped to the door where Jenks was still keeping his post, and
taking him aside informed him of the occurrence, and its fortunate
termination through the instrumentality of their beloved institution.
"O blessed masonry!" exclaimed Jenks.
`Yea, blessed—thrice blessed and celestially glorious!' responded
Timothy—`without this sanctified salvation of savoring salubrity, we
should have been twice disembogued since we left the land of our
depravity; but we have triumphed over all, and are now safe.'
"Be not too confident of that, Brother Timothy," said the
other—"are you sure that no one of the visitors heard this man's
exclamation of shaved bear?"
`I declare!' replied Timothy, dropping the elegant, for the more
common mode of expression, as he was wont to do on most business-like
occasions—`I declare, I never thought to see to that.'
"Go in immediately then," said Jenks, with much trepidation— "see
if you can discover any symptoms among them that look like trouble—
any winks and whispering. Tim, I am afraid we are ruined after all! I
am glad it is almost night. O, if we can get through this day!" he
continued, letting his voice fall into a low ejaculating kind of
soliloquy, as Timothy hastily left him for the exhibition room—"If
we can outlive this day, they shall never catch me in this hornets'
nest again till the day of pentecost."
On Timothy's return to the show-room, he soon perceived enough to
convince him that Jenks' fears and apprehensions were not altogether
groundless. A midshipman, it seems, had overheard part of the drover's
exclamation, and, having closely inspected Boaz with his quizzing
glass during Timothy's absence from the room, and discovered the
hairs just beginning to start through the skin, came to the same
conclusion that the creature could be nothing but a common bear with
his hair shaved off. And keeping the discovery from the public for the
purpose of reserving the frolic of punishing the hoax to himself and
his companions, he was now, as Timothy came into the room, whispering
with one of his fellows to whom he had just communicated the secret,
and conferring on the best mode of kicking up a row on the occasion.
The wicked looks of the two fellows as they stood in one corner
engaged in a close conversation, occasionally glancing their eyes from
Boaz to Timothy, at once convinced the latter that they had mischief
in view which was intended for himself and Boaz; and accordingly he
kept a close watch of their movements.
After whispering awhile, these two fellows went out, and Timothy
began to hope he was mistaken as to their intentions. But he was not
long left to console himself with such reflections; for they soon
returned with two other companions, when all, as if to remove all
doubts as to the identity of Boaz, fell to scrutinizing him anew with
their glasses. While they were thus engaged, Timothy's quick ear
caught parts of sentences, as one of the two who came in last was
whispering to the other—"D—n me for a lubber, if Tom an't
right—I've seen many a bear in cruising— no mistake—let's get
under weigh—no time to lose," &c. Soon after this they all four
stole out of the room as slyly as possible, and went off into the city.
Timothy lost no time in informing Jenks of all he had seen. The
latter on hearing this account, was at no loss in coming to the
conclusion that these fellows, whom he had himself noticed with
suspicion, had gone off to raise a band of their companions for a mob.
And he told Timothy that their only chance now was to clear out all
the visitors as quick as possible, and lock up the exhibition-room.
This measure being concluded on, Timothy went in and informed the
company that they wished to close the exhibition for a short time, and
that those who wished to examine the animal any further could have an
opportunity in the evening. But the company were slow in obeying the
order—some said they could not come again—others they had paid
their money and had a right to stay as long as they pleased; and all
seemed to think that no harm would be done by a little delay. What was
to be done? Any appearance of impatience on the part of the keepers
might create suspicion. Jenks stood on thorns as he witnessed the
dilatory movements of the company dropping off one by one at long
intervals. He could have pulled them out by their necks in the agony
of his impatience to see them gone; but he was afraid to manifest the
least uneasiness. As no new ones, however, were now admitted, the
number of those within gradually diminished; and finally, all but two
or three took their departure. Just at this time Jenks heard a
distant hum like that of an approaching multitude. He instantly called
Timothy and told him to clear the room with the utmost despatch. It
was some time however before the latter succeeded in getting the two
remaining visiters started, as one was telling a story in which he did
not like to be interrupted till he had got through. Meanwhile the
clamor and noise appeared to be rapidly approaching; and the yelping
of dogs could be distinguished among the other sounds that now began
to swell loudly on the breeze. Jenks could stand it no longer, and was
about rushing into the exhibition-room to drive the remaining
loiterers out by force, when he met them coming out. No sooner had the
feet of the hindmost of these passed out of the reach of the door,
than, swinging it to as if he considered life or death depended on the
act, he hastily locked it, not however till he had caught a glimpse of
the enemy in full force rushing into the yard. In a moment they were
at the door thundering for admittance. Our travellers paused an
instant to listen to the exclamations of the besieging multitude. "Is
the tar and feathers come, Jack?" said one voice. "Send off for more
dogs," said another. "Bring along the rail," cried a third. "Beat down
the door—what's the use in puttering?" exclaimed a fourth.
Timothy and Jenks waited no longer, but hastily tying up the
contents of their chest in their pocket-handkerchiefs, they began
their retreat through the window in the rear, which, as we have before
mentioned, the prudence of Jenks, had provided as a retreat from
danger. They had scarcely let themselves down on the other side before
the door of the exhibition room flew from its hinges before the bars
and axes of the assailants, who now rushed tumultuously into the
room. "Damn my eyes, Tom, the knaves have escaped!—but here is the
bear," exclaimed one. "Let him loose! turn him into the street! call
up the dogs!" said several. "Look in that back room," cried the first
— "the fellows can't be far off, for I saw one of the damned
rascals just retreating into the door as we hove in sight." Such were
the consoling sounds that fell on the ears of our travellers as they
were making their way with all convenient speed over fences, through
back yards, gates, &c. into a dark alley that led out to a street on
the opposite side of the square—still pursuing their way with hot
haste they paused not til they had got two squares between them and
the scene of action. Here, just as they came out into a long street,
their ears were saluted by the mingled din of the voices of dogs and
men, and looking in the direction of the , they saw Boaz crossing the
street but one square from them upon the keen skip with a troop of
dogs of all sorts and sizes at his heels, filling the air with the
discordant cries of pup, cur, bull and mastiff, commingling with the
shouts of the mob pushing on hard behind them. All at once Boaz made a
halt in the middle of the street and turned with terrible fury on his
four-footed pursuers. Immediately the last dying yelp of some
luckless cur sent up quivering in the air by the teeth of the enraged
Bear, the bass groan of the bull dog coming within reach of his loving
embrace, and the death screech of others, announced to his old masters
that their ursine companion was not idle. While Jenks and Timothy
stood witnessing with exultation the gallant exploits of Boaz, the
whole pack of dogs, as their masters came up and encouraged them by
their presence, sprang at once upon the poor animal. A tremendous
struggle now ensued, and many a dog paid for his temerity by the
forfeit of his life before their dread antagonist yielded up his
breath and fell beneath the overpowering numbers of his foes.
"There is the last of poor Boaz!" said Jenks with a sigh; "but he
has died like a hero!"
In ten minutes from this time our travellers were on board a sloop
which they fortunately found at the wharf getting under weigh for
Albany. The breeze sprang up, and with the fading twilight the sight
and sounds of the receding city slowly melted in darkness and silence.
CHAPTER XII.
"Help, muse, this once, we do implore,And we will trouble thee no more."
Hudibras improved.
It was a pleasant autumnal morning, and the sun shone warmly and
brightly down into that stupendous chasm of the Highlands, through
which the majestic Hudson is forever rolling his vast column of pure
and uncontaminated waters, the accumulated tribute of a thousand
hills, to cool and freshen the turbid bosom of the briny ocean. On the
deck of a sloop moored at a landing near this picturesqe spot two men
were now to be seen sitting, like tailors, with something between them
on which they appeared to be intensely employed; while the sounds of
axes on shore, and the appearance of several men throwing wood towards
the vessel, denoted that she had hauled up at this place to take in a
quantity of that article, and that all the crew, except the two
persons just mentioned, were now engaged on shore for that purpose. Of
these two last named personages, one was a dumpy looking fellow of the
apparent age of about thirty-five, with red hair and a freckled face.
The other was evidently much younger, tall and well formed in his
person. His hair and eyes were black; and indeed he was every way as
remarkable for his fine, as his companion for his insignificant,
appearance. After they had been thus busily engaged awhile the younger
one, suddenly springing on to his legs, bounded several feet from the
deck, snapping his fingers and exclaiming, "Nine hundred and
forty-four odd dollars! O thunder and bombs! O lightning! two
lightnings! O Jupiter and Jeremiah! Nine hundred and forty-four odd
dollars! What shall we do with it all? Upon my sequacity I did not
dream there was so much. O Nebuchadnezzar and the rest of the
patriarchs, what a tornado of effulgent fortune has befel us! Hurra!
Huzza! kick over the chairs—raise Ned, and break things!" `Come,
come, Tim,' said the other, who, though partaking largely in the
raptures of his friend, seemed less enthusiastic in the manner of
expressing them, `come, Tim, you are out of your senses. They will
observe you on shore, if you crack and crow at this rate. Come, sit
down again, and let us divide this windfall according to agreement;
and then we will talk over other matters.' The parties were soon
again seated with the glittering heap between them, and with a sort of
suppressed chuckling, and eyes beaming with exultation and delight,
proceeded to the task of dividing the booty. This pleasing employment
was at length satisfactorily completed; and each one gathered up his
portion, and, carefully tying it up in an extra cravat, deposited it
in his bundle.
"Now, brother Timothy," said the elder, "what do you propose to
drive at by way of laying out your money? I believe," he continued
without waiting for a reply, "I believe I shall go directly home and
pay off the mortgage on my place. I shall have money enough now to
square off every thing to the last cent, and have some odd change
left, I guess. Gemini! who would have thought of such thumping luck!
By George! I'll get the old woman a bran-fir'd new calico at Albany,
and the boys a bushel of fishhooks. Lord! how the little devils will
grin and snap their eyes when I get home!—and the old woman—Tim,
I kinder like the old creature, after all, if she does raise a
clatter about masonry once in a while.—But as I was saying, what
are you going to do?"
`Why, as to myself, brother Jenks,' replied Timothy, `I have been
thinking that I should make some tarryfication at Albany; and, if I
can get in with the brethren there, I shall take the higher degrees of
masonry, and perhaps attend to the great study of the forty-seven
Euclids, mentioned in our lectures.'
"You are right, brother Timothy," said the other, "you have now the
lucre to enable you to perfect yourself in the great and noble art of
masonry; and I advise you by all manner of means to attend to it. I
have a masonic friend at Albany who will introduce you into his lodge.
If I had your gifts, Timothy, I would be a great man. When I proposed
to you to join me in this expedition to New York, I knew what your
appearance and gifts of speech would do. I can contrive as well as the
fattest of them, but hang me, if I can argue. You see how cutely I
planned out this show business of Boaz which has lined our pockets so
handsomely. And for all that you remember how they all always seemed
to look and listen to you to explain and expound matters—and how all
the ladies gathered round you, while me, the main-spring of the whole,
they would scarcely notice at all. It makes me mad when I think of
it. But blast 'em, I have now got pretty well paid for bearing their
treatment this time; for mean and insignificant as they appeared to
think me, I had wit enough, it seems, to Tom-fool the whole posse of
'em there in New-York, big-bugs and all. But as to you, there is some
encouragement for you to advance in Masonry. You can stay a few months
in Albany, perfect yourself in all the lower degrees, and take all the
higher. And when you have done this I have no doubt you will be one of
the brightest Masons in all America. You can then travel where you
please and get a good living by lecturing to the lodges about the
country. Your fortune will then be made, and then you will be a great
man, Timothy."
`That is precisely the plan,' rejoined our hero, as he pulled up
his cravat in the dignified consciousness of meriting his companion's
encomiums, `that is precisely the plan I ramified and co-operated for
myself before I left home, provided we should meet with that indelible
success in the exhibition of Boaz which we hoped and prophetized, and
which has now, bating the poor animals' abolishment, transpired and
expanded to a certain occurment.'
"Ah! poor Boaz! said Jenks mournfully, "How sorry I am that we
could not have got him away alive! what a noble fellow for a bear he
was, Timothy! and how bravely he died!"
`Yes,' observed the other with kindling enthusiasm, `Yes, as I
looked on with the most indignant admiration, and saw them expunging
the life of the poor fellow, I thought of Cæsar who was killed and
assassinated in the senate by Brutus and a concatenation of others,
and who only had time to look Brutus in the face and say, tu Brute
, which meant, I suppose, too much of a brute, and this I take
it was the reason why the murderer was called Brutus. But why I
similified the two cases was because Boaz was also assassinated by
brutes, like Cæsar. And I opinionate likewise the death of Boaz
resembles the way and manner, that we read some of our ancient
brethren were put to the torture and rack—those two machines that
they used to bind and murder Masons upon, to get their secrets in the
days of poperarity.'
"That is very true," rejoined Jenks, "and, like those old martyrs,
Boaz may be considered as dying for the cause of masonry, since he was
the means of helping us to money which you are agoing to lay out in
studying, and of course in extending the knowledge of the art; and if
you should become a great Mason, Timothy, by means of the money he
brought you, he will have been a great benefit to our order, and ought
to have a monument, like those old heroes and martyrs, erected to his
memory. I wish you would write a pair of verses about him,
Timothy—same as if they were going to be put on a grave-stone,—
epitaphs I think they call them."
`My mind,' replied Timothy, in answer to this request or
proposition of his friend, `my mind was never much diverged towards
rhymetry, but we may as well have our time amplified, on our voyage,
in writing something for the glorification of his memory, as in any
other way, since we have but little else to procrastinate our leisure
employment. '
The crew now coming on board and beginning to take in their wood,
this interesting discussion upon the character of Boaz, and on the
propriety of composing an elegiac tribute to his memory, was of course
suspended. In a short time, however, the wood was taken in—all the
business for which the vessel had moored was completed, and she was
again put before the wind and proceeded slowly on her voyage. After
indulging awhile in viewing the magnificent and diversified scenery
that opened in beauty and grandeur on either side of them as they
wound their way along the bends of this noble and picturesque river,
our friends began to bethink them of the task which they lately had
under consideration, that of honoring the lamented Boaz with an
epitaph. They accordingly borrowed pen, ink and paper of the captain,
and going to a retired part of the deck, fitted or piled up some
square boxes of freight so that they very well answered the double
purpose of seats and writing desk. Here, being again by themselves,
they resumed the discussion of the subject.
"Now, as I told you, Brother Jenks," observed Timothy, as he spread
a sheet of white paper before him, and held the pen in his hand
shaking out its superfluity of ink, "now as I told you, I comprehend
the art of poetification but badly. I have often tried, but I never
could make more than one line of rhyming in my life without
confuscating my sentiments or debasing the sublimity of my language.
And I should rather prefer concocting an oration instead of making a
rhymified curtailment on this grievous occasion."
`I still think,' said Jenks, firmly persisting in his opinion,
`that a pair of verses would be much more fitting for an epitaph. If
you cannot do it yourself, perhaps we both could by putting our heads
together. Now suppose you write the first two lines, and kinder give a
pitch to it; and I guess I can think up two more to match them, and so
make it rhyme,—what say you?'
"I will make the endeavor of a beginning," replied our hero, "If
you really think that the most feasible designment."
`But is there not some rule,' asked the other, `for making verses?
I conclude all the lines have to be of a particular length: For unless
we know how long each one is to be, how can we get the others right?'
"To be sure," replied the other, "I have somewhere read the rules
of making rhymetry—I think it was Blair's Lecturizing, or some other
great work on the decomposition of language; and I believe the length
of the lines is reckoned by feet"—
`Inches, more like!' interrupted Jenks—`who on earth ever heard
of a line of poetry two or three feet long?'
"Why, I don't exactly understand it myself," said Timothy, somewhat
puzzled how to get along with the question, "but still I am very
explicit that the book said feet, and did not, as I commemorate,
mention inches at all. I don't know that I can explanitate the
business very discriminately myself. Yet I suppose these feet are not
so long as common feet—probably not longer than inches, as you
opinionate. But one thing I am certain and conclusive about, and that
is, that all the lines must be measured."
`Well then,' said Jenks, `we wont puzzle our brains any more on
that point, but measure for ourselves. So you may write off a couple
of lines of about a proper length, and I will try to mate them in due
order and proportion.'
Our hero now took his pen, and wrote a caption; and, then, after
thinking awhile, now putting his pen almost to the paper, now taking
it suddenly back to relapse into musing again, and exhibiting sundry
other of the usual symptoms and sufferings of mental parturition, he
at length dashed off two whole lines without the least pause or
hesitation, and handed them over to his companion, whose more
mechanical genius, it was expected, would enable him to match them
with alternate rhyme. Jenks was for proceeding to business in proper
form, and doing every thing in a workmanlike manner. He accordingly
took the paper and first laid it squarely before him. After this was
adjusted, he thrust his hands into his breeches' pocket, and drew out
a little folded box-wood rule, which, as he said, being somewhat of a
joiner, he always carried about with him. He then took the exact
measure of the length of the two lines which Timothy had written, in
inches, fourths, eighths, &c., agreeably to the rule which his
literary friend had suggested. Having ascertained the measure in this
manner, he next took a separate piece of paper, and pricking off a
corresponding space, drew two perpendiculars for boundaries on the
right and left, so that he might write his lines horizontally and at
right angles between them, and have their required length indicated
without the trouble of repeated measurement to find when he had got
them of the right length. Having thus hit on a satisfactory plan for
preserving the measure which his friend had adopted, he then read the
lines that were to be mated, and, humming over the closing or final
words of each, put his brains to the task to get two others of
corresponding sound to make the rhyme. These he had the good fortune
to hit upon without much trouble, and having done so, he carefully
placed them close against the right perpendicular, for the final or
rhyming words of the two lines which were to constitute his part of
the performance. Nothing now remained but the less important task of
finding sentiment and words to fill up the lines. And this, after
running over the words in the two lines of Timothy awhile to get the
jog of them, as he expressed it, he very soon and very happily
effected; and then, with much self-gratulation, transcribed and placed
them exactly under Timothy's lines in their order, thus completing one
verse of their undertaking to the mutual satisfaction of the parties.
Another verse was then begun and finished in the same manner; and
thus they proceeded through five entire verses, which brought them to
the conclusion of their performance. This notable production of
partnership poetry I have most fortunately been enabled to obtain; and
to remove all doubts of its genuineness I can assure the reader that I
now have it before me in the original hand writing, and on the same
piece of paper on which it was first written. I shall make no
apologies in offering it entire, believing that my masonic readers at
least will be capable of justly appreciating its merits, and concur
with me in considering it a morceau of genius too precious to be lost.
It is as follows:
AN EPITAPH ON A FOUR-FOOTED BROTHER. Here lies the poor Boaz, our
dogmatized brother, Most potently skill'd at the grip or the token;
And yet all his Masonry proved but a bother— He made signs of
distress, but his guts were ripp'd open. Like Sampson he fell on the
loss of his hair, But the arches of glory bent o'er him in falling—
For the Philistine dogs by the dozen were there, By the help of his
jaw-bone laid kicking and sprawling. Like the Templars of yore he died
for the cause, And ne'er flinch'd till his frontier exposures were
riven— But I guess he's at rest, now sucking his claws, For the
crows were last seen with him going towards heaven. And he there,
bidding sun, moon, and lesser lights, hail! Aye shall stand by his
great brother Bear in the stars— And snarl at the lion—snap off
the ram's tail, And fight the old dog-star like thunder and mars. Let
masonic pig-asses in tempests of rhyme, Then trumpet his honors from
ocean to sea— And the curse be decreed, on account of this crime,
That no dog shall hereafter a freemason be.
Such the chaste, classical and elegant offspring of the masonic
muse as invoked by the combined efforts of our two friends in behalf
of the memory and virtues of their lamented brother, Boaz! It perhaps
were needless to attempt its praise, or to say how much it resembles,
in beauty and pathos, many of those much admired songs and odes,
which through the consenting judgment of ages, are now found gracing
the pages of the Book of Constitutions. I have been particular in
describing the original mode of versification which the writers of
this unique and inimitable production here adopted, in the
construction of their rhymes, in order to give modern rhymers,
especially the ode-makers of the masonic household, the benefit of the
improvement. They will not fail, I think, to see at once its
advantages, and avail themselves of the system accordingly. Some may
perhaps say that this system is liable to objection, as having a
greater tendency than the old one to lead those adopting it to
sacrifice the sense to the rhyme. But in answer to this I would say,
that I believe there is little danger of making matters much worse in
this respect than they always have been among even the most celebrated
rhymers: For some of the most approved of these, it would seem, have
considered, with the humorous author of the work from which I have
quoted at the beginning of this chapter, that "Rhyme the rudder is of
verses,"— which implies that the rhyme must govern, whatever shall
become of the sense or sentiment. We learn from one of the annotators
of Pope, in one of the first editions of his works published after his
death, that the great poet finished and sent to the press the copy of
his "Essay on Man," with those well known introductory lines proposing
as they now read to "Expatiate free on all this scene of man, A
mighty maze, but not without a plan!" written in the following manner:
"Expatiate free o'er all this scene of man, A mighty maze, and all
without a plan!" But on being told by a judicious literary friend
that the whole treatise went directly to contradict this proposition
which he had laid down as the foundation of his work, all going to
prove a great and connected plan in all the operations of the Deity,
he, with a most accommodating spirit, took his pen and altered the
last line of the couplet as it now stands,
"A mighty maze,
but not without a plan!"
Thus transforming himself from an atheist, a believer in chance,
and a want of any fixed order in the works of creation, as the line,
as he first had it would imply, into a consistent believer in the
settled and determinate plans of providence, and all this too, as one
would judge, only because he luckily hit on another phrase that would
effect the change without injuring the rhyme! If the consideration of
rhyme then could thus influence the great and acknowledged model and
father of versification, what may not be expected from the children?
Alas then for those who depend, for moral or ethical guides, on the
maxims and precepts of rhyming philosophers!
CHAPTER XIII.
Intry, mintry, cutry corn,Apple seed and apple thorn;Wier, brier, limber lock,
Three geese in a flock.
Nursery Ballad.
On the second morning after leaving the great emporium of trade,
and the patroness of mobs and shaved bears, our travellers arrived
safe and sound, in purse and limb, at the busy mart of Fort Orange, as
Albany was called by the original Dutch settlers. Leaving Timothy in a
sort of Dutch doggery, or sailor's hotel, situated near the wharf,
Jenks immediately went in search of the friend to whom he had
proposed to introduce the former. He soon returned, however, with the
news that this friend was absent from the city. In this dilemma he
advised Timothy to put himself on his own resources for an
introduction into society, telling him if he would rig himself up with
a new suit of clothes, and take lodgings in some fashionable hotel
with a well furnished bar, he could find no difficulty in becoming
acquainted with the brotherhood. The two friends then took a formal
and tender leave of each other, after a mutual promise of
correspondence by letter till Timothy should rejoin the other in a few
months, the next spring at the farthest, under his hospitable roof in
the Green-Mountains.
Our hero felt much regret at first in being separated from his
friend, and thus suddenly deprived of his company and council. But
lack of a just confidence in himself being never a very prominent
defect in our hero's character, he now felt, therefore, but little
hesitation in putting himself at once in the way of public notice. In
accordance with the suggestion of Jenks, and more perhaps in
compliance with the dictates of his own feelings, he determined in
the first place to obtain that by no means uncurrent pass-port to good
society, a fine suit of apparel. He therefore took his bundle in his
hand and went directly in search of a merchant tailor. Having found
one he at once stated his wish to purchase a genteel suit of clothes.
The man eying Timothy an instant, observed, "he presumed he had none
that would fit," and was about turning away when his eye glancing on a
roll of bank bills which our hero was holding in his fingers, he
suddenly recollected "a suit or two that would doubtless suit to a
hair." "It was surprising," he said, "that he should have forgotten
them." Suit after suit was then produced by this vulgar fraction of
humanity, and a bargain was soon completed to the mutual satisfaction
of both parties. And Timothy, having enrobed himself in his new
purchase, and made his toilet with suitable care in a private room
furnished him by the now very accommodating tailor, immediately set
out to look up a boarding house. After going the rounds of the public
houses awhile, and making all necessary inquiries, he at length took
lodgings in a popular hotel in the best part of the city, which
eminently possessed the requisites mentioned by Jenks, it being
celebrated as a house of choice liquors, and as a resort of all those
who justly appreciate them. Timothy's next object was to form some
masonic acquaintance. And in this he was peculiarly fortunate. At the
dinner table, to which he was soon summoned after engaging his board
he threw out the usual masonic sign as he lowered his empty glass from
his lips, and had the pleasure of seeing it answered by a young
gentleman who sat opposite to him. As soon as the company rose from
the table Timothy made a sign or beck to this newly discovered
brother, and was followed by him, though with evident reluctance, to
the room which the landlord had assigned to the former. They were no
sooner alone in the room than this person observed that "he regretted
very much the low state of the funds of his lodge, and he was fearful
that little or nothing could be spared at that time, still however he
was always willing to hear a brother's story." Timothy, as soon as he
could find a place to break in upon his alarmed brother, proceeded to
inform him that he had no desire to draw on the charities of his
brethren, but having a few hundred dollars at his command, and being
very desirous to perfect himself in Masonry, he knew of no way in
which he could spend his money more profitably or pleasantly; and all
the assistance he desired was such introductions to the brethren of
the place as would be necessary in pursuing this object. The merchant,
for he proved to be a young merchant of the city, on hearing that no
draft was to be made on his charity, as he seemed rather hastily to
have anticipated, immediately broke through the atmosphere of
restraint and repulsiveness in which he had enveloped himself on
entering the room, and suddenly became very sociable and friendly. He
highly commended our hero's intention of pursuing such a noble study
as Masonry. He greatly respected such people, he observed, and always
felt bound to sell them goods much cheaper than he sold them to
others. His name he said was Van Stetter, and his store was in —
street, where he was ever extremely happy to see his friends.
A general understanding having thus been effected between Timothy
and Van Stetter, they fell to conversing on other topics; and before
they had been together one hour they had become, by the strength of
the mystic tie, not only familiar acquaintances but sworn friends. The
merchant then arose, and repeating his friendly offers, and promising
to furnish a supply of masonic books as soon as Timothy should wish to
commence his studies, bid the latter a good day and departed. Much did
our hero congratulate himself, when the other was gone, on his good
fortune in thus happily securing so valuable an acquaintance; and he
could not help again blessing, and admiring anew, that glorious
institution which could so soon convert an entire stranger into a
faithful friend.
Being now fairly settled, and every thing appearing bright before
him, Timothy's first care was to write a long letter to his parents,
informing them of his singular good fortune, and of his present
determination to remain for the present in Albany in order to become a
great man in Masonry, which would perhaps take him till the next
spring to accomplish. Having performed this pleasing task, and
dispatched his letter by mail, he spent several of the following days
in viewing the different parts of the city, and its various
curiosities, before sitting down to those important studies in which
he felt conscious he was destined shortly to become a great and
distinguished adept.
In the course of a few days Van Stetter, who had been absent on
business most of the time since the introduction above mentioned,
called at Timothy's room and brought him a large supply of masonic
books; and at the same time informed him that the lodge of which he
was a member held a meeting that evening, and gave him an invitation
to attend as a visiting brother. Timothy was overjoyed at this
gratifying intelligence and thankfully accepted the kind invitation of
his friend. Accordingly at the appointed hour, they repaired to the
lodge-room. Here they found a goodly number of the brethren assembled,
although the lodge was not yet called to order. This gave Timothy an
excellent opportunity of being personally introduced to most of the
members, by all of whom he was received and treated with many
flattering attentions. And not a little elated were his feelings by
such a reception from men of the appearance and consequence of those
by whom he was now surrounded. He felt that glow of inward
complacency which is ever experienced by modest merit when treated
according to its conscious worth; and he perceived at once how greatly
he had been underrated by the world. But now he had at last got into
that sphere for which his high endowments had designed him, and from
which he had been kept only by his inauspicious fortune that had
thrown him among those who were incapable of appreciating his merits.
Equally gratifying likewise was this meeting to our hero in other
respects. The gifted promptitude with which the work of the lodge was
performed—the splendour of the furniture, the rich dresses, and the
dazzling decorations of the members, together with the convivial
elegance of the refreshments, did not fail to make a lively impression
on the mind of one who, as yet, had seen only the interior of an
ill-furnished lodge-room in the Green-Mountains; and he went home
filled with renewed love and veneration for the mystic beauties of
divine Masonry.
In about a week after the lodge meeting above mentioned, a meeting
of the Temple Royal Arch Chapter was holden at Temple Lodge Room in
the city; and Timothy, at the suggestion of his friend, Van Stetter,
preferred his application to that body for receiving the Royal Arch
degree. Having presented his credentials from the Lodge, where he was
initiated and received the subordinate degrees, to several of his
masonic acquaintance, he was by their recommendations balloted in;
and, as there was another applicant for the degree present, it was
proposed to make up the team, as it is beautifully termed in masonic
technics, by a volunteer, and exalt both the candidates that very
evening. The imagination of Timothy had long dwelt with rapture on
the happy hour which was to make him a Royal Arch Mason, and now as
that much desired event was at hand, his feelings and fancy were
wrought up to the highest pitch of expectation; and it was with the
most trembling anxiety, and fearful interest that he entered upon this
new and untried scene in the vast labyrinth of masonic wonders. Yet
he manfully submitted to the ceremonials; and as brightly as he had
pictured to himself the glories of this degree he found the reality
still more splendid and impressive. But I will not attempt to describe
the deep and mingled emotions, the rapid alternations of fear,
amazement and admiration which took possession of his breast as he
passed through those august and awful ceremonies—as he now
encountered the living arch, formed by the conjoined hands of two
long rows of the brethren, and thus compassing numerous manual
cross-chains which rose and fell like so many saw-gates, over the
impeded path of the low-stooping candidate who strove on beneath
in all the bother and agony of a poor wretch running the gauntlet,
sometimes cuffed and buffetted, sometimes knocked back, sometimes
pitched forward, and sometimes entirely overthrown and kept
scrambling on his back, like some luckless mud-turtle in the hands of
a group of mischievous urchins, till the sport had lost its charms of
novelty for the tittering brotherhood— as he now took the rough and
rugged rounds of his dark and perplexing pilgrimage, sometimes
hobbling over net-ropes, chairs and benches, sometimes tumbling
headlong over heaps of wood and faggots, and sometimes compelled to
dodge, curl down his head, hop up, or dance about, to save his pate
and shins from clubs, brick-bats and cannon balls, that fell and flew
about the room in all directions on the breaking down of the walls
of Jerusalem—as now he was lowered down into the dark,
subterraneous vault to find the sacred ark, in the shape of an old
cigar-box, and was scorched,suffocated, and blown almost sky high by a
terrible explosion of burning gun-powder—as now he kneeled at the
altar to take the voluntary oath, under the pressure of sharp
instruments and uplifted swords—as he now listened to the deep toned
and solemn prayer of the High Priest—and, in fine, as now he was
admitted to the light, and beheld the splendid furniture of the
lodge-room, the gorgeous robes of scarlet and purple of the Council,
the white garments and glittering breast-plate of the High Priest,
and the crimson habiliments of the Grand King, wearing the awful
mitre, inscribed, "Holiness to the Lord."
But these scenes of almost oppressive sublimity were occasionally
relieved by those of a lighter character; and the comic and amusing,
like sunshine through a summer's cloud, often broke beautifully in to
enliven and diversify the performance.
As the old Jewish guide who personates Moses leading the children
of Israel through the wilderness, under the masonic title of Principal
Sojourner, now conducted the hoodwinked candidates through or rather
over the semblant wilderness of the lodge-room, consisting, as before
intimated, of heaps of wood, brush, chairs and benches, the company,
bating the unavoidable affliction of battered shins and broken noses,
met with many amusing adventures. On arriving at each of the guarded
passes on their rout, or veils as they are technically called, the
guide was compelled to give certain pass-words before they were
suffered to proceed. But Moses, being now somewhat old, and having
grown rather rusty in the use of these words, it having been about a
thousand years since he had used them much, was often sadly puzzled to
recollect them, and made many diverting mistakes in endeavoring to
give them at the places where they were required. "I am that I am,"
being the pass-words for the first veil, Moses, as he approached the
master, exclaimed in his Jewish brogue, "What a ram I am?" The master
shook his head. "I am dat ram, den," said the improving guide—`No!'
said the master. "Well den," said Moses, "I am dat I ram"— not
quite—"I am dat I am." `Right, worthy pilgrims, ' said the master,
`proceed on your way. I see you have the true pass-words. You will
find many difficulties to encounter. Your next pass-words are Shem,
Ham and Japhet—don't forget them.' Thus permitted to proceed,
they pursued their journey and soon arrived at the next veil. But
here again, alas for the memory of poor old Moses—the pass-words,
which he had been so strictly charged to remember, had quite escaped
him; but the old sojourner had no notion of giving up in despair, and
accordingly he at once put his wits to the trumps in trying to stumble
again on the words of this masonic Se same. And soon beginning
to rally his scattered ideas, and remembering the pass-words
consisted of the names of three men of scriptural notoriety, he, with
that inimitable humour and drollery with which Masonry has here so
appositely invested his character, now cried out to the master, "
She shake, Me shake and Abed-we-go." But the master gave him so
stern a look of rebuke that it threw him at first into some confusion.
Soon recovering, however, he hammed and hawed once or twice, and, in
a subdued tone of voice, said, "Shadrach, Meshack and Abednigo
." `No! no!' said the master.
"Well, it was some tree peoples I be sure," said the guide
scratching his head and looking round in obvious perplexity, "it was,
let me see, it was, `Shem, Japhet and Bacon-leg."'
The master still shook his head, but with a look of more
encouragement.
"It was den, it was Shem, Japhet and Ham which be de same nor
bacon-leg."
"Try again, worthy pilgrim," said the softening master.
"Oh! Ah!" exclaimed Moses with
urekaen rapture, "I have it
now, it was `Shem, Ham and Japhet."'
Such is a faint sample of the scintillations of wit and the bright
flashes of thought and fancy that were made to sparkle and shine
through this splendid performance; and accompanied as these chaste and
innocent sallies always were by the most exhilerating shouts of
laughter and applause from the surrounding companions, it failed not
to render the scene one of indescribable interest.
Nor were other parts of the performance much less replete with
interest and instructive amusement. After the finding of the long lost
ark, the opening of that sacred vessel, and the discovery of the bible
in the presence of the council, who make the walls of the lodge-room
resound with hallelujahs of rejoicing on the occasion; the detection
of a substance which the High Priest "guesses, presumes and finally
declares to be manna," comprised a scene alike delightful to the
curious, the thoughtless and the learned. And then the closing, the
closing act of this magnificent drama! the marching in a circle of the
gay and glittering companions—the three times three raising of the
arms, stamping of the feet and spatting of the hands— the breaking
off into tripple squads and the raising of the Royal or Living Arch,
chanting in deep toned cadences beneath its apex of bumping heads,
that sublime motto of metrical wisdom—
"As we three did agree The sacred word to keep, And as we three did
agree The sacred word to search, So we three do agree To close this
Royal Arch."
What could be more grand, more imposing and beautiful! Our hero
stood wrapt in admiration at the spectacle. The early associations of
his childhood rushed instantly on his mind; for he here at once beheld
the origin, as well as the combined beauties of those exquisite little
juvenile dramas which have ever been the praise and delight of
succeeding generations:
"Come Philander let's be a marching."
And again that other no less beautiful one, where the resemblance
is still more striking—
"You nor I nor no man knows How oats, peas, beans and barley grows,
Thus the farmer sows his peas, Thus he stands and takes his ease, He
stamps his foot, he spats his hands, He wheels about, and thus he
stands."
In this degree also, besides the invaluable acquisition of the long
lost word which is here regained, the key to the ineffable characters
or Royal Arch Cypher, and many other secrets of equally momentous
consequence, our hero gained much historical information which was
equally new and important, and which served to correct some erroneous
impressions which he had derived from those uncertain authorities,
the common uninitiated historians. It was here he learned for the
first time the interesting circumstance that the bible was discovered
and preserved by Zerubbabel and his companions, all Royal Arch Masons;
and consequently that but for Masonry all Christendom would even to
this day have been groping in pagan darkness. Here also was brought
to light the astounding fact that Moses, as before intimated, lived to
the unparalleled age of about one thousand years! This fact which is
obtained only through the medium of Masonry, he inferred with
indisputable certainty from that part of the degree which represents
Moses present and yet hale and hearty, at the destruction or breaking
down of the walls of Jerusalem, and indeed for years after, which
every chronologist knows would make him of the age I have mentioned.
These two facts alone, if nothing else were contained in this degree,
would be sufficient to render it of incalculable importance; but
these were but as a drop of the bucket compared with the great arcana
of hidden knowledge which was here unfolded, and all of it too of
equal importance and authenticity of the specimens just given. Deeply
indeed did the thirsty soul of Timothy drink in the treasured beauties
of this concealed fountain of light and wisdom. All that he had before
seen of the glories of Freemasonry fell far short, in his opinion, of
the mingled beauty, wisdom and magnificence of this closing act in the
great and stupendous drama of ancient Freemasonry. Nor was he at all
singular in this opinion. Other great men have considered this degree
the same, as I am gratified to learn from a recent work by my acute
and accomplished masonic cotemporary, Mr. W. L. Stone, who considers
this degree "far more splendid and effective than either of its
predecessors;" while of those predecessors, or inferior degrees, he
says they "impressed lessons on his mind which he hopes will never be
effaced." Thus we here see one of those singular and striking
coincidences which will often happen in the views and impressions
which have been entertained on the same point by two such minds as
those of our hero, and the unbiased author above quoted, when they
would have no means of knowing the opinions entertained by each other.
But as beautiful and perfect as our hero considered this noble
degree, there was yet one little scene which he believed to be capable
of improvement. It was that in which the High Priest, on opening the
discovered ark, finds a substance which he and the Council, after
tasting, smelling and divers other evidences of doubt, concluded to be
manna. Now the improvements suggested, consisted in calling up old
Moses, who was then on the spot to settle the question at once,
whether the substance was manna or not; for he, it will be
recollected, was the very person who put it in the ark, eight or nine
hundred years before, when he and his people were in the wilderness,
feeding on this same manna, of course he would at once determine
whether this was the same kind of stuff which formerly served for the
fish, flesh, fowl, bread and pudding, of his breakfast, dinner and
supper. This suggested improvement, however, in which I have the
happiness to concur with my hero, is now submitted to the craft with
the most humble deference, but should it meet with their approbation,
and especially that of my friend Mr. Stone, they and he are heartily
welcome to the suggestion; and I shall wait with some anxiety for the
appearance of the next edition of the work of that author, to see
whether he considers the proposed alteration, worthy of adoption. But
to return to our hero. How was his mind raised and expanded by the
scenes of this glorious evening! A few months before, he would have
thought, in his ignorance, the use of that awful epithet, "I am that I
am," in the manner above described, to be nothing less than the most
daring impiety, and the representation of God in the burning bush, the
height of blasphemous presumption. But now, he the more admired the
privileges of that institution which permits its sons to do that with
impunity, and even praise, which in the rest of the world would be
audacious and criminal. And he could not help looking with pity on the
condition of all those yet out of the pale of the masonic sanctum
sanctorum. For he was now fully satisfied that all wisdom, virtue and
religion are here concentrated. And he felt himself immeasurably
exalted above the rest of mankind, like one of the superior beings in
full fellowship with God, whom he had just seen represented as one
mingling in the ceremonies of the lodge-room.
CHAPTER XIV.
"There are more things in heaven and earth, Horatio,"Than any but Freemasons ever dreamed of.
Shakespeare improved.
The next morning, Timothy, having passed a night of much crural
uneasiness, rose early, and went down to the bar, with a view of
getting some brandy to bathe his shins. Here he encountered Van
Stetter, who, being just in the act of taking his morning potation,
warmly pressed the former to join him, telling him that the internal
application of a double fog-cutter, would prove a much more pleasant
and effective medicine, to one in his condition. But our hero rather
declined the prescription, observing that he usually drank but little
spirits, and he had always thought that the habit of daily drinking
was inconsistent with correct morals. Van Stetter at first endeavored
to laugh Timothy out of such countryfied whims, but finding him
serious in what he had said, recourse was next had, to argument.
"I did not expect," said Van Stetter, "to hear such silly scruples
from so bright a Mason as you are, Mr. Peacock."
`I was not under the awarement,' observed Timothy, `that masonry
propelled its approbation towards drinking.'
"There is where you are sadly in the dark," replied the other. "Do
not the highest and brightest of our sublime order, set us the example
of a free use of the enlivening bowl? And do not the precepts of the
most approved writers among the craft directly sanction the practice?
You cannot have forgotten those soul-cheering lines in the Book of
Constitutions—
"The world is all in darkness, About us they conjecture, But little
think, A song and drink, Succeeds the Mason's lecture. Fill to him,
To the brim, Then, Landlord, bring a hogshead, And in a corner place
it, Till it rebound with hallow sound, Each Mason here will face it."
`It is very true,' observed Timothy, his early impressions
beginning to give way before the direct, and not to be mistaken,
meaning of this quotation, `it is true I have read the lines, and
often heard them songnified in the lodge-room; and would not be
understood to nullify, or extenuate their veracity; but I had supposed
that they applied only to the circumvented potables of the craft in
lodge-meetings, where I take it the liquor is in a sort sanctified by
the ratification of its use in masonic purposes, after the similified
example of the wine in sacramental churchifications. '
"That cannot be the case," said the merchant, "for if it was as you
suppose, drinking would have been made a part of the ceremonies,
instead of being resorted to, as it always is, only in time of
refreshment. No, brother Peacock, you entertain very erroneous notions
on the subject. The meaning of these lines, and numerous other
passages of the same import, to be found in this great guide and
teacher of all true Masons, evidently is, that the craft are
particularly privileged to indulge in the luxury of good liquors, on
all proper occasions, when they should never prove cravens at the
bumper."
`I begin to see through my perceptions more clearly,' said our
hero, `and I am free to confess that your remarks have transfused so
much rationality into the matter, that it is now transparent to my
cogitations. But I take it that there is nothing in the Book of
Constitutions, that inclines to a recommendment of morning drams,
which I have been taught to believe are injurious to the obstetrical
department of the stomach.'
"Now hear that," exclaimed Van Stetter, laughing,— "was there
ever such a scrupulous animal for a man of your cloth;—such a doctor
of doubts and divinity preaching and hesitating over a fog-cutter!
Why, man, it is the very thing for the stomach, to correct the
crudities and keep out the fog and chill in such dark mornings as
these. But to put the matter at rest in your mind, I can refer you to
a verse in one of the odes in the Book of Constitutions, which
expressly gives its approbation to the wholesome practice of
moistening our systems with a good glass of a morning. It runs thus:—
"When the sun from the east salutes mortal eyes, And the sky-lark
melodious bids us arise, With our hearts full of joy, we the summons
obey, Straight repair to our work, and to moisten our clay."
Timothy could no longer withstand such arguments, backed as they
were by these palpable quotations, taken directly from the very
scriptures of Masonry. And with that frankness, which is the peculiar
characteristic of noble minds, when convinced of the truth, he freely
gave up the point in dispute, making many apologies for his unjust
prejudices, and manitesting no little chagrin at this detection of
his ignorance of masonic principles. But my readers in general, I
trust, will hold him at least excusable, when it is recollected that
as yet he had enjoyed but limited opportunities of imbibing the true
spirit of masonic philosophy to free him from those prejudices which
he had received from the feeble light of uninitiated wisdom, and to
correct those narrow notions which had been implanted in his mind by
the lessons of the nursery. And even my masonic readers, I cannot but
indulge the hope, will extend their charity, and kindly overlook this
sin of ignorance in a brother; and more especially so, when they
learn, how cheerfully he now gave evidence of the sincerity of his
conviction, in the manful acceptance of the proffered glass, and never
afterwards, either in theory or practice, had the slightest indication
to relapse into that error from which he had been thus kindly rescued.
Time, with our hero, now rolled pleasantly away. His days were
spent in the most assiduous devotion to his masonic studies; and his
evenings at the lodge-room, or at the store of Van Stetter, in company
of a few choice spirits of the mystic tie, occasionally diversified,
however, by visiting places of public resort, and taking moonlight
rambles about the city. In one of these rambles, a little incident
occurred, which, as it may serve to illustrate some of the less known
principles of Divine Masonry, is perhaps worthy of a place in these
instructive adventures. As Timothy was returning homeward one night,
at a rather late hour, and passing a house, which Van Stetter had
before pointed out to him as the residence of a new star in the
courts of pleasure, he heard a great outcry within; while at the same
time, a lady appeared at the door, crying aloud for assistance.
Rushing immediately into the apartment from which the noise proceeded,
he beheld two men in a desperate conflict, which was instantly brought
to a close, however, by one felling the other to the floor with a
heavily loaded cane. At the first glance which Timothy cast at the
conqueror, (who paused a moment over the apparently lifeless body of
his prostrate foe,) he knew he had seen the man somewhere before—a
second look told him, to his surprise, it was no other than the pious
dignitary, whose deep and devotional tones of voice, on the evening
of his own exaltation to the Royal Arch degree, had filled his mind
with such solemn reverence. The recognition was mutual, but attended
with evident confusion on the part of the man in the broil, who making
the Royal Arch sign to Timothy, instantly glided out of the house,
leaving the latter in care of the dead or wounded man, still lying on
the floor without the least sign of reanimation. Scarcely had our hero
time to recover from his surprise, when the lady, who had run out for
help, returned with two men, all of whom eagerly inquired for the
aggressor. On finding he had just escaped, they sharply interrogated
Timothy respecting his name, abode, and his knowledge of the person
who had committed the deed. To all of which he gave true answers,
except the last item in the catechism, which he well knew his
obligation required him to conceal. Being convinced that Timothy was
no accomplice in the transaction, they proceeded to take up the yet
lifeless man, and put him on to a bed, suffering the former to depart
unmolested. As soon as our hero reached his lodgings, he took his
friend Van Stetter aside and informed him of the whole adventure,
expressing his surprise that a man so gifted and apparently devotional
in the prayers and other religious exercises of the lodge-room, should
be found visiting such establishments.
Van Stetter could scarcely refrain from laughing at the last
observation of Timothy, but kindly attributing it to inexperience in
the indulgences vouchsafed by the liberal principles of Masonry, he
immediately undertook the task of setting the matter in its proper
light. "In the very prayer to which you have alluded, brother
Peacock," said he, "you may infer a sanction of the indulgences which
you seem so inclined to censure in our illustrious companion. You
will recollect, probably, this passage in the prayer in question: `We
bless thee that when man had fallen from his innocence and his
happiness, thou didst leave him the powers of reasoning, and capacity
of improvement, and of pleasure.' Here you must see that the
capacity for pleasure which our exalted brother was improving, is
accounted as a privilege to the craft, for which they should be
thankful to heaven. And again the same prayer says, `Give us grace
diligently to search thy word in the book of nature, wherein
the duties of our high vocation are inculcated with divine authority.'
Now if we are to look to the book of nature for our guide, as is here
directly intimated, where is the brother whose nature does not
occasionally point to these pleasures in which you seem to doubt the
propriety of indulging?"
Timothy could not gainsay this argument, drawn as he knew it was
from the most solemn part of the mystic creed; and he silently
acquiesced in the views of his more experienced brother. "I see how it
is with you," continued Van Stetter, after a short pause, and it was
the same with me before my mind received the full light of Masonry.
You cannot at once break through the mists of early prejudices and
notions, which are perhaps wisely enough too, intended to restrain and
govern the uninitiated world, who, in their blinded condition, have
nothing better to guide them. But we, who have been admitted to the
true light, have laws and rules to guide as superior to all others,
and whatever they sanction, we need have no scruples in practicing.
But as I see you are now convinced of all this, let us return to our
first subject. There may something grow out of this affair that will
require consideration on another point. You say the man scarcely gave
signs of life when you left him?"
`I certainly considered the poor fellow,' replied Timothy, `but
little better than totally extinguished.'
"Did you learn who he was, and what gave rise to the squabble,"
asked Van Stetter?
`I heard the lady say,' said the other, `that he lived with a
saddler in the upper part of the city; and, as far as I could digest a
legible conjecture as to the causes of the belligerent catasterophy,
from all I heard devised and intimated on the subject, I opinionate
that the man had a premature engagement with the lady, which she
nullified in favor of the more superfine embellishments of our worthy
companion.'
"Nothing more likely," observed Van Stetter, "but did you learn
whether they knew who our brother was?"
`I suppose not,' replied Timothy, `as the lady said it was a Mr.
Montague.'
"Good!" exclaimed the other, "he had the caution to go under an
assumed name. Perhaps all may go well, but I fear the wounded man may
know our companion, and expose his name, should the poor creature get
so as to speak. Now what I have been coming at, brother Peacock, is
this—suppose this man dies, or is like to die, and our exalted
brother in the difficulty should be discovered and arrested; and you
should be summoned as a witness against him, what should you swear to?"
`Swear to?' replied Timothy, `why I should swear to all I knew, why
not?'
"What!" said Van Stetter, "would you betray a brother Royal Arch,
when the other party does not even belong to the craft in any degree?"
`Why how could I help it,' said Timothy, surprised at the earnest
and censorious manner of the other, `how could I help telling all I
know about this casual dilemma; for I shall be under bodily oath to
tell the truth, the whole truth, and nothing but the truth?'
"Would you dare to break your solemn obligations?" said the other,
with a withering frown. "Have you not sworn, under the dreadful
penalty of having your scull cleaved from your head, that you will
aid and assist a companion, Royal Arch Mason, when engaged in any
difficulty; and espouse his cause, so far as to extricate him from the
same, if in your power, whether he be right or wrong? And would
not your companion be in difficulty in such a case? and would it not
be in your power to extricate, or clear him, by swearing that he was
not the man that you saw knock down the other in the broil? And again
have you not sworn in the same fearful oath, that a companion,
Royal Arch Mason's secrets, given you in charge as such, and you
knowing them to be such, shall remain as secure and inviolable in
your breast, as his own, murder and treason not excepted? And did
not your companion in this case, make you the sign, and thus give you
in charge the secret of his being at that place, and of the deed he
had committed? What say you to all this? Speak! for we must know who
there is among us that will dare to betray the secrets of the craft."
Our hero was dumbfounded. The difficulties of the supposed case,
now for the first time, flashed vividly across his mind. On the one
hand was his civil oath, a breach of which he had been taught to hold
as the most heinous of crimes—while on the other, stood his masonic
obligations with their terrible penalties, in direct conflict with his
civil duties, staring him full in the face! It was a dilemma which he
had never foreseen; and now as it was a situation in which probably he
would soon be placed, his heart sunk within him at the distressing
thought. Troubled and confused, he knew not what to say or think, and
he humbly threw himself on the mercy of his friend, imploring
forgiveness if he had done wrong, and asking advice how to act in
case he should be called into court, and wishing to hear explained
how these two conflicting obligations were reconciled with each other.
Van Stetter, now instantly softening down to the most soothing and
friendly tones, assured Timothy that there was no doubt or difficulty
at all in the case. That it was an undoubted duty to protect a brother
in trouble, whatever might become of his civil oath, which every true
Mason took, when it was forced upon him in these cases, with the
mental reservation, that he would tell all except what might be
inconsistent with his more sacred masonic obligation. And when he did
this, he would commit no crime in stating what would be necessary to
extricate a companion from difficulty, while at the same time he could
save himself from the awful guilt of breaking the oaths of his order.
Saying this, and exhorting Timothy to be true and steadfast, should
any thing happen to put his fidelity to the test, Van Stetter bid his
friend good night, and retired to his own apartment.
The events of the following day showed that the fears and
anticipations of our two friends were not unfounded. Their luckless
companion was arrested and brought before a city magistrate, on the
charge of assault with intent to kill. And Timothy was summoned to
appear forthwith as a witness against him. Scarcely had the officer
finished reading his summons, before Van Stetter, who had early been
apprised of what was going forward, appeared, and requesting a
moment's indulgence of the former, while he transacted some important
business with his friend, took Timothy aside, and informed him that
the brethren had already held a hasty consultation on the business,
which began to wear, he said, rather a serious appearance. "The
fellow is scarcely expected to live," he continued, "and they have
found a new witness in a man who was most unluckily going by the door
as the accused was coming out, when he left you, and what was still
worse, this witness caught a glimpse of his face, and knew him, which
led to his arrest. Now if this man appears, as he doubtless will, as
well as the girl, we fear it will be a tough case. But, as good luck
will have it, the magistrate is a Royal Arch, and if you prove true,
Timothy, we think all will turn out right. We have concluded that the
only safe way will be for you to swear plumply, as I intimated last
night, that the accused is not the person you saw engaged in the
affray. This will save him. And now, brother Peacock, in one word,
can we trust you? All eyes will be upon you, and it is the very time
for you to immortalize yourself with the brotherhood of this city."
Our hero having mastered all his scruples on this subject, and
being most anxious to retrieve his masonic character, which he feared
had suffered in the eyes of Van Stetter, by his late doubts, now felt
proud by the opportunity of evincing his fidelity to the brotherhood;
and assuring his friend of his fixed resolution to be true, he joined
the officer and proceeded to the place of trial. On the way, several
of his masonic acquaintances, falling in with him, still more
encouraged him to persevere in his determinations by their looks and
by whispering in his ear, as apportunities presented, their brief
exhortations to be steadfast in the good purpose. On arriving at the
court room, our hero found the trial was already in progress. The
grounds of the prosecution having been stated, the girl, at whose
house the broil happened, was called on for her testimony. Besides the
particulars which led to the quarrel, she plumply and positively swore
to the identity of the prisoner at the bar, with the person who gave
the deadly blow. This testimony, of itself, so clear and full as it
was, very evidently impressed the minds of the by-standers, with the
opinion of the prisoner's guilt; and being strongly confirmed by the
next witness, who was equally positive that the person whom he saw
coming out of the house at the time and place mentioned by the other
witness, was no other than the accused, the cause began now to be
considered a clear one, and not an individual present, except the
brotherhood, supposed that there was the slightest chance for the
acquittal of the accused. But how little did they know of the saving
virtues of Freemasonry— of the power and strength of its mystic tie.
Events soon told them that they had reckoned without their host. Our
hero was now called on to the stand. Casting his eyes around on the
spectators, he met the riveted and meaning glances of many a brother,
waiting in breathless solicitude, for that important testimony which
was to furnish the promised proof of his fidelity. He read at once in
their looks, their expectations and requirements, and he was happy in
feeling that they were not to be disappointed— that they were about
to behold so conspicuous an example of his devotion to the glorious
principles of Freemasonry. He then, with an air big with the
consciousness of the responsibility which devolved upon him, proceeded
to give in his testimony, stating that he was present at the affray
when a man was struck down and wounded by a severe blow from another
man, but positively denied that the accused was the person who
committed the deed, or that he was present at the time or before or
after it happened. The girl looked at our hero with undissembled
amazement. And the council for the prosecution would not believe that
the witness testified as he intended, till he had put the same
question over and over again, and as often received the same positive
answers. A murmur of surprise and suspicion ran through the crowd, and
the low muttered words, "perjury, bribery" &c. from the friends
of the wounded man occasionally became audible. But Timothy regarded
not these out-breakings of malice and blinded ignorance, for he saw
that in the grateful and approving looks of his brethren around him,
that assured him of their protection and a safe immunity from the
operation of any of those narrow rules of local justice, which the
uninitiated might attempt to enforce against him. The trial was now
soon brought to a close. The accused bringing one other witness to
prove him at another part of the city, within a few minutes of the
time when the broil was stated to have taken place, there rested his
defence. The council for the prosecution, having been so taken by
surprise, by the testimony of Timothy, his own witness, as to throw
him into confusion, and spoil his premeditated speech, proposed to his
brother to submit the facts without argument, which being acceded to,
the court now took the case. When the magistrate, taking up the only
point, at issue, whether the accused was or was not, the person who
committed the deed, and balancing the testimony of the last witness,
proving the accused in another part of the city at or near the time,
against that of the man passing by, who was greatly liable to be
mistaken in deciding upon personal identity by moonlight, and weighing
the assertions of Timothy, an unimpeached witness against those of a
girl of ill fame, was at no loss in perceiving which way the scales of
justice preponderated; and he therefore pronounced a full acquittal of
the prisoner.
There was no noisy exultation on the part of the brotherhood at
this triumph of their principles; but though every thing was conducted
with that prudence and caution so characteristic of the order; though
scarcely a sign of rejoicing was visible among them; yet Timothy, on
leaving the house, and on his way homeward, soon discovered, in the
silent and cordial grasp of the hand, in the speaking look, or the low
whispered "Well done thou faithful," how important that triumph was
considered, and how highly estimated were those services by which it
was accomplished.
Our hero was ever after the favorite of his city brotherhood.
CHAPTER XV.
"For mystic learning wondrous able,In magic, talismen are cabal;Whose primitive tradition reachesAs far as Adam's first green breeches."
For several of the following weeks, our hero devoted himself almost
wholly to masonry. And considering the great natural aptitude of his
genius for this noble study, and considering the unwearied pains taken
for his instruction by the brotherhood since his late important
services for the craft, and the lively interest they now manifested
for his advancement, it is, perhaps, scarcely to be wondered at, that
his progress was unrivalled. He attended all the frequent meetings of
the Chapter, many of which were holden on his own account, and
proceeded with rapid advances through the most prominent degrees of
knighthood. We regret that the limits assigned to this work will not
permit us to follow him further in his brilliant career in the
lodge-room, describing, as we have so far attempted to do, the
peculiar excellencies and leading features of each of these important
and splendid degrees. But this not being the case, we can only say,
that new beauties and wonders, new fountains of light and wisdom, were
continually unfolding themselves to his enraptured mind, as he
proceeded, step by step, through the august mazes of this stupendous
system.
Thus passed the time of our hero till about the middle of winter,
when the Grand Chapter of the State of New York assembled at Albany
for their annual session. At this session, which lasted about a week,
nearly all the great, the high and illustrious of the order in the
state, embracing most of its highest civil officers, were present.
What a golden opportunity for the young aspirant of masonic honors!
Here was the great Clinton—here the Van Rensselaers, the Van
Derheighdens, and scores of other proud Vans,
"Who boast their descent from Burgher Patroon, And, like bull-frogs
from ditches, now croak to the moon."
Not a little proud was our hero to be admitted into the company, to
set beside, and be placed upon an equal with these high titled
dignitaries of masonry. And, as he walked in their gorgeous
processions, often arm in arm with the most distinguished, and glanced
at his own fine form, his elegant dress and the splendid ensignia with
which it was surmounted, betokening his own elevated rank in masonry,
his heart swelled and expanded with exulting delight, and, in the
repletion of his happiness, he sighed, "this it is to be great!"
But the splendor of parade that marked this brilliant assemblage of
the wealth, rank and talent of the land, as magnificent and imposing
as it was, still yielded in comparison to the richness of the
intellectual repast which was here afforded. The wise, the learned and
the eloquent, all brought their rich offerings to the mystic shrine.
But among all those who contributed to this glorious feast of the
mind, the celebrated Salem Town, Grand Chaplain, took, by far, the
most conspicuous part on this important occasion. Besides the
performance of the customary clerical duties of his station, this
profound masonic philosopher favored the Chapter with the fruits of
his prodigious researches, in the shape of lectures, or addresses,
delivered each day during the session, on the origin, history and
principles of Freemasonry. Our hero was an eager and delighted
recipient of his learned instruction,and he thought, as he daily sat
under the pure droppings of this masonic sanctuary, that he had never
heard such wisdom.
In his first lecture, this great and good man gave a suscinct and
lucid history of the origin of Freemasonry. After a few general
prefatory remarks, and after stating what were the secrets of masonry,
such as the signs, pass-words, &c. which might not be told, he
proceeded to discuss that which might be told, introducing the main
subject of the lecture with the following bold and beautiful
antithesis: "But it is no secret that masonry is of divine origin
." With this triumphant assertion, he proceeded to consider the
proofs of the proposition, with all that logical accuracy and
conclusiveness which so eminently characterize his published
productions. He said "the earth was created to unfold the great
councils of eternity." That man was created a social being, and it was
therefore necessary to form associations for the purpose of carrying
into effect the views of heaven, which the energies of civil
government were too feeble to accomplish. And that as masonry was the
oldest and the most noble of all these associations, it was hence
intended to become the repository of the will of heaven, and hence the
medium by which that will was to be promulgated to the world. Thus
leading the hearer to the irresistible conclusion, not only that
masonry was of divine origin, but that the earth itself was in fact
created for the use of masonry. It would be just like many pragmatical
professors of whys, ergos and wherefores, to carp here and say that
the premises in this masterly argument were all assumed. But the
out-breakings of spleen and ignorance! who heeds them? The argument,
in substance, is here, and will speak for itself,—I have no fears
that my intelligent readers will not justly appreciate it. But should
any still entertain the least doubts on this subject, let them follow
this great reasoner into the succeeding lectures, where the same
argument is resumed, with such accumulations of testimony as to
convince the most skeptical. I allude more particularly to that
masterly parallel which he drew between Masonry and revelation, and
which subsequently appeared in his great work on speculative masonry.
In this parallel, after enumerating a long array of coincidences, to
prove that Masonry and revelation must have been one and the same,
co-existent, and of common origin, and reserving, like a skillful
logician, the strongest and most striking for the last, he puts all
doubts at defiance, and caps the climax with the following:— "And
finally, the Scriptures teach us in general terms, all the duties of
charity, to feed the hungry and clothe the naked, to visit the widow
and fatherless,—masonry dwells upon these subjects in every degree,
and lays her members under solemn obligations to exercise christian
charity and benevolence. The word of God teaches us to love our
enemies, and render good for evil. Masonry will feed a brother,
though a personal enemy, even at the point of a sword, should his
necessities absolutely require it!"
Having thus conclusively settled the question of the divine origin
of Masonry, the learned lecturer proceeded to show the existence and
continuance of the institution from the creation down to the present
time; and, taking the simple, single fact, that Masonry and geometry
are synonymous terms for the basis of his argument, he was here again
triumphantly successful in establishing this important point. For, as
the principles of geometry were involved in the creation of the world,
in the construction of Noah's ark, and the ark of the Tabernacles,
built by Moses, nothing could be clearer than the conclusion that God,
Noah and Moses, were eminent Freemasons. In a manner equally learned
and ingenious did he trace the footsteps of Masonry from Moses to
Solomon, the well-known Grand Master, and thence to Alexander the
Great, Pythagoras, Hypocrates, the Roman Generals, and lastly the
Druids and the princes of civilized Europe. After he had thus
completed his masterly history of ancient Freemasonry, he then passed
on to consider the general tenets and character of the institution.
And here the soundness of his moral and political principies, and the
powers of his eloquence were no less conspicuous than the learned
research and logical acumen which he had displayed in the historical
part of his subject. One of his addresses at this stage of his
lectures particularly arrested our hero's attention. While treating on
the unity and fellowship of Masons in all parts of the world, however
they might differ in "things unessential" or indifferent to the order,
such as Christianity, Paganism, Mahometanism, piracy and the like, he
set forth, with the most glowing eloquence, the privileges and
advantages of masonry. "Here is a privilege," said he, "no where else
to be found: Do you fall into the merciless hands of the unrelenting
Turk? even there the shackles of slavery are broken from your hands
through the intercession of a brother: Do you meet an enemy in battle
array? the token of a Mason instantly converts him into a guardian
angel. Even the bloody flag of a pirate is changed for the olive
branch of peace by the mysterious token of a Mason." He then related
several interesting anecdotes illustrative of these remarks: One,
where an American was captured and imprisoned in Egypt, and escaped
by the aid of a Turkish Mason: Another, where an American, imprisoned
in Edinburgh, among other prisoners, was liberated by the craft in
that city, on his being recognized as a Mason, while all the rest of
the prisoners, not being Masons, had to submit to their fate. And yet
another, where a whole crew falling into the hands of a pirate, were
preserved from death by one of their number being a Mason and giving
the token to the piratical leader, who, proving a worthy brother,
graciously spared the lives of all his prisoners.
Timothy could scarcely keep his seat for the liveliness of his
emotions while these anecdotes were relating. The escape of himself
and his friend Jenks from arrest, in the affair of the counterfeit
bill, in the Highlands, occurred instantly to his mind in confirmation
of the lecturer's remarks. The late recent affair too, of the arrest
and escape of his exalted companion from a disgraceful punishment,
rushed forcibly to his mind. Never before had he perceived the
advantages of Masonry in so strong a light as set forth in these
anecdotes. For he at once saw that the lecturer had told but half the
story—having left the most important inferences yet to be drawn by
the hearer—common sense told him that if a Mason could thus escape
the operation of the rigid rules of war, or the despotic laws of a
Turkish despot, how easily he might put all other laws at complete
defiance. And in the case of the pirate, it was no less manifest that
the same sacred token, which saved the innocent crew, must be
reciprocally obeyed by snatching that piratical leader from the
gallows should he unfortunately fall into the hands of his enemies,
those unfeeling ministers of the law, and undergo condemnation. Our
hero was lost in admiration of the institution which vouchsafed all
these precious immunities to its members; and again and again did he
bless the day that enrolled him among that favored number, and made
him a recipient of those saving virtues and invaluable privileges.
Such are a few, among a thousand others that might be cited, of the
bright specimens of the logic and learning, and wisdom and eloquence,
which the illustrious Grand Chaplain displayed in the course of these
celebrated lectures. Well may the fraternity be proud of the man whose
genius has not only shed such lustre on their institution, but
irradiated its kindly light into the minds of the purblind
uninitiated, till thousands have been brought to the fold of Masonry.
Such minds do not appear in every age, but, like comets, at intervals
of centuries, come blazing along, shedding abroad their glorious
effulgence, and dispersing the gloom around them. Seven cities, it is
said, contended for the honor of the birth-place of Homer. Of the
birth-place of the great lecturer, we are not apprised. Should not the
public be put in possession of information on this point, without
further delay, to prevent such unhappy contests hereafter, as those
which vexed the Grecian cities in disputing for the distinguished
honor of giving birth to their favorite bard? The literary birth-place
of the Grand Chaplain, however, is fortunately established. That high
distincton falls to the envied lot of his doating Alma Mater, the
Otter-Creek Minerva, who would not long sit demure and unnoticed in
her Green-Mountain bower, had she a few more such hopeful sons to
brighten her into fame by the light of their reflected honors.
For the remainder of the winter, and most of the spring following,
our hero unremittedly devoted himself to the great object he had
chosen, on which to concentrate the energies of his mighty genius. And
the progress he still continued to make, plainly evinced, that these
golden opportunities had fallen to the lot of one who was highly
capable of improving them. Besides perfecting himself in the lectures
of all the subordinate degrees, he paused not in his onward career
till he had taken all the ineffable degrees, and all the degrees of
knighthood which the Chapters, Councils or Encampments, to which he
could have access, were capable of conferring. And so thoroughly did
he study the lessons or lectures of each, that he soon acquired the
reputation, even among the expert and accomplished Masons of the
cipatal, of being a proficient of no ordinary promise.
Having now arrived at a proud summit in the path of masonic
advancement, he began to bethink him of leaving the city, in order to
avail himself of his acquirements in some way, to replenish his purse,
which his winter's living in the capital, together with expenses
incidental to the many degrees he had taken in Masonry, had now
reduced to rather alarming dimensions. While revolving these things
in his mind, he received a most welcome letter from his old friend,
Jenks, giving him an urgent invitation to revisit the Green-Mountains,
and deliver an oration before the lodge, which had the honor of making
him a Mason, at the approaching anniversary of the birth day of St.
John, which they had concluded to celebrate. Highly flattered at the
complimentary nature of this invitation, he immediately resolved to
accept it, being gratified at the thought of so fine an opportunity of
showing his former masonic associates, a specimen of the improvement
he had made since he left them. Accordingly he wrote a long letter to
Jenks, in which, after detailing his personal adventures since they
parted, he announced his willingness to undertake the proposed task of
preparing an address for their approaching celebration, and promised
to be on the spot in season to deliver it in person. Having done this,
and come to the conclusion of remaining several weeks longer in the
city, that he might have access to masonic books, while engaged in
preparing his oration, he now diligently betook himself to the
pleasing task. Night and day, did he labor in this grateful
employment, till he had brought his performance to a most satisfactory
conclusion. After this he spent several days in committing his oration
to memory, speaking it over in his room, and practicing before a large
mirror, after the manner of Demosthenes, to get the action,
which consisted, in his opinion, in gesticulation and commanding
attitudes. Not, however, that he meant to copy the manner of the great
Grecian orator, for he had another prototype in view, of a far
superior kind, as he believed, in the Grand Chaplain, and him he
endeavored to imitate with the most sedulous care, in catching his
graceful attitudes and melodious modulations of voice. While engaged
in this interesting employment, and in making preparations for his
departure, he accidentally one day happened at the post-office, where
he most unexpectedly found two letters for him. Hurrying back to his
room, he proceeded to examine them. Percieving the superscription of
one to be in his father's hand, he tore it open and read it as
follows:—
"O, Tim,—I have lately found out a most Jo-fired discovery! You
know Tim, about the time you was born, I joined the Masons—at least
I thought I did. Now I have lately found out that business was but
little better than a damn'd hoe-axe. Bill Botherem, the scamp of
tophet, damn him! Well, yer see, he made me believe he could take me
in, and so he did, and be damn'd to him! but he had no right to,
besides more than half of his jigerations there, initials, I think
they call them, were no Masonry at all amost. And all the scorching
and drenching, and all that flumydiddle about tin pans and pistols and
number ones and number twos—and all that botheration about going
over with it again, cause a fellow could'nt help swearing a little, to
let off the steam, was nothing but some of Bill's divlish cheatery and
whimsification. For I have found out there is nothing in Masonry
against swearing in a natural way at all amost. Well, yer see, Bill
has at last got found out in his diviltrees. A little while after you
went away, one of the fellows who helped Bill in that scurvy business,
joined the true lodge, and told on't after he'd kept the secret in his
clam shells more than twenty years. So neighbor Gibson, who is a
Mason, came to me, and told me all as how I had been Tom fooled, and
advised me to join the true lodge, and so I did, and have now got the
bony fide Masonry—and by the Lord Harry, how easy 'tis! Bill's
Masory could not hold a candle to it! Well, yer see, we now considered
what was to be done with Bill. But some thought he did'nt fairly break
his oaths, and some said it was so long agone that we'd better let it
drop, and so we did, only concluding to let all the brethren and
other trusty folks know in a kinder private way, that Bill was a
villain. But Bill, yer see, did'nt know as how we'd found him out, and
so he lately tried another trick, and really made a young fellow a
Mason privately, and told all the true secrets, they say. But what is
the drollest is, he's got found out in that too. The fellow, yer see,
was courting a gall, and told her all—and you know how things drop
through wimen. She told it to a Mason's wife, and so it got to the
lodge. We have taken the young fellow in, but they all say something
must be done with Bill this time, or he will ruin the whole
tote of us. And sure enough. Thunder! must all the world know all the
didos we cut up in the lodge-room—wimen and all? A pretty kettle of
fish that! I am clear for bringing the perjured scoundrel up to the
bull-ring. But we are in a bother how to come at it in a legal kind of
a way, as yer may say—and so we want you should come home and
insult on the business. So you'd as well ax those great bug-Masons
there in York State, their advice, and then pull up stakes for
Mug-Wump, in no time. Brother Gibson, says he is agoing to write you
too. Your mother has got the extatics to see you, and so I remain your
honorable father.
PELETIAH PEACOCK."
The other letter was in Royal Arch cypher, and from the person
mentioned in Mr. Peacock's letter, which, being translated for the
benefit of the uninitiated, reads as follows:—
"Dear Brother,—Botherworth has perjured himself. Vengeance must
be had—but the manner—come and assist us.
In caution,
GIBSON."
Timothy could scarcely restrain his indignation sufficiently to
read these letters through. The insult here practiced upon his father
alone, called loudly for punishment, but this, despisable as it was,
seemed as nothing to the awful guilt of Botherworth, in breaking his
obligations and turning the sacred rights of Masonry into mockery!
Shuddering at the very thought of the deep damnation that the wretch
had brought upon himself, our hero lost no time in laying the case
before some of the most experienced and learned of the craft in the
city, and finding them unanimous in their opinion on this subject, he
took their advice as to the best manner of proceedure when he arrived
at the scene of action, and proceeded to make preparations for an
immediate departure for the spot to which he felt that a high duty now
called him, and to which he was determined to hasten with no other
delay than that which might be required on his way to meet his
engagement with his Vermont brethren, at their approaching festival.
Accordingly, the next day after a tender parting from his city
brethren—one of whom, I scarce need say which, presented him with an
elegant gold headed cane on the occasion,—our hero took stage and
bid a reluctant farewell to the city, where every thing had conspired
to contribute to his happiness and to advance him in the path of
mystic greatness.
Nothing worthy of relation occurred on the two first days of his
journey—and on the second night, he had the pleasure of grasping the
trusty hand of his old friend Jenks, at his home in the
Green-Mountains.
[5] See Town's Speculative Mosonry, Chap. I, Edition I, page 37.
CHAPTER XVI.
"O what a fall was there, my countrymen!""Some luckless star, with baleful powerAnd mischief fraught, sure rules the hour."
Once more, gentle reader, must we make a brief pause among the
ever-green mountains of that rugged, yet fertile and flourishing
state, which, in so many respects, may be termed the Switzerland of
America. That fearless and sturdy little sister of the Republic, who
has ever stood the unflinching sentinel of the out-post unrelieved,
asking no assistance for herself, and eager to meet the first foe that
would attempt to encroach on the bright domain of her beautiful,
though often unmindful sisterhood. That state, in fine, whose sons are
hardy, industrious, healthy, and physically vigorous as the green,
rock-grasping forests that clothe their native mountains, patriotic to
a proverb, and as ignorant of the vices, as many of their contemptuous
Atlantic neighbors are of the virtues, and, at the same time, more
intelligent, perhaps, as a mass of people, than those of any other
spot on the face of the globe.
The anniversary of the birth-day of St. John happened this
memorable year, as it generally does in New-England, I believe, on the
24th day of June, and not in one of the autumnal months, as among the
observant brotherhood of the southern states, and some parts of
Europe. It was a lovely day, and of that season of the year when the
scenery of this part of the country, more especially appears in all
its glory. The zephyrs were gently ruffling the deep green foliage
that exuberantly covered the mountain sides, or waving the vigorous
growth of the rich fields of corn and wheat, in the fertile valley
beneath, within which our hero was this day to make his public debut,
as the young Boanerges of Masonry.
In an old pasture or common adjoining the road about one hundred
rods from the tavern, the identical tavern where Timothy first opened
his eyes to the glorious light of Masonry, a platform of new boards
had been built up and elevated six or eight feet from the ground, over
which was erected a booth of green boughs, and in front was placed a
row of small ever-green trees leaning their tops against the stage in
a slanting position for the double purpose of ornament and of
screening from the view of the audience the unseemly chasm beneath.
This was the rostrum prepared for the orator of the day. At the
distance of some fifteen or twenty feet in front, and parallel with
the stage, were numerous rows of benches, composed by laying boards
on short logs or blocks, for the accommodation of the audience. And at
the right of these, through an artificial grove of maple saplings,
sharpened and set into the ground, ran a long table, with seats on
each side, fitted up in a style in good keeping with what we have
already described. While baskets of cold baked meats, bread, various
kinds of pastry, fried cakes, cut into curious fantastical shapes, but
mostly typical of masonic emblems, such as square, compasses, &c., the
ingenious devices of the landlord's and other masons' wives, called in
to assist in the mighty preparations,—honey, preserves, and
nicknacks without number, as well as bottles of beer, cider, and even
Malaga wine, with the usual accompaniment of glasses, were already on
the ground, and placed, at a short distance from the table in the
custody of Susan, the landlord's daughter, and her
brothers,—personages to whom the reader was introduced in a former
chapter—the former of whom from the gayest and most frolicsome had
now become metamorphosed into the demurest of damsels, wearing a
checkered apron and beauless bonnet, modes which she adopted at a
camp-meeting, soon after receiving the visit of his majesty of the
black face and nine-foot tail, as described in the chapter to which we
have just alluded. But leaving these, now actively employed in
preparing the dinner table for the brotherhood, and such others as
might choose to join them on this joyful occasion, let us return to
the inn where the company of the day were mostly already assembled.
About eleven o'clock in the forenoon, the drum beat at the door,
and the long line of the brethren, issuing from the lodge-room, formed
procession in front of the house, and, preceded by martial music,
moved on to the place we have described, the master of the lodge and
orator first, the subordinate officers next, then the masonic
privates, or brethren generally, and lastly, the citizens with their
own or mason's wives, sweet-hearts, or partners protempore; for
hundreds of both sexes, and all ages, had flocked in from the
neighboring country, coming on foot, in gigwaggons, on horse back,
like beavers, with their better parts behind them, and even in
ox-teams, to witness the novelties of a masonic festival.
When the procession reached the place prepared for the exercises of
the day, the orator, master and chaplain for the occasion, ascended
the stage, while the audience were seated on the benches prepared for
them in front.
Now was a moment of intense and thrilling interest to our hero.
Never did he feel a more lively sense of the responsibility which
rested on him. He perceived himself the focus of all eyes, and he knew
that high expectations were formed of the performance on which he was
about to enter; but he felt proud in the consciousness, that as
bright as these expectations might be, they were still more brightly
to be answered. And as he glanced at his own fine coat, so favorably
contrasted with the rustic habiliments of those around him, his
flowing ruffles, his snowwhite vest, and above all, the rich crimson
sash and other glittering badges of his proud exaltation in Masonry,
now displayed over his person in the most tasteful arrangement, he
felt a glow of self complacency at the thought of the unparalelled
sensation that his appearance was about to make on the hungry
expectants of the gaping and wonderstruck multitude. And, in fancy, he
already heard the low whispered plaudits of the wise, the suppressless
awe and astonishment of the ignorant, and the tender and languishing
sighs of the heart smitten fair. But why delay the anxious reader
with the anticipated banquet of intellectual luxuries when the bright
reality is before him. As soon as the brief clerical exercises were
over, our hero gracefully rose, advanced to the front of the stage,
and, after saluting the three masonic points of the compass,
designating the rising, meridian and setting sun, with as many
elegant bows, he looked slowly around on the audience, in imitation
of his reverend Albanian prototype in oratory, and, drawing himself up
with that dignity so peculiarly his own, addressed the listening crowd
as follows—
Illustrious Companions, Right Worshipful Masters and Beloved
Brethren, of our ancient, co-existent, honorable and refulgent
Institution of Free and accepted Masonry:
With the most profound ebulitions of diffident responsibility, I
rise to address you on this stupendous occasion. Assembled as we are
to ruminate on the transcendant and ineffable principles of that
glorious institution whose existence is co-ordinate with the origin of
antiquity, and whose promulgated expansion extends from where the
rising sun elucidates the golden portals of the east, to where it sets
in the oriental extremities of the west, let us in the first place,
promenade back through the mysterious ages of ancestry and exaggerate
a short biography of its radient progress from its suppedaneous
commencement, down to its present glorious state of splendid
redundance. It is agreed by all, that Freemasonry existed among the
earliest generations of our posteriors after the general deluge.
Learned men of our order, however, have discovered that it begun its
origin at a much more antiquated period of the universe even before
progenerated man had heard the audible voice of the grand architect of
the world, bidding him enter and behold the light of the
exhilerating heavens. And I am conclusively of the opinion that it
must have commenced its created existence somewhere near the
beginning of eternity. From traditional knowledge, known only to the
craft, it has been long dogmatically settled, that "masonry is of
divine origin." The expulsion of the rambellious angels from Heaven,
it may be lucidly argufied, was for unmasonic conduct. Hence it is
implicitly proved that there was a grand lodge in that luminous
expansion. The first indefinite evidence of the existence of masonry
on this subterraneous hemisphere is in the garden of Eden. It is the
most conjectural probability that after the Great Almighty Supreme,
and Worshipful Grand Master of the mundane Universe, had expelled
those unworthy masons from the Grand-lodge of the celestial canopy,
he sent forth his trusty wardens to ramify a subordinate lodge among
the puerile inhabitants of the earth, that they might pass through a
state of reprobation before they were permitted to transmigrate to the
great and lofty encampment of Heaven. And it was problematically
these who initiated Adam into the secrets of masonry, and clothed him
with the apron, that universal expressment of our order, which we
read, he wore as he meandered the orchards of Paradise. Eve, I
comprehend was not allowed to consolidate in the blessings of masonry,
because, as our Book of Constitutions, so clearly explanitates, she
turned cowan and attempted in an unlawful way to get at the secrets by
eating the forbidden fruit of the tree of masonry which Satan, an
expelled mason of the most serpentine deviltry, told her would make
her like one of the initiated. Hence the orderous name of
Eve'sdroppers, whom it has ever since been the original custom of our
order to place tylers at the door, with drawn swords, to scarify and
extrampate—and hence also the reason why her daughters, those lovely
but unfortunate feminine emblements of creation, have never been
allowed to mingle in the lodge-room. The next certain information
which has been transplanted to us concerning masonry, relates to the
terrible apochraphy of the flood, which furnishes the most devastating
testimony of the continued existence of our art in the personified
character of the thrice illustrious Grand Master Noah. For a proof of
this mysterious circumstantiality, we need only concentrate to the
ulterior fact, that masonry and geometry are the same, or which is
called by learned ventriloquists, synonymous identities. Now as Noah
planned and constructified the ark, that expansive battlement of the
convoluted waters, and as this could never have been architecturized
and developed without, with a literary endowment of geometry, hence
it is an evident and obvious manifestation to the most itinerant
comprehension, that Noah was a most superabundant mason. And here,
beloved brethren, who but must pause, in the most obstreperous
admiration, over the great and magnified benefits which our blessed
institution has protruded on the terrestial inhabitants of the
revolutionary world. There we behold the astonishing veracity, that,
but for Masonry, no ark could have been made and digested for the
predominant salvation of those who were afterwards devised to multiply
the earth, and all mankind in consequential inference, must have been
forever extinguished, and found emaciated graves in the watery billows
of annihilated eternity!
Thus we see how emphatical and tantamount is the proof that those
two illustrious Israelites, Adam and Noah, were free and accepted
masons; and it is equally doubtless that there were thousands of
others, even in those unfathomable ages, who belonged to the same
institution; and, although our records are not particularly
translucent on the subject, I have no doubt but Methusalem,
Perswasalem and Beelzebub, and all the rest of the old patriarchs,
were worthy and accepted brothers of our divine order. But to proceed
in mythological order, the next perspicuous mason that we meet with in
our accounts is Moses, who was, as we all know that have been exalted
to the seventh degree, a Royal Arch Mason. It is a probable
coincidence, I think, that this August degree, as it is usually
called, (on account, I suppose, of its having been discovered and
first conferred in the month of August,) was for the first time
developed to this superlative brother and companion from the burning
bush amidst the tremendous ambiguity and thunderiferous rockings of
Mount Sinai.— For it was here that the omnific word, "I am that I
am," which none but the craft will presume to depreciate, was
delivered to Moses for the benefit of the order through all exterior
ages. From this time to the days of the great and refulgent Solomon,
little is irradiated in our historical inventions concerning the state
of our artificial institution: But all traditional probabilities unite
in concurring that all the superfluous characters of that undiscovered
period were engaged in extending the art with the most propagating
velocity. Among the most predominant of these, I should place Joshua
and Sampson. We peruse, in scriptural dispensations, that Joshua, the
great General of the Jewish militia, while monopolized in battle with
his obnoxious invaders, being hard run, and wanting more time to
disembogue his hostile enemies, commanded the sun and moon to stand
still, and they obeyed him. Now I have no questionable doubt but this
pathetic achievement, which has so long discomfited the uninitiated to
expounderate, was effectualized by the art of masonry: Joshua, we
know, was highly identified, and, like Companion Royal Arch Moses,
held facial intercourse with the Illustrious Grand Puissant of the
World, and I think it the most probable preponderance that he made
the grand hailing sign of distress to the great masonic deification
enthroned on the circumjacent canopy of heaven, who observed the sign
and immediately stopped those great geological luminaries to answer
the distressing emergencies of brother Joshua, and deliver him from
his extatic difficulty. Thus we again behold, in admirable wonder, the
powerful omnipotence of masonic chicanery which can even control the
revolving astronomies of heaven! Equally suppositious likewise is the
evidence that Sampson, that almighty wrestler of antiquity, was a
bright and complicated mason. For proof of this congenial fact we need
only perambulate that part of the Bible which treats of his
multangular explosions among the interpolling Philistines. There we
find it implicitly stated that Sampson had thirty companions with him
at his wedding feast. Now is it not highly presumptious that these
must have been Companion Royal Arch Masons? I think the evidence most
conclusive and testimonial: Sampson therefore was a brother of that
glorified degree, and a mason whose prodigious muscular emotion must
have made him a most pelucid ornament to the institution through the
remotest bounds of posterity. It was not however till that primeval
period of triumphal magnificence, the reign of King Solomon, the great
Sovereign Commander, and Prince of the Tabernacle, that masonry shone
forth in all its glory and concupisence. It was then that the
tremendous stupefaction of the temple, the wonder of all cotemporary
posterity, uprose to the belligerent heavens in all the pride of
monumental aggrandizement wholly by the geometry of masonic
instrumentality. From this time, which is termed the Augustine period,
in honor of the August, or Royal Arch emblazonments of architecture,
that enhanced this emphatic epoch, our divine art soon expanded, with
the most epidemic enlargement, over the circumambient territories of
the congregated world. It was then that our great patron, St. John,
came out of the wilderness, preaching the beauties of masonry, and
wearing the sash, or girdle, of a Royal Arch Mason, (thus
preposterously proving that he was one of the glorious fellowship,
and had arrived to that superlative exaltation,) and established and
secreted a day for masonic designment, which he called the
Anniversary, and which has always since, from time immemorial, been
caricatured by the brotherhood as the glorious anniversary of St.
John. The same great and ostentatious day, beloved brethren, which we
are triumphantly permitted at this time to celebrate; and a day which
all the worthy and accepted will forever coagulate in celebrating till
the last hour of time shall evaporate, and mankind be abolished in the
deluge of eternity! It was there too that Nebuchadnezzar and
Pythagoras, Tubal Cain and Homer, Alexander and Zerubbabel, Hiram and
Bachus, Zoraster, Zedekiah and Vulcan, Aristotle, Juno, Plato, and
Apollo, Frederick, Pluto and Voltaire— all, all bright and luminous
masons, shone along the transcendant galaxy of futurity like the opake
meteors that irrigate the conflagrated arches of heaven!
Having now, my beloved and auspicious brethren, disseminated before
you a brief historical circumcision of the origin and progressive
intensity of our wonderful institution, let us preponder awhile on its
momentous beauties, its ambiguous advantages, and its inevitable
principles.
Of all the ties that bind and mankind together in this sublunary
vale of the the tie of masonry is the most inveterate and powerful.
By this, men of all sexes and credentials—men of the most homotonous
opinions and incarnate malevolence, are bound together like Sampson's
foxes, in municipal consanguinuity and connubial entrenchments. It is
this that clothes the morally destitute, and protects the indigent
incendiary from prosecuting enemies: It is this that dries the tears
of unfathered orphans, and dispenses with charity to the weeping
widow. It is masonry which mystifies the arts and sciences, and opens
the only true fountains of inanity to the world. It pervades the halls
of justice in sinuous counteraction, and snatches the prosecuted from
perilous enthralment. It opens the prison to relieve the faithful
delinquents, and defies the world in arms to stop it. It also the
domestic tenement, and populates society. It exhilarates its members,
rubifies their intellectual receptacles, and exalts them above the
vulgar mass of credulity. And finally, it concentrates, refines and
vitiates all who come within the pale of its Sanctum Pandemonium,
whether they be found roaming the burning wastes of arctic sands, or
inhabiting the torrid regions of the frozen North.
Such, brethren, is Speculative Freemasonry! And such will it
continue till it countermarches all the terraqueous altitudes of the
world, when, as my most appropriate and magniloquent friend, the
Thrice Illustrious Salem Town supposes, a masonic millenium will come,
and usher the whole earth in rapid pervasion. Then will all become one
great exasperated family of freemasons, except, perhaps, a few of the
most disinvited exclusives, such as idiots and feminine excrescences.
But here let me offer my derogatory consolation to my fair hearers
whom I see listening around me in lovely admiration. Let me have the
assurance to tell them, that although they may not be allowed to
amalgamate in the regular forcipations of the lodge-room, yet they are
never so safe as when in the circumventive arms of a free and accepted
mason. And we are bound by our obligations in the most inoperative
manner to refrain from our indulgent latitudes towards these fair and
necessary implements of creation, and particularly so if we know them
to enjoy the equivocal honor of being the wives or daughters of our
exalted brotherhood. Then let them always seek the gloririous
disparagement of monopolizing their connubial paramours from among
our amorous fraternity. O! let them come to us for aid and embracing
protection; and we will fly forward with our arms wide extended to
meet and enrapture them."
At that fated instant,
Heu miscrande puer! the luckless
orator, in suiting the action to the word by rushing eagerly forward
with protruded arms towards the fair and blushing objects of his
address, unfortunately pressed too hard against the single board,
which composed the only railing in front, for its feeble powers of
resistance to withstand. When the faithless barrier suddenly gave way,
and, alas! alas! amidst a flourish of his long-studied and most
elegant gestures, and with his countenance wreathed with the most
inviting smiles, he was precipitated from his lofty stand down
headlong on to the bushes which stood bracing against the front of the
stage, and, these quickly yielding near their tops to his rearward
weight, and giving him a new impulse by way of a counter somerset, he
finally landed in broken tumbles, feet downwards on the ground
beneath— where, by a most strange and still more luckless
concurrence, he struck directly astride an old ram, the leader of a
flock, which, unobserved, had taken shelter from the burning rays of
the sun, in this cool retreat in which they were now quietly reposing
when their strange visitant descended among their affrighted ranks.
The horned old patriarch, little dreaming of such a visit from above,
and being less appeasable, or less mindful of the honor thus
unexpectedly paid him, than Alborak, the ennobled ass of the Turkish
prophet, was not slow in manifesting a disposition to depart without
waiting particularly to consult his rider as to the course to be
taken. And, after one or two desperate and ineffectual lunges to free
himself of his load and retreat back under the stage, he suddenly
floundered around and made a prodigious bolt through the partial
breach, just made in the bushes, appearing in the open space in front
of the stage before the astonished multitude with the terrified orator
on his back, riding stern foremost, with one hand thrown wildly aloft,
still firmly grasping the precious manuscript, and the other
despairingly extended for aid, believing in the fright and confusion
of the moment, that it could be no other than the devil himself who
was thus bearing him off in triumph.
After proceeding a few short, rapid bounds in this manner, the no
less frightened animal made a sudden turn, and, tumbling his rider at
full length on the ground among the feet of a bevy of screaming
damsels, leaped high over heads, benches and every thing opposing his
progress, leading the way for his woolly tribe, now issuing in close
column from their covert with the speed of the wind, running over the
prostrate orator, regardless of his snow white unmentionables, vest
and flowing ruffles, and trampling down or upsetting all in their way
as they followed at the heels of their determined leader. Forcing
their passage in this way through the crowd till they came against the
end of the long dinner table, now fully spread for the company, and
covered with all that had been prepared for the occasion, the file
leaders came to some insurmountable obstacle, and the whole flock were
brought to a stand; when, as the very demons of mischief would have
it, they suddenly tacked about, mounted the table, which furnished a
clear road for escape, and the whole train of forty sheep, enfilading
off one after another swift as lightning, raced over its whole length
from one end to the other; and, unheeding the scattering fragments of
meats, pies, vegetables and nutcakes which flew from beneath their
trampling feet in all directions, and the rattling din of knives,
forks, broken crockery and glasses which attended their desolating
progress, triumphantly escaped, shaking off the very dust of their
tails in seeming mockery at the company whom they left behind, some
fainting or shrieking, some grappling up clubs and stones in their
phrenzy to hurl after the retreating fiends, or calling loudly for
dogs to assail them, some cursing and raving at the loss of their
dinner, some hallooing or breaking out into shouts of laughter, and
all in wild uproar and commotion.—But we drop the curtain, leaving
epicures to yearn with compassion, young masonic orators to
sympathize, and the brotherhood at large to weep over the scene!
CHAPTER XVII.
Amoto quaeramus seria ludo.
—Horace.
Our tale, gentle reader, must now assume a more serious aspect.
From the more light, and often somewhat ludicrous incidents through
which we have passed to this stage of our narrative—incidents from
which more gifted pens than ours might have plentifully drawn the
shafts of effective satire, or the food for merry laughter—we now
reluctantly turn to scenes calculated to cause other reflections—
to awaken other and more painful emotions.
About ten days subsequent to the events recorded in our last
chapter, William Botherworth, whose frolicsome exhibitions of masonry
improved occupied a conspicuous place in the first or introductory
part of these remarkable adventures, received from a commercial
acquaintance of the neighboring port the following letter:—
"Wm. Botherworth,
Sir,—As war is now declared, and a fleet of the enemy's forces
said to be hovering round the coast, we are fearful that they will
reach this place, in which case our property would be exposed to
destruction. The quantity of hops which you left in store with us
might be removed into the interior without much trouble or expense;
and I am very anxious that you should come to town immediately to
devise measures respecting them. I wish you to come tomorrow, as
after that I may be absent several days. Do not fail of being here by
to-morrow evening.
Yours, &c.
S. RODGERS."
"Pshaw!" said Botherworth to himself—"pshaw, man! your wits must
surely be wool-gathering. In the first place the British will never
get there; and if they should, they will doubtless respect all private
property. They must be wanton fiends indeed to destroy my few hundreds
of hops. However, Rodgers may know more than he tells, and perhaps,
on the whole, I had better ride down to-morrow and see for myself."
Such were the passing thoughts of Botherworth as he run over for a
second time this brief epistle, so artfully calculated to arrest the
attention of the person to whom it was addressed. And, putting up the
letter with the conclusion that he should obey the summons, as
unnecessary and even singular as it appeared to him, proceeded to
make such little arrangements about his farm as he considered his
intended absence for a day or two would require.
Botherworth, although by nature a person of great buoyancy of
spirits and cheerfulness of disposition, qualities which he still in a
good measure retained, had yet of late years manifested much less
inclination for convivial companionship, or for mingling with society
at large, than formerly. And becoming of consequence more domestic, he
had supplied himself with a good selection of books with which to
furnish that recreation and employment of his leisure at home which
the excess of his social feelings had formerly led him to seek too
much perhaps abroad in the usual routine of profitless amusements.
From these, together with the early advantages which he had enjoyed of
seeing the world and becoming acquainted with mankind, he had by this
time acquired a stock of general knowledge much more extensive than is
commonly to be met with among men in his sphere of life; while at the
same time, aided by a mind naturally acute and discriminating he had
formed original views and settled opinions upon almost all subjects
connected with the different classes and organizations of society and
its various institutions. The circumstance of his expulsion from the
masonic lodge for causes growing out of the prevailing characteristic
of his more youthful years, as before intimated, creating probably
some degree of acrimony and sensitiveness of feeling towards the
fraternity, had led him to bestow much study and reflection on the
nature and principles of that peculiar institution. The result of all
of which was to establish in his mind the honest, though at that
period, the singular, conviction that the whole system was founded on
principles radically wrong, and unjust and unequal in their operations
towards the rest of society; and, to say nothing of its ceremonies
and lofty pretensions which he had always felt disposed to ridicule,
that its oaths and obligations could not be either legally or morally
binding upon those who had taken them. And it was with these views and
impressions that he had ventured, a few months previous to the time
of which we are speaking, upon the act of which the reader has been
already apprised, that of imparting to a young friend, in a
confidential way, all the essential secrets of Freemasonry—little
dreaming, at the time, as he had formerly made partial experiments of
the kind with impunity, that consequences so melancholy to himself
were so soon to follow, and even now wholly unconscious that he had
been betrayed to the infuriated, but cautious and darkdoing
brotherhood.
In the evening following the day which brought him the letter above
quoted, Botherworth came into his house with looks so uncommonly
pensive and dejected as to attract the notice of the family; for still
a bachelor, though now upwards of forty, he had living with him at
this time, in capacity of house-keeper, a quaker lady whose husband
followed the sea, with her two children, both fine boys, to all of
whom Botherworth was much attached. Taking a seat at an open window,
he long sat gazing out, in thoughtful silence, on the surrounding
landscape, that lay spread in tranquil beauty before him. The stars
were beginning to twinkle through the gathering curtains of night; and
the full orbed moon, majestically mounting the deep cerulean vault of
the orient heavens, and brightening each moment into more glorious
effulgence, as the twilight, streak after streak, slowly faded in the
west, threw her silvery beams, with increasing splendor, over the
broad and diversified landscape, now glimmering on the placid stream,
now kindling in refracted brightness and beauty on the cascade, and
now shedding a varied and sombre glory over hill and dale, town and
woodland, as far as the eye could reach, round the adjacent country,
all quiet and noisless as the repose of sleeping infancy, except when
the voice of the plaintive whippoorwill, responding to his mate on
the distant hill, at measured intervals, broke sweetly in upon the
silence of the scene.
"Miriam," said he at length, partially rousing himself from his
long reverie, and addressing the quakeress who sat knitting in quiet
cheerfulness near him, "Miriam, what a beautiful evening!—or
rather," he continued after a pause, "beautiful, and happifying it
seems to me it should be, with all these bright and glorious objects
before us."
`And why is it not so, friend William,' said the person addressed.
"I know not," replied the other, "but every thing to-night to me
appears to wear a singularly gloomy aspect. Even this scene, with all
its brightness, which ever before as I remember, looked pleasant and
delightful, now appears strangely mournful and deathly. And why is it?
Can it be that nature ever sympathises with our feelings, or rather
is it, that the state of our feelings produces this effect? What are
those favorite lines of yours, Miriam, which I have often heard you
singing, containing, I think, some sentiments on this subject?"
`It is not according to my people's creed to sing,' meekly replied
the quakeress, `yet not deeming the forbearance essential, I sometimes
transgress, perhaps wrongfully; but does thee wish me to sing the
lines now?'
Botherworth replying in the affirmative, the lady, who, though
untutored by art, was yet one of those whom nature has often gifted
with powers of minstrelsy more exquisite and effective than any thing
which the highest acquirements in musical science alone can bestow,
now commencing in a low, soft, melodious voice, sang the following
stanzas:—
When the pulse of joy beats high, And pleasure weaves her fairy
dreams, O, how delightful to the eye— How gladsome all around us
seems! Fountain, streamlet, garden, grove, All, all, in semblant
brightness drest, And breathing melody and love, Reflect the sunshine
of the breast. But when sorrow's clouds arise, And settle on the mind
in gloom, How quickly every bright hue dies Of all that joyousness
and bloom! Earth and skies with mingled light, The vocal grove, the
streamlet's flow, Now seem to sicken on the sight, Or murmur back the
sufferer's wo. Thus forever—dark or fair, As our own breasts,
life's path we find; And gloom or brightness gathers there, As
mirror'd from the changeful mind.
"Miriam," said Botherworth, again apparently awakening from the
moody abstraction into which he had relapsed when the quakeress had
ceased, "Miriam, do you believe we shall have an existence in another
world?"
`Surely, friend William,' said she, in evident surprise at the
question, `surely thee cannot doubt the scriptures?'
"No, I do not," replied the other—"on them my only hope of a
hereafter is grounded, for, but for them I should be forced into the
fearful conviction, that with the body the soul perished. Human pride
I know flatters itself with the thought of immortality, and in the
wish, the strong hope, believes it, calling this belief, which grows
only out of the desire, as I have often thought, a proof of the
soul's future existence. But is there any thing in nature— in
reason, that sufficiently indicates it? The soul and body
comparatively begin their existence together— are in maturity at the
same time, and at the same time decay, and apparently terminate their
existence. When the oil in the lamp is consumed, the light goes out,
and is seemingly extinguished for ever. But the thought—the bare
thought of annihilation, how dark, how dreadful!"
`What makes thee talk so,' again soothingly asked the quakeress,
`and appear so gloomy to-night. Thee art generally jocose, and I
sometimes think too vain and light in thy conversation—but now. Thee
art well, friend Wiliam? '
"Yes, I am well, Miriam," said he, mournfully, "but it seems to me
as if this pleasant evening was to be the last I shall ever behold.
But what matters it, should it in reality be so? I have no wife or
children, no relations indeed, but the most distant, to mourn for me.
The world in which I once delighted to mingle, will move on without
me, unconcious of its loss. The gay will still be merry and laugh, as
I have done; the mercenary will still traffic and contrive, absorbed
in their own interests, and the ambitious will still go on, pursuing
the objects of their aim, and thinking only of their own advancement.
The little vacancy in the ranks of society which my absence may
occasion, will quickly be filled by others, probably more deserving.
And who will miss me?"
`Why!—thou dost indeed surprise me!' said the agitated listener,
laying down her knitting work with increasing emotion—`It pains me,
friend William, to hear thee talk so. Why does thee expect to die now
more than any other time?'
"I have no reason for thinking so," relied Botherworth, in the same
desponding tone, "none that would generally be considered as one, I
presume; but as I before intimated, there is a dark and fearful cloud
upon my soul. For several hours past, I have felt some unaccountable
influence acting on my feelings under which they seem to labor in
troubled agony as if they, and not my reason, were instinctively
sensible that some danger, some hidden evil was impending over
me—the whole operating upon me, in spite of all my endeavors to
shake it off, like what the sailors used to call the death-spell which
sometimes seized the victim doomed soon to perish by battle or storm.
But what it is, or when, or where, the bolt is to fall, I know not.
To-morrow I am going to town to be absent perhaps several days. If any
thing should happen to me, you will find my will in my desk which you
may deliver to the person to whom it is directed, and in proper time
you will learn what I have done for you and your children."
So saying, he bid the quakeress a tender good night, and leaving
her with tears standing in her eyes, retired to rest.
Among all the various branches of the reputed supernatural, as
enchantment, witchcraft, second-sight visions, prophetic dreams,
apparitions, signs, warnings &c., which have successively been in
vogue in different countries, and in different ages of the world, but
which are now mostly exploded as discovered to have been but the
tricks and inventions of the artful and designing, or accounted for on
natural principles, there is no one that has received less attention
from intelligent and philosophical writers than that which is
generally known by the term of presentiments. And, yet, it
appears to me there is no one of them all, that is so well entitled to
consideration, as regards the many and authenticated facts which can
be cited in support of its real existence, and at the same time so
difficult of solution when that existence is established. History,
biography and the records of travellers and journalists furnish
numerous instances of men having experienced deep forebodings of the
fate which soon awaited them, but which no human foresight could then
reasonably have predicted. Men too, whose character for intelligence
and courage, exempted them from the presumption that they might have
been under the influence of imagination or superstitious fears. Among
these, for example, may be instanced the brave Baron De Kalb, who fell
at the south in the American Revolution, and the gallant Pike, a
victim of the last war, both of whom, previous to the battles in which
they respectively perished, felt an unwavering conviction that their
earthly career would be terminated in the approaching contest. The
conflagration of Richmond theatre furnished also one or two most
striking examples of this kind. If these and the like instances are
not attributable to sheer chance, which, it appears to me we are
hardly warranted in presuming, then it follows that the doctrine of
presentiments is established as having a foundation in fact, and is
not the less entitled to credit because it has a particular and not a
general application. But once admitting the existence of this
mysterious principle, where is the human philosophy that can explain
its operation or fathom its causes? If I rightly understand the
history of these cases, and I have heard some of them from the lips of
those who described from actual experience, the operation seems to be
instinctive, and chiefly confined to the feelings or animal
sensibilities, and apparently originating with them, while the
impression on the mind is vague and undefined, suggesting no distinct
ideas, and seemingly putting it in action only for the purpose of
contriving or providing escape from the boded danger. Indeed the
intellect appears to have but little to do with these
impressions—and often, while the mind rejects them and seems to
convince itself that they arise from assignable causes, the same dark,
boding, irrepulsible feeling, in spite of all the suggestions of
reason, again and again returns to haunt the agitated bosom. To what
then is this principle to be assigned? To instinct, like that which is
said to forewarn the feathered tribe of approaching convulsions of
nature? Or is it a direct communication from higher spiritual beings
made to the animal, not the intellectual part of our existence? But
this last supposition would involve the proposition that spiritual,
can communicate with animal existence without the intervention of
mind—a proposition never yet admitted among the settled principles
of philosophy—it would open the door to a new and unexplored field
in the doctrine of pneumatology. Whence then shall we turn for a
solution of this inextricable subject? Where are the enterprising
Locks and Stewarts of the age, that they pass the subject unnoticed?
If a vulgar superstition, is it not prevalent enough to require a
refutation?— and if not, why do they shrink from the investigation,
and the attempt of solving the mystery?
The next morning, Botherworth arose lively and cheerful. The cloud
had evidently passed from his brow; and taking his breakfast in his
usual serenity of mind, and sociability of manner, and without the
slightest allusion to the events of the preceding evening, set forward
on foot to where he expected to intersect a public stage, which before
night would land him at his place of destination.
CHAPTER XVIII.
"Off with his head: so much for Buckingham."
Once more change we the scene of our eventful drama. On the same
evening during which the events described in our last chapter
transpired, another scene having an important bearing on the
catastrophe of our tale was acting in a different quarter. Of this
scene, it is our next purpose to lift the curtain.
In a spacious hall, situated in one of our flourishing seaports,
and consecrated to the uses of the mystic order, now sat a small
circle of the brotherhood in deep consultation on some matter
evidently of high import to the interests of their revered
institution. Though few in numbers, they were obviously, from their
dress, age, and deportment, a select and chosen band composed of the
high and honored, and the wise and trusty of the fraternity. They
appeared to be intently engaged in examining various books,
manuscripts and papers, which lay spread on the table before them,
and which, after having been perused by one, were handed on to
another, with a low, passing remark, and sometimes with a direction by
the finger to some particular passage, till they were thus passed
round the whole circle. After having been engaged awhile in this
manner, an elderly personage, who appeared to be acting as the
presiding dignitary on the occasion, giving a rap on the table with
his small ivory gavel, now rose and observed,—
"This charge, Brothers Knights—this charge, or accusation, which
has been presented by our illustrious visiting companion in behalf of
our respected brethren of Mugwump, against this poor infatuated man,
being amply proved and established by testimony which, by the usages
of the craft, has always been admitted in similar cases, it remains
only for us now to consider what order shall be taken in regard to
this unpleasant transaction. And involving, as I scarcely need tell
you it does, a crime of the foulest turpitude, and touching, in the
most vital part, the interests and safety of our exalted institution,
it is meet that we proceed with due caution, and proper deliberation,
in determining what punishment should be awarded to the execrable
wretch who has thus dared to violate his oaths, and trample under
foot one of the most sacred and essential jewels of masonry. To this
end, a full expression of the individual opinions of all present is
highly desirable."
So saying, and shaking back his silvery locks with impressive
dignity, he resumed his seat; when, after a moment of profound
silence, a tall and somewhat youthful looking person arose, and
extending forth his hand, while his elbow gracefully rested on his
side, addressed the listening conclave as follows:—
"Illustrious Companions, and
"Brothers most puissant and powerful:
"I will own that I am imbued with the most deep and momentous
indignation at the constipated atrocity of this most unheard-of,
unthought-of, and diabolical instigation which we are now congregated
to nullify and dissertate. And while I candidly confess, that I have
drank deep of the hallucinating fountains of masonry, and mounted high
its perpendicular glories, that I have often sat in learned
ostentation with the most illustrious Grand Kings, holy and
illustrious Knights, and Potentates and their exalted Princes of our
celestial order, in the circumambient State of New-York, where masonry
has arrived to such a pitch of cohesive perfection as to monopolize
all the most ponderous offices of their government, and embrace by far
the most inflated portion of their society. While I confess all these
great and exulting advantages for masonic developements, I feel a more
qualified presumption in obtruding my delectable opinions on your
obsequious attention. And as regards the proper and punishable
infliction which ought to be fulminated on the head of this indelible
reptile, I have but one concentrated opinion. We swear and solemnize
in all the subordinate degrees that we will suffer our lives to be
abolished if we violate our obligations; and in the higher and more
mystified exaltations of masonry, we are commanded to bring all others
who violate their infringements to the most speedy and condign
punishment. In the obligation of Knight Adepts of the Eagle or
Sun, which I, and some of you, I comprehend, have been superlatively
glorified in taking, we find these sentimental commands: We are
bound to cause their death, and take vengeance on the treason by the
destruction of the traitor, all of which is beautifully
illustrified in that evangelical degree, by the fate of the man
peeping. Now my conclusive opinion forces me to the most
inveterate belief, that as the perjured wretch, who is now under
investigation for betraying the secrets of masonry, has not had the
honorable conscience, like Jubela, Jubelo, Jubelum, to deliver
himself up to be excruciated by the penalties of his obligation, it is
our most nefarious duty to execute them ourselves, and blot out the
monster from the face of his existence."
With this burst of eloquent indignation and brilliant display of
masonic erudition, our hero, (who, having lived through his
Green-Mountain ramification as he probably, in his own flowing
language, would have expressed it, had now arrived at the scene of
action, and, as the reader I presume has already discovered, was no
other than the gifted speaker,) slowly sunk back into his seat, not
fainting, like the great Pinckney at the close of his speech, but
calmly adjusting his ruffles over a bosom heaving with the proud
consciousness that his zeal and faithfulness in the cause of masonry
could only be equalled by the eloquence and ability with which he had
enforced its divine precepts.
As soon as the hum of applause which followed this powerful appeal
had a little subsided, a member; who had not appeared to join in these
manifestations of approbation, hesitatingly arose, and, with the marks
of doubt, irresolution and perplexity, deeply depicted on his
countenance, timidly observed,
"I am very fearful, respected Brothers, that we shall act too
precipitately in this painful business. I am aware that most of our
obligations conclude with penalties or imprecations of death; but
these are ancient forms, and adopted probably in the dark ages, when
laws and customs were altogether different from those of the present
day. And I am not, I confess, without some misgivings and doubts
whether we are authorized, in these times of civilization and
wholesome laws, to execute these penalties according to their literal
meaning. Indeed I believe that some intelligent masons are of the
opinion that an expulsion is all the punishment that we now have any
right to inflict for betraying the secrets or"—
Here a general sneer of contempt and indignation interrupted the
speaker, and "Who thinks so?"—"who says so?"—"where are the
cowardly traitors that dare avow it?" hastily demanded half a dozen
members at once, starting on to their feet and bending their angry and
almost withering looks full on the abashed and shrinking speaker.
"Order!" exclaimed the Master, giving a loud rap on the
table—"Order, Brethren! Our councils vouchsafe a free expression of
opinion, and each member has a right to utter his sentiments, however
erroneous and unmasonic they may be. And it is the duty of the
brethren to curb and circumscribe their passions within due bounds,
and endeavor to enlighten the erring by reason rather than with the
language of menace."
Thus rebuked by the Master, the brotherhood, restraining their
agitated forms and disturbed feelings, again sunk into silence—not
however, without throwing many a dark and meaning look, and many a
glance of suspicion on the weak and erring brother who now sat mute
and trembling and seemingly sinking to the floor under the weight of
his own conscious unworthiness.
Order having now been restored in the conclave, the discussion was
resumed. Several speeches of a very determined tone, and full of fiery
declamation, were now made in opposition to the remarks of the
doubting brother. After which, a member of the conclave who had been
a cool and dispassionate, and so far a silent observer of the scene,
now rose and calmly observed,
That for one he never approved of the use of harsh terms in
expressing the performance of those disagreeable duties which justice
sometimes required at their hands. They often served to alarm the
timid and faint hearted; besides, they were not in accordance with the
general policy of the craft. Such things should be expressed, he
said, as they should be done, with that caution and prudence which
constituted some of the most cardinal virtues of the true mason. But
as to the principle laid down by his illustrious and eminently gifted
brother Peacock, aside from the terms in which it was expressed, he
was surprised that any doubts should be entertained by any intelligent
mason on a point which he considered so well settled by the
precedents and examples to be found in the history of the institution.
So saying he then took up a book, and, turning to a passage at which
he had previously turned down a leaf, proceeded to read the history of
the degree of Elected Knights of Nine, also of the degree of Elected
Grand Master, or Illustrious Elected of Fifteen; the former giving an
account of the death of Akirop, who, having been guilty of some crime
of an enormous nature, had fled from Jerusalem and concealed himself
in a cavern, where he was seized by a band of trusty brethren,
allotted to that honorable service by their Grand Master Solomon, and
slain by Joabert, who in his impatient zeal thus anticipated that
justice on the traitor which of right belonged to the Grand Master to
execute. The latter passage described a similar transaction.
"Now, Right Worshipful Brethren," said the speaker, closing the
book and looking down upon it with a sort of embarrassing modesty as
he stood carelessly balancing it in his hands,—"this work, although
perhaps it does not become me to speak of its merits, yet having been
diligently compiled from the best historical authorities, and
carefully compared with all the traditional accounts on the subject,
and moreover having been fully approved and recommended by competent
judges, whose names are hereto prefixed, as a true and authentic
history—this work, I say, it seems to me, is calculated to throw all
the light on the subject now under consideration which can possibly
be needed to indicate the course of our operations. We here see that
the brethren were so anxious for the honor of bringing the traitor to
justice for this crime, which, whatever it might have been, is ranked
in the oath of the degree the same as the crime of divulging the
secrets, and subject to the same punishment, that Solomon was
compelled to restrain their commendable zeal, and decide by lot who
should be the favored few to perform this important and glorious
service. And we further see that when Joabert, in his just indignation
against the traitor, had too impatiently slain him, Solomon was even
offended with this zealous brother, not on account of the act, but
because he had deprived him of the enviable chance of meting out
justice to the villain with his own hands; but by proper intercession,
however, he not only became appeased and forgave Joabert, but invested
him with the highest honors in reward for this heroic service to the
institution! Now will any mason dare attempt to impeach this high
example, or question the rectitude of the conduct of that eminent
Grand Master of antiquity? And are we, who are but the dust of
the balance in the comparison, are we sitting here coldly
hesitating, and doubting the right and justice of the act which the
illustrious King Solomon, who has so long and so proudly been hailed
by our admiring order as the great and shining light of the East to
guide their humble footsteps in the paths of masonic wisdom— the
right and justice of the act, I say, which the illustrious Solomon
thus esteemed and thus rewarded? Is this such a specimen of light and
improvement as you should be willing the shade of that mighty man,
looking down from his lofty seat in heaven, should behold in his
followers? I beg leave to close my remarks with a quotation from the
same work:"
"King Solomon, our patron, Transmitted this command— The faithful
and praiseworthy True light MUST understand. And my
descendants also, Who're seated in the East, Have not
fulfilled their duty, Till light has reached the West."
Closing his observations with this beautiful little specimen of the
inspiration of the mystic muse, here so appositely introduced, the
learned speaker sat down amidst the warm, deep, rapturous, and
long-continued applauses of the approving brotherhood, who thus, with
almost united acclaim, pronounced the sense of the conclave on the
subject matter in debate.
Nothing further being offered in opposition to the affirmative of
this important question, and there having been such decided
indications that the arguments and cited authorities of the last
speaker had, in the minds of the conclave, unanswerably and
irrevocably settled the fate of the victim, this part of the
discussion was now dropped, and the mode of disposing of the
unfortunate man was next brought under consideration. Here there
appeared to be some diversity of opinion: Some proposed that lots
should be cast, after the example of King Solomon, for designating
the performers of this important duty: Some that the villain should
be put out of the way by the first of their number who should meet him
alone in some by-place to which he might be easily allured: Some
thought that he should be dealt with by the full council in the
lodge-room where the penalties should be executed in a true and
strictly masonic manner, else it would be but little better than
actual murder; and others that it should be done by volunteers who
should be left to choose their own time, place and manner of
performing the meritorious deed. None of these however seemed fully to
answer the minds of all present. It was in this emergency that the
genius of our hero, which often seemed to be masonically intuitive,
shone conspicuous. He proposed that as many balls as there were
members present should be put into an urn, three of which should be
stained with blood, or some red substance, as indicative of the duty
of those who should draw them: and that the urn should then be passed
round, when each member should draw out one of these balls, and,
without examining it, put it in his pocket till he had left the lodge
room, when those who, by inspecting their respective balls when
alone, discovered themselves to be the fortunate men, should meet each
other at midnight in the most central church-yard, hold a private
meeting, and concert measures for the execution of their duty, which
was however to be performed according to masonic technics, though in
some secret place, and without the knowledge of any other of the
This ingenious and truly masonic plan of our hero was received by
the conclave generally with the most flattering approbation. Some
praised it because it embraced in substance the plan they had
suggested: Some because it was better calculated than any other way to
prevent giving rise to any of those little jealousies and feelings of
envy which might be created towards those who had the superior good
fortune to be designated for the honor; and yet others of the prudent
and cautious cast approved of the measure on account of the safety it
insured to all concerned, in case of discovery and a meddlesome
interference of the civil authorities, who would thereby be deprived
of witnesses except in the immediate actors, or principals, who could
not be compelled to criminate themselves. In short, all saw the
advantages of the proposed plan, and it was immediately adopted.
The several members of the conclave now commenced, with great
alacrity, making preparations for carrying the plan of operations into
instant effect. An urn, containing a number of the marbles used in the
common ballotings of the lodge-room, corresponding to the number of
members present, was brought forth and set upon the table—when
Timothy, heroically pricking a vein in his own wrist, took three of
the balls and bathed them all over with the blood thus produced, till
they were deeply and indelibly stained with the significant and
ominous color. After which they were returned and shaken up with the
balls remaining in the urn. The brethren were then formally arranged
at equal distances from each other round the long, eliptical table,
about which the conclave had been irregularly gathered during their
discussion, and the solitary lamp, which had set in the midst, was
removed to a distant corner of the room. The fate-holding urn was then
taken by a Warden and passed slowly and silently along the gloomy
circle, and, while the distant and feeble light dimly threw its
sidelong and flickering rays athwart the livid and ghastly-looking
visages of the darkly grouped brotherhood, displaying the varying
indications of the deep and contrasted emotions with which they were
respectively agitated—from the demoniac smile of anticipated
vengeance, to the cold and settled gravity of predetermined
justice—from the stern and fiery glance of the headlong and
danger-daring, to the hesitating start or convulsive shudder of the
misgiving and doubtful—all, in turn, were subjected to the test, and
successively put forth their tremulous hands and drew out their
uncertain allotments.
This fearful ceremony being now concluded, the Master then stated
to the conclave that this meeting not having been a regularly opened
and conducted lodge, but acting as a select investigating tribunal,
and the criminal not having been present, it had been deemed advisable
to hold on the following evening a Grand Council of Knights, before
which the guilty wretch, (measures having been taken to have him in
town,) would be arraigned to answer to the dreadful charge which had
been preferred and proved against him,—this mode of procedure being
considered most conformable to ancient usages when one of the craft
had been found guilty of treasonable or other heinous offences
against the institution. And here, if he did not, like some of the
ancient traitors, imprecate his own doom, the fearful sentence which
had this evening been matured, would be pronounced against the
perjured offender, and he would be left to those on whom the high duty
might devolve of meting out the measure of justice adequate to the
enormity of the crime. The conclave then broke up, and the brethren,
after lingering awhile to make arrangements and devise measures for
the operations of the next day and evening, stealthily retired to
their respective abodes.
No sooner had our hero reached his lodgings and found himself
alone, than he eagerly pulled forth the uncertain ball—when, to the
unspeakable delight of his aspiring soul, he saw himself one of the
honored and fortunate three who were commissioned for the important
duty—a duty which the lapse of ages might not again afford the
enviable chance of performing.
With such heroic and exalted feeling glowing in his devoted bosom,
he sat off at the appointed hour for the designated rendezvous of the
chosen trio, the result of whose deliberations will be seen in our
following and final chapter.
CHAPTER XIX.
"There is no doubt but Morgan richly deserved his fate."
Massachusetts Newspaper.
Many were the strange faces—strange to the citizens generally,
though not to the brotherhood—which were seen in the different parts
of the town on the day following the conclave described in the
preceding chapter: For many distinguished for the eminence they had
attained on the mystic ladder, coming on various pretences from the
neighboring towns and cities, had here now assembled to assist their
brethren in their deliberations, and in concerting and carrying into
effect all those provisional measures for secrecy and safety which
might be required for ensuring the present and ultimate success of
their fearful undertaking.
It was nearly sunset when Botherworth arrived in the place. After
putting up, and taking some refreshment, at a public house, he
immediately repaired to the quarters of Rodgers, the commercial
correspondent of whom we have already made mention. That gentleman,
however, though apprised of Botherworth's arrival within a few moments
from the time it happened, as were most of the combination of which
the former, as the reader may have already suspected, was an active
member, not wishing to meet the latter till about dark, both because
it would not comport with that part of the plan of operations which
had been assigned to his management, and because he was unwilling to
risk his countenance with so much concealed beneath it, in a
confronted meeting by full day light, had now just stepped out, having
left word that he should return in a short time to attend upon such as
might call in his absence, or wait on them at their lodgings. On
learning this from the person in attendance, Botherworth slowly
sauntered back to his hotel, and amused himself with a newspaper till
it became too dark to allow of his reading any longer by day-light. He
then arose and left the house with the view of going a second time in
search of Rodgers. He had proceeded but a few rods, however, when he
was met by the person in question. At the first sight of this man,
Botherworth made, he knew not why, an involuntary start, recoiling
from his approaching person as from the contact of a viper, and felt
for the instant all those dark and fearful sensations of vague
apprehension, which the last evening at home he had so unaccountably
experienced, again rushing over him; but making a strong effort to
repel these unwelcome intruders, he soon succeeded in so far mastering
these feelings, as to salute Rodgers with considerable show of
cordiality. His greeting was returned by the other with equal attempts
at cordiality, but with an air and manner no less embarrassed and
hesitating, though arising from causes far different, as the
conscience of the latter but too plainly informed him.
The mutual civilities and common-place questions usual on such
occasions being over, Rodgers carelessly observed that his partner had
just returned, as he had learned a few minutes before, from an
excursion to the neighboring port, and had probably brought news with
him which would be interesting to them both, and perhaps necessary to
know before coming to any determination on the business which had
caused their present meeting: he would therefore propose a walk, if
agreeable, to his partner's residence, which was situated, he said, in
an opposite part of the town. Botherworth, readily assenting to this
plausible proposal, and not being acquainted with the situation of the
house in question, immediately gave himself up to the guidance of the
other, and they proceeded leisurely along, frequently pausing, at the
suggestion of Rodgers, to inspect the new buildings which they passed
in their route, late improvements in the streets, and such other
objects as the latter could find for enlisting the attention of his
companion, and consequently for delaying their progress. Upon all
these Rodgers now seemed uncommonly communicative, and, as
Botherworth thought, strangely disposed to linger. In this dilatory
manner they proceeded on, the latter expecting every moment when they
should arrive at the place of destination, till they had reached the
very outskirts of the town, and it had become quite too dark for
further observation on the objects around them. Botherworth mentioning
both of these circumstances to his companion, asked him if they had
passed the residence of his partner. On which Rodgers replied that the
evening was so pleasant that he had gone somewhat out of their direct
route for the purpose of observing and pointing out the novelties
which were always springing up in a town of that size, and they had
now got considerably beyond the place; but they would immediately
return by the shortest course. So saying, and taking the arm of his
still unsuspecting companion, Rodgers turned about, and, with a
quickened pace, struck into another street leading back into the most
populous part of the town. In this way they passed rapidly on,
frequently making short turns, and crossing into other streets, till
Botherworth (it now having become very dark, and he not being
familiarly acquainted with this part of the town) became wholly at a
loss as to the street they were traversing: when all at once, Rodgers,
who had all along been extremely sociable, and was now in the midst
of a ludicrous story, suddenly turned into the yard of a tall
building, and, with a sort of hurried motion, pulling the other along
with him, and interrupting himself only to say, in a quick,
parenthelical tone, "Here-here—this is the place," made directly up
to the open door, and unceremoniously entered.
Here finding themselves in what appeared to be a broad space-way,
or passage leading to other parts of the building, they continued to
advance forward, groping their way through the almost utter darkness
before them, till they had proceeded some fifteen or twenty feet from
the entrance, when Botherworth, wondering that no light was to be seen
in any direction, and thinking that things wore a rather strange
appearance for a private dwelling, began to pause and hesitate about
proceeding any farther. Just at this moment a slight bustle from
behind attracted his attention, and partly turning his head he
distinctly heard the sound of slowly turning hinges: and whirling
suddenly round, he imperfectly distinguished some persons cautiously
pushing to, and closing the door, behind which, in a dark corner of
the space, they appeared to have been standing in concealment.
Scarcely had he time to rally his thoughts, before Rodgers, now
relinquishing his arm and stepping out of his reach, gave a sharp rap
on the wall with his cane. Botherworth's suspicions being now
thoroughly aroused, he sternly demanded of Rodgers what building this
was, and what was the meaning of all these singular movements. But
before he received any reply, and while repeating the question in a
louder and more startled tone of voice, a man suddenly appeared with a
light at the head of a broad flight of stairs leading up from the
space-way to a large hall on the second floor, and began to descend,
holding the lamp in one hand and a glittering poniard in the other,
while his person was invested with all the showy insignia of one of
the higher orders of masonry. Botherworth gazed on the scene now
unfolded to his eyes, in mute amazement. At the entrance through which
he had passed into the building, stood two men, one just in the act of
withdrawing the key from the door which he had locked on the inside,
and both armed with the same weapons and clothed with the same badges
as worn by the brother who appeared in the opposite direction. Rodgers
was standing at the further end of the space-way, pretending to be
looking for some door or place for escape, and affecting great flurry
and surprise, as if they had got into a wrong building by mistake:
while the man coming down stairs, having paused about midway, now
stood fumbling and trying to unfold a paper which he held in his
hands. A moment of profound silence ensued, in which all parties stood
gazing at each other in deep surprise or awkward embarrassment.
Botherworth, however, who now saw the whole truth at a glance, was
not long in giving utterance to the rising tempest of his emotions.
"Treacherous wretch!" he exclaimed, with bitter energy, turning his
eyes, fiercely sparkling with indignation, and throwing out his
clenched fist towards the mute and shrinking form of Rodgers,
"treacherous wretch! is this the game you have been playing all the
while to decoy me into this pit-fall! Speak, villain!" he continued,
uplifting his arm and advancing toward the dumb-founded and trembling
betrayer, "speak, perfidious, doubly damned villian, or I will"—
`Stop, stop, sir,' cried one of the men at the door, rushing
quickly between them, `this course will not avail you here.'
"Here!—where?" exclaimed Botherworth, turning roughly on the
intruder, "and who are you, to assume the right of interfering
in our private quarrels?"
`Where you are, and who
we are, these badges will well
inform you,' retorted the other, pointing to their aprons, `and as
for this man, whom you are so harshly assailing, he has done but his
duty, as the business we have with you, sir, will shortly show you.
Brother,' he continued, motioning to the man on the stairs, `why delay
to execute your mission?'
"Is your name William Botherworth?" now asked the latter, in some
trepidation, descending the remaining steps, yet keeping at a
respectful distance from the person addressed.
`And supposing it is, what then, sir?' said Botherworth scornfully,
in reply.
"Then, in that case, and you seem to admit the fact," replied this
doughty minister of the mystic mission, holding out the paper which
quivered in his hand like the leaf of an aspen, "then, sir, I have
here a summons for you, in behalf of our Venerable Council, above
assembled, and by order of our Most Potent Grand Master, to appear
before them, and answer unto certain matters and charges then and
there to be preferred against you, of which you may not fail to
comply."
Botherworth, after sending an anxious glance round the apartment
and scrutinizing anew the looks and persons of those around him, as if
searching for some avenue of escape, or weighing the chances of
overpowering his captors in a sudden onset, and seemingly rejecting
such expedients as hopeless, at length, in a tone of mingled
submission and defiance, observed, `Well, be it so—I see I am
ensnared, and in your power, and what I am compelled to do, I may as
well do unconstrained—I will go in, but if the liberty of speech is
not also denied me, they shall hear some truths, though all the
mock King Solomons in the country should be present.'
So saying, he motioned to his keepers his readiness to attend them
to the hall; when two of them immediately closed in on each side of
him, after the manner of the guards of a prisoner, and, while the less
stout-hearted brother, who had acted as grand summonser on the
occasion, nimbly mounted before them to herald their coming to the
council, they all ascended the stairs, leaving Rodgers (who was, it
seemed to be understood, having now fulfilled his part in the drama,
to be excused from any farther attendance) alone to his own enviable
reflections on the noble and generous part he had acted towards his
confiding acquaintance. On reaching the hall door, one of the
brothers gave the appropriate rap, which was immediately answered by
another within, when, after waiting a few moments, the door opened,
and they were ushered into the same spacious lodge-room mentioned in
the foregoing chapter.
Here a scene, in which the splendid, the grotesque and the
terrible, were strangely blended, now burst with over-powering
brightness on the dazzled and unexpecting senses of Botherworth. The
lodge had been opened with the imposing and fearful degree of Elected Knights of Nine, as being, in the opinion of the
brotherhood, more appropriate than any other to the important occasion
which had called them together. The hall, intended to represent the
audience chamber of King Solomon, who is said, by the standard
historians of the craft, to have instituted, in his wisdom and mercy,
this tragical order of knighthood, was decorated with hangings of
white and scarlet, pictured in flames, as typical, probably, of the
leading characteristics of the degree, like the fiery and
torture-painted robes worn by the victims of the Inquisition on their
way to the stake. Nine bright lights in the east and eight in the west
sent forth their steady streams of reflecting light, and filled the
room with the most dazzling effulgence. The Most Potent Grand Master,
personating Solomon, was seated in the east under a purple canopy,
embroidered with skeletons, death's heads and cross-bones, with a
table before him covered with black, dressed out in all his royal
robes, with a crown on his head and a glittering sceptre in his hand.
While the brethren, arranged in formidable array on either side of
the throne, and clad in the deepest black with broad ribbons of the
same color pending from their shoulders, and terminating in tasselled
dagger sheaths, with aprons of white, but sprinkled with blood and
painted with the figures of bloody heads and arms, holding bloody
daggers, and with broad brimmed hats on their heads, slouched over
their eyes, now stood with drawn poniards in their uplifted hands,
fiercely scowling at the new comer at the door, and looking like a
gang of bandits just interrupted in some bloody achievement with the
gory evidences of their unholy deeds freshly reeking upon them. The
whole presenting a scene to the unapprised spectator, as wild and
incongruous, as it was terrific and revolting. A spectacle more
calculated perhaps to inspire awe, to dazzle and appal, than any one
to be met with, in the whole round of masonic machinery, and a
spectacle indeed, before which even the naturally fearless Botherworth
could not keep his stout heart from quailing.
After a few moments of profound silence, maintained apparently in
order that the imposing scene before him might have its full effect on
the mind of the prisoner, the brethren, at some slight signal from the
throne, all sunk back into their seats, crossing their legs at the
knee and resting their heads on their right hands;—when the Master
knocked eight and one with the handle of his poniard which was
instantly repeated by the Grand Warden in the west, and then by all
the brethren together. The noise of this instructive ceremony having
died away, and all again become hushed in silence, the Grand Master,
laying aside the poniard and elevating his sceptre, looked round the
Council and said: "Elected Knights and Princes of Jerusalem present,
let the accused now be presented before our tribunal of justice and
mercy." The two brother Knights, who conducted Botherworth into the
room, and who still retained their places at his side, now led the
latter forward near the middle of the floor and directly in front of
the throne; when the Most Potent, in the deep and passionless tones of
a judge, addressed him as follows:
"William Botherworth—you stand charged of wantonly and wickedly
violating the sacred obligations which you have voluntarily taken
never to reveal, except to a brother, the secrets and mysteries of our
divine institution, by communicating the same to one of the profane
and uninitiated. You are also accused of having, in an early period
in your life, set at nought the sacred injunctions of our institution
by a pretended initiation of one seeking the true light, wherein our
awful solemnities were impiously turned into ridicule and mockery, and
our order greatly scandalized. To these dreadful allegations which
have been fully substantiated to us and of which we have proofs at
hand, what do you plead in defence, and what reasons offer, why the
ancient usages of our honorable fraternity should not be conformed to,
touching the punishment of so heinous and high-handed offences?"
With a slight quivering of the lip and tremulousness of the voice,
but with a firm and undaunted countenance, Botherworth, looking slowly
round on the portentous faces of the brotherhood, and settling his
keen and indignant eye on the Master, replied:
`Most Worshipful Master, and you gentlemen, abettors, or Knights,
or whatever title you, or either of you may please to assume, to sit
in judgement upon me, addmitting all the facts set forth in your
charges, the truth of which you assume to have been already
established against me, though I have never been confronted with my
accusers, or allowed even the shadow of hearing or trial—admitting I
have confidentially communicated to an individual the secrets or
ceremonies of an institution from which I have been long ago
expelled—admitting all this, I hold myself justified and blameless
in the act. I account myself absolved from the obligations which you
say I have violated—obligations which I never voluntarily or
understandingly took, but which were forced upon me, trembling under
the often applied torture of sharp pointed instruments, and confused
and bewildered by the new and startling objects around
me—obligations which, even in any circumstances, those imposing
them had no just right or authority to administer,— which in
themselves, are immoral and illegal, enjoining as they do, in many
parts of them, acts contrary to the laws of the land and prohibited by
the precepts of revelation, and which, therefore ought not, and cannot
be binding on the conscience or conduct of those who unfortunately
become subjected to their unjust and soul-damning enthralment. And
having violated no law of my country— contravened no rule of
morality or any way infringed upon the rights of individuals, I deny,
fearlessly deny, the right of your institution, to which I owe no
allegiance, to arraign, and bring me to judgement, and I will hold
myself amenable to none of your tribunals.'
"Perjured wretch!" exclaimed the Master, kindling in resentment for
the insulted dignity of his sacred office, and shocked at the
audacious heresies of the accused,— "perjured wretch! dare you in
the same breath confess your sacred oaths violated, and exult in your
unatoned guilt? We are not wanting in authority to judge, or power to
execute. Tamper not with the sword of justice, for it is not slow in
vengeance. Villain! fear and tremble!"
`I fear you not,' resumed Botherworth, in the same undismayed and
reckless tone, `I neither fear your authority, or tremble at your
threatenings. I will say nothing of the singular and volume-speaking
fact that I now stand a guarded prisoner before you, in a free
country, and in the heart of a christianized and intelligent
community, arrested by no legal authority, and retained in duress by
those who have no right to control my actions. I will say nothing of
the base and detestable plan of deceit and treachery, by which I was
entrapped and brought into this place by one of your number, acting
doubtless under commission from this illustrious Council. I will say
nothing of these, for they flow directly from that system of darkness
and iniquity which are the Jachin and Boaz, the very pillars and
keystone of your boasted institution—they are but the legitimate
fruits of those fearful oaths which require of the poor blinded and
haltered candidate, at the very threshold of your pagan temple, to
give his sanction to murder and suicide; and which go on enjoining, as
he advances step by step along its bewildering labyrinths of moral
pollution, the same connivance or commission of acts of a deeper and
deeper turpitude, till at length he finds himself, as the occasions
arise, doubly, trebly, and irretrievably sworn to the participation
or execution of half the foul deeds to be found in the whole dark
catalogue of crime! I will not trouble you with a further recital of
my private opinions of the character of your institution, nor of those
settled and honest convictions which long ago forced me to the choice
of burning my Bible and rejecting its law of universal love, charity
and forgiveness, or of discarding forever my masonry with its whole
system of selfish favoritism, iniquity and vengeance,—and which, I
need not tell you, resulted in the determination to retain the former
and renounce the latter. I will not detain you, as well I might, with
arguments and allegations like these. But, in answer to your question
when you ask what reasons I have to offer why the ancient usages of
your order should not be conformed to respecting my punishment, I
again repeat, that no law either human or divine has given you
jurisdiction over me. I again boldly deny your right to judge or
control me. I fearlessly impeach your pretended authority, and, aware
as I am of the fearful doom which a conformity to those usages would
involve—of the dark and murderous designs which your menaces imply,
I bid you beware how you attempt to execute your hellish purposes. I
bid you beware how you lay a finger upon me for evil. The loud cry of
murder will reach beyond the walls of your infernal conclave, and
summon up a host to my aid. But should you succeed in the foul designs
which you are plotting against me, I bid you remember the prophetic
warning which I now give you—my blood will not long be unavenged;
but crying up from the ground, will be answered in the judgement of
heaven, which will soon smite your proud fabric to the dust, and lay
your unhallowed and impious mysteries, and your bloody register of
crimes!'
As Botherworth closed this audacious speech, arraigning with such
daring mockery the exalted purity and justice of the divine
institution of masonry, and bidding defiance to its heaven-delegated
authority with such high-handed insults, there was a deep and general
commotion in the Council. Dark and sullen looks of hatred and
detestation, and quick and fiery glances of indignation were every
where bent on the blaspheming speaker, and, accompanied by the heaving
breast, the short, suppressed breathings, and the low, broken
mutterings of out-breaking wrath, now but too plainly indicated the
determined and unanimous purposes of the outraged and agitated
brotherhood.
The Most Potent now hastily rising from his seat, with every muscle
quivering with rage, and with a voice half choked with emotion, rapped
furiously on the table, exclaiming, "Anathema maranatha! Anathema
maranatha!"
Swift as echo came the startling raps of the brotherhood in
response.
"Nekum!" cried the Master.
"Vengeance!" responded the Council.
"So mote it be!" said the Master.
"Amen, amen, amen, amen!" exclaimed the brotherhood in eager reply.
The formalities of order were now no longer attempted to be
maintained in the Council; and the members, hastily leaving their
places, began to scatter promiscuously over the floor of the
lodge-room—some gliding stealthily out of the door, some gathering
into small groups about the room and whispering together with quick
and earnest, but restrained gestures—some passing in and out the
preparation-room and disrobing themselves of their masonic habiliments
or badges, and others with hurried, nervous steps, and excited
countenances, moving to and fro in seeming preparation for some
approaching event; while the low, half suppressed murmur of eager
voices which ran through the hall, and the expectant looks and
attitudes every where visible, seemed to indicate that the crisis was
now at hand.
Botherworth was by no means unmindful of these ominous appearances;
and, not being very strictly guarded at this moment, he began to edge
along by degrees towards the door, which, though still effectually
tyled, afforded nevertheless the only avenue for his escape from the
hall. His progress, however, was quickly arrested by the watchful
brotherhood, who no sooner observed the movement than they
immediately gathered round the spot where he stood, some falling in
between him and the door to obstruct his way, and others, with
affected indifference and carelessness, jostling about his person. But
Botherworth, not relishing such familiar proximity just at this time,
sternly bade them stand off at their peril. This repulse had a
momentary effect in making them give way; yet they soon again closed
up around him, and, though awkwardly mute, still continued the same
manoeuvres of frequently changing places, turning round and rubbing
against his body. Becoming more and more suspicious of this singular
conduct, he again attempted to disengage himself and make his way out
of the crowd, when all at once one of the brethren, who, like the
tiger, had been watching for a favorable opportunity to seize his
prey, suddenly sprang upon him from behind, and grasped him with both
arms fast round the middle. A brief but desperate struggle now ensued.
With a prodigious effort, Botherworth wrenched himself from the grasp
of his antagonist, and hurled him headlong to the floor: But before he
could avail himself of his advantage, both of his own legs were
grappled by another of his foes, and he himself was prostrated in
turn. A dozen now sprang upon his body at once, and with maniac grasp
confined him to the floor, while one darting to his head, passed a
large pocket-handkerchief over his face, and, holding both ends, drew
it forcibly through his mouth just as the stifled cry of murder was
escaping his lips. Holding him in this situation till he had nearly
exhausted his strength in his ineffectual struggles to get free, his
victors then proceeded to disable him from making uny farther
resistance. They first firmly tied his wrists together behind
him—next closely pinioned his arms with a rope, one end of which was
left dangling in his rear for future purposes; and lastly, so
effectually gagged him as to prevent the possibility of his raising an
alarm by any articulate cries for assistance. He was now helped on to
his feet, and, after being threatened with instant death if he
attempted to groan or make any noise, led down stairs by two of the
brethren walking each side and holding their poniards to his breast,
while a third holding on to the end of the rope, and armed with the
same weapon to prick him if he faultered, followed behind. At the
door stood a close carriage drawn up in readiness to receive the
prisoner, and two of the three brothers who had been allotted the
preceding evening to the last important duty, and who had now left the
lodge-room for the purpose on the breaking up of the Council, were in
attendance, anxiously awaiting his appearance from the hall—one of
whom, having mounted the driver's seat, was now holding the reins,
while the other, who was no other than our hero, was seated within to
take charge of the unfortunate man on the way to the place which had
been appointed by the three for the final catastrophe, and whither the
third one of their number had already proceeded alone to see that all
things were duly prepared, and to await the arrival of his companions.
When the keepers of Botherworth had got him to the door, they made
a brief pause, and, in a quick, under-tone of voice, exchanged the
pass-word with their companions in waiting. They then, after peering
about a moment in the darkness to discover if any one was approaching,
hastily urged him forward, forced him into the carriage, and, in
willing ignorance of the identity of the brothers to whom they had
delivered their charge, instantly retreated back to the recesses of
their sanctum sanctorum to join their brethren in resuming the
deliberations of the conclave. But having no occasion to witness the
further proceedings of the rest of this illustrious assemblage, let us
bid them a final adieu, and follow the fortunes of our hero, who was
now about to fill the measure of his masonic glory in the closing
scene of our changeful and sad-ending story.
As soon as Timothy had seated the prisoner by his side in the
carriage, securely possessed himself of the end of the rope by which
he was pinioned, and sternly enjoined the strictest silence at the
point of his poniard, he made a signal to his companion, and
immediately they were in motion on their way out of town.
Trembling with the most painful solicitude and fearful apprehension
lest something should occur to excite suspicion, or frustrate their
purposes, did our hero and his trusty companion pass slowly and
cautiously along the different parts of the town, and though the
streets were now dark and deserted, or illumined only by here and
there a light dimly twinkling through the gloom, and silent as the
city of the dead except occasionally perhaps the distant and dying
sounds of the receding steps of some benighted debauchee stealthily
pursuing his way homeward, yet they suffered not their vigilance to
abate, nor would their feelings allow them to breathe freely, till
they had passed the last straggling tenement of the suburbs,—when
feeling comparatively relieved from this agitating sense of insecurity
and fear, they struck off into an uninhabited road, and proceeded
rapidly onward to the place of destination. After a drive of about
half an hour, during which the gloomy silence of the way was only
broken by the deep sighs and stifled groans that sometimes
involuntarily burst from the bosom of the agonized and wretched
prisoner, or the rumbling of distant thunder now occasionally heard in
the south, which seemed to send forth its low, deep utterance in
mournful response to his sufferings, the carriage halted near an
extensive sheet of water.
The brother who had acted as driver, having dismounted from his
seat, and fastened his horses, now repaired to the carriage door and
threw it open;—when he and our hero helped Botherworth out upon the
ground, and after placing him between them, and cautiously securing
their holds on his person, they turned into a narrow lane, and forced
him along till they arrived at the water's edge.
Here lay a boat in which their pioneer brother was now standing,
just handling the oars, and making ready to push off from the shore.
The boat was a large skiff with three boards thrown across for seats,
besides the low one near the stern for the oarsman, but with nothing
else about it uncommon or suspicious except a fifty-six pound iron
weight which lay in the bottom in the rear of the middle seat.
As soon as the brother in charge of the boat was recognized as such
by his companions on shore through the official medium of the
pass-word, the prisoner, after some ineffectual attempts at
resistance, was dragged on board and placed on the centre cross board
or high seat. Our hero took the seat in front, and his compani on the
driver the one next behind the prisoner, while in rear of all, the
third of the consecrated band, betook himself to the seat and office
of oarsman. Thus arranged, they headed round, and immediately pushed
out towards the middle of the wide expanse of sleeping waters that lay
shrouded in darkness before them.
For some time they rowed on in silence, while the gloom seemed
every moment growing more and more deep and impenetrable around them.
When all at once a broad and lingering flash of lightning burst upon
the waters in the brightness of noon-day, displaying a scene in the
boat at which the brotherhood themselves startled. The oarsman with
his lips in motion counting the stroaks of his oars, a calculation
having been made of the number required to carry them far enough from
the shore for their purpose, was now bending lustily to his work,
while the large drops of persperation were falling fast from his
anxious and troubled brow. The brother sitting immediately behind the
prisoner, was egerly engaged in tying the end of the rope, by which
the arms of the latter were confined, to the iron weight that lay
between them in the bottom of the boat. While the victim himself,
still unconcious of the fatal machinery preparing at his back, was
glaring, with the attitudes of surprise and horror, upon the face of
Timothy, whom he seemed now for the first time to have recognized as
his old acquaintance; for the latter had not only kept his return a
secret from all but the brotherhood, but, for reasons best known to
himself, had carefully avoided confronting Botherworth in the late
lodge meeting. And on thus unexpectedly discovering among his foes the
person whom he had supposed some hundred miles distant—whom he had
often obliged as a friend and neighbor, and to whom now, but for the
connection in which he found him, he would have confidently appealed
for aid in this emergency, the astonished and heart-struck man started
from his seat, and gazing an instant on the rapt and lofty mien before
him with a look which spake that to which the Ettu Brute of
Caesar were meaningless, sunk dispairingly down with a groan of
unutterable anguish as the last glimmerings of the wasting flash
played faintly over the deeply depicted wo of his distorted features.
A loud peal from the approaching thunder-cloud came booming over the
broad face of the bay, and all again was hushed in silence and
darkness.
Our hero's philosophy and sense of masonic justice as stern as was
the one, and as exalted and deep-rooted as was the other, were, it
must be confessed, a little shaken by this unexpected incident. The
thought that he was about to lift his hand against one whom he had
long familiarly known as a kind and agreeable neighbor produced indeed
some unpleasant sensations, and made kim for the moment almost relent
of his noble purposes. But other thoughts soon came and brought with
them an antidote for this excusable frailty of feeling. He thought of
his insulted father whose injuries had never been avenged. He thought
of the just behests of that institution to which his heart was
wedded—whose sacred principles he had irrevocably adopted as his
only guide of action in life, and his pass-port to heaven in the hour
of death, and whose violated laws now seemed to cry aloud for
vengeance on the audacious wretch who had spurned and trampled them
under foot with such impious defiance. And above all, he thought of
his own solemn oaths in which he had unreservedly sworn on the holy
bible, invoking the everlasting God to keep him steadfast. "To
sacrifice the traitors of masonry." "To be ready to inflict the
same penalty (that suffered by Akirop) on all those who
disclose the secrets of their degrees," and "to take vengeance
on the treason by the destruction of the traitor"—and were not
these sacred obligations to be regarded? What were the ordinary
injunctions of the civil laws of the country to these? What indeed
had they to do with him in such a case? He was entirely aloof from
their prohibitions, and above their control. He was the honored
subject of another, and paramount government, and under its high
sanction he was now acting. And as for incurring any moral guilt by
the deed he was about to commit, that was inconsistent and impossible;
for in one of those sublime and exalted degrees he had taken he had
been "made holy," and consequently was now placed beyond the
liability of sinning. He thought of all these, and as they passed
through his mind, he wondered at his momentary weakness. His bosom
again became steeled, and his arm nerved for the high and enviable
duty before him, and he grew impatient for the moment of its
execution to arrive.
Meanwhile the thick and blackening mass of cloud in the south was
rapidly approaching. Nearer and nearer fell the thunder-claps, and
more and more vividly played the lightnings around the wide-stretched
and lofty van of the dark, moving column—now shooting fiercely and
perpendicularly down from their vapory battlements above to the face
of the startled deep beneath—and now, like the fiery serpents of the
fabled Tartarus, crinkling and leaping from wave to wave along the
wide arena of their terriffic gambols till the whole bay was kindled
into light and seemingly converted into one vast Phlegethon of flames.
The prisoner at each returning flash, during the first part of this
grand and fearful scene, was observed to send many a searching and
wistful look around over the face of the vacant waters. And now,
finding there was no foreign vessel in sight, or any other craft
indeed, to which his keepers could be taking him, as he seemed to have
imagined was, at the worst, their purpose, he began to grow every
moment more alarmed and restive. A cold sweat stood on his face, and
his features became more and more troubled, and his eyes more wildly
despairing, till his whole frame seemed to writhe in agony under the
workings of his dreadful apprehensions. And, though still painfully
gagged, deep and heart-rending groans, now in the accents of wo and
distress, and now in the tones of supplication to his keepers, or to
heaven for mercy, were continually bursting in convulsive sobs from
his anguished bosom.
For many minutes the boat still shot swiftly onward in its course,
with no other indication that the fast nearing storm or the increasing
restlessness of the prisoner were heeded by the brethren, except in
the augmented velocity with which they forced their skiff through the
surging waters. But soon, however, the strokes of the oarsman began
visibly to relax, while the cautious changing of postures, the fixing
of feet, and the long-drawn and tremulous respirations of the band,
plainly told that the awful moment was approaching. At length, in a
chosen interval of darkness, the now almost motionless oars were
suddenly thrown aback, and the boat brought to a stand. For one
moment there was a dead and fearful pause. Our hero and his companion
by the prisoner awaited with trembling nerves and suspended breaths
the fatal signal from the oarsman. At last it came—the same
significant word of the lodge-room—"Nekum!" In an instant our
hero was upon his feet—in another his poniard was buried to the hilt
in the bosom of the prisoner;—while the other, fiercely grappling
at the same time one end of the seat on which the unfortunate man was
writhing, and the ponderous weight to which he was fastened, hurled
both together into the water. With the splashing sound descended the
lightning stream in quivering flames to the spot, revealing here the
hero exultingly brandishing his reeking blade aloft, and exclaiming, "
Vengeance is taken!"—and there the sinking man, with the crimson
current spouting up through the discoloured wave that was flowing over
his convulsed and death-set features. Darkness again succeeded. Once
more rose a faint bubbling groan, and all was still. The boat wheeled
swiftly round for the shore, and the loud crash of thunder that
followed told the requium of the hapless Botherworth, the victim of
masonic vengeance!
Back to the Index
Page | http://vickysands.com/01/04/455.htm | CC-MAIN-2017-39 | refinedweb | 77,023 | 52.06 |
Swift UI was one of the most exciting announcements at WWDC 2019. This new framework makes it easier and faster for developers to build better user interface code with fewer errors, providing nearly automatic support for device capabilities like Dark Mode, advanced Accessibility and Dynamic Type among others.
import SwiftUI struct Content : View{ @State var model = Themes.listModel var body: some View{ List(model.items, action:model.selectItem){ item in Image(item.image) VStack(aligment: .leading){ Text(item.title) Text(item.subtitle) .color(.gray) } } } }
SwiftUI uses a declarative syntax, this lets you write your code in a more ‘natural way’, where you just have to state what the UI should do. Creating a table of items with labels and images with specific fonts, colors and animations with a beautiful smooth layout has never been easier!
But wait! There’s more… SwiftUI is not alone, it’s accompanied by one of the best Xcode design tools ever!
Previews will let you build you’re UI as easy as dragging and dropping, keeping both the canvas and the code editor in sync, and since Xcode is recompiling the changes automatically, testing how you’re UI looks on any device, orientation, with different font sizes, localizations or Dark Mode has become easier than ever.
Furthermore, SwiftUI is native on all Apple Platforms. So, as the saying goes, you can “Learn once, apply everywhere”.
What about storyboards?
If you create a new project with Xcode 11 & SwiftUI you will see that there is no main.storyboard in the project directory. It seems that Apple intents to replace storyboards with SwiftUI for new projects targeting iOS 13 and above. If you want lo learn more about this exciting new framework, check out the following links:
Sources | https://www.krasamo.com/swiftui/ | CC-MAIN-2021-04 | refinedweb | 291 | 54.12 |
Revision history for PGObject 1.402.6 2014-10-09 Better exception handling 1.402.5 2014-09-07 Fixed test numbering that caused build failures 1.402.4 2014-09-05 Fixed to_db and pgobject_to_db serialization functions (+added tests) 1.402.3 2014-09-04 Supporting both the old pgobject_to_db and the new to_db methods. More code cleanup 1.402.2 2014-09-01 Code cleanup 1.402.1 2014-08-21 Better documentation of memoization uses and misuses. 1.402.0 2014-08-20 Added optional memoization of database catalog lookups. 1.4.1 2014-03-03 Fixed type instantiation bug when calling from externally with a named registry 1.4 2014-02-24 1. Added support for arrays and registered types. Note that this does not parse the array from text format and only handles an array passed to it. This paves the way for array-handling composite types, however. 2. DB_TESTING environment variable now used to control database tests, consistent with other PGObject modules. 3. MANIFEST.SKIP amended to support Mercurial 1.3 2013-11-14 1. Added get_registered() for composite type decoding 1.11 2013-06-05 1. Some additional safety checks in the database tests 1.10 2013-05-30 1. Added type registration system. 2. Added function prefixes for object types. 3. Added documentation of namespace layout. 1.01 2013-05-25 1. Minor changes to test cases to let them finish cleanly when the db is not available. 2. Minor documentation changes. 1.00 2013-05-24 First version, released on an unsuspecting world. Differences from LedgerSMB's interface include: 1. Function information is modularized into its own api 2. windowed aggs with rows unbounded preceding are supported 3. Database handle management outside scope of this module | https://metacpan.org/changes/distribution/PGObject | CC-MAIN-2015-27 | refinedweb | 295 | 63.76 |
Hi>
> questions
> ------------
> The library for dragging the AJAX debug dialog has the following
> notice: "distributed under commons creative license 2.0" - this is
> potentially problematic since it's a family of licenses some of which
> are open source compatible, some of which are not. what are the
> details?
I have asked this on our mailinglist. A priliminary search uncovered
some nasty licensing issue. Thanks for catching this. I've created a
high priority issue to resolve it [1]
> niclas already noted the missing headers from threadtest (major due to
> number and copyright)
These will be altered and fixed in a new attempt. Thanks Niclas!
> DISCLAIMER but is missing LICENSE and NOTICE from:
> * wicket-*-javadoc.jar
> * wicket-*-sources.jar
>
> (all artifacts MUST have LICENSE and NOTICE)
I will work with the maven gurus to ask how to fix this.
>.).
That said, I'll add the header.
>.
> i'd recommend creating release notes (but i hope that these are
> missing since this is only an audit release).
Normally we have those as well, containing links to our documentation
etc. Are the release notes part of what is voted on?
> BTW i see the current namespace is. do
> you plan to change this upon (sometime)?
Yep, however, we think we should only change this after graduation as
we are still not officially an Apache project :).
Thanks for looking into this and providing us with some solid
feedback. I expect to have a new release available somewhere next week
with all problems solved and questions answered.
Martijn
[1]
-- | http://mail-archives.eu.apache.org/mod_mbox/incubator-general/200704.mbox/%3C918312fe0704070535h4dc3e4ddyb3ae9c86acedc1ce@mail.gmail.com%3E | CC-MAIN-2020-40 | refinedweb | 254 | 66.13 |
For a typical Django application, database interactions are of key importance. Ensuring that the database queries being made are correct helps to ensure that the application results are correct. Further, ensuring that the database queries produced for the application are efficient helps to make sure that the application will be able to support the desired number of concurrent users.
Django provides support in this area by making the database query history available for examination. This type of access is useful to see the SQL that is issued as a result of calling a particular model method. However, it is not helpful in learning about the bigger picture of what SQL queries are made during the processing of a particular request.
This section will show how to include information about the SQL queries needed for production of a page in the page itself. We will alter our existing survey application templates to include query information, and examine the query history for some of the existing survey application views. Though we are not aware of any problems with the existing views, we may learn something in the process of verifying that they issue the queries we expect.
Settings for accessing query history in templates
Before the query history can be accessed from a template, we need to ensure some required settings are configured properly. Three settings are needed in order for the SQL query information to be available in a template. First, the debug context processor, django.core.context_processors.debug, must be included in the TEMPLATE_CONTEXT_PROCESSORS setting. This context processor is included in the default value for TEMPLATE_CONTEXT_PROCESSORS. We have not changed that setting; therefore we do not need to do anything to enable this context processor in our project.
Second, the IP address of the machine sending the request must be listed in the INTERNAL_IPS setting. This is not a setting we have used before, and it is empty by default, so we will need to add it to the settings file. When testing using the same machine as where the development server runs, setting INTERNAL_IPS to include the loopback address is sufficient:
# Addresses for internal machines that can see potentially sensitive
# information such as the query history for a request.
INTERNAL_IPS = ('127.0.0.1', )
If you also test from other machines, you will need to include their IP addresses in this setting as well.
Third and finally, DEBUG must be True in order for the SQL query history to be available in templates.
When those three settings conditions are met, the SQL query history may be available in templates via a template variable named sql_queries. This variable contains a list of dictionaries. Each dictionary contains two keys: sql and time. The value for sql is the SQL query itself, and the value for time is the number of seconds the query took to execute.
Note that the sql_queries context variable is set by the debug context processor. Context processors are only called during template rendering when a RequestContext is used to render the template. Up until now, we have not used RequestContexts in our survey application views, since they were not necessary for the code so far. But in order to access the query history from the template, we will need to start using RequestContexts. Therefore, in addition to modifying the templates, we will need to change the view code slightly in order to include query history in the generated pages for the survey application.
SQL queries for the home page
Let's start by seeing what queries are issued in order to generate the survey application home page. Recall that the home page view code is:,
})
There are three QuerySets rendered in the template, so we would expect to see that this view generates three SQL queries. In order to check that, we must first change the view to use a RequestContext:
from django.template import RequestContext,},
RequestContext(request))
The only change here is to add the RequestContext(request) as a third parameter to render_to_response, after adding an import for it earlier in the file. When we make this change, we may as well also change the render_to_response lines for the other views to use RequestContexts as well. That way when we get to the point of examining the SQL queries for each, we will not get tripped up by having forgotten to make this small change.
Second, we'll need to display the information from sql_queries somewhere in our survey/home.html template. But where? We don't necessarily want this information displayed in the browser along with the genuine application data, since that could get confusing. One way to include it in the response but not have it be automatically visible on the browser page is to put it in an HTML comment. Then the browser will not display it on the page, but it can be seen by viewing the HTML source for the displayed page.
As a first attempt at implementing this, we might change the top of survey/home.html to look like this:
{% extends "survey/base.html" %}
{% block content %}
<!--
{{ sql_queries|length }} queries
{% for qdict in sql_queries %}
{{ qdict.sql }} ({{ qdict.time }} seconds)
{% endfor %}
-->
This template code prints out the contents of sql_queries within an HTML comment at the very beginning of the content block supplied by survey/home. html. First, the number of queries is noted by filtering the list through the length filter. Then the code iterates through each dictionary in the sql_queries list and displays sql, followed by a note in parentheses about the time taken for each query.
How well does that work? If we try it out by retrieving the survey home page (after ensuring the development server is running), and use the browser's menu item for viewing the HTML source for the page, we might see that the comment block contains something like:
<!--
1 queries
SELECT `django_session`.`session_key`, `django_session`.`session_data`,
`django_session`.`expire_date` FROM `django_session` WHERE (`django_
session`.`session_key` = d538f13c423c2fe1e7f8d8147b0f6887 AND `django_
session`.`expire_date` > 2009-10-24 17:24:49 ) (0.001 seconds)
-->
Note that the exact number of queries displayed here will depend on the version of Django you are running. This result is from Django 1.1.1; later versions of Django may not show any queries displayed here. Furthermore, the history of the browser's interaction with the site will affect the queries issued. This result is from a browser that had been used to access the admin application, and the last interaction with the admin application was to log out. You may see additional queries if the browser had been used to access the admin application but the user had not logged out. Finally, the database in use can also affect the specific queries issued and their exact formatting. This result is from a MySQL database.
That's not exactly what we expected. First, a minor annoyance, but 1 queries is wrong, it should be 1 query. Perhaps that wouldn't annoy you, particularly just in internal or debug information, but it would annoy me. I would change the template code that displays the query count to use correct pluralization:
{% with sql_queries|length as qcount %}
{{ qcount }} quer{{ qcount|pluralize:"y,ies" }}
{% endwith %}
Here, since the template needs to use the length result multiple times, it is first cached in the qcount variable by using a {% with %} block. Then it is displayed, and it is used as the variable input to the pluralize filter that will put the correct letters on the end of quer depending on the qcount value. Now the comment block will show 0 queries, 1 query, 2 queries, and so on.
With that minor annoyance out of the way, we can concentrate on the next, larger, issue, which is that the displayed query is not a query we were expecting. Furthermore, the three queries we were expecting, to retrieve the lists of completed, active, and upcoming surveys, are nowhere to be seen. What's going on? We'll take each of these in turn.
The query that is shown is accessing the django_session table. This table is used by the django.contrib.sessions application. Even though the survey application does not use this application, it is listed in our INSTALLED_APPS, since it is included in the settings.py file that startproject generates. Also, the middleware that the sessions application uses is listed in MIDDLEWARE_CLASSES.
The sessions application stores the session identifier in a cookie, named sessionid by default, that is sent to the browser as soon as any application uses a session. The browser will return the cookie in all requests to the same server. If the cookie is present in a request, the session middleware will use it to retrieve the session data. This is the query we see previously listed: the session middleware is retrieving the data for the session identified by the session cookie sent by the browser.
But the survey application does not use sessions, so how did the browser get a session cookie in the first place? The answer is that the admin application uses sessions, and this browser had previously been used to access the admin application. At that time, the sessionid cookie was set in a response, and the browser faithfully returns it on all subsequent requests. Thus, it seems likely that this django_session table query is due to a sessionid cookie set as a side-effect of using the admin application.
Can we confirm that? If we find and delete the cookie from the browser and reload the page, we should see that this SQL query is no longer listed. Without the cookie in the request, whatever code was triggering access to the session data won't have anything to look up. And since the survey application does not use sessions, none of its responses should include a new session cookie, which would cause subsequent requests to include a session lookup. Is this reasoning correct? If we try it, we will see that the comment block changes to:
<!--
0 queries
-->
Thus, we seem to have confirmed, to some extent, what happened to cause a django_session table query during processing of a survey application response. We did not track down what exact code accessed the session identified by the cookie—it could have been middleware or a context processor, but we probably don't need to know the details. It's enough to keep in mind that there are other applications running in our project besides the one we are working on, and they may cause database interactions independent of our own code. If we observe behavior which looks like it might cause a problem for our code, we can investigate further, but for this particular case we will just avoid using the admin application for now, as we would like to focus attention on the queries our own code is generating.
Now that we understand the query that was listed, what about the expected ones that were not listed? The missing queries are due to a combination of the lazy evaluation property of QuerySets and the exact placement of the comment block that lists the contents of sql_queries. We put the comment block at the top of the content block in the home page, to make it easy to find the SQL query information when looking at the page source. The template is rendered after the three QuerySets are created by the view, so it might seem that the comment placed at the top should show the SQL queries for the three QuerySets.
However, QuerySets are lazy; simply creating a QuerySet does not immediately cause interaction with the database. Rather, sending the SQL to the database is delayed until the QuerySet results are actually accessed. For the survey home page, that does not happen until the parts of the template that loop through each QuerySet are rendered. Those parts are all below where we placed the sql_queries information, so the corresponding SQL queries had not yet been issued. The fix for this is to move the placement of the comment block to the very bottom of the content block.
When we do that we should also fix two other issues with the query display. First, notice that the query displayed above has > shown instead of the > symbol that would actually have been in the query sent to the database. Furthermore, if the database in use is one (such as PostgreSQL) that uses straight quotes instead of back quotes for quoting, all of the back quotes in the query would be shown as ". This is due to Django's automatic escaping of HTML markup characters. This is unnecessary and hard to read in our HTML comment, so we can suppress it by sending the sql query value through the safe filter.
Second, the query is very long. In order to avoid needing to scroll to the right in order to see the entire query, we can also filter the sql value through wordwrap to introduce some line breaks and make the output more readable.
To make these changes, remove the added comment block from the top of the content block in the survey/home.html template and instead change the bottom of this template to be:
{% endif %}
<!--
{% with sql_queries|length as qcount %}
{{ qcount }} quer{{ qcount|pluralize:"y,ies" }}
{% endwith %}
{% for qdict in sql_queries %}
{{ qdict.sql|safe|wordwrap:60 }} ({{ qdict.time }} seconds)
{% endfor %}
-->
{% endblock content %}
Now, if we again reload the survey home page and view the source for the returned page, we will see the queries listed in a comment at the bottom:
<!--
3 queries
SELECT `survey_survey`.`id`, `survey_survey`.`title`,
`survey_survey`.`opens`, `survey_survey`.`closes` FROM
`survey_survey` WHERE (`survey_survey`.`opens` <= 2009-10-25
AND `survey_survey`.`closes` >= 2009-10-25 ) (0.000 seconds)
SELECT `survey_survey`.`id`, `survey_survey`.`title`,
`survey_survey`.`opens`, `survey_survey`.`closes` FROM
`survey_survey` WHERE (`survey_survey`.`closes` < 2009-10-25
AND `survey_survey`.`closes` >= 2009-10-11 ) (0.000 seconds)
SELECT `survey_survey`.`id`, `survey_survey`.`title`,
`survey_survey`.`opens`, `survey_survey`.`closes` FROM
`survey_survey` WHERE (`survey_survey`.`opens` > 2009-10-25
AND `survey_survey`.`opens` <= 2009-11-01 ) (0.000 seconds)
-->
That is good, those look like exactly what we expect to see for queries for the home page. Now that we seem to have some working template code to show queries, we will consider packaging up this snippet so that it can easily be reused elsewhere.
Packaging the template query display for reuse
We've now got a small block of template code that we can put in any template to easily see what SQL queries were needed to produce a page. However, it is not so small that it can be easily re-typed whenever it might come in handy. Therefore, it would be good to package it up in a form where it can be conveniently included wherever and whenever it might be needed. The Django template {% include %} tag makes this easy to do.
Where should the snippet go? Note that this template snippet is completely general and not in any way tied to the survey application. While it would be easy to simply include it among the survey templates, putting it there will make it harder to reuse for future projects. A better approach is to put it in an independent application.
Creating an entirely new application just for this one snippet may seem a bit extreme. However, it is common during development to create small utility functions or template snippets that don't really belong in the main application. So it is likely during development of a real project that there would be other such things that should logically be placed somewhere besides the main application. It's helpful to have someplace else to put them.
Let's create a new Django application, then, to hold any general utility code that does not logically belong within the survey application:
kmt@lbox:/dj_projects/marketr$ python manage.py startapp gen_utils
Since its purpose is to hold general utility code, we've named the new application gen_utils. It can serve as a place to put any non-survey-specific code that seems like it might be potentially re-usable elsewhere. Note that as time goes on and more and more stuff accumulates in an application like this, it may become apparent that some subset of it would be useful to package into its own independent, self-contained application with a more descriptive name than gen_utils. But for now it is enough to start with one place to put utility code that is not really tied to the survey application.
Next, we can create a templates directory within gen_utils, and a gen_utils directory under templates, and create a file, showqueries.html, to hold the template snippet:
{% if sql_queries %}<!--
{% with sql_queries|length as qcount %}
{{ qcount }} quer{{ qcount|pluralize:"y,ies" }}
{% endwith %}
{% for qdict in sql_queries %}
{{ qdict.sql|safe|wordwrap:60 }} ({{ qdict.time }} seconds)
{% endfor %}
-->{% endif %}
We've made one change here from the previous code placed directly in the survey/home.html template, which is to place the entire HTML comment block inside an {% if sql_qureies %} block. If the sql_queries variable has not been included in the template context, then there is no reason to produce the comment at all.
As part of packaging code for reuse, it's also good practice to double-check and make sure that the code is truly reusable and not going to fail in odd ways if given unexpected or unusual input. Taking a look at that snippet, is there anything that might be found in an arbitrary sql_queries input that could cause a problem?
The answer is yes. If a SQL query value contains the HTML end-of-comment delimiter, then the comment block will be terminated early. This could result in the browser rendering what was intended to be a comment as part of the page content displayed to the user. To see this, we can try inserting a model filter call that includes the HTML end-of-comment delimiter into the home page view code, and see what the browser shows.
But what is the HTML end-of-comment delimiter? You might guess that it is -->, but in fact it is just the two dashes in a row. Technically, the <! and > are defined as the beginning and end of markup declaration, while the dashes mark the beginning and end of the comment. Thus, a query that contains two dashes in a row should trigger the behavior we are worried about here. To test this, add this line of code to the home view:
Survey.objects.filter(title__contains='--').count()
Note nothing has to be done with the results of the call; the added code must simply ensure that the query containing the two dashes is actually sent to the database. This added line does that by retrieving the count of results matching the pattern containing two dashes. With that added line in the home view, Firefox will display the survey home page like so:
The two dashes in a row in a SQL query value caused Firefox to prematurely terminate the comment block, and data we had intended to be still inside the comment has appeared in the browser page. In order to avoid this, we need to ensure that two dashes in a row never appear in the SQL query values included in the comment block.
A quick glance through the built-in Django filters doesn't reveal any that could be used to replace a string of two dashes with something else. The cut filter could be used to remove them, but simply removing them would make the sql value misleading as there would be no indication that the characters had been removed from the string. Therefore, it seems we will need to develop a custom filter for this.
We will put the custom filter in the gen_utils application. Filters and template tags must be placed in a templatetags module in an application, so we must first create the templatetags directory. Then, we can put an implementation for a replace_dashes filter into a file named gentags.py within gen_utils/templatetags:
from django import template
register = template.Library()
@register.filter
def replace_dashes(value):
return value.replace('--','~~double-dash~~')
replace_dashes.is_safe = True
The bulk of this code is the standard boilerplate import, register assignment, and @register.filter decoration needed to register the replace_dashes function so that it is available for use as a filter. The function itself simply replaces any occurrences of a pair of dashes in a string with ~~double-dash~~ instead. Since there is no way to escape the dashes so that they will not be interpreted as the end of the comment yet still appear as dashes, we replace them with a string describing what had been there. The last line marks the replace_dashes filter as safe, meaning it does not introduce any HTML markup characters that would need to be escaped in its output.
We also need to change the template snippet in gen_utils/showqueries.html to load and use this filter for display of the SQL query values:
{% if sql_queries %}<!--
{% with sql_queries|length as qcount %}
{{ qcount }} quer{{ qcount|pluralize:"y,ies" }}
{% endwith %}
{% load gentags %}
{% for qdict in sql_queries %}
{{ qdict.sql|safe|replace_dashes|wordwrap:60 }} ({{ qdict.time }}
seconds)
{% endfor %}
-->{% endif %}
The only changes here are the addition of the {% load gentags %} line and the addition of replace_dashes in the sequence of filters applied to qdict.sql.
Finally, we can remove the comment snippet from the survey/home.html template. Instead, we will put the new general snippet in the survey/base.html template, so this becomes:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"">
<html xmlns="">
<head>
<title>{% block title %}Survey Central{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
{% include "gen_utils/showqueries.html" %}
</html>
Placing {% include %} in the base template will cause every template that inherits from base to automatically have the comment block added, assuming that the other conditions of DEBUG being turned on, the requesting IP address being listed in INTERNAL_IPS, and the response being rendered with a RequestContext, are met. We'd likely want to remove this before putting the application in a production environment, but during development it can come in handy to have easy automatic access to the SQL queries used to generate any page.
Summary
In this article, we developed some template utility code to track what SQL requests are made during production of a page.
If you have read this article you may be interested to view : | https://www.packtpub.com/books/content/tracking-sql-queries-request-using-django | CC-MAIN-2017-13 | refinedweb | 3,737 | 60.95 |
- Import the example project
- Register the agent
- Configure your project
- Provision your cluster
- Use your cluster
- Remove the cluster
Create an Amazon EKS cluster
You can create a cluster on Amazon Elastic Kubernetes Service (EKS) through Infrastructure as Code (IaC). This process uses the AWS and Kubernetes Terraform providers to create EKS clusters. You connect the clusters to GitLab by using the GitLab agent for Kubernetes.
Prerequisites:
- An Amazon Web Services (AWS) account, with a set of configured security credentials.
- A runner you can use to run the GitLab CI/CD pipeline.
Steps:
- Import the example project.
- Register the agent for Kubernetes.
-:
- An Amazon Virtual Private Cloud (VPC).
- An Amazon Elastic Kubernetes Service (EKS) cluster.
-
eks-agentand select Register an agent.
- GitLab generates a registration token for the agent. Securely store this secret token, as you will need it later.
- GitLab provides an address for the agent server (KAS), which you will also need later.
Configure your project
Use CI/CD environment variables to configure your project.
Required configuration:
- On the left sidebar, select Settings > CI/CD.
- Expand Variables.
- Set the variable
AWS_ACCESS_KEY_IDto your AWS access key ID.
- Set the variable
AWS_SECRET_ACCESS_KEYto your AWS secret access key.
- Set the variable
TF_VAR_agent_tokento the agent token displayed in the previous task.
- Set the variable
TF_VAR_kas_addressto the agent server address displayed in the previous task.
Optional configuration:
The file
variables.tf
contains other variables that you can override according to your needs:
TF_VAR_region: Set your cluster’s region.
TF_VAR_cluster_name: Set your cluster’s name.
TF_VAR_cluster_version: Set the version of Kubernetes.
TF_VAR_instance_type: Set the instance type for the Kubernetes nodes.
TF_VAR_instance_count: Set the number of Kubernetes nodes.
TF_VAR_agent_version: Set the version of the GitLab agent.
TF_VAR_agent_namespace: Set the Kubernetes namespace for the GitLab agent.
View the AWS view the new cluster:
- In AWS: From the EKS console, select Amazon EKS > Clusters.
- In GitLab: On the left (). | https://docs.gitlab.com/ee/user/infrastructure/clusters/connect/new_eks_cluster.html | CC-MAIN-2022-21 | refinedweb | 312 | 52.36 |
Introduction
In this guide, we’ll configure Jenkins and CodeCommit to allow users to easily create and destroy infrastructure using Terraform code.
For this guide, let’s suppose our deployment has the following requirements:
- Users don’t need to install anything from their own, especially on their laptop.
- Users don’t need to use the command line.
- Users need to have a simple input experience with select boxes, etc. Where there are open input fields, the value inserted needs to be evaluated and verified.
- Users can check the output results for errors and all users can see the previous executions from other users
TERRAFORM
Terraform is used to define and build infrastructures using code, and is becoming more popular day by day. One of its advantages is that you can build infrastructure using many providers, including AWS, Azure, Google Cloud, and VMware (a full listing can be found here).
Another important advantage is that writing code using the Terraform language is comfortable and much simpler than other similar technologies.
You can download and use Terraform for free. It is an open source project, but the community version is command line based and does not include a web console.
When you run Terraform code, you will have the `terraform.tfstate` file and `terraform.tfstate.backup` after the second run. You need these files to delete or update an existing configuration. If you want update the infrastructure, you need also the code that you use during the builds so you’ll need to save these text files to reuse in the future, or at minimum, for your records.
JENKINS
We’ll use Jenkins to provide a simple way for users to create and destroy architecture using jobs. Everything is region dependent and when you change regions, you have different parameters to pass. To have this dynamicity with parameters, we can install the Uno Choice plugin . This allows us to change a menu depending on the region selected:
In this example, only the networks for the selected region are shown. We’ll explain how to configure the plugin to behave this way in a later section.
Install and Configure Jenkins
We’ll use a Linux AMI machine for our Jenkins installation, but you can easily adapt these instructions to other Linux distributions. These commands should be run by a user or role with administrator access:
yum update -y wget -O /etc/yum.repos.d/jenkins.repo rpm --import yum install jenkins -y chkconfig jenkins on
Change the `jenkins` user before starting Jenkins for the first time. For our purposes, we’ll use one with full access like the `ec2-user` in Linux AMI or the `ubuntu` user for an Ubuntu LTS distribution.
sed -i 's/JENKINS_USER="jenkins"/JENKINS_USER="ec2-user"/g' /etc/sysconfig/jenkins chown ec2-user:ec2-user /var/lib/jenkins/ chown ec2-user:ec2-user /var/log/jenkins chown ec2-user:ec2-user /var/cache/jenkins/ service jenkins start
Optionally, install Apache or put the machine behind a load balancer if you want to use SSL or you can’t access the default Jenkins port 8080.
To complete the setup, copy the following into a script and execute it:
#!/bin/bash
###### install programs
sudo yum update -y
sudo yum install git python27-pip.noarch -y
sudo /usr/local/bin/pip install –upgrade pip
sudo /usr/local/bin/pip install requests
sudo /usr/local/bin/pip install requests –upgrade
##### configure git #############
git config –global credential.helper ‘!aws –profile codecommit credial-helper $@’
git config –global credential.UseHttpPath true
git config –global user.name “Jenkins automation tool”
git config –global user.email myemail@mycompany.com
REPO=”/home/ec2-user/git-repos”
if [ ! -d “$REPO” ]; then
mkdir /home/ec2-user/git-repos ;
fi
if [ ! -f “/usr/bin/terraform” ]; then
cd /tmp
wget unzip terraform_0.8.7_linux_amd64.zip
sudo mv terraform /usr/bin/
fi
CodeCommit
In this section, we’ll configure CodeCommit quickly and without much explanation. For more detail, check out the course on Manage & Deploy Code with AWS Developer Tools
Create an IAM user without password access and with only permission to have CodeCommit access:
On the Jenkins machine, create a set of SSH keys. Do not use a passphrase:
ssh-keygen
Upload the generated .pub file using the AWS web console and configure the security credentials as follows:
Configure Git as follows:
cd /home/ec2=user/.ssh ~/.ssh> cat config Host git-codecommit.*.amazonaws.com User REPLACE-YOUR-SSH-KEY-ID IdentityFile ~/.ssh/codecommit
Add the keys to the administrative user’s `.ssh` directory:
~/.ssh> ll
-rw——- 1 ec2-user ec2-user 1.7K Sep 26 09:05 codecommit
-rw-r–r– 1 ec2-user ec2-user 405 Sep 26 09:06 codecommit.pub
-rw——- 1 ec2-user ec2-user 110 Sep 26 09:07 config
Test the CodeCommit connection. Here’s example output from a successful connection message:
ssh git-codecommit.us-east-1.amazonaws.com The authenticity of host 'git-codecommit.us-east-1.amazonaws.com (54.239.20.155)' can't be established. RSA key fingerprint is a6:9c:7d:bc:35:f5:d4:5f:8b:ba:6f:c8:bc:d4:83:84. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'git-codecommit.us-east-1.amazonaws.com,54.239.20.155' .
Dynamic Uno Parameter Plugin
Next, we’ll setup the advanced dynamic input type parameters, which allow us to select different options for each AWS region. For example, if we select one region, we’ll see a list of databases available in that region, but if we select another region, we’ll have a different set of database options.
Copy the following script into the “Script” text area:
import static groovy.io.FileType.FILES if (binding.variables.get('aws_region') != null) { region = binding.variables.get('aws_region') def dir = new File("/home/ec2-user/git-repos/databases-resources/"+region+"/cassandra-resources/"); def files = []; dir.traverse(type: FILES, maxDepth: 0) { def values = (it.toString()).split('/'); files.add(values[values.size()-1]) }; return files }
The other parameter, `aws_region` can be a simple “Choice Parameter” with a list of regions available.
To use this parameter:
To add this option:
- Install the Update Sites Manager plugin, available here:
- Add the biouno site following the instraution in this link
Install the uno-choice-plugin. Instructions can be found here: the people that doesn’t have so much experience with Jenkins, the update site manager is like use apt/yum with additional sources respect the original. The point 2 means add the source biouno package repository, only after this action you can install all the plugin available from biouno. I installed the package uno-choice-cascade
Save the “State” with AWS CodeCommit
Now that AWS CodeCommit is working from your Jenkins machine, you can work inside a versioned directory and to save all the files of your Terraform runs using Git commands.
After each Terraform run, save the state of the Terraform code to CodeCommit by committing and pushing the files in the job’s directory by adding the following commands to your job:
git add -A git commit -m ‘any comments that you like’ git push origin master
Your `terraform.tfstate` and `terraform.tfstate.backup` will be versioned and stored for future reference.
Jenkins as a Web Console
You are the Jenkins Administrator, you the access to every job with full rights, but in many cases this is not what you want. In my case I want give access only to run the job but not to modify that. To do this you need to setup this special settings with role.
It is important for users to be able to run the jobs that you created for them, but not to be able to modify them. To configure this, install the following plugin:
After the installation, enable the role access control:
Click on Manage Jenkins, and a new option will be shown:
Click on Manage Roles:
Create a role called, for example, `run_job_only` and assign the options shown here:
From here, assign your user to the `run_job_only` role we just created.
Conclusion
That’s it! Your users can now use the Jenkins web console to create and destroy architecture using Terraform.
Future Developments
These have not been tested yet but here are some possible improvements:
- Integrate Terraform in Jenkins with the plugin
- Integrate the CodeCommit inside the Jenkins using a git plugin
- Save the Terraform state files in S3 to have a durable repository. The disadvantage is not to have the state and the creation code in the same place. | https://linuxacademy.com/guide/18753-automating-terraform-with-jenkins-and-aws-codecommit/ | CC-MAIN-2019-39 | refinedweb | 1,420 | 54.63 |
I
doveadm script is run on the destination server. The documentation provides the settings, but does not mention which dovecot configuration file the settings have to be entered.
I
4 Answers
You can also do the following on the command-line without configuration files:
# \ backup -R -u <DESTINATION_MAILBOX> imapc:
I had great problems, because my source IMAP only supports STARTTLS on port 143.
-o imapc_ssl=starttls was a life-saver in my case.
You can make a sync after the initial backup with:
# \ sync -1 -R -u <DESTINATION_MAILBOX> imapc:
Of course, this is quite insecure if you have more users on the box that can see your commands (and passwords) with
who or by looking into your .bash_history file, so beware.
If the two mail servers are running without problems with the IMAP protocol I would use
imapsync to do the job. Both Courier and Dovecot are supported by
imapsync.
It's really straightforward to use and support many features, like regexp mappings for different folder synchronisation.
The software is FOSS and can be found here:
If you need the UID sync you can add the option
--useuid in the imapsync. I'm not sure if you're talking about this kind of UID. But this is the option that you should be looking for:
--useuid : Use uid instead of header as a criterium to recognize messages. Option --usecache is then implied unless --nousecache is used.
- Hi. Thanks for the hint. I have also considered using imapsync. But I have read ( wiki2.dovecot.org/Migration ) that it does not preserve the UID of the e-mails. If UIDs are not preserved, the IMAP clients which are already bound to the first server, when they are pointed to the new server, will not be able to sync with the local cache and have to download all (thousands) of messages from scratch. I would therefore like to stick to the original documentation, which is albeit a bit unclear Jun 18, 2014 at 12:11
- Sorry but I was unable to understand this. IMAPSync does not care about UID. It works on the IMAP layer, so the UID's are defined at your server by you at the account creation processes. Jun 18, 2014 at 16:09
- Exactly. IMAPsync does not care about UIDs, but clients like Thunderbird do. It is clearly said here: wiki2.dovecot.org/Migration#IMAP_migration "When migrating mails from another IMAP server, you should make sure that these are preserved: If UIDs are lost, at the minimum clients' message cache gets cleaned and messages are re-downloaded as new. Some IMAP clients store metadata by assigning it to specific UID, if UIDs are changed these will be lost.". The solution is to use doveadm but I don't understand how. Jun 19, 2014 at 14:23
- I don't get the point of UID mapping. But I've updated my answer to fit your needs. Jun 20, 2014 at 4:41
You should migrate your mail using the
dsync utility from Dovecot. This will preserve the UIDs and even POP3 UIDLs if necessary.
Run
dsync using the
backup -R option, to 'reverse backup' from the remote IMAP server to the local Dovecot server. You need to have a special configuration file created, something like this:
imapc_host = imap.company.com imapc_user = %u@company.com imapc_password = mypassword imapc_features = rfc822.size fetch-headers imapc_port = 143 pop3c_host = pop3host.company.com pop3c_user = %u@company.com pop3c_password = mypassword pop3c_port = 110 namespace pop3c { prefix = POP3-MIGRATION-NS/ location = pop3c:~/pop3c list = no hidden = yes } !include /etc/dovecot/dovecot.conf plugin { pop3_migration_mailbox = POP3-MIGRATION-NS/INBOX pop3_migration_skip_size_check = yes pop3_migration_ignore_missing_uidls=yes } mail_prefetch_count = 20 mail_shared_explicit_inbox = no protocol doveadm { mail_plugins = $mail_plugins pop3_migration }
Note this is for a single user; you may want to have different options if you use a master user/password, or if you require SSL for the connections.
Then call it with something like:
dsync -D -v -u username -c configfile.cfg
The
username replaces the
%u in the
config.cfg file. The
-D -v is verbose debug mode.
- The Dovecot documentation page Migrating mailboxes has more examples on creating this file. Jan 31 at 19:59
You need to include those settings in Dovecot configuration,
usually Dovecot configs are in
/etc/dovecot/.
Best would be to place the configuration in
/etc/dovecot/conf.d/90-migration.conf (all files in
conf.d dir are automatically included).
To reload the config you need to run:
sudo doveadm reload | https://serverfault.com/questions/605342/migrating-from-any-imap-pop3-server-to-dovecot | CC-MAIN-2022-40 | refinedweb | 741 | 65.42 |
Passing SqlDataReader thro a web service...
Discussion in 'ASP .Net Web Services' started by Colin Basterfield, Jan 16, 2004.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
sending email thro SMTP server=?Utf-8?B?dWZyYWY=?=, May 20, 2005, in forum: ASP .Net
- Replies:
- 4
- Views:
- 2,807
- =?Utf-8?B?dWZyYWY=?=
- May 30, 2005
Configurable hardware thro' VHDLdutta, Aug 13, 2003, in forum: VHDL
- Replies:
- 0
- Views:
- 1,196
- dutta
- Aug 13, 2003
Invoke a method in Java webservice thro' soap call from Asp.net client.Samuel, Jul 30, 2003, in forum: ASP .Net
- Replies:
- 0
- Views:
- 605
- Samuel
- Jul 30, 2003
RE: Error connecting to sql server thro .net=?Utf-8?B?YWJiYXMgYWRhbmFsxLE=?=, Aug 6, 2004, in forum: ASP .Net
- Replies:
- 0
- Views:
- 388
- =?Utf-8?B?YWJiYXMgYWRhbmFsxLE=?=
- Aug 6, 2004
How to retain the namespace xmlns:enc in XML thro XSLT ?Rajesh, Jul 18, 2006, in forum: Java
- Replies:
- 0
- Views:
- 415
- Rajesh
- Jul 18, 2006 | http://www.thecodingforums.com/threads/passing-sqldatareader-thro-a-web-service.782531/ | CC-MAIN-2015-14 | refinedweb | 197 | 77.23 |
On Fri, Jun 29, 2012 at 12:36:30PM -0700, Andrew Boie wrote:> Android userspace tells the kernel that it wants to boot into recovery> or some other non-default OS environment by passing a string argument> to reboot(). It is left to the OEM to hook this up to their specific> bootloader.How does userspace "tell" the kernel this? You are creating a newuser/kernel api here, and haven't documented it at all. That's notgenerally a wise idea.> This driver uses the bootloader control block (BCB) in the 'misc'> partition, which is the AOSP mechanism used to communicate with> the bootloader. Writing 'bootonce-NNN' to the command field> will cause the bootloader to do a oneshot boot into an alternate> boot label NNN if it exists. The device and partition number are> passed in via kernel command line.I don't understand still, why userspace can't just do this as it is theone that knws where the device and partition is, and it knows what itwants to have written in this area, why have the kernel do this? Whynot just modify userspace to do it instead?> It is the bootloader's job to guard against this area being uninitialzed> or containing an invalid boot label, and just boot normally if that> is the case. The bootloader will always populate a magic signature in> the BCB; the driver will refuse to update it if not present.That sounds like something that userspace should be doing, not thekernel.> Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>> ---> drivers/staging/android/Kconfig | 11 ++> drivers/staging/android/Makefile | 1 +> drivers/staging/android/bcb.c | 232 ++++++++++++++++++++++++++++++++++++++Why is this being proposed for drivers/staging/? What is wrong with thecode that is keeping it out of the "real" part of the kernel (well,except for the above questions that is)?What would need to be done to it to get it out of staging, and whyhasn't that been done to the code already?> > diff --git a/drivers/staging/android/Kconfig b/drivers/staging/android/Kconfig> index 9a99238..c30fd20 100644> --- a/drivers/staging/android/Kconfig> +++ b/drivers/staging/android/Kconfig> @@ -78,6 +78,17 @@ config ANDROID_INTF_ALARM_DEV> elapsed realtime, and a non-wakeup alarm on the monotonic clock.> Also exports the alarm interface to user-space.> > +config BOOTLOADER_CONTROL> + tristate "Bootloader Control Block module"> + default n> + help> + This driver installs a reboot hook, such that if reboot() is invoked> + with a string argument NNN, "bootonce-NNN" is copied to the command> + field in the Bootloader Control Block on the /misc partition, to be> + read by the bootloader. If the string matches one of the boot labels> + defined in its configuration, it will boot once into that label. The> + device and partition number are specified on the kernel command line.> +> endif # if ANDROID> > endmenu> diff --git a/drivers/staging/android/Makefile b/drivers/staging/android/Makefile> index 8e18d4e..a27707f 100644> --- a/drivers/staging/android/Makefile> +++ b/drivers/staging/android/Makefile> @@ -9,5 +9,6 @@ obj-$(CONFIG_ANDROID_LOW_MEMORY_KILLER) += lowmemorykiller.o> obj-$(CONFIG_ANDROID_SWITCH) += switch/> obj-$(CONFIG_ANDROID_INTF_ALARM_DEV) += alarm-dev.o> obj-$(CONFIG_PERSISTENT_TRACER) += trace_persistent.o> +obj-$(CONFIG_BOOTLOADER_CONTROL) += bcb.o> > CFLAGS_REMOVE_trace_persistent.o = -pg> diff --git a/drivers/staging/android/bcb.c b/drivers/staging/android/bcb.c> new file mode 100644> index 0000000..af75257> --- /dev/null> +++ b/drivers/staging/android/bcb.c> @@ -0,0 +1,232 @@> +/*> + * bcb.c: Reboot hook to write bootloader commands to> + * the Android bootloader control block> + *> + * (C) Copyright 2012 Intel Corporation> + * Author: Andrew Boie <andrew.p.boie@intel.com>> + *> + * This program is free software; you can redistribute it and/or> + * modify it under the terms of the GNU General Public License> + * as published by the Free Software Foundation; version 2> + * of the License.> + */> +> +#include <linux/module.h>> +#include <linux/moduleparam.h>> +#include <linux/blkdev.h>> +#include <linux/reboot.h>> +> +#define BCB_MAGIC 0xFEEDFACE> +> +/* Persistent area written by Android recovery console and Linux bcb driver> + * reboot hook for communication with the bootloader. Bootloader must> + * gracefully handle this area being unitinitailzed */> +struct bootloader_message {> + /* Directive to the bootloader on what it needs to do next.> + * Possible values:> + * boot-NNN - Automatically boot into label NNN> + * bootonce-NNN - Automatically boot into label NNN, clearing this> + * field afterwards> + * anything else / garbage - Boot default label */> + char command[32];> +> + /* Storage area for error codes when using the BCB to boot into special> + * boot targets, e.g. for baseband update. Not used here. */> + char status[32];> +> + /* Area for recovery console to stash its command line arguments> + * in case it is reset and the cache command file is erased.> + * Not used here. */> + char recovery[1024];> +> + /* Magic sentinel value written by the bootloader; don't update this> + * if not equalto to BCB_MAGIC */> + uint32_t magic;> +};Ick, you are tacking this onto the reboot() syscall? And doing sowithout setting any of those fields to 0? How do you handle nullterminating the command line arguments, or the command or the statusfields properly? Pad them out with spaces? You better document theheck out of this as you just essencially are creating a whole newsyscall, and we can't do that without lots of documentation and review.Actually, why not just create a new syscall? That's what you reallywant here, right?> +/* TODO: device names/partition numbers are unstable. Add support for looking> + * by GPT partition UUIDs */They are more than just "unstable" they are not stable at all and shouldnot be used at all for something like this.> +static char *bootdev = "sda";> +module_param(bootdev, charp, S_IRUGO);> +MODULE_PARM_DESC(bootdev, "Block device for bootloader communication");> +> +static int partno;> +module_param(partno, int, S_IRUGO);> +MODULE_PARM_DESC(partno, "Partition number for bootloader communication");So, by default, you write over sda. Not very nice. And a moduleparameter? Really? That's not a good way to talk to a module, who isgoing to set these options and how are they going to know how to do it?And who is going to give them the permission to set these options?Why are these module parameters, and the other information tacked on ina string to the reboot syscall? Wouldn't it make more sense to put itall in the syscall? That way you could build the code into thekernel...Note, none of this review should be construed as me saying this is avalid option to be putting into the kernel at all. I still think itshould be done in userspace and see no reason why it can not be donethat way.thanks,greg k-h | http://lkml.org/lkml/2012/6/29/485 | CC-MAIN-2017-30 | refinedweb | 1,064 | 56.86 |
Proper way to pass args to next() method
- Андрей Музыкин last edited by Андрей Музыкин
Hello!
I want following procedure inside next() method to be executed:
def next(): compute some indicators and other <statistic> ...... connect remote server via <socket>, send <statistic> wait for remote to respond with <signal> execute by/sell/hold, based on received <signal>
The question is: how to pass <socket> details , which will be available right before I call cerebro.run()?
Generally, question is about passing to .next() any arguments, dynamically computed for the specific run()
- Андрей Музыкин last edited by Андрей Музыкин
UPD:
Seems the easy way is to reinstantiate bt.Cerebro() before each run and pass everything as parameters:
class TestStrategy(bt.Strategy): params = (('socket', None),) ... <Loop over multiple strategy runs>: <check RemoteServer, get updated socket details> cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy, socket=<FreshSocket>) < add data, etc.> cerbro.run()
- backtrader administrators last edited by
You were faster that the coming answer.
params(for parameters) is the standard way to pass things that will get to the strategy and that you can later address as
self.params.myparamor with the shorthand
self.p.myparam
There is no need for that indentation. See at the top of the page. Use 2 lines with 3-backticks marks to enclose the code block.
Or go directly (also at the top) to:
- Андрей Музыкин last edited by
Yup, pure "read manual first" case. Fixed. | https://community.backtrader.com/topic/433/proper-way-to-pass-args-to-next-method/3 | CC-MAIN-2022-40 | refinedweb | 235 | 57.67 |
#include "petscvec.h" PetscErrorCode VecLoad(Vec newvec, PetscViewer viewer)Collective on PetscViewer
The input file must contain the full global vector, as written by the routine VecView().
If the type or size of newvec is not set before a call to VecLoad, PETSc sets the type and the local and global sizes. If type and/or sizes are already set, then the same are used.
If using binary and the blocksize of the vector is greater than one then you must provide a unique prefix to the vector with PetscObjectSetOptionsPrefix((PetscObject)vec,"uniqueprefix"); BEFORE calling VecView() on the vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the filename. If you copy the binary file, make sure you copy the associated .info file with it.
If using HDF5, you must assign the Vec the same name as was used in the Vec that was stored in the file using PetscObjectSetName(). Otherwise you will get the error message: "Cannot H5DOpen2() with Vec name NAMEOFOBJECT"
int VEC_FILE_CLASSID int number of rows PetscScalar *values of all entries
In addition,:intermediate
Location:src/vec/vec/interface/vector.c
Index of all Vec routines
Table of Contents for all manual pages
Index of all manual pages | http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/Vec/VecLoad.html | CC-MAIN-2018-09 | refinedweb | 233 | 59.74 |
fgets—
#include <stdio.h>
char *
fgets(char
*str, int size,
FILE *stream);
fgets() function reads at most size-1 characters from the given stream and stores them in the string str. Reading stops when a newline character is found, at end-of-file, on error, or after size-1 bytes are read. The newline, if any, is retained. The string will be NUL-terminated if
fgets() succeeds; otherwise the contents of str are undefined.
fgets() returns a pointer to the string. If end-of-file or an error occurs before any characters are read, it returns
NULL. The
fgets() function does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred. Whether
fgets() can possibly fail with a size argument of 1 is implementation-dependent. On OpenBSD,
fgets() will never return
NULLwhen size is 1.
EBADF]
EINVAL]
The function
fgets() may also fail and set
errno for any of the errors specified for the routines
fflush(3),
fstat(2),
read(2), or
malloc(3).
fgets() conforms to ANSI X3.159-1989 (“ANSI C89”).
fgets() first appeared in Version 7 AT&T UNIX.:
fgets() will not contain a newline either. Thus
strchr() will return
NULLand the program will terminate, even if the line was valid.
strchr(), correctly assume the end of the string is represented by a NUL (‘\0’) character. If the first character of a line returned by
fgets() were NUL,
strchr() would immediately return without considering the rest of the returned text which may indeed include a newline.
Consider using getline(3) instead when dealing with untrusted input.
It is erroneous to assume that
fgets()
never returns an empty string when successful. If a line starts with the NUL
character, fgets will store the NUL and continue reading until it encounters
a newline or end-of-file. This will result in an empty string being
returned. The following bit of code illustrates a case where the programmer
assumes the string cannot be zero length.
char buf[1024]; if (fgets(buf, sizeof(buf), fp) != NULL) { /* WRONG */ if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = '\0'; }
If
strlen() returns 0, the index into the
buffer becomes -1. One way to concisely and correctly trim a newline is
shown below.
char buf[1024]; if (fgets(buf, sizeof(buf), fp) != NULL) buf[strcspn(buf, "\n")] = '\0'; | https://man.openbsd.org/fgets.3 | CC-MAIN-2019-22 | refinedweb | 396 | 66.84 |
Can anyone explain the concept of stander error in C? I was told that anything that's sent to stderr isn't buffered.
Printable View
Can anyone explain the concept of stander error in C? I was told that anything that's sent to stderr isn't buffered.
Well, let's begin with the underlying file descriptors. fd 0 is by default connected to the standard input, fd 1 to the standard output and fd 2 to the standard error. As with any file descriptors, nothing sent to or received from them is ever buffered (except for standard input, where the terminal driver's line discipline will buffer a line if icanon is set).
At process startup, libc creates three FILE structures, each referring to each of these file descriptors. The entire purpose of FILE structures and stdio is to create a standard interface for buffering file data. stdout is by default line buffered (meaning the contents of the buffer is only flushed to the file descriptor when a newline is "sent" to it or when it's closed (or when fflush is called on it)). stderr is completely unbuffered, though, so that any error messages will be displayed immediately for the user to see.
Was there anything more about it?
Actually, I was just testing this in C. Since stderr isn't buffered, I thought that these messages would appear first out of any.
I thought the output would read STDERR, STDOUT 1, STDOUT 2, STDOUT 3 but the order doesn't appear this way. Instead, they are output as the function fprintf are called.I thought the output would read STDERR, STDOUT 1, STDOUT 2, STDOUT 3 but the order doesn't appear this way. Instead, they are output as the function fprintf are called.Code:
#include <stdio.h>
int main()
{
fprintf( stdout, "STDOUT 1\n" );
fprintf( stdout, "STDOUT 2\n" );
fprintf( stderr, "STDERR\n" );
fprintf( stdout, "STDOUT 3\n" );
return 0;
}
Naturally. Like I said, stdout is flushed if you attempt to send a newline over it. Try this instead:
I haven't actually tried it, but if I'm correct, it should give you something like this:I haven't actually tried it, but if I'm correct, it should give you something like this:Code:
#include <stdio.h>
int main(void)
{
fprintf(stdout, "STDOUT 1 ");
fprintf(stderr, "STDERR 1 ");
fprintf(stdout, "STDOUT 2\n");
fprintf(stderr, "STDERR 2\n");
}
Code:
STDERR 1 STDOUT 1 STDOUT 2
STDERR 2
Hmm. I wasn't aware that newline flushed the buffer. Does that also apply to the cout << operator? I know that using endl will flush the buffer but I'm not sure if appending a newline character to a string will flush the buffer without endl.
Well, you know, I really don't know how C++ works that well, and never once in my life have I used its iostreams. But as far as I know (which isn't very far, but anyway), iostreams are just front-ends to a FILE structure.
Dolda, are you saying I don't need to call fflush(NULL) to flush stderr if the string I'm printing ends with a newline?
I wasn't aware of that. Nice tip. I'm going to have to test it of course... ;-)
You don't have to flush stderr at all. All you might need to flush is stdout, and yes, that is only if your output doesn't end with a newline. stderr, on the other hand, is always completely unbuffered.
I just finished testing this out. As always, Dolda is right. I remember when I first wrote a program in C, I used a case structure and I was having problems with the printf(). Messages were being printed in a strange order (wasn't using stderr) and now that I think about it, it's because I wasn't appending the newline character. Of course the string "Enter a choice: \n" isn't appealing since the user would enter his/her choice on a newline so I believe I used fflush to get rid of the side effect.
If you want to, you can turn off buffering on stdout with this:
See the setvbuf(3) man page for details.See the setvbuf(3) man page for details.Code:
setvbuf(stdout, NULL, _IONBF, 0); | http://www.linuxforums.org/forum/programming-scripting/standard-error-print-2129.html | CC-MAIN-2014-52 | refinedweb | 721 | 80.72 |
# Go Code Generation from OpenAPI spec
OpenAPI specification
---------------------
One of the nicest features of Go is the power of code generation. `go generate` command serves as a Swish knife allowing you to generate enums, mocks and stubs. In this article, we will employ this feature to generate a Go code from OpenAPI specification. OpenAPI specification is a modern industrial standard for REST API. This standard has fantastic tooling support and allows you to conveniently render and validate the spec. We are going to befriend the power of Go code generation with the elegance and clarity of the OpenAPI specification. In this way, you don't have to manually update the Go boilerplate code after every change in the spec. You also ensure that your docs and your code are a single entity, as your code is being begotten from the docs.
Let's start dead-simple: we have a service that accepts order requests. Let's declare endpoint `order/10045234` that accepts PUT requests, where `10045234` is an ID of a particular order. We expect to receive an order as a JSON payload in the following format.
```
{"item": "Tea Table Green", "price": 106}
```
How can describe this endpoint in the OpenAPI spec?
The skeleton of the spec looks the following:
```
openapi: 3.0.3
info:
title: Go and OpenAPI Are Friends Forever
description: Let's do it
version: 1.0.0
paths:
components:
```
First, we need to describe the response body — `order` and put this description under section `components`. In OpenAPI the order object looks the following:
```
components:
schemas:
Order:
type: object
properties:
item:
type: string
price:
type: integer
```
It's a bit more verbose, but it is also very expressive. We can easily add validations rules on top of it. For example, we can enlist all possible items:
```
item:
type: string
enum:
- Tea Table Green
- Tea Table Red
```
OpenAPI specification is very rich and lets one easily specify that price must be a positive integer or that id must be in UUID format. We also can specify which fields are mandatory.
Now, let's specify our endpoint under section `paths`.
```
paths:
"/order/{id}":
put:
summary: Create an order
parameters:
- in: path
description: Order ID
name: id
schema:
type: string
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/Order"
```
The above part of the specification states that we expect a PUT request on the endpoint "/order/id" with the `Order` object as payload. Finally, let's add an expected response to the endpoint.
```
responses:
"201":
description: The order was successfully created.
```
Code Generation
---------------
At this point we have the complete specification:
```
openapi: 3.0.3
info:
title: Title
description: Title
version: 1.0.0
components:
schemas:
Order:
type: object
properties:
item:
type: string
enum:
- Tea Table Green
- Tea Table Red
id:
type: string
price:
type: integer
paths:
"/order/{id}":
put:
summary: Create an order
parameters:
- in: path
description: Order ID
name: id
schema:
format: string
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/Order"
responses:
"201":
description: The order was successfully created.
```
Now, the fun part: let the machine do its job and generate the code. To do so we will employ an awesome Go lib [oapi-codegen](https://github.com/deepmap/oapi-codegen). Download it with `go get` and add the following command to your Makefile:
```
gen:
oapi-codegen -package spec spec.yaml > gen.go
```
Play Time!
----------
Now, let's give it a try and see what we got from the generation. For the client side, we have `NewClientWithResponses` function that returns a ready-to-use client object. The generator also creates order object as `PutOrderIdJsonRequestBody` and enum values for `item` properties. You can notice that `price` and `item` expects pointers, as those fields are optional in our OpenAPI spec.
```
const server = "localhost:8080"
func main() {
client, err := spec.NewClientWithResponses(server)
if err != nil {
log.Fatal(err)
}
item := spec.OrderItemTeaTableGreen
price := 14
resp, err := client.PutOrderIdWithResponse(context.Background(), "234578", spec.PutOrderIdJSONRequestBody{
Item: &item, Price: &price,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.StatusCode())
}
```
In less than 15 lines of hand-written code, we got a full-fledged client of our API! The OpenAPI standard has a tremendous palette of tooling and the code be generated for a variety of languages.
And for the server side, we got interface `ServerInterface` with a single method `PutOrderId` to implement. Let's declare a type `server` that conforms to this interface. By default, the code is generated for router `echo`, which can be downloaded as `go get github.com/labstack/echo`.
```
type server struct {}
func (s server) PutOrderId(c echo.Context, id string) error {
var req spec.PutOrderIdJSONRequestBody
if err := c.Bind(&req); err != nil {
log.Fatal(err)
}
log.Printf("id: %v, req: %v", id, req)
return nil
}
```
Now all we need to do is to register this handler:
```
func main() {
e := echo.New()
spec.RegisterHandlers(e, server{})
e.Logger.Fatal(e.Start(address))
}
```
At this stage, we have a fully working client and server with a minimum amount of hand-written code. There is a ton of cool features we can add on top of that, for example, `echo` offers a middleware that will automatically validate the request payload and return detailed validation error. Overall, the usage of OpenAPI specification in combination with `oapi-codegen` generator and `echo` framework can radically increase the speed of web development by removing the necessity for hand-written boiler-plate code.
The specification and code can be found [here](https://github.com/ayzu/article-openapi-go). | https://habr.com/ru/post/571660/ | null | null | 916 | 55.95 |
4 Key Observability Metrics for Distributed Applications
What to watch with your cloud applications- in this post, we'll cover areas your metrics should focus on to ensure you're not missing key insights.
Join the DZone community and get the full member experience.Join For Free
A common architectural design pattern these days is to break up an application monolith into smaller microservices. Each microservice is then responsible for a specific aspect or feature of your app. For example, one microservice might be responsible for serving external API requests, while another might handle data fetching for your frontend.
Designing a robust and fail-safe infrastructure in this way can be challenging; monitoring the operations of all these microservices together can be even harder. It's best not to simply rely on your application logs for an understanding of your systems' successes and errors. Setting up proper monitoring will provide you with a more complete picture, but it can be difficult to know where to start. In this post, we'll cover service areas your metrics should focus on to ensure you're not missing key insights.
Before Getting Started
We're going to make a few assumptions about your app setup. Don't worry—you don't need to use any specific framework to start tracking metrics. However, it does help to have a general understanding of the components involved. In other words, how you set up your observability tooling matters less than what you track.
Since a sufficiently large set of microservices requires some level of coordination, we're going to assume you are using Kubernetes for orchestration. We're also assuming you have a time series database like Prometheus or InfluxDB for storing your metrics data. You might also need an ingress controller, such as the one Kong provides to control traffic flow, and a service mesh, such as Kuma, to better facilitate connections between services.
Before implementing any monitoring, it's essential to know how your services actually interact with one another. Writing out a document that identifies which services and features depend on one another and how availability issues would impact them can help you strategize around setting baseline numbers for what constitutes an appropriate threshold.
Types of Metrics
You should be able to see data points from two perspectives: Impact Data and Causal Data. Impact Data represents information that identifies who is being impacted. For example, if there's a service interruption and responses slow down, Impact Data can help identify what percentage of your active users is affected.
While Impact Data determines who is being affected, Causal Data identifies what is being affected and why. Kong Ingress, which can monitor network activity, can give us insight into Impact Data. Meanwhile, Kuma can collect and report Causal Data.
Let's look at a few data sources and explore the differences between Impact Data and Causal Data that can be collected about them.
Latency
Latency is the amount of time it takes between a user performing an action and its final result. For example, if a user adds an item to their shopping cart, the latency would measure the time between the item addition and the moment the user sees a response that indicates its successful addition. If the service responsible for fulfilling this action degraded, the latency would increase, and without an immediate response, the user might wonder whether the site was working at all.
To properly track latency in an Impact Data context, it's necessary to follow a single event throughout its entire lifetime. Sticking with our purchasing example, we might expect the full flow of an event to look like the following:
The customer clicks the "Add to Cart" button
The browser makes a server-side request, initiating the event
The server accepts the request
A database query ensures that the product is still in stock
The database response is parsed, a response is sent to the user, and the event is complete
To successfully follow this sequence, you should standardize on a naming pattern that identifies both what is happening and when it's happening, such as
customer_purchase.initiate,
customer_purchase.queried,
customer_purchase.finalized, and so on. Depending on your programming language, you might be able to provide a function block or lambda to the metrics service:
statsd.timing('customer_purchase.initiate') do # ... end
By providing specific keywords, you ought to hone in on which segment of the event was slow in the event of a latency issue.
Tracking latency in a Causal Data context requires you to track the speed of an event between services, not just the actions performed. In practice, this means timing service-to-service requests:
statsd.histogram('customer_purchase.initiate') do statsd.histogram('customer_purchase.external_database_query') do # ... end end
This shouldn't be limited to capturing the overall endpoint request/response cycles. That sort of latency tracking is too broad and ought to be more granular. Suppose you have a microservice with an endpoint that makes internal database requests. In that case, you might want to time the moment the request was received, how long the query took, the moment the service responded with a request, and the moment when the originating client received that request. This way, you can pinpoint precisely how the services communicate with one another.
Traffic
You want your application to be useful and popular—but an influx of users can be too much of a good thing if you're not prepared! Changes in site traffic can be difficult to predict. You might be able to serve user load on a day-to-day basis, but events (both expected and unexpected) can have unanticipated consequences. Is your eCommerce site running a weekend promotion? Did your site go viral because of some unexpected praise? Traffic variances can also be affected by geolocation. Perhaps users in Japan are experiencing traffic load in a way that users in France are not. You might think that your systems are working as intended, but all it takes is a massive influx of users to test that belief. If an event takes 200ms to complete, but your system can only process one event at a time, it might not seem like there's a problem—until the event queue is suddenly clogged up with work.
Similar to latency, it's useful to track the number of events being processed throughout the event's lifecycle to get a sense of any bottlenecks. For example, tracking the number of jobs in a queue, the number of HTTP requests completed per second, and the number of active users are good starting points for monitoring traffic.
For Causal Data, monitoring traffic involves capturing how services transmit information to one another, similar to how we did it for latency. Your monitoring setup ought to track the number of requests to specific services, their response codes, their payload sizes, and so on—as much about the request and response cycle as necessary. When you need to investigate worsening performance, knowing which service is experiencing problems will help you track the possible source much sooner.
Error Rates
Tracking error rates is rather straightforward. Any 5xx (or even 4xx) issued as an HTTP response by your server should be tagged and counted. Even situations that you've accounted for, such as caught exceptions, should be monitored because they still represent a non-ideal state. These issues can act as warnings for deeper problems stemming from defensive coding that doesn't address actual problems.
Kuma can capture the error codes and messages thrown by your service, but this represents only a portion of actionable data. For example, you can also capture the arguments which caused the error (in case a query was malformed), the database query issued (in case it timed out), the permissions of the acting user (in case they made an unauthorized attempt), and so on. In short, capturing the state of your service at the moment it produces an error can help you replicate the issue in your development and testing environments.
Saturation
You should track the memory usage, CPU utilization, disk reads/writes, and available storage of each of your microservices. If your resource usage regularly spikes during certain hours or operations or increases at a steady rate, this suggests you’re overutilizing your server. While your server may be running as expected, once again, an influx of traffic or other unforeseen occurrences can quickly topple it over.
Kong Ingress only monitors network activity, so it's not ideal for tracking saturation. However, there are many tools available for tracking this with Kubernetes.
Implementing Monitoring and Observability
Up to now, we've discussed the kinds of metrics that will be important to track in your cloud application. Next, let’s dive into some specific steps you can take to implement this monitoring and observability.
Install Prometheus
Prometheus is the go-to standard for monitoring, an open-source system that is easy to install and integrate with your Kubernetes setup. Installation is especially simple if you use Helm.
First, we create a
monitoring namespace:
$ kubectl create namespace monitoring
Next, we use Helm to install Prometheus. We make sure to add the Prometheus charts to Helm as well:
$ helm repo add prometheus-community $ helm repo add stable $ helm repo update $ helm install -f -n monitoring prometheus prometheus-community/prometheus
The values file referenced at sets the data scrape interval for Prometheus to ten seconds.
Enable Prometheus Plugin in Kong
Assuming you are using Kong Ingress Controller (KIC) for Kubernetes, your next step will be to create a custom resource—a
KongPlugin resource—which integrates into the observability platform that provides excellent dashboards for visualization of data scraped by Prometheus. We use Helm to install Grafana as follows:
$ helm install grafana stable/grafana -n monitoring --values
You can view the bit.ly URL in the above command to see the specific configuration values for Grafana that we provide upon installation.
Enable Port Forwarding
Now that Prometheus and Grafana are up and running in our Kubernetes cluster, we'll need access to their dashboards. For this article, we'll set up basic port forwarding to expose those services. This is a simple—but not very secure—way to get access, but not advisable port
9090 and the Grafana dashboard on port
3000.
Those simple steps should be sufficient to set you off and running. With Kong Ingress Controller and its integrated Prometheus plugin, capturing metrics with Prometheus and visualizing them with Grafana are quick and simple to set up.
Conclusion
Whenever you need to investigate worsening performance, your Impact Data metrics can help orient you on the magnitude of the problem: it should tell you how many people are affected. Likewise, your Causal Data identifies what isn't working and why. The former points you to the plume of smoke, and the latter takes you to the fire.
In addition to all of the above, you should also consider the rate at which your metrics are changing. For example, say your traffic numbers are increasing. Observing how quickly those numbers are moving can help you determine when (or if) it'll become a problem. This is essential for managing upcoming work with regular deployments and changes to your services. It also establishes what an ideal performance metric should be.
Google wrote an entire book on site reliability, which is a must-read for any developer. If you're already running Kong alongside your clusters, plugins such as this one integrate directly with Prometheus, which means less configuration on your part to monitor and store metrics for your services.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/key-observability-metrics-for-distributed-applicat | CC-MAIN-2021-31 | refinedweb | 1,937 | 50.87 |
Meaning of the -tt option reads:
"Like -tt, but raises an error rather than a warning"
now reads:
"Like -t, but raises an error rather than a warning"
p. 45 --
"from future import division"
now reads:
"from __future__ import division"
"j is less than i"
now reads:
"j is less than or equal to i"
L[i:i]=['a','b'] inserts the items 'a' and 'b' after item i in L.
now reads:
L[i:i]=['a','b'] inserts the items 'a' and 'b' before item i in L.
The last sentence ends with
"..., while L*=n has the effect of adding n copies of L to the end of L."
The last sentence now reads:
"..., while L *= n has the effect of adding n-1 copies of L to the end of L."
x[1] = 42 # x is now [1,42,2,3]
Now reads:
x[1] = 42 # x is now [1,42,3,4]
"else expression:
statement(s)"
Now reads:
"else:
statement(s)"
def percent2(a, b, c): #needs 2.2 or "from future import"
Now reads:
def percent2(a, b, c): #needs 2.2 or "from __future__ import"
def make_adder_2(augend): # needs 2.2 or "from future import"
Now reads:
def make_adder_2(augend): # needs 2.2 or "from __future__ import"
print x.e, x.d, x.c, x.b. x.a
NOW READS:
print x.e, x.d, x.c, x.b, x.a
Missing "to" in "A bound method is similar TO an unbound method,..." has now been added.
The code samples use the variable "heigth", which is now correctly spelled as "height".
The code:
class OptimizedRectangle(object):
__slots__ = 'width', 'height'
__slots__ cannot usefully be added by inheritance in this way; so the
example should be rewritten to avoid inheritance and rather just copy
the whole Rectangle class as given at the top of page 85 under the new
name OptimizedRectangle:
class OptimizedRectangle(object):
__slots__ = 'width', 'height'
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
area = property(getArea, doc="area of the rectangle")
"__metaclass_ = type"
Now reads:
"__metaclass__ = type"
"Since type(object) is type, a class C that inherits from object (or some other built-
in type) gets the same metaclass as object (i.e., type(C), C's metaclass, is also
type) Thus, being a new-style class is synonymous with having type as the metaclass."
"Thus, being..." is the start of a second sentence. A period HAS BEEN ADDED to the end of the sentence
"Since type(object)...".
"except InvalidAttribute, err"
Now reads:
"except InvalidAttribute, err:"
where it says:
For more on buffer, see Chapter 13.
The text now reads:
The buffer built-in is now deprecated.
"if re.search(..."
Now reads:
"if digatend.search(..."
The bottom line of text was missing in printings after 9/03.
the missing line was:
want to print only words that are followed by whitespace (not
THIS HAS BEEN CORRECTED.
The last Paragraph of the description of map states:-
"When func is None, map returns a list of tuples ..."
This is only true if map is given at least 2 seqs to "map".
If it is given a single seq, it returns the seq itself.
This can cause serious errors in programs that expect
tuples to be returned.
Note from the Author or Editor:p. 164 under `map`, 2nd paragraph, change the text that now reads
When func is None, map returns a list of tuples, each with n items (one item from each iterable); this is
to read
When func is None, map returns a list of tuples, each with n items (one item from each iterable) when n>1; this is
and add to the same paragraph (which now ends "the longer ones.") a further sentence
When func is None and n is 1, map returns a list of the items of seq (while zip would return a list of tuples with just one item each).
The os.path Module functions table is missing the "expanduser" method
and related description. (See, for example, the documentation at the
following URL:)
"For example, os.path.basename('b/c/d.e') returns 'b/c'"
Now reads:
"For examples, os.path.dirname('b/c/d.e') returns 'b/c'"
"but calling lstat on a file that does not support seeking ..."
should be:
"but calling lseek on a file that does not support seeking ..."
To make the example work the same way for both the direct and indirect method, the line:
zinfo.compress_type = zipfile.ZIP_DEFLATED
HAS BEEN ADDED after the line:
zinfo = zipfile.ZipInfo(name, time.localtime()[:6])
When languages is None, translation looks in the environment for the lang to use, like install.
However, languages can also be a list of one or more lang names separated by colons (:), in which
case translation uses the first of these names for which it finds a .mo file.
NOW READS:
When languages is None, translation looks in the environment for the lang to use, like
install: it examines, in order, environment variables LANGUAGE, LC_ALL, LC_MESSAGES, LANG -- the first
non-empty one is split on ':' to give a list of lang names (for example, 'de:en' would be split to give ['de','en']).
When not None, languages must be a list of one or more lang names (for example, ['de','en']). Translation uses the
first lang name in the list for which it finds an .mo file.
gettext.translation(domain, languages=lang)
NOW READS:
gettext.translation(domain, languages=[lang])
"in releases of Python older than the ones covered in this book,
unpickling from an untrusted data source was a security risk ... No
such weaknesses are known in Python 2.1 and later."
This is no longer true, the 2nd edition says:
Note that unpickling from an untrusted data source is a security risk; an attacker could
exploit this to execute arbitrary code. Don't unpickle untrusted data!
x.close()
Now reads:
x.cursor()
Classes ExternalInterfacing and Serializer (snippets on pages 284-285)
are not thread-safe as shown in the book. Change the snippets as
follows:
Add the following auxiliary class, to be used in both snippets, and
useful in its own right:
class PoolOfQueues:
# thread-safe, because a list's pop and append methods are atomic
def __init__(self):
self.pool = []
def get_a_queue_from_pool(self):
try: return self.pool.pop()
except IndexError: return Queue.Queue()
def return_a_queue_to_pool(self, q):
self.pool.append(q)
queues=PoolOfQueues()
Change class ExternalInterfacing to:
class ExternalInterfacing(Threading.Thread):
def __init__(self, externalCallable, **kwds):
Threading.Thread.__init__(self, **kwds)
self.setDaemon(1)
self.externalCallable = externalCallable
self.workRequestQueue = Queue.Queue()
self.start()
def request(self, *args, **kwds):
"called by other threads as externalCallable would be"
q = queues.get_a_queue_from_pool()
self.workRequestQueue.put((q, args, kwds))
try: return q.get()
finally: queues.return_a_queue_to_pool(q)
def run(self):
while 1:
q, args, kwds = self.workRequestQueue.get()
q.put(self.externalCallable(*args, **kwds))
Change class Serializer to:
class Serializer(Threading.Thread):
def __init__(self, **kwds):
Threading.Thread.__init__(self, **kwds)
self.setDaemon(1)
self.workRequestQueue = Queue.Queue()
self.start()
def apply(self, callable, *args, **kwds):
"called by other threads as callable would be"
q = queues.get_a_queue_from_pool()
self.workRequestQueue.put((q, callable, args, kwds))
try: return q.get()
finally: queues.return_a_queue_to_pool(q)
def run(self):
while 1:
q, callable, args, kwds = self.workRequestQueue.get()
q.put(callable(*args, **kwds))
import Threading, Queue
Now reads:
import threading, Queue
import Threading
Now reads:
import threading
import os
os.spawnv(os.p_WAIT, editor, [textfile])
NOW READS:
import os
os.spawnv(os.p_WAIT, editor, [editor, textfile])
and, the last sentence NOW READS:
The first item of the argument <replaceable>args</replaceable> is
passed to the program being spawned as "the name under which the
program is being invoked". Most programs don't look at this, so you
can place any string there. Just in case the editor program does look
at this special first argument, passing the same string
<replaceable>editor</replaceable> that is used as the second argument
to os.spawnv is the simplest and most effective approach.
tofile Note that f should be open for reading in binary mode, for example with
mode 'rb'.
now reads:
tofile Note that f should be open for writing in binary mode, for example with
mode 'wb'.
a[0,2:4)
Now reads:
a[0,2:4]
where it says:
an array with rank of one less than a and of the same size as a
The text now reads:
an array with rank 1 and of the same size as a
where it says:
just like array(a,copy=False).flat
The text now reads:
just like array(a,copy=(not a.iscontiguous())).flat
The URL has changed and now reads:
In the example to diplay GIF images in the example, the line:
img.config(image=gifsdict[imgname])
Is now indented as follows:
def list_entry_clicked(*ignore):
imgname = L.get(L.curselection()[0])
img.config(image=gifsdict[imgname])
An Entry instance with state=DISABLED is a good way...
"state=DISABLED" should be replaced by "state='readonly'" for the
remainder of the page.
state=DISABLED doesn't allow you to select an Entry's text
or copy it to the clipboard.
Note from the Author or Editor:p. 416 and 417 *NOT* 337, change all occurrences of DISABLED (I count four) to 'readonly' (lowercase and with single quotes around). So for example
state=DISABLED
must become
state='readonly'
and so on.
toggle c.deselect()
Now reads:
toggle c.toggle()
The entry for 'iconify' shows 'deiconify' for the example.
Iconify T.deiconify()
Now reads:
Iconify T.iconify()
The following two lines have been added to the end of the script:
root.config(menu=bar)
Tkinter.mainloop()
def makeshow(menu):
def emit(entry, menu=menu): print menu, entry
return emit
NOW READS:
def mkshow(menu, entry):
def emit(): print menu, entry
return emit
AND the first two lines on the top of page 347;
and use command=mkshow('File') and command=mkshow('Edit'),
respectively, in the calls to the add_command methods of fil and edi.
NOW READ:
and use command=mkshow('File', x) and command=mkshow('Edit', x),
respectively, in the calls to the add_command methods of fil and edi.
logical error
j = CY*(y-miny)/(maxy-miny)
Now reads:
j = CY - CY*(y-miny)/(maxy-miny)
try: x.f()
except AttributeError:
sys.stderr.write('x is type %s, (%r)
'%(x,type(x)))
That 3rd line NOW READS:
sys.stderr.write('x is type %s, (%r)
'%(type(x), x))
omitted nlist method.
The nlst method should probably be included, in its normal alphabetical order
(i.e., after mkd but before pwd) with the text (in the usual mixture of fonts
and typefaces like for the other methods):
nlst f.nlst(pathname='.')
Sends a NLST command to the FTP server, asking for the names
of the files in the directory named by pathname (by default,
the current directory), and returns the list of the filenames.
((i.e., as usual, I would omit weird, rarely used stuff such as, in this case,
the optional, non-portable extra arguments)).
"...supplies an attribute s.server that..."
NOW READS:
"...supplies an attribute s.system that..."
s.server.listMethods()
s.server.methodSignature(name)
s.server.methodHelp(name)
NOW READ:
s.system.listMethods()
s.system.methodSignature(name)
s.system.methodHelp(name)
where it says
ntohl htonl(i32)
The text now reads:
ntohl ntohl(i32)
AND
where it says
ntohs htons(i32)
The text now reads:
ntohs ntohs(i32)
The example trivial HTTP server is missing the two lines to instantiate and start up the server.
After the line do_HEAD = do_POST = do_GET, the following two lines have been added:
server = BaseHTTPServer.HTTPServer(('',80), TrivialHTTPRequestHandler)
server.serve_forever()
try: ous.remove(x)
except ValueError: pass
x.close()
NOW READ:
try: ous.remove(x)
except ValueError: pass
x.close()
ins.remove(x)
MIMEImage class MIMEAudio(_imagedata,...
Now reads:
MIMEImage class MIMEImage(_imagedata,...
quoteattr escape(data,entities={})
Now reads:
quoteattr quoteattr(data,entities={})
Pages 507, 508, and 511:
The following warning note has been added on page 511:
The code examples given on pages 507, 508 and 511 may crash under
some version of Python and Windows (not Python 2.3, and not Linux
versions of Python). To fix your version of Python so that it is able to
run the examples, visit URL:
and download and run the appropriate self-installing .EXE, for example
currently PyXML-0.8.2.win32-py2.2.exe if you run Python 2.2 on any
version of Microsoft Windows. This self-installing EXE will add to your
Python installation the latest version of the "XML subsystem" of Python,
and, as a side effect, fix any bugs connected to XML handling that may
have been diagnosed after the release of your version of Python.
There are two arrays declared as
static char merge_docs[]
The second one (page 536) now reads:
static char mergenew_docs[] = "
sdist default does not include scripts or data files, even if specifically mentioned
in the setup.py script. The default only includes:
"all Python source files implied by the py_modules and packages options"
To include scripts or data files by sdist, you have to create a MANIFEST.in
The Installer website NOW READS:
Index for "*" and "**" should be augmented for
define extra arguments, 60
pass extra arguments, 64
There is no entry in the index for the consept "frozen", mentioned on page 121 just
before and after the heading "Searching the Filesystem for a Module".
Worse IMHO, there's no explanation in the book, that I can find, on what "frozen
modules" is. A line or two on page 121 would have been nice.
© 2017, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.oreilly.com/catalog/errata.csp?isbn=9780596001889 | CC-MAIN-2017-30 | refinedweb | 2,295 | 64.81 |
Hive Architecture in Depth
Apache Hive is an ETL and Data warehousing tool built on top of Hadoop for data summarization, analysis and querying of large data systems in open source Hadoop platform. The tables in Hive are similar to tables in a relational database, and data units can be organized from larger to more granular units with the help of Partitioning and Bucketing.
As part of this blog, I will be explaining as to how the architecture works on executing a hive query. Details such as the execution of queries, format, location and schema of hive table inside the Metastore etc.
There are 4 main components as part of Hive Architecture.
- Hadoop core components(Hdfs, MapReduce)
- Metastore
- Driver
- Hive Clients
Let’s start off with each of the components individually.
- Hadoop core components:
i) HDFS: When we load the data into a Hive Table it internally stores the data in HDFS path i.e by default in hive warehouse directory.
The hive default warehouse location can be found at
We can create a hive table and load the data into it as shown in below images.
ii) MapReduce: When we Run the below query, it will run a Map Reduce job by converting or compiling the query into a java class file, building a jar and execute this jar file.
2. Metastore: is a namespace for tables. This is a crucial part for the hive as all the metadata information related to the hive such as details related to the table, columns, partitions, location is present as part of it. Usually, the Metastore is available as part of the Relational databases eg: MySql
You can check the DataBase configuration via hive-site.xml
The Metastore details can be found as shown below.
Metastore has an overall 51 tables describing various properties related to the table but out of these 51 the below 3 tables are the ones which provide majority of the information, that in-turn helps hive infer the schema properties to execute the hive commands on a table.
i) TBLS — Store all table information (Table name, Owner, Type of Table(Managed|External)
ii) DBS — Database information (Location of database, Database name, Owner)
iii) COLUMNS_V2 — column name and the datatype
Note: In real-time the access to metastore is restricted to the Admin and specific users.
3. Driver: The component that parses the query, does semantic analysis on the different query blocks and query expressions and eventually generates an execution plan with the help of the table and partition metadata looked up from the metastore. The execution plan created by the compiler is a DAG of stages.
A bunch of jar files that are part of hive package help in converting these HiveQL queries into equivalent MapReduce jobs(java) and execute them on MapReduce.
To check if the hive can talk to the appropriate cluster. i.e for hive to interact, query or execute with the existing cluster. You can check details under core-site.xml.
You can verify the same from hive as well.
4. Hive Clients: It is the interface through which we can submit the hive queries. eg: hive CLI, beeline are some of the terminal interfaces, we can also use the Web-interface like Hue, Ambari to perform the same.
On connecting to Hive via CLI or Web-Interface it establishes a connection to Metastore as well.
The commands and queries related to this post are added as part of my GIT repository.
If you enjoyed reading it, you can click the heart ❤️ below and let others know about it. If you have got anything to add please feel free to leave a response 💬💭. | https://medium.com/plumbersofdatascience/hive-architecture-in-depth-ba44e8946cbc | CC-MAIN-2019-39 | refinedweb | 610 | 59.13 |
Java Reference
In-Depth Information
Setter injection methods are invoked by the container before any business methods
on the bean instance. Multiple resources may be injected using the @Resources
annotation. For example, in the following code snippet two resources of type javax.
sql.DataSource are injected.
@Resources({
@Resource(name="ds1", type="javax.sql.DataSource"),
@Resource(name="ds2", type="javax.sql.DataSource")
} )
JNDI resources injected with the dependency mechanism may be looked up in the
java:comp/env namespace. For example, if the JNDI name of a resource of type
javax.sql.DataSource is catalogDB , the resource may be looked up as follows.
InitialContext ctx = new InitialContext();
Javax.sql.DataSource ds = ctx.lookup("java:comp/env/catalogDB");
Simplified Session Beans
In EJB 2.x, a session bean is required to implement the SessionBean interface. An
EJB 3.0 session bean class is a POJO ( Plain Old Java Object ) and does not implement
the SessionBean interface.
An EJB 2.x session bean class includes one or more ejbCreate methods, the callback
methods ejbActivate , ejbPassivate , ejbRemove , and setSessionContext , and
the business methods defined in the local/remote interface. An EJB 3.0 session bean
class includes only the business methods.
In EJB 3.0, EJB component interfaces and home interfaces are not required for
session beans. A remote interface in an EJB 2.x session EJB extends the javax.ejb.
EJBObject interface; a local interface extends the javax.ejb.EJBLocalObject
interface. A home interface in an EJB 2.x session EJB extends the javax.ejb.EJBHome
interface; a local home interface extends the javax.ejb.EJBLocalHome interface. In
EJB 3.0 the home/local home and remote/local interfaces are not required. The EJB
interfaces are replaced with a POJI ( Plain Old Java Interface ) business interface.
If a business interface is not included with the session bean class, a POJI business
interface gets generated from the session bean class by the EJB server.
An EJB 2.x session EJB includes a deployment descriptor that specifies the EJB name,
the bean class name, and the interfaces. The deployment descriptor also specifies
the bean type of Stateless/Stateful. In EJB 3.0, a deployment descriptor is not
required for a session bean. An example EJB 2.x session bean, which implements the
SessionBean interface, is listed next:
Search WWH ::
Custom Search | http://what-when-how.com/Tutorial/topic-235ji0lm/EJB-30-Database-Persistence-with-Oracle-Fusion-Middleware-11g-25.html | CC-MAIN-2020-16 | refinedweb | 386 | 53.88 |
You can use the LookupValue() member function, e.g., // Assuming vtkScalars is a subclass of vtkDataArray minIndex = vtkScalars.LookupValue(minValue) maxIndex = vtkScalars.LookupValue(maxValue) This will do the scanning David mentioned and return (probably) the first index that matches the value you are querying. There is even a variant that puts all the IDs with the query value in a vtkIdList. See Hope that helps, Cory On Tue, Jul 7, 2015 at 3:35 PM, David Cole via vtkusers <vtkusers at vtk.org> wrote: > 0 0 1 2 8 9 10 9 0 0 0 9 10 9 8 6 4 3 0 0 > > What's the index of 10? > > :-P > > > You'll have to scan looking for the first or last index, I think, > since, in general, the min and max may occur any number of times in a > data set. > > HTH, > David C. > > > > > On Tue, Jul 7, 2015 at 4:30 PM, mightos <mightos at gmail.com> wrote: > > Hello > > > > Let's say I have a vtkScalars with 100000 values. > > I would like to know the minimum and maximum values and their position in > > the vtkScalars. > > > > I currently use vtkScalars.GetRange()[0] to get the minimum value and > > vtkScalars.GetRange()[1] for the maximum. However, I was wondering how I > > could get the indexes from that. > > > > Any help is welcome :) > > > > > > > > -- > >: <> | https://public.kitware.com/pipermail/vtkusers/2015-July/091426.html | CC-MAIN-2022-27 | refinedweb | 221 | 84.57 |
ComboBox font sizebvm May 10, 2012 5:45 PM
It looks to me that the editable text field of a ComboBox inherits the font size of its ancestors, but the popup list of choices doesn't. Is this a bug or a feature? If the latter, what's the right way to style the popup? Looking at the CSS reference, I tried
but it didn't take.but it didn't take.
#myComboBox .list-cell { -fx-font-size: ... }
This content has been marked as final. Show 8 replies
1. Re: ComboBox font sizejsmith May 10, 2012 6:02 PM (in response to bvm)Something like
may work (haven't tried it though).
.combo-box-popup .list-cell { ... }
Not sure if you can stick the id in there or not as it may not carry through from the parent stage to the popup's stage.
All the popup controls (contextmenu, choicebox, combobox, dropdown, etc) work this way.
Because the popups show up in the own stages with their own root scenes, the stuff in the popup doesn't inherit any styles from the rest of the scenes parents.
Although perhaps there are good reasons for this, I find it quite annoying.
What I have done in the past is listened for when the popups are displayed grabbed their root and then restyled them at runtime - which is not a good solution for numerous reasons.
Looking at the css documentation it shows a substructure like so:
list-cell - a ListCell instance used to show the selection in the button area of a non-editable ComboBoxSo I think you want to apply your style to combo-box-popup rather than directly to the combobox because applying it directly to the combobox will only make it take effect on the combobox button and not on the list of possible choices.
text-input — a TextField instance used to show the selection and allow input in the button area of an editable ComboBox
combo-box-popup - a PopupControl that is displayed when the button is pressed
- list-view - a ListView
-- list-cell - a ListCell
2. Re: ComboBox font sizebvm May 10, 2012 6:14 PM (in response to jsmith)
jsmith wrote:Unfortunately not. In fact, even the absurdly over-broad
Something like
may work (haven't tried it though).
.combo-box-popup .list-cell { ... }
doesn't work.
.list-cell { ... }
3. Re: ComboBox font sizejsmith May 10, 2012 6:17 PM (in response to jsmith)Here is a sample I did earlier for a ChoiceBox.
As the concepts are similar, perhaps it gives you some direction on how to knock up a similar sample for ComboBox.
import javafx.application.Application; import javafx.collections.FXCollections; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class ChoiceColor extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { FlowPane flowPane = new FlowPane(10, 10); flowPane.setId("flowPane"); ChoiceBox choiceBox = new ChoiceBox(FXCollections.observableArrayList("option 1", "option 2")); choiceBox.getSelectionModel().select(0); Label label = new Label("Options"); flowPane.getChildren().addAll(label, choiceBox); Scene scene = new Scene(flowPane); scene.getStylesheets().add(ChoiceColor.class.getResource("choices.css").toExternalForm()); stage.setScene(scene); stage.show(); } }
The key is the mystical #choice-box-menu-item .label selector. As you can see I never assigned, that id, so it comes from somewhere in the skin and I found it in caspian.css in jfxrt.jar. Perhaps you can find something similar for combobox?
// choices.css FlowPane { -fx-background-color: fuschia; -fx-font-size: 20; } #flowPane .label { -fx-text-fill: red; } #flowPane .choice-box .label { -fx-text-fill: green; } #choice-box-menu-item .label { -fx-text-fill: salmon; -fx-font-size: 20; }
4. Re: ComboBox font sizeDavid Grieve May 10, 2012 6:55 PM (in response to bvm).combo-box-popup .list-view .list-cell .text {
-fx-fill: red;
-fx-font-size: 16px;
}
5. Re: ComboBox font sizejsmith May 10, 2012 7:00 PM (in response to David Grieve)That's very cool. Works great. Thx David.
6. Re: ComboBox font size956927 Oct 31, 2012 9:21 AM (in response to David Grieve)Hy there,
this did not work for me ;(
so i have a combobox in JavaFX 2.0 with default style combo-box and combo-box-base
If a apply in css to .combo-box .text{
-fx-fill: red;
-fx-font-size: 16px;
}
The default visible value is colored correct.
Then i tried to apply you style with
.combo-box-popup .list-view .list-cell .text {
-fx-fill: red;
-fx-font-size: 16px;
}
But could not see any difference to my listed items when i click the combo.
I also tried
.list-view .list-cell .text {
-fx-fill: red;
-fx-font-size: 16px;
}
But did not work either.
Thanks for additional hints
BR
7. Re: ComboBox font sizeedward17 Nov 1, 2012 11:43 AM (in response to 956927)In my experinece it works, but not once you compile the code. I opened a bug a while back on it.
8. Re: ComboBox font sizebmy1 Nov 6, 2012 6:22 AM (in response to bvm)Are there any news on this topic? I guess the issue is covered by, but are there any valid workarounds available? | https://community.oracle.com/message/10330249 | CC-MAIN-2015-48 | refinedweb | 874 | 65.32 |
Rails: Building a single-page Backbone app without sacrificing Turbolinks.
Part 2: Avoiding the zombie encroachment, or managing memory without a page change.
In Part 1 we covered how to ensure Backbone and Turbolinks share the browser history in your app without conflict.
With the loss of the full page load goes an important fig leaf in poor Backbone memory management. You can no longer depend on an eventual page change to clean up objects you forgot to release. Over time this can result in hordes of zombies, double-renders and orphaned event callbacks.
Why does a page change matter anyway?
Central to this whole challenge is that, in JavaScript, an object cannot be garbage collected until it is no longer referenced by anything that is being retained.
Instead of a full page change, Turbolinks retains the active page and injects the body and title of the new one. Backbone views from the active page will stick around because they haven’t been released properly, merely replaced in the DOM. Accidentally retained objects will accumulate indefinitely as the user navigates. Even your Backbone app itself will stick around unless you clean it up.
Fortunately it isn’t as hard as it may seem to avoid situations where memory issues creep in. The constraint can even be a good thing, keeping you honest and encouraging healthy code. Here are a few guidelines that will help you stay out of danger.
1. Establish a view teardown strategy
Commonly this means adding a close() method to the Backbone.View prototype that removes the view element from the DOM and executes a callback if one exists.
Backbone.View::close = ->
@remove()
@onClose() if @onClose?
class ItemListView extends Backbone.View
onClose: ->
console.log "Item list view is being closed!"
Calling remove() on a view automatically removes the view element from the DOM, clears any bound events and data, and calls stopListening() on the view itself. Having a callback like the onClose method allows you to perform custom cleanup on the view itself. Derick Bailey first detailed this on his blog.
It’s up to you to make sure you track your subviews so that you can release them in the onClose callback.
onClose: ->
itemView.close() for itemView in @itemViews
2. Undelegate bound views
Backbone allows us to bind to existing DOM elements by specifying the el attribute when creating a view:
view = new MyApp.ItemListView(el: ‘#items’, collection: @items)
This time we can’t remove the element from the DOM when cleaning it up because the app may need to bind to it again if the user revisits a cached version of the page. No problem, we simply need to adjust our close() method to undelegate events manually and avoid removing the view element when told to do so.
Backbone.View::close = (remove = true) ->
if remove
@remove()
else
@undelegateEvents()
@stopListening()
@onClose() if @onClose()
3. Don’t bind when you should listenTo
You’ll often find yourself binding to a lot of model or collection events like this:
initialize: ->
@model.on 'change:total', @refreshTotal, this
@model.on 'change:state', @refreshState, this
# ...
You may want to use listenTo() instead. The following code is analogous but allows the view to track events and unbind them with a single call to stopListening().
initialize: ->
@listenTo @model, 'change:total', @refreshTotal
@listenTo @model, 'change:state', @refreshState
# ...
Since stopListening() is called automatically when you close the view unbinding callbacks is now one less thing to worry about.
4. Beware of binding outside the view scope
You almost never want a view to bind to events outside its scope but in some cases, such as listening to the document for a particular keydown combination, it just can’t be helped.
These are amongst the most dangerous of bindings. If unremoved they will accumulate. If they reference the view it will stick around forever. If the view is destroyed they’ll trigger callbacks that no longer exist.
The onClose callback provides the obvious place to clear these up. It’s possible to namespace them by purpose so that they can be safely removed in groups.
class ItemListView extends Backbone.View
initialize: ->
$(document).on 'keydown.hotkeys', @respondToDeleteKeydown
$(document).on 'keydown.hotkeys', @respondToShiftCKeydown
onClose: ->
$(document).off('keydown.hotkeys')
However I’m still not happy with this approach. I find that these events almost always constitute a particular role that requires its own object or context, hotkeys being a good example.
I prefer to use a global pubSub object that extends Backbone.Events and can be listened to by any object in your app:
window.pubSub = _.extend({}, Backbone.Events)
The hotkeys functionality can be abstracted into a jQuery plugin that triggers events on the pubSub object. This setup is much more modular and clean. Your views listenTo the pubSub object and stopListening automatically when they’re closed.
initialize: ->
@listenTo pubSub, 'hotkey:delete', @respondToDeleteKeydown
@listenTo pubSub, 'hotkey:shift_c', @respondToShiftCKeydown
All you have to worry about is releasing a single pubSub object and stopping the jQuery plugin when your app is closed. For more information on pubSub in Backbone check out Tim Ruffles’s blog post.
5. Tidy up after the page has changed
The last challenge is to make sure your app gets tidied up at the right time. This is straightforward enough — you probably want to create a close() method for your router that will close the views it has created. If you’ve used your onClose callbacks correctly this should bubble down into all subviews, removing their events and cleaning up the DOM elements they’ve created.
Let’s take our setup from Part 1 and keep a reference to the router so that we can close it later when we’re done. We’ll add a teardown method that so we can clean up our app and call it when the page:change event is fired.
window.MyApp =
Models: {}
Collections: {}
Views: {}
Routers: {}
initialize: ->
@router = new MyApp.Routers.Items()
Backbone.history.start()
teardown: ->
@router.close()
@router = undefined
$(document).on 'page:change', ->
if MyApp.router?
Backbone.history.stop()
MyApp.teardown()
if shouldLoadApp() # Function from part 1
# Initialize the app
There are a number of reasons for cleaning up after the page has changed.
- If the user navigates from the Backbone app page but hits the stop button, the app will still be active.
- If the user navigates from the Backbone app page it will retain its state and appearance until the page change has occurred.
- If the user navigates to the Backbone app page using the back or forward browser buttons the app will otherwise be in an unpredictable state.
- If it’s a full page load, the router won’t exist and no action will be taken.
Wrapping up
That’s it. These guidelines should help you keep your app clean. If you have any others I’d love to hear them —catch me on Twitter at @midhir.
The full source from this blog post and Part 1 is available as a gist. | https://medium.com/@midhir/rails-building-a-single-page-backbone-app-without-sacrificing-turbolinks-edf4849ddb73 | CC-MAIN-2018-34 | refinedweb | 1,156 | 65.22 |
The Semantic Line Interface 123 123
First time accepted submitter yuriyg_ua writes "[The] semantic line interface may combine features of both command line and graphical interface, which would allow even more complex applications than we have seen before." The idea is that the layer underlying user interfaces should define the semantic relations between data enabling the UI to provide better contextual information. Kind of a modern version of the CLIM presentation system.
Re: (Score:3, Interesting)
In short: slow and annoying for people who know what they're doing. Supposedly useful for people without a clue.
Re: (Score:2)
it is not useful in the least. he gives an example of turning off a monitor and being able to access it in a few clicks. the problem with that is that the user needs to know that they want or need to turn off the monitor.
Total waste of time ... (Score:4, Informative)
Re: (Score:3)
Or like tab completion with modern bash_completions collections.
This is indeed pretty useless. Most attempts to "improve" the CLI with GUI elements have been, other than basic things like paste buffers and scrollbar integratuon. What I'd welcome instead is people approaching GUIs with an eye towards making it so that you don't have to write documentation like "first go to start bar and select control panel and then find the "network and file sharing center" item and double click that and then on the sideb
Re: (Score:2)
so that you don't have to write documentation like "first go to start bar and select control panel and then find the "network and file sharing center" item and double click that and then on the sidebar find "manage wireless networks" and highlight a network and right click and select properties and find Security/Settings/802.1x/blah//blah/bla
I proposed this: [ubuntu.com]
While it is supposed to be for phone support, it can also help "expert users":
The user can also type "tab" "B1" "space" to go item "B1".
If this was ever implemented, I'd probably use it to configure/control all sorts of stuff quickly.
A command explodes into objects (Score:2)
I think there's still a disconnect between GUI and CLI at a more fundamental level - people think of CLI as meaning text and only text, and GUI as only graphics (despite labels, fields, etc. being textual). Most (or every, if possible) UI item should be interactable (is that a word?) by keyboard or GUI, but for an example I'll start with a command line - when you run a command, it should create one or more interactable objects as the output. In a lot of cases (say, "cp" or "rm"), it could be an exit code th
Re: (Score:2)
Smarter people can probably come up with genuinely good ideas. Sadly, I've seen little of this even tried.
Try a modern linux with bash completions installed. Type "ls --" and hit tab. That and more people need to read the bash manpage.
Why you'd want to "arrow through" a large list of commands is beyond me.
Re: (Score:2)
Try a modern linux with bash completions installed. Type "ls --" and hit tab.
Why you'd want to "arrow through" a large list of commands is beyond me.
First, you wouldn't want to do that through a large list, only a small list. Also, a well designed interface would allow you to more powerful search tools that could be much faster (tree that expands as you type, giving you shortcuts to jump to or prune branches). I think that means you've missed the point.
The point is you're still thinking "text and only text" as the output from any command. Text based key completions (tab, arrow key, etc) are terribly old these days. I think you could find something like
Windows 7 search box? (Score:1)
Isn't this similar functionality to the windows 7 "search" box in the start menu?
Re:Windows 7 search box? (Score:5, Informative)
More like 4DOS shell (complete with menu system popping up). Or <Tab> in bash that is probably related to it. Or any autocompletion that relies on a parser instead of a dictionary.
Does Windows 7 search box parse the input to select the context, or use a flat list of "things" to call?
Re: (Score:2)
Or any autocompletion that relies on a parser instead of a dictionary.
I'd toss in a heaping dose of apropos [wikipedia.org] for semantic relationships as well. For example, to get from "pattern" to "grep".
If you could pull all those things together, it would be pretty wicked, I think. Tall order though, and I suspect there are people working on it (recent enhancements to context-sensitive tab completion come to mind).
Re: (Score:2)
No, that's something completely different.
apropos(1) uses the input language (unordered list of English words) completely incompatible with the language used by the interactive shell (shell and program-specific command line arguments). They do not belong together, should never be a part of the same entry, and user interface must never encourage the user to mix them. Interactive help may have command-line interface, even command-line interface with autocompletion, however this has absolutely nothing to do wi
Re: (Score:1)
Re: (Score:2)
it'll find task specific things in the new control panel
It won't find where to shut off that annoying "tap to click" feature on the notebook... it's not in control panel (where it should be) at all. 7's CP is a step backwards from XP IMO.
Embarrassingly, Linux gave me a similar idiocy yesterday when I discovered that you could make the bar at the bottom disappear; it was the one thing I thought Windows had an edge. I discovered it by accident; you should not have to discover features by accident, nor should
Re: (Score:3)
Technically, "Linux" doesn't provide any UI at all.
Were you using Gnome, KDE, XFCE, TWM, or some other desktop/window manager?
It's important that we know where to properly assign the blame and file the bug report.
(I'd guess Gnome. They're rather notorious for completely hiding configuration options...)
Re: (Score:2)
I get sloppy writing about Linux. Actually I should say GNU, but at any rate the desktop is KDE on Ubuntu (kubuntu 11.4).
I tried Gnome about ten years ago and hated it. Maybe I should try it again... but if they like to hide options, maybe not.
Re: (Score:2)
The semantic web just doesn't exist (Score:1, Offtopic)
I remember back in the 90s when I was first learning HTML and there were several articles talking about how the web was not sematic enough and I didn't really get the point. Now I totally get it. While trying to make good examples for climagic [climagic.org] on how to interface with the web, its just so much trouble. Even with all the recent focus on good web standards, web developers do stuff that just hinder people who want to scrape data. We really need some good commands for retrieving data from web documents, espec
Re: (Score:3)
Let's say I find a web page that I like, and maybe it has a form on it somewhere with a dropdown containing a list of countries. I'd like to scrape that list and do some kind of throwaway mashup for myself. It's painful. Or maybe I'd like to sift through a list of articles on a magazine website, and I care only about some paragraphs which talk about a city I've been to. And I'd like to display those paragraphs on a private dashboard. Again,
Re: (Score:3)
There are tools for tagging the content to make it easy to parse - mainly microformats, microdata and RDFa. The problem is that most content producers don't have an incentive to use them.
As an effort from the data consumer end, there's Scraper Wiki [scraperwiki.com], where people can share scrapers, but it's an hack compared to the real solution.
Re: (Score:3)
I think the fact you must rely upon the site to make the 'correct' choices would be the meat of the complaint. If you are constructing *your* server and client, sure you can apply the discipline and make the correct technology choices. In his example, he is wanting to do some sort automation against arbitrary sites he comes across. Because the technology is so open-ended, he has no idea of how one site will behave versus another and rarely get to reuse code. I've been there a few times, using the web dev
Re: (Score:2)
But if the information is there in my machine/browser I ought to have tools to do what I want with it, irrespective of what the content holders designed for me to see. You seem to argue that what the content holder wants should be good enough for me. It usually is, but only because the effort to extract/repurpose the bits I'm interested in is too high. The current web
Re: (Score:2)
You seem to argue that what the content holder wants should be good enough for me.
The content holder thinks that what the content holder provides is good enough. That's what OP means (I think).
Re: (Score:2)
I'd like to scrape that list and do some kind of throwaway mashup for myself. It's painful.
That's not so much a problem with the semantic web, but simply a lack of a more powerful copy&paste in your webbrowser/OS. The information is already there, nicely structured in a list and all, but your browser provides no way to get it out of the dropdown menu easily. If you go low-tech and use Lynx, you can just copy&paste the thing right out of your terminal with little problem. Nice benefit of everything being text in a terminal, even GUI elements.
Now of course when it comes to building more per
Re: (Score:3)
Or maybe I'd like to sift through a list of articles on a magazine website, and I care only about some paragraphs which talk about a city I've been to. And I'd like to display those paragraphs on a private dashboard.
You're not getting it. Ask yourself this: why would the magazine website want to make it easy for you to do that? If you did, you wouldn't see all the advertisements they plaster on their site to pay for it.
Re:The semantic web just doesn't exist (Score:4, Interesting)
Re: (Score:2)
Exactly. My point is it shouldn't be up to them. I have a computer that can spider the articles like a regular user, including the ads if that's what it takes, and I have processing tools on my machine to mine the content. What I don't have (but *should*, IMHO) are tools that make this pipeline so effortless that I can use them regularly during web surfing.
You think those tools should exist? Then write them yourself. There's no economic incentive for others to do it for you, after all.
Re: (Score:2)
it shouldn't be up to them
You do realize that all this requires human effort, and that requires money above and beyond what 99.999% of all web users care about. TANSTAATFL.
Re: (Score:2)
I agree that it's a major problem in using computers nowadays. The first one to publish a solution to this problem will have the next Facetwitoogle. I have my own design for this solution, but have to code it in my free time and will take a while to wire all the needed background processing.
The key to get it right is having an interface simple enough that pipes can be buil
Re: (Score:2)
Found your problem. You seem to think that the web is about the data. Didn't flash give you a hint? Didn't the mac web design pros teach you anything? It's about the layout, stupid!
This post optimized for 640 x480 and best viewed with netscape navigator using adobe type I Garamond font.
Re: (Score:2)
Let's say I find a web page that I like, and maybe it has a form on it somewhere with a dropdown containing a list of countries. I'd like to scrape that list and do some kind of throwaway mashup for myself. I
Are you saying you'd like to somehow... combine... other people's data... with other data... generating new data? That's outrageous! And I'm sure it's illegal. Hard-working programmers spent hours of their lives keying in that data, and now you want to just use it as if knowledge were some kind of... shared public resource or something? That must violate about a billionty copyright-patent laws, and if it doesn't, we'll darn sure pass new ones to make sure it does!
Consumers remixing data on their own. What h
Re:The semantic web just doesn't exist (Score:5, Informative)
JSON is a serialization, not a semantic format. You need RDF or something similar, regardless of its encoding - JSON, XML, Turtle [wikipedia.org], etc.
And as far as I know, there isn't a standard format for serializing RDF with JSON, although some work has been done on it.
Re: (Score:2)
But an API is considerably more effort than just sticking e.g. RDFa tags on your HTML templates describing the content, and more useful for the user than an API that you have to specifically code against, since you can use a generic parser.
Re: (Score:2)
XML and RDF are very different things.
XML and JSON are two serialization formats, yes (although the former supports namespaces, which is useful for serializing certain formats, like RDF).
RDF [wikipedia.org] is a completely different beast: it's a way to describe metadata using triples of Subject, Predicate and Object in a standard way. This format can be serialized in different ways: XML, N-Triples, Turtle, etc.
My point is that using "just JSON" (or just XML) is bad because what happens is that each person invents their ow
Re: (Score:2)
Re: (Score:2)
Yeah I'd agree with this, made it all the more impressive when I saw this web summarising app [bbc.co.uk] on the BBC the other day.
iPhone only, so I haven't been able to play with it.
Re:The semantic web just doesn't exist (Score:5, Informative)
Web developers don't want you to scrape data. They want you to get the data by manually going to their website with your browser like everyone else. If they wanted you to have a more efficient way of accessing data from their site, they'd publish an API, which is indeed what websites do for things where they want you to automate it. If there's no API, that's because they don't want you to automate anything.
Of course, there's a good reason for this too: if you automate your access to the data, you won't see their advertisements, err, I mean valuable marketing messages.
Re: (Score:2)
I vote with my wallet, and I'm vocal about it every time a distributor/vendor calls to complain we stopped ordering from them. I then tell them that I have no time to fax an order over, or even to reenter it every time I need 200 line items to replenish production stock/kits. A few distributors allow uploads of CSV or XLS files, and that works reasonably well, even though you still have to screen-scrape the entire process to extract the final outcome (what's in stock, what is the pricing, etc). It gets real
Re: (Score:2, Funny)
Nice to see more racist support for Ron Paul. I guess Newt and Mitt aren't white enough.
Re: (Score:2)
His proposed G.R.O.P.E. (General Raciness Of Personal Encroachment) act would have revolutionized America to being a mirror culture of Italy - where proud men would be free to stink and indiscriminately slap womens' butts on the streets, and everybody would like it and laugh over pizza dinners.
Re: (Score:3)
would have revolutionized America to being a mirror culture of Italy - where proud men would be free to stink and indiscriminately slap womens' butts on the streets, and everybody would like it and laugh over pizza dinners.
Ok, maybe I'm missing something basic, but wouldn't these proud men, who like slapping womens' butts on the streets, also get mad if another man slapped their wives' butt while she was walking down the street?
Re: (Score:2)
Ok, maybe I'm missing something basic, but wouldn't these proud men, who like slapping womens' butts on the streets, also get mad if another man slapped their wives' butt while she was walking down the street?
If we're talking about the Italian model, these "proud men" aren't married - they still live with their mommas, who clean their rooms, do their laundry, and cook their meals for them.
How did this shit get on the front page? (Score:5, Insightful)
So a guy submits an link to his own blog page featuring a long and dreary essay containing some half-baked ill-defined vague handwavey idea about some kind of "semantic" interface which seems to have no new basis beyond what google's autocomplete or win7's search functions already do, and it gets posted to the front page? If you're going to allow self-publicity like this, it should at least be for good articles rather than shit ones.
Re:How did this shit get on the front page? (Score:4, Funny)
Maybe after the fighting in the Stallman article, Slashdot wanted to post something so shitty, its readers would have no choice but to band together against it.
This isn't new. (Score:5, Interesting)
Go back and play Hugo's House of Horrors (or many similiar adventure games of the not-quite-post-text era) and you'll see an interface that looks a lot like what this guy is describing.
Re:This isn't new. (Score:4, Interesting)
Or any of the Lisp machine variants that blurred the line between CLI and GUI and editor; plus the lines between OS and application. I still haven't seen any user interface that comes close to what you had on a Symbolics machine. Ie, click on a word in your command line, get a drop down menu of command options, etc. There was definitely a contextual user interface going on there. Of course these systems were designed for programmers whereas most people make UIs for end users or administrators instead.
This isn't new...Genera. (Score:4, Informative)
Genera [wikipedia.org]
Re: (Score:2)
Yet, a knowledgeable user or an average (I'd hope) administrator would be able to not only leverage but strongly appreciate.
In some ways, I think this is actually what Microsoft attempted to do with PowerShell: some semantic functionality is possible, it's just awkward and kludged. (I believe you can interface GUI with the CLI through eg. a pipe to/from each other, for instance. Correct me if I'm wrong, I've only dabbled with it.)
Re: (Score:3)
Yet, a knowledgeable user or an average (I'd hope) administrator would be able to not only leverage but strongly appreciate.
From an admin's point of view, you do not want any interface that's not (a) absolutely consistent, or (b) tries to second-guess you. Those may be fine for users who need hand holding, but for an admin, it can be downright dangerous.
It reminds me of the joke where a soldier pulls the trigger, and up pops Clippy, saying "It looks like you attempt to shoot a human being. Would you like help with this?"
No, if you know what you're doing, you don't want any help or distractions. You want the machine to obey, a
Re: (Score:2)
AutoCAD has been using this since at least the the late 80's when I first started using it.
Pull down menus at the top, a sidebar menu that is somewhat contextual, and a command line at the bottom. All surrounding the drawing area in the middle.
Of course most of the people I see using AtoCAD these days never used it before it became a Windows based program and are always clicking through menus. While I keep my left hand on the keyboard to type commands, or their shortcuts.
Re: (Score:2)
Pull down menus at the top, a sidebar menu that is somewhat contextual, and a command line at the bottom. All surrounding the drawing area in the middle.
I've seen similar interfaces in a lot of other industry-specific hardware. I've seen lighting controllers (think robotic lights you see at concerts) that have interfaces like this (used more for setup/programming than in a live situation).
I know that I've used command line in some primitive CAD software (ages ago), since it was the only way to ensure (in that software) that lines were drawn at accurate lengths/angles/etc. This was a "CAD-lite" package that was somewhere between something like AutoCAD and
Worst article ever? (Score:5, Informative)
Games.
The first paragraph is riddled with unfounded assumptions and grammatical mistakes - as is, I assume, the remainder of the article. While I stopped reading after the second paragraph, I did spend a few seconds to scroll down to the bottom of the page to the only screenshot of what Semantic Line Interface might look like:
Example of a Semantic Line Interface [blogspot.com]
Visionary.
Re: (Score:2)
The first paragraph is riddled with unfounded assumptions and grammatical mistakes
The same thing threw me at first -- he's Russian writing ESL.
screenshot of what Semantic Line Interface might look like:
Totally agree with your assessment at first glance. Reading the article explains what he's getting at, though, and it makes some sense.
Mind you, I actually find a lot of what he says to be incorrect, and I suspect a lot of it is long-trodden ground (not my area of expertise), but the quality of presentation i
Re: (Score:2)
That being said, I don't think that it is unreasonable to request that the author have somebody proof read his article before submitting to Slashdot to be read by a large English-speaking audience. Or to include half-decent mockups/illustrations. Presentation is important when disseminating ideas.
I
I find it amazing... (Score:2)
That even though slashdot is the apotheosis of geek sitelization, that this one paragraph hasn't resulted in far dirtier comments about boys and girls enjoying a tactile experience. Is this place just chock full of Sheldon Coopers?
Side note: I don't care if you do or don't like the/any show/character/screen/entertainment media. I just don't care. Don't tell me; I don't care. I put this note in here knowing that some people will have an instant complaint -- guess what...don't care.
Mod up (Score:2)
A moment of person growth, live on Slashdot!
Re: (Score:2)
Combining the CLI with the GUI?
Haven't I been doing this with all the CAD programmes I've ever used? Six. I think I've used six. Maybe seven. One was complete shite. Six. I'm going with six.
Set Datum 0,0,0
Show Layer 12, 15, 35, 60
Zoom 200%
All faster than clicking. Most of the time a quick C&P from previous commands was all that was needed.
The "Zoom Window" command would prompt the user to click two points.
Is it worth read
Command line (Score:1, Interesting)
The command line is not coming back, especially with more applications moving to mobile devices where typing is just a hassle. The CLI will remain a nerd's tool. That's just reality.
Re: (Score:3)
The command line is not coming back, especially with more applications moving to mobile devices where typing is just a hassle.
But whenever we complain about some UI removing menus, desktop launchers and any other easy way of starting an application the fanboys tell us that's OK because we can just type the name of the application on a command line instead.
Re: (Score:2)
Meet the new boss, same as the old boss
Re: (Score:1)
Who is "we?" Who are the fanboys you're referring to? Do you have a specific example to clarify what you're talking about?
On the other hand (Score:4, Insightful),
Re: (Score:2),
I really like the UNIX-way, where almost everything is CLI-based, and for most of these commands, there is a GUI available as well. That GUI does usually not have all the options or has them in such a way that they still are inaccessible, but it does the job for anyone not familiar with those commands. And that's the way it should be. OSX and Ubuntu do this really well (which are the two systems I use on a regular basis) for OS-stuff.
But take Photoshop (the non-OS-stuff), if I take a selection or apply a co
Re: (Score:2, Insightful)
Reality check: it never went away.
And I'm not just talking about the fact that power users have continued to prefer it consistently, or even the way Mac power users gravitated towards CLI when OS X introduced it to their world. I'm talking about the stuff my grandparents use. Does that Google search box remind you of anything? Hint: it doesn't involve much clicking on buttons or menus! What about the total redesign of the start menu in Windows 7 to put the emphasis on
Re: (Score:2)
I was going to mention something similar, because even with the move to mobile devices the text has just become dictated. What is interesting with Siri is you do not HAVE to speak it. If it misunderstands the dictation, there is nothing stopping you from tapping the box and typing what you want it to do in natural language, it will react as if you had said it.
Re:Command line (Score:5, Interesting)
The overarching issue isn't really CLI vs GUI, but that the OS provides the user with very little semantic information, instead you simply get pretty pixel graphics. Case in point: Look at your screen right now, how much of the text you see can you select and copy as text? The answer will of course vary depending on what you do, but you can be pretty sure that it will be a good bit lower then 100% (i.e. window titles, menus, etc. can't be selected). There is really no good reason for that being that way, other then that being the way it has always been. The text is available to the OS and the applications, but there are no tools to get it out or at least not easily. Now that's of course just a very basic case, the issues goes of course much deeper when it comes to active parts of the GUI. When your filemanager is displaying a list, can you copy it into a spreadsheet? Can you move the play button of your MP3 player over to your iPhone? etc.).
Re: (Score:2)).
Some simple examples that do stuff like this, although this is clearly not as advanced as what you suggest:
* OSX Finder: drag file into Terminal, and the filename including the path is copied to the terminal
* Ubuntu Nautilus: press CTRL-L and the path turns into an textfield with the complete path, which you can copy and edit
Re: (Score:2)
Those are not only not as advanced. They are not general actions (you can't really drag that file into anything, altough that is getting better with time), and are not scriptable.
Re: (Score:2)
Re: (Score:2)
The command line is not coming back
Nor is it going away. It is what it is; not useful for most visual-oriented tasks, and filling the space between writing your own code and using a stock gui for data-oriented tasks.
When the stock gui won't do what you need to do, the CLI can often get the job done without writing your own full toolkit.
The CLI will remain a nerd's tool.
You damn skippy it will! Users just give up when the GUI won't do it. Pretty much leaves them either relying on a nerd to help, or up shit c
Re: (Score:1)
Using "nerd" in the pejorative sense is archaic.
The fact that 'nerd' isn't an insult doesn't make people whose talents lean in that direction (or their lives) superior, it just means they're no longer demonized for it.
Users just give up when the GUI won't do it. Pretty much leaves them either relying on a nerd to help, or up shit creek. Must be a horrible way to live -- if you can even call that living.
... Seems being an information tool-maker is up there with having opposable thumbs on the "competitive advantage" scale, right?
Nope, try again... People with practically any ability or profession can look down upon about others that don't share that trait, regardless of what it happens to be. Mature people grasp that individuals find different things natural or pleasurable, and that their strengths and interests are balanced out by weaknesses & boredom with th
Re: (Score:2)
People with practically any ability or profession can look down upon about others that don't share that trait
... Someone that finds a task a dull hassle is preserving/improving their quality of life by asking someone skilled in that field to do so for them, as it means they can focus their energy on something more suited to them.
In the early 90's I was cutting code that not many people wanted while I worked at a coffee shop to pay the bills. My brother was trading commodities with the world at his feet. So
Re: (Score:2)
The command line is not coming back...
I didn't realize it was gone...or optionally: Go tell all the admins!
Re: (Score:2)
If you use google or post on slashdot you are already using a CLI you just don't know it because of the wrapper.
This sounds a familiar (Score:5, Informative)
Think all the autocomplete addons for unix shells.
Or even just a bit of work on top of powershell, I don't know if something Something like posh ( [http] ) implements autocompletes like that, but it wouldn't be hard to do in powershell since a well written cmdlet will expose strongly typed inputs which would allow you to use a fancy widget for input without any issues.
Re: (Score:2)
Sorry about the broken link, here is a clickable one [codeplex.com]
Re: (Score:2)
Sorry about the broken link, here is a clickable one [codeplex.com]
Let me guess, a copy-paste from Firefox 9, which hides the [http] part but sticks them in pastes? I hate that too.
I hope windows 8 has vista / 7 start menu search (Score:2)
As that is like this and to take it way is a big loss.
So kinda like... (Score:2)
Not again... (Score:4, Informative)
Googlize Features and Menus (Score:2)
I've proposed something similar for years. Features would have a title and synonyms* and be tracked in a kind of database. One then searches for features similar to using a Google search and the features are then listed in the search results along with parameters, and any links to prerequisites, if needed.
There still may be menus and icons that use (reference) these very same features, but the Google-like approach works better for obscure settings.
* Synonyms may be user-configurable in case I call something
Semantic organization of content (Score:1)
Sorry that it's behind a paywall, but here is my (peer-reviewed) take on it all [acm.org]
From the abstract:
This research returns to first principals, and considers the underlying Dexter Model of Hypertext, and how that may be placed within a broader model of docu
I like GnomeDo (Score:2)
I dislike GnomeShell.
Bah dum dum (Score:2)
And Jason Foxx likes pears.
A potential Interface? (Score:1)
Real problem. Bad solution. (Score:5, Insightful)
The article cited offers a crap solution, but there is a problem. It's the "What menu is that in?" problem. This is a real issue with some programs, especially the ones with modal and/or context sensitive toolbars and menus. It's really annoying when you read the manual, it tells you to use the "join" menu item, you can't find the "join" menu item, and the manual doesn't tell you under what circumstances the "join" menu item will be available.
The original Macintosh Human Interface Guidelines insisted that menu items should be greyed out when inapplicable, but they shouldn't disappear. Many GUIs today either make them disappear, or leave them looking normal but inoperative. The right solution today is probably to grey them out, but bring up a tooltip that explains what's needed to make that function usable.
(My current hatred in user interface design is invisible buttons, ones that only appear when moused over. Facebook is notorious for this. Many users don't know that if you hover over an ad, you get the option to make that advertiser go away.)
Re: (Score:2)
That's not enough. Consider Word or Openoffice; an application that has so many functions, both in menus, in dialogs after menus, in buttonbars, etc. I still fight with it, and I still damn Openoffice to hell for being such a loyal follower of the Word way-of-thinking.
Re: (Score:2)
You know what I like (and also the paragon of office-email programs, Outlook, doesn't provide this) ? Auto-completion. I think auto-completion, as used in shells, but now also in emailers like Evolution (where it completes addresses from your address-book), allows you to forego a tiresome process of inspecting dialogs and clicking and typing at the same time. It should be bloody everywhere. Infinite undo is something else that should be bloody everywhere; your desktop environment should provide it. The same
Re: (Score:2)
1. Outlook does autocomplete of addresses - has done for years.
2. Undo cannot be provided by the OS because the concept of application state (and what constitutes a previous state, and how to revert to it) is private and specific to each application.
3. Not sure what your comment is re: fonts, but certainly in Windows every application has access to the same set of system wide fonts. Word doesn't have it's own fonts (although it does have own styles, which are different and by necessity Word specific).
Re: (Score:2)
Eclipse has an excellent solution for this.
Ctrl + 3 pops up a search window that lets you type your way in to every available command in the system. Including what is hidden in the menues and context menues. So instead of trying to remember if the "Override/implement method" is hidden in the Source or Refactor menu or in the context menues somewhere, I just press ctrl + 3 and type 'override'.
I miss that in MS Office and many other applications.
been done - cuiterm (Score:2)
I think cuiterm does that. [linux.pte.hu] [linux.pte.hu]
Sadly, when it came out it crashed every now and then and these days it won't even launch.
It's a great concept though
Three User Interfaces... Naturally! (Score:2) [abstractionphysics.net]:
Humanized Enso (Score:2)
It sounds like the article is proposing a solution very similar to Humanized's Enso Launcher. [humanized.com]
I tried Enso for a bit. It seems like a nice concept, but one thing that annoyed me to no end was having to type "open" over and over. I want to open something by default. | http://developers.slashdot.org/story/12/01/02/2358240/the-semantic-line-interface?sdsrc=prevbtmprev | CC-MAIN-2015-32 | refinedweb | 6,109 | 70.23 |
Bobby Smallman wrote:Something about posting eight questions in a single post on topics which are relatively well covered makes me less inclined to give large amounts of time responding. But I will however direct you to another post which 1/8th of your post was inquiring about.
Deepak Lal wrote:2> Can we subclass singleton class ...Please help me ?
David Newton wrote:I'm still not satisfied with the level of effort shown, and this still smacks *loudly* of homework and/or interview questions.
Regarding TreeSet: have you read the documentation? If not, go do so now. If you have, what does it say about ordering and the iterator?
//I'm stuck here.can you help me out now
SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
// i dont know how to proceed at this step.Please help me now.
Deepak Lal wrote: 1> David i have read the documentation of TreeSet and it says you need to implement Comparator interface and thats what i have done in the code..Could you please please render help.
Deepak Lal wrote:Regarding subclassing a singleton class,it gets subclassed.but i want to know why it is possible because a singleton by definition itself gives a single instance of class which has a private constructor,so whats the use of
subclassing a singleton class.Please clarify me on this point ?
Deepak Lal wrote:Singleton class and subclass -->Can you check whats wrong.
class SingletonClass{
private SingletonClass(){}
private static SingletonClass singletonclass;
public static synchronized SingletonClass getInstance(){
if(singletonclass == null){
singletonclass = new SingletonClass();
}
return singletonclass;
}
}
class XYZ extends SingletonClass{
private XYZ(){} //im getting an error at this line..please help me
} //subclassing a singleton class
public class SingletonClassTest{
public static void main(String args[]){
@SuppressWarnings("unused")
SingletonClass singleton = SingletonClass.getInstance();
System.out.println("Only one instance created ");
}
}
Deepak Lal wrote:Can i subclass a singleton class ?
Deepak Lal wrote:Since we have private Constructors in a subclass which extends a Singleton class,we cannot subclass a Singleton class.
Rob Prime wrote:Although that allows you to subclass a class it will no longer be a singleton - the class can be instantiated from anywhere. Singletons that are designed to be subclassed usually have protected constructors.
Deepak Lal wrote:1>Suppose i have 5 elements added to a ArrayList and Vector.? suppose i now add 6th element to ArrayList and Vector.How will it be internally added in both the cases.Please explain
2>In which scenario would i use a List and a Map except for the normal differences being that list is being used for sequential addition of elements and Map is for (Key,Value) Pair ?
Deepak Lal wrote:1> i asked for ArrayList which implies ArrayList.java and i asked for Vector ,does the Vector implementation refer to LinkedList.java as you have pointed out.
Rob Prime wrote: . . . We do require everyone to ShowSomeEffort. | http://www.coderanch.com/t/511220/java/java/Clarifications-Suggestions-Java | CC-MAIN-2015-18 | refinedweb | 480 | 57.87 |
User Name:
Published: 28 Dec 2007
By: Kent Sharkey
An introduction to SubSonic, a data-layer builder.
One of the signs of an easily maintained application is a division of labor between the classes, usually resulting in a user interface
layer, a business layer and a data access layer. While this technique helps to better organize the application, many developers shy away from
creating them. Creating a reliable and fast data access layer requires some planning, and once you've created one, they all start to look
similar. SubSonic helps you by automatically creating a data access layer based on your database.
SubSonic is a data-layer builder. More than that, it's an auto-magic object-relational mapping (ORM) tool that "Helps a Web site
build itself."
Beyond the hype, though, just what does SubSonic do, and how can it help you build your applications faster? SubSonic reads the structure
of your database, and builds classes to provide you with a fast and flexible data access layer. It requires minimal configuration to set up,
provides you with a number of different methods for retrieving and saving data, and includes methods to customize the classes to fit with
your own development style. SubSonic was inspired by the ActiveRecord classes in Ruby on Rails. However, SubSonic is pure .NET and fits with
the .NET methods of development.
Compared with other ORMs, SubSonic requires remarkably little configuration. At a minimum, you will need to add the following to your
web.config (or app.config) file:
That's it - no need to identify the tables you want, or perform any mapping between the tables and objects. In practice, the
configuration looks like the following:
Once you have configured your application, you can generate your data access layer using the SubSonic command-line tool.
Alternately, if you are using ASP.NET, you can use the build provider to dynamically generate the data layer.
You can use the command-line tool from (surprisingly enough) the command-line, but it is easier to create a new External Tool (see Figure
1) to create the classes. Figure 2 shows the generated classes.
Generating the classes gives you a
set of physical files you can look at, admire, and learn from, but you shouldn't edit these files. Any changes you make will be overridden if
you regenerate the data layer. Instead, as all the classes are defined as partial, you can override them in your own files (see "Extending
the generated classes" below). To avoid the temptation of editing the files, you can use the build provider to automatically generate the
classes.
In order to use the build provider, you must add a few more entries into the web.config file:
The above setting assigns the build provider to any files ending in .abp in the App_Code subdirectory. This is
similar to the way that adding an XML schema to the App_Code directory creates a typed DataSet. You only need a single .abp file
for the build provider, and it does not need any text in it, it only needs to be present. When the application is built, the presence of the
file triggers the generation of the classes, just as with the command-line tool (see Figure 3). The only difference is that now you don't see
them in your project.
.abp
Once you have created your DAL with SubSonic, either manually or using the build provider, you are ready to begin to query your database.
At this writing, there are providers for a number of databases:
SubSonic generates three classes for each table in your database:
The
strongly-typed classes enable you to query the database using a variety of methods, depending on the needs of the situation. Below are just a
few possible types of queries you could create using the generated classes:
The retrieval methods provided by the generated classes give you a full range of options for building the queries, from where
clauses, order by clauses, in clauses and even Boolean operations. You can retrieve the strongly-typed objects or collections, a DataSet, or
an IDataReader, depending on your needs.
In addition to the strongly-typed classes, SubSonic also includes a generic query tool, creatively called Query. You can use this to
perform ad hoc queries of your database.
The above example uses the Product class to identify the table to query. You could have also done this by creating the Query
using the following code:
Each of the methods in the query returns a Query object. This enables you to string them together as necessary to retrieve just
the data you need.
Performance of the SubSonic generated objects is good - generally faster than using typed DataSets. Therefore, you are not sacrificing
performance to make use of SubSonic.
In addition to the data access functionality, SubSonic also includes a few controls that make working with data easier.
The most dramatic of the controls that ships with SubSonic is the scaffold control. Like a scaffold on a construction site, or the
scaffolding in Ruby on Rails, it is intended to provide you with an easy way to create something, with the intention that eventually the
scaffolding will be removed. In the case of SubSonic, the scaffolding makes it easy to edit a table.
The scaffold control will then render itself as a table (see Figure 5) with the ability to edit existing items or add new
items.
Selecting an item to edit
renders a form with controls appropriate for the various controls. As you can see from the Figure 6, the Posted On field creates a Calendar
control, and the Body field gets a multi-line Textbox.
In addition to the scaffold control,
SubSonic also includes the QuickTable control (see Figure 7), which displays data in a grid format, an updated Calendar control that also
allows for entering in a time (see Figure 8), and a ManyToMany control (see Figure 9) that helps you edit related columns.
Each of the controls looks fine
out of the box, but also includes a number of properties for setting the CSS styles for the elements of the control.
It would be easy to overlook the Sugar namespace when using SubSonic, however if you do, you'd miss some useful functionality.
SubSonic.Sugar doesn't include a lot of glamorous functions, but instead it provides the "miscellaneous" functions part of the API, and
includes functions for:
No application can provide the solution for all needs, and so the default classes built by SubSonic may not be enough. You may want to add
methods to the generated classes, or you may want to change the way the classes themselves are generated. SubSonic provides for both needs.
All of the classes generated by SubSonic are partial classes. This means that you can add functionality to them by creating another class
with the same name, just as you do when creating Windows Forms applications. For example, the following code would add a new method to the
Category class to calculate the number of posts in that category.
If you don't like the way the generated classes are constructed, you can also override the templates used. The templates used
are similar to templated controls in ASP.NET, where you provide a set of markup that is repeated for each row. In the case of the SubSonic
templates, they are repeated for each table you generate. You can create your own set of templates, and have SubSonic use them by including
the TemplateDirectory attribute. For an example of doing this, see Rob Conery's post on using his MVC templates (see the References section
below).
You know you have a database you need to connect to an application. You know that putting the SQL requests in the page is a bad
architectural decision. You know you should write a data layer to manage the CRUD for your application. You really want to get it all done
now so that you can go home to loved ones. SubSonic helps you solve all of these in a single stroke, without sacrificing performance,
maintainability or flexibility. Just download it and give it a try. Your applications will thank you.
This author has published 2 articles on DotNetSlackers. View other articles or the complete profile here.
Reply
|
Permanent
link
[MVP since 2005] [MCAD]
Webmaster of DotNetSlackers
Question or Suggestion?
Feel free to ask my any .NET question
Our Posting FAQ
Long Live .NET
Kazi Manzur Rashid (Amit)
_________________________
Simone Busoli
Feel free to ask me any .NET question
TTFN - Kent
Thanks & Regards
The trouble with the world is that the stupid are sure and the intelligent are full of doubt.
Shahid Hussain Shaikh
Please login to rate or to leave a comment.
Link to us
All material is copyrighted by its respective authors. Site design and layout
is copyrighted by DotNetSlackers.
Advertising Software by Ban Man Pro | http://dotnetslackers.com/articles/aspnet/IntroductionToSubSonic.aspx | CC-MAIN-2014-42 | refinedweb | 1,483 | 62.78 |
Working with Files in C#
In this article, you will learn how to manipulate directories and files in your system. Further, we will discuss how to read from and write to a file by using the powerful .NET classes.
The Namespace
System.IO provides all the necessary classes, methods, and properties for manipulating directories and files. Table 1 elaborates the main classes under this namespace.
Table 1—Classes under System.IO
Working with DirectoryInfo and FileInfo classes
The base class of DirectoryInfo and FileInfo is FileSystemInfo. This is an abstract class, meaning you can't instantiate this class. But you can use the properties defined by this class. Table 2 elaborates its properties and methods.
Table 2—Members of FileSystemInfo class
The DirectoryInfo class provides methods for creating, moving, and deleting directories. To make use of the above properties, create an object of the DirectoryInfo class as shown in Listing 1:
Listing 1
DirectoryInfo dir1 = new DirectoryInfo(@"F:\WINNT");
You then can access the properties by using the object dir1, as shown in the code fragment in Listing 2:
Listing 2
Console.WriteLine("Full Name is : {0}", dir1.FullName); Console.WriteLine("Attributes are : {0}", dir1.Attributes.ToString());
You can also apply the values of FileAttributes enumeration. Its values are shown in Table 3.
Table 3—FileAttributes Enumeration Values
Working with Files under a Directory
Suppose that you want to list all BMP files under the f:\Pictures directory. You can write a code as shown in the code snippet given in Listing 3:
Listing 3
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT"); FileInfo[] bmpfiles = dir.GetFiles("*.bmp); Console.WriteLine("Total number of bmp files", bmpfiles.Length); Foreach( FileInfo f in bmpfiles) { Console.WriteLine("Name is : {0}", f.Name); Console.WriteLine("Length of the file is : {0}", f.Length); Console.WriteLine("Creation time is : {0}", f.CreationTime); Console.WriteLine("Attributes of the file are : {0}", f.Attributes.ToString()); }
Creating Subdirectories
You can easily create a subdirectory. Listing fragment 4 describes how to create a subdirectory called MySub under the Sub directory.
Listing 4
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT"); try { dir.CreateSubdirectory("Sub"); dir.CreateSubdirectory(@"Sub\MySub"); } catch(IOException e) { Console.WriteLine(e.Message); }
Creating Files by Using the FileInfo Class
With the FileInfo class, you can create new files, access information about the files, delete, and move files. This class also provides methods for opening, reading from, and writing to a file. Listing 5 shows how to create a text file and access its information like its creation time, full name, and so forth.
Listing 5
FileInfo fi = new FileInfo(@"F:\Myprogram.txt"); FileStream fstr = fi.Create(); Console.WriteLine("Creation Time: {0}",f.CreationTime); Console.WriteLine("Full Name: {0}",f.FullName); Console.WriteLine("FileAttributes: {0}",f.Attributes.ToString()); //Way to delete Myprogram.txt file. Console.WriteLine("Press any key to delete the file"); Console.Read(); fstr.Close(); fi.Delete();
Understanding the Open() Method
The FileInfo class defines a method named Open() with which you can create files by applying the values of the FileMode and FileAccess enumerations. The code snippet in Listing 6 describes its usage:
Listing 6
FileInfo f = new FileInfo("c:\myfile.txt"); FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);
You then can read from and write to a file by using the object 's'. In the overloaded Open() method, permission is given only for reading from a file. If you want to write to a file, you have to apply the ReadWrite value of FileAccess enumeration. Tables 4 and 5 describe the values of the FileMode and FileAccess enumerations.
Table 4—FileMode Enumeration values
Table 5—FileAccess Enumeration values
Writing to a Text File by Using the StreamWriter Class
You can easily write texts or other information to a file by using the CreateText() method of the FileInfo class. However, you have to obtain a valid StreamWriter. It's this StreamWriter reference that provides the required functionalities for writing to a file. To illustrate, Listing 7 writes a series of texts to the Mytext.txt file.
Listing 7
FileInfo f = new FileInfo("Mytext.txt") StreamWriter w = f.CreateText(); w.WriteLine("This is from"); w.WriteLine("Chapter 6"); w.WriteLine("Of C# Module"); w.Write(w.NewLine); w.WriteLine("Thanks for your time"); w.Close();
Reading from a Text File
You can read from a Text file by using the StreamReader class. For this, you have to specify the file name using the static OpenText() method of the File class. Listing 8 reads the contents that we have written in Listing 7:
Listing 8
Console.WriteLine("Reading the contents from the file"); StreamReader s = File.OpenText("Mytext.txt"); string read = null; while ((read = s.ReadLine()) != null) { Console.WriteLine(read); } s.Close();<< | https://www.developer.com/net/csharp/article.php/1496821/Working-with-Files-in-C.htm | CC-MAIN-2019-09 | refinedweb | 783 | 51.34 |
WebMIDIKit: Simplest Swift MIDI library
###Want to learn audio synthesis, sound design and how to make cool sounds in an afternoon? Check out Syntorial!
About
What's MIDI
MIDI is a standard governing music software and music device interconnectivity. It lets you make music by sending data between applications and devices.
What's WebMIDI
WebMIDI is a browser API standard that brings the MIDI technology to the web. WebMIDI is minimal, it only describes MIDI port selection, receiving data from input ports and sending data to output ports. WebMIDI is currently implemented in Chrome & Opera. Note that WebMIDI is relatively low level as messages are still represented as sequences of UInt8s (bytes/octets).
What's WebMIDIKit
WebMIDIKit is an implementation of the WebMIDI API for macOS/iOS. On these OS, the native framework for working with MIDI is CoreMIDI.
CoreMIDI is old and the API is entirely in C (💩). Using it involves a lot of void pointer casting (💩^9.329), and other unspeakable things. Furthermore, some of the APIs didn't quite survive the transition to Swift and are essentially unusable in Swift (
MIDIPacketList APIs, I'm looking at you).
CoreMIDI is also extremely verbose and error prone. Selecting an input port and receiving data from it is ~80 lines of convoluted Swift code. WebMIDIKit let's you do the same thing in 1.
WebMIDIKit is a part of the AudioKit project and will eventually replace AudioKit's MIDI implementation.
Also note that WebMIDIKit adds some APIs which aren't a part of the WebMIDI standard. These are marked as non-standard in the code base.
Usage
Installation
Use Swift Package Manager.
import PackageDescription let package = Package( name: "WebMIDIKitDemo", dependencies: [ .Package(url: "", majorVersion: 1) ] )
Selecting an input port and receiving MIDI messages from it
import WebMIDIKit /// represents the MIDI session let midi: MIDIAccess = MIDIAccess() /// prints all MIDI inputs available to the console and asks the user which port they want to select let inputPort: MIDIInput? = midi.inputs.prompt() /// Receiving MIDI events /// set the input port's onMIDIMessage callback which gets called when the port receives MIDI packets inputPort?.onMIDIMessage = { (packet: MIDIPacket) in print("received \(packet)") }
Selecting an output port and sending MIDI packets to it
/// select an output port let outputPort: MIDIOutput? = midi.outputs.prompt() /// send messages to it outputPort.map { /// send a note on message /// the bytes are in the normal MIDI message format () /// i.e. you have to send two events, a note on event and a note off event to play a single note /// the format is as follows: /// byte0 = message type (0x90 = note on, 0x80 = note off) /// byte1 = the note played (0x60 = C8, see) /// byte2 = velocity (how loud the note should be 127 (=0x7f) is max, 0 is min) let noteOn: [UInt8] = [0x90, 0x60, 0x7f] let noteOff: [UInt8] = [0x80, 0x60, 0] /// send the note on event $0.send(noteOn) /// send a note off message 1000 ms (1 second) later $0.send(noteOff, offset: 1000) /// in WebMIDIKit, you can also chain these $0.send(noteOn) .send(noteOff, offset: 1000) }
If the output port you want to select has a corresponding input port you can also do
let outputPort: MIDIOutput? = midi.output(for: inputPort)
Similarly, you can find an input port for the output port.
let inputPort2: MIDIInput? = midi.input(for: outputPort)
Looping over ports
Port maps are dictionary like collections of
MIDIInputs or
MIDIOutputs that are indexed with the port's id. As a result, you cannot index into them like you would into an array (the reason for this being that the endpoints can be added and removed so you cannot reference them by their index).
for (id, port) in midi.inputs { print(id, port) }
Installation
Use Swift Package Manager. Add the following
.Package entry into your dependencies.
import PackageDescription let packet = Package( name: "...", target: [], dependencies: [ // ... .Package(url:"", version: 1) ] )
If you are having any build issues, look at the sample project sample project.
Documentation
MIDIAccess
Represents the MIDI session. See spec.
class MIDIAccess { /// collections of MIDIInputs and MIDIOutputs currently connected to the computer var inputs: MIDIInputMap { get } var outputs: MIDIOutputMap { get } /// will be called if a port changes either connection state or port state var onStateChange: ((MIDIPort) -> ())? = nil { get set } init() /// given an output, tries to find the corresponding input port func input(for port: MIDIOutput) -> MIDIInput? /// given an input, tries to find the corresponding output port /// if you send data to the output port returned, the corresponding input port /// will receive it (assuming the `onMIDIMessage` is set) func output(for port: MIDIInput) -> MIDIOutput? }
MIDIPort
See spec. Represents the base class of
MIDIInput and
MIDIOutput.
Note that you don't construct MIDIPorts nor it's subclasses yourself, you only get them from the
MIDIAccess object. Also note that you only ever deal with subclasses or
MIDIPort (
MIDIInput or
MIDIOutput) never
MIDIPort itself.
class MIDIPort { var id: Int { get } var manufacturer: String { get } var name: String { get } /// .input (for MIDIInput) or .output (for MIDIOutput) var type: MIDIPortType { get } var version: Int { get } /// .connected | .disconnected, /// indicates if the port's endpoint is connected or not var state: MIDIPortDeviceState { get } /// .open | .closed var connection: MIDIPortConnectionState { get } /// open the port, is called implicitly when MIDIInput's onMIDIMessage is set or MIDIOutputs' send is called func open() /// closes the port func close() }
MIDIInput
Allows for receiving data send to the port.
class MIDIInput: MIDIPort { /// set this and it will get called when the port receives messages. var onMIDIMessage: ((MIDIPacket) -> ())? = nil { get set } }
MIDIOutput
class MIDIOutput: MIDIPort { /// send data to port, note that unlike the WebMIDI API, /// the last parameter specifies offset from now, when the event should be scheduled (as opposed to absolute timestamp) /// the unit remains milliseconds though. /// note that right now, WebMIDIKit doesn't support sending multiple packets in the same call, to send multiple packets, you need on call per packet func send<S: Sequence>(_ data: S, offset: Timestamp = 0) -> MIDIOutput where S.Iterator.Element == UInt8 // clear all scheduled but yet undelivered midi events func clear() }
Github
Help us keep the lights on
Dependencies
Used By
Total: 2 | https://swiftpack.co/package/adamnemecek/WebMIDIKit | CC-MAIN-2019-30 | refinedweb | 1,002 | 55.03 |
There is a new feature in EF 5.0 that change the way to create the Many-to-Many Relationship. It is really convenient way to create a relationship with Entities. Before dive into that let’s check that, how we create a many-to-many relationship in previous versions.
Before EF Core 5.0
Let’s take our common scenario with
Tag example. A blog post can have multiple tags and one tag can be tagged with many posts.
This is our
Post entity.
public class Post { public int Id { get; set; } public string Name { get; set; } }
This is out
Tag entity.
public class Tag { public int Id { get; set; } public string Text { get; set; } }
So these 2 entities have a many-to-many relationship. Let’s create the joining entity that contains all the mapping details with both entities.
public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public int TagId { get; set; } public Tag Tag { get; set; } }
This
PostIdand
TagIdworks as composite primary key
Now we need to add this mapping to our
Tag entities.
// inside the Tag.cs file public ICollection<PostTag> PostTags { get; set; } // inside the Post.cs file public ICollection<PostTag> PostTags { get; set; }
Now we are at the last step. We use the
Fluent APIto define the primary keys of the
PostTag .
// inside the context class // define composite primary key protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>().HasKey(pt => new { pt.PostId, pt.TagId }); }
That’s it. Once we enable the migration this will create a table called
PostTag and it has a composite primary key and has a relation with
Tag tables.
If you defined the keys in
PostTag class differently you need to mention it in
OnModelCreating by using
Fluent API.
// in PostTag class public int PId { get; set; } public Post Post { get; set; } // inside the OnModelCreating method in context class modelBuilder.Entity<PostTag>() .HasOne<Post>(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId);
Hola, that is lots of code. Now let’s see how what are an improvement with EF Core 5.0
EF Core 5.0
Create the
Post entity with navigation property.
public class Post { public int Id { get; set; } public string Name { get; set; } public ICollection<PostTag> PostTags { get; set; } }
Create the
Tag entity with navigation property.
public class Tag { public int Id { get; set; } public string Text { get; set; } public ICollection<PostTag> PostTags { get; set; } }
That’s it. Now EF Core will identify this as a many-to-many relationship and it will create a table
PostTag . The
PostTag table data can be query and update without explicitly referring to that table. If we need more modification we can use
Fluent API aswell.
I will wrap up this post from here. If you have anything to ask regarding this please leave a comment here. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you.
That’s for today friends. See you soon. Thank you.
References:
What's New in EF Core 5.0
Discussion (2)
Why this approach is actually better than creating entity for the joining table?
I think this feature is enabled a less code approach. Because even in previously we can do this using code first approach , but had to write more code. | https://dev.to/rasikag/ef-core-5-0-many-to-many-relationship-48kl | CC-MAIN-2022-21 | refinedweb | 563 | 67.35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.