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 |
|---|---|---|---|---|---|
#include <avr/io.h>#include <util/delay.h>#define LCD_ON 0x0C#define LCD_OFF 0x08#define LCD_SET_PAGE 0x80 // X-address #define LCD_SET_ADD 0x80 // y-address #define LCD_RAM_ADDRESS_MODE 0x02#define LCD_FUNCTION_SET_EXT 0x36#define LCD_FUNCTION_SET_BASIC 0x30#define LCD_CURSOR_CONTROL_SET 0x18#define LCD_DISP_CLEAR 0x01#define LCD_ENTRY_MODE_SET 0x06 // Display cursor shift left to right, page shift scroll down#define DI 14 // same as RS, PORT C, bit 0#define RW 15 // PORT c, bit 1#define EN 16 // PORT c, bit2// RESET ... straight to highvoid setup() { Serial.begin(9600); DDRD = DDRD | B11110000; // pins d7-d4 to output DDRB = DDRB | B1111; // pins d8 to d11 to output DDRC = DDRC | B111; // pins A0 to A2 to output digitalWrite(DI, LOW); initlcd();}void initlcd(void) { delay(50); WriteCommand(LCD_FUNCTION_SET_BASIC); _delay_us(100); WriteCommand(LCD_FUNCTION_SET_EXT); _delay_us(100); WriteCommand(LCD_ON); _delay_us(100); WriteCommand(LCD_DISP_CLEAR); delay(50); WriteCommand(LCD_ENTRY_MODE_SET);}void WriteCommand(byte cmd){ PORTC = B100; // EN | RW | DI _delay_us(7); lcdDataOut(cmd); _delay_us(10); PORTC = B000; // EN | RW | DI _delay_us(30);}void WriteData(byte data) { PORTC = B101; // EN | RW | DI _delay_us(3); lcdDataOut(data); _delay_us(5); PORTC = B001; // EN | RW | DI _delay_us(25);}void lcdDataOut(byte data) { byte dataD = data & B11110000; //bits 7 to 4 for pins 4-7 byte dataB = data & B1111; //bits 3 to 0 for pins 8-11 PORTB &= B11110000; PORTB |= dataB; // PORTD &= B00001111; PORTD |= dataD; //lower nibble of 8 bits}void loop() { for (int i = 0; i < 32; i++) { WriteCommand(LCD_SET_PAGE | i); WriteCommand(LCD_SET_ADD); for (int j =0; j < 16 ; j++) { WriteData(0xFF); WriteData(0xFF); } } for (int i = 0; i < 32; i++) { WriteCommand(LCD_SET_PAGE | i); WriteCommand(LCD_SET_ADD); for (int j =0; j < 16 ; j++) { WriteData(0x00); WriteData(0x00); } }}
Good idea. The display size should be mentioned. Maybe the FPS should be scaled to a virtual 64x64 display:If mFPS is the measured FPS rate and w and h are the display dimensions, then a comparable, size independent iFPS might beiFPS = mFPS * 64 * 64 / (w * h)Oliver
glcd also uses delays with more accurate timing to match glcd spec timinglike Tas and Tdsw rather than using longer delays using <util/delay.h><util/delay.h> has many issues in its delay cycle calculations....If the delays in WriteData() and WriteCommand() werecut down closer to the spec, the fame rate would go up.
Has anybody suffered this same fate ( need faster screen, to keep up with arduino ) or is it due to contrast. I have a POT connected to 5v and GND with the wiper going to backlight anode. What is the proper way to do contrast on these displays as this just dims the backlight. Pixels to backlight contrast is still equal.The only Identifiying marks my screen has is 'HJ12864ZW' and the datasheet is entirely in chinese, So I have had to use the generic ST7920 datasheet.
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=87474.msg666873 | CC-MAIN-2015-48 | refinedweb | 493 | 51.21 |
Combined, these new features make template creation much easier through programmatic advances and new features in the user interface (UI). Word 2007 isolates custom XML data from the document, providing true separation of data and view. Content controls provide an easy way to create blocks of content, such as drop-down menus, that are more secure from accidental modification by end users. After you add content controls, you can use XML mapping to map data from custom XML data to the document. This article uses a real-world scenario to demonstrate how to use these features. Following the scenario, you can read details about content controls and XML mapping to help you get started creating your own Word 2007 templates.
In Word 2003, to use tables, you must surround each cell in the two tables with an XML element. If you have done this before, then you are familiar with the pink tags that represent each element's begin and end tags. You can update the data in each XML element as necessary. This is a valid approach, but it leaves the data vulnerable to accidental modification. An end user who is not knowledgeable about XML might accidentally delete one of the pink beginning or end tags of an XML element. The solution to lock down the tables may sound obvious, but it is not a trivial task in Word 2003. To address this, many template designers create a one-page section for the tables and completely lock it down, preventing end users from making any modifications whatsoever.
Word 2007 offers a new feature called content controls that make a solution to the scenario much more robust and elegant. There are several different types of content controls, including drop–down menus, combo boxes, rich text, plain text, calendar, and picture, all of which let a template designer create form-like editing in a document. When a content control is inserted in a document, it is identified by a border and a title in the UI, neither of which prints. This results in a highly visible piece of content that is easy to work with, but, unlike the older controls in Word, does not contain unnecessary pieces that print on the page.
For this scenario, the data in each cell is contained in a content control for plain text. When a control is inserted
You can embed content controls within one another. Nesting controls helps make a template easier to work with. You can also create a custom document building block out of a group of nested content controls.
Document building blocks are predefined pieces of content, such as a cover page, a header, a footer, or a custom-built clause in a contract. Building blocks facilitate the quick creation of professional-looking Word documents. You can also create custom building blocks. For example, in a table, you can insert content controls into each cell and group the entire table into its own, larger document building block, and then you can insert the custom document building block elsewhere in the document.
Using XML Mapping
The new Office Open.
XML mapping is a feature of Word 2007 that enables you to create a link between a document and an XML file. This creates true data/view separation between the document formatting and the custom XML data.
XML mapping enables you to map an element in a custom XML part that is attached to the document. For our stock options template scenario, you can map most of the cells in the tables to custom XML. For example, look at the content control in the "Last Price" cell in the table. To map the "Last Price" content control to data in an element in a custom XML part, you do the following: using events. In this scenario, the document Open event triggers an add-in that retrieves the latest stock price for the company in question. This price is inserted into the element in the custom XML data to which the "last price" content control is mapped. The add-in can also perform calculations to determine figures, such as the 52–week high, the 52–week low, the moving averages, and others. All this happens behind the scenes when the document opens. The template user never does anything and always sees current data.
Modifying Custom XML Data
Because creating rich templates likely involves the use of custom XML data, it is worth briefly discussing how custom XML is stored in a document and how to work with this custom XML. Word 2003 technology and WordprocessingML introduced the capability of including custom XML data in a Word document. This created a multitude of possibilities for template developers by allowing you to associate pieces of content in the document with custom XML, so that if the XML changed, so did the content. This was a huge success. Word 2007 introduces several new enhancements to this functionality.
Custom XML in Word 2003 is immersed within the XML that describes the entire document. When the end user saves a document as XML in Word 2003, the result is an XML file conforming to the WordprocessingML schema that contains every bit of information necessary to describe the document. When you introduce custom XML, Word 2003 embeds it within the same WordprocessingML document. This means that programmatically manipulating the custom XML data poses some risk because any accidental invalidation of the custom XML can corrupt the entire document.
Word 2007 now uses the new Microsoft Office Word XML Format. The Word XML Format separates key pieces of a document from the body. Content such as headers, footers, endnotes, images, and lists is contained within separate XML files within the new file format. The new file format is a bundle of XML files contained inside a ZIP container that are mapped together with relationship files. If you attach custom XML to a Word 2007 document, Word 2007 stores it in its own separate XML file within the ZIP container. This makes it easier to identify and manipulate custom XML programmatically by changing, deleting, or adding data to the file.
The Microsoft .NET Framework 3.0 System.IO.Packaging class enables you to access the Word XML Format programmatically. You use the PackagePart class to operate on an individual part, such as a custom XML part, in the document.
Even if a mistake occurs that invalidates the custom XML data, the rest of the document is untouched. Therefore, the document still opens successfully. When this happens, a dialog box indicating a problem appears, alerting the end user to the damaged part. You must fix the custom XML data, but all other data within the document is still intact.
This section describes how to add and work with content controls. It includes information about the new objects and collections in the Word 2007 object model. It shows you how to work with content controls programmatically and through the UI, and provides an object model reference for all collections and objects that are specific to content controls, including both new objects and current objects that have new members. a portion of a document and, as the template author, you can specify what each region does. For example, if you want a region of your template to be a calendar, you insert a calendar content control in that area of the document, which automatically determines what that block of content does. Similarly, if you want a section of a template to display an image, create a picture content control in that area. In this way, you can.
The easiest way to create a content control is through the UI (although you can also create them programmatically). To create a content control through the UI, select the text that you want to turn into a content control and then, on the Developer tab of the Ribbon, choose the content control type that you want.
Figure 3 shows how to insert a plain text content control while building a template.
The ability to lock content controls enables you, as the template author, to create content controls without any fear of end users accidentally deleting or editing them. In the past, achieving this behavior was difficult. With the content controls in Word 2007, you can easily lock predefined portions of content against deletion and editing. Any portion of a template can also accept user input while other portions that are meant to be read-only are locked. You lock content controls using a dialog box that is located on the Developer tab of the Office Fluent Ribbon. By default, this dialog box is turned off, so the casual user cannot unlock content controls easily. You can also lock content controls programmatically, using the Word 2007 object model.
Another powerful feature of content controls is their ability to map to data in an XML file. When a content control is mapped to XML data, you gain new possibilities that do not exist in forms. As an example, one task you can do is map the options in a drop-down list content control to a node in an XML file. When you do this, each entry in the drop-down list in the UI is determined by the XML file's schema definition, and the drop-down list's current selection is stored in the mapped node.
The new Word XML Format is another change that creates additional possibilities. In the Word XML Format, XML data is stored in its own data store, completely separate from the document. This is a change from the WordprocessingML file format of Word 2003. This separation makes it easier to update XML data programmatically behind the scenes. Using the more flexible XML storage in Word 2007, you can programmatically change the items in a drop-down list content control by mapping each entry to an XML file.
A collection of ContentControlListEntry objects on ContentControl objects that are of type wdContentControlDropDownList or wdContentControlComboBox. Each ContentControlListEntry is an entry in either a drop-down list or a combo box. This collection does not pertain to other types of content controls. When you call a method or property on ContentControlListEntries for a content control that is not a drop-down list or a combo box, Word displays an error to the user.
ContentControlListEntry
An object for a single entry in a content control that is either a drop-down list or a combo box. ContentControlListEntry objects do not pertain to other types of content controls. When you call a method or property on ContentControlListEntry for a content control that is not a drop-down list or a combo box, Word displays an error to the user.
The calendar content control enables the end user to select a date from a calendar control. The calendar appears when the end user moves the pointer over the content control or clicks inside it. You can specify the format of the selected date either through the UI or programmatically.
Document Building Blocks.
For example, if you want a list of stock quotes in a template to update automatically, you can create a document building block that is a table composed of cells, with each cell containing one plain text content control for a stock quote. Each text content control is mapped to a node in a custom XML part that contains a current stock price. In this case, you do not map the document building blocks to data, but you do map text content controls inside it. After you create it, you can lock the whole document building block so that end users cannot accidentally delete or break it.
Drop-Down List
The drop-down list content control lets the end user select from a list of options in a drop-down menu. You can map the data in each entry to a node in a custom XML part. Programmatically, drop-down list and combo box content controls are different from other content controls because they each have a ContentControlListEntries collection. The ContentControlListEntries collection contains each entry from which the user can choose in the content control.
A text content control is a block of plain text. Unlike the similar rich text content control, you can map the contents of a text content control to data in a custom XML part.
If you do not remove the ability to edit the contents of a text content control, and you map the content control to data in an XML node, the user can directly edit the XML data through the document. For example, a plain text content control mapped to a node that contains the word "hello" displays that word in the document. If a user edits that content control by deleting "hello" and replacing it with "good bye," the XML node updates so that the data it contains is the string "good bye."
To add a content control programmatically, you call the Add method on a ContentControls collection. The ContentControls collection on the Range object, Selection object, or Document object can call the Add method. Add the following line of code into the Microsoft Visual Basic for Applications (VBA) Immediate window to create a picture content control on the current selection in the document.
This code creates a picture content control. To add other types of content controls, modify the wdContentControlType parameter to be wdContentControlDate, wdContentControlDocumentPartGallery, wdContentControlDropDownList, wdContentControlComboBox, wdContentControlRichText, or wdContentControlText.
A ContentControls collection belongs to the Range object and to the Selection object.
Locking Content Controls
You can lock content controls to prevent deletion, content modification, or both. Locking content controls enables you to create, for example, a drop-down list populated with data from an XML file that the end user cannot delete or modify. The user can select any of the items in this drop-down list, but cannot modify the list itself. With this new feature, it is easy for you, as the template designer, to create a content control of rich text that contains, for example, copyright information that you do not want deleted or modified. In Word 2003, if you want to protect a part of a document, you must protect a style and then apply that style to whatever text you want to lock. Content controls make this easier. Now, you can create rich documents with combo boxes, drop-down lists, text, pictures, and more, and protect any or all of the items so that the end user does not accidentally break the document.
You can lock a content control either through the UI or programmatically.
You can assign helpful instructional text to content controls. This text is called placeholder text. Placeholder text appears on the content control when its contents are empty. For example, placeholder text assigned to a rich text content control might say, "Please enter your comments here." When the user begins typing in the content control, the placeholder text goes away. If the user deletes all the content from the content control, the placeholder text reappears. Also, if the content control is mapped to XML data and an event forces the data to update so that its contents are empty, the placeholder text reappears.
You can format placeholder text. This formatting is separate from the formatting of the contents of the content control. For example, you might format the placeholder text to have a font with a large point size and to be bold, so that the user notices it. But, you might want the style of the contents of the content control to match the style of text in the rest of the document.
Modifying Placeholder Text Programmatically
To modify the placeholder text of a content control programmatically, call the SetPlaceholderText method of the content control. SetPlaceholderText can take three parameters, an AutoTextEntry, a Range, or a String. For simplicity, this example takes a String literal containing "Type text here."
If you need to get the placeholder text, you can get it as an AutoTextEntry using the PlaceholderText property of the ContentControl object.
XML mapping is new to Word 2007. XML mapping is a feature that enables you to create a link between a document and an XML file. This creates true data/view separation between the document formatting and the custom XML data. A more formal definition of XML mapping is to say it is a property on a content control that links the content of the content control to an XML element in a data store that is stored alongside the document. The last part of this definition refers to the Word XML Format, in which parts of a document are contained in individual XML files inside a compressed Word 2007 XML document. Inside the compressed document, in their own specific directories, are XML files that contain data mapped to content controls.
This means that XML mapping now works on XML data that is separate from the document content. This separation of data from formatting enables you to create more robust documents than you could with.
Any content controls that you map to damaged XML may not work properly, but the rest of the document remains undamaged. If something happens to the XML data that prevents it from validating against its schema, the document itself still opens. This separation also creates additional possibilities because it enables you to change, update, or delete XML data that you map to content controls, thereby changing the contents of those content controls without having to worry about what happens with the formatting of the document.
What Is Included in an XML Mapping?
XML mapping, content controls, and the new file format are related. The following section of this article focuses on XML mapping.
Custom XML Parts
The 2007 release of Microsoft Office associates every XML mapping with unique XML within the XML data store for the document. The data store provides access to all of the custom XML parts that are stored in an open file. You may refer to any node within any custom XML part inside the data store..
The data store in a document in the Word 2007 object model is contained in a new collection of the Document object, called CustomXMLParts. A CustomXMLParts collection contains CustomXMLPart objects. It points to all the data store items that are available to a document. A CustomXMLPart object represents a single custom XML part in the data store.
To load a custom XML part, you must first add a new data store to a Document object by calling the Add method. The Add method appends a new, empty data store to the document. Because it is empty, you cannot use it yet. Next, you must load a custom XML part from an XML file into the data store, or CustomXMLPart object, by calling its Load method, using a valid path to an XML file as the parameter.
Notice that, by default, there is always at least one data store on the document. For example, if you add the following code in the VBA Immediate window on a new, blank document, you get a count of one, not zero.
The default custom XML part contains the document's standard document properties; you cannot delete it. You can always look at a custom XML part by calling the read-only XML property on it. If you call the XML property of a CustomXMLPart (data store), a string is returned, which contains the XML in that data store. For example, use the VBA immediate window to call the XML property on a blank document.
The following XML appears.
<?xml version="1.0" standalone="yes"?> <CoreProperties xmlns=""> <Title></Title> <Subject></Subject> <Creator>Microsoft Employee</Creator> <Keywords></Keywords> <Description></Description> <LastModifiedBy></LastModifiedBy> <Category/> <Identifier/> <ContentType/> <ContentStatus/> <Language/> <Version/> <Revision xmlns=" metadata/core-properties">1</Revision> <DateCreated xmlns=""> 2005-06-29T20:13:00Z</DateCreated> </CoreProperties>
You can also access a specific item on the whole CustomXMLParts collection if you index the namespace. For example:
The following sample code demonstrates how to attach an XML file to a document, so that it becomes an available data store item. Remember that if you identify your first added data store by passing an index to the CustomXMLParts object (for example, oCustomXMLPart(2).Load), you must use an index of two. This is because an index of one returns the default store with standard properties for the 2007 release. Note that, alternatively, you can index CustomXMLParts objects by their namespaces.
Dim oCustomXMLPart As Office.CustomXMLPart Dim strXMLPartName As String strXMLPartName = "c:\myDataStoreFiles\myXMLDataStore.xml" ' First, add a new custom XML part to the document. Set oCustomXMLPart = ActiveDocument.CustomXMLParts.Add ' Second, load the XML file into the custom XML part. oCustomXMLPart.Load (strXMLPartName)
After you add a data store to your document (and the data store points to a valid XML file), you are ready to map one of its nodes to a content control. To do this, pass a String containing a valid XPath to a ContentControl object using its SetMapping method. An example of doing this with an XPath that refers to a data store node containing the first name of a book's author may look like the following.
' An XML mapping was added and loaded with information ' about books. ' First, create the Xpath. Dim strXPath As String strXPath = "/s:book/s:AuthorFirstName" ' Next, create an instance of a content control to work with. Dim oContentControl As Word.ContentControl Set oContentControl = Application.Selection.ContentControls.Add _ (wdContentcontrolComboBox) ' Last, map the data using the Xpath. oContentControl.XMLMapping.SetMapping strXPath
XPath Links and Data
The link between a content control and the data in a data store does not change. That is, the XPath link is static. This means that after you map the data to the content control, the content of the content control is linked to the content of the node that is returned by the XPath, until you explicitly remove or change the XML mapping of that content control.
If a change occurs in the node's data, the content control automatically reflects the pear."
Now, suppose the content control is mapped to a <fruitType> node of the following custom XML part..
The text in the document now appears like this.
"This is the text in my document. I would like a peach."
Notice that the content control updates. In a different scenario, suppose the <fruit> node is data mapped to a drop-down list content control. Suppose that, in this case, the schema attached to the document specifies three possible choices for the <fruitType> element, in this order.
Therefore, these are the options available from the drop-down list and they appear in the order that you list them in the schema. In this case, the addition to the custom XML part of the third node, containing the string "Banana", changes the selection of the drop-down list to "Banana," from whatever was selected before the addition.
What Are Dangling References?
When a content control cannot be successfully mapped to a node in a linked custom XML part (for example, if the XPath is invalid), the XML mapping is said to become a dangling reference. There is no UI that indicates that a content control contains a dangling reference. The only way to confirm the existence of a dangling reference is through the object model.
When a dangling reference occurs, the content control in the document does not change in appearance.
There are two types of dangling references.
Dangling XPath References
When you replace or remove a node from a custom XML part, the potential exists for one or more XML mappings to become dangling references. This happens when the XPath of the XML mapping no longer resolves to data, which can be caused by the removal of a mapped node. A change to a custom XML part can also append a child to a mapped node that the schema specifies must be a leaf node. The addition of a leaf turns the mapped node from a leaf into a parent node.
In these cases, the XPath used in the XML mapping does not change, only the custom XML part does. Even though the XPath does not change, it now points to data it cannot use. That is a dangling XPath reference.
Each time you update the custom XML part, the Word document determines whether any dangling references are resolved. In other words, it checks whether any dangling references now point to a valid node in the custom XML part. If so, Word immediately updates the content control to reflect the updated, valid banana."
The XPath used to map this content control to a node in a custom XML part looks like this: "\tree\fruit\fruitType(3)".
You can enumerate the collection of data stores on a document by using the Item method of the CustomXMLParts collection. This Item method can take a Long parameter that specifies the index of the store you want or a String parameter that specifies the root namespace of the data store you want. Note that, if more than one CustomXMLPart object matches this root namespace, Word returns the first match in the index order.
Get the interface for an existing store item.
You can do this by using the same Item method that enumerates the CustomXMLParts collection. You can also use two other methods. Each returns a CustomXMLPart object. These are the SelectByID method, which takes a String parameter containing the ID of the desired store, and the SelectByNamespace method, which takes a String parameter containing the root namespace of the desired store..
The CustomXMLNode object, which represents a node in a custom XML part, contains two methods: ReplaceChildNode and ReplaceChildSubtree. The first method replaces a single node and the second method replaces a node and its children. Both methods require that you specify the node to remove and the node to replace it with, as parameters.able property called NodeValue, which can either get or set the text in the node. Note that this works only on nodes that contain text. Text nodes are those of types msoXMLNodeText, msoXMLNodeComment, msoXMLNodeProcessingInstruction, and msoXMLNodeAttribute. To get the value of a subtree, use the read-only GetNodes property of a CustomXMLNode object, which returns a CustomDataXMLNodes collection, and then iterate through the collection calling NodeValue on each., assume that the user inserts two plain text content controls into an otherwise blank document. At this point, you have not mapped the content control to any data or added any custom XML parts to the document.
Now, add the XML file, C:\test.xml, as a custom XML part. The first of the following two lines of code creates and adds an empty, custom XML part to the active document. The second line loads the XML file into the newly created custom XML part. Remember that there is already one default XML part containing document properties, so the first custom XML part always has an index of two.
Next, map one text content control to the <a> node and the other to the <b> node by passing an XPath to the appropriate node to a content control in the active document's ContentControls collection:
After you execute these two lines, each text content control displays the text, or data, of the node to which it is respectively mapped. Therefore, in the document, the first text content control displays "NodeA" and the second one displays "NodeB".
It is assumed that neither text block is locked against content changes. Now, suppose a user edits the text of the first node in the document to be "Hello." When this happens, the data in the XML part <a> node instantly changes to be "Hello." To verify this, enter the following line of code into the VBA immediate window and run it.
As expected, it returns node <a> with the word "Hello" as its data.
You can now see the tight link between a data-mapped content control and the custom XML part to which it is mapped. The data contained in mapped nodes can change programmatically with an add-in or directly in the document..
Running the Demo subroutine sets up the oStream object to listen to events.
Remember from the previous scenario that the document has two text content controls, one data mapped to the <a> node and the other data mapped to the <b> node. You want to set up events so that when the <a> node is modified, the <b> node automatically does something. The following oStream_NodeAfterReplace subroutine accomplishes this.
Private Sub oStream_NodeAfterReplace(ByVal OldNode As Office.CustomXMLNode, ByVal NewNode As _ Office.CustomXMLNode, ByVal InUndoRedo As Boolean) ' Check if NewNode, which is the node after the change, is ' the "a" node by looking at the BaseName of its ParentNode. If NewNode.ParentNode.BaseName = "a" Then oStream.DocumentElement.LastChild.Text = "You changed a!" End If End Sub
This routine is triggered after the user changes the text in the first text content control, mapped to element <a>. If the <a> node changes, the text of the last child in the custom XML part is updated. Because the stream has only two nodes, the last node is the <b> node. After the text of <b> node is updated, the updated text of "You changed a!" automatically appears in the second text content control.
Although this example is very simple, it shows what you can do with events, XML mapping, and content controls. You can use code such as this to update any text in a document when one text content control changes. This is powerful because it assumes nothing about the document formatting, and it does not work with the document formatting. Instead, it works against the schema that you attach to the document.
XML Mapping and the Word XML Format
In the new Word XML Format, each custom part persists in its own XML part in the document container, which contains the file name and its relationship information. In Word 2007, the XML part is stored off the root of a file's container in a folder called dataStore.
The relationship file, stored inside a _rels folder, describes all the relationships from one XML part to all other XML parts within a Word XML document. There are two relationship types for custom XML parts:
The relationship type for the XML is: /2006/relationships/customXml
The relationship type for the XML properties is: /2006/relationships/customXmlProps
An ID is stored with each relationship, enabling you to identify it uniquely within the data store.
The actual custom XML part is stored in its own file alongside the _rels folder. The file format for a custom XML part looks like the following. pieces (such as drop-down menus, text blocks, calendars, and pictures) to a document. You can also lock these content controls to prevent accidental modification by end users.
Additionally, Word 2007 enhances the way documents work with custom XML, allowing simple mapping of data to content controls. Word separates XML data from the presentation of the document so that it is easier to modify both data and formatting programmatically. New events in the object model let you create quick and simple add-ins that update data using content controls mapped to elements in custom XML attached to a document.
This new functionality greatly increases the speed with which a template designer creates documents. Not only that, but the templates are more user-friendly and more robust. You can load content controls with a wealth of information by mapping to custom XML data.
For more information about developer enhancements in Word 2007, see these resources: | https://msdn.microsoft.com/de-de/library/bb266219(v=office.12).aspx | CC-MAIN-2015-18 | refinedweb | 5,258 | 61.56 |
I have a Java class that is used for a companies different branches located around the Country, and each branch will keep a track of its client list. How can i implement this so that "London" branch only pulls the list of clients that has used that branch, but not able to see the client list of other branches? I am thinking of a client class that contains an array, but im struggling to find a way of linking the classes together
public class Branch implements Manager {
//instance variables that will be available to children of Branch
private String branchName;
// constructor
public Branch(String name) {
this.branchName = name;
}
//Returns the location of the branch as a String
@Override
public String getBranch() {
return this.branchName;
}
//Returns a String representation of customers who have used the Branch
@Override
public String getAllCustomers() {
return "Customer list will go here";
}
How about:
Map<String, List<Clients>>
?
So you can map a branch to a list of clients. | https://codedump.io/share/loJ08mEKoLoU/1/java-class-with-array | CC-MAIN-2017-34 | refinedweb | 162 | 61.8 |
Several people have problems using the XML class to load and save their data. It can get confusing when an XMLNode at one level looks and acts the same as an XMLNode at another level. I loved the idea of XML, but it always seemed more work than it was worth to get it to work correctly.
tlhIn'toq posted an XML solution for a poster in this thread. I saw that code and fell in love with it. It was simple. It was elegant. It did exactly what it needed to do. It used serialization to remove a lot of the grunt work involving XML. It was also built specifically for the poster's class. That's when I had the idea of using Generics to make the code more powerful. Ever since then XML files bend to my bidding. All it takes is a little work on the front end. I'll show you how to do it.
Set Up
First, we need some classes to work with. Since the original solution was for XNA, I stuck with the video game theme. But I wrote this without XNA installed, nor is this solution only for game programmers. I used a copy of VS2010, .Net 4.0 (but I'm sure it will work on earlier versions), all optimized for my work production.
First I created an enum called ItemType:
public enum ItemType { Weapon, Shield, Potion, }
This is used by my two classes. The first is an Item:
public class Item { #region Fields public ItemType Type; public int Strength; public String Name; #endregion #region Constructors #region Item() public Item() { Type = ItemType.Potion; Name = ""; Strength = 0; } #endregion #region Item(Name, Type, Strength) public Item(string Name, ItemType Type, int Strength) { this.Name = Name; this.Type = Type; this.Strength = Strength; } #endregion #region Item(Item) public Item(Item old) { this.Name = old.Name; this.Type = old.Type; this.Strength = old.Strength; } #endregion #endregion #region ToString public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("\tName: "); builder.Append(Name); builder.Append("\n\tType: "); builder.Append(Type.ToString()); builder.Append("\n\tStrength: "); builder.Append(Strength); return builder.ToString(); } #endregion }
A very important note. Any class that uses this trick must have a default, parameterless constructor. It just does.
My second class is a Unit:
public class Unit { #region Fields public Item Weapon; public Item Shield; public List<Item> Bag; public string Name; #endregion #region Constructors #region Unit() public Unit() { Bag = new List<Item>(); } #endregion #region Unit(Name) public Unit(string Name) : this() { this.Name = Name; } #endregion #endregion #region ToString public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("Name: "); builder.Append(Name); builder.Append("\nWeapon:\n"); builder.Append(Weapon); builder.Append("\nShield:\n"); builder.Append(Shield); builder.Append("\nBag:\n"); foreach (Item item in Bag) { builder.Append(item); builder.Append("\n\n"); } return builder.ToString(); } #endregion }
Another note. This project was created for testing purposes. I created a couple of public fields and some basic constructors. Production code should use private fields, properties, better constructors (but at least a default one!), and methods. I left them out for space consideration. I added the ToString method for later use.
Serialization
This is the bit of front end you need to do to get the code to work. This is easy work, though. If you know how to serialize already, you can skip this section.
What we want is a way for the code to take apart the class and recombine it. This can be used for many things. It is used to write with BinaryWriter to a file. It's also used a lot when working with ports. Your class needs a way of breaking itself down, and building itself from those parts. First, you need to add the using System.Runtime.Serialization to both the Item and the Unit classes (or just once if you have them in the same file).
Let's break down our Item class. The class has three properties, a number of constructors, ToString, and any othe methods you wanted. The important bits we need are the properties. The other information can be recreated if we have this information. We'll create a method to pry this information out. The method name will be GetObjectData. It will return void. It will take two parameters, SerializationInfo and StreamingContext. This signature needs to be exact, so the serializers can call it.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { }
In the method, we want to give the SerializationInfo any info we need to serialize. SerializationInfo has a method called AddValue that will help us do that. We pass two parameters, the name of the property and the value. So add the following to GetObjectData:
info.AddValue("Name", Name); info.AddValue("Type", Type); info.AddValue("Strength", Strength);
It doesn't matter what names we give the properties, but it is easier to debug if you give it a simple name to remember and type.
You are done with the first part. You took apart an Item. Now you just need to put it back together. For this, we need a constructor. It will have the same properties as GetObjectData.
public Item(SerializationInfo info, StreamingContext ctxt) { }
The SerializationInfo is the same object that we just passed our properties. We need to get them back. We do this by calling the GetValue method. This method also takes two parameters, the name of the property and the property type. It returns an object. Once we get the object from GetValue, we need to cast it to the proper type. So we have Name = (string)info.GetValue(. This will set our Name property to the result of GetValue after we turned it into a string. For the first parameter, we use the same string we used when adding the value, "Name". Name = (string)info.GetValue("Name", . For the second parameter, we need to tell it what kind of object it is looking for. So we pass it the typeof(string). Now we have one line to get our Name out of serialization.
Name = (string)info.GetValue("Name", typeof(string));
We just need to do the same thing for the other properties we want. The order doesn't matter. That is why there is a name, so you can add or remove them in any order.
public Item(SerializationInfo info, StreamingContext ctxt) { Name = (string)info.GetValue("Name", typeof(string)); Type = (ItemType)info.GetValue("Type", typeof(ItemType)); Strength = (int)info.GetValue("Strength", typeof(int)); }
Serialize Unit
We need to do the same thing for our Unit class. It is important that any class you want to convert to XML, including properties that are classes, are serialized. Otherwise the serializer will not be able to convert the class.
GetObjectData is the easiest to do. Simply add all of our properites. The Unit class has four properties.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("Name", Name); info.AddValue("Weapon", Weapon); info.AddValue("Shield", Shield); info.AddValue("Bag", Bag); }
Wait, Bag is a complex property. It is a List of Items. What are we going to do? Ignore it! Serializers know about Collections. All you have to worry about is telling the Serializer that it is a collection. You don't have to here, it will figure out what object it is when you hand it over.
The next step is to write a new constructor. If you understood the last section, you should be able to build this:
public Unit(SerializationInfo info, StreamingContext ctxt) { Name = (string)info.GetValue("Name", typeof(string)); Weapon = (Item)info.GetValue("Weapon", typeof(Item)); Shield = (Item)info.GetValue("Shield", typeof(Item)); }
We're missing the information on Bag. How do we get it from info? We tell it it's a collection! typeof(List<Item>) How do we store it into our Bag property? We cast it to a collection! Add this line to the constructor:
Bag = (List<Item>)info.GetValue("Bag", typeof(List<Item>));
You just turned the two classes into serializable classes. It takes a bit of effort, but it will make everything work in the end. You can now pass those around to readers and writers and not do any complex work.
Generics and XML
I will make this XML thing easy. Create a new class. Call it MyXML. Now we'll create two static methods, one to read objects and one to save objects.
Now we'll use generics. Generics is what collections like List use. We make one method, and that method can be used for all sorts of datatypes. So that means we will create a class that saves and gets objects from XML files. This will work for the Unit class, but it will also work for any other class that has been properly serialized.
We need three using statements for this class.
using System.Xml.Serialization; using System.Xml; using System.IO;
We'll create a method called SaveObject. It will be public static, and return a boolean value to show whether it worked. It will take two parameters, an object to save and a filename to save it. To create a generic, we use a placeholder for the datatype. I'll use the letter 'T' (the normal convention), but you can use any letter.
public static bool SaveObject<T>(T obj, string FileName) { }
After the method name, I inserted <T>. This tells the compiler that this is a generic and can be used with any datatype. The parameter obj is of type T. So the compiler knows that if a string is passed, than type T is string. If Unit is passed, type T is Unit. Now we can use T as if it were any other datatype.
The first step is to create an XMLSerializer. The constructor of the XMLSerializer requires a datatype. Well, we have the object to send it, so we just use the parameter obj. The GetType method is an Object scope variable, so it will work with any C# Object.
var x = new XmlSerializer(obj.GetType());
Next, we create a StreamWriter. This will write the actual XML file. We pass it the FileName we got as a parameter. We also pass it false. The second parameter is a boolean value of whether to append the file. False means we'll overwrite the file, if it exists already.
using (var Writer = new StreamWriter(FileName, false))
The only thing we need to do is call the Serialize method of x. We'll pass it the Writer and obj. then return true.
x.Serialize(Writer, obj); } return true;
I wrapped it in a try/catch block. We should check to verify that the FileName is a full path that has write access. There will also be an error if the object passed isn't serializable. The full function is as follows.
public static bool SaveObject<T>(T obj, string FileName) { try { var x = new XmlSerializer(obj.GetType()); using (var Writer = new StreamWriter(FileName, false)) { x.Serialize(Writer, obj); } return true; } catch { return false; } }
Now we create a similar function that does the reverse. It also returns a boolean value so we know if it worked. We pass it the object to save to, and the filename. The object needs to be by reference. That way the function can edit it, and the caller knows the function will edit it. We create an instance of FileStream using (FileStream stream = new FileStream(FileName, FileMode.Open)). This uses the FileName passed, and says that the stream will be open (instead of say create).
Now create an XMLTextReader XmlTextReader reader = new XmlTextReader(stream). This will use the stream to read an XML file. Now create an XMLSerializer var x = new XmlSerializer(obj.GetType()). Again we call the GetType on Object so the XMLSerializer knows what type of object it will be. Next we call Deserialize and cast into our object type T obj = (T)x.Deserialize(reader);. The full function is as follows.
public static bool GetObject<T>(ref T obj, string FileName) { try { using (FileStream stream = new FileStream(FileName, FileMode.Open)) { XmlTextReader reader = new XmlTextReader(stream); var x = new XmlSerializer(obj.GetType()); obj = (T)x.Deserialize(reader); return true; } } catch { } return false; }
You may think you want to return an object of type T and just pass it a FileName. This won't work. To call obj.GetType(), obj need to be instantiated. I don't know of a way to generically create an obj of type T. Since we need to pass it an instantiated obj, we might as well pass by reference and do the work there.
Putting It Together
So we had to add one function and one constructor for each class we want to turn into XML. We also created a new class, but made it generic so you can use it over and over again in different projects.
It is easy to use. First, we create a Unit and a FileName.
string FileName = "MyUnit.XML"; Item MyWeapon = new Item("Sword", ItemType.Weapon, 10); Item MyShield = new Item("Shield", ItemType.Shield, 8); Item MyPotion = new Item("Health Potion", ItemType.Potion, 5); Item BackUpWeapon = new Item("Ax", ItemType.Weapon, 7); Unit Dan = new Unit("Dan"); Dan.Weapon = MyWeapon; Dan.Shield = MyShield; Dan.Bag.Add(MyPotion); Dan.Bag.Add(BackUpWeapon);
To turn it into XML, we just call the function
MyXML.SaveObject(Dan, FileName);. That's it. You can check the XML file.
To pull it out of XML is just as easy.
Unit Dan2 = new Unit(); MyXML.GetObject(ref Dan2, FileName);
I hope this tutorial has been helpful. I know this has helped me in my coding. I included a .zip of my project for easier viewing.
Attached File(s)
Robin19.zip (34.38K)
Number of downloads: 584 | http://www.dreamincode.net/forums/topic/191471-reading-and-writing-xml-using-serialization/page__pid__1121835__st__0 | CC-MAIN-2016-07 | refinedweb | 2,285 | 69.68 |
This chapter describes some general tips related to cross-platform development.
The main include file is
"wx/wx.h"; this includes the most commonly used modules of wxWidgets.
To save on compilation time, include only those header files relevant to the source file. If you are using precompiled headers, you should include the following section before any other includes:
// For compilers that support precompilation, includes "wx.h". #include <wx/wxprec.h> #ifndef WX_PRECOMP // Include your minimal set of headers here, or wx.h # include <wx/wx.h> #endif ... now your other include files ...
The file
"wx/wxprec.h" includes
"wx/wx.h". Although this incantation may seem quirky, it is in fact the end result of a lot of experimentation, and several Windows compilers to use precompilation which is largely automatic for compilers with necessary support. Currently it is used for Visual C++ (including embedded Visual C++) and newer versions of GCC. Some compilers might need extra work from the application developer to set the build environment up as necessary for the support.
All ports of wxWidgets can create either a static library or a shared library.
".so" (Shared Object) under Linux and
".dll" (Dynamic Link Library) under Windows.).
wxWidgets can also be built in multilib and monolithic variants. See the Library List for more information on these.
When (or DEB or other forms of binaries) for installing wxWidgets on Linux, a correct
"setup.h" is shipped in the package and this must not be changed.
On Microsoft Windows, wxWidgets has a different set of makefiles for each compiler, because each compiler's
'make' tool is slightly different. Popular Windows compilers that we cater for, and the corresponding makefile extensions, include: Microsoft Visual C++ (.vc) and MinGW/Cygwin (.gcc). Makefiles are provided for the wxWidgets library itself, samples, demos, and utilities.
On Linux and macOS, you use the
'configure' command to generate the necessary makefiles. You should also use this method when building with MinGW/Cygwin on Windows.
We also provide project files for some compilers, such as Microsoft VC++. However, we recommend using makefiles to build the wxWidgets library itself, because makefiles can be more powerful and less manual intervention is required.
On Windows using a compiler other than MinGW/Cygwin, you would build the wxWidgets library from the
"build/msw" directory which contains the relevant makefiles.
On Windows using MinGW/Cygwin, and on Unix and macOS, you invoke 'configure' (found in the top-level of the wxWidgets source hierarchy), from within a suitable empty directory for containing makefiles, object files and libraries.
For details on using makefiles, configure, and project files, please see
"docs/xxx/install.txt" in your distribution, where
"xxx" is the platform of interest, such as
msw,
gtk,
x11,
mac.
All wxWidgets makefiles are generated using Bakefile. wxWidgets also provides (in the
"build/bakefiles/wxpresets" folder) the wxWidgets bakefile presets. These files allow you to create bakefiles for your own wxWidgets-based applications very easily.
wxWidgets application compilation under MS Windows requires at least one extra file: a.ico
The icon can then be referenced by name when creating a frame icon. See the Microsoft Windows SDK documentation..
In general wxWindow-derived objects should always be allocated on the heap as wxWidgets will destroy them itself. The only, but important, exception to this rule are the modal dialogs, i.e. wxDialog objects which are shown using wxDialog::ShowModal() method. They may be allocated on the stack and, indeed, usually are local variables to ensure that they are destroyed on scope exit as wxWidgets does not destroy them unlike with all the other windows. So while it is still possible to allocate modal dialogs on the heap, you should still destroy or delete them explicitly in this case instead of relying on wxWidgets doing it..
A problem which sometimes arises from writing multi-platform programs is that the basic C types are not defined the same on all platforms. This holds true for both the length in bits of the standard types (such as int and long) as well as their byte order, which might be little endian (typically on Intel computers) or big endian (typically on some Unix workstations). wxWidgets defines types and macros that make it easy to write architecture independent code. The types are:
wxInt32, wxInt16, wxInt8, wxUint32, wxUint16 = wxWord, wxUint8 = wxByte
where wxInt32 stands for a 32-bit signed integer type etc. You can also check which architecture the program is compiled on using the wxBYTE_ORDER define which is either wxBIG_ENDIAN or wxLITTLE_ENDIAN (in the future maybe wxPDP_ENDIAN as well).
The macros handling bit-swapping with respect to the applications endianness are described in the Byte Order section.
One of the purposes of wxWidgets is to reduce the need for conditional compilation in source code, which can be messy and confusing to follow. However, sometimes it is necessary to incorporate platform-specific features (such as metafile use under MS Windows). The wxUSE Preprocessor Symbols symbols listed in the file
setup.h may be used for this purpose, along with any user-supplied ones.
The following documents some miscellaneous C++ issues.
wxWidgets does not use templates (except for some advanced features that are switched off by default) since it is a notoriously unportable feature.
wxWidgets does not use C++ run-time type information since wxWidgets provides its own run-time type information system, implemented using macros.
Some compilers, such as Microsoft C++, support precompiled headers. This can save a great deal of compiling time. The recommended approach is to precompile
"wx.h", using this precompiled header for compiling both wxWidgets itself and any wxWidgets applications. For Windows compilers, two dummy source files are provided (one for normal applications and one for creating DLLs) to allow initial creation of the precompiled header.
However, there are several downsides to using precompiled headers. One is that to take advantage of the facility, you often need to include more header files than would normally be the case. This means that changing a header file will cause more recompilations (in the case of wxWidgets, everything needs to be recompiled since everything includes
"wx.h").
A related problem is that for compilers that don't have precompiled headers, including a lot of header files slows down compilation considerably. For this reason, you will find (in the common X and Windows parts of the library) conditional compilation that under Unix, includes a minimal set of headers; and when using Visual C++, includes
"wx.h". This should help provide the optimal compilation for each compiler, although it is biased towards the precompiled headers facility available in Microsoft C++.
When building an application which may be used under different environments, one difficulty is coping with documents which may be moved to different directories on other machines. Saving a file which has pointers to full pathnames is going to be inherently unportable.
One approach is to store filenames on their own, with no directory information. The application then searches into a list of standard paths (platform-specific) through the use of wxStandardPaths.
Eventually you may want to use also the wxPathList class.
Nowadays the limitations of DOS 8+3 filenames doesn't apply anymore. Most modern operating systems allow at least 255 characters in the filename; the exact maximum length, as well as the characters allowed in the filenames, are OS-specific so you should try to avoid extremely long (> 255 chars) filenames and/or filenames with non-ANSI characters.
Another thing you need to keep in mind is that all Windows operating systems are case-insensitive, while Unix operating systems (Linux, Mac, etc) are case-sensitive.
Also, for text files, different OSes use different End Of Lines (EOL). Windows uses CR+LF convention, Linux uses LF only, Mac CR only.
The wxTextFile, wxTextInputStream, wxTextOutputStream classes help to abstract from these differences. Of course, there are also 3rd party utilities such as
dos2unix and
unix2dos which do the EOL conversions.
See also the Files and Directories section of the reference manual for the description of miscellaneous file handling functions.
It is good practice to use ASSERT statements liberally, that check for conditions that should or should not hold, and print out appropriate error messages.
These can be compiled out of a non-debugging version of wxWidgets and your application. Using ASSERT is an example of `defensive programming': it can alert you to problems later on.
See wxASSERT() for more info.
Using wxString can be much safer and more convenient than using
wxChar*.
You can reduce the possibility of memory leaks substantially, and it is much more convenient to use the overloaded operators than functions such as
strcmp. wxString won't add a significant overhead to your program; the overhead is compensated for by easier manipulation (which means less code).
The same goes for other data types: use classes wherever possible.
XRC(wxWidgets resource files) where possible, because they can be easily changed independently of source code. See the XML Based Resource System (XRC) for more info.
It is common to blow up the problem in one's imagination, so that it seems to threaten weeks, months or even years of work. The problem you face may seem insurmountable: but almost never is. Once you have been programming for some time, you will be able to remember similar incidents that threw you into the depths of despair. But remember, you always solved the problem, somehow!
Perseverance is often the key, even though a seemingly trivial problem can take an apparently inordinate amount of time to solve. In the end, you will probably wonder why you worried so much. That's not to say it isn't painful at the time. Try not to worry – there are many more important things in life.
Reduce the code exhibiting the problem to the smallest program possible that exhibits the problem. If it is not possible to reduce a large and complex program to a very small program, then try to ensure your code doesn't hide the problem (you may have attempted to minimize the problem in some way: but now you want to expose it).
With luck, you can add a small amount of code that causes the program to go from functioning to non-functioning state. This should give a clue to the problem. In some cases though, such as memory leaks or wrong deallocation, this can still give totally spurious results!
This sounds like facetious advice, but it is surprising how often people don't use a debugger. Often it is an overhead to install or learn how to use a debugger, but it really is essential for anything but the most trivial programs.
There is a variety of logging functions that you can use in your program: see Logging.
Using tracing statements may be more convenient than using the debugger in some circumstances (such as when your debugger doesn't support a lot of debugging code, or you wish to print a bunch of variables).
You can use wxDebugContext to check for memory leaks and corrupt memory: in fact in debugging mode, wxWidgets will automatically check for memory leaks at the end of the program if wxWidgets is suitably configured. Depending on the operating system and compiler, more or less specific information about the problem will be logged.
You should also use Debugging macros as part of a "defensive programming" strategy, scattering wxASSERT()s liberally to test for problems in your code as early as possible. Forward thinking will save a surprising amount of time in the long run.
See the Debugging for further information. | https://docs.wxwidgets.org/trunk/page_multiplatform.html | CC-MAIN-2022-05 | refinedweb | 1,922 | 54.63 |
By kalyan.net
via techbubbles.com
Submitted: Dec 07 2012 / 19:27
What is Service Bus? The Windows Azure Service Bus provides a secured infrastructure for wide-spread communication. It provides the connectivity options for Windows Communication Foundation and other service points. This post explains various tools around Service Bus like the most fundamental is how to create a namespace and how to create entities and how these work through the windows azure new portal. To use service bus or any of the features that it provides then you need to have the namespace. Name space is very similar to web site or IIS site or database in SQL server which gives a scope to contain the entities. | http://www.dzone.com/links/service_bus_fundamentals.html?ref=rs | CC-MAIN-2014-15 | refinedweb | 118 | 63.39 |
how can i use a string in a switch statement?
You can't. You can only switch on "integral types" like char and int.
You need to do a bunch of if-else if statements for strings.
thanks for your help
You can also define a map<string,int> that you can use to look up a string, obtain a corresponding integer, and use that integer in a switch. Depending on how you write your code, that strategy may well run faster, and be easier to maintain, than using a series of if-then-else statements.
Since I don't know exactly what your situation is, I'm just going to throw this out there as a possibility.
You could also use an enumeration:
#include <iostream>
using namespace std;
enum myEnum {BASE_VAL = 0, FIRST_VALUE, SECOND_VALUE, VALUE_TEN = 10};
int main() {
myEnum example(FIRST_VALUE); //select any valid member of the enumeration
switch (example) {
case BASE_VAL:
cout << "example is a BASE_VAL." << endl;
break;
case FIRST_VALUE:
cout << "example is a FIRST_VALUE." << endl;
break;
case SECOND_VALUE:
cout << "example is a SECOND_VALUE." << endl;
break;
case VALUE_TEN:
cout << "example is VALUE_TEN." << endl;
default:
cout << "example is not a valid member of myEnum." << endl;
}
cin.get();
return 0;
}
An enumeration is essentially just a collection of integral constants. That's why it works. | https://www.daniweb.com/programming/software-development/threads/344634/string-use-in-switch-statement | CC-MAIN-2016-50 | refinedweb | 215 | 64 |
I want to write a simple java agent which can print the name of a method called by the java program instrumented.
For example, my java program I want to instrument is:
public class TestInstr { public static void sayHello() { System.out.println("Hello !"); } public static void main(String args[]) { sayHello(); sayHello(); sayHello(); } }
I would like to display something like this :
method sayHello has been called Hello ! method sayHello has been called Hello ! method sayHello has been called Hello !
Thanks for your help!
You can use an instrumentation library such as Javassist to do that.
Let me give you an example for a single method, you can extend this to all methods using Javassist or reflection:
ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("TestInstr"); CtMethod m = cc.getDeclaredMethod("sayHello"); m.insertBefore("{ System.out.println(\"method sayHello has been called\"); }"); cc.writeFile();
Check this link for details:
###
I seem to remember that
AspectJ can do stuff like this; I have no experience with it, however, so exploring possibilities is up to you! 😀
###
In the method you could add
public class TestInstr { public static void sayHello() { System.out.println("method sayHello has been called"); System.out.println("Hello !"); } public static void main(String args[]) { sayHello(); sayHello(); sayHello(); } }
You could use this to get the current method
public String getCurrentMethodName() { StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace(); return stackTraceElements[1].toString(); }
I’m not sure if this is what you’re looking for.
###
I do not think it is easy.
The only option I can think of would be implementing a class loader and replacing the original classes with stubs created by you (Hibernate / JPA does something like that for lazy loading). The stubs would perform the operation you require and then call the original classes to perform the work. It would mean a heavy burden (reflection calls are not cheap).
###
If your need is simply to record a method was called or not, then aspect-oriented programming is exact what you need, no matter AspectJ(static) or Spring AOP(dynamic), both provide powerful capability to do that.
However you may need some instrument libraries in case you want to do more instrument stuff, such like track the execution time, calling track.
Hope it helps. | https://exceptionshub.com/how-to-instrument-java-methods.html | CC-MAIN-2022-05 | refinedweb | 370 | 57.06 |
New Year PVS-Studio 6.00 Release: Scanning Roslyn
The long wait is finally over. We have released a static code analyzer PVS-Studio 6.00 that supports the analysis of C# projects. It can now analyze projects written in languages C, C++, C++/CLI, C++/CX, and C#. For this release, we have prepared a report based on the analysis of open-source project Roslyn. It is thanks to Roslyn that we were able to add the C# support to PVS-Studio, and we are very grateful to Microsoft for this project.
PVS-Studio 6.00
PVS-Studio is a static code analyzer designed to detect software bugs at the coding stage and created to be easy-to-use.
We regularly add new diagnostic rules to enable the search of new bug patterns in applications written in C/C++. For example, we have recently added search of class members that are not initialized in constructors, and it was quite a non-trivial task indeed. However, improving the diagnostics can't be deemed a reason for upgrading the product's major version number; for this we waited until we brought something really new to our analyzer. And now, it has finally happened. Meet the sixth version of PVS-Studio with support for C# programming language.
PVS-Studio 6.00 trial version can be downloaded here:
In the sixth version of our tool, we ended support for older Visual Studio versions, VS2005 and VS2008. If your team still uses one of these, we suggest that you stick with the previous version of PVS-Studio, 5.31, or its updates if there are any.
The demo version has just one limitation. You have 50 click-jumps to the code. Once you've used these, the tool will suggest filling out a small questionnaire. If you agree, you'll be granted 50 more jumps.
While the demo version's limitation may seem severe, we experimented a lot before we shaped this limitation, and there are solid reasons behind it.
The small number of "clicks" will prompt you to get engaged in communication via email sooner. If you want to view the other messages, we can grant you a registration key for, say, one week. Just send us an email. Communication by email usually allows us to help users start taking advantage of the analyzer quicker and easier.
Roslyn
Programmers are immune to ads. You can't lure them with words like "mission", "perfectly", and "innovation-focused". Every programmer is accustomed to ignoring ads and knows how to disable banners using Adblock Plus.
The only way to attract their attention is to show how they can benefit by using a particular software tool. It is this path we have taken; we show how useful static analysis tools can be by scanning open-source projects.
PVS-Studio can find bugs in well-known projects such as CoreCLR, LibreOffice, Linux Kernel, Qt, Unreal Engine 4, Chromium, and so on. By now, our team has scanned 230 open-source projects and found a total of 9355 bugs. Yes, that's right: 9355 is the number of bugs, not diagnostic messages. To read about the most interesting scans, see the corresponding articles.
Now we've finally got to C# projects too. It is little wonder that we picked Roslyn as one of the first projects to be analyzed. After all, it is thanks to this software that we were given the opportunity to support C#-code analysis in PVS-Studio.
I'd like to thank the Microsoft company for developing this open-source project; it will surely have a significant impact on the C#-infrastructure's development. Well, it has already started to happen! For example, such famous projects as ReSharper and CodeRush are being ported to the Roslyn platform.
Now a few words about the Roslyn project itself.
.NET Compiler Platform, better known by its codename . Roslyn APIs are of three types, namely feature APIs, work-space APIs and compiler APIs. Feature APIs make the refactoring and fixing process easier..
References:
- GitHub. Roslyn.
- Wikipedia. .NET Compiler Platform ("Roslyn")
- .NET Compiler Platform ("Roslyn") Overview.
- MSDN. Forum. Microsoft "Roslyn" CTP.
- MSDN. Taking a tour of Roslyn.
- Learn Roslyn Now.
- Miguel de Icaza. Mono and Roslyn.
Bugs found
There are not many errors that PVS-Studio found in Roslyn, and this is not surprising for such a famous project, especially since it is developed by Microsoft, with their long established quality-control systems. Finding anything at all in Roslyn's code would be already a victory, and we are proud that we can do it.
Many of the bugs discussed refer to tests or error handlers, and this is normal too. Errors in the code which gets executed most frequently are fixed through testing and user reports. But it is the fact that PVS-Studio can catch these bugs beforehand that matters. It means that many bugs, which previously took much time and effort to fix, could potentially be fixed immediately by using PVS-Studio on a regular basis.
In other words: it is regular use that makes the analyzer valuable, not casual runs. View static code analysis as an extension to compiler warnings. It's not a good idea to enable compiler warnings once a year, is it? You have to address them as they appear; it helps save development time on tracking down silly mistakes through debugging. It's just the same with static analyzers.
Let's see now what interesting bugs we managed to find with PVS-Studio in the Roslyn project:
Error No. 1, in tests. Copy-Paste.
public void IndexerMemberRace() { .... for (int i = 0; i < 20; i++) { .... if (i % 2 == 0) { thread1.Start(); thread2.Start(); } else { thread1.Start(); thread2.Start(); } .... } .... }
PVS-Studio diagnostic message: V3004 The 'then' statement is equivalent to the 'else' statement. GetSemanticInfoTests.cs 2269
This is an example of errors found in tests. They can live there for years since they don't cause any trouble. It's just that the test doesn't check all that it was meant to. In both branches, thread 1 starts all the time, followed by thread 2. The code was most likely meant to look like this:
if (i % 2 == 0) { thread1.Start(); thread2.Start(); } else { // Threads' start order changed thread2.Start(); thread1.Start(); }
Error No. 2, in tests. Typo.
public DiagnosticAsyncToken( AsynchronousOperationListener listener, string name, object tag, string filePath, int lineNumber) : base(listener) { Name = Name; Tag = tag; FilePath = filePath; LineNumber = lineNumber; StackTrace = PortableShim.StackTrace.GetString(); }
PVS-Studio diagnostic message: V3005 The 'Name' variable is assigned to itself. AsynchronousOperationListener.DiagnosticAsyncToken.cs 32
It's not easy to spot the error here. Poor variable naming is to blame. Class attributes' names differ from those of function arguments only in having the first letter capitalized. That way, it's easy to make a typo, and that's exactly what happened: Name = Name.
Errors No. 3, No. 4. Copy-Paste.
private Task<SyntaxToken> GetNewTokenWithRemovedOrToggledPragmaAsync(....) { var result = isStartToken ? GetNewTokenWithPragmaUnsuppress( token, indexOfTriviaToRemoveOrToggle, _diagnostic, Fixer, isStartToken, toggle) : GetNewTokenWithPragmaUnsuppress( token, indexOfTriviaToRemoveOrToggle, _diagnostic, Fixer, isStartToken, toggle); return Task.FromResult(result); }
PVS-Studio diagnostic message: V3012 The '?:' operator, regardless of its conditional expression, always returns one and the same value. AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction_Pragma.cs 177
No matter what value 'isStartToken' refers to, the GetNewTokenWithPragmaUnsuppress() function is called with the same set of arguments. It seems that the function call was duplicated through Copy-Paste and the programmer forgot to edit the copy.
Here is another similar case:
private void DisplayDiagnostics(....) { .... _console.Out.WriteLine( string.Format((notShown == 1) ? ScriptingResources.PlusAdditionalError : ScriptingResources.PlusAdditionalError, notShown)); .... }
PVS-Studio diagnostic message: V3012 The '?:' operator, regardless of its conditional expression, always returns one and the same value: ScriptingResources.PlusAdditionalError. CommandLineRunner.cs 428
Errors No. 5, No. 6. Carelessness.
I haven't collected many statistics on typical mistakes made by C# programmers yet, but, besides ordinary typos, there is obviously one bug pattern that's in the lead. It has to do with casting a reference using the 'as' operator, and checking the source reference instead of the resulting one. Here's a synthetic example:
var A = B as T; if (B) A.Foo();
And this is how this bug looks in real-life code:
public override bool Equals(object obj) { var d = obj as DiagnosticDescription; if (obj == null) return false; if (!_code.Equals(d._code)) return false; .... }
PVS-Studio diagnostic message: V3019 Possibly an incorrect variable is compared to null after type conversion using 'as' keyword. Check variables 'obj', 'd'. DiagnosticDescription.cs 201
The next example is lengthier, but the problem is the same:
protected override bool AreEqual(object other) { var otherResourceString = other as LocalizableResourceString; return other != null && _nameOfLocalizableResource == otherResourceString._nameOfLocalizableResource && _resourceManager == otherResourceString._resourceManager && _resourceSource == otherResourceString._resourceSource && .... }
PVS-Studio diagnostic message: V3019 Possibly an incorrect variable is compared to null after type conversion using 'as' keyword. Check variables 'other', 'otherResourceString'. LocalizableResourceString.cs 121
Error No. 7. Double detection.
Sometimes a bug may trigger two, or even three, different warnings. Here's such an example:
private bool HasMatchingEndTag( XmlElementStartTagSyntax parentStartTag) { if (parentStartTag == null) { return false; } var parentElement = parentStartTag.Parent as XmlElementSyntax; if (parentStartTag == null) { return false; } var endTag = parentElement.EndTag; .... }
PVS-Studio diagnostic messages:
- V3019 Possibly an incorrect variable is compared to null after type conversion using 'as' keyword. Check variables 'parentStartTag', 'parentElement'. XmlTagCompletionCommandHandler.cs 123
- V3021 There are two 'if' statements with identical conditional expressions. The first 'if' statement contains method return. This means that the second 'if' statement is senseless XmlTagCompletionCommandHandler.cs 117
In the beginning of the function's body, the 'parentStartTag' argument is checked for null. If it is null, the function returns.
After that, the programmer wanted to check if the reference really points to a class of type 'XmlElementSyntax', but at this point, a typo sneaked in. Instead of 'parentElement', 'parentStartTag' is checked for the second time.
The analyzer detects two anomalies at once here. The first has to do with rechecking the value of 'parentStartTag' as it doesn't make sense, since the function has already returned if it was a null reference. The second deals with the analyzer's suspicions that a wrong variable might be checked after the 'as' operator.
The fixed version of that code should look like this:
if (parentStartTag == null) { return false; } var parentElement = parentStartTag.Parent as XmlElementSyntax; if (parentElement == null) { return false; }
Errors No. 8, No. 9. Copy-Paste.
Sorry for a long sample, but I didn't feel it is right to replace it with a synthetic one:
internal static bool ReportConflictWithParameter(....) { .... if (newSymbolKind == SymbolKind.Parameter || newSymbolKind == SymbolKind.Local) { diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name); return true; } if (newSymbolKind == SymbolKind.TypeParameter) { return false; } if (newSymbolKind == SymbolKind.Parameter || newSymbolKind == SymbolKind.Local) { diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name); return true; } .... }
PVS-Studio diagnostic message: V3021 There are two 'if' statements with identical conditional expressions. The first 'if' statement contains method return. This means that the second 'if' statement is senseless InMethodBinder.cs 264
In this code, the first and the third 'if' statements are the same. It's probably because the programmer copied a code block and forgot to change it. On the other hand, the duplicate 'if' might just be an extra line, and should be removed.
There was another code fragment like that, but don't worry, I won't make you read it. Just note the diagnostic message:
V3021 There are two 'if' statements with identical conditional expressions. The first 'if' statement contains method return. This means that the second 'if' statement is senseless WithLambdaParametersBinder.cs 131
Error No. 10. Incorrect condition.
public enum TypeCode { .... Object = 1, .... DateTime = 16, .... } static object GetHostObjectValue(Type lmrType, object rawValue) { var typeCode = Metadata.Type.GetTypeCode(lmrType); return (lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object) ? rawValue : null; }
PVS-Studio diagnostic message: V3022 Expression 'lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object' is always true. DkmClrValue.cs 136
The expression is pretty complicated, so here's the gist of it:
(typeCode != 1 || typeCode != 16)
This expression is always true, no matter what value the 'typeCode' variable refers to.
Error No. 11. Redundant condition.
public enum EventCommand { Disable = -3, Enable = -2, SendManifest = -1, Update = 0 } protected override void OnEventCommand( EventCommandEventArgs command) { base.OnEventCommand(command); if (command.Command == EventCommand.SendManifest || command.Command != EventCommand.Disable || FunctionDefinitionRequested(command)) .... }
PVS-Studio diagnostic message: V3023 Consider inspecting this expression. The expression is excessive or contains a misprint. RoslynEventSource.cs 79
Again, the main idea is this:
if (A == -1 || A != -3)
This expression is either incorrect or redundant and can be reduced to the following:
if (A != -3)
Error No. 12. Logging error
static CompilerServerLogger() { .... loggingFileName = Path.Combine(loggingFileName, string.Format("server.{1}.{2}.log", loggingFileName, GetCurrentProcessId(), Environment.TickCount)); .... }
PVS-Studio diagnostic message: V3025 Incorrect format. A different number of format items is expected while calling 'Format' function. Expected: 2. Present: 3. CompilerServerLogger.cs 49
The 'loggingFileName' variable is not used in any way in the call on function Format(). It doesn't look right.
Error No. 13, in error handler.
private const string WriteFileExceptionMessage = @"{1} To reload the Roslyn compiler package, close Visual Studio and any MSBuild processes, then restart Visual Studio."; private void WriteMSBuildFiles(....) { .... catch (Exception e) { VsShellUtilities.ShowMessageBox( this, string.Format(WriteFileExceptionMessage, e.Message), null, OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } }
PVS-Studio diagnostic message: V3025 Incorrect format. A different number of format items is expected while calling 'Format' function. Expected: 2. Present: 1. CompilerPackage.cs 105
An exception is very likely to be raised when the program tries displaying the Message Box. The reason is that the Format() function is trying to print the second additional argument which is absent.
I suspect that the constant format string should begin with the following:
@"{0}
Errors No. 14, No. 15, in error handler.
I can't agree with the statement that function DumpAttributes() is not used in any way for now. There are two bugs at once found in it, each of which triggers an exception:
private void DumpAttributes(Symbol s) { int i = 0; foreach (var sa in s.GetAttributes()) { int j = 0; foreach (var pa in sa.CommonConstructorArguments) { Console.WriteLine("{0} {1} {2}", pa.ToString()); j += 1; } j = 0; foreach (var na in sa.CommonNamedArguments) { Console.WriteLine("{0} {1} {2} = {3}", na.Key, na.Value.ToString()); j += 1; } i += 1; } }
PVS-Studio diagnostic messages:
- V3025 Incorrect format. A different number of format items is expected while calling 'WriteLine' function. Expected: 3. Present: 1. LoadingAttributes.cs 551
- V3025 Incorrect format. A different number of format items is expected while calling 'WriteLine' function. Expected: 4. Present: 2. LoadingAttributes.cs 558
In both calls on function WriteLine(), it receives fewer arguments than expected. As a result, FormatExceptions are raised.
Error No. 16. Dangerous expression.
I bet you'll just glance over the code below and skip it for good. It's excellent proof that we need those tireless code analyzers.
private static bool SymbolsAreCompatibleCore(....) { .... var type = methodSymbol.ContainingType; var newType = newMethodSymbol.ContainingType; if ((type != null && type.IsEnumType() && type.EnumUnderlyingType != null && type.EnumUnderlyingType.SpecialType == newType.SpecialType) || (newType != null && newType.IsEnumType() && newType.EnumUnderlyingType != null && newType.EnumUnderlyingType.SpecialType == type.SpecialType)) { return true; } .... }
PVS-Studio diagnostic message: V3027 The variable 'newType' was utilized in the logical expression before it was verified against null in the same logical expression. AbstractSpeculationAnalyzer.cs 383
To show what makes this code dangerous, here's a simple synthetic example based on it:
if ((A != null && A.x == B.y) || (B != null && B.q == A.w))
As you can see, the condition's logic implies that A and B may be null references. The expression consists of two parts: in the first part reference A is checked, but reference B isn't; in the second part reference B is checked, but reference A isn't.
This code may be lucky enough to stay runnable, but it does look strange and dangerous.
Errors No. 17, No. 18. Double assignments.
public static string Stringize(this Diagnostic e) { var retVal = string.Empty; if (e.Location.IsInSource) { retVal = e.Location.SourceSpan.ToString() + ": "; } else if (e.Location.IsInMetadata) { return "metadata: "; } else { return "no location: "; } retVal = e.Severity.ToString() + " " + e.Id + ": " + e.GetMessage(CultureInfo.CurrentCulture); return retVal; }
PVS-Studio diagnostic message: V3008 The 'retVal' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 324, 313. DiagnosticExtensions.cs 324
Notice how variable 'retVal' is assigned a value in one of the 'if' statement's branches, but is then assigned another value at the end of the function's body. I'm not sure, but the second assignment should probably be rewritten in the following way:
retVal = retVal + e.Severity.ToString() + " " + e.Id + ": " + e.GetMessage(CultureInfo.CurrentCulture);
Here is another similar case:
public int GetMethodsInDocument( ISymUnmanagedDocument document, int bufferLength, out int count, ....) { .... if (bufferLength > 0) { .... count = actualCount; } else { count = extentsByMethod.Length; } count = 0; return HResult.S_OK; }
PVS-Studio diagnostic message: V3008 The 'count' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 317, 314. SymReader.cs 317
The function returns a value by 'count' reference. In different parts of the function, 'count' is assigned different values. What doesn't look right is that 'count' is for some reason assigned 0 at the end of the function's body all the time. This is quite strange.
Error No. 19, in tests. Typo.
internal void VerifySemantics(....) { .... if (additionalOldSources != null) { oldTrees = oldTrees.Concat( additionalOldSources.Select(s => ParseText(s))); } if (additionalOldSources != null) { newTrees = newTrees.Concat( additionalNewSources.Select(s => ParseText(s))); } .... }
PVS-Studio diagnostic message: V3029 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 223, 228. EditAndContinueTestHelpers.cs 223
In the second condition, 'additionalNewSources' should be checked instead of 'additionalOldSources'. If the 'additionalNewSources' reference turns out to be null, an exception will be raised when trying to call function Select().
Error No. 20. Questionable.
I've not shown all the warnings output by the PVS-Studio analyzer, of course. There are lots of warnings that are obviously false positives, but there are even more cases where I'm simply not familiar with Roslyn well enough to tell if they are bugs or not. This is one such case:
public static SyntaxTrivia Whitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace( text, elastic: false); } public static SyntaxTrivia ElasticWhitespace(string text) { return Syntax.InternalSyntax.SyntaxFactory.Whitespace( text, elastic: false); }
V3013 It is odd that the body of 'Whitespace' function is fully equivalent to the body of 'ElasticWhitespace' function (118, line 129). SyntaxFactory.cs 118
Two functions have the same bodies. The analyzer doesn't like it, and neither do I. But I don't know the project well enough to be sure; this code may well be correct. So, I can only make an assumption: in the ElasticWhitespace() function, argument 'elastic', which equals 'true', should probably be used.
Error Nxx.
I hope you understand that I can't investigate every case like the one above in detail. I scan lots of projects, and I don't have much knowledge about each of them. That's why I discuss only the most evident errors in my articles. In this one, I've discussed 20 such bugs, but I suspect PVS-Studio found many more. This is why I encourage Roslyn developers to scan the project themselves, rather than relying solely on this article. The demo version won't be sufficient for this task, but we can grant a temporary registration key.
Comparison with ReSharper
I've written just a few articles on C# analysis, and have given only one conference talk at this point. But what I've already found, is that one question is asked all the time: "Do you have a comparison with ReSharper?"
I don't like this for two reasons. Firstly, these tools belong to different fields. PVS-Studio is a typical code analyzer designed for bug searching. ReSharper is a productivity tool designed to facilitate programing, and capable of generating a large set of recommendations.
PVS-Studio and ReSharper employ totally different approaches to many aspects. For example, PVS-Studio comes with documentation with detailed descriptions for each diagnostic, accompanied by examples and advice on corrections. ReSharper claims to apply "1400 code inspections in C#, VB.NET, XAML, XML, ASP.NET, ASP.NET MVC, Razor, JavaScript, TypeScript, HTML, CSS, ResX". The figure 1400 does look impressive, but it doesn't actually tell you anything. The descriptions of all these code inspections are probably somewhere out there, but personally I failed to find them. How can I compare our tool with ReSharper when I can't even know what errors in particular ReSharper can detect in C# applications?
Secondly, any comparison we could offer would be knocked. We've already been through such an experience before, and sworn off doing any such comparisons again. For example, we carried out a thorough comparison of PVS-Studio with Cppcheck and Visual Studio SCA once, and it took us lots of time and effort. The results were presented in brief and detailed versions. After that, there was probably no programmer left who hadn't criticized us for doing everything wrong, or accused us of being biased, and that it was unfair to choose these projects for comparison. So we see no point in wasting time on a comparison. No matter how thorough and honest it was, one could always label it biased.
However, I still have to answer the question if we are in any way better than ReSharper. And I have an answer.
Do you use ReSharper? Nice. Now install PVS-Studio and see if it can find bugs in your project!
Conclusion
I suggest without further delay, download PVS-Studio and running it on your projects. You've got warnings? But your code is quite runnable, isn't it? The bugs you've found are most likely inhabiting rarely used code areas because in frequently used ones, you had them fixed long ago, though hard and painfully. Now imagine how much effort you could save using PVS-Studio regularly. Of course, it can't catch all the bugs. But instead of wasting time hunting typos and slip-ups, spend it on something more worthwhile, and let PVS-Studio take care of those silly mistakes.
P.S. You don't make silly mistakes? Well, well! It only seems you don't. Everyone does - just have a look here. | http://www.viva64.com/en/b/0363/ | CC-MAIN-2016-22 | refinedweb | 3,704 | 50.63 |
Table of Contents
- Controlling a Solver via GAMS Options
- The Solver Options File
- Starting Point and Initial Basis
- Solve trace
- Branch-and-Cut-and-Heuristic Facility (BCH)
- Choosing an appropriate Solver
For the novice GAMS user, solver usage can be very simple: one runs the model and inspects the listing file to see what the solution is. No knowledge of solver options or solver specific return codes is required. While this is enough for some users, most will quickly find they need some basic knowledge of how to control the solver and interpret the results. Section Controlling a Solver via GAMS Options describes how to set the GAMS options that control a solver. Further, most solvers allow the user to set additional, solver-specific options. These can be set via a solver specific options file, which will be discussed in Section The Solver Options File. However, use of generic GAMS options should be prefered, since a GAMS option setting applies to all solvers and is interpreted by the solvers in a consistent way.
A number of solvers can make use of an initialization of variable and equation values. This will be discussed in Starting Point and Initial Basis.
Further solver specific topics, which are more interesting for advanced users, are discussed in the Sections Solve trace and Branch-and-Cut-and-Heuristic Facility (BCH).
For some hints on how to select a solver, see Choosing an appropriate Solver.
Controlling a Solver via GAMS Options
GAMS options can be set on the GAMS command line, e.g.,
$ gams trnsport iterlim = 100
Additionally, they can be set by an option statement within a GAMS model, e.g.,
option iterlim = 100;
Finally, a model attribute can set a GAMS option for an individual model:
mymodel.iterlim = 100;
The model suffix takes precedence over the option statement, which takes precendence over the command line parameters. If none of these methods is used to set an option, default values apply.
Further, one can unset any model-specific option by assigning it the value
NA:
mymodel.iterlim = NA;
Unfortunately, not every option can be via as command line parameter, option statement, and model attribute. We refer to
- Solver-Related Options for the list of solve-related options that can be set via the command line,
- Options that Control Solver-Specific Parameters and Options that Control the Choice of Solver for the list of solve-related options that can be set via the option statement, and
- Model Attributes Mainly Used Before Solve for the list of solve-related model attributes.
The Solver Options File
To specify solver-specific options, it is necessary to use a solver option file. Two things are required to do this: one must create an option file having a proper name, and one must tell the solver to read and use this option file.
To tell a solver to use an option file, one can set the
optfile model attribute or the optfile option to a positive value. For example,
model mymodel /all/; mymodel.optfile = 1; solve mymodel using nlp maximizing dollars;
The option file takes its name from the solver being used:
solvername.XYZ, where
solvername is the name of the solver that is specified, and the suffix
XYZ depends on the value to which
optfile has been set. If its value is 1, the suffix is
opt. For example, the option file when calling CONOPT would be called
conopt.opt. See the documentation on optfile for more information.
The format of the options file can change marginally from solver to solver. The following illustrates some frequent features of the option file format. However, solvers may vary from this format. Thus, the solver-specific documentation should be checked before using an option file.
- Blank lines in an option file are ignored.
- A comment line might begin with an asterisk (
*) in the first column, is not interpreted by either GAMS or the solver, and is used purely for documentation.
- Each non-comment line contains only one option specification.
- The format for specifying options is as follows:
keyword(s) [modifier] [value]The keyword may consist of one or more words and is not case sensitive. The value might be an integer, a real, or a string. Real numbers can be expressed in scientific format, e.g., 1e-6. Note that not all options require modifiers or values.
- Any errors in the spelling of keyword(s) or modifiers will lead to that option being misunderstood and therefore ignored. Errors in the value of an option can result in unpredictable behavior. When detected, errors are either ignored or pushed to a default or limiting value, but not all can or will be detected.
Consider the following CPLEX options file,
* CPLEX options file barrier crossover 2
The first line begins with an asterisk and therefore contains comments. The first option specifies the use of the barrier algorithm to solve the linear programming problem, while the second option specifies that the crossover option 2 is to be used. Details of these options can be found in Summary of CPLEX Options.
Consider the following MINOS options file,
* MINOS options file scale option 2 completion partial
The first option sets the scale option to a value of 2. In this case, the keyword
'scale option' consists of two words. In the second line, the
completion option is set to
partial. Details of these options can be found in Summary of MINOS Options.
Dot Options
Dot options in a solver option file allow users to associate values to variables and equations using the GAMS name of the variables and equations. The general syntax of a dot option in the option file is as follows:
(variable/equation name).optionname (value)
Dot options can be specified for
all, a
block, a
slice, and a
single variable and equation. Please note that a specific dot option may only apply to variables or equations (e.g. the GAMS/Gurobi dot option prior applies to variables only). The following example makes the use of the dot option clear.
For example, suppose one has a GAMS declaration:
Set i /i1*i5/; Set j /j2*j4/; Variable v(i,j); Equation e(i,j);
Consider the following lines in an option file with the imaginary option name
dotopt:
The values of the dot option are applied in correspondence to the sequence in which they appear in the option file. In the current example, the values of
dotopt for the equation
e would be as follows:
Starting Point and Initial Basis
Starting Point
NLP solvers that search for a locally optimal solution of a NLP require an initial point to start their search. Further, as closer this initial point is to a local optimum, the less effort the solver may have to spend. The latter can also be true for solvers that search for global optimal solutions, such as most LP or MIP solver or global MINLP solvers.
Because of this immense importance of a starting point, GAMS always passes a starting point to a solver. By default, the point passed on by GAMS is given by the level and marginal attributes of variables and equations. If these values have not been set yet, default values are used. This default value is zero, except for variables which bounds would forbid this value. In this case, the bound closest to zero is used.
Next to setting these values explicitly in a GAMS model, a user can also load them from a save file or a GDX point file via execute_loadpoint. The latter may have been generated by running a related model and using option savepoint. Further, in models with several solve statements, the solution from one solve, if any, is used to initialize the starting point for a succeeding solve. This happens automatically since solutions from a solve statements are also stored in the level and marginal values of variables and equations. Finally, note that model attribute defpoint can be used to force sending the default starting point to a solver.
For some solvers, in particular for MIP or MINLP, an option may have to be set to make use of the starting point. Further, some solvers offer the possibility to make use of a partial starting point or use the starting point as a guide for the search. For details, see the specific solver manuals and look for parameters like
mipstart and the use of the GAMS parameter tryint.
Initial Basis
While for some solvers, the values of a starting point are sufficient to initialize the search, active-set based algorithms make use of a different form of starting information. An active-set based algorithms tries to identify which constraints are active (or binding) in a feasible or optimal solution, that is, which variable are at one of their bounds (if any) and for which equations the activity equals to the right-hand-side. For linear programs, the simplex algorithm is such an algorithm. The classifications of constraints into active and inactive ones is called a basis. Active constraints are called nonbasic and inactive constraint are called basic. A basis that specifies the active constraints in an optimal solution is called an optimal basis.
Active-set based algorithms may start by guessing an initial basis and then iteratively update this basis by switching the basic-status of constraints until an optimal basis is found. Therefore, solution time may be reduced substantially if one can identify a priori a good approximation of an optimal basis. Such a user-provided initial basis is also called an advanced basis. However, provision of an advanced basis does not always help. Especially presolving algorithms in a solver may cause that a user provided initial basis is ignored. Further, solvers may perform poorly when the given basis is "worse" than what the solver would otherwise have constructed with its own heuristics. Finally, it is needless to say that only active-set based algorithms are amenable to the use of an initial basis.
If sufficient information is available in the starting point, then GAMS uses these values to automatically form an initial basis for a solver. This basis is formed as follows:
- Variables with a zero level value are suggested to be nonbasic, if and only if they have a non-zero marginal value.
- Variables with a non-zero level value are suggested to be nonbasic, if and only if the level value equals to one of the variable bounds. As a variable at one of their bounds indicates that the bound may be binding, nonbasic variables should also have non-zero marginal.
- Equations with non-zero marginal are suggested to be nonbasic. Otherwise, they are suggested to be basic.
Next, GAMS decides whether the so formed basis contains sufficiently many nonbasic entries. It does so by checking whether the number of nonbasic entries in the basis exceeds the number of equations times the value of GAMS option bratio. Thus in a problem with 1000 equations and with the default value of
bratio (0.25), GAMS will not suggest a basis unless it could find at least 250 nonbasic constraints.
Note, that the default starting point is usually not sufficient for the construction of an initial basis. If the automatic transfer of a basis from one solve statement to the next leads to poor behavior in the solver, setting the option bratio to 1 or the model attribute defpoint to 1 can suppress the use of an initial basis.
A user can also attempt to explicitly provide an initial basis by setting a corresponding starting point. That is, one can set a guess for an initial basis by specifying
- non-zero marginals for equations that are felt to be active in a solution
- non-zero marginals for variables that are felt to be at their bound in a solution
- non-zero levels for the variables that are felt to be non-zero in a solution
Solve trace
In order to do accurate performance evaluations it may be useful to obtain more detailed information about a solve than the "end data" that the trace file provides. E.g., for a branch-and-bound based solver, one may want to have intermediate information about the values of primal and dual bounds at the root node and subsequent nodes within the search.
The solve trace option that is implemented in some of the GAMS solver interfaces allows users to output solve information, e.g., primal and dual bounds, for every
n nodes or at every time step. For example, the user may be interested in the objective value of the incumbent solution or the best dual bound on the optimal value every 50 nodes and every five seconds of the solve.
- Note
- The solve trace file format and options may change in a future GAMS release.
The solve trace option is invoked via a GAMS solver options file. Usually, options to specify a filename of the trace file to be created and options to specify time and node intervals are available. Please refer to the GAMS solver manuals for the exact names of these options (search for
solvetrace or
miptrace).
The solve trace file is written in comma-separated-value (CSV) format, where the entries in each line have the following meaning:
A sample solve trace file is miptrace.mtr where the file includes statistics of a GAMS run using the MIP model blend2 from the Performance Library and the solver XPRESS. See also the slides for the presentation Advanced Use of GAMS Solver Links (2013) for some ideas on what to do with the solve trace functionality.
Branch-and-Cut-and-Heuristic Facility (BCH)
Global search algorithms can sometimes significantly benefit from user supplied routines that support the solution process of an hard optimization problem. For example, branch-and-cut solvers (e.g., CPLEX, Gurobi, SCIP, Xpress) can profit from user-supplied cutting planes or good feasible solutions. GAMS users could supply these as part of the model given to the solver, by adding a set of constraints representing likely to be violated cuts and an initial solution (possibly in combination with GAMS parameters like tryint and solver-specific options like mipstart in CPLEX). However, this does not allow a dynamic interaction between a running solver and user supplied routines that, for example, use a current relaxation solution to construct cutting planes or feasible solutions. The GAMS Branch-and-Cut-and-Heuristic (BCH) facility attempts to automate all major steps necessary to make callbacks that certain solvers provide for such usage available to the GAMS user. This allows GAMS users to apply complex solution strategies without having to have intimate knowledge about the inner workings of a specific solver.
Currently, only two solvers support the BCH facility: CPLEX and SBB. With GAMS/CPLEX, user supplied GAMS programs that implement primal heuristics and cut generation can be used. With SBB, only primal heuristics are possible.
As the name indicates, the BCH facility has been designed with the solving process of a branch-and-cut solver (e.g., CPLEX, Gurobi, SCIP, Xpress) in mind. Such solvers often allow to call a user supplied routine after a node in the branch-and-bound (B&B) tree has been processed. Within that routine, available information like the solution of a relaxation (often an LP or NLP) at that node and the current incumbent, if any, is exported by the BCH facility into a GDX file using the original GAMS namespace. Next, different user supplied GAMS programs can be called, e.g., for finding cuts which are violated by the relaxation solution (cut generator) or to find new incumbents (primal heuristic). These GAMS programs should import the information from the GDX file and do their computations. After termination, the BCH facility resumes control, reads the findings from the GAMS program and passes them to the solver.
A relaxation solution may be exported into a file
bchout.gdx by the BCH facility. This GDX file does not only contain the variable values as level values (
.l), but also variable bounds (
.lo and
.up). For a B&B solver, these are the local bounds at this node. Hence, they reflect branching decisions made in the B&B tree and bound tightenings that were deduced by the solver. In a similar way, the BCH facility may export an incumbent solution to the GDX file
bchout_i.gdx. The bounds for the incumbent solution reflect global bounds, i.e., the original bounds, possibly tightened by the solver. GDX files can be imported by the GAMS program using the compile time $load or run time execute_load.
The BCH facility is activated and controlled by setting certain options in the solvers options file. The precise names and meanings of the options may vary from one solver to another. Therefore, also the corresponding GAMS solver manual should be checked. The options that come with the BCH facility can be used to define the calls of the users GAMS programs, to determine when they should be called, and to overwrite the filenames for the GDX files (to avoid name clashes). General BCH related options are the following:
In the following, the interface for the available callbacks are explained in more detail and corresponding options are listed.
Primal Heuristics
In the primal heuristic callback, the user can provide a GAMS program which tries to construct a feasible solution based on the information provided by the solver, e.g., a current relaxation solution and the current incumbent. Thus, the GAMS program could attempt to repair infeasibilities in the relaxation solution or try to improve the incumbent from the solver.
If the GAMS program finds a new solution, it should store it in the level values of variables that correspond to the original variables. For example, if the original model uses binary variable
open(i,t), then at the end of the GAMS program
open.l(i,t) should contain a 0 (zero) or a 1 (one). The BCH facility calls the GAMS program and instructs GAMS to store the results in a GDX file at termination. This GDX file is then read in again by the BCH facility and the solution is passed back to the solver. The solver checks this solution for infeasibilties and in case this check is passed and the solution is better than the best known solution, the solver updates it's incumbent.
If the GAMS program cannot find a feasible solution, it can terminate with an execution error triggered by an abort statement to prevent the BCH facility from reading the results from the heuristic run.
BCH parameters to control the primal heuristic call are typically the following:
As an example, for the Oil Pipeline Network Design problem, the BCH options to invoke the primal heuristic in the GAMS program
bchoil_h.inc when using GAMS/CPLEX could be
userheurcall bchoil_h.inc mip cplex optcr 0 reslim 10 userheurfirst 5 userheurfreq 20 userheurinterval 1000
Cutting Planes
In the cut generator callback, the user can provide a GAMS program which tries to find a linear cut (that is, a linear inequality) that is violated by the relaxation solution. The solver would then add these cuts to it's cut pool. Typically, it then resolves the relaxation at the node and calls the cut generator again. If no cutting planes are found, the solver will continue, e.g., by processing the next node. Please note that the solver cannot perform validity checks on the provided cuts. Hence, it is possible to cut off areas of the feasible region, including optimal solutions.
Exporting cuts is a little more complicated than a solution because next to the cut coefficients, also the sense and the right-hand-side of the cut inequality needs to be exported. Further, exporting several cuts with one call should be possible. For this purpose, the GAMS program has to define and fill a set
cc and parameters
numcuts,
rhs_c(cc), and
sense_c(cc) appropriately. The set
cc is used as a cut index. It can be larger than the number of actually generated cuts. Parameter
numcuts should specify the number of added cuts.
rhs_c(cc) should store the right-hand-side of each cut. Finally,
sense_c(cc) should store the sense of each cut, which must be 1 for lower-equal (≤), 2 for equal (=, rather unusual for cuts), and 3 for greater-equal (≥). The corresponding declaration in GAMS code may be
$set MaxCuts 100 Set cc 'cuts' / 1 * %MaxCuts% /; Parameters numcuts 'number of cuts to be added' / 0 / rhs_c(cc) 'cut rhs' sense_c(cc) 'the sense of the cuts';
The only thing missing are the cut coefficients. As it should be possible to return more than one cut, using variable attributes like level values is not sufficient. Therefore, for each variable that is part of a cut, a new parameter must be added in the GAMS program. The name of the parameter must be the name of the corresponding variable with an additional
_c at the end. Further, the parameter must be indexed like the variable, but with the cut index set cc added at the beginning. For example, assume variable
open(i,t) should be part of a cut. Then the cut coefficients should be stored in a parameter
open_c(cc,i,t), e.g.,
Parameter open_c(cc,i,t) 'coefficients of variable open(i,t) in cut cc';
The BCH facility reads all parameters that end in
_c, takes the base name and looks for a variable with that name and indicies and builds up the cut matrix. A cut cannot introduce a new variable into the model. All cuts added to the model are assumed to be global cuts, that is, they need to be valid for the entire problem, not just for the current node.
BCH parameters to control the cut generation call are typically the following:
As an example, for the Oil Pipeline Network Design problem, the BCH options to invoke the cut generator in the GAMS program
bchoil_c.inc when using GAMS/CPLEX could be
usercutcall bchoil_c.inc mip cplex usercutfirst 0 usercutfreq 0 usercutnewint yes
Incumbent Callbacks
The incumbent callbacks can be used to execute a GAMS program when the solver found a new feasible solution that improves the incumbent. Additionally, the incumbent check callback
UserIncbCall can be used to notify the solver whether the given feasible solution should be accepted by the solver. This allows to implement a filtering mechanism that forces a solver to search for additional solutions even though an optimal solution might have been found already.
The following parameters control the incumbent callbacks:
Examples
The GAMS model library contains a few examples to show to use the BCH facility:
- bchtlbas.gms : Trim Loss Minimization with Heuristic using BCH Facility This model implements a very simple LP/MIP based primal heuristic for the trimloss minimization problem.
- bchfcnet.gms : Fixed Cost Network Flow Problem with Cuts using BCH Facility This model implements simple but difficult to separate cuts for a network design problem. The global solver BARON is used to find violated cuts by solving a non-convex MINLP.
- bchmknap.gms : Multi knapsack problem using BCH Facility This model implements simple cover inequalities for the multi-knapsack problem.
- bchoil.gms : Oil Pipeline Design Problem using BCH Facility This is the most complex example. It implements three different primal heuristics: an initial heuristic based on a simplified cost structure, a rounding heuristic, and a local branching heuristic. In addition, complex cuts are generated by solving regionalized versions of the original problem.
- dicegrid.gms : MIP Decomposition and Parallel Grid Submission - DICE Example This example uses many of the UserJobID option to rename files, since running multiple jobs in parallel requires the use of different filenames. This example also uses the incumbent reporting call UserIncbICall.
- solnpool.gms : Cplex Solution Pool for a Simple Facility Location Problem This example uses the incumbent checking call UserIncbCall as an advanced filter for accepting or rejecting solutions found by CPLEX.
Choosing an appropriate Solver
For any of the GAMS problem classes (LP, MCP, MINLP, ...), there is no solver that is best on every problem instance. Below, we provide some links to rules of thumb on choosing a solver or solver comparisons.
- T. Koch, T. Achterberg, E. Andersen, O. Bastert, T. Berthold, R. Bixby, E. Danna, G. Gamrath, A. Gleixner, S. Heinz, A. Lodi, H. Mittelmann, T. Ralphs, D. Salvagnin, D. Steffy, K. Wolter, MIPLIB 2010, Mathematical Programming Computations, 3:2 (2011) 103-163. preprint
- M. Bussieck and S. Vigerske, MINLP Solver Software.
- SNOPT vs. IPOPT: P. Gill, M. Saunders, E. Wong, On the Performance of SQP Methods for Nonlinear Optimization, 2015
- H. Mittelmann: Decision Tree for Optimization Software and Benchmarks for Optimization Software
Relative Merits of MINOS and CONOPT
How to choose between MINOS and CONOPT
It is almost impossible to predict how difficult it is to solve a particular model. The best and most reliable way to find out which solver to use is to try out both. However, there are a few rules of thumb:
CONOPT is well suited for models with very non-linear constraints. If you experience that MINOS has problems achieving feasiblity during the optimization, you should try CONOPT. On the other hand, if your model has few nonlinearities outside the objective function, MINOS and QUADMINOS is probably the best solver.
CONOPT is has a fast method for finding a first feasible solution that is particularly well suited for models with few degrees of freedom (this means: the number of variables is approximately the same as the number of constraints - in other words, models that are almost square). In these cases CONOPT is likely to outperform MINOS while for models with many more variables than equations MINOS is probably more suited.
CONOPT has a preprocessing step in which recursive equations and variables are solved and removed from the model. If you have a model where many equations can be solved one by one, CONOPT will take advantage of this property. Similarly, intermediate variables only used to define objective function terms are eliminated from the model and the constraints are moved into the objective function.
CONOPT has many built-in tests (e.g. tests for detecting poor scaling). Many models that can be improved by the modeler are rejected with a constructive message. CONOPT is therefore a useful diagnostic tool during model development even if another solver is used for the production runs.
Why serious NLP modelers should have both MINOS and CONOPT
It is almost impossible to predict how difficult it is to solve a particular model. However, if you have two solvers, you can try both. The overall reliability is increased and the expected solution time will be reduced.
On a test set of 196 large and difficult models, many poorly scaled or without initial values, both MINOS and CONOPT failed on 14 models. However only 4 failed on both MINOS and CONOPT. So the reliability of the combined set of solvers is much better than any individual solver.
Many examples of poorly formulated models were observed on which MINOS failed. CONOPT rejected many of the models, but with diagnostic messages pinpointing the cause of the problem. After incorporating the changes suggested by CONOPT, both MINOS and CONOPT could solve the model. Switching between the two solvers during the initial model building and debugging phase can often provide useful information for improving the model formulation.
Special Offer for two NLP Solvers
In order to encourage modelers to have two NLP solvers, GAMS offers a 50% discount on the second solver when both MINOS and CONOPT are purchased together.
PATH versus MILES
This document describes some of the differences between the MCP solvers PATH 4.7 and MILES. MILES is a free solver, that comes with the GAMS/BASE module, while PATH is an optional solver, that is charged for separately.
PATH and MILES are two GAMS solvers capable of solving mixed nonlinear complementarity problems (MCP). Both solvers are based on the sequential linear complementarity algorithm, i.e., they both solve a sequence of linear mixed complementarity problems whose solutions typically converge to the solution of the MCP. To solve each of the linear subproblems (major iterations), both codes use a generalization of an algorithm due to Lemke that is based on a sequence of pivots (minor iterations) similar to those generated by the simplex method for linear programming. To do these pivots efficiently, both codes use the same sparse linear algebra package.
As a result of the above similarities, the performance of the two codes is comparable for many "easy" models. Viewed over a broad range of problems, however, PATH is typically faster and more robust than MILES. While both codes solve all the MCP and MPSGE models in GAMSLIB, PATH signicantly outperforms MILES on the MCPLIB test collection found at CPNET.
Most sophisticated MCP and MPSGE modelers prefer to use PATH over MILES. PATH has a crashing scheme that allows it to quickly improve the user given starting point before starting to solve the linear subproblems. This frequently speeds up solution time. PATH automatically attempts to fix "singular" models using a technique based on proximal perturbations. In many cases, this enables the linear subproblems to be solved, leading to a model solution. This typically helps modelers at model development time.
PATH has many more solution options to enable it solve difficult models. The code automatically tries useful options on difficult problems using a restart procedure. PATH has a much more sophisticated "globalization" procedure that typically improves speed and robustness. PATH implements a nonmonotone watchdog technique. Stalling is frequently circumvented by allowing larger steps to be taken toward solutions.
PATH has many more diagnostic features that help uncover problems in a model. In particular, singularities in the model, zero rows and columns and several measures of optimality are returned to the user. Theoretically, PATH has better convergence properties than MILES. In particular, new merit functions are known to allow more reliable and faster convergence. | https://www.gams.com/latest/docs/UG_SolverUsage.html | CC-MAIN-2019-04 | refinedweb | 4,982 | 52.19 |
Step-by-step
Get an ESP32
The ESP32 is a souped up version of the ESP8266 microcontroller that took the MCU/IoT hobbyist world by storm in 2016. The ESP32 has a faster and dual core processor, more memory, more I/O, and supports Bluetooth as well as WiFi. However getting hold of one since its release in September has been like finding hens teeth. Thats starting to change now and a variety of boards are becoming available through the usual retail channels.
This recipe should work with any ESP32 module. The dev style boards with built-in USB are easiest to get going with. Here I'm using an ESP32 Thing from Sparkfun.
Get the Arduino IDE and add the ESP32 extensions
To create your development environment you need to (1) get the Arduino IDE, (2) install the ESP32 extensions into the IDE, and also (3) add the MQTT library.
1) Get the Arduino IDE from here. Any not too old release should work if you already have this installed. I've been testing this recipe using 1.6.12.
(2) Install the ESP32 extensions for the Arduino IDE. Presently the ESP32 extensions have not had an official release and are not available via the Arduino Board manager, so you need to install these manually from the Github repository. Follow the instructions here, its actually pretty straight forward and worked right away with no hitches for me.
(3) Add the MQTT library. The recipe in this sketch uses MQTT to communicate with the Watson IoT Platform, so you need to add the MQTT library to the Arduino IDE. This is using the PubSubClient by Nick O'Leary, its the standard Arduino MQTT library and works fine on the ESP32. To install it, in the Arduino IDE goto the menu bar “Sketch” -> “Include Library” -> “Manage Libraries…” to bring up the Library Manager and then in the “Filter your search…” box enter PubSub. Select the entry and click “Install”.
Thats you're ready to go programming the ESP32. You can select your ESP32 from the Arduino IDE menu bar “Tools” -> “Board” -> “ESP32 Dev Module” as shown here:
Program the ESP32 with this sketch
Copy and paste the following sketch into the Arduino IDE and update the bits inbetween the “Customise these values” lines. As a minimum all you need to change is your WiFi SSID and password and then it will use the Watson Quickstart service with a DeviceId of “Test1”, or if you have registered you own organisation and devices you can update from the quickstart defaults to use your own device:
/**
* Helloworld style, connect an ESP32 to IBM's Watson IoT Platform
*
* Author: Anthony Elder
* License: Apache License v2
*/
#include <SPI.h>
#include <WiFi.h>
#include <PubSubClient.h>
//-------- Customise these values -----------
const char* ssid = "<yourWifiSSID>";
const char* password = "<yourWifiPassword>";
#define ORG "quickstart" // your organization or "quickstart"
#define DEVICE_TYPE "esp32" // use this default for quickstart or customize to your registered device type
#define DEVICE_ID "test1" // use this default for quickstart or customize to your registered device id
#define TOKEN "<yourDeviceToken>" // your device token or not used with "quickstart"
//--------, wifiClient);
void setup() {
Serial.begin(115200); delay(1); Serial.println();
initWiFi();
}
void loop() {
if (!!!client.connected()) {
Serial.print("Reconnecting client to "); Serial.println(server);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
String payload = "{ \"d\" : {\"counter\":";
payload += millis()/1000;
payload += "}}";
Serial.print("Sending payload: "); Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}
delay(3000);
}
void initWiFi() {
Serial.print("Connecting to "); Serial.print(ssid);
if (strcmp (WiFi.SSID().c_str(), ssid) != 0) {
WiFi.begin(ssid, password);
}
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(""); Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
Click the Upload button in the Arduino IDE and the sketch will be compiled and uploaded to the ESP32. Depending on your ESP32 module you may need to reset and manually set the ESP32 into upload flashing mode however the ESP32 Thing board I have works seamlessly with auto reset.
Have the Serial Monitor window open and you should see the sketch running right away:
View the published data at Watson
To view the data being published to Watson go to this url:
(in that URL the “test1” portion matches the DEVICE_ID definition from the sketch, if you have modified that name or are using your own Watson organisaition and device then update the URL accordingly)
Thats it!
So thats how easy it is to get going with using the ESP32 with the Watson IoT platform.
The ESP32 is a powerful MCU with many advanced capabilities that can be usefully combined with Watson platform – a remote sensor device with many I/O functions, but also exciting possibilities as a powerful gateway device combining WiFi and Bluetooth enabling connecting very low power BLE sensors to Watson without needing a complex gateway computer.
Stay tuned for more more developerWorks ESP32 recipes demonstrating these and other capabilities.
2 Comments on "Connect an ESP32 to the Watson IoT Platform!"
Note that as identified by ccfoo242 presently in the very lastest ESP32/Arduino code in github this example now fails with errno 88, see.
Simplest way to avoid that for now is to revert to an earlier revision, eg e77ec63 –
The “errno 88” problem has been fixed now in Github so the sketch in this recipe should be working fine again with the latest ESP32 Github code. | https://developer.ibm.com/recipes/tutorials/connect-an-esp32-to-the-watson-iot-platform/ | CC-MAIN-2017-04 | refinedweb | 909 | 53.92 |
13 April 2012 06:40 [Source: ICIS news]
(recasts lead, adds details throughout)
?xml:namespace>
On a year-on-year basis, the country’s export growth fell to 8.9% in March, compared with the 18.4% increase in the previous month.
Despite the slowdown, analysts said
“Though headline export growth will continue to moderate – compared with last year’s annualised 20.6% – the strength of
The country’s industrial output grew by 11.6% year on year in the three months to March, with total retail sales for the period up by 10.9% year on year, the National Bureau of Statistics (NBS) said.
The country recorded a 3.6% year-on-year rise in its consumer price index (CPI) and a 0.3% decline in its producer price index (PPI) in March.
“
“The country should concentrate on [its] macro policy and monetary policy and help to build investors’ confidence,” Ding added.
Citigroup economist Shen Minggao said: “
“It may take some time for the market to accept that
“It is likely that from now on, [China’s] macroeconomic policy will be geared towards resolving structural imbalances as opposed to generating short-term growth catalysts – unless the global economy collapses, of course,” it added.
($1 = €0.76)
With additional reporting by Rachel Y | http://www.icis.com/Articles/2012/04/13/9549948/chinas-gdp-growth-slows-to-8.1-in-first-quarter-of-2012.html | CC-MAIN-2014-49 | refinedweb | 213 | 65.83 |
Here is a little Bayesian Network to predict the claims for two different types of drivers over the next year, see also example 16.16 in [1].
Let’s assume there are good and bad drivers. The probabilities that a good driver will have 0, 1 or 2 claims in any given year are set to 70%, 20% and 10%, while for bad drivers the probabilities are 50%, 30% and 20% respectively.
Further I assume that 75% of all drivers are good drivers and only 25% would be classified as bad drivers. Therefore the average number of claims per policyholder across the whole customer base would [2]. I start with the contingency probability tables for the driver type and the conditional probabilities for 0, 1 and 2 claims in year 1 and 2. As I assume independence between the years I set the same probabilities. I can now review my model as a mosaic plot (above) and as a graph (below) as well.
Next, I set the client’s evidence (0 claims in year one and 1 claim in year two) and propagate these back through my network to estimate the probabilities that the customer is either a good (73.68%) or a bad (26.32%) driver. Knowing that a good driver has on overage 0.4 claims a year and a bad driver 0.7 claims I predict the number of claims for my customer with the given claims history as 0.4789.
Alternatively I could have added a third node for year 3 and queried the network for the probabilities of 0, 1 or 2 claims given that the customer had zero claims in year 1 and one claim in year 2. The sum product of the number of claims and probabilities gives me again an expected claims number of 0.4789.
References
[1] Klugman, S. A., Panjer, H. H. & Willmot, G. E. (2009), Loss Models: From Data to Decisions, Wiley Series in Proability and Statistics.
[2] Søren Højsgaard (2012). Graphical Independence Networks with the gRain Package for R. Journal of Statistical Software, 46(10), 1-26. URL] Rgraphviz_2.6.0 gRain_1.2-2 gRbase_1.6-12 graph_1.40.0
loaded via a namespace (and not attached):
[1] BiocGenerics_0.8.0 igraph_0.6.6 lattice_0.20-24 Matrix_1.1-0
[5] parallel_3.0.2 RBGL_1.38.0 stats4_3.0.2 tools_3... | http://www.r-bloggers.com/predicting-claims-with-a-bayesian-network/ | CC-MAIN-2016-07 | refinedweb | 393 | 72.46 |
It would be great to expose the pccount stats in order to build browser/chrome coverage tools.
Created attachment 560603 [details] [diff] [review]
Work-in-progress/Proof-of-Concept patch for Code Inspector demo.
Created attachment 572744 [details] [diff] [review]
WIP (f8d66a792ddc)
Add hooks for starting and stopping PC count profiling, keeping track of the counts accumulated while profiling (at a runtime granularity) and getting count information for the profiled scripts.
var utils = this.contentWindow.QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIDOMWindowUtils);
utils.startPCCountProfiling();
utils.stopPCCountProfiling();
var count = utils.getPCCountScriptCount();
var json = utils.getPCCountScriptSummary(i);
var json = utils.getPCCountScriptContents(scriptIndex);
utils.purgePCCounts();
startPCCountProfiling discards all JIT code in the runtime and does any recompilation with PC counters on the scripts, stopPCCountProfiling also discards all code and interns all profiled scripts and associated counts in a big array which is wiped by purgePCCounts and queried by the other two methods.
getPCCountScriptSummary gets a small bit of JSON for the script (name, aggregate counts for help in sorting), getPCCountScriptContents gets detailed JSON for the opcodes in the script, pretty-printed decompilation of the script's code (in many cases web JS is minified, so pretty printing is necessary) and information to identify the precise location in the decompiled code of opcodes (needs more work).
(I'm guessing there is a better interface to hang this than nsIDOMWindowUtils, but I don't know these interfaces at all).
Created attachment 572746 [details]
screen shot
Screen shot from a mockup based on CodeInspector, using these hooks to sort scripts by JIT activity and pick out hot expressions in each one.
Oh, code for the mockup above will be on GitHub soon (once I figure out how to make new projects).
(In reply to Brian Hackett from comment #4)
> Oh, code for the mockup above will be on GitHub soon (once I figure out how
> to make new projects).
Nice!
Maybe you could fork CodeInspector so that we can work together on it via pull requests exchanges? :)
(In reply to Cedric Vivier [cedricv] from comment #5)
> Nice!
> Maybe you could fork CodeInspector so that we can work together on it via
> pull requests exchanges? :)
Cool, I forked CodeInspector to the link below and committed the changes I made.
Created attachment 574478 [details] [diff] [review]
WIP (920c5da54a5c)
Rework things to compute offsets in the decompiled text for all expressions, not just top level ones. Makes addon integration a good deal simpler. Mostly done.
Created attachment 575316 [details] [diff] [review]
patch (920c5da54a5c)
Created attachment 575981 [details] [diff] [review]
PCCount interface changes
Splitting this patch up for review.
Steve, this part has the API hooks for starting and stopping PC counts and constructing JSON for scripts. Everything except the decompiler changes, basically.
Created attachment 575984 [details] [diff] [review]
compute decompiled code offsets for each op
The second part of the patch.
Jeff, this extends the decompiler to optionally compute the decompiled text for each opcode and the position in the final decompilation of those opcodes. This is needed so that extensions can precisely tie information about the execution of a script to the actual
decompiled code for the script (see attached screenshot).
Comment on attachment 575981 [details] [diff] [review]
PCCount interface changes
Review of attachment 575981 [details] [diff] [review]:
-----------------------------------------------------------------
Just nits.
::: dom/interfaces/base/nsIDOMWindowUtils.idl
@@ +67,5 @@
> interface nsIDOMWindow;
> interface nsIDOMFile;
> interface nsIFile;
>
> +[ptr] native JSObjectPtr (JSObject);
What's this for? I don't see it used.
::: js/src/jscompartment.cpp
@@ +550,5 @@
> releaseTypes = false;
>
> /*
> + * Don't purge types when scripts may need to be decompiled for profiling.
> + * XXX remove when script->function() is always available.
Please file a bug and reference it here.
::: js/src/jsgc.cpp
@@ +3631,5 @@
> + * Function None Profile Query
> + * --------
> + * StartPCCountProfiling Profile Profile Profile
> + * StopPCCountProfiling None Query Query
> + * PurgePCCounts None None None
The case of calling StartPCCountProfiling() when the state is Query was a little hard to follow. The definition of Profile is that active scripts have counter information, but it takes some investigation to discover that you're turning on counting *immediately*, at least for interpreter frames. Seems worth a comment.
Along those lines, how does that work if StartPCCountProfiling is invoked from a JITted function? It looks to me like it wouldn't start counting until the next GC? I don't see anything forcing it into the Interpoline or whatever.
At any rate, the exact semantics should be documented somewhere.
::: js/src/jsopcode.cpp
@@ +5968,5 @@
> + if (atom) {
> + AppendJSONProperty(buf, "name");
> + if (!(str = JS_ValueToSource(cx, StringValue(atom))))
> + return NULL;
> + buf.append(str);
This string-quoting dance seems to happen often enough that you could make an AppendJSONString(buf, cx, JSString) returning bool.
@@ +6006,5 @@
> + propertyTotals[j - OpcodeCounts::ACCESS_COUNT] += value;
> + continue;
> + }
> + JS_NOT_REACHED("Bad opcode");
> + } else if (OpcodeCounts::arithOp(op)) {
This 'else' is inconsistent with the rest of the structure. But I think the whole thing would read slightly better with 'else if's -- there don't seem to be any special-case fallthroughs that the continues are helping with.
@@ +6166,5 @@
> +
> + MaybeComma comma = NO_COMMA;
> + for (unsigned i = 0; i < numCounts; i++) {
> + double value = counts.get(i);
> + if (value) {
if (value > 0), maybe? I know it's fine here, but doing exact comparisons on floats gives me the heebie-jeebies. (Though I guess if you really were worried about rounding, that'd be value > 0.5. And that would just be silly here.)
::: js/src/jsopcode.h
@@ +710,5 @@
> +
> + // Boolean conversion, for 'if (counters) ...'
> + operator void*() const {
> + return counts;
> + }
I know I wrote this, but is it really a good idea? Does it make things easier or harder to follow?
::: js/src/jsopcodeinlines.h
@@ +73,5 @@
> }
>
> +class SrcNoteLineScanner
> +{
> + /* offset of the current JSOp in the bytecode */
Heh. I have a patch in my queue that moves this into jsscript.h. jsopcodeinlines.h definitely seems better. But the advanceTo implementation probably ought to moved to jsopcode.cpp now.
Comment on attachment 575984 [details] [diff] [review]
compute decompiled code offsets for each op
Review of attachment 575984 [details] [diff] [review]:
-----------------------------------------------------------------
One blind man is as good as any other, I guess, for reviewing this...
For the record, I am not particularly keen on even further depending on decompilation correctness for this information. Our decompiler code is just so clean, simple, and obviously correct, what could possibly go wrong?
::: js/src/jsopcode.cpp
@@ +1028,5 @@
> + /*
> + * Surrounded by parentheses when printed, which parentOffset does not
> + * account for.
> + */
> + bool parentheses;
I'd prefer the name |parenthesized|.
@@ +1051,5 @@
> Vector<JSAtom *> *localNames; /* argument and variable names */
> + Vector<DecompiledOpcode> *decompiledOpcodes; /* optional state for decompiled ops */
> +
> + DecompiledOpcode &decompiled(jsbytecode *pc) {
> + return (*decompiledOpcodes)[pc - script->code];
Add an explicit not-NULL assert here, since you're indexing into it (with a presumably small number, sure, but still).
@@ +1219,5 @@
> + if (ntext) {
> + memcpy((char *) ntext, text, len);
> + } else {
> + js_ReportOutOfMemory(ss->sprinter.context);
> + return false;
This is better done as an |if (!ntext)| block.
@@ +1245,5 @@
> +static inline void
> +SprintOpcode(SprintStack *ss, const char *str, jsbytecode *pc,
> + jsbytecode *parentpc, size_t startOffset)
> +{
> + if (startOffset < 0) {
This will generate a compiler warning with some compilers. And I don't see why they wouldn't be right to do so. Should |startOffset| be |ptrdiff_t|? The check as written right now is not going to have any effect.
@@ +2259,5 @@
> + jsbytecode **lastlvalpc, jsbytecode **lastrvalpc)
> +{
> + const char *token;
> + if (sn && SN_TYPE(sn) == SRC_ASSIGNOP) {
> + if (lastop == JSOP_GETTER) {
I think both the lastop getter/setter possibilities here are dead code. The uses here look like the assigning-getters-and-setters syntax I removed a year and a half ago:
Remove it in a followup bug/patch, please.
@@ +2283,5 @@
> InitSprintStack(JSContext *cx, SprintStack *ss, JSPrinter *jp, uintN depth)
> {
> INIT_SPRINTER(cx, &ss->sprinter, &cx->tempLifoAlloc(), PAREN_SLOP);
>
> + /* Allocate the parallel (to avoid padding) offset, opcode and bytecode stacks. */
Haters gonna hate the serial comma, yo. (I never picked up this bad habit thanks to my parents, God and Ayn Rand.)
@@ +4014,2 @@
> } else {
> + SprintOpcode(ss, argv[0], lvalpc, pc, todo);
You might as well remove these SprintOpcodes from the if/else bodies, since they're so obviously duplicative.
@@ +4026,1 @@
> break;
You're leaking |argv| and |argbytecodes| here, aren't you? Please fix this.
Ideally we'd have detailed enough line and column number information that we wouldn't have to use the decompiler for this. Floating reconstituted code alongside the real code is not the greatest UI.
Bug 568142 is about adding column info. It has a patch, but it's old.
Ideally we could do things both ways. For many websites the real code is a minified wad of JS with the absolute minimum amount of whitespace, and the reconstituted code makes the structure of the code (if not the intent) clearer. For this bug we also need exact column/extent information for pretty much every opcode in the script, and I fear that trying to keep track of this with source notes will eat a lot of memory.
It seems better all around if we compress and use the original source, then we can extract line/column information from that code for expressions in both the original source *and* a pretty printed version of the parse tree.
Created attachment 582553 [details] [diff] [review]
Get at the JSContext through IDL
Comment on attachment 582553 [details] [diff] [review]
Get at the JSContext through IDL
dev-doc-needed: as far as I can see, the new APIs are all introduced in the "PCCount interface changes" patch <> and should be documented at | https://bugzilla.mozilla.org/show_bug.cgi?id=687134 | CC-MAIN-2017-09 | refinedweb | 1,567 | 54.12 |
- Author:
- gregb
- Posted:
- June 3, 2009
- Language:
- Python
- Version:
- 1.3
- captcha
- Score:
- 1 (after 3 ratings)
If, like me, you've had trouble installing the Python Imaging Library or FreeType, you may have also had trouble getting a captcha to work. Here's my quick and dirty workaround — be warned, this is very low level security, and shouldn't be used on high-profile sites.
Originally published at
Credit to the author of django-simple-captcha, from whom I borrowed most of this code.
Usage
from django import forms from ABOVE-FILE import CaptchaField class CaptchaTestForm(forms.Form): myfield = forms.TextField() security_check = CaptchaField()
#
Please login first before commenting. | https://djangosnippets.org/snippets/1548/ | CC-MAIN-2016-44 | refinedweb | 109 | 65.73 |
Nmap Development
mailing list archives
On 6/22/2011 6:47 PM, David Fifield wrote:
This doesn't work for me; Python installed according to the instructions
in docs/win32-installer-zenmap-buildguide.txt doesn't have the win32api
module. If I remove the try...pass I get an exception when trying to
kill a scan.
Can you back out this change until we've had time to discuss it and
possible alternatives?
David Fifield
Reverted.
The problem was that win32api module is part of pywin32 which was available
win32-installer-zenmap-buildguide.txt.
I have the following two alternative approaches that work just fine:
import ctypes
-or-
# :-P
os.popen('TASKKILL /PID '+str(self.command_process.pid)+' /F')
_______________________________________________
Sent through the nmap-dev mailing list
Archived at
By Date
By Thread | http://seclists.org/nmap-dev/2011/q2/1179 | CC-MAIN-2014-42 | refinedweb | 132 | 68.77 |
.
Check my article about connecting the two using I2C if you haven’t already seen it. Before we start, we need to set up the Raspberry Pi so it’s ready for serial communication.
Raspberry Pi Serial GPIO Configuration
0. if you have not seen my article on how to remote access your Raspberry Pi, take a look here:
1. In order to use the Raspberry Pi’s serial port, we need to disable getty (the program that displays login screen) by find this line in file /etc/inittab
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
And comment it out by adding # in front of it
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
2. To prevents the Raspberry Pi from sending out data to the serial ports when it boots, go to file /boot/cmdline.txt and find the line and remove it
console=ttyAMA0,115200 kgdboc=ttyAMA0,115200
3. reboot the Raspberry Pi using this command: sudo reboot
4. Now, Install minicom
sudo apt-get install minicom
And that’s the end of the software configuration.
Connect Serial Pins and GPIO with a Voltage Level Converter
Load this program on your Arduino first:
[sourcecode language=”cpp”]
byte number = 0;
void setup(){
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
number = Serial.read();
Serial.print(“character recieved: “);
Serial.println(number, DEC);
}
}
[/sourcecode]
Then connect your Arduino, Raspberry Pi and Logic Level Converter like this:
This is how the wires are connected.
And this is the GPIO pins on the Raspberry Pi. Make sure you connect the correct pin otherwise you might damage your Pi.
A Simple Example with Minicom
Now to connect to the Arduino via serial port using this command in putty or terminal
minicom -b 9600 -o -D /dev/ttyAMA0
When you type a character into the console, it will received by the Arduino, and it will send the corresponding ASCII code back. Check here for ASCII Table. And there it is, the Raspberry Pi is talking to the Arduino over GPIO serial port.
To exit, press CTRL + A release then press Q
Example with Python Program
Using Python programming language, you can make Raspberry Pi do many fascinating stuff with the Arduino when they are connected. Install Py-Serial first:
sudo apt-get install python-serial
Here’s a simple application that sends the string ‘testing’ over the GPIO serial interface
[sourcecode language=”python”]
import serial
ser = serial.Serial(‘/dev/ttyAMA0’, 9600, timeout=1)
ser.open()
ser.write(“testing”)
try:
while 1:
response = ser.readline()
print response
except KeyboardInterrupt:
ser.close()
[/sourcecode]
To exit, press CTRL + C
Connect Raspberry Pi and Arduino with a Voltage Divider
Apart from replacing the Login Level Converter with a voltage divider, the way it works is the same as above. Anyway, I will show you a different example to demonstrate this. A voltage divider is basically just two resistors.
There is something you should be aware of before we continue. The RX pin on the Arduino is held at 5 Volts even when it is not initialized. The reason could be that the Arduino is flashed from the Arduino IDE through these pins when you program it, and there are weak external pull-ups to keep the lines to 5 Volts at other times. So this method might be risky. I recommend using a proper level converter, if you insist on doing it this way, try adding a resistor in series to the RX pin, and never connect the Raspberry Pi to Arduino RX pin before you flash the program to Arduino, otherwise you may end up with a damaged Pi!
The Arduino serial pin is held at 5 volts and Raspberry Pi’s at 3.3 volts. Therefore a voltage divider would be required, it’s basically just two resistors.
Here is the program you need to write to the Arduino board.
[sourcecode language=”cpp”]
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int incoming = Serial.read();
Serial.print(“character recieved: “)
Serial.print(incoming, DEC);
}
}
[/sourcecode]
Now you can connect directly from your computer to the Raspberry Pi on the tty-device of the Arduino, just like we described above. (type below into your putty)
minicom -b 9600 -o -D /dev/ttyAMA0
And as you type in characters in the console, you should see something like this:
And that’s the end of this Raspberry Pi and Arduino article. There are other ways of connecting, if you don’t already know, you can also use a Micro USB cable. Check out this post:
Hey Oscar!
I just found your (super) instructions, and wanted to go through it.
Funny, I already fail on the very beginning. On my Raspi3 the /etc/inittab file doesn’t exist.
It seems it’s gone nowadays, see
raspberrypi.org/forums/viewtopic.php?f=66&t=123081
But also when I follow the steps in the linked doc to deactivate getty, I don’t get your tutorial to work.
Hooking an oszilloscope to the Tx output of the raspi I don’t see anying coming there, so the minicom remains dead silent.
Any hints on how to get this going with a new setup?
Thanks,
Ralf
ok, reason found.
On Raspi3 the AMA0 points to bluetooth.
Serial nuw is on ttyS0.
Thanks anyway….
Hey, Oscar:
I just dropped by to say thank you.
I’m an educator trying to get fit with Arduino and RPi before using them for teaching STEM to the kids.
Your blog is really a source of inspiration.
Cheers,
Rod
Just a minor thing, I ran into the following error when running the python code:
File “gpio_serial.py”, line 4, in
myserial.open()
File “/usr/lib/python2.7/dist-packages/serial/serialposix.py”, line 271, in open
raise SerialException(“Port is already open.”)
serial.serialutil.SerialException: Port is already open.
It seems that the Serial constructor already opens the port, I had to comment out the following line of code:
ser.open()
Hi Oscar,
A thought about the RX pin voltage issue if using the voltage divider TX – put a schottkey diode to clamp the Rpi TX to the +3.3V, will prevent problems from the weak pull-up.
Hi dear………
I needed an easy way to transmit information to the Arduino to have the light convey meaningful information
Hi Oscar, is it uart or usart? and is it possible using this method to connect multiple arduinos with one raspy?
to connect multiple arduino to 1 Pi, I2C is a better option.
Hello,
I have a question and i can not find the answer so maybe you can help me.
I have a raspberry pi with a python program (Tweet monitor learn.sparkfun.com/tutorials/raspberry-pi-twitter-monitor)
When a tweet is found with the term i want it turn on a led (GPIO 22 HIGH)
And i have a other program (a clock with 18 7-segment display) on a arduino mega, when a button is push (Pin 7 HIGH) the clock decrease one second.
I wanted to know if it’s possible to plug the GPIO 22 (rpi) to the Pin 7 (arudino) and the GND to GND.
I was afraid to kill the raspberry (because raspberry 3.3V and arduino 5V apparently) but in my situation it’s from the raspberry to arduino and only this way not the other.
Thanks
and sorry about my english.. ;)
use i2C, you don’t need any conversion, and you can connect them directly.
Thanks for your answer
I will look your tutorial on i2c
And what about connect directly RPi GPIO 22 to arduino 7 and gnd to gnd without conversion ?
i don’t see there is any problem with that, if you set your Pin7 on Arduino as read only.
but it’s a good idea to measure the voltage on that pin, make sure it’s safe before connection.
Hi Oscar,
We developed an addon board for raspberry Pi called CoPiino ( CoPiino.cc ). It communicates directly with Raspberry Pi and on the other and has connectors which are Arduino compatible.
Please let us know if you are interested to check it out.
Best
– Sven
Hi Sven,
not sure if you are the same person, i replied to Tswaehn earlier.
cheers
Oscar
Thanks for the info. I know this is fairly old but when connecting to an Arduino Nano, I had to swap Tx and Rx between the arduino and the LLC so that it goes Tx to Tx and Rx to Rx.
I was beating my head against the wall trying different things and finally said screw it and swapped them. No sparks, no smoke, no flames… just a happy RPi that is casually talking to the Nano… thanks for the post. Great info!
I too had the same problem. My TX and RX from the Arduino went into TX and RX respectively (not swapped as shown above) on the level converter.
First congratulations by your work that was very usefull.
I have this problem:
I want communicate arduino and raspberry using xbee
I’ve tryed use this code:
import serial
ser = serial.Serial(‘/dev/ttyAMA0’, 9600)
ser.open()
string = “Hello from Raspberry pi”
print(‘Sending “%s” ‘ %string)
ser.write(‘%s’ %string)
while True:
incoming = ser.readline().strip()
print(‘Received %s’ %incoming)
ser.write(‘RPi RECEIVED: %S’ %incoming)
And this error appears:
Import error: No module named serial.
I’ve tested and the minicom works. I see the information sent from arduíno, but just using minicom because the code doesn’t work. Can you help about this problem?
Thank you and one more time congratulations
Ps:
I’ve alrady installed this:
sudo apt-get install python-serial
and all is update.
There might be two version of python on your pi (python2 and python3), and you only installed serial on python2, and you are using python3 to compile the code, that might be why you are getting this error.
I didn’t have this issue for some reason, but try what is suggested here:
have you installed python-serial?
I connect arduino Mega serial pins and raspberry type B GPIO with a adafruit voltage level converter
I copied and pasted your code (python for Raspberry). code with
if response == ‘ n’ or response ==” or response == ‘ r’
thank you for your site he taught me a lot.
We are a bunch of volunteers and opening a new scheme
in our community. Your web site offered us with useful info to work on. You have performed an impressive activity and our whole community will likely be grateful to you.
that’s great! :)
Hi Oscar!
It seems you are using a BSS138 vor level shifting. I’m currently trying to send and receive data to a multiwii which is Arduine mega 2560 based. My Baud rate is 115200, is that too fast for that shifter? Do I need to use 9600?
Thanks for any comments on this as I can’t proceed currently.
Very good info. Lucky me I ran across your blog by chance (stumbleupon).
I have book marked it for later!
Hi Oscar,
Is it possible to connect multiple Arduino’s to one RPi via GPIO?
Thanks,
Rutger
by using i2c, yes! (up to 128 connections)
Why not use i2c to begin with? It seems like then you wouldn’t need to disable the various console outputs, can drop the level converter, and get expandability as a bonus.
I am just exploring the possibility here, how to use, what to use, is up to the readers.
I have mine hooked up in a similar way, but it isn’t working for me. My multimeter shows that the high level on the logic board is at 5v, and the low level is at 3.3v. The TX from the Pi goes in the A3 pin on the logic converter, and the B3 pin then connects to the RX pin on the Arduino.
I’m curious… when using the logic converter, does it matter where the 3.3v and 5v come from? The only difference with my setup is that the Arduino 5v output is also powering the Pi.
So yeah, I’m not sure why mine isn’t working. Reading the serial RX pin on the Arduino always shows a value of -1.
you should use seperate external 5V to power the PI. have you tried using potential divider? just to rule out the possibility that your logic converter is bad.
Hello,
The caution note at the top of the article says the Arduino RX pin is held at 5V,
yet the pictorial diagram show the voltage divider on the Arduino TX pin.
Regards,
Bill Thomson
No. the RX is only held at 5V when it’s not initialized and that could be a problem. (but I haven’t had any issue because of this so far)
And you only need to use voltage divider on the Arduino TX as the voltage could changes between 0V and 5V on this pin connection.
The Arduino RX voltage should be safe for the PI connected directly, because only the PI is driving the voltage on this connection (0V to 3.3V).
Then why not to put 2 voltage dividers, one from TX (Arduino) to GPIO8(RPi) and the other between RX (Arduino) and GPIO 10(RPi), so make sure RX won’t break the RPi ??
Wonderful beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog web site?
The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright
clear concept
An impressive share! I’ve blog.
This is very interesting, You’re a very skilled blogger.
I have joined your rss feed and look forward to seeking more of your great post.
Also, I’ve shared your web site in my social networks!
Nice Article!!!!!!!!!!…
Hi Miralay, sorry I don’t think I can help with your problem, because I don’t own a RS232 so I can’t test it and I have never used that type of cable before either.
have you tried google that problem? hope you can find an answer. | https://oscarliang.com/raspberry-pi-and-arduino-connected-serial-gpio/ | CC-MAIN-2017-13 | refinedweb | 2,364 | 72.87 |
OLPC:Wiki
From OLPC
This is a wiki page about this editable site. We are currently running MediaWiki Version 1.13.3. If you are new to wikis, please read the Wiki getting started page for tips, tutorials, and people who can help you get going. Experienced wiki users, see our Style guide for how you can make your edits more helpful and efficient.
For cross-population of the wiki with updates from RT, trac and the like, see OLPC:Wiki integration.
Please leave notes about your wiki experiences, and comments or suggestions about this wiki, here. For more on children using wikis, see wikis for children. For more about wikis, see Ward Cunningham's lovely rundown of the principles he followed when developing the first wiki.
skins
The default skin has been changed to Shikiwiki. Common skins available are listed below:
Shikiwiki
This is a monobook clone developed by Simon Dorner, Helga Schmidt, daja77, and Sj.
bugs and requests
- A better-colored XO-icon for the user-login, along the top-right nav. The colors of the current one are a little bit off.
- IE issues
- The current layout breaks on certain pages in IE. For instance, when inside a pop-up window... (noticed when testing the new contributors-program database; see user:aaronk for details). Bug reporting and IE testing are appreciated.
- The top tabs are transparent in IE; not intended.
- The "translate" form dropdown is rounded in Safari, and looks out of place.
- There is little in the way of hovertext, and a number of images lack alt tags.
- Alignment of the namespace tab ('article', 'project' et al) is slightly imperfect; at some text-sizes it doesn't align with the body border.
Monobook
Monobook remains the default mediawiki skin, is close to shikiwiki, and the most robust of the other available skins.
Plugins and extensions
2008
- Semantic MediaWiki and Semantic Forms
- see Semantic MediaWiki
- Newuserlog
- new users have their own log now. useful long-term extension.
- UserLoginLog
- big brother, or your little brother, can observe logins as well as edits. Implemented to help note and evaluate vandalism; may be short-lived.
- Cite
- Now you can use <ref></ref> and <references/> to your heart's content.
- Examples: see Guia OLPC Peru Parte II
2007
minor extensions written by user:sj
- iframe
- ability to 'embed' other web sites inside of wiki, sort of a 'portal' effect.
- Examples: See MediaWiki.
- ref
- add footnote references to dialog or research text.
- Examples: See wikipedia.
- Youtube
- put a video-id between <youtube> tags
- Google Video : put a video id between <gvideo>
- inputbox
- prefill a target page with a template, to help people start a new type of page or otherwise give them an easy form within the wiki to fill out.
- Examples: see starting a page and User talk:Sj for examples.
- gitembed
- You can now embed plaintext documents from git, such as readme files and man pages, config pages, specs, &c, using the <gitembed> extension.
- OLPCgitembedurl
- Examples: see Talk:rainbow
- Next up: adding a patch to the extension so that it knows how to find the revision # of the document it's transcluding. Sj talk
- The CSS for this extension is inappropriate; we should tuck the 'Welcome to gitembed' header beneath the main display rather than to the left of it. --Michael Stone 18:24, 4 June 2008 (EDT)
- gspread
- you can embed a google spreadsheet in a wiki page. Example: see OLPC talk:Wiki.
- GSpreadEmbed
- traclink
- You can now embed a link to a trac ticket from the wiki, using <trac>NNNN</trac> or <trac>NNNN description</trac>.
- olpcTracLink
- Example : I can describe ticket #2129 (adding BlockParty to images) without elaborate linking to the original, and it finds the right page on dev.
ImageMap
ImageMap,
Here is an example:
<imagemap> Image:Foo.jpg|200px|picture of a foo poly 131 45 213 41 210 110 127 109 [[Display]] poly 104 126 105 171 269 162 267 124 [[Keyboard]] # Comment : rect takes two corners. rect 15 95 94 176 [[learning learning]] # Comment : circles are center + radius circle 57 57 20 [[OLPC|one laptop per child]] desc bottom-left </imagemap>
Suggestions and comments
Losing summaries
I find that when I edit pages and add links, the process of asking me an arithmetic question frequently discards the summary that I entered, so I have to scroll down and enter it again. I haven't been able to determine a pattern to when this happens.--Mokurai
- Does it ask you an arithmetic question when you are logged in? It is only supposed to ask when the edits are anonymous (part of the Mediawiki anti-spam measures). --Walter 08:25, 22 October 2006 (EDT)
Better CAPTCHA
As everyone knows, a text based captcha is insecure. In the case of this wiki, it is also annoying. Thus the solution: reCAPTCHA. Not only does it have an audio alternative, but it also helps digitize books. ffm 12:50, 1 January 2008 (EST)
Searching for "FORTH"
The Wiki Search function does not find the word "forth" on any page or page title. The Go function correctly goes to the page entitled "FORTH". My problem is that I have to use Google to search for references to the FORTH programming language in order to make them into links, now that I have created a FORTH page.
forth site:wiki.laptop.org
--Mokurai 01:55, 22 October 2006 (EDT)
-)
Make wiki Search CasE INsensitive
We will all be better served if both Go and Search are not sensitive to case. Google works that way, so practically every participant here will be LESS surprised if case is ignored. How can this objective be pursued? Nitpicker 19:06, 9 December 2006 (EST)
-)
See also
Wiki corrections
- wiki edit toolbar is missing when editing pages.
- the 'G1G1' logo in bottom right corner is out of date, no g1g1 program anymore. | http://wiki.laptop.org/go/Wiki/lang-es | CC-MAIN-2015-18 | refinedweb | 977 | 63.39 |
On 13 Nov 1999, david parsons wrote:>. 3.something. And it required the mounpoint to be immediatesubdirectory of root. Due to the way they've stored the namespace statethe whole thing fscked up magnificiently if you tried to work with theroot of mounted fs via the old drive name. SUBST was less b0rken, though.And more useful, BTW - it gave weak equivalent of tilde-expansion. Mixingthem was Bad Idea(tm). I've looked at 3.30 kernel - scary and fascinating.Obviously modeled after v7, but _what_ a mess had they slapped ontothe upper half for CP/M emulation... Scary. It almost looked like a smallsubset of UNIX placed on a box with rather shitty IO and buried under theheaploads of CP/M compatibility crap. They might start with CP/M clone,but 3.x internals looked rather like a castrated and mutilated Xenix.> It's almost exactly mount, though MS-DOS didn't have> a procfs to nicely export the mount table./me notices the provocation./me recalls the US laws regarding the death threats./me says nothing and walks away.> david parsons \bi/ Of course MS could have dropped it, then re-added it> \/ recently as a New! Thing!ISTR some claims that NT 3.5 had unified tree and foo:bar names didn'teven reach the kernel - translation happened in one of the shared libs.If it's really so their stuff should actually remount filesystems.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.rutgers.eduPlease read the FAQ at | https://lkml.org/lkml/1999/11/13/116 | CC-MAIN-2017-13 | refinedweb | 263 | 69.28 |
ui.Animate wider usage
@omz, is it possible to fudge something so ui.animate works a little differently than it does at the moment.
It would be very convenient if you could call ui.animate with a start, finish and increment along with its duration parameter. And it passes back the value on each call to the defined function.
I am pretty sure ui.animate is written in objective c as I could not find it in the ui file.
It may simple to write for you, but not for me. But I think this functionality would be welcomed by many here.
But again, if there is a way to fudge it so I can rely on the same mechanism, that would be great.
@omz , just trying to animate/draw the class below. Meaning just set the value from 0.0 to 1.0 for the duration specified. I have tried this with a method with @ui.in_background. I got some strange results. I am sure it was just me doing something stupid, but just seems like the mechanism is already there.
class CircleProgress(ui.View): def __init__(self, *args , **kwargs): self.min = 0. self.max = 1.0 self.v = 0. self.increments = .01 self.margin = (0,0,0,0) self.drawing_on = True self.alpha = 1 self.fill_color = 'red' self.stroke_color = 'black' self.font =('Arial Rounded MT Bold', 18) self.label_on = True self.set_attrs(**kwargs) btn = ui.Button(name = 'inc') btn.action = self.animate btn.width = self.width btn.height = self.height btn.flex = 'wh' self.add_subview(btn) btn.bring_to_front() def inc(self, sender = None): self.value += self.increments if self.value > self.max: self.value = self.min self.set_needs_display() def dec(self): self.value -= self.increments if self.value < self.min: self.value = self.max self.set_needs_display() def value(self, v): if v < self.min or v > self.max: return self.value = v self.set_needs_display() def draw(self): if not self.drawing_on : return cr = ui.Rect(*self.bounds).inset(*self.margin) p = max(0.0, min(1.0, self.value)) r = cr.width / 2 path = ui.Path.oval(*cr) path.line_width = .5 ui.set_color(self.stroke_color) path.stroke() center = ui.Point(r, r) path.move_to(center.x, center.y) start = radians(-90) end = start + p * radians(360) path.add_arc(r, r, r, start, end) path.close() ui.set_color(self.fill_color) path.eo_fill_rule = True path.fill() self.draw_label() def draw_label(self): if not self.drawing_on : return if not self.label_on: return cr = ui.Rect(*self.bounds) ui.set_color('purple') s = str('{:.0%}'.format(self.v)) dim = ui.measure_string(s, max_width=cr.width, font=self.font, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) lb_rect = ui.Rect(0,0, dim[0], dim[1]) lb_rect.center(cr.center()) ui.draw_string(s, lb_rect , font=self.font, color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) def set_attrs(self, **kwargs): for k,v in kwargs.iteritems(): if hasattr(self, k): setattr(self, k, v) def animate(self, sender = None): print 'in animate...' def animation(): self.alpha = 0 # fade out self.value = self.alpha self.set_needs_display() ui.animate(animation, duration=2)
@omz this also relates. In Pythonista startup I have
from objc_util import * UIView.beginAnimations_(None) UIView.setAnimationDuration_(0)
From you.
It also stops ui.animate() animating , which makes sense. When I am testing now, i comment out these lines And shut down Pythonista , and restart. Is it possible to easily reverse this in code. I tried to pass UIView.beginAnimations_(None) 1 instead of None. Just crashed.
Again, just useful for testing. I prefer to have the Animations off most of the time. But if inside a .py file I can turn them on, then off again, that would be great.
UIView.commitAnimations()
will close out the beginAnimations and effectively undo the duration of none.
Your above code seems to mix value as a method, and value as a variable, no? Perhaps you are missing a property decorator?
Also, not sure you need or should put a set needs display inside the animation function. I think that would only be executed once. I think you want to set heeds display when the value changes, but no other times. If you are trying to animate just the alpha, then what you have works. If you are trying to animate changing value, this approach will not work, you will need to have your own thread, or call ui.delay which calls itself, etc. animate can only animate changes to properties, such as frame, colors, transforms, basically things that ios knows how to draw and knows how to interpolate. iOS does not onow how to interpolate a custom draw function.
As @JonB already pointed out,
ui.animateisn't really suitable for animating custom attributes/drawing.
You can get the effect you're looking for by combining
ui.animate(for fading in/out) with
ui.delay(for changing the progress and redrawing). I posted an example of a simple animation using
ui.delayin this thread (not exactly what you want, but the technique would be similar).
@JonB , thanks. Yes I had changed the value property aend realized I need the set_needs_display() in the animate method. I had just been changing things around
@JonB , thanks. UIView.commitAnimations() Works as expected.Very convenient.
I will try @omz code for the animate. For this class not part of the functionality, more use a built in test to be sure the min, max , v are working correctly. Will be more useful for other things though
@JonB , I know this question sort of seems stupid. But I was looking up flex on the forum. I have never really felt in control of it. Anyway, I remembered the animation you did a long time ago this_post
But if you had wanted to draw out realtime b.x, b.y, b.height , b.width for example this would be have been impossible as far as I can see. Using this method that is.
Look it's ok, I accept the way it is. Just my use case did not really give a clear idea about the possible uses.
But anyone reading this and have difficulties getting your head around flex, @JonB ' s code post at the link is visual and very helpful
@omz , @JonB or @anyoneelse.
I did the below just using ui.Delay based on the conversations above. Again, it's simple, but often the handiest things are.
So it's just a class trying to give a framework for a callback over a duration with the number range 0.0 to 1.0. Just trying to emulate part of ui.animate. The time for me is the tricky thing. But what I have done seems to accurate to amount the 100ths of a second.
Just overall I don't know if the approach is a good one or not. Maybe there are some really bad flaws in this approach. Any feedback welcome, scathing feedback is fine.
It's a little long for posting. I thought about a gist, but thought I have a better chance to get feedback if it's listed here
import ui import time, warnings class CallMeBack(object): ''' CLASS - CallMeBack Purpose to call a user supplied function 100 times with simlar units of elapased time between calls with a number between 0.0 and 1.0 for the passed duration. This is an attempt to mimick the part of @omz's animate function, that you can set and forget to get a series of numbers between 0 - 1.0 over a specfic duration without binding to any attributes. just passes the value to the supplied function/method its only work in progress. i am certin will have to refactor. i am guessing i will need to have some @classmethod decorators to make it as flexible as @omz's ui.animate. this is at least a start. A pause method? maybe does not make sense ''' def __init__(self, func, duration = 1.0, begin = True, on_completion = None, obj_ref = None): self.iterations = 0 # a counter of the num of iterations done self.duration = duration # the time to spead 100 callbacks over self.time_unit = 0 # 1/100th of the duration self._value = 0 # current value self.func = func # the callers func that is called # if supplied, calls this function after the 100 iterations self.on_completion = on_completion self.start_time = 0 # is set once the start method is invoked self.finish_time = 0 # used for debug. measure how long we took self.working = False # a flag, to protect from being called # whilst running. we are not reenterant # so its possible to store a reference to a object, which you can # recover in the callback function self.obj_ref = obj_ref # start from init with begin = True *arg if begin: self.start() def start(self, duration = None): # the timing and process start method. can be called from __init__ # or here externally # aviod being called while running. if self.working: warnings.warn('CallMeBack cannot be called whilst it is running.') return # block being called again until we finish self.working = True if duration: self.duration = duration self.start_time = time.time() self.time_unit = self.duration / 100. # would be nice to have exp, log etc... ui.delay(self._work_linear(), 0) def _work_linear(self): # the method that is called 100 times at evenlyish time intervals # which in turns calls the callers function with numbers 0.0 to 1.0 # i know, this can be better. for now its ok to spell it out _expected_time = self.iterations * self.time_unit _real_time =time.time() - self.start_time _diff = _expected_time - _real_time if self.iterations == 100: # hmmm, call last time self.func(self, 1.0) # we are finished self.finish_time = time.time() ui.cancel_delays() print 'duration {}, total time {}, difference {}'.format(self.duration , self.finish_time - self.start_time, (self.finish_time - self.start_time) - self.duration) # if a completion routine has been defined, is called here if self.on_completion: self.on_completion(self) # reset some values, so calling multiple times work self.reset() self.working = False return # call the callers function with ref to this object and the current # value self._value = self.iterations / 100. self.func(self, self._value) self.iterations += 1 # call ui.delay with .95% of the time unit we have. # this seems ok at the moment. if a lot of processing happens # in the callers function, it will start to fall behind # hofully _diff counteracts it ui.delay(self._work_linear, (self.time_unit ) + _diff) @property def value(self): return self._value @property def finished(self): return self.working def reset(self): # reset some vars, in the event we are started again self.iterations = 0 self._value = 0 self.working = False def cancel(self, ignore_completion = False, finish_with = None): # for manual cancelling # finish_with just allows your func to be called a last time # with a value like 1.0 Could provide a more appealling effect ui.cancel_delays() if finish_with: self.func(finish_with) if self.on_completion: if not ignore_completion: self.on_completion(self)
Was not sure how the below pattern would work with something real. It worked fine.
def test_animate(self, sender = None): def inc(sender, v): self.value(v) cb = CallMeBack(inc, duration = 5.0) # another version def test_animate(self, sender = None): self.alpha = 0 def inc(sender, v): self.value(v) self.alpha = v cb = CallMeBack(inc, duration = 5.0) | https://forum.omz-software.com/topic/2928/ui-animate-wider-usage/12 | CC-MAIN-2021-10 | refinedweb | 1,863 | 62.64 |
Vue Picture Swipe GalleryVue Picture Swipe Gallery
This component is a simple wrapper for the awesome Photoswipe. It's a Vue plugin that displays a gallery of image with swipe function (and more). Includes lazy (smart) loading (mobile friendly) and thumbnails.
DemoDemo
InstallInstall
npm install --save vue-picture-swipe
UsageUsage
You can use it as you want. Here are some examples if you want to use it inline, or in a
.vue file component or even with Laravel.
Inline usageInline usage
You can using it inline:
<vue-picture-swipe :</vue-picture-swipe>
Just remember to register the component:
import VuePictureSwipe from 'vue-picture-swipe'; Vue.component('vue-picture-swipe', VuePictureSwipe); new Vue({ el: '#app' })
Usage in another componentUsage in another component
Create a component
Example.vue. Then paste this:
<template> <vue-picture-swipe :</vue-picture-swipe> </template> <script> import VuePictureSwipe from 'vue-picture-swipe'; export default { data() { return { items: [{ src: '', thumbnail: '', w: 600, h: 400, alt: 'some numbers on a grey background' // optional alt attribute for thumbnail image }, { src: '', thumbnail: '', w: 1200, h: 900 } ]}; } } </script>
Usage with LaravelUsage with Laravel
Edit
resources/assets/js/app.js and add this just before the
new Vue lines.
import VuePictureSwipe from 'vue-picture-swipe'; Vue.component('vue-picture-swipe', VuePictureSwipe);
Then run your watcher:
npm run watch
Advanced usageAdvanced usage
PhotoSwipe optionsPhotoSwipe options
Use
options for Photoswipe options.
<!-- Disable "share" buttons. --> <vue-picture-swipe :</vue-picture-swipe>
PhotoSwipe instancePhotoSwipe instance
You can access the PhotoSwipe instance via setting a ref, the instance object is exposed as
pswp.
<vue-picture-swipe</vue-picture-swipe>
this.$refs.pictureSwipe.pswp
Why?Why?
I did not found any vue component that uses thumbnail (smaller version of images) and is mobile-friendly (swipe)
- This one is documented (and issued) in chinese only and has no thumbnails. Edit: I translated the readme (with google translate) and submitted a PR that was accepted, so now, the documentation is in english)
- This one is documented (and issued) in chinese too and has no thumbnails either.
- This one has no documentation.
- This one is a kind of fork of the previous one
- ...
So I created mine.
Source: | https://reposhub.com/vuejs/carousel/rap2hpoutre-vue-picture-swipe.html | CC-MAIN-2021-21 | refinedweb | 355 | 54.83 |
Is There Risk to the Risk Premium?
It is obvious now to almost everyone that the stock market returns of the late 1990s were drastically above average. Investors are starting to lower their expected returns from the stratospheric levels of a few years ago, but according to a recent study by John Hancock Financial Services investors are still expecting annual returns of 16% over the next 20 years. Not only is this unrealistic, but dangerous as investors plan for retirement. Investors using these expectations for planning purposes will not be able to build an adequate retirement nest egg. These high expected rates of return also help justify the historically low savings rate. Investors assume that since their portfolio will be growing at such a high rate, they do not have to add additional funds. Once investors realize equities are producing returns substantially lower then expected, the savings rate will have to rise. This in turn will curtail the spending spree that U.S. consumers have enjoyed with obvious repercussions throughout the economy.
So 16% equity returns are unrealistic, but what should investors expect as a long-term rate of return? According to Ibbotson Associates, publisher of the annual yearbook, Stocks, Bonds, Bills and Inflation, since 1926 equity investors have earned an 8% real rate of return. Ibbotson Associates also calculate that bonds have delivered real return of 3%. This means equities have a risk premium of 5%. The equity risk premium is simply the return over bonds that equity investors require for assuming more risk.
The recent issue of Financial Analyst Journal included an article, What Risk Premium is Normal, by Robert Arnott, managing partner at First Quadrant, L.P, and Peter Bernstein, president of Peter L. Bernstein, Inc., and author of Against the Gods and The Power of Gold. The authors ask if investors in 1926 expected real returns of 8%. No, is the short answer and the long answer covers almost 20 pages. Arnott and Bernstein create a model to calculate what investors would have expected the real rate of return on stocks to be over time. They contend the real rate of return should be the dividend yield, plus (or minus) dividend growth, plus (or minus) changes in valuation multiples. Of course investors cannot realistically expect valuation multiples to change when determining future expected returns.
During the early part of the 1900's investors did not perceive the stock market as a long-run economic growth investment. Investors simply tried to buy low and sell high and never considered the notion of buy-and-hold. Additionally, investors assumed that company managers would siphon off any economic gains by issuing more shares to themselves (that sounds familiar), investors did not assume growth in dividends either. (I highly recommend reading Edward Chancellor's Devil Take the Hindmost for a complete history of financial markets which discusses this "robber baron" capitalism.) Investors could not have assumed any expansion of valuation multiples either. And with the U.S. on the gold standard there was virtually no trend in inflation. This leaves the 1926 investor expecting to earn the dividend yield, which was 5.1% at the time. With government bonds yielding 3.7%, investor only required an equity risk premium of 1.4%
In hindsight we know investors earned a 5% risk premium as the real return on stocks was 8% and government bonds returned about 3% after inflation. These results have become regarded as the historical average returns investors should expect. Arnott and Bernstein found that the "historical" 5% risk premium for equities was due to several "accidents."
After World War II, "expected inflation became a normal part of bond valuation." This development resulted in a "one-time shock to bonds that decoupled nominal yields from real yields." As bond investors factored in inflation, nominal yields increased costing bond investors 0.4% a year over 75 years. This accounted for almost one-tenth of the excess return equity holders earned relative to bondholders.
The second accident was the rising valuation multiples that stocks experienced since 1926. Arnott and Bernstein calculate that from 1926 to 2001, multiples rose from 18 times dividends to 70 times dividends currently. This multiple expansion accounts for fully one-third of the excess return over the past 75 years, even though the entire increase in valuation multiples happened since 1984.
Regulatory reform accounted for about one-fourth of the excess return. Prior to 1926, stocks did not pass though much economic growth to shareholders as company insiders issued themselves more shares, which left outside investors unable to fully participate as the company grew. Now shareholders receive a substantial amount of the economic growth generated by companies. This led to a 1.4% increase in real dividend payments and in real earnings.
Lastly, investors have benefited from survivorship bias. Arnott and Bernstein contend that the US has benefited from having no wars fought on its own soil, or having experienced a revolution. Also, during the past century, four of the fifteen largest stock markets at the beginning of the century experienced a total loss of capital (China, Russia, Argentina, and Egypt). Two others came close - Germany (twice) and Japan. While impossible to quantify, the authors say, "U.S. investors in early 1926 would not have considered this likelihood to be zero, nor should today's true long-term investor."
Getting back to the model to forecast what rates of returns investors should expect. As previously stated, Arnott and Bernstein contend that equity returns are derived from the dividend yield, growth in dividends, and changes in valuation multiples.
Investors commonly assume that in the long-run earnings growth will equal GDP growth. The authors show that growth in stock prices is more closely aligned with per capita GDP growth. The reasoning makes sense as well. Investors should only benefit from the growth in the companies they are invested in. Since a growing economy will spur new companies, these new companies will crowd out a portion of the economic growth experienced by existing companies.
During the past 200 years, 85% of equity returns has come from three sources: inflation, dividends, and the rising valuation levels experienced since 1982.
Over the past several years dividends have played a lesser role in total returns. Recently, investors preferred companies that reinvested earnings back into the company in order to achieve faster growth. Tax laws have also influenced investors' preference away from receiving regular dividends. The authors found that it is not historically beneficial for companies to reinvest dividends back into the company. Since 1871 (there is no reliable source of earnings information prior), the average earnings yield has been 7.6% and the average dividend yield has been 4.7%. This results in a "retained earnings yield" of about 3%. In other words, companies should grow earnings and dividends at 3% otherwise investors would rather receive the money and invest it themselves.
Interestingly, the article states that companies experienced an internal growth rate of 1.2% to 1.5% over the past 200 years. Since the economy as a whole has grown at a 3.6% rate, the majority of the growth came from new enterprises and not from reinvesting in existing companies. Oddly enough, in an earlier article, Bernstein found that earnings and dividend growth is actually higher when dividend payout ratios are higher. Bernstein proposes that when managers have less money to invest, they are more selective about their investment projects. The article also points out that growing companies tend to issue more shares, which imposes another drag on per share dividend and earnings growth.
Putting all this together, the article supposes real GDP growth of 3% over the next 40 years with an annual 1% population growth rate. This would yield a ceiling of 2% growth for dividends. Subtracting out the average historical dilution of 1%, results in future dividend growth of only 1% with the economy growing at a healthy 3% rate.
The article determines that the expected real stock returns over the past 192 years averaged 6.1% derived from three components; an earnings yield of 5.0%, per capita GDP growth of 1.7%, less 0.6% shrinkage of dividends relative to real per capital GDP growth. The actual return was 6.8% over the 192 year period. The major factor in the 70 basis point excess return was due to the rise in valuation multiples that started in 1982 with the other "accidents" making up the remainder. The 6.8% real return is also noticeably lower than the 8% return experienced since 1926.
Before determining the risk premium for equities, the expected bond return needs to be determined. The biggest determinate of bond yields is what expectations are for inflation. The authors estimate expected future inflation based on the prior three year inflation rate. Until after World War II inflation was largely non-existent during peace time. By this model, the authors found a real bond rate of 3.7%, comprised of a nominal rate of 4.9% and an inflation rate of 1.2%. The actual inflation rate experienced was 1.4%, so the model is with in the ballpark. Arnott and Bernstein also mention that during the 1950s and 1960s bond investors kept expecting inflation to go away and were mis-pricing bonds for an extended period of time.
By subtracting the real expected bond return (3.7%) from the real expected stock return (6.1%) the authors derived the expected risk premium of 2.4% during the past 196 years. This is well below the 5% commonly assumed today. Additionally, Arnott and Bernstein calculate that the "current risk premium is approximately zero, and a sensible expectation for the future real return for both stocks and bonds is 2-4 percent, far lower than the actuarial assumptions on which most investors are basing their planning and spending."
Stock market history is often reduced to the period since 1926. This time period has been extremely good to equity investors. But it appears that the excess returns stocks offered were due to several one-time adjustments and not a sustainable trend. The article did include one bright spot. Since investors should only expect a 2.5% risk premium, the market does not have to correct as much as it would if investors required a 5% premium. Unfortunately, this "still requires a near halving of stock valuations or a 2 percent drop in real bond yields (or a combination of the two)."
TweetTweet | http://www.safehaven.com/article/419/is-there-risk-to-the-risk-premium | CC-MAIN-2018-09 | refinedweb | 1,747 | 56.45 |
Closed Bug 697429 Opened 10 years ago Closed 3 years ago
Bring filter
.py up to date for compare locales
Categories
(Thunderbird :: Build Config, defect)
Tracking
(Not tracked)
People
(Reporter: standard8, Unassigned)
Details
Attachments
(1 file, 1 obsolete file)
Thunderbird's filter.py has gotten a little out of date and needs a bit of work, namely: - We shouldn't exclude checking some strings in plugins.dtd, especially as we want them now. - Match the rest of the file to the same style as Firefox's filter.py so that we can easily translate changes across from one file to the other.
Attachment #569670 - Flags: review?(l10n)
Flags: in-testsuite-
Comment on attachment 569670 [details] [diff] [review] The fix Review of attachment 569670 [details] [diff] [review]: ----------------------------------------------------------------- We haven't done this for any of firefox etc, but if we're changing big, we should change for the better. A good example is the 1.9.2 one, which uses text flags instead of fancy bools, see. Can we just go that route instead?
Attachment #569670 - Flags: review?(l10n) → review-
Similar patch to the previous but uses "ignore" and "error" in the return values.
Attachment #569670 - Attachment is obsolete: true
Attachment #579633 - Flags: review?(l10n)
Comment on attachment 579633 [details] [diff] [review] The fix v2 Review of attachment 579633 [details] [diff] [review]: ----------------------------------------------------------------- This looks much better than the true/false mess, but there are some comments and logic that could even be stronger, thus an r-. ::: mail/locales/filter.py @@ +18,3 @@ > if mod == "extensions/spellcheck": > + # l10n ships en-US dictionary or something, do compare > + return "error" The comment here is a tad confusing. What this is doing is that if we had a .dtd or .properties file in en-US and l10n, it'd actually compare. Really just a safeguard. See also the comment below. @@ +26,5 @@ > + if path != "chrome/messenger-region/region.properties": > + # only region.properties exceptions remain, compare all others > + return "error" > + > + return (re.match(r"browser\.search\.order\.[1-9]", entity)) and "ignore" or "error" I'd suggest to invert the logic, and have all exceptions being in explicit conditions. Something like (with 4space indention, too): if mod == "mail": if path == "defines.inc": return (entity == "MOZ_LANGPACK_CONTRIBUTORS") and "ignore" or "error" elif path == "chrome/messenger-region/region.properties": return (re.match(r"browser\.search\.order\.[1-9]", entity)) and "ignore" or "error" return "error"
Attachment #579633 - Flags: review?(l10n) → review-
Assignee: mbanner → nobody
Do we/Thunderbird still need this?
Flags: needinfo?(philipp)
Flags: needinfo?(l10n)
Can't speak to the initial comment here, really. I'd suspect yes, though.
Flags: needinfo?(l10n)
Let's close this and create a new bug if something breaks.
Status: NEW → RESOLVED
Closed: 3 years ago
Flags: needinfo?(philipp)
Resolution: --- → INVALID | https://bugzilla.mozilla.org/show_bug.cgi?id=697429 | CC-MAIN-2022-05 | refinedweb | 458 | 59.9 |
Thus far we have dealt with portfolios of at most two assets, with only one involving any risk. It is time to turn to the general relationship between the characteristics of a portfolio and the characteristics of its components.
Let there be n assets and s states of the world, with R an {n*s} matrix in which the element in row i and column j is the return (or value) of asset i in state of the world j. Here is an example with n=3 and s=4:
Good Fair Poor Bad Asset1 5 5 5 5 Asset2 10 8 6 -5 Asset3 25 12 2 -20
Let x be an {n*1} vector of asset holdings in a portfolio. For example:
x Asset1 0.20 Asset2 0.30 Asset3 0.50
What will be the return of the portfolio in each of the states? This is easily computed. The {1*s} vector of portfolio returns in the states (rp) will be:
rp = x'*R
Here:
Good Fair Poor Bad rp 16.50 9.40 3.80 -10.50
Now, let p be an {s*1} vector of the probabilities of the various states of the world. In this case:
p Good 0.40 Fair 0.30 Poor 0.20 Bad 0.10
The expected return (or value) of the portfolio will be:
ep = rp*p
In this case:
ep = 9.13
It is useful to write the expression for expected return in terms of its fundamental components:
ep = x'*R*p
The product of the three terms can be computed in either of two ways. Above, we computed x'*R, then multiplied the result by p. Alternatively, we could have multiplied x' by the result obtained by multiplying R times p:
ep = x'*(R*p)
The parenthesized expression is an {n*1} vector in which each element is the expected return (or value ) of one of the n securities. Let e be this vector:
e = R*p
Here:
e Asset1 5.00 Asset2 7.10 Asset3 12.00
Using these results we may write:
ep = x'*e
That is, the expected return (or value) of a portfolio is equal to the product of the vector of its asset holdings and the vector of asset expected returns (or values). This is the case whether the returns are discrete, as in this derivation, or continuous (that is, drawn from continuous distributions).
The units utilized for the values in vectors x and e will depend on the application. In some cases, physical units (e.g. shares) may be appropriate for x; in others, values (e.g. dollars); and in yet others, proportions of total value. Whatever the units selected, to find the end-of-period value of a portfolio, the end-of-period values per unit of exposure should be placed in vector e and the number of units of each asset held placed in vector x. To find the expected return (or value-relative) for a portfolio, multiply the expected returns (or value-relatives) in vector e by the exposures to the assets in vector x.
Whatever the application, the relationship between the expected outcome of a portfolio and the expected outcomes for its components is relatively simple and intuitive. For example, the expected return on a portfolio is a weighted average of the expected returns on its components, with the proportionate values used as weights. Since the relationship is linear, the marginal effect on portfolio expected return of a small change in the exposure to a single component will equal its expected outcome:
d(ep)/d(x(j)) = e(j)
If the expected outcome were the only relevant characteristic of a portfolio, it would be easy to make investment decisions. But risk is also relevant. And, as we will see, its determination presents a more substantial challenge.
For present purposes we will use as a measure of portfolio risk the standard deviation of the distribution of its one-period return or the square of this value, the variance of returns.
By definition, the variance of a portfolio's return is the expected value of the squared deviation of the actual return from the portfolio's expected return. It depends, in turn, on the possible asset returns (R), the probability distribution across states of the world (p) and the portfolio's composition (x). The relationship is, however, somewhat complex.
To begin it is useful to create a matrix of deviations of security returns from their expectations. This can be accomplished by subtracting from each security return the corresponding expectation:
d = R - e*ones(1,s)
The result (d) shows the deviation (surprise) associated with each security in each of the states of the world. Here:
Good Fair Poor Bad Asset1 0.00 0.00 0.00 0.00 Asset2 2.90 0.90 -1.10 -12.10 Asset3 13.00 0.00 -10.00 -32.00
The deviation (surprise) associated with the portfolio in each of the states of the world can be obtained by multiplying the transpose of the composition vector times the asset deviation matrix:
dp = x'*d
In this case:
Good Fair Poor Bad dp 7.37 0.27 -5.33 -19.63
To determine the variance of the portfolio, we wish to take a probability-weighted sum of the squared deviations. A simple way to do so uses the dot-product operation, in which elements are treated one by one:
vp = sum(p'.*(dp.^2))
However, there is a more elegant and (as will be seen) far more useful way to do the computation. First, we create a {s*s} matrix with the state probabilities on the main diagonal and zeros elsewhere. This can be done in one statement:
P = diag(p);
In this case, P will be:
Good Fair Poor Bad Good 0.40 0.00 0.00 0.00 Fair 0.00 0.30 0.00 0.00 Poor 0.00 0.00 0.20 0.00 Bad 0.00 0.00 0.00 0.10
The variance of the portfolio is then given by a more conventional matrix expression:
vp = dp*P*dp'
For our portfolio:
vp = 65.9641
and
sdp = sqrt(vp) = 8.1218
To see why the latter procedure for computing variance is more useful, we substitute the vectors used to compute dp:
vp = (x'*d)*P*(x'*d)'
There is an easier way to write the last portion. Remember that the transpose operation turns a matrix on its side. From this it follows that:
(a*b)' = b'*a'
For example, let a be a {ra*c} matrix and b a {c*rb} matrix. Then (a*b) is {ra*rb} and (a*b)' is {rb*ra}. Now consider the expression to the right of the equal sign. The first term (b') is of dimension {rb*c}, while the second is of dimension {c*ra}. Their product will thus be of dimension {rb*ra}. Since each element will represent the sum of the same set of products as in the result produced by the expression on the left, the resulting matrices will in fact be the same.
We can use this result to note that:
(x'*d)' = d'*x''
But two transpose operations will simply turn a matrix on its side, then turn it back, giving the original matrix. Therefore:
(x'*d)' = d'*x
And the expression for portfolio variance can be written as:
vp = (x'*d)*P*(d'*x)
Of course the multiplications can be performed in any desired order. For example:
vp = x'*(d*P*d')*x
The parenthesized term is of great importance in portfolio analysis - - enough to warrant its own section in this exposition.
The matrix described in the previous section is termed the covariance matrix for the assets in question. Each of its elements is said to measure the covariance between the corresponding assets. Using C to represent the covariance matrix:
C = d*P*d'
In this example:
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 18.49 56.00 Asset3 0.00 56.00 190.00
The variance of a portfolio depends on the portfolio's composition (x) and the covariance matrix for the assets in question:
vp = x'*C*x
which of course gives the same value found earlier (65.9641).
Well and good. But what do the covariance numbers mean? How are we to interpret the fact that the covariance of Asset2 with Asset3 is 56.00, while that of Asset3 with itself is 190.00, and so on?
Examination of the matrices involved in the computation of C provides the answer. Recall that C=d*P*d'. Consider the covariance of Asset2 and Asset3. It uses the information in row 2 of matrix d and that in column 3 of matrix d' (the latter is, of course, also in row 3 of matrix d). It also uses the vector of probabilities along the diagonal of matrix P. The net result, written in a slightly casual notation is that:
C(2,3) = sum(d(2,s)*p'(s)*d(3,s))
where the sum is taken over the states of the world.
As this expression shows, the covariance between two assets is a probability-weighted sum of the product of their deviations. To verify this we can adapt the expression above to make it legal in MATLAB:
c23 = sum(d(2,:).*p'.*d(3,:))
The answer is 56.00, precisely equal to the value in the second row and third column of the covariance matrix.
Put in terms of prospective results: the covariance between two assets is the expected value of the product of their deviations from their respective expected values. It immediately follows that the covariance of asset i with asset j is the same as the covariance of asset j with asset i. Thus the matrix is symmetric around its main diagonal -- note that the value in row 2, column 3 is the same as that in row 3, column 2. It also follows from the expression for covariance that the covariance of an asset with itself is its variance. The asset variances thus lie on the main diagonal of the covariance matrix. In this case:
va = diag(C)
Here:
va Asset1 0.00 Asset2 18.49 Asset3 190.00
The asset standard deviations are of course the square roots of these numbers:
sda = sqrt(diag(C))
In this case:
sda Asset1 0.00 Asset2 4.30 Asset3 13.78
Note that the first asset's return is certain. Hence its variance and standard deviation are zero. The second asset is risky, with a standard deviation of 4.30. The third is considerably more risky, with a standard deviation of 13.78.
Since the covariance matrix includes asset variances along the main diagonal, the entire matrix is sometimes termed a variance-covariance matrix. For brevity we will use the simpler term covariance matrix, but it should be remembered that the diagonal elements are both covariances and variances.
For the special case in which the probability of each state is the same, it is possible to compute the covariance matrix more simply using the standard MATLAB function cov. However, the function assumes that the inputs represent a sample of observations drawn from a larger population and hence adjusts the values in the matrix upwards to offset the bias associated with measuring deviations from a fitted mean. In effect, each value produced by the MATLAB function cov will equal the one given by our formulas times (s/(s-1)), where is the number of states (observations).
To use the cov function, simply provide the matrix of observations, with each row representing a different observation (state) and each column a different asset class. For example, if the returns in our {n*s} matrix R were historic observations and we were willing to assume that they were equally probable we could compute:
C = cov(R')
which would give:
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 44.92 122.58 Asset3 0.00 122.58 360.92
These values are, of course, quite different from those found earlier, due to both the assumption of equal probabilities and the correction for bias.
With this aside completed, we return to our forward-looking example.
It is relatively easy to find a meaning for the elements on the main diagonal of the covariance matrix. But what of the remaining ones? How can one interpret the fact that the covariance of Asset2 with Asset3 is 56.00?
The solution is to scale each covariance by the product of the standard deviations of the associated assets. The result is the correlation coefficient for the two assets, usually denoted by the Greek letter rho:
rho(i,j) = C(i,j)/(sda(i)*sda(j))
The matrix of correlation coefficients is termed (unimaginatively) the correlation matrix. We denote it Corr. To compute it, we compute a matrix containing the products of the asset standard deviations:
sda*sda':
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 18.49 59.27 Asset3 0.00 59.27 190.00
We need to divide each element in the covariance matrix by the corresponding element in this matrix. This can be done in one equation:
Corr = C./(sda*sda')
Giving:
Asset1 Asset2 Asset3 Asset1 NaN NaN NaN Asset2 NaN 1.00 0.94 Asset3 NaN 0.94 1.00
Notice that the elements associated with asset pairs in which one of the assets is riskless are NaN (not a number), since they involve an attempt to divide zero (the covariance) by zero(the product of two standard deviations, one of which is zero).
While the correlation of two assets, one of which is riskless, is not really a number, it sometimes proves helpful to set it to zero. This can be accomplished by adjusting the matrix of the cross-products of the standard deviations to have ones in the cells for which the true value is zero. A simple way to do this is to add to the original matrix a matrix with 1.0 in such positions. Since "true" is represented in MATLAB as 1.0, a single matrix expression does the job. Here is a set of statements that accomplishes the objective:
z = sda*sda'; z = z + (z==0); CC = C./z;
where CC is the desired correlation matrix. In this case:
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 1.00 0.94 Asset3 0.00 0.94 1.00
In most cases, the covariance matrix is known, and the correlation matrix derived from it as an aid in interpretation. However, there are cases in which standard deviations and correlations are estimated first, and the covariance matrix derived from those estimates. To do this, we simply reverse the terms in the definition of correlation. For the element in row i, column j:
C(i,j) = rho(i,j)*sda(i)*sda(j)
And, for the entire matrix:
C =CC.*(sda*sda')
Note that the adjusted matrix CC was used in the latter computation to avoid NaN values in the cells associated with the riskless asset.
Asset covariances are the main ingredients for computing portfolio risks. But we have shown that standard deviations are much easier to interpret than are asset variances. Similarly, correlations often prove more useful for communicating relationships than do covariances.
Correlation coefficients measure the extent of the association between two variables. Each such coefficient must lie between -1 and +1, inclusive. A positive coefficient indicates a positive association: a greater-than-expected outcome for one variable is likely to be associated with a greater- than-expected outcome for the other while a smaller-than-expected outcome for one is likely to be associated with a smaller-than-expected outcome for the other. A negative coefficient indicates a negative association: a greater-than-expected outcome for one variable is likely to be associated with a smaller-than-expected outcome for the other while a smaller-than- expected outcome for one is likely to be associated with a greater-than-expected outcome for the other.
The figures below provide examples. In each case the probabilities of the points shown are assumed to be equal.
In the above examples the variables are roughly jointly normally distributed with means of zero and standard deviations of 1.0 -- roughly, because each of the 100 points is drawn from such a joint distribution so the (sample) distribution of the actual results departs somewhat from the underlying (population) distribution.
Note that in the case of perfect positive correlation (+1.0), the points fall precisely along an upward- sloping straight line. In this case it has a slope of approximately 45 degrees due to the nature of the variables. In general, the line may have a greater or smaller slope. Nonetheless, a necessary and sufficient condition for perfect positive correlation is that all possible outcomes plot on an upward-sloping straight line.
In the case of perfect negative correlation the plot has the opposite characteristic. All points will plot on a downward-sloping straight line. Here too, the slope will depend on the magnitudes of the variables, but the line will be downward-sloping in any event.
As the figures show, in the case of less-than-perfect positive correlation (between 0 and +1.0), the points will tend to follow an upward-sloping line, but will deviate from it. The closer the correlation coefficient is to zero, the greater will be such deviations and the more difficult it will be to see any positive relationship. In the case of less-than-perfect negative correlation (between 0 and -1), the points will tend to follow a downward-sloping line. Here too, the closer the correlation coefficient is to zero, the greater will be the deviations and the more obscure the relationship.
If the correlation coefficient is zero, the best linear approximation of the relationship will be a flat line. This does not preclude the possibility that there is a non-linear relationship between the variables. The figure below shows a case in which the correlation coefficient is zero, but knowledge of the value of the variable on the horizontal axis would help a great deal if one wished to predict the value of the variable on the vertical axis. In this case the variables are uncorrelated, but they are not independent.
In the special case in which probabilities are equal, one can use the MATLAB function corrcoef to compute a correlation matrix directly from an {n*s} matrix of values of n assets in s different states of the world, with each row representing a different state (observation) and each column a different asset. For example:
corrcoef(R')
would give:
Asset1 Asset2 Asset3 Asset1 NaN NaN NaN Asset2 NaN 1.00 0.96 Asset3 NaN 0.96 1.00
In this case the only source of the differences from our forward- looking estimates is the use of equal probabilities rather than the predicted probabilities. Since the correlation coefficient is the ratio of estimated variance to the product of two estimated standard deviations, any adjustment of the covariance matrix for sample bias cancels out, leaving the correlation coefficients unaffected.
Analysts frequently utilize historic returns to estimate the covariances among future returns. If all returns, past and future, were drawn from a stable joint distribution, it would be desirable to use as many observations from the past as possible in order to maximize the accuracy of the resultant estimates of the true underlying process that will generate future returns. However, if the parameters of the distribution are likely to have changed over time, the situation is more difficult. One can utilize a great deal of data, much of which may be of limited relevance for the future. Alternatively, a small amount of recent data can be employed, with the attendant danger of substantial estimation errors. Which is better -- a great deal of possibly irrelevant data or too little relevant data?
There is no easy answer to the question. The optimal procedure ultimately will depend on the manner in which covariances evolve through time. Some Analysts approach the problem by limiting the historic data to, say, 60 monthly observations, with each observation assigned the same weight (probability). Others select only periods in which underlying conditions are assumed to have been similar to those existing at the present time (e.g. periods following recessions if a recession has recently been experienced). Yet others employ complex procedures in which covariances are assumed to be positively correlated but with a tendency to eventually revert to a long-run mean value. Here we focus on a simple procedure utilized in a number of asset allocation models that assumes that the future is more likely to be like the recent past than the distant past.
In an exponential weighting scheme each historic observation is assigned a multiple of the weight assigned to its predecessor. For example, observation t could be assigned a weight equal to 2^(t/h) divided by a constant (k), with the latter set so that the sum of all the weights equaled 1.0. In such a scheme h can be interpreted as an assumed half-life. To see why, consider the weights assigned to months t and t-h:
w(t) = (2^(t/h))/k w(t-h) = (2^((t-h)/h))/k
Thus:
w(t)/w(t-h) = (2^(t/h))/((2^t/h)/2) = 2
Thus if month t is the most recent month and h=60, the observation 60 months ago will be assigned half as much weight as the most recent month.
The weight assigned to any month relative to that assigned to its predecessor will be:
(2^(t/h))/(2^((t-1)/h))
which will equal 2^(1/h). Thus if a 60-month half life is utilized, each month's observation will be given a weight equal to 2^(1/60) or 1.0116 times that given the prior month (1.16% higher).
It is relatively straightforward to compute a set of such weights using MATLAB. Assume that there are T observations. The vector of dates (1,2,...T) is given by:
d = 1:1:T;
The vector of 2^(t/h) values will be:
w = 2.^(d/h)
where h is the desired half-life.
The weights can easily be normalized so that they sum to 1.0:
p = w/sum(w)
We denote the result p since the weights will serve as probabilities. In a sense, the assumption is made that the probability is p(t) that next month's returns will equal those that occurred in month t.
Having selected a set of probabilities, we proceed as before to estimate expected returns, deviations and the covariance matrix:
e = R*p; d = R - e*ones(1,T); C = d*diag(p)*d';
The library function wcov obviates the need to remember all these formulas. It takes as inputs a matrix of returns for n assets in s states (or from s historic time periods). For convenience, the return matrix can have assets in the rows and states (observations) in the columns or vice-versa. The function assumes (reasonably) that the number of states (observations) exceeds the number of assets and proceeds accordingly.
To cover more cases, the half-life parameter can be specified as zero, in which event the states (observations) are given equal weights.
The simplest way to utilize the function is as follows:
C = wcov(R,h)
where R is the matrix of returns, h is the half-life and C is the resultant covariance matrix.
If more information is desired, one or more additional variables may be indicated. For example:
[C,sda] = wcov(R,h)
will also return sda as the vector of standard deviations.
The statement:
[C,sda,CC] = wcov(R,h)
will also return CC as the matrix of correlation coefficients, following the convention that the correlation coefficient is zero if the corresponding covariance is zero.
Finally, the statement:
[C,sda,CC,e] = wcov(R,h)
will also return the expected returns, based on the assumption that future probabilities equal the weights computed from the assumed half-life.
The Weighted Statistics Worksheet allows you to compute both equal-weighted and exponentially-weighted means, standard deviations and correlation coefficients. An example using returns for a set of Vanguard mutual funds from 1991 through 1995 provides a chance for you to experiment with different weighting schemes. Try a half-life of zero for equal weights, then compare the results with those obtained with other values (for example, 12, 24, .. 60). You might even wish to try a negative half-life to weight earlier observations more heavily than later ones.
You may also wish to copy and paste other return series into the weighted statistics worksheet so that you can calculate the resulting historic statistics.
It is remarkably easy to determine the covariances between two portfolios. Recall the formula for computing the covariance of portfolio x:
vp = x'*C*x
where x is the vector with the portfolio composition and C is the covariance matrix for asset returns.
Now, let xa represent one portfolio and xb another. For example:
xa Asset1 0.10 Asset2 0.50 Asset3 0.40
xb Asset1 0.40 Asset2 0.10 Asset3 0.50
Assume that the covariance matrix (C) is:
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 18.49 56.00 Asset3 0.00 56.00 190.00
The covariance between the two portfolios is given by:
cab = xa'*C*xb
Which in this case equals 55.16.
The relationship can be extended to cover a case in which there are multiple portfolios. Let X be an {n*p} matrix containing information on the composition of p portfolios of n assets. For example:
xa xb Asset1 0.10 0.40 Asset2 0.50 0.10 Asset3 0.40 0.50
Then the covariance matrix for the portfolios is given by:
Cp = X'*C*X
Which gives:
xa xb xa 57.42 55.16 xb 55.16 53.28
Note that the elements on the main diagonal indicate the variances of the two portfolios, while the other elements equal their covariance.
It is straightforward to compute the covariance of each asset with a given portfolio. Recall the statement for the covariance of portfolio xa with portfolio xb:
cab = xa'*C*xb
This can be computed in two operations:
cab = xa'*(C*xb)
For example, with xb:
Asset1 0.40 Asset2 0.10 Asset3 0.50
and C:
Asset1 Asset2 Asset3 Asset1 0.00 0.00 0.00 Asset2 0.00 18.49 56.00 Asset3 0.00 56.00 190.00
then
cab = xa'*cp
where cp = C*xb, or:
cp Asset1 0.00 Asset2 29.85 Asset3 100.60
Now, assume that xa contains only the first asset:
xa Asset1 1.00 Asset2 0.00 Asset3 0.00
Clearly, the covariance of xa with xb will equal the first value in vector cp (0.00).
If xa contained only the second asset, its covariance with xb would equal the second value in vector cp (29.85). And so on.
The conclusion is not hard to reach. Vector cp contains the covariances of the asset classes with portfolio xb.
More generally, if:
cp = C*x
then cp(i) is the covariance of asset i with portfolio x.
Note that the covariance of an asset with a portfolio will be a weighted average of its covariances with all the assets (including itself), with the composition of the current portfolio used as weights..
Given this central fact of investment life, it follows that the impact on the risk of a portfolio of a small change in the amount invested in a particular asset is not simply a function of the risk of that asset. The impact will depend on the covariances of the asset with all the other assets currently in the portfolio and on the composition of the portfolio.
Consider a portfolio x and a "difference vector" d. We wish to determine the effect on portfolio variance of a switch from portfolio x to portfolio x+d.
The variance of x will be:
vx = x'*C*x
While that of (x+d) will be:
vv = (x+d)'*C*(x+d)
The latter can be expanded by noting first that (x+d)'=x'+d', giving:
vv = (x'+d')*C*(x+d)
then by multiplying out all the terms:
vv = x'*C*x + x'*C*d + d'*C*x + d'*C*d
Since the first term of the latter expression equals the variance of x, the change in variance is given by the sum of the last three terms:
dvp = x'*C*d + d'*C*x + d'*C*d
The first two terms are the same. This follows from the facts that: (1) the transpose of a scalar is the same scalar, (2) the transpose of a product of matrices is the product of their transposes, taken in reverse order and (3) the covariance matrix C is symmetric, so that its transpose equals the original matrix. Given this, we may write:
dvp = 2*d'*C*x + d'*C*d
We are interested here in the effect on variance of a small change in the holding of one asset. Thus d will contain only one small non-zero element. For example,if we wished to know the effect of a small change in the holdings of asset 2 we could set:
d Asset1 0.00 Asset2 0.01 Asset3 0.00
Since the elements in d will be either zero or very small (very much less than 1.0), the final term in the earlier expression (d'*C*d) will be even smaller. Indeed, as d approaches zero, the one element in d'*C*d will approach zero considerably faster, since it involves the square of the non-zero element in d. For purposes of computing the marginal effect of a change we may ignore the final term, giving:
dvp = 2*d'*C*x
or
dvp = d'*2*C*x
From this it follows that d(vp)/d(x(j)) will equal the j'th row of 2*C*x. More generally, 2*C*x is the vector of marginal risks of the asset classes:
mr = 2*C*x
with mr(j) indicating the change in portfolio variance per unit change in the amount invested in asset j.
Note finally, that C*x is the vector of the covariances of the assets with portfolio x, which we have denoted cp. Thus:
mr = 2*cp
and two times the covariance of an asset with a portfolio indicates the marginal risk of that asset, given the composition of the portfolio. In our case:
mr Asset1 0.00 Asset2 59.70 Asset3 201.20
Thus variance would not be affected by a small change in the holding of asset 1. It would increase at a rate of 59.70 per unit change in Asset 2 and at a rate of 201.20 per unit change in Asset 3. Of course these figures hold only approximately for finite changes in the assets, with the error greater, the larger the underlying change. Moreover, they assume that only one element in the portfolio is changed. If the assets represent zero investment strategies this may be feasible. If, however, they are true investments, at least one holding will have to be decreased for another to be increased. We will take these aspects into account in later discussions. For now it suffices to have determined the vector of derivatives of variance with respect to asset holdings. | http://web.stanford.edu/~wfsharpe/mia/rr/mia_rr4.htm | CC-MAIN-2015-06 | refinedweb | 5,283 | 54.73 |
Profiling django views for SQL queries
We at HackerEarth regularly conduct 24-hours internal hackathons usually once a month to boost ourselves to get familiar with new technologies and to come up with great ideas and hacks to increase our productivity. A hackathon project can be anything from creating a new product to creating some tools which helps our own devlopment. In the hakathon in Dec 2015, I came up with the idea to create a profiler which could tell which code inside django views causes SQL queries so that we can optimize them easily.
Initial thoughts
There are already many good django packages to profile views for SQL queries. One of them is django-toolbar which we already use. Django-toolbar is great but it shows all raw SQL queries which are happening inside a view and you have to analyze each query, see the whole traceback and figure out which line of code inside the view is triggering the query. This way, you can only figure out the line number of the code in a file, not the exact function or expression or attribute access which is causing the query. What I wanted was that a profiler should tell about the exact expressions which trigger the SQL queries.
There were some solutions which came up in my mind to get it done like using tracebacks or by manipulating AST of the python function. Praveen had just told me about the python’s ast module which can parse and modify code during runtime and I was fascinated about using it in future. I chose to use AST manipulation to implement the profiler and the trick here is to patch every function call, attribute access and other constructs. Here is what I thought:
Suppose there is a function
f which internally calls
get_user triggering a SQL query
@profile def f(request): ... user = get_user(request) ...
and decorating the function
f with
profile decorator will manipulate its
AST code.
It will find all
locations of function calls inside function body and will encapsulate it
in our special function
call_handler. So the function
f’s definition will
become
def f(request): ... user = call_handler(get_user, request) ...
call_handler will call the passed function with given arguments. Before
calling it will start tracking for the SQL queries. And after the function
has been called it will collect the sql_queries and will store it with the
function so that we can see later if during call any SQL query was made.
Moreover, to attain the functionality of collecting queries I will have to
patch the django code which makes SQL queries (I will talk about it later).
It’s definition would be something like
def call_handler(func, *args, **kwargs): sql_counter.start_tracking() result = func(*args, **kwargs) sql_queries = sql_counter.collect_queries() store_queries(func, sql_queries) return result
And then we’ll be able to see what calls inside function made SQL queries.
Implementation
How to manipulate AST?
The python docs of ast doesn’t give much information on usage of it. Then I found Green Tree Snakes. Also I found an example to convert python code to javascript in a stackoverflow’s answer using ast transformation. I found them pretty helpful.
There were following improvements in initial ideas while implementing:
There are many cases other than function calling where python code gets executed e.g. on attribute access, automatic coercion to bool in
if/
else ifstatements and automatic coercion to iter in
forstatement. So I’d to cover them up too.
The
call_handlerwas making whole function body unhygienic because any other usage of name
call_handlerwill clash with it. So I thought to make a namespace with very unique name that nobody will define in any other place. Here, I came up with word
goofyand replaced decorator
profilewith
goofy.profile()and replaced
call_handlerwith
goofy.call_handler. And the only thing that I’ll have to import is
goofy.
In
goofy.call_handlerI need to pass other information like
lineno,
colnotoo along with the calling function.
Here is the code which transforms the AST
import ast class Transformer(ast.NodeTransformer): def __init__(self, lineno): """ lineno is the actual position of function code in source file """ self._lineno = lineno self._dec_lineno = 1 def visit_FunctionDef(self, func): """ Remove decorators so that the decorators doesn't get applied more. """ for dec in func.decorator_list: if (isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute) and isinstance(dec.func.value, ast.Name) and dec.func.value.id == 'goofy' and dec.func.attr == 'profile'): self._dec_lineno = dec.lineno func.decorator_list = [] func_ast = self.generic_visit(func) return func_ast def visit_Call(self, call): """ Change the function calling syntax func(*args, **kwargs) will be transformed to goofy.call_handler(func, line_no, col_no, *args, **kwargs) """ call_ast = self.generic_visit(call) call_ast.args.insert(0, call_ast.func) call_ast.func = ast.Attribute( value=ast.Name(id='goofy', ctx=ast.Load()), attr='call_handler', ctx=ast.Load()) call_lineno = self._lineno - self._dec_lineno + call_ast.lineno call_colno = call_ast.col_offset + 1 call_ast.args.insert(1, ast.Num(call_lineno)) call_ast.args.insert(2, ast.Num(call_colno)) return call_ast
There are many variants of statements and expressions in python, details of which you can find in ast docs’s Abstract grammar section. So any type of node that has to be changed while transforming the AST, a corresponding method of visit_<NodeClass> in Transformer class has to be written. (like visit_FunctionDef and visit_Call methods in above code). In actual code, I’d to implement visit_Assign, visit_Attribute, visit_If, visit_BoolOp and visit_For etc. too.
And here’s the code for
goofy class.
def goofy_profiler(f): frame, filename, line_number, _, lines, _ = inspect.stack()[1] if lines[0].startswith('def'): line_number -= 1 source = inspect.getsource(f) decorator_lineno = source.count('\n', 0, source.index('@goofy.profile')+1) + 1 tree = ast.parse(source) transformer = Transformer(line_number) transformed_tree = transformer.visit(tree) ast.fix_missing_locations(transformed_tree) ast.increment_lineno(transformed_tree, line_number - decorator_lineno) module_globals = inspect.getmodule(f).__dict__ exec(compile(transformed_tree, filename=filename, mode="exec"), module_globals) func = eval(f.__name__, module_globals) func = deco(func) return func def deco(func): @wraps(func) def wrapper(*args, **kwargs): SQLCounter.clear_data() SQLCounter.current_func(func) start_time = datetime.now() result = func(*args, **kwargs) timedelta = datetime.now() - start_time print 'Function: {}.{}'.format( func.__module__, func.func_name) print 'Total processing time: {} ms'.format( timedelta.total_seconds()*1000) SQLCounter.show_data() return result return wrapper class goofy(object): @staticmethod def profile(): return goofy_profiler @staticmethod def call_handler(func, lineno, colno, *args, **kwargs): sargs = (" {}(..)".format(func.__name__), lineno, colno) SQLCounter.before(*sargs) result = func(*args, **kwargs) SQLCounter.after(*sargs) return result
Also I’d to patch the execute_sql method of SQLCompiler to collect sql queries.
from django.db.models.sql.compiler import SQLCompiler from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.constants import MULTI def execute_sql(self, *args, **kwargs): try: q, params = self.as_sql() if not q: raise EmptyResultSet except EmptyResultSet: if kwargs.get('result_type', MULTI) == MULTI: return iter([]) else: return start = datetime.now() try: return self.__execute_sql(*args, **kwargs) finally: d = (datetime.now() - start) SQLCounter.insert({ 'query' : q, 'type' : 'sql', 'time' : 0.0 + d.seconds * 1000.0 + d.microseconds/1000.0 }) SQLCompiler.__execute_sql = SQLCompiler.execute_sql SQLCompiler.execute_sql = execute_sql
And here is the code of SQLCounter which collects SQL queries and also the information of what SQL queries got executed at different position inside a function.
class SQLCounter(object): @classmethod def clear_data(cls): cls.current_code = '' cls.check = False cls.data = defaultdict(list) cls.hit_count = defaultdict(int) @classmethod def before(cls, activity, lineno, colno): cls.check = True cls.current_code = ("line no {:<4}: {}".format(lineno, activity), lineno) cls.hit_count[cls.current_code] += 1 @classmethod def after(cls, activity, lineno, colno): cls.check = False @classmethod def insert(cls, data): cls.data[cls.current_code].append(data) @classmethod def current_func(cls, func): cls.func = func @classmethod def show_data(cls): if not cls.data: return data = sorted(cls.data.items(),key=lambda a: a[0][1]) table = [] headers = ['Location', 'Hit', 'Queries', 'Time (ms)', 'Avg Time (ms)'] total_tm = 0.0 total_qs = 0 for current_code, qdata in data: activity, _ = current_code qs = len(qdata) total_qs += qs tm = sum(k['time'] for k in qdata) total_tm += tm avg_tm = tm / qs hit = cls.hit_count[current_code] table.append([activity, hit, qs, tm, avg_tm]) print "Total SQL queries: {}, Total time: {} ms".format( total_qs, total_tm) tabular_table = tabulate(table, headers, tablefmt="simple") print tabular_table
Usage
There is a view
get_bot_submission_response in our codebase and we applied
goofy.profile()
decorator on it to profile it.
from goofy import goofy @goofy.profile() def get_bot_submission_response(request, game): ...
When the view gets called it prints following output to console.
Function: problems.views.get_bot_submission_response Total processing time: 201.499 ms Total SQL queries: 8, Total time: 9.856 ms Location Hit Queries Time (ms) Avg Time (ms) -------------------------------------------- ----- --------- ----------- --------------- line no 100 : .user 1 1 0.97 0.97 line no 100 : .player1 1 1 1.38 1.38 line no 112 : .problem 1 1 1.52 1.52 line no 119 : player_2_name(..) 1 2 2.193 1.0965 line no 138 : get_game_data(..) 1 2 2.244 1.122 line no 163 : render_to_string(..) 1 1 1.549 1.549
All the .<attribute> tells the location of attribute access which triggered SQL queries. .user, .player1, .problem are attribute access and player_2_name(..), get_game_data(..), render_to_string(..) are function calls. I’ve used the tabulate package to pretty print the table.
What’s next
Not only SQL but any type of queries can be profiled in this model. We also added the feature to profile memcached queries in goofy profiler. Lots of more improvements can be done upon it. We’ll soon clean the goofy profiler’s code and open source it on github. Stay tuned!
Posted by Shubham Jain. You can follow me on twitter @sjiitr | http://engineering.hackerearth.com/2016/02/01/profiling-django-views/ | CC-MAIN-2018-09 | refinedweb | 1,596 | 52.76 |
Recent:
Archives:
."
JavaBeans can be configured to "listen" to other software objects. And as you'll see, a Java 1.1 class (including any JavaBean) can listen not only to its parent, but also to any class that produces events by becoming an event listener. The event listener idea is central to how Java classes (and other JavaBeans) handle events.
Last month we discussed a specific type of event listener: the
PropertyChangeListener interface that takes action when other Beans' properties change. This month we'll take a closer look at the whole concept
of an "event listener." You'll see how event listeners are used in the new AWT. (When I say "new," I mean since JDK 1.1 was
released.) We'll talk about how to define your own event types, and then make those new event types visible to other classes.
Then, as an example, we'll extend the BarChartBean, creating a new event type and then using it to wire the BarChartBean to
another Bean. We'll go over some details about how to write event listener interfaces, using the AWT as an example, and conclude
with a discussion of inner classes, a new Java 1.1 language feature.
I'd also like to introduce two new icons that will help identify key points:
A software event is a piece of data that indicates that something has occurred. Maybe a user moved the mouse. Maybe a datagram just arrived from the network. Maybe a sensor has detected that someone's just come in the back door. All of these occurrences can be modeled as events, and information about what happened can be included in the event. Often it's convenient to write software systems in terms of event processing: Programming then becomes a process of specifying "when this happens, do that." If the mouse moved, move the cursor with it; if a datagram arrived, read it; if there's an intruder, play the recording of Roseanne releasing the rabid Rottweiler.
Usually, an event contains information about the event source (the object that created or first received the event), when the event occurred, and some subclass-specific information that the event receiver can use to figure out what happened and what to do. In a windowing system, for example, there might be a subtype of event for mouse clicks. The mouse click event would include the time the click occurred, and also might include such information as where on the screen the mouse was clicked, the state of the SHIFT and ALT buttons, and an indication of which mouse button was clicked. The code that handles the event is called, strangely enough, the event handler.
So, what does this have to do with JavaBeans? Events are the primary way that Beans communicate with each other. As we'll see below, if you choose events and their connections judiciously, you can interconnect Beans in your application, tell each Bean what to do in response to the events it cares about, and the application simply behaves. Each Bean minds its own business, responding appropriately to incoming events, and sending new events to interested neighboring Beans as new situations occur. Once you understand how to use events, you can write Beans that use them to communicate with other components. And what's more, external systems like Integrated Development Environments (IDEs) automatically detect the events your Beans use and let you interconnect Beans graphically. IDEs also can send events to and receive events from JavaBeans, essentially controlling them from the outside.
In order to understand how events work with Beans, though, you've got to understand how they work in Java. And events work differently now that JDK 1.1 is the standard.
In the Java Developer's Kit (JDK) 1.0, events were used primarily in the Abstract Windowing Toolkit (AWT) to tell classes when something happened in the user interface. Programmers used inheritance to process events by subclassing an object that could receive that event type and overriding how the parent class processed the event.
For example, in Java version 1.0, the only way to get an Action event was to inherit from some other class that already knew how to handle Action events:
public class MyButton extends java.awt.Button { // Override action() method to handle action event public boolean action(Event evt, Object what) { // Now do something with the action event } }
This means that only classes that inherited from java.awt.Button could do anything to respond to a button click. This structure left Java events tied to the user interface and inflexible. It wasn't easy to create new event types. And even if you could create new events, it was hard to change the events that a class could respond to, because that information was hard-coded into the "family tree" (the inheritance graph) of the AWT.
The new JDK 1.1 has a more general event structure, which allows classes that produce events to interact with other classes that don't. Instead of defining event-processing methods that client subclasses must override, the new model defines interfaces that any class may implement if it wants to receive a particular message type. (You may hear this referred to as processing events by delegation instead of by inheritance.) Let's continue with this JDK 1.0 button example and move toward the JDK 1.1 model.
Let's say I wanted to create a new class that does something when a button is pressed. In 1.0, I'd have to subclass
java.awt.Button to handle the Button action event, and then that button would somehow notify my new class that the button press had occurred:
//... elsewhere in the program we define the object that "listens" // for button actions. ActionListener myActionListener = new ActionListener(); //... // Button action event public class MyButton extends java.awt.Button { // Override action() to notify my new class public boolean action(Event evt, Object object) { myActionListener.action(evt, object); } }
Now the object
myActionListener receives an event every time any
MyButton is pushed.
myActionListener is not necessarily a subclass of java.awt.Component, but it does contain an
action() method. We call the new class an
ActionListener because, seen from the new class's point of view, it is "listening" for action events on the button it is "attached" to.
There are still some problems, though: | http://www.javaworld.com/javaworld/jw-10-1997/jw-10-beans.html | crawl-002 | refinedweb | 1,061 | 63.29 |
I am trying to add two numbers represented by Linked List in FORWARD direction. I have written the function to add them, but I am unable to understand how to forward carry to next level. It is turning out to be zero all time. Please advise me corrections in add function below,
Update1# I have written padding functionto make linked lists of equal length by adding zero to front of smaller number as below,
**Input:**
First Number : 351 0->3->5->1
Second Number : 2249 2->2->4->9
Correct Addition : 2600 2->6->0->0
The result I am getting is 2590 2->5->9->0
======================= Code ============================
#The carry is passed as zero.
def addRecursively(self, h1, h2, carry):
if h1 == None and h2 == None:
return None
self.addRecursively( h1.next, h2.next, carry)
print "h1.val: ", h1.data," h2.val: ", h2.data, " Carry: ", carry
num =carry
if h1:
num +=h1.data
if h2:
num +=h2.data
carry = 1 if num>=10 else 0
num = num % 10
print "num: ", num, " carry: ",carry
=============================================================
Output:
h1.val: 1 h2.val: 9 Carry: 0
num: 0 carry: 1
h1.val: 5 h2.val: 4 Carry: 0
num: 9 carry: 0
h1.val: 3 h2.val: 2 Carry: 0
num: 5 carry: 0
h1.val: 0 h2.val: 2 Carry: 0
num: 2 carry: 0
def saveToLL(self, data) :
if self.head == None:
self.head = Node(data)
else:
node = Node(data)
node.next = self.head
self.head =node
return self.head
# ===== Addition function to add element using stack =====
def addRecursively(self, h1, h2):
if h1 == None and h2 == None:
return 0
# carry will be returned by recursive call
carry = self.addRecursively( h1.next, h2.next)
print "h1.val: ", h1.data," h2.val: ", h2.data, " Carry: ", carry
num = carry
if h1:
num +=h1.data
if h2:
num +=h2.data
# now return the carry of the current addition
carry_ret = 1 if num >= 10 else 0
# this should be set somewhere in self or one of the lists?
num = num % 10
self.saveToLL(num)
return carry_ret
The issue is that you need the recursive call to tell you whether there was a carry in the recursive addition that you need to add to the current position. For example, if you call add as
addRecursively(1->2, 1->9), it is going to recursively call
addRecursively(2, 9) and the first call needs to know to add an extra 1 to the addition of 1 + 1 (the 0th position digits).
I don't know how your code is setting values in the class that is keeping track of the numbers, but what you can do is have the recursive call return how much to carry:
# No carry passed in def addRecursively(self, h1, h2): if h1 == None and h2 == None: return 0 # carry will be returned by recursive call carry = self.addRecursively( h1.next, h2.next) num = carry if h1: num += h1.data if h2: num += h2.data num = num % 10 self.saveToLL(num) # now return the carry of the current addition return 1 if num >= 10 else 0
I take it the code you posted is more pseudocode and not the exact code you are using? It never seems to set anything of self or either of the lists. Am I missing something?
You can do what you are trying to do by passing carry into the recursive call and having it set the value of carry, but then you need to pass the carry "by reference" so that the changes persist. To do this, you could wrap the int in a class (say a Digit class?). | https://codedump.io/share/1wvEXU4YsAB3/1/adding-two-num173bers-rep173re173sented-by-a-linked-list-num173ber-stored-in-forward-order--python | CC-MAIN-2021-39 | refinedweb | 601 | 73.68 |
Software Engineering. Project Management. Effectiveness.
Here's a quick step through of using WCF in Visual Studio 2005. In this case I used a local machine, running Windows 2003, for the service and the client.
There's lot of possible paths, and this is just one path through. I focused on "Hello World" to run through the basic mechanics, but chose a path to touch enough things that might be interesting to explore another day.
ScenarioUse Visual Studio 2005 to do a dry run of creating a WCF service hosted in IIS and calling it from a console application on your local development workstation. (Note that you don't need to host WCF in IIS; for example, you could use a surrogate console application.)
PreparationIn my case, I needed the .NET 3.0 components and the WCF extensions for Visual Studio:1. .NET 3.0 Runtime Components2. WCF and WPF extensions for Visual studio
Summary of Steps
Step 1. Create the test serviceIn this step, we'll create a WCF service that uses HTTP bindings, for backward compatibility (non-.NET 3.0 clients)
Step 2. Add a Hello World MethodIn Service.cs, you'll add your Hello World method:
Compile and debug any errors.Step 3. Test your WCF service
There's two issues you might hit here:
Step 4. Enable meta-data for your WCF Service.
Step 5. Create the test client.In this step, we'll create a quick console app to call the WCF service:
Step 6. Add a Web Services reference to your WCF Service.In this step, we'll add a Web Services reference.
Step 7. Add the namespace to your
Step 8. Call your WCF serviceIn your test client, call your WCF service: static void Main(string[] args) { MyService service = new MyService(); string foo; foo = service.HelloWorld(); Console.WriteLine(foo); }When you compile and run your console application, you should see the following:Hello WorldPress any key to continue . . .
Additional Resources
Hopefully this step through helps you quickly see some of the bits and pieces you can play with.
J. | http://blogs.msdn.com/jmeier/archive/2007/10/15/how-to-create-a-hello-world-wcf-service-using-visual-studio.aspx | crawl-002 | refinedweb | 346 | 66.23 |
Reduce JavaScript payloads with tree shaking
Today roughly 300 KB when compressed.
JavaScript is an expensive resource to process. Unlike images which only incur relatively trivial decode time once downloaded, JavaScript must be parsed, compiled, and then finally executed. Byte for byte, this makes JavaScript more expensive than other types of resources.
While improvements are continually being made to improve the efficiency of JavaScript engines, improving JavaScript performance is—as always—a task for developers.
To that end, there are techniques to improve JavaScript performance. Code splitting, is one such technique that improves performance by partitioning application JavaScript into chunks, and serving those chunks to only the routes of an application that need them.
While this technique works, it doesn't address a common problem of JavaScript-heavy applications, which is the inclusion of code that's never used. Tree shaking attempts to solve this problem. an app is young—a sapling, if you will—it may have few dependencies. It's also using most—if not all—the dependencies you add. As your app matures, static
import statements code)—this example imports only specific parts of it. In dev builds, this doesn't change anything, as the entire module gets imported regardless. In production builds, webpack can be configured to "shake" off exports from ES6 modules that weren't explicitly imported, making those production builds smaller. In this guide, you'll learn how to do just that!
Finding opportunities to shake a tree #
For illustrative purposes, a sample one-page app is available that demonstrates how tree shaking works. You can clone it and follow along if you like, but we'll cover every step of the way together in this guide, so cloning isn't necessary (unless hands-on learning is your thing).
The sample app is a searchable database of guitar effect pedals. You enter a query and a list of effect pedals will appear.
The behavior that drives this app is separated into vendor (i.e., Preact and Emotion) and app-specific code bundles (or "chunks", as webpack calls them):
The JavaScript bundles shown in the figure above are production builds, meaning they're optimized through uglification. 21.1 KB for an app-specific bundle isn't bad, but it should be noted that no tree shaking is occurring whatsoever. Let's look at the app code and see what can be done to fix that.
In any application, finding tree shaking opportunities are going to involve looking for static
import statements. Near the top of the main component file, you'll see a line like this:
import * as utils from "../../utils/utils";
You can import ES6 modules in a variety of ways, but ones like this should get your attention. This specific line says "
import everything from the
utils module, and put it in a namespace called
utils." The big question to ask here is, "just how much stuff is in that module?"
If you look at the
utils module source code, you'll find there's about 1,300 lines of code.
Do you need all that stuff? Let's double check by searching the main component file that imports the
utils module to see how many instances of that namespace come up.
As it turns out, the
utils namespace appears in only three spots in our application—but for what functions? If you take a look at the main component file again, it appears to be only one function, which is
utils.simpleSort, which is used to sort the search results list by a number of criteria when the sorting dropdowns are changed:
if (this.state.sortBy === "model") {
// `simpleSort`);
}
Out of a 1,300 line file with a bunch of exports, only one of them is used. This results in shipping a lot of unused JavaScript.
While this example app is admittedly a bit contrived, it doesn't change the fact that this synthetic sort of scenario resembles actual optimization opportunities you may encounter in a production web app. Now that you've identified an opportunity for tree shaking to be useful, how is it actually done?
Keeping Babel from transpiling ES6 modules to CommonJS modules #
Babel is an indispensable tool, but it may make the effects of tree shaking a bit more difficult to observe. If you're using
@babel/preset-env, Babel may transform ES6 modules into more widely compatible CommonJS modules—that is, modules you
require instead of
import.
Because tree shaking is more difficult to do for CommonJS modules, webpack won't know what to prune from bundles if you decide to use them. The solution is to configure
@babel/preset-env to explicitly leave ES6 modules alone. Wherever you configure Babel—be it in
babel.config.js or
package.json—this involves adding a little something extra:
// babel.config.js
export default {
presets: [
[
"@babel/preset-env", {
modules: false
}
]
]
}
Specifying
modules: false in your
@babel/preset-env config gets Babel to behave as desired, which allows webpack to analyze your dependency tree and shake off unused dependencies. example,
addFruit produces a side effect when it modifies the
fruits array, which is outside its scope.
Side effects also apply to ES6 modules, and that matters in the context of tree shaking. Modules that take predictable inputs and produce equally predictable outputs without modifying anything outside of their own scope are dependencies that can be safely dropped if we're not using them. They're self-contained, modular pieces of code. Hence, "modules".
Where webpack is concerned, a hint can be used to specify's needed #
After instructing Babel to leave ES6 modules alone, a slight adjustment to our
import syntax is required to bring in only the functions needed from the
utils module. In this guide's example, all that's needed is the
simpleSort function:
import { simpleSort } from "../../utils/utils";
Because only
simpleSort is being imported instead of the entire
utils module, every instance of
utils.simpleSort will need to changed to
simpleSort:
if (this.state.sortBy === "model") {
json = simpleSort(json, "model", this.state.sortOrder);
} else if (this.state.sortBy === "type") {
json = simpleSort(json, "type", this.state.sortOrder);
} else {
json = simpleSort(json, "manufacturer", this.state.sortOrder);
}
This should be all that's needed for tree shaking to work in this example. is successful:
Asset Size Chunks Chunk Names
js/vendors.45ce9b64.js 36.9 KiB 0 [emitted] vendors
js/main.559652be.js 8.46 KiB 1 [emitted] main
While both bundles shrank, it's really the
main bundle that benefits most. By shaking off the unused parts of the
utils module, the
main bundle shrinks by about 60%. This not only lowers the amount of time the script takes to the download, but processing time as well.
Go shake some trees! #
Whatever mileage you get out of tree shaking depends on your app and its dependencies and architecture. Try it! If you know for a fact you haven't set up your module bundler to perform this optimization, there's no harm trying and seeing how it benefits your application.
You may realize a significant performance gain from tree shaking, or not much at all. But by configuring your build system to take advantage of this optimization in production builds and selectively importing only what your application needs, you'll be proactively keeping your application bundles as small as possible.
Special thanks to Kristofer Baxter, Jason Miller, Addy Osmani, Jeff Posnick, Sam Saccone, and Philip Walton for their valuable feedback, which significantly improved the quality of this article. | https://web.dev/reduce-javascript-payloads-with-tree-shaking/ | CC-MAIN-2022-21 | refinedweb | 1,249 | 63.09 |
XML::Essex::Model - Essex objects representing SAX events and DOM trees
Used internally by Essex, see below for external API examples.
A description of all of the events explicitly supported so far. Unsupported events are still handled as anonymous events, see XML::Essex::Event for details.
A goal of essex is to allow code to be as terse or verbose as is appropriate for the job at hand.
So almost every object may be abbreviated.
So
start_element may be abbreviated as
start_elt for both the
isa() method/function and for class creation.
All objects are actually blessed in to classes using the long name,
like
XML::Essex::start_element even if you use an abbreviation like
XML::Essex::start_elt-new> to create them.
All events are stringifiable for debugging purposes and so that attribute values,
character data,
and processing instructions may be matched with Perl string operations like regular expressions and
index().
It is usually more effective to use EventPath,
but you can use stringified values for things like complex regexp matching.
It is unwise to match other events with string operators because no XML escaping of data is done,
so "<" in an attribute value or character data is stringified as "<",
so
print()ing out the three events associated with the sequence "<foo><bar/></foo>" will look like "<foo><bar/></foo>",
obviously not what the document intended.
Given the rarity of such constructs in real life XML,
though,
this is sufficient for debugging purposes,
and does make it easy to match against strings.
Ordinarily,
you tell
get() what kind of object you want using an EventPath expression:
my $start_element = get "start_element::*";
You can also just
get() whatever's next in the document or use a union expression. In this case, you may need to see what you've gotten. The
isa() method (see below) and the
isa() functions (see XML::Essex) should be used to figure out what type of object is being used before relying on the stringification:
get until isa "chars" and /Bond, James Bond/; get until type eq "characters" and /Bond, James Bond/; get until isa( "chars" ) && /Bond, James Bond/; get "text()" until /Bond, James Bond/;
This makes it easier to match characters data, but other methods should be used to select things like start tags and elements:
get "start_element::*" until $_->name eq "address" && $_->{id} eq $id; get "start_element::address" until $_->{id} eq $id;
The lack of escaping only affects stringification of objects, for instance:
warn $_; ## See what event is being dealt with right now /Bond, James Bond/ ## Match current event
. Things are escaped properly when the put operator is used, using
put() emits properly escaped XML.
Some observervations:
<?xml ...?>, which is parsed by all XML parsers).
sort()function.
<?xml...?>declaration, often have things that look like attributes but are not, so the items above about whitespace and attribute sort order do not apply. Actually, the
<?xml ... ?>declaration is well defined and there will be only a single whitespace character, though the pseudo-attributes version, encoding and standalone will not be sorted.
"{}foo"), except for the empty namespace URI, which alway stringifies as "" (ie no prefix). See XML::Essex's Namspaces section for details.
All of the objects in the model provide the following methods. These methods are exported as functions from the XML::Essex module for convenience (those functions are wrappers around these methods).
Returns TRUE if the object is of the type, abbreviated type, or class passed. So, for an object encapsulating a characters event, returns TRUE for any of:
XML::Essex::Event ## The base class for all events XML::Essex::start_document ## The actuall class name start_document ## The event type start_doc ## The event type, abbreviated
Returns the class name, such as
XML::Essex::start_document.
Returns the class name, such as
start_document.
Returns the class name, the type name and any abbreviations. The abbreviations are sorted from longest to shortest.
aka: start_doc
my $e = start_doc \%values; ## %values is not defined in SAX1/SAX2
Stringifies as:
start_document($reserved)
where $reserved is a character string that may sometime include info passed in the start_document event, probably formatted as attributes.
aka: (no abbreviations)
my $e = xml_decl; my $e = xml_decl Version => "1", Encoding => "UTF-8", Standalone => "yes"; my $e = xml_decl { Version => "1", Encoding => "UTF-8", Standalone => "yes" };
Stringifies as:
<?xml version="$version" encoding="$enc" standalone="$yes_or_no"?>
Note that this does not follow the sorted attribute order behavior of start_element, as the seeming attributes here are not attributes, like processing instructions that have pretend attributes.
aka: end_doc
my $e = end_doc \%values; ## %values is not defined in SAX1/SAX2
Stringifies as:
end_document($reserved)
where $reserved is a character string that may sometime include info passed in the end_document event, probably formatted as attributes.
aka: start_elt
my $e = start_elt foo => { attr => "val" }; my $e = start_elt $start_elt; ## Copy constructor my $e = start_elt $end_elt; ## end_elt deconstructor my $e = start_elt $elt; ## elt deconstructor
Stringifies as:
<foo attr1="$val1" attr2="val2">
The element name and any attribute names are prefixed according to namespace mappings registered in the Essex processor, the prefixes they had in the source document are ignored. If no prefix has been mapped, jclark notation (
{http:...}foo) is used. Then they are sorted according to Perl's
sort() function, so jclarked attribute names come last, as it happens.
TODO: Support attribute ordering via consecutive {...} sets.
Attributes may be accessed using hash dereferences:
get "start_element::*" until $_->{id} eq "10"; ## No namespace prefix get "start_element::*" until $_->{"{}id"} eq "10"; get "start_element::*" until $_->{"{}id"} eq "10"; get "start_element::*" until $_->{"foo:id"} eq "10";
and the attribute names may be obtained by:
keys %$_;
. Keys are returned in no predictable order, see Namespaces for details on the three formats keys may be returned in.
Returns the name of the node according to the namespace stringification rules.
Returns the name of the node in James Clark notation.
my @keys = $e->jclark_keys
Returns a list of attribute names in jclark notation ("{...}name").
aka: attr
my $name_attr = $start_elt->{name}; my $attr = attr $name; my $attr = attr $name => $value; my $attr = attr { LocalName => $local_name, NamespaceURI => $ns_uri, Value => $value, };
Stringifies as its value:
harvey
This is not a SAX event, but an object returned from within element or start_element objects that gives you access to the
NamespaceUri,
LocalName, and
Value fields of the attribute. Does not give access to the Name or Prefix fields present in SAX events.
If you create an attribute with an undefined value, it will stringify as the
undefined value. Attributes that are created without an explicit
undefined
Value field will be given the defaul value of "", including attributes that are autovivified. This allows
get "*" until $_->{id} eq "10";
to work. This has the side effect of addingan
id="" attribute to all elements without an
id attribute. To avoid the side effect, use the
exists function to detect nonexistant attributes:
get "*" until exists $_->{id} and $_->{id} eq "10";
aka: end_elt
my $e = end_element "foo"; my $e = end_element $start_elt; my $e = end_element $end_elt; my $e = end_element $elt;
Stringifies as:
</foo>
See start_element for details on namespace handling.
aka: elt
my $e = elt foo => "content", $other_elt, "more content", $pi, ...; my $e = elt foo => { attr1 => "val1" }, "content", ...;
Stringifies as:
<foo attr1="val1">content</foo>
Never stringifies as an empty element tag (
<foo/>), although downstream filters and handlers may choose to do that.
Constructs an element. An element is a sequence of events between a matching start_element and end_element, inclusive.
Attributes may be accessed using Perl hash dereferencing, as with start_element events, see "start_element" for details.
Content may be accessed using Perl array dereferencing:
my @content = @$_; unshift @$_, "prefixed content"; push @$_, "appended content";
Note that
my $elt2 = elt $elt1; ## doesn't copy content, just name+attra
only copies the name and attributes, it does not copy the content. To copy content do either of:
my $elt2 = elt $elt1, @$elt1; my $elt2 = $elt1->clone;
This is because the first parameter is converted to a start/end_element pair and any content is ignored. This is so that:
my $elt2 = elt $elt1, "new content";
creates an element with the indicated content.
Returns the names of attributes as a list of JamesClarkified keys, just like start_element's
jclark_keys().
Returns the name of the node according to the namespace stringification rules.
Returns the name of the node in James Clark notation.
aka: chars
my $e = chars "A stitch", " in time", " saves nine"; my $e = chars { Data => "A stitch in time saves nine", };
Stringifies like a string:
A stitch in time saves nine.
Character events are aggregated.
TODO: make that aggregation happen.
aka: (no abbreviation)
my $e = comment "A stitch in time saves nine"; my $e = comment { Data => "A stitch in time saves nine", };
Stringifies like a string:
A stitch in time saves nine.
Instances of the Essex object model classes carry a reference to the original data (SAX events), rather than copying it. This means that there are fewer copies (a good thing; though there is an increased cost of getting at any data in the events) and that upstream filters may send blessed, tied, or overloaded objects to us and they will not be molested unless the Essex filter messes with them. There is also an implementation reason for this, it makes overloading hash accesses like
$_-{}> easier to implement.
Passing an Essex event to a constructor for a new Essex event does result in a deep copy of the referenced data (via
XML::Essex::Event::clone()).
The objects in the Essex object model are not available independantly as class files. You must use
XML::Essex::Model to get at them. This is because there is a set of event types used in almost all SAX filters and it is cheaper to compile one file containing these than to open multiple files.
This does not mean that all classes are loaded when the XML::Essex::Model is
use()ed or
require()ed, rare events are likely to be autoloaded.
In order to allow
my $e = XML::Essex::start_elt( ... );
to work as expected--in case the calling package prefers not to import
start_elt(), for instance--the objects in the model are all in the XML::Essex::Event::... namespace, like
XML::Essex::Event::start_element.
You may use this module under the terms of the BSD, Artistic, oir GPL licenses, any version.
Barrie Slaymaker <barries@slaysys.com> | http://search.cpan.org/~rbs/XML-Filter-Essex-0.01/lib/XML/Essex/Model.pm | CC-MAIN-2018-17 | refinedweb | 1,718 | 58.72 |
waitid - wait for a child process to change state
#include <sys/wait.h> int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
The waitid() function suspends the calling thread until one child of the process containing the calling thread changes state. It records the current state of a child in the structure pointed to by infop. If a child process changed state prior to the call to waitid(), waitid() returns immediately. If more than one thread is suspended in wait() or waitpid() waiting termination of the same process, exactly one thread will return the process status at the time of the target process termination
The idtype and id arguments are used to specify which children waitid() will wait for.
If idtype is P_PID, waitid() will wait for the child with a process ID equal to (pid_t)id.
If idtype is P_PGID, waitid() will wait for any child with a process group ID equal to (pid_t)id.
If idtype is P_ALL, waitid() will wait for any children and id is ignored.
The options argument is used to specify which state changes waitid() will wait for. It is formed by OR-ing together one or more of the following flags:
- structure pointed to by infop will be filled in by the system with the status of the process. The si_signo member will always be equal to SIGCHLD.
If waitid() returns due to the change of state of one of its children, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error.
The waitid() function will.
exec, exit(), wait(), <sys/wait.h>. | http://pubs.opengroup.org/onlinepubs/007908799/xsh/waitid.html | CC-MAIN-2013-20 | refinedweb | 265 | 71.04 |
An alternative (Python style) module system for R
.Rprofilefile in the project root confuses the installer.
shinyappsinstaller, since there’s nothing that forbids non-project files in a package directory (even though
R CMD CHECKdoesn’t like it).
shinyappsand see whether we can figure this out. Thanks for the report!
Is it possible to ship my code as a regular package with no default exports, and use
modules to import bits as needed? Example
## install my package (once only for sure) devtools::install_github("holgerbrandl/datautils") ## load it, which will export nothing in its NAMESPACE require(datautils) ## import a source file from within the package modules::import('bio/bioinfo_commons', attach=TRUE)
Obviously the last line does not work that way. Is such a usecase supported by
modules?
instfolder in the package.
modules::import_package('datautils')but (once again due to how R packages work) this doesn’t allow you to use nested modules (
bio/bioinf_commons). :-(
modules, what other mechanism would you suggest to allow some user to install my modules? To me, (ab)using the r package system for installation, and
modulesfor fine-grained namespace control seemed like a nice combo.
modules::import(‘datautils/inst/bio/bioinfo_commons’), it should fail with
Error: ‘datautils' is not installed! Install firstif
datautilsis not yet installed. This would be more consistent with
import_packageerror behavior.
import_from_package('datautils/inst/bio/bioinf_commons')there is no easy way to overcome that problem.
git clonethe ones I need. Not elegant but it works. Any package mechanism would probably be built on top of that.
import * from foois strongly discouraged in Python). But: you can achieve something along these lines by using
export_submoduleinside a module. | https://gitter.im/klmr/modules?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge | CC-MAIN-2019-39 | refinedweb | 273 | 51.14 |
- Write a program to find the number of possible triangles from any three elements of array.
- Count number of possible triangles from array elements using sorting.
Given an integer array of size N. We have to count total number of possible triangles which can be formed using any three elements of array as sides of triangle. Here we are going to use the side sum property of triangle to determine the possibility of a triangle for three given side lengths.
The sum of any two sides of a triangle must be greater than the third side.For Example :
Let A, B and C be the length of three sides of a triangle. Then A+B > C, B+C > A and A+C > B.
Let A, B and C be the length of three sides of a triangle. Then A+B > C, B+C > A and A+C > B.
Input Array : 4 22 7 5 10 Output : Triangle Count : 3 4 7 5 4 7 10 7 5 10
Let inputArray be an integer array of size N.
Brute Force Method
- Using three for loop, generate all possible combination of triplet and check whether these three elements satisfy above mentioned condition or not.
By Sorting Input Array
Algorithm to count number of possible triangle from array elements using sorting.
- Sort inputArray using any O(nLogn) average time algorithm like quick sort or merge sort.
- Initialize first and second to 0 and 1 index.
- Using two for loop, generate all possible pairs of elements, inputArray[first] and inputArray[second]. Both corresponds to two sides of triangle.
- inputArray[first] and inputArray[second] can form triangle with inputArray[third], if inputArray[first] + inputArray[second] > inputArray[third].
- Initialize third = second+1. Traverse inputArray until inputArray[first] + inputArray[second] > inputArray[third]. Now, third-second+1 gives the count of all possible triangles having inputArray[first] and inputArray[second] as two sides.
C program to count number of triangles using array elements using sorting
#include <stdio.h> #include <stdlib.h> /* This function will be used as a comparator function by qsort function */ int compare(const void* one, const void* two) { return *(int*)one > *(int*)two; } /* Returns total number of possible triangles */ int getTotalTriangles(int *array, int size) { int triangleCount = 0, i, j, k; /* sort input array */ qsort(array, size, sizeof(int), compare); /* Using two for loops, fix first two sides of a triangle and then try to find the count of all such elements which is greater than the sum of both sides. */ for(i = 0; i < size-2; ++i) { /* Iteratr for second element */ for (j = i+1; j < size; ++j) { /* Initialize third element */ k = j +1; /* Three elemets of an array can form a triangle if, sum of any two element is more than third element */ while (k < size && (array[i] + array[j])> array[k]) { k++; } /* Total number of possible triangle with array[i] and array[j] as teo sides are k - j -1 */ triangleCount += k - j - 1; } } return triangleCount; } int main() { int array[5] = {4, 22, 7, 5, 10}; printf("Total Possible Triangles : %d\n", getTotalTriangles(array, 5)); return 0; }Output
Total Possible Triangles : 3 | https://www.techcrashcourse.com/2016/08/program-count-possible-triangles-array-elements.html | CC-MAIN-2021-04 | refinedweb | 520 | 52.19 |
Hello, i tried searching the forum and google but still cannot find good answer on this.
After i found a successful code in doing filter, now im having a hard time for a solution where
you can choose show all on a drop box to reverse the filter.
I have 3 option on a dropdown box
1) optional tours
2) group departure
3) free and easy
>> i'd like to add option SHOW ALL and filter will be reversed and show all items (inside a repeater)
here's the code im using for filter.
import wixData from 'wix-data'; $w.onReady(() => { wixData.query('ShowAll') .find() .then(res => { let options = [{"value": "ShowAll", "label": "All Tours"}]; options.push(...res.items.map(type => { return {"value": type.search,"label": type.search}; })); $w("#dropdownfilter").options = options; }) }); let lastFilterSearch; let lastFilterType; let debounceTimer; export function searchbar_keyPress_1(event, $w) { //Add your code for this event here: if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = undefined; } debounceTimer = setTimeout(() => { filter($w("#searchbar").value, lastFilterType); },200); } function filter(search, type) { if (lastFilterSearch !== search || lastFilterType !== type) { let newFilter = wixData.filter(); if(search) newFilter = newFilter.contains('title',search); if(type) newFilter = newFilter.eq('tourCategory', type); $w("#dataset1").setFilter(newFilter); lastFilterSearch = search; lastFilterType = type; } } export function dropdownfilter_change(event, $w) { filter(lastFilterSearch, $w("#dropdownfilter").value); }
Hope someone can help me :)
A query with Show all as you have coded:
wixData.query('ShowAll') will not return all items. There is no such query.
What you want to do is that if the user has selected the All option from the dropdown, the filter will be cleared, like this:
$w("#dataset1").setFilter();
That is, to retrieve all items, you reset by using an empty filter. The dataset will then return all items since the results are not being filtered.
Thank you Yisrael for the fastest response on my inquiry.
Im just starting to learn coding and im not sure where can i put that code to show all items (reset filter) $w("#dataset1").setFilter();
How should i set up this code or where in the part of the whole code should it paste it?
I will add an item with label "ALL" and values "ALL" on my dropdown. Do i need some tagging code?
Sorry for many questions.
Thank you so much | https://www.wix.com/corvid/forum/community-discussion/show-all-under-drop-down-box-filter | CC-MAIN-2019-47 | refinedweb | 373 | 58.58 |
Time value of money
I need to discuss the answers in class. Just wanted to double check my answers to be sure.
1. Polly Graham will receive $12,000 a year for the next 15 years as a result of her patent. If a 9 percent rate is applied, should she be willing to sell out her future rights now for $100,000?
2. The Clearinghouse Sweepstakes has just informed you that you have won $1 million. The amount is to be paid out at the rate of $20,000 a year for the next 50 years. With a discount rate of 10 percent, what is the present value of your winnings?
3. Juan Garza invested $20,000 10 years ago at 12 percent, compounded quarterly. How much has he accumulated?
4. Exodus Limousine Company has $1,000 par value bonds outstanding at 10 percent interest. The bonds will mature in 50 years. Compute the current price of the bonds if the percent yield to maturity is:
a. 5 percent.
b. 15 percent.
5. Venus Sportswear Corporation has preferred stock outstanding that pays an annual dividend of $12. It has a price of $110. What is the required rate of return (yield) on the preferred stock?
6. Static Electric Co. currently pays a $2.10 annual cash dividend (D0). It plans to maintain the dividend at this level for the foreseeable future as no future growth is anticipated. If the required rate of return by common stockholders (Ke) is 12 percent, what is the price of the common stock?
7. Sullivan Cement Company can issue debt yielding 13 percent. The company is paying a 36 percent rate. What is the aftertax cost of debt?
8. You buy a new piece of equipment for $16,980, and you receive a cash inflow of $3,000 per year for 12 years. What is the internal rate of return?
Solution Summary
The solution explains various questions relating to time value of money | https://brainmass.com/economics/bonds/218600 | CC-MAIN-2018-22 | refinedweb | 329 | 75.91 |
Managing Objective-C objects within an iOS application is always challenging due to the fixed amount of physical memory and the limited battery life of handheld devices. To address these challenges, Apple has introduced a new approach called "automatic reference counting" (ARC). In this article, I compare ARC against explicit
retain/release and against garbage collection, as well as demonstrate automatic reference counting in an iOS project, and review some key guidelines on using ARC.
Readers should have a working knowledge of Objective-C and of the Xcode IDE.
Managing by Messaging
Initially, I manage ObjC objects through explicit messaging. I create the object using
alloc and
init messages (Figure 1). I send a
retain message to hold onto the object, and a
release message to dispose of it. ObjC objects made with
alloc/init start with an internal retain count of one. A
retain message increases that count by one, while a
release message decreases it by one. When the retain count reaches zero, the object self-destructs, freeing memory it has reserved.
Figure 1.
We can also use a factory method to create the ObjC object. This marks the object for
autorelease, adding its pointer to the autorelease pool (Figure 2). We can do the same to an
alloc/init object by sending the latter an autorelease message.
Figure 2.
The pool checks its collection of object pointers during each event cycle. When it finds an object that is out-of-scope and has a retain count of one, it disposes of that object with a
release message. To deter disposal, we can send one or more
retain messages to the autoreleased object. Then to allow disposal, we counter the
retains with an equal number of
release messages.
Explicit messaging is still the best way to manage ObjC objects within an iOS application. It takes almost no overhead, it is easy to debug, and it can be fine-tuned for performance.
On the other hand, explicit messaging is prone to errors. An uneven number of
retain and
release messages can cause a memory leak or an
EXC_BAD_ACCESS error. An explicit
release to an autoreleased object can also lead to an
EXC_BAD_ACCESS. And a collection object (like an array or a set) may not self-destruct when some of its entries have retain counts greater than one.
Managing by Garbage Collection
MacOS X 10.5 (Leopard) gave us another way to manage ObjC objects garbage collection. Here, each Cocoa application gets its own collection service, which runs as a secondary thread (Figure 3).
Figure 3.
The service identifies all the root objects created right after launch time, then tracks every object created afterwards. It checks each one for scope and for strong references to a root. If the object has these attributes, the service lets it persists (marked in blue). Otherwise, it disposes of the object with a
finalize message (marked in red).
The collection service is a conservative one. It can be interrupted, even suspended, when high performance is required. It is a generational service. It assumes the most recent objects to have the shortest lifespans.
Access to the collection service is through the class
NSGarbageCollector. With this class, I can disable the service or change its behavior. I can even assign new root objects or reset the service itself.
Garbage collection removes the need for explicit
retain and
release messages. It can reduce dangling pointers and guard against null pointers. On the other hand, it requires all custom ObjC objects to be updated. Clean-up code must go into the
finalize method, not the
dealloc method. The ObjC object also must send a
finalize message to its parent.
Next, the collection service needs to know when an object reference is weak. Otherwise, it assumes all references to be strong. This can lead to circular references and to memory leaks. The service also ignores objects created with
malloc(): Those should be disposed of manually or created using the Cocoa function
NSAllocateCollectable().
Finally, the service still incurs a performance hit despite being conservative. This is one reason why garbage collection is absent on iOS.
Enter ARC
ARC is an innovative approach that has many of the benefits of garbage collection, but without the performance costs.
Internally, ARC is not a runtime service. It is, in fact, a deterministic two-part phase provided by the new Clang front-end. Figure 4 shows the two parts of that phase. In
the front-end phase, Clang examines each pre-processed file for objects and properties. It then inserts the right
retain,
release, and
autorelease statements based on some fixed rules.
Figure 4.
For example, if the object is allocated and local to a method, it gets a release statement near the end of that method. If it is a class property, its
release statement goes into the class'
dealloc method. If the object is a return value or is part of a collection object, it gets an
autorelease statement. And if the object is weakly referenced, it is left alone.
The front-end also inserts
retain statements for objects not locally owned. It updates any accessors declared with the directive
@property. It adds calls to the parent's
dealloc routine, and it reports any explicit management calls and any ambiguous ownership.
In the optimize phase, Clang subjects the modified sources to load balancing. It counts the
retain and
release calls made for each object, then pares them to the optimal minimum. This avoids excessive
retains and
releases, which can impact on overall performance.
To demonstrate, look at the sample code in Listing One.
Listing]) { myStr = aStr; } return ([self makeBar]); } - (Bar *)makeBar { Bar *tBar //... //... conversion code goes here //... return (tBar); } //... @end
Here, I show an ObjC class bereft of any
retain/release messages. It has one private property
myStr, which is an instance of
NSString (line 5). It declares a read-only getter, also named
myStr (line 7). It defines a modifier
foo2Bar and an internal function
makeBar (lines 18-36). The class also imports the header for class
Bar using the
@class directive (line 1).
Listing Two shows the same sample code post-ARC.
Listing]) { [aStr retain]; [myStr release]; myStr = aStr; } return ([self makeBar]); } - (Bar *)makeBar { Bar *tBar //... //... conversion code goes here //... [tBar autorelease]; return (tBar); } //... - (void)dealloc { [myStr release]; [super dealloc]; } @end
The class interface remains unchanged. But its
foo2Bar modifier got two new statements. One statement sends a
release message to property
myStr (line 24). Another sends a
retain statement to argument
aStr (line 25). The
makeBar function sends an
autorelease message to local
tBar before returning the latter as its result. Finally, ARC overrides the class'
dealloc method. In that method, it releases the property
myStr (line 44) and invokes the parent's
dealloc method (line 45). If a
dealloc method is already present, ARC will update its code appropriately.
Since ARC decides on its own how an ObjC object should be managed, it cuts the time spent on developing the class code. It prevents any dangling and null pointers. It can even be disabled on a per-file basis. This last feature lets the programmer reuse legacy sources of proven reliability.
But the Clang compiler is built into LLVM 3.0, which is available only on Xcode 4.2 and newer. Optimized runtime support for ARC is present only on MacOS X 10.7 (Lion) and iOS 5.0. It is possible to use ARC in iOS 4.3 binaries through glue code. It is also possible to use ARC in OS X 10.6 binaries, provided the latter does not employ any weak pointers
Next, ARC works exclusively with ObjC sources. It has no effect on PyObjC and AppleScriptObjC sources. It does, however, affect the underlying ObjC code that bridges each PyObjC and ASOC class to Cocoa. Also of note, some third-party frameworks may cause errors when compiled with ARC enabled. Make sure to contact the framework developer for updated versions. | http://www.drdobbs.com/mobile/automatic-reference-counting-on-ios/240000820?pgno=1 | CC-MAIN-2014-10 | refinedweb | 1,325 | 66.94 |
Extending Wireshark with Python
Note: Python support was removed from wireshark as of June 2014 (commit 1777f6082462). An alternative might be.
Is it still possible to make a dissector plugin for Wireshark in python ?
The projects aim is to give the possibility to developers to easily extend Wireshark with Python.
It is a project in development and therefore is experimental. It is better to not use this in production for now. It is good though for prototyping as the syntax is rather concise.
It is better to have read doc/README.developer and doc/README.python before attempting to play with the Python API.
Requirements
You must have a valid Python environment (python >= 2.3) and ctypes.
ctypes is part of the Python package from the version 2.5. If you have an older version, you have to install it yourself.
Compile with Python support
./configure –with-python
For a common installation all Pythonic stuff will be installed in ${libdir}/wireshark/python/${VERSION}/
All dissectors can be added to ${libdir}/wireshark/python/${VERSION}/wspy_dissectors/. You do not need to register your protocol in a Makefile whatsoever. Just add a <dissectorname>.py in this directory and it will be detected at Wireshark/Tshark launch.
Writing your first dissector in Python
This Python binding has been written with the idea in mind to ease the development of dissectors (write less) without losing the power offered by libwireshark. The consequence is that you have to follow some conventions.
A valid skeleton dissector
from wspy_dissector import Dissector class homeplug(Dissector): def protocol_ids(self): return [ ("ethertype", 0x887B, None) ] def dissect(self): print 'yahoo!' def register_protocol(): return homeplug("HomePlug protocol", "HomePlug", "homeplug")
This dissector will print at the console 'yahoo!' when dissecting a packet of the homeplug protocol.
Note: The homeplug dissector already exists in wireshark-1.4.2, so whilst this example is valid, you should choose another name if you actually want to try it out.
A valid dissector is composed of 2 main items. Let's see how this works:
Defining a dissector : class homeplug is defined inheriting from Dissector which contains all the magic simplifying stuff for you.
protocol_ids method must return a list of three values, all parameters used in dissector_add
None can be defined in the third parameter and it will create a new handle for this dissector (create_dissector_handle()).
you could use self.find_dissector or self.create_dissector_handle() as well.
dissect method which is the method called when a packet is to be dissected by this dissector.
the function register_protocol : This function MUST be present to be able to register your dissector. This function is called at the time Wireshark is registering all protocols. It basically has to return a handle to the instanciated dissector.
Dissecting Something
from wspy_dissector import Dissector from wspy_dissector import FT_UINT8, FT_NONE from wspy_dissector import BASE_NONE class homeplug(Dissector): def protocol_ids(self): return [ ("ethertype", 0x887B, None) ] def dissect(self): self.dissect_mctrl() def dissect_mctrl(self): hf = self.fields() subt = self.subtrees() self.c_tree = self.tree() tree = self.c_tree.add_item(hf.homeplug_mctrl, length=1, adv=False) mctrl_tree = tree.add_subtree(subt.mctrl) mctrl_tree.add_item(hf.homeplug_mctrl_rsvd, length=1, adv=False) mctrl_tree.add_item(hf.homeplug_mctrl_ne, length=1) def register_protocol(): tp = homeplug("HomePlug protocol", "HomePlug", "homeplug") hf = tp.fields() hf.add("Mac Control Field", "homeplug.mctrl", FT_NONE, BASE_NONE) hf.add("Reserved", "homeplug.mctrl.rsvd", FT_UINT8, bitmask=0x80) hf.add("Number of MAC Data Entries", "homeplug.mctrl.ne", FT_UINT8, bitmask=0x7F) subt = tp.subtrees() subt.add('mctrl') return tp
Advanced Stuff
Adding the Base Subtree
This phase has been automated but you could want to personalize this. Here is how to do that.
from wspy_dissector import Dissector class homeplug(Dissector): def protocol_ids(self): return "ethertype", 0x887B def dissect(self): subt = self.subtrees() main_tree = self.tree() p_tree = main_tree.add_item(self.protocol()) homeplug_tree = p_tree.add_subtree(subt.homeplug) def register_protocol(): tp = homeplug("HomePlug protocol", "HomePlug", "homeplug") subt = tp.subtrees() subt.add('homeplug') return tp
Steps to define the base tree in which the dissection tree will be displayed:
registering the protocol subtree in the homeplug dissector with Subtree.add(<treename>). This step is made in register_protocol before returning a handle of the homeplug dissector.
display the subtree in method dissect :
subt = self.subtrees() returns a Subtree object. You can refer to any subtree you want based on this object.
For example, when you want to create the subtree 'homeplug' with p_tree.add_subtree method you'll have to pass the reference of this subtree. You can do that with subt.homeplug. Every subtree defined when registering can be accessed later as an attribute of the Subtree object.
NOTE: defining a subtree with the same name as the third parameter used for the creation of the dissector (in this case "homeplug"), makes you responsible for adding the main subtree of this dissector. Else, if this subtree isn't defined, this main subtree will be added for you automatically.
Using libwireshark directly
The idea is to let user have a direct access to some libwireshark functions without having been wrapped by this binding.
… work in progress …
Limitations (TODO)
- dissect_tcp_pdus
- RVALS, VALS, …
- conversation
- tap
- having a dissect function differentiated for tcp and udp
- and probably many more …
Imported from on 2020-08-11 23:23:44 UTC | https://wiki.wireshark.org/Python.md | CC-MAIN-2022-27 | refinedweb | 867 | 51.55 |
I am currently working on a school assignment where i have to make a couple of powershell scripts to perform a basic configuration of a windows server 2012 r2. First script needs to do the following:
o Server name: WDC
o Ip address: 192.168.1.45
o Subnet: 255.255.255.0
o Gateway: 192.168.1.1
o DNS: 192.168.1.1
o Administrator password: Admin2016
o Primaire DNS server 8.8.8.8
o Secundaire DNS server 192.168.1.45
o Promote to dc
o ...
Problem is that the server needs to reboot after the name change and that the script cannot continue after this.
I know I could do this by for example splitting up the script and continuing the second part with runonce in the registry after reboot, but my teacher swears that it is possible to do this in one ps1 file and furthermore he says that it should be possible to autologin after the reboot and then resume the same script file from where it stopped before the reboot.
This script has to be executed on a local machine, so I can't use workflows. I have been searching for a significant amount of time but can't seem to find any suitable solution to do this exactly how the teacher wants it.
Hope someone can help.
Cheers
Resuming as such wouldn't be possible. But you can determine if the changes that need a reboot have already been done and just don't repeat the steps for those settings. Essentially, check if you need to make an adjustment to a step, and only then you need to reboot. During the second run, your script won't need to re-apply the new settings which need a reboot and should be able to effectively continue where it left off in its previous run.
As for the auto-login and script re-run parts, both are solvable. There is a solution using registry settings to auto-logon a user. You'd need to add the password for that login to the registry, so this may be a security concern. And running a script after logon is possible using the Windows task scheduler. In addition to using fixed time schedules the scheduler also supports running tasks after certain events. There is a delay if you use those events, it can be up to several minutes long. If that isn't acceptable, you could also use a link to the script in the StartUp folder of the user account used to automatically log on.
The autologon works with registry keys. You need a few keys in the HKLM namespace:
Path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon Value Name: AutoAdminLogon Value Type: REG_SZ Value data: 1 Path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon Value Name: DefaultUserName Value Type: REG_SZ Value data: <name of the user you want to log on> Path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon Value Name: DefaultPassword Value Type: REG_SZ Value data: <password of the user you want to log on>
and if this is a domain user
Path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon Value Name: DefaultDomainName Value Type: REG_SZ Value data: <name of the domain the user belongs to> | https://codedump.io/share/HBoxJXjQxbS4/1/powershell-resume-script-after-reboot | CC-MAIN-2021-17 | refinedweb | 539 | 60.65 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
xodb is a Xapian object database for Python.
For information on Xapian, please go to
Xapian stores information in database records called documents. xodb is a library which takes ordinary python objects and converts them into xapian documents. This database can then be queried for documents that match a xapian query language expression.
There are main usage patters in xodb, indexing, and querying.
Indexing
Indexing is acomplished by defining a Schema object that describes how a python object of a certain type is used to generate a xapian document. For example, here is 'Department' class that has a name, and a list of employees:
class Department(object): def __init__(self, name, employees): self.name = name self.employees = employees
Instaces of this python class could be described using the following Schema:
from xodb import Schema, String, Array class DepartmentSchema(Schema): language = String.using(default="en") name = String.using(facet=True) employees = Array.of(String.using(facet=True))
The schema tells xodb that the object will have the fields language, name, and employees. The first two are strings, and the third is an array of string. Note that the object definition above does not provide a language, in this case, the provided default "en" will be used.
Now a new xapian database can be created with xodb:
import xodb db = xodb.temp()
Next, tell xodb that the DepartmentSchema describes the Department type:
db.map(Department, DepartmentSchema)
Now, create some departments:
housing = Department("housing", ['bob', 'jane']) monkeys = Department("monkeys", ['bob', rick])
and add them to the database:
db.add(housing, monkeys)
Since we are done adding objects, flush the changes to disk so that other xapian readers can see the new data:
db.flush()
And that's it, now we can query for the data.
Querying
Data is queried out of xapian using the standard xapian QueryParser query language syntax. xodb passes the query you provide, straight into the query parser, so the xapian documentation is the best source for exact syntax documentation.
In general however the syntax follows a simple "search engine" expression language where a user can enter a bunch of terms, or terms prefixed with a "name:" prefix. For example:
assert db.query("name:monkeys").next().name == 'monkeys" | https://bitbucket.org/pombredanne/xodb | CC-MAIN-2018-09 | refinedweb | 391 | 56.86 |
How to import UNO exceptions? [closed]
I'm working on a Python application that uses a running LO instance. I'd like to know how to import the LO specific exceptions that may occur when running my program. Background below, but the prompting motivation for this question is that I want to catch the specific LO error "NoConnectException". How do I import this error from UNO? No iteration of "
from uno import ..." I've tried seems to work.
Background:
When a program exception occurs that is actionable, the "Pythonic way" is to be as specific about handling it as possible. For instance, if I have a list of 5 elements, and I try to select the 6th one, that is more specifically an
IndexError, rather than just a general
Exception. Thus, instead of code like this:
my_list = [1, 2, 3, 4, 5] # indexed from 0 through 4 i = 5 try: num = my_list[i] except Exception as e: print("You insensitive clod! {} is not a valid index!").format( i )
it is better to use the specific error you intend to handle, thus preventing the masking of an actual error:
my_list = [1, 2, 3, 4, 5] # indexed from 0 through 4 i = 5 try: num = my_list[5] except IndexError as e: print("You insensitive clod! {} is not a valid index!").format( i )
How do I import the LO specific errors that can occur? I've tried a number of iterations, but I don't know where to look these up and api.libreoffice.org is not (currently) proving much help to me. | https://ask.libreoffice.org/en/question/12384/how-to-import-uno-exceptions/ | CC-MAIN-2019-09 | refinedweb | 260 | 64.3 |
about this project:
i worked a long time on this project and the voice recognition works now. I did not create the body of GLADOS. Someone else made the 3d models off GLADOS, i made the control unit for the voice recognition.
For the person who made the body this is the link to his instructable:
Glados can control a lot in my room. From lights to my computer. In this tutorial i will explain the basics of the control system. This is expandedable by repeating the steps.
I use 2 arduino's in this situation. I'm still learning to code and this was a major step up for me. I'm investigating how i can put all this work on one simple rasberry pi.
how it works:
i use a software called voice attack. It is officialy used for voice control in games. This software enables you to attach programs or keystrokes to certain voice commands. I used it in a way that a certain voice commands opens a python script wich will send a serial code to the arduino1. The arduino1 will make a certain output HIGH that wil be send to arduino 2. The arduino 2 reads this of his inputs and will make the requested output HIGH or LOW of the relays. and so turn on or off the lights. This arduino1 is neccesary because the arduino resetted itself after every update from the serial data it received. I have not found a way to fix it yet but i'm looking into it.
25/04/2018
for all the people who voted for me on the voice activated contest THANK YOU (i know i am really late with thanking you guys).
Without your'e help i woudnt have made it. The project stands now still for a while becaue is have an intership with school but when i have the time to work furter on it i will.
If you want to stay up to date on the glados project subscribe on my youtube channel my name is douwe miedema on youtube. When i have something to show you guys i will upload it there.
Step 1: What Do You Need
you need some stuff to create this project:
hardware:
* A computer (or if you want to have it on 24/7 i recommend a mini computer because it takes less power).
* A relay board (in this case a 4 channel).
* 2 arduino uno's (if you want to control more outputs use 2 arduino mega's).
Software:
* Python software.
* Arduino software.
* Voice attack (this costs 10 dollars).
Step 2: Start With Voice Attack
If you want to make new voice commands press on edit profile.
Step 3: Make New Command
Press new command.
as you can see i have allready created a lot of commands.
Step 4: Type in Where She Needs to React To
Type in the text box what you would like her to react to as a voice command. for this preview is it "activate light 1".
Step 5: Run Aplication
now press on "other -> windows -> run aplication".
Step 6: Look for the Python Code
Press the button "browse for application".
Step 7: Select the Python Code
Choose the correct python code. in this case "activate_light_1".
(Preview of the python code is at the bottom of the instructable.)
Step 8: Select a Sound
If you made your own glados quotes you can press other -> sounds -> play a random sound. I do always random sound because i have more quotes that GLADOS can say. I do that because i wont get tired of always hearing the same answers.
If you dont know how to make glados voice here is a good tuturial about it:
The official texst to speech site doesnt exist anymore so i use another one of oddcast the voice of samantha.
If you dont want to make glados voice you can also do other -> sounds -> stop text-to-speech
Step 9: Find Your Sound
Press on browse for application.
Step 10: Select the Sound
Select the sound in this case it is activate light.
Step 11: Press Ok
Press now the ok button.
Step 12: Press Done
Press on done.
Now you created you first command you can try it if you want.
You did now only acivate the first light. you also need to deactivate light 1 and do that also for light 2 and 3.
Step 13: Arduino 1 Code
This is the arduino that gets serial data from the computer remember this arduino needs to stay plugged in the computer for serial data to work!
(on the bottom of the instructable are downloads)
Download this in arduino 1:
// this is de code for arduino 1
char serialData;
int light_1_on_signal = 2; // yellow calbe goes to arduino 2 input 2
int light_1_off_signal = 3; // yelow cable goes to arduino 2 input 3
int light_2_on_signal = 4; // yelow cable goes to arduino 2 input 4
int light_2_off_signal = 5; // yelow cable goes to arduino 2 input 5
int light_3_on_signal = 6; // yelow cable goes to arduino 2 input 6
int light_3_off_signal = 7; // yelow cable goes to arduino 2 input 7
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(light_1_on_signal, OUTPUT);
pinMode(light_1_off_signal, OUTPUT);
pinMode(light_2_on_signal, OUTPUT);
pinMode(light_2_off_signal, OUTPUT);
pinMode(light_3_on_signal, OUTPUT);
pinMode(light_3_off_signal, OUTPUT);
Serial.begin(9600); // bautrate }
// the loop routine runs over and over again forever: void loop() {
if(serialData == '1'){
digitalWrite(light_1_on_signal, HIGH); // making light_1_on_signal active
}
if(serialData == '2'){
digitalWrite(light_1_off_signal, HIGH); // making light_1_off_signal active
}
if(serialData == '3'){
digitalWrite(light_2_on_signal, HIGH); // making light_2_on_signal active
}
if(serialData == '4'){
digitalWrite(light_2_off_signal, HIGH); // making light_2_off_signal active
}
if(serialData == '5'){
digitalWrite(light_3_on_signal, HIGH); // making light_3_on_signal active
}
if(serialData == '6'){
digitalWrite(light_3_off_signal, HIGH); // making light_3_off_signal active
}
}
Step 14: Arduino 2 Code
(on the bottom of the instructable are downloads)
Download this in arduino 2:
// this is de code for arduino 2
const int light_1_on_signal = 2; // yellow calbe comes from arduino 1 input 2
const int light_1_off_signal = 3; // yellow calbe comes from arduino 1 input 3
const int light_2_on_signal = 4; // yellow calbe comes from arduino 1 input 4
const int light_2_off_signal = 5; // yellow calbe comes from arduino 1 input 5
const int light_3_on_signal = 6; // yellow calbe comes from arduino 1 input 6
const int light_3_off_signal = 7; // yellow calbe comes from arduino 1 input 7
const int light_1 = 8; // makes the relay fotr light 1 HIGH or LOW (on or off)
const int light_2 = 9; // makes the relay fotr light 1 HIGH or LOW (on or off)
const int light_3 = 10; // makes the relay fotr light 1 HIGH or LOW (on or off)
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an input.
pinMode(light_1_on_signal, INPUT);
pinMode(light_1_off_signal, INPUT);
pinMode(light_2_on_signal, INPUT);
pinMode(light_2_off_signal, INPUT);
pinMode(light_3_on_signal, INPUT);
pinMode(light_3_off_signal, INPUT);
// initialize the digital pin as an output.
pinMode(light_1, OUTPUT);
pinMode(light_2, OUTPUT);
pinMode(light_3, OUTPUT); }
// the loop routine runs over and over again forever:
void loop() {
if(digitalRead(light_1_on_signal) == HIGH) {
// if light_1_on_signa gives a signal he will gives 5v to the relay
digitalWrite(light_1, HIGH); }
if(digitalRead(light_1_off_signal) == HIGH) {
// if light_1_on_signa gives a signal he turns off the 5v to the relay
digitalWrite(light_1, LOW); }
if(digitalRead(light_2_on_signal) == HIGH) {
// if light_1_on_signa gives a signal he will gives 5v to the relay digitalWrite(light_2, HIGH); }
if(digitalRead(light_2_off_signal) == HIGH) {
// if light_1_on_signa gives a signal he turns off the 5v to the relay
digitalWrite(light_2, LOW); }
if(digitalRead(light_3_on_signal) == HIGH) {
// if light_1_on_signa gives a signal he will gives 5v to the relay digitalWrite(light_3, HIGH); }
if(digitalRead(light_3_off_signal) == HIGH) {
// if light_1_on_signa gives a signal he turns off the 5v to the relay
digitalWrite(light_3, LOW);
}
}
Step 15: Electric Circuit
I made a drawing of how you need to wire it.
Step 16: Python Code
You need to put this in the python script remember to change the com port to the one the arduino is connected with.
(on the bottom of the instructable are downloads)
python code:
import serial
import time
ser = serial.Serial("COM4", 9600)
time.sleep(1)
ser.write("1")
Step 17:
Here do you have all the files to make this project enjoy :)
Grand Prize in the
Voice Activated Challenge
12 Discussions
10 months ago
(dont know how to edit already written comments on this sitw, this idea has to do something with my other commen) you could also add face recognicion so that GLaDOS moves and looks at you like in the game that would be awseome
Reply 10 months ago
thanks for your reply. i will eventually hang glados on the ceiling and im bissy with puting ultrasonic sensors in her so she can follow you in the room :)
10 months ago
Great job ! What about using this as the body so it can move itself has another function (lamp) and you can hang it on the ceeiling instead of pvc
1 year ago
heel veel succes met al je uitvindingen Douwe Miedema
1 year ago
Awesome Douwe! I love it!
1 year ago
Proud of my son Douwe♥️
He is a REAL engineer!
1 year ago
Fantastic, i'm so amazed what you did,my compliments
1 year ago
this is simply amazing
i will make somthing like this thanks for the tip and a push in the right direction.
but it wil be next year. first i'm making my house completly remote controlledwith mqtt.
thanks
Reply 1 year ago
youre welcome. I love it that i inspired you and if have youre own system is working i would love to see a video of it !
1 year ago
This is great! I love the look and functionality!
Reply 1 year ago
thnxx ;)
1 year ago
The cake is a lie... | https://www.instructables.com/id/GLADOS-Home-Automation-voice-Recognition/ | CC-MAIN-2019-09 | refinedweb | 1,631 | 66.37 |
Opened 6 years ago
Closed 5 years ago
Last modified 5 years ago
#7672 closed (fixed)
Add filter for 'Day of week' on Date / DateTime fields
Description
It would be very useful to be able to do DB filtering based on the day of week (eg Mon, Tue, Wed). For example:
Event.objects.filter(event_date__dow=3)
would result in SQL similar to:
MySQL: SELECT [select query etc here] WHERE DAYOFWEEK(event_date) = 3;
PostgreSQL: SELECT [select query etc here] WHERE EXTRACT(DOW FROM event_date) = 3;
Oracle: SELECT [select query etc here] WHERE TO_CHAR(event_date,'D') = '3';
I have tested the syntax of MySQL's DAYOFWEEK() and Postgres' EXTRACT(DOW) functions. I don't have access to Oracle to check the syntax of the above queries. I assume SQLite will need a wrapper function similar to what's used for __month et al right now.
Unsure at this stage of best way to handle different locales where the start date may change between Sunday/Monday/other, or different database systems assuming a week start day.
The attached patch is my intitial draft. It has been tested in both MySQL 5.0 & PostgreSQL 7.4. Oracle is untested, and I haven't yet figured out the SQLite code. I have a concern the Oracle code will bomb out due to TO_CHAR returning a char, and the Django ORM tries to compare it to an integer.
References:
MySQL Date Ref:
Postgres:
Oracle:
Attachments (7)
Change History (19)
Changed 6 years ago by rossp
comment:1 Changed 6 years ago by garcia_marc
- milestone set to post-1.0
- Needs documentation set
- Needs tests set
- Patch needs improvement set
- Triage Stage changed from Unreviewed to Design decision needed
It looks nice to me, but as improvement this is post 1.0.
Some comments on the patch:
- dow sounds meaningless to me, shouldn't be better week_day?
- postgresql and sqlite backends are not modified. Am I missing something, or them should be also changed?
- tests and documentation should be added to the patch.
Btw, good idea, and good work. :)
Changed 6 years ago by rossp
New revision, see note below.
comment:2 Changed 6 years ago by rossp
- Needs documentation unset
- Needs tests unset
Added attachment dayofweek_filter-r7866.v2.diff :
- Renamed dow to week_day (I'd been using dow as that's what Postgres uses, and was my initial use case.
- Postgres backend needed to be modified to translate week_day into dow for the query.
- SQLite backend still unmodified, got to get my head around how the existing date filtering works there.
- Oracle not yet tested
- Tests & Docs added
Post 1.0 sounds fine to me, thanks for the suggestions. I knew I'd miss a bunch of stuff with my first patch.
comment:3 Changed 6 years ago by rossp
For reference, I've just done some investigation on the different date structures used in Python & the various database engines. I'm beginning to see why this isn't as easy as at face value :)
Method Range ------ ----- PYTHON datetime_object.weekday() 0-6 Sunday=6 datetime_object.isoweekday() 1-7 Sunday=7 dt_object.isoweekday() % 7 0-6 Sunday=0 # Can easily add 1 for a 1-7 week where Sunday=1 MYSQL DAYOFWEEK(timestamp) 1-7 Sunday=1 WEEKDAY(timestamp) 0-6 Monday=0 POSTGRES EXTRACT('dow' FROM timestamp) 0-6 Sunday=0 TO_CHAR(timestamp, 'D') 1-7 Sunday=1 ORACLE TO_CHAR(timestamp, 'D') 1-7 Sunday=1 (US), Sunday=6 (UK)
I'm thinking it will be easier to assume 1-7 with Sunday=1 and use the relevant functions from above, although I'm unsure at this stage of the best way to handle Oracle as I don't have access to an Oracle server to test on. Do we know the current Oracle date locale config from within Django at runtime?
comment:4 Changed 6 years ago by mtredinnick
@rossp: that sort of analysis is exactly what needed to be done here. Thanks for taking the time to do the research (if you could find a way to pass on that diligence to other people wanting database changes, it would be appreciated). Looks like we can pick a way for each database that will return something consistent (e.g. "Sunday" is 1).
Not sure how we find out the Oracle date locale. If it's a client-side settings, it's something we can control. If it's a server-side setting (which sounds more likely), it's something we would need to be able to query. Ian Kelly might be able to help us out there. I can't imagine the answer would be "it's impossible", though.
Probably still post-1.0, barring miracles or lots of free time, but it's looking like something that might be possible.
comment:5 Changed 6 years ago by rossp
Malcolm, thanks for the positive feedback. No point trying to make a change like this unless it works (and, indeed, works consistently) across all of the officially supported database systems.
Current Status:
- Settled on Sunday=1, Saturday=6. IMO this is the only logical option after reviewing the above table, and regardless of an individuals locale settings it's at least consistent within the API.
- Works in Postgres & MySQL
- Sort-of works in SQLite, working on that (I'm having other unrelated SQLite issues locally)
I will attempt contacting Ian Kelly re: Oracle. Latest patch is attached.
Changed 6 years ago by rossp
3rd revision. Makes Sunday=1, Saturday=6. Works in Postgres & MySQL, SQLite & Oracle untested.
Changed 6 years ago by rossp
Fixed indentation, now works in sqlite3, postgres and mysql. Oracle untested.
comment:6 Changed 6 years ago by rossp
Just added another patch:
- Fixed indentation so it now works in sqlite3
- Oracle still untested. Have e-mailed Ian Kelly, although if anybody else out there uses Oracle it'd be great if they could test this :)
Test suites have been updated, so in theory you can just patch this in and run the Django test suite.
Changed 6 years ago by rossp
Force oracle to use American format week day (i.e. Sunday=1)
comment:7 Changed 6 years ago by rossp
Attached another file, this one forces Oracle to use the American territory information, including Sunday=1.
I'm not sure that this is the best way to do it, but it avoids doing another query at runtime. Another option, suggested by Ian Kelly, is to do a query at connection time and cache the resulting offset. This removes reliance on knowledge of Oracle's territories:
select to_char(to_date('06-JUL-2008', 'DD-MON-YYYY'), 'D') as 'testday' from dual;
If the resulting 'testday' field is 1, do nothing. If it's 7, treat dates like Python dates (eg " Monday-base-date % 7 + 1 = sunday-base-date ").
For now I'm going to leave this one as-is until someone can confirm it works with Oracle, unless the devs believe we should test this offset. It will result in an extra query for each connection, I'm not sure if that's a problem or not.
Changed 6 years ago by rossp
Updated to work on Django 1.0 (SVN rev 9097)
comment:8 Changed 6 years ago by rossp
I have added this to the 1.1 feature request list, with discussion at in django-developers.
comment:9 Changed 5 years ago by kmtracey
I updated the patch to apply cleanly on current trunk, then tested on MySQL, Oracle, PostgreSQL (8.3), and sqlite.
The first two worked fine, the new tests that exercise week_day lookup passed.
PostgreSQL failed due to lack of an operator comparing text to integer and lack of an explicit cast. I think this extra pickiness on Postgres is due to the version I am running, and I found I could fix it by adding an explicit cast to integer: return "TO_CHAR(%s, 'D')::integer" % field_name, which looks a little odd (to_char cast to integer?) but works.
Sqlite also failed, it just didn't find matching records, until I removed the conversion to unicode that had surrounded the return value in _sqlite_extract: return (dt.isoweekday() % 7) + 1. This one I don't understand, the full function here is:
def _sqlite_extract(lookup_type, dt): if dt is None: return None try: dt = util.typecast_timestamp(dt) except (ValueError, TypeError): return None if lookup_type == 'week_day': return (dt.isoweekday() % 7) + 1 else: return unicode(getattr(dt, lookup_type))
It isn't immediately clear to me why the unicode conversion that used to be there used to work and now does not, and unfortunately I'm running out of time to look at this today (I thought I was going to have much more time to work on this today but the untimely death of a power supply rather ate up my day) so figured I'd just note this here and see if it makes sense to anyone else. Ross -- this did used to work on sqlite3 with the unicode conversion, correct?
comment:10 Changed 5 years ago by kmtracey
OK, I think I figured out what was causing the sqlite failures. For month and day lookups (but not week_day), get_db_prep_lookup was forcing the rhs-value to unicode. This was added in r8526 so wasn't in the code base when the patch was initially developed. Adding week_day to the list of lookups here means _sqlite_extract can consistently return unicode for week_day as well as the other lookups, plus the need for the ::integer cast in the Postgres code goes away, so that seems like a cleaner solution. I updated the patch to use this approach.
Changed 5 years ago by kmtracey
comment:11 Changed 5 years ago by kmtracey
- Resolution set to fixed
- Status changed from new to closed
comment:12 Changed 5 years ago by anonymous
- milestone post-1.0 deleted
Milestone post-1.0 deleted
Initial Patch - Allow day of week filtering in ORM. | https://code.djangoproject.com/ticket/7672 | CC-MAIN-2014-23 | refinedweb | 1,654 | 70.33 |
, I needed a basic month-view calendar control to use in a few places in the app. I searched, and found Creating an Outlook Calendar using WPF (by rudigobbler), which was a great day-view. I also found Richard Gavel's excellent on-going (I hope) work on Creating the Outlook UI with WPF,per
This article assumes you have a basic understanding of .NET and WPF. The code is not complicated, nor is it long. I make use of lambda functions (System.Predicate) in order to find appointments for each day, but that's about as complicated as it gets. Note that this requires .NET Framework 3.x - I built it on 3.5 SP1.
System.Predicate
The sample app (see download at top) shows the basic use of the calendar. Note that in Window1.xaml, I only include a reference to the local assembly, like so:
xmlns:cal="clr-namespace:QuickWPFMonthCalendar"
Window1.xaml only contains one line of markup between the Window open and closing tags:
Window
<cal:MonthView x:
This is Window1.xaml in Visual Studio 2008's design mode. As you can see, using it is pretty simple:
The MonthView control exposes several events, which are declared in MonthView.xaml.vb like this As Integer)
I used two custom EventArgs structures, MonthChangedEventArgs and NewAppointmentEventArgs. This was mainly because I'm using other information in the application I built; you could just pass a date, or an ID, or an actual appointment object.
EventArgs
MonthChangedEventArgs
NewAppointmentEventArgs
To handle the events, just write an event handler as you would for any control. In the sample app's Window1.xaml.vb, I used the following:
Private Sub DayBoxDoubleClicked_event(ByVal e As NewAppointmentEventArgs) _
Handles AptCalendar.DayBoxDoubleClicked
MessageBox.Show("You double-clicked on day " & _
CDate(e.StartDate).ToShortDateString(), _
"Calendar Event", MessageBoxButton.OK)
End Sub
Private Sub AppointmentDblClicked(ByVal Appointment_Id As Integer) _
Handles AptCalendar.AppointmentDblClicked
MessageBox.Show("You double-clicked on appointment with ID = " & _
Appointment_Id, "Calendar Event", MessageBoxButton.OK)
End Sub
Private, and has more fields and functionality. For this demo, I stripped out everything LINQ-specific. MonthView stores appointments as a List(Of Appointment), which you set using the property MonthAppointments (ideally, you only pass the appointments the calendar needs to show that month). In this demo, I have a loop in the Window's Loaded event that creates appointments on 50 random days during the current year, and I pass only a filtered list (using List(Of T).FindAll) to MonthAppointments.
Appointment
List(Of Appointment)
MonthAppointments
Loaded
List(Of T).FindAll
Setting the MonthAppointments property will automatically redraw the calendar to show the currently selected month. There is one other public property, DisplayStartDate (of type Date), which is used to set the month and year to show (the day and time are ignored). Setting DisplayStartDate does not (possibly confusingly) cause the calendar to re-render with that month; this is because in my app, I always set some appointments (even if I assign an empty List(Of Appointment) to MonthAppoint
In order to tell where a user has double-clicked (since it could be on an appointment, or in the blank part of a daybox control), I repurposed a function that I'm using in another part of the app, which was originally in C# and comes from Bea Stollnitz's blog.
Also - I included a small. | http://www.codeproject.com/Articles/39199/Quick-and-Simple-WPF-Month-view-Calendar-Updated?fid=1545703&df=90&mpp=10&sort=Position&spc=None&tid=3284909 | CC-MAIN-2017-17 | refinedweb | 562 | 56.76 |
Neo4j
Neo4j is a native graph database that leverages data relationships as first-class entities. You can connect a Databricks cluster to a Neo4j cluster using the neo4j-spark-connector, which offers Apache Spark APIs for RDD, DataFrame, GraphX, and GraphFrames. The neo4j-spark-connector uses the binary Bolt protocol to transfer data to and from the Neo4j server.
This article describes how to deploy and configure Neo4j, configure Databricks to access Neo4j, and includes a notebook demonstrating usage.
Note
You cannot access this data source from a cluster running Databricks Runtime 7.0 or above because a Neo4j connector that supports Apache Spark 3.0 is not available.
Neo4j deployment and configuration
You can deploy Neo4j on various cloud providers.
To deploy Neo4j on AWS EC2 using a custom AMI follow the instructions in Hosting Neo4j on EC2 on AWS. For other options, see the official Neo4j cloud deployment guide. This guide assumes Neo4j 3.2.2.
Change the Neo4j password from the default (you should be prompted when you first access Neo4j) and modify
conf/neo4j.conf to accept remote connections.
#
For more information, see Configuring Neo4j Connectors.
Databricks configuration
If your Neo4j cluster is running in AWS and you want to use private IPs, see the VPC Peering guide.
Install two libraries: neo4j-spark-connector and graphframes as Spark Packages. See the libraries guide for instructions.
Create a cluster with these Spark configurations.
spark.neo4j.bolt.url bolt://<ip-of-neo4j-instance>:7687 spark.neo4j.bolt.user <username> spark.neo4j.bolt.password <password>
Import libraries and test the connection.
import org.neo4j.spark._ import org.graphframes._ val neo = Neo4j(sc) // Dummy Cypher query to check connection val testConnection = neo.cypher("MATCH (n) RETURN n;").loadRdd[Long] | https://docs.databricks.com/data/data-sources/neo4j.html | CC-MAIN-2021-39 | refinedweb | 291 | 60.72 |
Hi & thanks for using our service. I'll do my best to give you a complete & accurate answer. Please ask me to clarify anything you don't understand.
Ok great, thanks.
This gets a little tricky in your particular circumstances; the reason being that brokers/salesmen in your industry are paid on commission as a matter of practice.
Normally, in the circumstances of an owner of an "C" corporation (or an S-Corp for that matter) your compensation should come out through a payroll as an employee;
The ownership percentage really doesn't matter, or factor into this particular decision; the fact that you are an owner just tends to draw attention to the issue.
Personally, if you were my client, primarily because of my audit experience with clients being audited on this very issue, I'd probably have you take a relatively small salary, say 20%-25% of your total expected compensation as compensation for "managing the business & taking care of all the administrative duties" & then take the rest out in your commissions.
So it sounds like it is somewhat gray? The way I do it now I only take money out when it is earned via commission attached to specific transactions so as to run it properly as if we had multiple employees. At one point we have 3 owners and 10 employees and will possibly again in the future.
I am glad you said that it is the very reason I asked. I have a CPA who only sees black and white and says all money must be payroll "end of story." That seemed so definitive and strange to me though. I suggested exactly what you proposed and she shot it down but I will go ahead and take your advice.
One thing to be careful about is treating any non-commission compensation for anyone (a secretary of administrative assistant) as a independent contractor (1099); that isn't justified by "industry practice" - industry practice is the only thing that changes the circumstances from the normal situation of owner compensation to your unique situation.
What do you mean 10 "employees"................you aren't treating them as employees for compensation purposes are you?
That makes sense. I would put any non-agent on payroll for sure and did so in the past.
See, just using that term is a giant no - no.
No and forget the 10 employee thing I was giving you info that is no longer important. Before I became sole owner our company was made up of about 10 people. All secretaries and managers were on payroll and licensed agents were Indep. Contractors.
what term?
They are employees is they are reported on 1099s - they are independent contractors & by the way, you should have written contracts with them setting forth their general duties & compensation method & getting their ss#s & getting their confirmation that they understand their arrangement with the company & that they are independent contractors.
oh employees? I get it. Going forward the only "employees" I would have would be administrative assistants on payroll. Anyone else associated with the company would be independent contractor real estate and or loan agents not "employees."
Yes, i am aware of the need for written contracts for sales agents. Currently I have no agents but I would certainly do that if I take any on.
The first time one of them gets disgruntled over something & heads for the unemployment office will be when you are glad you have a written contract. Generally the way it works is that they are employees (irrespective of how they are compensated) until you prove otherwise.
If you were to lose on this point, it would be disaster.
The term I was referring to is calling them "employees".
Thank you so much for your thorough explanation it makes a lot more sense now.
Let me ask you one question.
sure
Who is telling you that you should be an employee? An accountant or ?
The CPA who files my corp. tax returns insists since I am sole owner I MUST be on payroll for ALL compensation no matter what.
Yeah, I'm not surprised. It is a battle with the IRS we don't like to fight. I would normally be telling you the same thing had I not gone through this with real estate & insurance people; the insurance is a little different as they have another classification called "statutory employees".
Your advice makes sense and is how I pictured it because you should be allowed to separate ownership duties and commission duties since as you point out, commission based earning is the nature of Real Estate
If he's a reasonable guy (your CPA) he may reconsider based on the industry practice; one other issue is that the mortgage broker compensation isn't as clear; that is all over the place; I've only handled one of them & everything was paid to him as an employee; he wasn't technically an owner although he considered his customers his clients.
Real estate is an extremely well established industry practice.
It kind of follows an old CPA saying.......pigs get fat; hogs get slaughtered;
You don't want to fall into the "hog" category;
Hog equals greed right?
Having some compensation (not just a minor amount lie $5,000.) but based upon more like 20 -25% of the total keeps you in the "pig" category...............
But obviously, this is all subjective & we have to be prepared to argue it if necessary.
Right, a little greed is ok; a lot of greed is usually death........the IRS has time & money on their side so the best and (really the only way to win on this) is at the grass roots with the agent; once he writes it up as disagreed & it goes up the line, the chances diminish no matter how right we are; it simply costs too much to fight it;
If an audit did happen and it was determined we were doing something wrong would the punishment be a big tax bill now owed or are we playing with jail time issues? I worry that ignorance of the tax law could get me in trouble since I have never knowingly done anything improper... i ask because perhaps it is not worth the hassle of having a Corp. since I am really the only person I may be better off as a sole proprietor? I will need to figure this all out soon I guess :)
One thing I did with this a couple of times is have the owner devote 1 day a week to administrative things.............playing golf, taking me to lunch, whatever;.............that's where the 20% came from; so I'd argue that to the agent; he doesn't sell on Friday; that's an administrative day; just don't forget that if the agent shows up on a thurs & friday...................:]
That works!
Jail, hardly.................please, unless you're selling drugs out of back office...............
Corps aren't what they use to be due to changes in the tax law; I usually tell clients, figure $2,000. extra to have a corp based on increased cost of compliance; certain insurances; etc., etc. You can buy a lot of liability insurance for $2,000.
Ha no drugs but good to know - I just see all these celebs going to jail for tax reasons but I guess not filing is worse than filing incorrectly
Last Question: My wife was an employee of the truest sense and even had a time card at her old job. She was ignorant and young at the time and thought her taxes were being taken out. It turns out her employer filed 1099's and treated her as an independent contractor. We recently were sent back taxes due from this time period still owed to the IRS. Based on what you just told me it sounds like she has a legitimate dispute. Does she? Is it worth disputing or would that just cause the IRS to delve further into her entire tax picture (aka me now)?
Plus it is rare to see a small business that keeps all the records up-to-date; usually there's like 10 annual meetings the day before the IRS arrives...............they have to make an appointment like anyone else..................
Not filing isn't the issue; NOT PAYING is the problem.
Gotcha
Regarding Business records/corp. minutes are monthly meetings required or just annual?
As far as your wife is concerned, how old is the problem; ie. when was the last time she worked there?
Annual.
I want to say 2005
So what happened? she didn't file?
Was this before you were married?
it went on from about 2001 - 2005 and my concern from an outsiders perspective it i sort of like c'monlady why didn't you look into this a long time ago. She was embarrassingly ignorant and flaky about it so it may be best to just pay it off
How much is it?
Yes, before we were married
now it is about $10K-$13K
I was going to go on an installment plan but my personal tax preparer said that just puts you on the IRS radar and it is better just to pay it off and move on
So she didn't file, thinking taxes were taken out?
She said she filed 1 or 2 years to try and get a return but most years no file. Yes, she thought taxes were coming out
Without winding up sleeping on the coach by telling me, how old was she during this 2001-2005?
19-23
my dates could be off it may have been 1999-2003 but you get teh idea
the
I'm asking because 1) I don't agree that it puts you on the "radar"...........as a matter of fact it is her obligation not yours (even though you'll be paying it) & 2) a good portion of it is probably penalties which with the right letter/excuse/etc. you can probably get removed; especially given her age; but you'll need your CPA to write the letter;
Yeah, I get the idea, now just don't tell me you're 50.
haha 30
ok, that makes me feel better
What state are you in?
Same state now that she worked in?
We live in CA and she worked in CAWell I get it is not my debt, but we file jointly since 2008 or 2009 and she files as a housewife. i was due about $3,000 in returns this year and the IRS automatically applied the return to her debt which is why I was concerned it would start affecting my filings or raise redf lags.
sorry for the sloppy replies I am not use to this chat mode
ok no problem, at least it isn't spanish
PS if I was 50 and you knew how hot my wife was you'd say it is AWESOME you are 50 LOL
So, she basically ignored this all this time?
Hot is good & bad at the same time..........the voice of experience talking here..way past 50.
pretty much...already had that loud fight because I am way too conservative to ever do that...and as I mentioned she is a looker so I got over it
She said she paid chunks when she could...not the smartest ormost responsible move
You know the old real estate advice; get a "lot" while you're young!
I know what you mean...hot is fun for you but they get away with more and you have pretty much the entire male population as competition to steal them away...they can suck you dry for 20 years and find a younger better looking richer guy...but that "love" crap is such a wonderful piece of denial enabling blindfold ha ha
If I was on this, I'd handle another way, but the timing is difficult; most guys won't bother with it; but this is quite a bit of money, even for a mortgage broker.......but I guess you gotta take the bad with the good; all in all...........sounds like you're ahead of the game;;;;;;;;;;;;;;;
where are you in California..............not your street address; just generally geographically
San Diego? or San Francisco?
I just tell her if she ever wants to leave try and do it while I still have either the looks or money to keep getting laid! ha ha
South Orange County
Money is the better choice in the end.................
Careful what you say here.............this isn't confidential............that's why no names for "customers".
Back to the serious stuff...what do you mean you'd handle another way? I frankly don't want to bother with the debt but wasn't sure if you were making a joke meaning don;t marry a girl with back taxes or if you are serious there is a way to do this. If you are saying filing jointly doesn't affect things or raise flags I would like to at the bare minimum get on an installment plan.
OK, are we pretty much done?
Or ideally, fight it. Do you think the fact she ignored it for so long makes dispute silly?
oh whoops thanks for the heads up...i was being completely sarcastic anyway
Not silly at all, but you can't fight yourself & win............you need someone who has the experience to work on it without it costing more than he can save you..............
OK...BUT....an installment plan is fine if they agree to it right? I'd like to at least get on a plan so it does not appear we are trying to ignore the debt.
I'd write a couple of letters & see what happens. The can't forgive interest, unless the taxes are wrong; the years are "closed' unless she didn't file, in which case they never close; the problem is that if she has paid money toward the bill, we don't know the facts re what they've charged; how much is tax, penalties, interest; she won't have any records; multiple years are involved ;the infor has to come from the IRS, this all takes time, effort, money (fees), so it definitely is a problem;
If there's an installment agreement it should be in here name only; it has nothing to do with you except that you have to pay it...............
Yeah, they'll give you a plan because if they don't you don't pay; how are they going to squeeze it out of your wife? She's not working; must not be rich or she would have paid it long ago just to get rid of it.................
here = her
that is what I was telling you...I thought the same thing but this last year, instead of sending me my return they applied it to her debt and took my whole return (only $3K).
Yeah, no question about it; did you make estimated payments?
yes
So you need to figure the estimates better so you pay in 90% or even less; worse case you pay some interest...................but you don't overpay.......................
I get it now though...On years I don't qualify for a return I won't have to pay toward the debt if it remains in her name. If I do get a return they take it until the debt is gone. Sounds fair so we are good
Do I just hit accept now?
I believe that once you have an installment agreement in place they won't try to collect it any other way as long as you make the payments.
I just hate to see someone pay all those penalties which are probably at least half of what she owes.
I will have her write a letter to at least try and get the penalties removed based on the reason she was being dealt with improperly by her employer...worth a try
Yeah, you can hit ACCEPT, give me a giant bonus >00<; a great feedback; whatever; if you need me again, just ask for Steve G. at the beginning of your question...
Thanks, XXXXX XXXXX with you......................
ok, look, hold on a minute.................
Likewise and thank you....when you said this is not private do you mean because the company sees it? i hope this isn't public conversation? Either way I will give you the maximum positive review...take care
ok holding
After you accept, this turns into a question/answer format; if you are going to have her write a letter, give me some time; say until tomorrow morning & I'll give her some phrases to include in the letter & maybe that will help.....................deal?
The conversation doesn't identify you, just me because i choose to put my name behind what I say.
I can't email you because we can't do that under the JustAnswer rules & your email would be automatically x'd out even if you were to try & give it tome.
You might be able to find me; but there's no need to do so.
How do I get the phrases to include form you then?
Just come back to this question; I won't close it out; but you can always retrieve it anyway. It will be listed with your customer number, name or whatever.
Once you ACCEPT, you'll see it leaves chat & goes to the Q/A section.
OK...great...this is an awesome service!
Accepting now so have a great day
If you have a problem just ask for me in a question; I'll get an email that's says your looking for me.
perfect
Or better yet send your wife. does she like older men? Yet?
there's no substitute for experience >00<
Ok, time to go.................ACCEPT./..............................
haha I hope she doesn't like them until I am old
Right. You behave
Community property sucks
with my luck she will like younger men then to feel younger herself!
haha i know...I think I am one of the lucky ones
I know that is what most guys think until they get served with divorce papers though LOL
She is a special one though...ok talk to you tomorrow
Look, the single biggest mistake is not to pay attention to them - you have to LISTEN as painful as it is siometimes'
Truth
Adios
bye for now | http://www.justanswer.com/tax/5czs7-sole-owner-c-corp-california-corp.html | CC-MAIN-2014-23 | refinedweb | 3,084 | 78.48 |
It should probably be pointed out that the keyring we're talking about here is the kernel's keyring, which you can manipulate using 'keyctl' from the 'keyutils' package, and not the GNOME keyring. That said, On Thu, Dec 06, 2007 at 10:33:27AM -0500, Daniel J Walsh wrote: > -----BEGIN PGP SIGNED MESSAGE----- > I don't fully understand how you intend to use keying, but I have talked > to Nalin about this, since he is about to allow or does allow the > storing of the kerberos tgt in a kernel keyring. The krb5 package grew this ability either in F7 or an update; set KRB5CCNAME=KEYRING:blahblahblah in your environment and 'kinit' and 'kdestroy' to your heart's content. Raw Hide's pam_krb5 adds a 'ccname_template' option which can be used to tell it to create a keyring-based ccache for your session instead of the usual file-based one. It still defaults to files, though. For now, at least. [snip] > So I would suggest that we remove pam_keyinit from system_auth and only > use it in login pam modules which call it after pam_selinux open. Agreed completely. It's surprising when the new credentials your screensaver got by using a PAM module get stored in a brand-new keyring which is not tied to the rest of your desktop session. > Now the next question is whether it should be called in su or sudo? > Since wouldn't this remove access to my keying material? That's an interesting problem. In the process of authenticating for sudo or su, we _might_ get new credentials which would be stored in the keyring. It's easier for me to think about if I think of those creds as being a Kerberos TGT, but since the keyring can store any kind of data, I don't think we can assume it's only going to crop up when you're using Kerberos. Anyway, we probably don't want to store them in the same keyring as the parent process, because that be a pretty bad leak, so for the sake of that case we should always be creating a new keyring in su and sudo. But if we don't get new creds, it's going to be more useful to just re-use any creds we already have, in case they're being used to store credentials which let us access networked filesystems. Assuming that behavior wouldn't be super-broken (if it is, someone jump in, please!), how could we make that happen? That is, how can we create a new session only when we have things to store in it? >. I'd kind of expect those keyrings to be labeled as usual. Is there value to having different labels on them, aside from being able to restrict what other types of processes can access them in an SELinux sense? While we're sorting all of that out, we should probably make sure the right thing's going on wrt pam_namespace and pam_loginuid. Sorry, more questions than answers. Nalin | https://www.redhat.com/archives/fedora-devel-list/2007-December/msg00483.html | CC-MAIN-2015-14 | refinedweb | 508 | 74.73 |
Deleting a wiki page is a commonly requested action of the wiki czar. This policy covers how to delete pages.
Contents
How to delete a page
- Add the {{delete|reason}} template to the page, at the top. Please insert the reason for your deletion so the wiki team will have no problem understanding why the page needs to evaporate.
- Move the page to the Archive: namespace. Select the move tab at the top of the page, and simply rename the page to include the prefix "Archive:".
- EXAMPLE: My_ugly_old_page => Archive:My_ugly_old_page
- EXAMPLE: User:Jpublic/Some_page => Archive:User:Jpublic/Some_page
Pages moved in this way are removed by the wiki team after a two-week cooling-off period.
Urgent deletion
If there is an urgent reason for deleting the page sooner, notify the wiki team by filing a ticket. Urgent reasons include the following:
- Confidential information has been disclosed on a new page
- Licensing or other legal issues
Be sure to fill in the "Wiki page" field if you file a ticket.]." | https://fedoraproject.org/w/index.php?title=FedoraProject:Deletion&direction=prev&oldid=197153 | CC-MAIN-2018-13 | refinedweb | 170 | 61.77 |
# How to make your home ‘smart’ without going crazy

Smart furniture, which keeps your house in order, is a must for almost any futuristic set. In fact, an auto-regulating climate, automatic lights and voice control over household devices — all this can be done and configured now. But it will take a little experience, basic knowledge of technology and sometimes programming, as well as a whole sea of fantasy. In my case, I did in the way that just fantasy will be enough, but first things first…
 I became interested in the idea of a “smart home” about five years ago. I made the simplest system at first. It controlled lights in my hallway and bathroom via motion sensor, the air drawing via humidity sensor, and also the weather station — everyone was crazy about them at that time. Every self-respecting DIY enthusiast had to make a weather station.
First of all, I equipped the apartment with a controlled relay to automatically turn on the light in the corridor and bathroom. It was simple — I had one sensor in the hallway, and one in the bathroom.
If someone went to the bathroom, then the corridor sensor would detect movement and immediately turn on the lights in the hallway and in the bathroom. At the same time, if no one entered the bathroom, the sensor inside the bathroom would indicate that and 15 seconds after the lights would turn off. If someone entered the bathroom, the hallway lights would turn off in a minute.
I also thought about cases such as if someone was too preoccupied with his own thoughts while sitting on a “white throne” in the bathroom (I had a combined bathroom). For this, the light in the bathroom was divided into two groups. One turned off 3 minutes after the sensor in the bathroom stopped detecting movements, and the other group would do the same 5 minutes later. So if you sit motionless for more than 5 minutes the light would turn off. Very disciplining. However, you could always move your hand and continue your thought journey.
The bathroom also had a humidity sensor, which would automatically start the air drawing if humidity exceeded 50%. As soon as the room was ventilated to 45% humidity, the drawer would turn off.
All this was management (or rather tried to be) through the Arduino platform.

Almost immediately, it became clear to me that this platform was not all about creating a smart home. The main disadvantage of working with Arduino was that the platform worked without using the network, and without it, no truly unified ecosystem could be created. Of course, I could add network support, but why do so? I’ve made an easy choice and changed the platform to another.
Having played enough with Arduino, I reconnected the house to the ESP-8266 board. In fact, this is the same Arduino, but with Wi-Fi support + it is more compact in size. This module is still popular among smart home gadget manufacturers.

In parallel, I tried to make the smart home even smarter. For example, I solved the problem of 24 hours underfloor heating or an always-on air conditioner. I bought a Chinese Beok Wi-Fi thermostats in order to do this. They allowed me to turn off the floor heating remotely, but I had to do it through a dedicated phone app.
I solved the problem of remote controls for the air conditioner using the Broadlink RM Pro infrared signal emulator. Nothing too complicated here: you record a signal from the air conditioning remote controller (or it can be any device with remote controls) to the emulator, and so when you press a button in the application, the emulator plays the previously recorded signal. In this case with my air conditioner, I had the opportunity to turn it on and off, set the operation mode and set other parameters remotely.
I also installed Livolo switches. With their help, I could also turn the lights on and off remotely.

On the contrary: I had to install a separate application again for control, and it had no feedback, so that I could not see whether the light was on, and if it was manually turned on/off by someone using a conventional switch.
My smart home also grew with various controlled Wi-Fi relays such as Sonoff or Tuya, and even the expensive Danalock for locking the apartment, which also required a separate application. I bought almost all of those little things (except Danalock) on Aliexpress, where they only cost a penny, which allowed me to experiment without serious investments.
One of the first relatively serious purchases was the Tion breezer. It coped with automatic CO2 control more or less, but the temperature had to be constantly adjusted throughout the winter. And again — it required a separate application.

I can’t even remember all the sensors and controllers that I tried back then. My smartphone was clogged with apps to manage them all. It was like a zoo, which you had to look after. I tried to combine these applications through all sorts of aggregators like HomeBridge / MajorDomo, etc. But all of them came with significant shortcomings:
* Unfriendly, and sometimes just terrible UI
* Lack of support
* Complex connection
The search for an ultimate application for centralized management for such a number of sensors, controllers and other systems had no success. Then I tried to tweak one of the «smart» devices — the very Tion breezer. I wrote a script to automatically control the heating depending on the room temperature. The fact is that the ventilation system did not have an automatic heating adjustment. It turned out that the room was either super-hot or super-cold. There was no way to hit the sweet spot. This problem was solved with a script.
Success with my script for the breezer prompted me to create my own application for smart home management. The main goal was to create a program with convenient integration of smart devices, multi-level automation conditions and the ability to manage all devices in the house.
For about a year, I myself was engaged in application development both on the front- and back-end.
The server side is on NodeJS. The choice was made in favor of NodeJS due to the developed community, which had implemented protocols for almost all devices on the market. The client part is on Angular (Ionic) and runs on Android / iOS. In general, a classic client-server architecture.
***For note:*** in the process of working on the application, I experienced a technical insight about the use of mixins when writing device drivers. I don’t know, maybe it seems elementary for everybody else, but it was a breath of fresh air for me.
I rewrote device drivers many times until I came up with something like this:
**Example of source code**
```
import {XiaomiSubdeviceV2} from '../xiaomi.subdevice.v2';
import {load_power} from '../capabilities/load_power';
import {power_plug} from '../capabilities/power_plug';
import {PowerPurpose} from '../../base/PowerPurpose';
import {Relay} from '../../base/types/Relay';
import {HomeKitAccessory} from '../../hap/HomeKitAccessory';
import {Lightbulb2Accessory} from '../../hap/Lightbulb2Accessory';
import {Yandex} from '../../yandex/Yandex';
import {YandexLightOrSwitch} from '../../yandex/YandexLightOrSwitch';
export class LumiPlug extends XiaomiSubdeviceV2.with(Relay, power_plug, load_power, PowerPurpose,
HomeKitAccessory, Lightbulb2Accessory,
Yandex, YandexLightOrSwitch) {
onCreate() {
super.onCreate();
this.model = 'Mi Smart Plug';
this.class_name = 'lumi.plug';
this.driver_name = 'Mi Smart Plug';
this.driver_type = 3;
this.parent_class_name = 'lumi.gateway';
}
getIcon() {
return 'socket';
}
}
```
The bottom line is that despite the variety of different devices, they all do the same and provide approximately the same information. Therefore, all the capabilities of the devices were put in separate mixins, which ultimately make up the final driver. For example, the application supports many devices that have the on / off function. It is taken out and put in a separate mixin to be used identically for all devices. Elementary, Watson!
This results in: drivers for new devices can be done fast and easy, because everything is standardized and there is no need to worry about further storage of the received information. For completely new protocols (which I did not have yet), mixins also base on existing ones. They receive device information and transmit it further. Such an approach allowed to reduce the amount of code by tens of times (initially each driver was a copy of a similar driver).
So gradually I went through all the circles of hell finishing back and the front ends. When the application became fairly tolerable to look at, I thought: why not share this with the public? I found project partners and assistants to bring the application to life.
First of all, it was necessary to make the design of the application. In order to do this, I had to turn to professional designers. I naively believed that it would take 3-4 months, but in the end the process dragged on. Despite the fact that the structure of the application did not change much from the original idea, literally everything had to be redone.
In parallel, not without the help from my project partners, I bought the most popular smart home devices and coded my application so that it could support these gadgets. Soon, however, it became clear that there would not be enough money for all smart devices, so we decided to ask the existing manufacturers for free test samples of their equipment. We were heard, and Wirenboard and MiMiSmart became the first serious suppliers.
So, together with the crew, I created a new application for smart home automation with a classic client-server architecture, available on any platform, with a convenient modern design. **[Meet the BARY \*.](https://bary.io)**
*\* The name did not come from Bari Alibasov, but from Barrymore the butler, from Arthur C. Doyle’s “The Hound of the Baskerville”, — your personal “smart butler”.*
What we have in result: a description with pretty pictures and cats
===================================================================
The main screen is a convenient dashboard that can view and manage the automated parameters in your rooms. Convenient is the key here, because in those applications that I tried myself the dashboards had to be configured manually. Not the most pleasant pastime activity.

You can divide your house into zones and rooms. Each room has different parameters: temperature, humidity, current electric power consumption, etc. (as well as selected actions). If we click on a room, we see a list of devices connected to it.

Here you can turn the device on/off, as well as check the main parameters. Switching to the device will give you a more detailed control with a full list of available functions.
All devices are connected using the same type of settings. For many devices there is a connection wizard. No configs for those who like it hot! Basically, it all comes down to specifying the IP address of your device (there is an auto search available for many devices). If the IP address suddenly changes — it's okay! The server will find it at the new address automatically.

There is integration with Apple HomeKit, it is used for voice control via Siri. All devices supported by BARY easily integrate with Apple HomeKit with just one click (hello HomeBridge lovers). Yandex Alice is also supported. And it turned out to be more friendly in terms of interface commands. For example, Siri does not want to close the curtains on the command «close the curtains», cannot set a certain volume value on TV, and so on. Yandex Alice is free of such quirks.
For the convenience of managing your territories, more automations have been implemented: perform actions when certain conditions are met. Logical, multilevel automation, i.e. you can do something like “Condition 1 and (Condition 2 or Condition 3)”. Everything in a reasonable and beautiful automation editor.

Personally, I myself have accumulated nearly a hundred of automations, and they are easy to find, everything is grouped by rooms and devices.

The app also supports scripting. Script is a set of actions performed after certain conditions are met. For my smart home, I only use the standard set:

My leaving/coming back home is implemented through Apple TV — it turns on/off automatically when everyone leaves/returns home. You come home and a sad TV host from the 1TV channel is already there to greet you. Isn’t that great?
Well, what is a smart home without the ability to look at your cat?

You can connect any camera that is capable of sending an RTSP stream.
I would also like to mention the statistics section. It turned out to be quite informative:

In the reference list, the red bar is the deviation from the average values for the last six months, the gray bar is the expense level within the average values.
The picture shows my statistics for September. It was cold, no heating was provided yet, so the heater was constantly on.
Also, statistics can be viewed for any connected device.

By the way, automation and statistics helped to cut electricity costs by more than 2 times.
All events that occur are stored and can be viewed.

Also on the main page there is a special tab that collects all of the selected main indicators.

By the way, water metering is implemented through the Xiaomi door/window sensor. To do this, solder the output from the pulse counter a special contact, and BARY will create a virtual counter, in which this sensor can be specified as source.
Architecture and security
=========================
The client-server exchange is encrypted using AES technology, and the server is located directly inside the automated room. In my opinion, this protects the system as much as possible from unwanted interventions.
If there is no white IP address, then you can use cloud. It will act as an intermediary, without the possibility of decoding commands, since the keys are on the server.
Where to get
============
The back end can run on almost any platform out there — thanks to NodeJS. For the most common platforms, we have prepared scripts that will do all the work automatically.
For Raspberry Pi based on Debian Stretch:
`wget -qO- "http://bary.io/install?setup" | sudo bash`
If someone would like to install on another platform, let us know and we will update the script. If you have any difficulties — you’re also welcome. We really need feedback.
The application is free and available on [Google Play](https://play.google.com/store/apps/details?id=io.bary) and [App Store](https://apps.apple.com/us/app/bary/id1460539463). Perhaps by the end of the year, the application will become paid.
Conclusion
==========
Why did I write this article for? The main goal is to get feedback from you.
Currently, the project is developing rapidly, and our entire team is working to support more equipment from the available on the market. Since I am not the only one working on the project, the tasks remain the same — to create the most convenient application that takes users demands seriously and solves the problems with self-installation of smart solutions for home.
We are open to dialogue on possible integrations and we are ready to implement equipment support from companies interested in partnership as soon as possible. You get a finished application so you do not waste time on software development. And we’d love to wided our range of supported devices for every taste and color. It’s a win-win for everybody.
Future plans and wishes
=======================
Currently, my team and I are actively developing a video storage unit. It will be possible to place videos in home storage or cloud. I think at the beginning of next year we can talk about our new release. Should there be an opportunity to playback the best cat moments, while you’re not at home?
Next year we are planning more integrations with various services: shopping and to-do list, calendar, etc. Everything you need is on one screen, — and everything in full view. Several turnkey projects have shown that this is very much in demand.
We are also planning to start production of controllers with preinstalled software for package solutions for smart home (currently the package solution «software + hardware» is available together with our partners [Wiren Board](https://wirenboard.com/ru/)).
It also supports Google Home and Amazon Alexa, with more to come!
By the way, if you are interested, you can see the list of supported devices (not complete) on [our website](https://bary.io/supported-devices), and if you did not find what you were looking for, feel free to ask in our [telegram group](https://ttttt.me/bary_io), you’re welcome!
We will be very grateful if you share what you are missing in existing applications and what functions you would like to add.
Thank you all for reading this article. Let's make our homes smarter together! | https://habr.com/ru/post/515484/ | null | null | 3,004 | 56.15 |
{-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} -- | -- Module : Test.DejaFu.Conc.Internal.Common -- Copyright : (c) 2016 Michael Walker -- License : MIT -- Maintainer : Michael Walker <mike@barrucadu.co.uk> -- Stability : experimental -- Portability : CPP, ExistentialQuantification, RankNTypes -- -- Common types and utility functions for deterministic execution of -- 'MonadConc' implementations. This module is NOT considered to form module Test.DejaFu.Conc.Internal.Common where import Control.Exception (Exception, MaskingState(..)) import Data.Map.Strict (Map) import Test.DejaFu.Common import Test.DejaFu.STM (STMLike) #if MIN_VERSION_base(4,9,0) import qualified Control.Monad.Fail as Fail #endif -------------------------------------------------------------------------------- -- * The @Conc@ Monad -- | The underlying monad is based on continuations over 'Action's. -- -- One might wonder why the return type isn't reflected in 'Action', -- and a free monad formulation used. This would remove the need for a -- @AStop@ actions having their parameter. However, this makes the -- current expression of threads and exception handlers very difficult -- (perhaps even not possible without significant reworking), so I -- abandoned the attempt. newtype M n r a = M { runM :: (a -> Action n r) -> Action n r } instance Functor (M n r) where fmap f m = M $ \ c -> runM m (c . f) instance Applicative (M n r) where -- without the @AReturn@, a thread could lock up testing by -- entering an infinite loop (eg: @forever (return ())@) pure x = M $ \c -> AReturn $ c x f <*> v = M $ \c -> runM f (\g -> runM v (c . g)) instance Monad (M n r) where return = pure m >>= k = M $ \c -> runM m (\x -> runM (k x) c) #if MIN_VERSION_base(4,9,0) fail = Fail.fail -- | @since 0.7.1.2 instance Fail.MonadFail (M n r) where #endif fail e = cont (\_ -> AThrow (MonadFailException e)) -- | The concurrent variable type used with the 'Conc' monad. One -- notable difference between these and 'MVar's is that 'MVar's are -- single-wakeup, and wake up in a FIFO order. Writing to a @MVar@ -- wakes up all threads blocked on reading it, and it is up to the -- scheduler which one runs next. Taking from a @MVar@ behaves -- analogously. data MVar r a = MVar { _cvarId :: MVarId , _cvarVal :: r (Maybe a) } -- | The mutable non-blocking reference type. These are like 'IORef's. -- -- @CRef@s are represented as a unique numeric identifier and a -- reference containing (a) any thread-local non-synchronised writes -- (so each thread sees its latest write), (b) a commit count (used in -- compare-and-swaps), and (c) the current value visible to all -- threads. data CRef r a = CRef { _crefId :: CRefId , _crefVal :: r (Map ThreadId a, Integer, a) } -- | The compare-and-swap proof type. -- -- @Ticket@s are represented as just a wrapper around the identifier -- of the 'CRef' it came from, the commit count at the time it was -- produced, and an @a@ value. This doesn't work in the source package -- (atomic-primops) because of the need to use pointer equality. Here -- we can just pack extra information into 'CRef' to avoid that need. data Ticket a = Ticket { _ticketCRef :: CRefId , _ticketWrites :: Integer , _ticketVal :: a } -- | Construct a continuation-passing operation from a function. cont :: ((a -> Action n r) -> Action n r) -> M n r a cont = M -- | Run a CPS computation with the given final computation. runCont :: M n r a -> (a -> Action n r) -> Action n r runCont = runM -------------------------------------------------------------------------------- -- * Primitive Actions -- | Scheduling is done in terms of a trace of 'Action's. Blocking can -- only occur as a result of an action, and they cover (most of) the -- primitives of the concurrency. 'spawn' is absent as it is -- implemented in terms of 'newEmptyMVar', 'fork', and 'putMVar'. data Action n r = AFork String ((forall b. M n r b -> M n r b) -> Action n r) (ThreadId -> Action n r) | AMyTId (ThreadId -> Action n r) | AGetNumCapabilities (Int -> Action n r) | ASetNumCapabilities Int (Action n r) | forall a. ANewMVar String (MVar r a -> Action n r) | forall a. APutMVar (MVar r a) a (Action n r) | forall a. ATryPutMVar (MVar r a) a (Bool -> Action n r) | forall a. AReadMVar (MVar r a) (a -> Action n r) | forall a. ATryReadMVar (MVar r a) (Maybe a -> Action n r) | forall a. ATakeMVar (MVar r a) (a -> Action n r) | forall a. ATryTakeMVar (MVar r a) (Maybe a -> Action n r) | forall a. ANewCRef String a (CRef r a -> Action n r) | forall a. AReadCRef (CRef r a) (a -> Action n r) | forall a. AReadCRefCas (CRef r a) (Ticket a -> Action n r) | forall a b. AModCRef (CRef r a) (a -> (a, b)) (b -> Action n r) | forall a b. AModCRefCas (CRef r a) (a -> (a, b)) (b -> Action n r) | forall a. AWriteCRef (CRef r a) a (Action n r) | forall a. ACasCRef (CRef r a) (Ticket a) a ((Bool, Ticket a) -> Action n r) | forall e. Exception e => AThrow e | forall e. Exception e => AThrowTo ThreadId e (Action n r) | forall a e. Exception e => ACatching (e -> M n r a) (M n r a) (a -> Action n r) | APopCatching (Action n r) | forall a. AMasking MaskingState ((forall b. M n r b -> M n r b) -> M n r a) (a -> Action n r) | AResetMask Bool Bool MaskingState (Action n r) | forall a. AAtom (STMLike n r a) (a -> Action n r) | ALift (n (Action n r)) | AYield (Action n r) | ADelay Int (Action n r) | AReturn (Action n r) | ACommit ThreadId CRefId | AStop (n ()) | forall a. ASub (M n r a) (Either Failure a -> Action n r) | AStopSub (Action n r) -------------------------------------------------------------------------------- -- * Scheduling & Traces -- | Look as far ahead in the given continuation as possible. lookahead :: Action n r -> Lookahead lookahead (AFork _ _ _) = WillFork lookahead (AMyTId _) = WillMyThreadId lookahead (AGetNumCapabilities _) = WillGetNumCapabilities lookahead (ASetNumCapabilities i _) = WillSetNumCapabilities i lookahead (ANewMVar _ _) = WillNewMVar lookahead (APutMVar (MVar c _) _ _) = WillPutMVar c lookahead (ATryPutMVar (MVar c _) _ _) = WillTryPutMVar c lookahead (AReadMVar (MVar c _) _) = WillReadMVar c lookahead (ATryReadMVar (MVar c _) _) = WillTryReadMVar c lookahead (ATakeMVar (MVar c _) _) = WillTakeMVar c lookahead (ATryTakeMVar (MVar c _) _) = WillTryTakeMVar c lookahead (ANewCRef _ _ _) = WillNewCRef lookahead (AReadCRef (CRef r _) _) = WillReadCRef r lookahead (AReadCRefCas (CRef r _) _) = WillReadCRefCas r lookahead (AModCRef (CRef r _) _ _) = WillModCRef r lookahead (AModCRefCas (CRef r _) _ _) = WillModCRefCas r lookahead (AWriteCRef (CRef r _) _ _) = WillWriteCRef r lookahead (ACasCRef (CRef r _) _ _ _) = WillCasCRef r lookahead (ACommit t c) = WillCommitCRef t c lookahead (AAtom _ _) = WillSTM lookahead (AThrow _) = WillThrow lookahead (AThrowTo tid _ _) = WillThrowTo tid lookahead (ACatching _ _ _) = WillCatching lookahead (APopCatching _) = WillPopCatching lookahead (AMasking ms _ _) = WillSetMasking False ms lookahead (AResetMask b1 b2 ms _) = (if b1 then WillSetMasking else WillResetMasking) b2 ms lookahead (ALift _) = WillLiftIO lookahead (AYield _) = WillYield lookahead (ADelay n _) = WillThreadDelay n lookahead (AReturn _) = WillReturn lookahead (AStop _) = WillStop lookahead (ASub _ _) = WillSubconcurrency lookahead (AStopSub _) = WillStopSubconcurrency | https://hackage.haskell.org/package/dejafu-0.9.0.0/docs/src/Test-DejaFu-Conc-Internal-Common.html | CC-MAIN-2020-16 | refinedweb | 1,136 | 52.49 |
Post data to an ASP using AxWebBrowser (solution)
I am trying to write a program which POSTs some data to an ASP page, using an AxWebBrowser.
This component (the Microsoft WebBrowser aka IE) is highly undocumented. :-( Just check the MSDN - lots of method parameters are simply NOT explained.
Anyway - for the Navigate method:
the PostData parameter must be an array of bytes (otherwise C# sends everything as Unicode).
Also.. there is one BIG gotcha: in order for ASP (or IIS, or whatever the fsck it is that screws things up in MS web products) to understand the fields you post, you must add this line in the headers:
Content-Type: application/x-www-form-urlencoded
If this is not in the headers, then the Request.Form collection of ASP will be empty.
Microsoft SUXXXXXXXX big time for not documented the god damn fscking WebBrowser method parameters!!!! What is more basic, than a web browser??????!!!!!!!
I know that I behave like an angry teenager, but I spent about 6 fscking hours debugging the STUPID IDIOTIC problem!!!!
And please don't delete my post - it is VERY useful to others who want to do the same thing!
Knight Rider
Thursday, June 19, 2003
Ah, one more thing...
The Navigate method has several parameters.
For the Header parameter, it is ok to pass a C# string.
For the PostData parameter, it is not ok to pass a C# string - you have to convert it to standard ASCIIZ first (every character must have 8 bits).
Why this highly ilogical behavior?
I know - the PostData goes after the header, and the Header goes into the, well, HTTP header.
But still - why this difference?
There is no logic in this!
Why did they choose to automatically convert some params from Unicode to ASCII, and not to convert some params from Unicode to ASCII?
Because the POSTed values CAN be Unicode, whereas the header can't be Unicode (the HTTP standard says so).
So in fact it is very logical.
Why doesn't Microsoft write this VERY IMPORTANT detail in the MSDN, in the page about the Navigate method?
If Bill Gates ever comes to my country, I shall come to the airport with a big sign saying "please update the god damn MSDN"!
:-)
Knight Rider
Thursday, June 19, 2003
Ah, just one more thing!
Why doesn't C# and VB .NET include a type of string (let's call it AsciiString) with 8 bits per character?
When you say:
string sUnicode = "bla-bla-bla";
AsciiString sAscii;
sAscrii=sUnicode;
then the 16-bit-per-character string should automatically be converted to ASCII 8-bit-per-character string.
The Unicode Hater Society - supporting string usage freedom
Hey Microsoft - Leave our strings alone!
Excuse me, but I am very nervous!
I hope someone will release a NEW language for .NET, called C# Pro, which will have STANDARD HONEST ASCII STRINGS!
We hate Unicode!
// Here is an Unicode to ASCII C# conversion function:
// Written by The Unicode Hater Society
// function is tested and works!
public byte[] UnicodeToAscii(string src) {
int len=src.Length;
byte[] result = new Byte[len+1];
for(int i=0; i<len; i++)
result[i] = Convert.ToByte(src[i]);
result[len]=0;
return result;
}
Windows API and low-level programming forever!
Yeah, man!
K&R are gonna rock your world! :)
Down with Unic0de!
K&R C is for wimps. I like Forth and ASM better. :)
J. Cobra Coder
Thursday, June 19, 2003
Yeah, man!
The day Intel will add wimpy Unicode string operations in the x86, I shall switch to MacIntosh with it's PowerPC, even if it should be called, in fact, SlowCPU. :)
Or.. horrors! They may have extended the strings operations behind my back, when I wasn't looking!
Does the x86 alread have Unicode string operations???
Only the allmighty AMD Athlon 64 may save the x86, now!
:-)
BTW.. I almost finished the app!
"We hate Unicode!"
Speak for yourself. MBCS is a serious pain. Unicode is much better.
Brad Wilson (dotnetguy.techieswithcats.com)
Thursday, June 19, 2003
Knight Rider -- an alternative for your UnicodeToAscii() method:
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str)
Not all of us speak English and use our particular alphabet you know (but I'm sure you were joking anyway).
Duncan Smart
Thursday, June 19, 2003
Have you considered reading the RFCs or some other primer on HTTP rather than blaming Microsoft for you not understanding how forms work?
SomeBody
Thursday, June 19, 2003
Actually Knight Rider it's just struck me the folly of your ways -- what on earth are you using Interop with AxWebBrowser for in the first place?? The .NET BCL already has robust support for POSTing, GETting and whatever to an HTTP server - namely System.Net.WebClient:
using System;
using System.Text;
using System.Net;
using System.Collections.Specialized;
//...
string url = "";
NameValueCollection formData = new NameValueCollection();
formData["field-keywords"] = "Harry Potter";
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(response);
Duncan, thank you VERY much for your extremely informative reply.
I am using axWebBrowser because I need it to manage cookies automatically: I login, the site gives me a cookie, and I want this cookie sent back to the server in the next requests.
I know I could have done this using some HTTP component or object, BUT by using axWebBrowser, I don't need to bother.
The MSDN documentation for axWebBrowser.Navigate is really extremely poor - they don't give the type of arguments, etc.
As for Unicode - I think that people should get over it and use only the English language. Let's face it, English has won! And I'm saying this as a non-native English speaker...
> Have you considered reading the RFCs or some other
> primer on HTTP rather than blaming Microsoft for you not
> understanding how forms work?
I have read the entire HTTP RFC about 5 years ago (I wrote a multithreaded web spider then), and I didn't remember the needed information.
But that's not the point.
axWebBrowser is a high level component. It should offer abstraction and SHIELD me from the implementation details.
A good printing component, for example, should print without requiring me to know anything about the print codes sent to the printer.
Knight Rider
Friday, June 20, 2003
Ok, since it's Microsoft's responsibility to shield you from such details, did you consider searching MSDN (or Google) for something such as WebBrowser PostData? When I do so, it's link #1 on Google and link #4 on MSDN.
SomeBody
Friday, June 20, 2003
Recent Topics
Fog Creek Home | https://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=1784&ixReplies=16 | CC-MAIN-2018-26 | refinedweb | 1,106 | 66.54 |
Hi all, Is it that the code in the mathtext module looks
> ugly or is it just me not understanding it? Also, if anyone
> has some good online sources about parsing etc. on the net,
> I vwould realy appreciate it.
It's probably you not understanding it
In my opinion, the code is
pretty nice and modular, with a few exceptions, but I'm biased.
Parsers can be a little hard to understand at first. You might start
by trying to understand pyparsing
and work through some of the basic examples there. Once you have your
head wrapped around that, it will get easier.
> Considering the foowing code (picked on random, from
> mathtext.py)
> I don't understand, for example, what does the statement:
> expression.parseString( s )
> do?
> "expression" is defined globaly, and is called (that is -
> its method) only once in the above definition of the
> function, but I don't understand - what does that particular
> line do?!?
It's not defined globally, but at module level. There is only one
expression that represents a TeX math expression (at least as far as
mathtext is concerned) so it is right that there is only one of them
at module level. It's like saying "a name is a first name followed by
an optional middle initial followed by a last name". You only need to
define this one, and then you set handlers to handle the different
components.
The expression assigns subexpressions to handlers. The statement
below says that an expression is one or more of a space, font element,
an accent, a symbol, a subscript, etc...
expression = OneOrMore(
space ^ font ^ accent ^ symbol ^ subscript ^ superscript ^ subsuperscript ^ group ^ composite ).setParseAction(handler.expression).setName("expression")
A subscript, for example, is a symbol group followed by an underscore
followed by a symbol group
subscript << Group( Optional(symgroup) + Literal('_') + symgroup )
and the handler is defined as
subscript = Forward().setParseAction(handler.subscript).setName("subscript")
which means that the function handler.subscript will be called every
time the pattern is matched. The tokens will be the first symbol
group, the underscore, and the second symbol group. Here is the
implementation of that function
def subscript(self, s, loc, toks):
assert(len(toks)==1)
#print 'subsup', toks
if len(toks[0])==2:
under, next = toks[0]
prev = SpaceElement(0)
else:
prev, under, next = toks[0]
if self.is_overunder(prev):
prev.neighbors['below'] = next
else:
prev.neighbors['subscript'] = next
return loc, [prev]
This grabs the tokens and assigns them to the names "prev" and "next".
Every element in the TeX expression is a special case of an Element,
and every Element has a dictionary mapping surrounding elements to
relative locations, either above or below or right or superscript or
subscript. The rest of this function takes the "next" element, and
assigns it either below (eg for \Sum_\0) or subscript (eg for x_0) and
the layout engine will then take this big tree and lay it out. See
for example the "set_origin" function?
> ------ Regarding the unicode s
upport in mathtext, mathtext
> currently uses the folowing dictionary for getting the glyph
> info out of the font files:
> latex_to_bakoma = {
> r'\oint' : ('cmex10', 45), r'\bigodot' : ('cmex10', 50),
> r'\bigoplus' : ('cmex10', 55), r'\bigotimes' : ('cmex10',
> 59), r'\sum' : ('cmex10', 51), r'\prod' : ('cmex10', 24),
> ...
> }
> I managed to build the following dictionary(little more left
> to be done): tex_to_unicode = { r'\S' : u'\u00a7', r'\P' :
> u'\u00b6', r'\Gamma' : u'\u0393', r'\Delta' : u'\u0394',
> r'\Theta' : u'\u0398', r'\Lambda' : u'\u039b', r'\Xi' :
> u'\u039e', r'\Pi' : u'\u03a0', r'\Sigma' : u'\u03a3',
> unicode_to_tex is straight forward. Am I on the right
> track? What should I do next?
Yes, this looks like the right approach. Once you have this
dictionary mostly working, you will need to try and make it work with
a set of unicode fonts. So instead of having the tex symbol point to
a file name and glyph index, you will need to parse a set of unicode
fonts to see which unicode symbols they provide and build a mapping
from unicode name -> file, glyph index. Then when you encounter a tex
symbol, you can use your tex_to_unicode dict combined with your
unicode -> filename, glyphindex dict to get the desired glyph.
> I also noticed that some TeX commands (commands in the sense
> that they can have arguments enclosed in brackets {}) are
> defined as only symbols: \sqrt alone, for example, displays
> just the begining of the square root:?, and \sqrt{123}
> triggers an error.
We don't have support for \sqrt{123} because we would need to do
something a little fancier (draw the horizontal line over 123). This
is doable and would be nice. To implement it, one approach would be
add some basic drawing functionality to the freetype module, eg to
tell freetype to draw a line on it's bitmap. Another approach would
simply be to grab the bitmap to freetype and pass it off to agg and
use the agg renderer to decorate it. This is probably preferable.
But I think this is a lower priority right now.
JDH | https://discourse.matplotlib.org/t/questions-about-mathtext-unicode-conversion-etc/5369 | CC-MAIN-2021-43 | refinedweb | 847 | 61.87 |
Shell Sort Technique In C++: A Complete Overview.
Shell sort is often termed as an improvement over insertion sort. In insertion sort, we take increments by 1 to compare elements and put them in their proper position.
In shell sort, the list is sorted by breaking it down into a number of smaller sublists. It’s not necessary that the lists need to be with contiguous elements. Instead, shell sort technique uses increment i, which is also called “gap” and uses it to create a list of elements that are “i” elements apart.
=> See Here To Explore The Full C++ Tutorials list.
What You Will Learn:
General Algorithm
The general algorithm for shell sort is given below.
shell_sort (A, N)
where A – list to be sorted; N – gap_size
set gap_size = N, flag = 1
while gap_size > 1 or flag = 1, repeat
begin
set flag = 0
set gap_size = (gap_size + 1)/2
end
for i = 0 to i< (N-gap_size) repeat
begin
if A[i + gap_size] > A[i]
swap A[i + gap_size], A[i]
set flag = 0
end
end
Thus in the above algorithm, we first set N which is the gap for sorting the array A using shell sort. In the next step, we divide the array into sub-arrays by using the gap. Then in the next step, we sort each of the sub-arrays so that at the end of the loop we will get a sorted array.
Next, let us consider a detailed example to better understand the shell sort using a pictorial representation.
Illustration
Let us illustrate the Shell sort with an Example.
Consider the following array of 10 elements.
If we provide a gap of 3, then we will have the following sub-lists with each element that is 3 elements apart. We then sort these three sublists.
The sorted sub-lists and the resultant list that we obtain after combining the three sorted sublists are shown below.
The above array that we have obtained after merging the sorted subarrays is nearly sorted. Now we can perform insertion sort on this list and sort the entire array. This final step is shown below for your reference.
As seen above, after performing shell sort and merging the sorted sublists, we only required three moves to completely sort the list. Thus we can see that we can significantly reduce the number of steps required to sort the array.
The choice of increment to create sub-lists is a unique feature of shell sort.
C++ Example
Let us see the implementation of shell sort in C++ below.
#include <iostream> using namespace std; // shellsort implementation int shellSort(int arr[], int N) { for (int gap = N/2; gap > 0; gap /= 2) { for (int i = gap; i < N; i += 1) { //sort sub lists created by applying gap int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; arr[j] = temp; } } return 0; } int main() { int arr[] = {45,23,53,43,18,24,8,95,101}, i; //Calculate size of array int N = sizeof(arr)/sizeof(arr[0]); cout << "Array to be sorted: \n"; for (int i=0; i<N; i++) cout << arr[i] << " "; shellSort(arr, N); cout << "\nArray after shell sort: \n"; for (int i=0; i<N; i++) cout << arr[i] << " "; return 0; }
Output:
Array to be sorted:
45 23 53 43 18 24 8 95 101
Array after shell sort:
8 18 23 24 43 45 53 95 101
We have used the same list that we used in the illustration and we can see that we begin initially by creating two sub-lists and then narrowing the gap further. Once sub lists are created as per the gap specified, we sort each of the sub lists. After all the sub lists are sorted, we get the almost sorted list. Now this list can be sorted using the basic insertion sort which will take very few moves.
Next, let us implement shell sort using Java language.
Java Example
// Java class for ShellSort class ShellSort { //function to sort the array using shell sort int sort(int arr[]) { int N = arr.length; // Start with a big gap, then narrow the gap for (int gap = N/2; gap > 0; gap /= 2) { //sort sub lists created by applying gap for (int i = gap; i < N; i += 1) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; arr[j] = temp; } } return 0; } } class Main{ public static void main(String args[]) { int arr[] = {45,23,53,43,18,24,8,95,101}; int N = arr.length; System.out.println("Array to be sorted: "); for (int i=0; i<N; ++i) System.out.print(arr[i] + " "); System.out.println(); ShellSort ob = new ShellSort(); ob.sort(arr); System.out.println(""Array after shell sort: "); for (int i=0; i<N; ++i) System.out.print(arr[i] + " "); System.out.println(); } }
Output:
Array to be sorted:
45 23 53 43 18 24 8 95 101
Array after shell sort:
8 18 23 24 43 45 53 95 101
We have implemented the same logic for shell sort in both C++ and Java programs. Thus as explained above in the Java program, we first divide the array into subarrays and then sort them to obtain a complete sorted array.
Conclusion
Shell sort is the highly efficient algorithm that comes to an improvement over the insertion sort.
While insertion sort works by incrementing its elements by 1, shell sort uses the parameter “gap” to divide the array into sub-arrays whose elements are “gap” apart. Then we can sort the individual list using insertion sort to obtain the complete sorted array.
Shell sort performs faster than insertion sort and takes fewer moves to sort the array when compared to insertion sort. Our upcoming tutorial will explore all about the heap sort technique for sorting data structures.
=> Visit Here To Learn C++ From Scratch. | https://www.softwaretestinghelp.com/shell-sort/ | CC-MAIN-2021-17 | refinedweb | 995 | 66.37 |
Follows,
I need some help with fixing a bug in my program. I can't post the entire code here as its an on going assignment.
I'm building a Tree in Python.
class Tree: def __init__(self, f, r): self.first = f self.rest = r
This is my Tree.
I perform a depth-first search on it.
So I call
traverse(tree.rest)
The traverse function looks like this:
def traverse(vertex): if len(vertex) == 0: return ...
The following is the error that keeps poping out:
if len(vertex) == 0:
AttributeError: Tree instance has no attribute '__len__'
Can someone help me with this.
drjay | https://www.daniweb.com/programming/software-development/threads/198143/fixing-attributeerror | CC-MAIN-2017-39 | refinedweb | 105 | 78.85 |
Ansible Plus Flask of issues you'd face in production:
The Server
In prod, this would hopefully be some high-powered IPAM with a REST API that dealt properly with auth and could be a reliable source of truth.
- server.py
from flask import Flask, jsonify app = Flask(__name__) # returns # { # "result": { # "chassis": "chassis-007", # "ip": "0.0.0.0" # } # } @app.route('/get_ip') def hello_world(): # In reality, this info could come from a form, or a db or whatever # Don't forget to deal with auth! return jsonify(dict(result=dict(ip='0.0.0.0', chassis='chassis-007'))) def main(): # Don't run these options in prod app.run(host='0.0.0.0', debug=True) if __name__ == "__main__": main()
Run it with
python server.py
The Hosts file
Since I'm not really doing anything, I'm using a minimal hosts file. In prod, you could use a static hosts file, or a dynamic hosts system that also queries your IPAM.
- hosts
[prod] localhost ansible_connection=local
The Playbook
This is the real meat of the work. I can decode the REST response from the HTTP
request by calling
from_json filter on the content from the HTTP response,
then walking the JSON object. I'll admit, this isn't the prettiest way to do
something like this, but working ugly code is better than nonworking pretty
code...
- playbook.yaml
--- - hosts: all gather_facts: false tasks: # - name: Get JSON from Source of Truth uri: # this shouldn't be hardcoded url: '' return_content: true register: json_response - name: Print the whole response to help with parsing debug: msg: "chassis is {% raw %}{{ json_response }}{% endraw %}" - name: Tell the world I got my chassis debug: # need to decode the response from the content part of the http response, then index into it msg: "chassis is {% raw %}{{ (json_response.content|from_json).result.chassis }}{% endraw %}"
Then run it with:
ansible-playbook -i hosts playbook.yaml
Ta-da! It prints
chassis-007 | https://www.bbkane.com/blog/ansible-plus-flask/ | CC-MAIN-2021-43 | refinedweb | 320 | 58.42 |
PVS-Studio in the Clouds: Azure DevOps
This is a second article, which focuses on usage of the PVS-Studio analyzer in cloud CI-systems. This time we'll consider the platform Azure DevOps — a cloud CI\CD solution from Microsoft. We'll be analyzing the ShareX project.
We'll need three components. The first is the PVS-Studio analyzer. The second is Azure DevOps, which we'll integrate the analyzer with. The third is the project that we'll check in order to demonstrate the abilities of PVS-Studio when working in a cloud. So let's get going.
PVS-Studio is a static code analyzer for finding errors and security defects. The tool supports the analysis of C, C++ and C# code.
Azure DevOps. The Azure DevOps platform includes such tools as Azure Pipeline, Azure Board, Azure Artifacts and others that speed up the process of creating software and improve its quality.
ShareX is a free app that lets you capture and record any part of the screen. The project is written in C# and is eminently suitable to show configuration of the static analyzer launch. The project source code is available on GitHub.
The output of the cloc command for the ShareX project:
In other words, the project is small, but quite sufficient to demonstrate the work of PVS-Studio together with the cloud platform.
Let's Start the Configuration
To start working in Azure DevOps, let's follow the link and press «Start free with GitHub».
Give the Microsoft application access to the GitHub account data.
You'll have to create a Microsoft account to complete your registration.
After registration, create a project:
Next, we need to move to «Pipelines» — «Builds» and create a new Build pipeline.
When asked where our code is located, we will answer — GitHub.
Authorize Azure Pipelines and choose the repository with the project, for which we'll configure the static analyzer's run.
In the template selection window, choose «Starter pipeline.»
We can run static code analysis of the project in two ways: using Microsoft-hosted or self-hosted agents.
First, we'll be using Microsoft-hosted agents. Such agents are ordinary virtual machines that launch when we run our pipeline. They are removed when the task is done. Usage of such agents allows us not to waste time for their support and updating, but imposes certain restrictions, for example — inability to install additional software that is used to build a project.
Let's replace the suggested default configuration for the following one for using Microsoft-hosted agents:
# Setting up run triggers # Run only for changes in the master branch trigger: - master # Since the installation of random software in virtual machines # is prohibited, we'll use a Docker container, # launched on a virtual machine with Windows Server 1803 pool: vmImage: 'win1803' container: microsoft/dotnet-framework:4.7.2-sdk-windowsservercore-1803 steps: # Download the analyzer distribution - task: PowerShell@2 inputs: targetType: 'inline' script: 'Invoke-WebRequest -Uri -OutFile PVS-Studio_setup.exe' - task: CmdLine@2 inputs: workingDirectory: $(System.DefaultWorkingDirectory) script: | # Restore the project and download dependencies nuget restore .\ShareX.sln # Create the directory, where files with analyzer reports will be saved md .\PVSTestResults # Install the analyzer PVS-Studio_setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /COMPONENTS=Core # Create the file with configuration and license information "C:\Program Files (x86)\PVS-Studio\PVS-Studio_Cmd.exe" credentials -u $(PVS_USERNAME) -n $(PVS_KEY) #
Note: according to the documentation, the container used has to be cached in the image of the virtual machine, but at the time of writing the article it's not working and the container is downloaded every time the task starts, which has a negative impact on the execution timing.
Let's save the pipeline and create variables which will be used for creating the license file. To do this, open the pipeline edit window and click «Variables» in the top right corner.
Then, add two variables — PVS_USERNAME and PVS_KEY, containing the user name and license key respectively. When creating the PVS_KEY variable don't forget to select «Keep this value secret» to encrypt values of the variable with a 2048-bit RSA key and to suppress the output of the variable value in the task performance log.
Save variables and run the pipeline by clicking «Run».
The second option to run the analysis — use a self-hosted agent. We can customize and manage self-hosted agents ourselves. Such agents give more opportunities to install software, needed for building and testing our software product.
Before using such agents, you have to configure them according to the instruction and install and configure the static analyzer.
To run the task on a self-hosted agent, we'll replace the suggested configuration with the following:
# Setting up triggers # Run the analysis for master-branch trigger: - master # The task is run on a self-hosted agent from the pool 'MyPool' pool: 'MyPool' steps: - task: CmdLine@2 inputs: workingDirectory: $(System.DefaultWorkingDirectory) script: | # Restore the project and download dependencies nuget restore .\ShareX.sln # Create the directory where files with analyzer reports will be saved md .\PVSTestResults #
Once the task is complete, you can download the archive with analyzer reports under the «Summary» tab or you can use the extension Send Mail that enables to configure emailing or consider another convenient tool on Marketplace.
Analysis Results
Now let's look at some bugs found in the tested project, ShareX.
Excessive checks
To warm up, let's start with simple flaws in the code, namely, with redundant checks:
private void PbThumbnail_MouseMove(object sender, MouseEventArgs e) { .... IDataObject dataObject = new DataObject(DataFormats.FileDrop, new string[] { Task.Info.FilePath }); if (dataObject != null) { Program.MainForm.AllowDrop = false; dragBoxFromMouseDown = Rectangle.Empty; pbThumbnail.DoDragDrop(dataObject, DragDropEffects.Copy | DragDropEffects.Move); Program.MainForm.AllowDrop = true; } .... }
PVS-Studio warning: V3022 [CWE-571] Expression 'dataObject != null' is always true. TaskThumbnailPanel.cs 415
Let's pay attention to the check of the dataObject variable for null. Why is it here? dataObject cannot be null in this case, as it's initialized by a reference on a created object. As a result, we have an excessive check. Critical? No. Looks succinct? No. This check is clearly better being removed so as not to clutter the code.
Let's look at another fragment of code which we can comment in a similar way:
private static Image GetDIBImage(MemoryStream ms) { .... try { .... return new Bitmap(bmp); .... } finally { if (gcHandle != IntPtr.Zero) { GCHandle.FromIntPtr(gcHandle).Free(); } } .... } private static Image GetImageAlternative() { .... using (MemoryStream ms = dataObject.GetData(format) as MemoryStream) { if (ms != null) { try { Image img = GetDIBImage(ms); if (img != null) { return img; } } catch (Exception e) { DebugHelper.WriteException(e); } } } .... }
PVS-Studio warning: V3022 [CWE-571] Expression 'img != null' is always true. ClipboardHelpers.cs 289
In the GetImageAlternative method, the img variable is checked that it's not null right after a new instance of the Bitmap class is created. The difference from the previous example here is that we use the GetDIBImage method instead of the constructor to initialize the img variable. The code author suggests that an exception might occur in this method, but he declares only blocks try and finally, omitting catch. Therefore, if an exception occurs, the caller method GetImageAlternative won't get a reference to an object of the Bitmap type, but will have to handle the exception in its own catch block. In this case, the img variable won't be initialized and the execution thread won't even reach the img != null check but will get in the catch block. Consequently, the analyzer did point to an excessive check.
Let's consider the following example of a V3022 warning:
private void btnCopyLink_Click(object sender, EventArgs e) { .... if (lvClipboardFormats.SelectedItems.Count == 0) { url = lvClipboardFormats.Items[0].SubItems[1].Text; } else if (lvClipboardFormats.SelectedItems.Count > 0) { url = lvClipboardFormats.SelectedItems[0].SubItems[1].Text; } .... }
PVS-Studio warning: V3022 [CWE-571] Expression 'lvClipboardFormats.SelectedItems.Count > 0' is always true. AfterUploadForm.cs 155
Let's take a closer look at the second conditional expression. There we check the value of the read-only Count property. This property shows the number of elements in the instance of the collection SelectedItems. The condition is only executed if the Count property is greater than zero. It all would be fine, but in the external if statement Count is already checked for 0. The instance of the SelectedItems collection cannot have the number of elements less than zero, therefore, Count is either equal or greater than 0. Since we've already performed the Count check for 0 in the first if statement and it was false, there's no point to write another Count check for being greater than zero in the else branch.
The final example of a V3022 warning will be the following fragment of code:
private void DrawCursorGraphics(Graphics g) { .... int cursorOffsetX = 10, cursorOffsetY = 10, itemGap = 10, itemCount = 0; Size totalSize = Size.Empty; int magnifierPosition = 0; Bitmap magnifier = null; if (Options.ShowMagnifier) { if (itemCount > 0) totalSize.Height += itemGap; .... } .... }
PVS-Studio warning: V3022 Expression 'itemCount > 0' is always false. RegionCaptureForm.cs 1100
The analyzer noticed that the condition itemCount > 0 will always be false, as the itemCount variable is declared and at the same time assigned zero above. This variable isn't used anywhere up to the very condition, therefore the analyzer was right about the conditional expression, whose value is always false.
Well, let's now look at something really sapid.
The best way to understand a bug is to visualize a bug
It seems to us that a rather interesting error was found in this place:
public static void Pixelate(Bitmap bmp, int pixelSize) { .... float r = 0, g = 0, b = 0, a = 0; float weightedCount = 0; for (int y2 = y; y2 < yLimit; y2++) { for (int x2 = x; x2 < xLimit; x2++) { ColorBgra color = unsafeBitmap.GetPixel(x2, y2); float pixelWeight = color.Alpha / 255; r += color.Red * pixelWeight; g += color.Green * pixelWeight; b += color.Blue * pixelWeight; a += color.Alpha * pixelWeight; weightedCount += pixelWeight; } } .... ColorBgra averageColor = new ColorBgra((byte)(b / weightedCount), (byte)(g / weightedCount), (byte)(r / weightedCount), (byte)(a / pixelCount)); .... }
I wouldn't like to show all the cards and reveal what our analyzer has found, so let's put it aside for a while.
By the name of the method, it is easy to guess what it is doing — you give it an image or a fragment of an image, and it pixelates it. The method's code is quite long, so we won't cite it entirely, but just try to explain its algorithm and explain what kind of a bug PVS-Studio managed to find.
This method receives two parameters: an object of the Bitmap type and the value of the int type that indicates the size of pixelation. The operation algorithm is quite simple:
1) Divide the received image fragment into squares with the side equal to the size of pixelation. For instance, if we have the pixelation size equal to 15, we'll get a square, containing 15x15=225 pixels.
2) Further, we traverse each pixel in this square and accumulate the values of the fields Red, Green, Blue and Alpha in intermediate variables, and before that multiply the value of the corresponding color and the alpha channel by the pixelWeight variable, obtained by dividing the Alpha value by 255 (the Alpha variable is of the byte type). Also when traversing pixels we sum up the values, written in pixelWeight into the weightedCount variable. The code fragment that executes the above actions is as follows:
ColorBgra color = unsafeBitmap.GetPixel(x2, y2); float pixelWeight = color.Alpha / 255; r += color.Red * pixelWeight; g += color.Green * pixelWeight; b += color.Blue * pixelWeight; a += color.Alpha * pixelWeight; weightedCount += pixelWeight;
By the way, note that if the value of the Alpha variable is zero, pixelWeight won't add to the weightedCount variable any value for this pixel. We'll need that in the future.
3) After traversing all pixels in the current square, we can make a common «average» color for this square. The code doing this looks as follows:
ColorBgra averageColor = new ColorBgra((byte)(b / weightedCount), (byte)(g / weightedCount), (byte)(r / weightedCount), (byte)(a / pixelCount));
4) Now when we got the final color and wrote it in the averageColor variable, we can again traverse each pixel of the square and assign it a value from averageColor.
5) Go back to the point 2 while we have unhandled squares.
Once again, the weightedCount variable isn't equal to the number of all pixels in a square. For example, if an image contains a completely transparent pixel (zero value in the alpha channel), the pixelWeight variable will be zero for this pixel (0 / 255 = 0). Therefore, this pixel won't effect formation of the weightedCount variable. It's quite logical — there's no point to take into account colors of a completely transparent pixel.
So it all seems reasonable — pixelation must work correctly. And it actually does. That's just not for png images that include pixels with values in the alpha channel below 255 and unequal to zero. Notice the pixelated picture below:
Have you seen the pixelation? Neither have we. Okay, now let's reveal this little intrigue and explain where exactly the bug is hiding in this method. The error crept into the line of the pixelWeight variable computation:
float pixelWeight = color.Alpha / 255;
The fact of the matter is that when declaring the pixelWeight variable as float, the code author implied that when dividing the Alpha field by 255, he'll get fractional numbers in addition to zero and one. This is where the problem hides, as the Alpha variable is of the byte type. When diving it by 255, we get an integer value. Only after that it'll be implicitly cast to the float type, meaning that the fractional part gets lost.
It's easy to explain why it's impossible to pixelate png images with some transparency. Since for these pixels values of the alpha channel are in the range 0 < Alpha < 255, the Alpha variable divided by 255 will always result in 0. Therefore, values of the variables pixelWeight, r, g, b, a, weightedCount will also always be 0. As a result, our averageColor will be with zero values in all channels: red — 0, blue — 0, green — 0, alpha — 0. By painting a square in this color, we do not change the original color of the pixels, as the averageColor is absolutely transparent. To fix this error, we just need to explicitly cast the Alpha field to the float type. Fixed version of the code line might look like this:
float pixelWeight = (float)color.Alpha / 255;
Well, it's high time to cite the message of PVS-Studio for the incorrect code:
PVS-Studio warning: V3041 [CWE-682] The expression was implicitly cast from 'int' type to 'float' type. Consider utilizing an explicit type cast to avoid the loss of a fractional part. An example: double A = (double)(X) / Y;. ImageHelpers.cs 1119
For comparison, let us cite the screenshot of a truly pixelated image, obtained on the corrected application version:
Potential NullReferenceException
public static bool AddMetadata(Image img, int id, string text) { .... pi.Value = bytesText; if (pi != null) { img.SetPropertyItem(pi); return true; } .... }
PVS-Studio warning: V3095 [CWE-476] The 'pi' object was used before it was verified against null. Check lines: 801, 803. ImageHelpers.cs 801
This code fragment shows that the author expected that the pi variable can be null, that is why before calling the method SetPropertyItem, the check pi != null takes place. It's strange that before this check the property is assigned an array of bytes, because if pi is null, an exception of the NullReferenceException type will be thrown.
A similar situation has been noticed in another place:
private static void Task_TaskCompleted(WorkerTask task) { .... task.KeepImage = false; if (task != null) { if (task.RequestSettingUpdate) { Program.MainForm.UpdateCheckStates(); } .... } .... }
PVS-Studio warning: V3095 [CWE-476] The 'task' object was used before it was verified against null. Check lines: 268, 270. TaskManager.cs 268
PVS-Studio found another similar error. The point is the same, so there is no great need to cite the code fragment, the analyzer message will be enough.
PVS-Studio warning: V3095 [CWE-476] The 'Config.PhotobucketAccountInfo' object was used before it was verified against null. Check lines: 216, 219. UploadersConfigForm.cs 216
The same return value
A suspicious code fragment was found in the EvalWindows method of the WindowsList class, which returns true in all cases:
public class WindowsList { public List<IntPtr> IgnoreWindows { get; set; } .... public WindowsList() { IgnoreWindows = new List<IntPtr>(); } public WindowsList(IntPtr ignoreWindow) : this() { IgnoreWindows.Add(ignoreWindow); } .... private bool EvalWindows(IntPtr hWnd, IntPtr lParam) { if (IgnoreWindows.Any(window => hWnd == window)) { return true; // <= } windows.Add(new WindowInfo(hWnd)); return true; // <= } }
PVS-Studio warning: V3009 It's odd that this method always returns one and the same value of 'true'. WindowsList.cs 82
In seems logical that if in the list named IgnoreWindows there is a pointer with the same name as hWnd, the method must return false.
The IgnoreWindows list can be filled either when calling the constructor WindowsList(IntPtr ignoreWindow) or directly through accessing the property as it's public. Anyway, according to Visual Studio, at the moment in the code this list is not filled. This is another strange place of this method.
Unsafe call of event handlers
protected void OnNewsLoaded() { if (NewsLoaded != null) { NewsLoaded(this, EventArgs.Empty); } }
PVS-Studio warning: V3083 [CWE-367] Unsafe invocation of event 'NewsLoaded', NullReferenceException is possible. Consider assigning event to a local variable before invoking it. NewsListControl.cs 111
Here a very nasty case might occur. After checking the NewsLoaded variable for null, the method, which handles an event, can be unsubscribed, for example, in another thread. In this case, by the time we get into the body of the if statement, the variable NewsLoaded will already be null. A NullReferenceException might occur when trying to call subscribers from the event NewsLoaded, which is null. It is much safer to use a null-conditional operator and rewrite the code above as follows:
protected void OnNewsLoaded() { NewsLoaded?.Invoke(this, EventArgs.Empty); }
The analyzer pointed to 68 similar fragments. We won't describe them all — they all have a similar call pattern.
Return null from ToString
Recently I've found out from an interesting article of my colleague that Microsoft doesn't recommend returning null from the overridden method ToString. PVS-Studio is well aware of this:
public override string ToString() { lock (loggerLock) { if (sbMessages != null && sbMessages.Length > 0) { return sbMessages.ToString(); } return null; } }
PVS-Studio warning: V3108 It is not recommended to return 'null' from 'ToSting()' method. Logger.cs 167
Why assigned if not used?
public SeafileCheckAccInfoResponse GetAccountInfo() { string url = URLHelpers.FixPrefix(APIURL); url = URLHelpers.CombineURL(APIURL, "account/info/?format=json"); .... }
PVS-Studio warning: V3008 The 'url' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 197, 196. Seafile.cs 197
As we can see from the example, when declaring the url variable, it is assigned a value, returned from the method FixPrefix. In the next line, we clear the obtained value even without using it anywhere. We get something similar to dead code: it works, but doesn't effect the result. Most likely, this error is a result of a copy-paste, as such code fragments take place in 9 more methods. As an example, we'll cite two methods with a similar first line:
public bool CheckAuthToken() { string url = URLHelpers.FixPrefix(APIURL); url = URLHelpers.CombineURL(APIURL, "auth/ping/?format=json"); .... } .... public bool CheckAPIURL() { string url = URLHelpers.FixPrefix(APIURL); url = URLHelpers.CombineURL(APIURL, "ping/?format=json"); .... }
Conclusions
As we can see, configuration complexity of automatic analyzer checks doesn't depend on a chosen CI-system. It took us literally 15 minutes and several mouse clicks to configure checking of our project code with a static analyzer.
In conclusion, we invite you to download and try the analyzer on your projects.
Only users with full accounts can post comments. Log in, please. | https://habr.com/en/company/pvs-studio/blog/467357/ | CC-MAIN-2019-47 | refinedweb | 3,321 | 56.96 |
Timeline
03/24/10:
- 23:54 Changeset [65320] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 23:47 Changeset [65319] by
- whitespace
- 23:42 Changeset [65318] by
- refactoring
- 23:27 Changeset [65317] by
- emos: forgot to remove isset_variant g95
- 23:25 Changeset [65316] by
- emos: disabled g95 variant since unsupported pointer() is used extensively …
- 23:25 Ticket #24207 (emacs-app does not compile on Snow Leopard) created by
- This is what I get... thanks -Roberto […]
- 21:54 Changeset [65315] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 21:40 Changeset [65314] by
- fix warnings
- 21:37 Changeset [65313] by
- support reading PortIndex from arbitrary url
- 20:47 Changeset [65312] by
- audio/mpd upgraded version from 0.15.8 to 0.15.9
- 19:54 Changeset [65311] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 19:21 Changeset [65310] by
- gpatch: update to 2.6.1, using patch derived from changes already upstream
- 18:54 Changeset [65309] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 18:45 Changeset [65308] by
- hs-digest: update to 0.0.0.8
- 18:41 Ticket #24206 (Update java/checkstyle (to version 5.1)) created by
- Hi, if anyone is feeling like doing some work, please update checkstyle …
- 18:34 Changeset [65307] by
- fcgi: fix livecheck
- 18:31 Changeset [65306] by
- qtplay: livecheck.check => livecheck.type
- 18:23 Changeset [65305] by
- go-devel: variants for bash_completion, emacs, and vim aren't really …
- 18:23 Changeset [65304] by
- siag: fix livecheck
- 18:22 Changeset [65303] by
- py*-pcapy: fix livecheck
- 18:19 Changeset [65302] by
- qtplay: fix livecheck
- 18:17 Ticket #24202 (mongodb 1.2.4 universal fails) closed by
- fixed: r65301
- 18:17 Changeset [65301] by
- #24202
- 18:17 Changeset [65300] by
- pdflib: update to 7.0.4p4
- 18:04 Changeset [65299] by
- pdflib: fix homepage and livecheck
- 17:55 Changeset [65298] by
- libconfuse: update to 2.7
- 17:54 Changeset [65297] by
- poppler: update to 0.12.4
- 17:54 Changeset [65296] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 17:53 Changeset [65295] by
- libconfuse: fix livecheck
- 17:42 Changeset [65294] by
- poppler: fix livecheck to only show stable releases
- 17:40 Changeset [65293] by
- poppler-data: update to 0.4.0
- 17:38 Ticket #18456 (Add missing port:p5-digest-hmac dependency) closed by
- fixed: Fixed in r65292.
- 17:38 Changeset [65292] by
- imapsync: add missing dependency on p5-digest-hmac; see #18456 (maintainer …
- 17:37 Changeset [65291] by
- stunnel: update to 4.32, use port:-style dependency for openssl, use …
- 17:36 Changeset [65290] by
- p5-graph: update to 0.94
- 17:35 Ticket #23651 (imapsync: Add missing depends_run on p5-digest-hmac) closed by
- duplicate: Duplicate of #18456.
- 17:34 Changeset [65289] by
- p5-digest-sha: update to 5.48
- 17:32 Changeset [65288] by
- p5-authen-sasl: update to 2.14
- 17:32 Changeset [65287] by
- p5-config-inifiles: update to 2.57
- 17:31 Changeset [65286] by
- p5-image-exiftool: update to 8.15
- 17:29 Changeset [65285] by
- p5-xml-namespacesupport: update to 1.11
- 17:28 Changeset [65284] by
- p5-image-size: update to 3.220
- 17:24 Changeset [65283] by
- audiofile: update to 0.2.7
- 17:22 Changeset [65282] by
- normalize: fix livecheck
- 17:21 Ticket #24205 (Enable SSL by default for ldns) created by
- The current port of unbound, 1.4.3_1, fails to install, because of a …
- 17:20 Changeset [65281] by
- audiofile: fix livecheck
- 17:19 Changeset [65280] by
- cd-discid: fix livecheck
- 17:12 Changeset [65279] by
- e2fsprogs: update to 1.41.11
- 17:02 Changeset [65278] by
- e2fsprogs: fix livecheck
- 17:00 Changeset [65277] by
- grace: fix livecheck
- 16:54 Changeset [65276] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 16:52 Ticket #24203 (php5-xhprof including supplied PHP classes) closed by
- fixed: Thanks, committed in r65275 with these changes: * "depends_lib-delete" …
- 16:52 Changeset [65275] by
- php5-xhprof: install examples, xhprof_lib, and xhprof_html; and add …
- 16:35 Changeset [65274] by
- gwenhywfar: fix livecheck
- 16:29 Changeset [65273] by
- hs-utf8-string: update to 0.3.6
- 16:27 Changeset [65272] by
- hs-ghc-paths: update to 0.1.0.6
- 16:26 Changeset [65271] by
- gavl: simplify livecheck
- 16:23 Changeset [65270] by
- gavl: update to 1.1.1
- 16:23 Changeset [65269] by
- gource: update to 0.26
- 16:20 Ticket #24204 (texlive_base-2007 User-modified texmf.cnf overwritten when it shouldn't be) created by
- I just upgraded texlive_base from 2007_7 to 2007_8. During this, it …
- 16:16 Changeset [65268] by
- fbopenssl: fix livecheck
- 16:10 Ticket #24203 (php5-xhprof including supplied PHP classes) created by
- While playing around with this PECL I noticed some crucial parts missing. …
- 16:10 Changeset [65267] by
- php5-mongo: update to 1.0.6
- 16:04 Ticket #24202 (mongodb 1.2.4 universal fails) created by
- […]
- 16:02 Ticket #23844 (Upgrade mongodb and mongodb-devel to latest versions) closed by
- fixed: Anthony updated mongodb to 1.2.4 in r64740. We do not have a port called …
- 15:54 Changeset [65266] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 15:40 Ticket #24201 (slrn-devel: update) created by
- It may be a good idea to update slrn-devel to a more-recent version. …
- 15:34 Ticket #24200 (patch slrn to current version) closed by
- duplicate: I addressed the update to 0.9.9p1 in #18463.
- 15:28 Ticket #24200 (patch slrn to current version) created by
-
- 15:27 Ticket #21882 (slrn-devel @0.9.9pre-69 fails to build with slang2 on Snow Leopard) closed by
- invalid: Replying to barryjprice@…: > ---> Computing dependencies …
- 15:23 Ticket #18463 (slrn 0.9.8.1: Update to 0.9.9p1) closed by
- fixed: Fixed in r65265.
- 15:22 Ticket #18198 (slrn: Portfile misses depends_lib if +ssl is being used) closed by
- fixed: Fixed in r65265.
- 15:22 Changeset [65265] by
- slrn: update to 0.9.9p1 (#18463), use port:-style dependencies, use …
- 15:14 Changeset [65264] by
- slang and slang2 conflict
- 14:57 Ticket #24199 (Coin +aqua violates mtree) created by
- Coin +aqua installs its framework into /Library/Frameworks: […] …
- 14:54 Changeset [65263] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 14:47 Changeset [65262] by
- Made changes to go-devel port as suggested by ryandesign
- 14:29 Ticket #24198 (Quarter: only absolute run-paths are allowed / can't find designer) closed by
- fixed: Fixed in r65261 by telling it where QtDesigner is.
- 14:29 Changeset [65261] by
- Quarter: fix build failure due to inability to locate QtDesigner; see …
- 14:21 Ticket #24198 (Quarter: only absolute run-paths are allowed / can't find designer) created by
- I can't build Quarter 1.0.0 on Snow Leopard: […] […] I assume …
- 14:01 Changeset [65260] by
- version 0.9.8n
- 13:54 Changeset [65259] by
- Total number of ports parsed: 6757 Ports successfully parsed: 6757 …
- 13:51 Ticket #24197 (simage: simage.pc and simage-default.cfg contain -arch flags) created by
- […] […] Those -arch flags should not be there; they will cause …
- 13:16 Ticket #24196 (simage: update to 1.7.0) created by
- simage should probably be updated to 1.7.0. The attached patch does this.
- 13:16 Changeset [65258] by
- New port p5-string-truncate 1.100570.
- 13:14 Ticket #24195 (simage: use port:-style dependencies) created by
- simage uses lib:-style dependencies. This allows for non-MacPorts software …
- 13:13 Changeset [65257] by
- version 3.60.1
- 13:13 Changeset [65256] by
- simage: change removal of libungif in quicktime variant to giflib; …
- 13:09 Changeset [65255] by
- Added portfile for development version of Google Go programming language
- 12:59 Ticket #23590 (Cannot build qt4-mac 4.6.1 on Snow Leopard.) closed by
- duplicate
- 12:37 Ticket #24192 (policykit-0.9 link error — symbol(s) not found) closed by
- invalid
- 12:35 Ticket #24194 (gcc43, gcc44 won't compile with non-default build_arch) created by
- I've tried and tried and tried .. nothing I do works. GCC 4.2, 4.3, nor …
- 12:34 Ticket #24193 (I can't use Cunit , installed but doesn't work. 10.6) created by
- Hi everybody, I'm using mac os x 10.6 (snow leopard). Macport is …
- 11:57 Ticket #24192 (policykit-0.9 link error — symbol(s) not found) created by
- While trying to install gnome-terminal on 10.6.2 with the latest XCode, …
- 11:45 Ticket #24191 (Coin: Coin.pc and coin-default.cfg contain -arch flags) created by
- […] These files should not contain -arch flags because it will cause …
- 11:41 Ticket #24190 (Coin: update to 3.1.3) created by
- Coin should probably be updated to version 3.1.3.
- 11:23 Ticket #24189 (typo in portfile for openmpi variant gcc44) created by
- configure argument for variant gcc44 is "--enablepi--f90" but should …
- 11:21 Ticket #24188 (moreutils: install ifne) created by
- moreutils deliberately doesn't build and install ifne, but I couldn't …
- 10:59 Ticket #24187 (kdelibs4 fails to build universal) created by
- Hi, I got no response from the Macports users list. So, I thought I'd …
- 10:57 Ticket #24186 (cmus-2.3.1 +universal Configure error — unrecognized option ...) created by
- While trying to upgrade cmus, I get the following error: […]
- 10:55 Changeset [65254] by
- moreutils: also fix docbook schema path in parallel.docbook
- 10:54 Changeset [65253] by
- Total number of ports parsed: 6755 Ports successfully parsed: 6755 …
- 10:53 Changeset [65252] by
- moreutils: change the DOCBOOK2XMAN patch and the PREFIX reinplace to …
- 10:35 Ticket #24094 (net/quvi@0.1.2 fails to build) closed by
- fixed: The problem was quvi would use an existing install's headers before …
- 10:35 Changeset [65251] by
- don't use existing quvi install's headers, #24094
- 10:32 Changeset [65250] by
- libdrizzle: fix long_description
- 10:30 Changeset [65249] by
- libpixman-devel: update to 0.17.4
- 10:29 Ticket #24185 (Unable to build p5-mail-spf on 10.5) created by
- Sorry if this ticket ends up at the wrong place but I couldn't find any …
- 10:28 Changeset [65248] by
- libpng: update to 1.2.43
- 10:26 Ticket #24172 (Add libdrizzle Portfile) closed by
- fixed: Thanks, added in r65247 with minor changes to whitespace, the …
- 10:25 Changeset [65247] by
- libdrizzle: new port, version 0.7; see #24172
- 10:19 Changeset [65246] by
- port1.0/portutil.tcl: Error out if Portfile has modification time in the …
- 10:00 Ticket #23860 (x264-20100224_2 - Updated version) closed by
- fixed: r65244. I also removed the revision. wickedguitar6: You should reinstall …
- 09:59 Changeset [65245] by
- ui_msg to notes
- 09:55 Changeset [65244] by
- Update to version 20100224. (#23860)
- 09:44 Ticket #24181 (problem installing afni through MacPorts) closed by
- duplicate: Duplicate of #23397. Please search before filing new tickets.
- 09:23 Ticket #24118 (xorg-libX11 1.3.3 does not build with +universal with coreutils ...) closed by
- duplicate: #24130
- 09:07 Ticket #24173 (build for gnome-desktop fails to find xml2po) closed by
- duplicate: #23983
- 09:06 Ticket #23945 (epiphany build failure due to xml2po) closed by
- duplicate: #23983
- 08:38 Ticket #24182 (error when installing libgnome) closed by
- duplicate: Duplicate of #24083, please search before filing new tickets.
- 08:17 Ticket #24178 (When patchfiles-delete deletes all patches in patchfiles, ...) closed by
- fixed: Fixed in r65243. If we want to do that for all options we would either …
- 08:16 Changeset [65243] by
- port1.0/portpatch.tcl: Avoid crash when patchfiles ends up empty, fixes …
- 07:54 Changeset [65242] by
- Total number of ports parsed: 6754 Ports successfully parsed: 6754 …
- 07:39 Ticket #24055 (mlt 0.5.0 render crashes) closed by
- fixed: Fixed by r65083.
- 07:29 Ticket #24051 (unbound.pid should go into prefix/var/run/unbound) closed by
- fixed: Add configure flag in r65241. Also use autoreconf.
- 07:29 Changeset [65241] by
- add pidfile config, #24051. also use autoreconf
- 07:22 Ticket #24160 (htop requires libtool) closed by
- fixed: Added autoreconf in r65197.
- 07:21 Changeset [65240] by
- add autoreconf, #24160
- 07:16 Changeset [65239] by
- emulators/qemu: Update to version 0.12.3
- 07:13 Changeset [65238] by
- bump revision after adding autoreconf
- 07:12 Changeset [65237] by
- add autoreconf, #24094
- 07:06 Changeset [65236] by
- direct mode fix
- 06:05 Changeset [65235] by
- mpvim: typo
- 05:54 Changeset [65234] by
- Total number of ports parsed: 6754 Ports successfully parsed: 6754 …
- 05:16 Changeset [65233] by
- updated version
- 04:05 Ticket #24184 (Spidermonkey build failure (undefined symbols) with non-default build_arch) created by
- The spidermonkey port on 32bit OS X 10.6/32bit firmware fails. …
- 03:52 Ticket #24183 (xalan-c 1.10 build failure (undefined symbols) with non-default build_arch) created by
- The xalan-c port on 32bit OS X 10.6/32bit firmware fails. The xerces-c …
- 03:43 Changeset [65232] by
- port/port.tcl: Fix wrapline by omitting indent on first line only as …
- 00:54 Changeset [65231] by
- Total number of ports parsed: 6754 Ports successfully parsed: 6754 …
- 00:08 Changeset [65230] by
- c-ares 1.7.1
Note: See TracTimeline for information about the timeline view. | http://trac.macports.org/timeline?from=2010-03-28T23%3A34%3A23-0700&precision=second | CC-MAIN-2015-32 | refinedweb | 2,202 | 62.58 |
Neha Dharni
2010-07-29
While I am trying to connect with database through jython, I am getting
exception "unable to instantiate datasource" in line mysqlConn =
zxJDBC.connectx(url, user, password, driver,CHARSET='iso_1')
My piece of code is :
from com.ziclix.python.sql import zxJDBC
url = 'jdbc:mysql://localhost/test'
user = 'test'
password = 'pass123'
driver = 'org.gjt.mm.mysql.Driver'
try:
mysqlConn = zxJDBC.connectx(url, user, password, driver,CHARSET='iso_1')
if mysqlConn is not None:
print "Successfully connected"
else:
print "Not able to connect with database"
except zxJDBC.DatabaseError,err:
print err
I have installed mysql-connector-java-5.1.13-bin.jar too and included that in
my classpath.Any clue why I am getting this error?
Kyle VanderBeek
2010-07-29
Although you're using it from Python/Jython, you're not actually using the
MySQLdb driver that exists in this project. You actually want the JDBC driver
project: | http://sourceforge.net/p/mysql-python/discussion/70460/thread/253c5143/ | CC-MAIN-2015-32 | refinedweb | 152 | 51.14 |
Question:
Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.
Pseudocode
- Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries
I need some serious help! I don't understand any of this stuff at all! This is all I have
def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main()
and I don't even know if it's right!
Solution:1
Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem.
I would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like
high and
low. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place.
The pseudocode references three variables,
high,
low and
tries. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses.
Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable,
i and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode.
Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the
while statement does this. If you're familiar with an
if statement,
while looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true.
Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have
if-
elif-
else clauses.
Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out.
In the first run through the loop, with
high containing 1000 and
low containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses.
If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work.
To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess.
When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it!
This technique of splitting a range in half and then continuing to the closer half is called bisection and appears in a wide range topics of interest to computer science.
How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that.
Here's an example using the
while clause:
>>> x = 1000 >>> while x > 1: ... x = x/2 ... print x ... 500 250 125 62 31 15 7 3 1 >>> x 1
Getting console input from the user should be done through the
raw_input() function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes)
>>> raw_input() Hello World! 'Hello World!' >>> y = raw_input() Hello World! >>> print y Hello World! >>>
How about some combining of concepts!
>>>>> while myvar != 'exit': ... myvar = raw_input() ... if myvar == 'apples': ... print "I like apples" ... elif myvar == 'bananas': ... print "I don't like bananas" ... else: ... print "I've never eaten", myvar ... apples I like apples mangoes I've never eaten mangoes bananas I don't like bananas exit I've never eaten exit >>>
Oops. little bit of a bug there. See if you can fix it!
Solution:2
I don't understand any of this stuff at all!
That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:
Print instructions to the user
So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment:
The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries.
"
print "some information"
to see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify!
Solution:3
You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise.
So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself.
In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it.
Solution:4
Doesn't match the psudocode exactly but it works. lol ;)
I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with:
high = 1000 low = 1 print "Pick a number between 1 and 1000." print "I will guess your number in 10 tries or less." print "Or at least i'll try to. ;)" print "My first guess is 500." guess = 500 tries = 0 answer = 1 print "Enter 1 if it's higher." print "Enter -1 if it's lower." print "Enter 0 if I guessed it!" print "" while (answer != 0): answer = int(raw_input("Am I close?")) if answer == 1: tries = tries + 1 low = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == -1: tries = tries + 1 high = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == 0: tries = tries + 1 print "Your number is:" print guess print "Yay! I got it! Number of guesses:" print tries
Solution:5
Okay, the nice part about using Python is that it's almost pseudocode anyway.
Now, let's think about the individual steps:
How do you get the average between high and low?
How do you ask the user if the answerr is correct
What do "if" statements look like in Python, and how would you write the pseudocode out as if statements?
Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do
high=23 low=7
then compute what you think should be the average or midpoint between them (hint: 15)
Solution:6
Welcome to Stack Overflow!
The trick here is to realize that your Python program should look almost like the pseudocode.
First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this:
Think of a number between 1 and 1000 and press Enter. >>> Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. >>> 1 Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. >>> -1 Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
etc.
When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500.
After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right).
So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode:
while high > low: # Guess (high + low) / 2 and ask user to respond # Handle user response
There is no need for a for-loop as you have in your code.
To take input we can do something like this:
guess = (high + low) / 2 response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.')
Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example.
Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set.
Good luck!
Solution:7
Here's a few hints to get you started:
Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3))
Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7.
Skip this for python users /* Secondly: your earliest programs can benefit from const correctness (here is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used. */
Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions).
Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time.
Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation.
Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/06/tutorial-transform-game-pseudo-code.html | CC-MAIN-2018-43 | refinedweb | 2,803 | 69.01 |
Well - this would help if it was part of the Console app. I don't really want to pop this
code in to each script just for testing purposes.
Furthermore, it would also be nice if the console could setup the args[] & stdin features.
This would mean:
Ø Ability to pass parameters to scripts (to emulate a command line)
Ø Pipe output of an o/s statement to the current script. [dir c:/ | <this script>].
The console would need to launch the o/s command etc.
..and so the wish list grows!!
Merlin Beedell
From: Schalk Cronjé [mailto:ysb33r@gmail.com]
Sent: 04 September 2015 18:07
To: users@groovy.incubator.apache.org
Subject: Re: GroovyConsole System.exit() suggestion
Does this - - help ?
On 04/09/2015 17:36, Merlin Beedell wrote:
I note that the useful GroovyConsole will exit if the script being run hits a System.exit().
This is understandable when the script runs in that same thread as the Console. But it would
be really useful to be able to run scripts in a separate thread to protect against exit()
[and to display the exit value] and also for scripts with infinite loops that need to be killed!
And, maybe, it would also allow these scripts to obtain the 'console' object for keyboard
input?
Console cons = System.console()
Boolean isWorking () {
if (!cons)
{
println "Cannot open a console for input"
//always the case under GroovyConsole
}
return (cons != null)
}
Merlin Beedell
--
Schalk W. Cronjé
Twitter / Ello / Toeter : @ysb33r | http://mail-archives.eu.apache.org/mod_mbox/groovy-users/201509.mbox/%3Cad03abd1c744470284d683d641f94409@fcs-exchange-a.fcs.cryoserver.com%3E | CC-MAIN-2021-04 | refinedweb | 248 | 76.62 |
I don't catch exception in Qt
I've encountered a big surprise for me.
My program doesn't catch any exception (in particully in main function ) when qt libraries have been included.
I googled this problem and didn't find an answer.
Please explain me:
- Why this happens ?
- How to bypass this ? I use a combination of libraries in software development (stl, boost, opencv) and i cant develop software, applying ONLY QT.
Details:
QT version - 5.2
Mingw 4.8 and 6.02
.pro file
#------------------------------------------------- # # Project created by QtCreator 2018-04-28T23:53:47 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = qt_eception TEMPLATE = app SOURCES += main.cpp HEADERS += FORMS +=
main.cpp
#include <QApplication> #undef main int main(int argc, char *argv[]) { try { QApplication a(argc, argv); throw "ex"; } catch(...) { // Do Nothing } return 0; }
- mrjj Lifetime Qt Champion last edited by
Hi
Qt should not have any effect your your ability to use exceptions.
Tried your sample on win 10 , vs 2015 compiler and it works.
@mrjj I don't have any problem with exception, if i don't include and don't apply Qt library. I use Qt creator 3.0.0 and windows 7. Can you advise me, where start to research this problem ?
- mrjj Lifetime Qt Champion last edited by
@Petin
When you dont "apply Qt library. " can it be its other compiler or
setting that is being used ?
What compiler are you using ?
- JKSH Moderators last edited by | https://forum.qt.io/topic/90269/i-don-t-catch-exception-in-qt/ | CC-MAIN-2020-16 | refinedweb | 244 | 69.68 |
A loop statement allows a program to execute a statement(s) multiple times which provides easier and flexible programming. C has three loop statements.
While loop allows a set of statements to be executed repeatedly until a given condition is true. The While loop can be viewed as a repeating if statement.
while (condition) { statements; }
In below mentioned example, program uses while loop to sum all integers from 1 to 5.
#include <stdio.h> int main (){ int i = 1; int sum = 0; while (i < 6){ sum = sum + i; i = i+1; } printf("%i",sum); return 0; }
15
The Do-While loop in C is a variant of while loop which execute statements before checking the conditions. Therefore the Do-While loop executes statements at least once.
do { statements; } while (condition);
The above explained example is programmed using do-while loop and mentioned below:
#include <stdio.h> int main (){ int i = 1; int sum = 0; do{ sum = sum + i; i = i+1; } while (i < 6); printf("%i",sum); return 0; }
15 | https://www.alphacodingskills.com/c/c-while-loop.php | CC-MAIN-2019-51 | refinedweb | 170 | 70.53 |
You can subscribe to this list here.
Showing
1
results of 1
Hi folks,
On 30 Dec 2000, at 17:27, the Illustrious Danny Smith wrote:
> Hello Paul G
>
> In a couple of recent messages you have referred to libstdc++-v3
> as a "release". Do you really mean the long-awaited
> libstdc++-v3? I am aware of a pre-release (libstdc++-2.91) but
> have not attempted to build it because, as I understand, to fully
> take advantage of some of new features (new name mangling,
> namespace std support) one most rebuild gcc. Have you done this
> with mingw as target?
Yes.
> If so, I would like to try it out and in
> particular, compare (footprint, efficiency, locale support) with
> the STLPort of the SGI iostream lib I use most of the time.
Sure...
Standard URL:
A Snapshot klink for cygwin and mingw:
Peace,
Paul G.
Nothing real can be threatened.
Nothing unreal exists. | http://sourceforge.net/p/mingw/mailman/mingw-dvlpr/?viewmonth=200012&viewday=31 | CC-MAIN-2014-52 | refinedweb | 154 | 73.47 |
Asked
Viewed 32 times
0
This is my code:
import time import Adafruit_GPIO.I2C as Adafruit_I2C import struct from math import * # Registers OUT_X_MSB = 0x01 CTRL_REG1 = 0x2A XYZ_DATA_CFG = 0x0E i2c = Adafruit_I2C.Device(0x1c, 1) # Adresse accéléromètre # Setups for calculation with configuration 2g gPerCount = 2.0 /128 while True: #Recovery of data from the accelerometer (status,x,y,z) = i2c.readList(OUT_X_MSB, 4) # Formatting for calculation bytes = struct.pack('BBB', x, y, z) x, y, z = struct.unpack('bbb', bytes) # Calculation of the acceleration per axis as a function of the accelerometer parametrage x *= gPerCount y *= gPerCount z *= gPerCount print (x) print (y) print (z) time.sleep(1)
And the output is this:
-1.4375 1.4375 1.0625 -1.4375 1.4375 1.0625 -1.4375 1.4375 1.0625 -1.4375 1.4375 1.0625 -1.4375 1.4375 1.0625 -1.4375 1.4375 1.0625
I Have checked the wiring and everything and for the life of me I cannot tell what the problem is.
- Why are you packing/unpacking x, y, and z. Could you just print status, x, y, z as received. – joan Dec 19 ’19 at 11:18
- Could this be detecting gravity? I don’t know what position you chip is. Does it give the same numbers if you turn it? – NomadMaker Dec 19 ’19 at 12:56
- Ah, let me see. (1) Your final output is always “-1.4375, 1.4375.1.0625”, to 4 decimal places. This implies the 2’s complement raw figures always the same. So there is no need to do any calculation to convert the raw 2’s complement numbers. Your code before converting raw data is in two big steps: (1) Config, (2) Read raw data. We can first look at the config/setup part, in your case is only one statement “gPerCount = 2.0 /128”. One thing is check out is to config yourself, usually in two or three steps: (a) Set g range, (b) Set interrupt config, (c) start measurement mode. / to continue, … – tlfong01 Dec 19 ’19 at 13:29
- We need to read the friendly datasheet to see the config procedure: (1) MMA8451Q 3-Axis, 14-bit/8-bit Digital Accelerometer Datasheet Document Number: MMA8451Q Rev. 10.3, 02/2017- NXP/ nxp.com/docs/en/data-sheet/MMA8451Q.pdf, … / to continue, … – tlfong01 Dec 19 ’19 at 13:30
- To troubleshoot, usually I start reading the application notes: penzu.com/public/f38b4cd1 – tlfong01 Dec 19 ’19 at 13:43
- I think we better start with the app note written by the app enggr: App Note AN4076 Data Manipulation and Basic Settings of the MMA8451/2/3Q by: Kimberly Tuck Applications Engineer bdtic.com/download/nxp/AN4076.pdf – tlfong01 Dec 19 ’19 at 13:47
- I skimmed the app note, and found the following sections useful: Sections 3, Standby and active mode (with code examples), 7. Convert 2’complement to signed decimal, 9. Polling vs interrupt. One possible reason of your always getting the same data is BECAUSE YOU ARE IN STANDBY MODE, therefore always reading the old, never changing data.. – tlfong01 Dec 19 ’19 at 13:55
- Section 3 tells you how to set the active mode: Section 3.0 … The device changes from Standby to Active Mode via bit 0 in register 0x2A, with demo code:. /* ** Set the Active bit in CTRL Reg 1 */ IIC_RegWrite(CTRL_REG1, (IIC_RegRead(CTRL_REG1) | ACTIVE_MASK)); So you might like to try your luck. Warning: I have never seen or played with your accelero module. I am just reading the friendly datasheet and app notes. No guarantee nothing won’t melt down nor blow up. Good luck and cheers! 🙂 – tlfong01 Dec 19 ’19 at 14:05
- @tlfong01 Thank you, your solution actually worked. The output values are now read properly, but I am having a different problem and that is the SDA/SCL value change and I connect other things to different pin of the pi (in this case quadcopter’s propellers) but that is a different issue. Thanks again. – Stefanos 20 mins ago
- @Stefanos, How nice to hear that your problem is solved. Ah, SDA/SCL problems are also sometimes tricky. Perhaps you can ask your other I2C questions is this forum. Happy quadcopter propelling! Cheers. – tlfong01 just now Edit
.END
Categories: Uncategorized | https://tlfong01.blog/2020/01/11/mma845x-accelerometer-problem/ | CC-MAIN-2021-25 | refinedweb | 713 | 74.19 |
coelhoMembers
Content count249
Joined
Last visited
Community Reputation389 Neutral
About fcoelho
- RankMember
fcoelho replied to PrestoChung's topic in Engines and Middleware[quote name='PrestoChung' timestamp='1334100273' post='4930035'] What does this mean, exactly. How can I run ./configure if I'm not in the SDL directory? [/quote] That usually means something along the lines of: [code]mkdir sdl-build cd sdl-build ../configure[/code] I'm not sure though if it can be a sub-directory of the root SDL folder..
fcoelho posted a topic in GDNet Comments, Suggestions, and IdeasMiddle-clicking a link on pretty much any browser will make the link open in a new tab while still focusing the tab you clicked the link from. When in the GDnet front page, clicking any news link will have it open in a new tab and will focus that new tab, which means I can't easily open all the links I'd like to read in new tabs. Also, left-clicking those links will open a new tab, but if I go back to the news page and click on another story, it will "reuse" the previously opened tab.
fcoelho replied to MARS_999's topic in General and Gameplay ProgrammingYou can use the following, it will traverse the file tree recursively (won't follow symbolic links) and add the file and directory names to the appropriate vectors. It won't add the base directory (you can add it yourself and check with [font="Courier New"]boost::filesystem::is_directory[/font]) and will throw if "path" isn't a directory. [source lang="cpp"] void GetFiles(const std::string &path, std::vector<std::string> &file, std::vector<std::string> &dir) { try { boost::filesystem::recursive_directory_iterator it(path); boost::filesystem::recursive_directory_iterator end; for ( /**/ ; it != end ; ++it) { if (boost::filesystem::is_regular_file(*it)) { file.push_back(it->path().generic_string()); } else if (boost::filesystem::is_directory(*it)) { dir.push_back(it->path().generic_string()); } } } catch (boost::filesystem::filesystem_error &e) { std::cerr << "Error reading files: '" << e.what() << "'\n"; } } [/source]
OpenGL
fcoelho replied to Phynix's topic in Graphics and GPU ProgrammingIf you have any in/out variables in those shaders, make sure each is "shared" with two [b]subsequent[/b] shader stages, i.e.: If your vertex shader has some variable which tou want to send to your fragment shader, say, a [font="Courier New"]out vec2 someVar[/font], be sure to include in your geometry shader too: [source lang="cpp"] //vertex out vec2 someVarToGS; void main() { someVarToGS = ... } //geometry in vec2 someVarToGS[]; out vec2 someVarToFS; void main() { for (each vertex) { someVarToFS = ... EmitVertex(); } ... } //fragment in vec2 someVarToFS; void main() { ... } [/source] Your geometry shader is also empty, which will produce nothing. You have to output your vertices for something to be rendered
fcoelho replied to fcoelho's topic in Engines and MiddlewareSince I couldn't find any reasonable solution, I've modified tolua++ to accept free function operators. In short, tolua++ is already able to correctly generate off-class operator bindings, but doesn't know what to do with them. If the error directive on operator.lua is supressed, [source] if not t:inclass() then --error("#operator can only be defined as class member") end [/source] then generated code for some operator will live in the global namespace. If one opens the generated bindings and moves the lines corresponding to those operators to inside the class module, operator overloading works nicely, i.e., if [source lang="cpp"] tolua_beginmodule(tolua_S,NULL); ... tolua_beginmodule(tolua_S,"b2Vec2"); ... tolua_endmodule(tolua_S); tolua_function(tolua_S,".mul",tolua_lancamento__mul00); tolua_endmodule(tolua_S); [/source] is changed to [source lang="cpp"] tolua_beginmodule(tolua_S,NULL); ... tolua_beginmodule(tolua_S,"b2Vec2"); ... tolua_function(tolua_S,".mul",tolua_lancamento__mul00); tolua_endmodule(tolua_S); tolua_endmodule(tolua_S); [/source] then the custom operator works. Since I didn't want to do this every time the package file changed, I've modified the lua sources to register the function in the right place automatically, relying on the first parameter of the operator argument list to determine who to bind that operator to. So, if there's an [font="Courier New"]operator+(const b2Vec2&, const b2Vec2&)[/font], it gets added to the b2Vec2 class. Pretty lame, but gets the work done, as long as the first parameter is a custom type. It is extremely simple, so there are possibly a lot of corner cases that I didn't test, but it works for me. Some restrictions: [list] [*]Due to the way operator overload works in Lua, no operator+=, operator-= etc. (already considered by tolua++) [*]If the first argument of a certain type isn't a custom type, the binding generation will fail. In these cases, I had to define a "wrapper" operator just for the sake of it, like: [source lang="cpp"] inline b2Vec2 operator*(const b2Vec2 &a, float s) { return operator*(s,a); } [/source] [/list] To be honest, I'm not used to patching, but if anyone's interested, attached is the diff file from my mercurial repository.[attachment=4820:offclassop.zip]
fcoelho posted a topic in Engines and MiddlewareI'm trying to create bindings for Box2D to use within Lua with tolua++. Tolua++ can generate operator bindings when they're defined as members of the given class, but not when they're free functions. In order to properly use Box2D in Lua, I'd like to generate bindings for its vector (b2Vec2) operators, which are defined as free functions. How can I create these bindings? [url=""]Luabind seems to be able to handle this[/url], but I'd rather do it with tolua++ if there's a (easy) way.
- [quote name='Durakken' timestamp='1309138092' post='4828066'] Sorta what I am talking about. I haven't tried it with the gameIsRunning variable... [source lang="python"] while 1: if GameMode == "StartMenu": pass elif GameMode == "..." ... for event in pygame.event.get(): if event.type == QUIT: pygame.quit() screen.blit(background, (0,0)) pygame.display.flip() [/source] this is what causes it. I don't know why. I'm curious as it should work like that but it doesn't for me. [/quote] The only problem with that code is the use of pygame.quit() in the event loop, causing the screen variable to be invalid. Other than that, it's ok.
- [quote]If I move the for loop out the if...elif structure and put it under it between it and the blit, the #draw everything stuff. And then run it. If I then click on the X instead of closing the window will say "not responding" then go open up a Windows error window.[/quote] From your description, I've came up with: [source lang="python"] while gameIsRunning: if GameMode == "StartMenu": pass elif GameMode == "..." ... for event in pygame.event.get(): if event.type == pygame.QUIT: gameIsRunning = False screen.blit(background, (0,0)) pygame.display.flip() pygame.quit() [/source] Which will run and quit without issues, so I don't think I know what you've done. Care to show some code?
- [quote]Thank you, can you tell me why a simple break doesn't work where you place gameisRunning = False (hit the close button does nothing)?[/quote]That's because [font="Courier New"]break[/font] will put you out of the innermost loop. In this case, the [font="Courier New"]for[/font] loop, not the [font="Courier New"]while[/font] loop. [quote]or why moving the for loop to about the blit it causes the game to stop responding?[/quote] I can't really tell what do you mean with that, or to [i]where[/i] the for loop really goes.
fcoelho replied to sleepingtom's topic in For Beginners[quote name='Kpyrate' timestamp='1309116110' post='4827974']in the introduction when it is stating that: - print "hello, world!" - will generate the quoted texted, I only get syntax errors. [/quote] If a simple [code]print "Hello, world"[/code] fails with a syntax error, that's most likely because you're running Python version 3 instead of Python 2. In that case, [url=""]check the link for the third edition of the book, which uses Python 3.[/url]
- [font="Courier New"] pygame.quit()[/font] doesn't quit your game. It just tells Pygame to get rid of it's resources, it's a cleanup method. When [font="Courier New"]pygame.QUIT[/font] is received, your program calls [font="Courier New"]pygame.quit()[/font] and it deletes a few things here and there, but your program keeps running. When you get to the line "[font="Courier New"]screen.blit(background, (0, 0))[/font]", the variable [font="Courier New"]screen[/font] is invalid, causing the [font="Courier New"]blit[/font] to fail. Instead of running everything inside a [font="Courier New"]while 1[/font] loop, keep a variable to tell whether your game is running, and set it in the event loop accordingly: [code] gameIsRunning = True while gameIsRunning: for e in pygame.event.get(): if event.type == QUIT: gameIsRunning = False [/code] After that, place [font="Courier New"]pygame.quit() [/font][font="Arial"]outside the game loop, so you don't run into invalid data.[/font]
- I've tried to change my create_fbo function, especially the texture clamping modes to see if there was a change, but the "replica" of the shadow right above the correct one still appears. Any ideas on how do I fix it? [code]FBO create_fbo(unsigned width, unsigned height) { FBO fbo; glGenFramebuffers(1, &fbo.id); glBindFramebuffer(GL_FRAMEBUFFER, fbo.id); glGenTextures(1, &fbo.zId); glGenTextures(1, &fbo.cId); glBindTexture(GL_TEXTURE_2D, fbo.cId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, fbo.zId);_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo.cId, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo.zId, 0); GLenum fboStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (fboStatus != GL_FRAMEBUFFER_COMPLETE) std::cerr << "Framebuffer incomplete\n"; return fbo; }[/code]
- In the fragment shader, something is considered shadowed when [code] if (depthFromLight < depthFromCamera) shadow = 0.5;[/code] But this creates the following artifact: [attachment=1626:samplingbehindfrustum.jpg] I've tried to use what's on [url=""]this[/url] site: [code] if (position.w > 0.0)[/code] but it doesn't fix it, it stays the same. I tried to use a "inFrustum" variable to check whether I should check the shadow map for texturing: [code]bool inFrustum = shadowCoord.x > 0.0 && shadowCoord.x < 1.0 && shadowCoord.y > 0.0 && shadowCoord.y < 1.0;[/code] But it creates another problem: [attachment=1625:infrustum.jpg] So, how do I fix this? [list=1][/list]
- The bias matrix is responsible for converting clip coordinates to a "texture coordinate acceptable range", i.e., converting the range [-1,+1] to [0,1]. I solved the problem a few hours ago, it was actually a bug with my math library + compiler version, which caused the bias matrix to be built incorrectly, instead of the expected [code] [.5 0 0 .5] [ 0 .5 0 .5] [ 0 0 .5 .5] [ 0 0 0 1] [/code] it compiled into [code] [ 1 0 0 .5] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [/code] It's mostly working now, except for some shadows outside the light frustum which I haven't been able to remove. I'm going to post it back here when I get home.
- bump? | https://www.gamedev.net/profile/142670-fcoelho/ | CC-MAIN-2017-30 | refinedweb | 1,861 | 56.96 |
Edit: This code is now on PyPi:
tl;dr Metaclasses are awesome
When using Django's Model or Form frameworks you can define a fixed set of choices for fields which are list of tuples containing a value and some text to associate with that value. The docs give the example code below to demonstrate how to define and use them, recommending that you define each of the choice values inside the Model as well as the list of choice tuples.
class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN)
I personally think that it looks ugly and violates DRY (something Django tries hard not to do) by doing it this way. It seems to me that this is inadequate because if you have a lot of fields with different and distinct choices the models themselves can get very long and messy or if you have two models that need the same choices you have to either have inter-model dependencies which is almost as bad as your other option of duplicating the choices in the other models definition. In my experience the display name of the choice is very similar to the name of the value it is referencing, for example in the code above each of the display text is just a correctly capitalized version of its value's reference so it seems almost silly having to write "sophomore" or "junior" 3 times to define a simple choice.
Wouldn't it be freaking awesome if you could define Django field choices like so:
class YearInSchool(Choice): FRESHMAN = 'FR', 'Fresher' # Fresher is the display text SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR', "Senior Student" class Student(models.Model): year_in_school = models.CharField(max_length=2, choices=YearInSchool, default=YearInSchool.FRESHMAN) freshers = Student.objects.filter(year_in_school=YearInSchool.FRESHMAN).all()
Well with a bit of metaclass magic you can. A metaclass in python is a class who's instances are classes instead of instances of classes. Kind of. If you are confused by that then have a look at this example code:
class Choice(object): class __metaclass__(type): def __init__(self, *args, **kwargs): print "I am alive!" print self def __iter__(self): for i in xrange(10): yield i
If you know anything about Python classes then this should look familiar. We define a class called Choice and inside that class we define another one called metaclass which has two special functions (shown by the double underscores surrounding the function name), init and iter. Those two methods are 'special' ones that most people know - init gets called when an instance of the class is being created and iter gets called when that instance is being enumerated. With metaclasses its exactly the same but instead of acting on instances of the class it acts on the class itself. Immediately after defining the class above the init gets called and you should see "I am alive!" get printed out as well as the class object self is referencing. Using the code above we can enumerate our class (the iter function gets called)
>>> list(Choice) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Its as simple as that. You can probably see where I am going here - it wouldn't be hard at all to create a class that returns its class fields in a form Django accepts for choices when it is being enumerated. Because i'm such a nice guy the code I have come up with is below:
import inspect class Choice(object): class __metaclass__(type): def __init__(self, name, type, other): self._data = [] for name, value in inspect.getmembers(self): if not name.startswith("_") and not inspect.isfunction(value): if isinstance(value,tuple) and len(value) > 1: data = value else: data = (value, " ".join([x.capitalize() for x in name.split("_")]),) self._data.append(data) setattr(self, name, data[0]) def __iter__(self): for value, data in self._data: yield value, data
Any subclass of Choice will introspect itself after it has been defined and extract its choices. A choice can be defined as one value or a tuple of (value, display_text). If the display text is not explicitly defined then it is generated from the field name (underscores converted to spaces and capitalized). After this the display name is removed from the class so when you reference it only the value is returned
>>> class UserLevels(Choice): USER = 1 MODERATOR = 2 ADMIN = 3, "Gods" >>> list(UserLevels) [(3, 'Gods'), (2, 'Moderator'), (1, 'User')] >>> UserLevels.ADMIN 3
So yeah. Metaclasses are pretty damn sweet and this makes my Django projects models (which often have 20+ different choice definitions) a lot nicer to look at.
UPDATE You want a way to get the name from a value? No problem. Christopher Trudeau got in contact with me and proposed this code, the difference being an added get_value function that returns the name based on the value, e.g Choice.get_value(1). Thanks Chris!
class Enum(object): class __metaclass__(type): def __init__(self, *args, **kwargs): self._data = [] for name, value in inspect.getmembers(self): if not name.startswith('_') and not inspect.ismethod(value): if isinstance(value, tuple) and len(value) > 1: data = value else: pieces = [x.capitalize() for x in name.split('_')] data = (value, ' '.join(pieces)) self._data.append(data) setattr(self, name, data[0]) self._hash = dict(self._data) def __iter__(self): for value, data in self._data: yield (value, data) @classmethod def get_value(self, key): return self._hash[key] | http://tomforb.es/using-python-metaclasses-to-make-awesome-django-model-field-choices?pid=0 | CC-MAIN-2015-32 | refinedweb | 929 | 61.56 |
Use Rails URL Helper with Javascript
Sometimes in some projects that I worked on I needed to use Rails URLs inside my JS, but I couldn't do this directly because, as you know, we need to integrate our scripts in some .erb file to be able to use them. So, to save you some time, you can use this gem.
Installing
gem "js-routes"
Setup
Require the js routes file in application.js or other manifest:
= require js-routes
Also in order to flush asset pipeline cache, sometimes you might need to run:
rake tmp:cache:clear
You have an advance setup mode adding
config/initializers/jsroutes.rb to your initializers. To see all the available options you can modify, click here.
Usage
Configuration above will create a nice javascript file with Routes object that has all the Rails routes available:
Routes.users_path() // => "/users" Routes.user_path(1) // => "/users/1" Routes.user_path(1, {format: 'json'}) // => "/users/1.json"
This is how you can use a serialized object as a route function argument:
var google = {id: 1, name: "Google"}; Routes.company_path(google) // => "/companies/1"
Advanced Setup
In case you need multiple route files for different parts of your application, you have to create the files manually. If you have in your application an admin and an application namespace for example:
# app/assets/javascripts/admin/routes.js.erb <%= JsRoutes.generate(namespace: "AdminRoutes", include: /admin/) %> # app/assets/javascripts/admin.js.coffee #= require admin/routes
# app/assets/javascripts/application/routes.js.erb <%= JsRoutes.generate(namespace: "AppRoutes", exclude: /admin/) %> # app/assets/javascripts/application.js.coffee #= require application/routes
This gem is nice to have on any project, because it gives you the possibility to use the Rails URL helpers on your fronted, you don't need to work anymore on .erb files to be able to use Rails paths inside your js scripts, making it extremely helpful.
I hope this helps you and saves you time and effort. Remember to contribute on the gem if you have any ideas to improve it, or even better: create your own gems to solve other problems and tell us about them!
Post any questions or comments below, we're happy to read you.
Cheers! | http://blog.magmalabs.io/2015/01/30/use-rails-url-helper-with-javascript.html | CC-MAIN-2019-09 | refinedweb | 366 | 56.86 |
hi everyone. how are you?
i have a class square that inherits the rectangle class. what i have is center coordinates of the center of a square. i have figured the arithmetic to getting the coords of the top left coord of the square (rectangle). what i need to do is to use the methods setSize and setLocation of the Rectangle class to tell the program that these new coordinates are where the square actually is, and then i can return the values to the user, but how do i properly use the methods setSize and setLocation?
Code :
import java.awt.Rectangle; public class Square extends Rectangle { public int x; public int y; public int sideLength; public Square(int xCoord, int yCoord, int lengthOfSide) { x = xCoord; y = yCoord; sideLength = lengthOfSide; } int xCoordTopLeft = x - sideLength / 2; int yCoordTopLeft = y + sideLength / 2; Rectangle r = new Rectangle(x, y); [B]r.setLocation(xCoordTopLeft, yCoordTopLeft); // error - says parentheses are misplaced r.setSize(sideLength, sideLength); //error[/B] public int getArea() { int area = sideLength * sideLength; return area; } } | http://www.javaprogrammingforums.com/%20java-theory-questions/3613-using-setsize-setlocation-methods-rectangle-class-printingthethread.html | CC-MAIN-2015-27 | refinedweb | 171 | 53.31 |
[Solved] Focus, child items, and the end of my wits
Hey guys,
I've got an example here where I'm trying to find the "best" way to do this. I've got a QML window with 2 elements: a text box and a listview. You guessed it, it's a search window.
I can easily assign focus programatically to 'scope' by setting scope.focus = true. The problem occurs when I try and figure out a decent way for setting the right focus when clicking on an element in the listview. The only way I can think of this happening in the delegate is by doing some parent.parent.parent.parent gibberish but that is very fragile as it depends on the hierarchy and I'm trying to create a re-usable ListView for my app.
Can anyone think of a pattern that would help me accomplish what I'm trying to do here?
Thanks!
@
import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
import QtGraphicalEffects 1.0
ApplicationWindow {
width: 600
height: 300
id: win ColumnLayout { anchors.fill: parent Text { Layout.fillWidth: true text: scope.focus ? "ListView has focus" : "ListView doesn't have focus" } TextInput { Layout.fillWidth: true focus: true } /* This is defined somewhere else, independent of the focus scope below */ Component { id: myDelegate Text { text: modelData ? modelData.name + ' (' + modelData.age + ')' : '' width: parent ? parent.width : 0 height: 32 MouseArea { anchors.fill: parent onClicked: { /* how best to set the rectangle enclosing the focus scope to have focus? */ /* This is the effect I want, but without referring to "scope" directly */ /* scope.focus = true */ /* Another way */ var scopehack = parent.parent.parent.parent.parent.parent.parent.parent.parent.parent console.log(scope,scopehack) scopehack.focus = true } } } } /* Actually a Flipable */ Rectangle { id: theflipable color: "#AABBCCDD" Layout.fillWidth: true Layout.fillHeight: true FocusScope { id: scope anchors.fill: parent focus: true Rectangle { anchors.fill: parent color: "transparent" radius: 3 RectangularGlow { anchors.fill: parent visible: scope.activeFocus glowRadius: 10 spread: 0.2 color: "red" cornerRadius: 13 } ScrollView { anchors.fill: parent /* The following two properties allow us to use keyboard navigation within the ListView. See */ flickableItem.interactive: true focus: true ListView { anchors.fill: parent boundsBehavior: Flickable.StopAtBounds clip: true focus: true model: ListModel{} delegate: Loader { width: parent.width sourceComponent: myDelegate property variant modelData: model } highlightFollowsCurrentItem: true highlight: Rectangle { width: parent ? parent.width : 0 color: "#3465A4" } highlightMoveDuration: 250 Component.onCompleted: { for(var ii = 0; ii < 250; ++ii) { model.append({'age':ii,'name':'Bopinder ' + ii}) } } } } } } } }
}
@
what is the problem with setting the focus via id.focus = true or id.forceActiveFocus()? I don't understand why you don't like that, still better than parent.parent.parent.parent.parent.focus = true I guess :D
Edit: if you don't know the item id at that point why not setting it from the outside to a custom property or something?
@
property Item focusTarget
@
and than from outside just set it to some id you want to get focus when you click on the delegate
@
yourComp.focusTarget = scope
@
Because the problem I have is something like this:
@
MyTopLevelWindow {
ColumnLayout {
SearchBar {}
RectangularGlow{...visible: searchResults.activeFocus }
SearchResults{ id: searchResults}
}
@
The actual ListView is way down, deep somewhere in the guts of SearchResults because I have a particular implementation I want to use. The focus is assigned to that but the rectangular glow effect is on the searchResults container. Does that make sense?
It looks like ListView.forceActiveFocus does what I need. Gonna do some testing.
see my edit, maybe that helps or I still don't know what the problem is the Item ids are usually accessible from everywhere unless its a separate qml file but then you can simple use an property alias or what i suggested maybe?
The key points to getting this was:
Understanding that FocusScope is a chain going up ancestry
I needed to was to forceActiveFocus on the child I wanted to get the active focus so it would bubble up to the parent that eventually had the RectangularGlow attached. Simply setting child.focus = true was not sufficient.
Thanks for the quick help Xander84! | https://forum.qt.io/topic/39494/solved-focus-child-items-and-the-end-of-my-wits/3 | CC-MAIN-2018-22 | refinedweb | 678 | 51.75 |
The lab I got from my teacher is supposed to be a 2D array. We're supposed to be using it to where it reads the strings from the file, and then it prints them out in an hour glass form like this:
HELLO
E L
L
E L
HELLO
This is my code so far, I just don't know how in the heck to get it to read string the strings from a file, then convert it to a char matrix, or any of that. If anyone could please explain and help me with my code, I'd highly appreciate it.
import java.io.*; import java.util.Scanner; public class Pattern { public static void main(String args[]) throws FileNotFoundException { System.out.println("Enter the path of the file:"); Scanner kb = new Scanner(System.in); String path = kb.next(); Scanner file = new Scanner(new File(path)); String s = file.next(); int start = 0; int q = 1; for(int r = 1; r <= s.length()-2; r++){ for(int c = 0; c < s.length()-start; c++){ if(c < start) System.out.print(" "); else System.out.print(((c - start) % 2 == 0) ? " " : s.charAt(c)); } System.out.println(); start += q; if(start==s.length()/2){ start -= q; start--; q *= -1; } } System.out.println(s); } } | https://www.javaprogrammingforums.com/whats-wrong-my-code/13771-2d-array-strings.html | CC-MAIN-2019-51 | refinedweb | 211 | 84.37 |
Created on 2010-08-05 09:32 by mark, last changed 2013-01-07 16:19 by serhiy.storchaka.
If you read in an XML file that specifies its encoding and then later on use xml.etree.ElementTree.write(), it is always written using US-ASCII.
I think the behaviour should be different:
(1) If the XML that was read included an encoding, that encoding should be remembered and used when writing.
(2) If there is no encoding the default for writing should be UTF-8 (which is the standard for XML files).
(3) For non-XML files use US-ASCII.
Naturally, any of these could be overridden using an encoding argument to the write() method.
It behaves as documented. Moved to "feature request".
I think it makes sense to keep input and output separate. After all, the part of the software that outputs a document doesn't necessarily know how it came in, so having the default output encoding depend on the input sounds error prone. Encoding should always be explicit. My advice is to reject this feature request.
Perhaps a useful compromise would be to add an "encoding" attribute that is set to the encoding of the XML file that's read in (and with a default of "ascii").
That way it would be possible to preserve the encoding, e.g.:
import xml.etree.ElementTree as etree
xml_tree = etree.ElementTree(in_filehandle)
# process the tree
xml_tree.write(out_filehandle, encoding=xml_tree.encoding)
lxml.etree has encapsulated this in a 'docinfo' property which also holds the XML 'version', the 'standalone' state and the DOCTYPE (if available).
Note that this information is readily available in lxml.etree for any parsed Element (by wrapping it in a new ElementTree), but not in ET where it can only be associated to the ElementTree instance that did the parsing, not one that just wraps a parsed tree of Element objects. I would expect that this is still enough to handle this use case, though.
Stefan
I don't see how lxml is relevant here? lxml is a third party library, whereas etree is part of the standard library. And according to the 3.1.2 docs etree doesn't have a docinfo (or any other) property.
That's why I mention it here to prevent future incompatibilities between the two libraries. | http://bugs.python.org/issue9522 | CC-MAIN-2015-35 | refinedweb | 386 | 66.13 |
The next version of OS (Vista) will have state-of-the-art speech technology built right in. WinFX will have a powerful API for enabling your users to speak to your apps and your apps to speak to your users.
At the last PDC (2005), Phillip Schmid, Robert Brown and Steve Chang gave a great talk “Ten Amazing Ways to Speech-Enable Your Application”, available at.
Below are some key points from the talk…
Vista will ship with 8 language speech recognizers
Vista shell is speech enabled, i.e. you can drive it without using a mouse or keyboard. If you can see it on the screen, you can say it! Anything you can do with a keyboard or mouse, you can say it!
Dictation is built into OS, i.e. any application that has a text field can take in dictation. Yes, no code needed — your application is automatically dictation enabled!
System.Speech API is now part of WinFX. Why use it? To add more speech enabled functionality than “what you see – you can say”. E.g. you can speech enable deeply nested menus…
Speech Synthesizer Example:
using System.Speech.Synthesis;
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
// To speak
synthesizer.SpeakText(“Your sentence goes here”);
// To send the output of synthesizer to .wav file
synthesizer.SetOutputToWaveFile(“YOUR FILE PATH HERE”);name
synthesizer.SpeakText(“Your sentense goes here”);
To customize speach recognition, do the following:
// 1. Create SpeechRecognizer instance (normally, once per application)
using System.Speech.Recognition;
SpeechRecognizer speechRecognizer = new SpeechRecognizer();
// 2. Create Grammar instance
Grammer phoneGrammer = new Grammar(“YOUR GRAMMAR FILE HERE”);
The grammar file is an xml file with words the speech recognizer should understand, and their mapped actions; e.g. in a provisioning application, you might have the following commands:
<rule id=PhoneCommands” scope=”public”>
<one-of>
<item> purchase new phone <tag>synthisizerAction=”PurchaseNewPhone”</tag> </item>
<item> reuse existing phone <tag>synthisizerAction=”ReusePhone”</tag> </item>
</one-of>
</rule>
// 3. Load grammar into recognizer
recognizer.LoadGrammar(phoneGrammer); // note: there can be many grammars loaded at the same time
// 4. Subscribe to SpeechRecognized event
phoneGrammer.SpeechRecognized += new EventHandler<RecognitionEventArgs>(PhoneGrammer_SpeechRecognized);
void PhoneGrammer_SpeechRecognized(object sender, RecognitionEventArgs e)
{
switch((string) e.Result.Semantics[“synthesizerAction”].Value)
{
case “PurchaseNewPhone”:
// TODO: Show new phone purchase form
break;
case “ReusePhone”:
// TODO: Show existing phone re-purposing form
break;
}
}
Now, how does Microsoft Speech Server relate to Vista’s speech functionality?
Microsoft Speech Server is about speech enabling your applications from the phone.
First, let’s set the stage… For those who are not familiar with this technology, Microsoft Speech Server acts as a digital data-to-voice translator:
– It interprets voice commands/data from a user and digitizes it
– It offers digitized information as XML to a web application for manipulation
– It takes digital information from a web application and ‘vocalizes’/’reads’ it to a user.
The possibilities range from sales support (e.g. you can search for customer phone numbers/addresses over the phone with your voice), to getting vocal directions from MapPoint to your customer’s location read to you while on the road, to commerce sites allowing you to check on the order status of an online purchase, get an ETA, and even to change the destination shipping address, to being able to record a message for a person and have it sent via email attachment via Exchange… Not to mention unprecedented support for developers to create friendly web applications for more easy access to the visually impaired.
The future version of Speech Server will use the same API, as one exposed in Vista, for extending the reach of your .NET applications to the telephone.
The SDK is available now, and can be used with VS 2005!
that’s cool.
would you tell me what exactly are those 8 languages?
From what I’ve been able to find out (read: no guarantee), the following languages will be supported:
– Chinese Simplified
– Chinese Traditional
– German
– Italian
– Japanese
– Korean
– Spanish
Does this work on XP too, or just Vista?
You can install WinFX on Windows XP. The Speech API is a part of the WinFX.
Actually while most of this does work on XP, importing a grammar from an XML file does not. It throws a NotSupportedException. Building the grammar in code does though.
I THINK they will have Brazilian Portuguese and French avaliable too (two important languages for microsoft that is still missing).
please I want to know how to get the other languages like spanish because I use it a lot in some documents | https://blogs.msdn.microsoft.com/irenak/2006/02/15/sysk-63-vistas-speech-capabilities/ | CC-MAIN-2017-17 | refinedweb | 749 | 55.44 |
Editor's note: An updated version of this article titled "Get started with Eclipse Platform" was published in July 2007. This original version will remain available for reference purposes. Read the new article to understand the latest features in Eclipse.
What is Eclipse?
Eclipse is a Java-based, extensible open source development platform. By itself, it is simply a framework and a set of services for building a development environment from plug-in components. Fortunately, Eclipse comes with a standard set of plug-ins, including the Java Development Tools (JDT).
While most users are quite happy to use Eclipse as a Java IDE, its ambitions do not stop there..
This parity and consistency isn't limited to Java development tools. premiere example of an Eclipse-based application is the IBM® WebSphere® Studio Workbench, which forms the basis of IBM's family of Java development tools. WebSphere Studio Application Developer, for example, adds support for JSPs, servlets, EJBs, XML, Web services, and database access. re-distributed better balance between commercial and community concerns.
The Open Software Initiative is a nonprofit organization that explicitly defines what open source means and certifies licenses that meet its criteria. Eclipse is licensed under the OSI-approved Common Public License (CPL) V1.0, which "is intended to facilitate the commercial use of the Program ..." (for the complete text of the Common Public License V1.0, see Resources).
Developers who create plug-ins for Eclipse or who use Eclipse as the basis for a software development application are required to release any Eclipse code that they use or modify under the CPL, but are free to license their own additions in any way they like. Proprietary code bundled with software from Eclipse does not need to be licensed as open source, and the source code does not need to be made available.
Although most developers will not use Eclipse to develop plug-ins or to create new products based on Eclipse, the open source nature of Eclipse is important beyond the mere fact that it makes Eclipse available for free .
Who is Eclipse?
The Eclipse.org Consortium manages and directs Eclipse's ongoing development. Created by IBM after reportedly spending $40 million developing Eclipse and releasing it as an open source project, the Eclipse.org Consortium recruited a number of software tool vendors including Borland, Merant, Rational, RedHat, SuSE, TogetherSoft, and QNX. Other companies have since joined, including Hewlett-Packard, Fujitsu, and Sybase. These companies each appoint a representative to a Board of Stewards that determines the direction and scope of the Eclipse project.
At the highest level, the Project Management Committee (PMC) manages the Eclipse project. The project is divided into subprojects and each of these has a leader. Large subprojects are divided into components, and each of these also has a leader. At present, most of these managerial roles are filled by people from the IBM subsidiary that originally developed Eclipse, Object Technology International (OTI), but as an open source project, anyone is welcome to participate. Responsibility for any specific piece is earned by contributing to the project.
Now that we've looked at some of the theory, history, and politics behind Eclipse, let's take a look at the product itself.
The Eclipse Workbench
The first time you open Eclipse, you see the welcome screen.
Figure 1. The Eclipse Workbench
.
Most of the other features of the workbench, such as the menu or the toolbar, should be similar to those of familiar applications. One convenient feature is a toolbar of shortcuts to different perspectives that appears on the left side of the screen; these vary dynamically according to context and history. Eclipse also comes with a robust help system that includes user guides for the Eclipse workbench and the included plug-ins such as the Java Development Tools. It is worthwhile to browse through the help files at least once to see the range of available options and to better understand the flow of Eclipse.
To continue this short tour of Eclipse, Environment (JDE)
To try out the Java development environment, we'll create and run a Hello World application. Using the Java perspective, right-click on the Hello project, and select New > Class, as shown in Figure 2. In the dialog box that appears, type "Hello" as the class name. Under "Which method stubs would you like to create?" check "public static void main(String[] args)," then Finish.
Figure 2. Creating a new class in the Java perspective
This will create a
.java file with a
Hello class and an empty
main() method in the editor area as shown in Figure 3. Add the following code to the method (note that the declaration for
i has been deliberately omitted):
Figure 3. The Hello class in the Java editor
You'll notice some of the Eclipse editor's features as you type, including syntax checking and code completion. In V2.1 (which I previewed by downloading build M2), when you type an open parenthesis or double quote, Eclipse will provide its partner automatically and place the cursor inside the pair.
In other cases, 4 shows the list of suggestions and the code it suggests for a local variable.
Figure 4. Quick Fix suggestions
>>IMAGE in Figure 5.
Figure 5. Output from the program
>>IMAGE 6.
Figure 6. The Debug perspective
CVS, the open source Concurrent Versions System.
Third-party plug-ins include:
Version control and configuration management
- CVS
- Merant PVCS
- Rational ClearCase
UML modeling
- OMONDO EclipseUML
- Rational XDE (replaces Rose)
- Together WebSphere Studio Edition
Graphics
- Batik SVG
- Macromedia Flash
Web development, HTML, XML
- Macromedia Dreamweaver
- XMLBuddy
Application server integration
- Sysdeo Tomcat launcher
For a more complete list of available plug-ins, see Resources.
Example: A UML modeling plug-in
To view an example of a plug-in and see how it integrates with Eclipse, download the popular OMONDO EclipseUML (see Resources); you'll need to register, but the plug-in is free. This plug-in depends on Graphical Editor Framework (GEF), another plug-in for Eclipse. GEF is part of the Tools subproject. To download GEF, go to the Eclipse Web site (see Resources), select Downloads and click the link for the Tools PMC downloads page. Note you will need to download the GEF build recommended by OMONDO (GEF V2.0 for OMONDO V1.0.2).
Once downloaded, a plug-in is usually installed by unzipping the download file and copying its contents to the Eclipse plug-ins directory. In this case, GEF requires that it be unzipped into the Eclipse directory (it automatically goes into the plug-ins directory from there) while EclipseUML requires unzipping directly into the plug-ins subdirectory of the Eclipse directory. To be safe, you might want to unzip each into a temporary directory and copy the directories as appropriate from there. If Eclipse is running, you'll need to stop and restart it for the plug-ins to be recognized.
Once EclipseUML (and GEF) are installed, you can create a class diagram the same way you create a Java class file. In the Java perspective, right click on the Hello project in the Package Explorer and select New > Other from the pop-up menu. There will be a new option for UML in the left panel of the New dialog. The free version of EclipseUML only supports class diagrams, so the only option on the right is UML Class Diagram. Select UML Class Diagram, and type in a name for the class diagram, such as "Hello":
Figure 7. The class diagram editor
In the editor area, a graphical editor will appear with a blank canvas for a class diagram. There are two ways you can create a class diagram: by reverse-engineering existing code by dragging and dropping a Java file from the Package Explorer onto the class diagram or by using the drawing tools available in the toolbar above the blank diagram. To try out the first method, create a new class called Person (use File > New >Class ) and give it the two private attributes listed below.
Listing 1. Two private attributes
/** Person.java * @author david */ public class Person { private String name; private Address address; /** * Returns the address. * @return Address */ public Address getAddress() { return address; } /** * Returns the name. * @return String */ public String getName() { return name; } /** * Sets the address. * @param address The address to set */ public void setAddress(Address address) { this.address = address; } /** * Sets the name. * @param name The name to set */ public void setName(String name) { this.name = name; } }
(I should confess that I only typed in the lines for the name and address attributes. The getter and setter methods were automatically generated through Eclipse by right-clicking on the source code and selecting Source > Generate Getter and Setter from the pop-up menu.)
Save and close
Person.java
Hello.ucd.
Figure 8. The Person class diagram
To create a Java class from the UML, click New class on the toolbar at the top of the class diagram window, third button from the left, and click on the class diagram. When the New class wizard opens, type in Address as the class name and click Finish.
You can add attributes to the class by right-clicking on the class name and selecting New > Attribute. In the New attribute dialog box, enter the attribute name, type, and visibility. Add methods by right-clicking on the class name and selecting New > Method.
As you change the diagram, the Source Editor window below the diagram will reflect the changes. Finally, you can diagram the relationship between the classes by clicking on the Association button (fifth from the left) and drawing a line from the Person class to the Address class. This will bring up another dialog box where the association properties can be entered (refer to the EclipseUML help for more information about the required information). The diagram should look something like Figure 9.
Figure 9. Association
This UML
plug-in demonstrates several characteristics that are typical of Eclipse
plug-ins. First, it shows the tight integration between tools. It is
never obvious that there are multiple components at work; the integration with
the Eclipse Platform and the JDT are seamless. For example, when the Person
class was created, it displayed syntax errors because one of its attributes,
Address, was undefined. These went away once the
Address class was created in the UML diagram.
Another characteristic is EclipseUML's ability to build on functionality offered by other plug-ins — in this case, the GEF, which provides tools for developing visual editors.
Yet another characteristic involves the way the EclipseUML plug-in is distributed using several tiers of functionality. The basic plug-in, which supports class diagrams, is free, but more sophisticated versions are available for a fee.
Eclipse Platform architecture
The Eclipse Platform is a framework with a powerful set of services that support plug-ins, such as JDT and the Plug-in Development Environment. It consists of several major components: the Platform runtime, Workspace, Workbench, Team Support, and Help.
Figure 10. The Eclipse Platform architecture
Platform
The Platform runtime is the kernel that discovers at startup what plug-ins are installed and creates a registry of information about them. To reduce start-up time and resource usage, it does not load any plug-in until it is actually needed. Except for the kernel, everything else is implemented as a plug-in.
Workspace
The Workspace is the plug-in responsible for managing the user's resources. This includes the projects the user creates, the files in those projects, and changes to files and other resources. The Workspace is also responsible for notifying other interested plug-ins about resource changes, such as files that are created, deleted, or changed.
Workbench
The Workbench provides Eclipse with a user interface (UI). It is built using the Standard Widget Toolkit (SWT) — a nonstandard alternative to Java's Swing/AWT GUI API — and a higher-level API, JFace, built on top of SWT that provides UI components.
The SWT has proven to be the most controversial part of Eclipse. SWT is more closely mapped to the native graphics capabilities of the underlying operating system than Swing or AWT, which not only makes SWT faster but also allows Java programs to have a look and feel more like native applications. The use of this new GUI API could limit the portability of the Eclipse workbench, but SWT ports for the most popular operating systems are already available.
The use of SWT by Eclipse affects only the portability of Eclipse itself — not any Java applications built using Eclipse, unless they use SWT instead of Swing/AWT.
Team support
The team support component is responsible for providing support for version control and configuration management. It adds views as necessary to allow the user to interact with whatever.
The forecast for Eclipse
A critical mass is developing around Eclipse. Major software tool vendors are on board, and the number of open source Eclipse plug-in projects is growing every day.
A portable, extensible, open source framework isn't a new idea, but because of its mature, robust, and elegant design, Eclipse brings a whole new dynamic into play. IBM's release of $40 million worth of world-class software into the open source arena has shaken things up in a way that has not been seen in a long time.
Resources
Learn
- Documentation, articles, and downloads of Eclipse are available from Eclipse.org.
- Information about open source software, including certified open source licenses such as the Public Common Licence, is available at the OpenSource.org.
- For an introduction to the Eclipse Platform, read "Working the Eclipse Platform."
- "Getting to know WebSphere Studio Application Developer" explains its capabilities, technologies, and its relationship to the Eclipse IDE.
- "Internationalizing your Eclipse plug-in" explains how to write Eclipse plug-ins for the international market. And "Testing your internationalized Eclipse plug-in" explains how to test Eclipse plug-ins for the international market.
- Author Benoit Marchal uses the Eclipse platform's open universal framework to build a user interface for XM in "Working XML: Use Eclipse to build a user interface for XM."
- Browse all the Eclipse content on developerWorks.
- Users new to Eclipse should look at the Eclipse start here.
- Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources.
- To listen to interesting interviews and discussions for software developers, check out popular OMONDO EclipseUML; you'll need to register, but the plug-in is free.
-. | http://www.ibm.com/developerworks/opensource/library/os-ecov/ | CC-MAIN-2015-32 | refinedweb | 2,406 | 53.21 |
Last.
Development tools
The php interpreter can be installed for usage from the command line, and as a consequence PHPUnit can be installed via PEAR ($ pear) to provide the phpunit command.
Phing is an Ant equivalent that makes it easier to integrate PHP-based tools as task. In our case, it is not necessary for starting out as in most cases it's just an interface over shell scripts. We automatically choose Vim for the editing part, but IDEs are welcome if you have an habit of working with them.
Jenkins is the standard choice for Continuous Integration, and it's not really dependent on the language; if we need a PHP-specific static analysis tool we'll look for a template and to introduce Phing build files.
The language
Compared with Java, PHP has many similarities: classes and interfaces as constructs, plus private, protected and public visibility for fields and methods. Due to the common age, both languages have several scalar base types like int and bool, but PHP also has string as one of them.
A similarity with Ruby is the presence of dynamic typing: you'll never see typing information on fields and parameters if not for documentation or defensive programming (like type hints).
The advantages of PHP are that it's built for the web, featuring a model based on lots of different workers each executing a PHP process. There are lots of batteries included for working with HTTP, formats and databases; and deployment is very easy.
The defects you'll live with are that these batteries are scattered in the global namespace, mostly as functions for historical reasons. But for any help, type php.net/functionname in your browser to see documentation on parameters, return values, edge cases and sample usage.
Project setup
A common choice for organizing code (mostly classes, each with its own source file) is in two src/ and test/ parallel trees. Classes should follow the PSR-0 standard, placing the Acme\Rocket class into src/Acme/Rocket.php; and should really use namespace in new code instead of underscores.
Autoload is commonly set up in test/bootstrap.php (that can later be shared with index.php or other entry points), using:
- __DIR__ as a magic constant pointing to the test/ folder.
- ini_set("include_path") to modify the paths where files would be searched by require_once() (think of the Java class path).
- spl_autoload_register() to define a function or closure to load classes based on their name.
Testing methodology
The team is using Acceptance Test Driven Development, in the double cycle of end-to-end and unit tests described in the GOOS book. In most cases, PHPUnit can be used for both acceptance/end-to-end tests and unit tests: there is no need for Selenium and similar tools if the most abstracted tests focus on HTTP API (while there would be if JavaScript is involved.)
PHPUnit provides the standard xUnit API: test*() methods are executed independently, setUp() and teardown() provide space for fixtures, and assert*() methods verify expectation on the code.
PHPUnit test cases also provides a point of entry with $this->getMock() to generate any kind of Test Double from a class or interface name. There is no need for verify calls: mock expectations are defined before their usage and checked automatically by the framework when appropriate.
phpunit.xml is a configuration file which I advise to setup to enable colors, bootstrap.php to be automatically used and to define the folder containing the test suite.
phpunit executed where phpunit.xml resides will run all the tests. You can also make a selection:
- phpunit --filter testMethodName executes only testMethodName() methods (also with an incomplete name).
- phpunit --group groupName allows you to filter test cases and methods tagged with @group.
- phpunit test/Acme/Rocket/ only executes a subset of tests, contained in the chosen folder.
Libraries
Many libraries for common problems like working with HTTP, SQL, JSON and XML are included in the language: json_encode(), SimpleXML, PDO and the Mongo extension.
Frameworks were not needed for now, but Zend Framework and Symfony are the first places to look if you're not afraid of technical debt.
ORMs are also a commodity, and in case you need to deal with many different entities the Doctrine ORM is my first choice. Also Doctrine ODMs are available for mapping objects into document databases such as CouchDB and MongoDB. | http://css.dzone.com/articles/standard-php-setup | CC-MAIN-2014-41 | refinedweb | 732 | 52.29 |
Introduction Param.
Example Code
Code without using generics:
public class Stack{object[] store; int size; public void Push(object x) {...} public object Pop() {...}}
Boxing and unboxing overhead:.
Stack stack = new Stack();stack.Push(3);int i = (int)stack.Pop(); //unboxing with explicit int casting
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.
No strong Type information at Compile Timeint i = (int)stack.Pop(); //run-time exception will be thrown at this pointThe above code is technically correct and you will not get any compile time error. The problem does not become visible until the code is executed; at that point an InvalidCastException is thrown.
Code with generics.
public class Stack<T>{ // items are of type T, which is kown when you create the objectT[])
Inside the CLR
When you compile Stack<T>, or any other generic type, it compiles down to IL and metadata just like any normal type. The IL and metadata contains additional information that knows there's a type parameter. This means you have the type information at compile time..
To support generics, Microsoft did some changes to CLR, metadata, type-loader,language compilers, IL instructions and so on for the next release of Visual Studio.NET(code named Whidbey).
What you can get with Generics
Generics can make the C# code more efficient, type-safe and maintainable.
Efficiency: Following points states that how performance is boosted.
Safety: Strong type checking at compile time, hence more bugs caught at compile time itself.
Maintainability: Maintainability is achieved with fewer explicit conversions between data types and code with generics improves clarity and expressively.
Conclusion
Generics gives better performance, type safety and clarity to the C# programs. Generics will increase program reliability by adding strong type checking. Learning how to use generics is straightforward, hopefully this article has inspired you to look deeper into how you can use them.
I am Sridhar Aagamuri, MCSD.Net and Working with Wipro Technologies as Technical Architect.
©2015
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/sdhar8po/GenericsInCSharp11152005055344AM/GenericsInCSharp.aspx | CC-MAIN-2015-06 | refinedweb | 344 | 58.89 |
As per the standards every directory will contain one Makefile. So you can
have three Makefiles for this job done if you have three directories.
(d) common
|
|---(f) common.h
|---(f) common.c
|---(f) Makefile --- MAkefile for the common folder.
(d) app
|
|---(f) app.h
|---(f) app.c
|---(f) Makefile
(d) unittest
|
|---(f) unittest.h
|---(f) unittest.c
|---(f) Makefile
(f) Makefile --- invoke all makefiles in the mentioned order.
If you want one Makefile to happen all these done, you can do in that way
also. Here you have to compile the files by providing paths of the files.
order is most impotent.
There are many system management tools. Chef is what we use, it is great
but there is a bit of a learning curve. You may want to look into your OS's
default package manager and distribute packages of your code base.
You need interaction, a way to start a process, and then monitor its output
and be able to pass input to the process..
Python has this, it is called subprocess.Popen. There are many examples of
similar questions and answers here on StackOverflow.
For example:
Running an interactive command from within python
Python - How do I pass a string into subprocess.Popen (using the stdin
argument)?
And many more.
You need to do ./brian. Unix will then look for it in the current
directory. Your current directory may not be in the system path and hence
it is unable to find a command named brian. was able to call some command line applications using NSTask as described
here:
NSTask or equivalent for iPhone
Including the NSTask.h header file from Mac OS X was enough to get this
working on my jailbroken device.
It looks like you are:
on Windows
trying to launch an external program asynchronously
Here is the secret sauce that will allow you to do so:
function async_exec_win($cmd)
{
$wshShell = new COM('WScript.Shell');
$wshShell->Run($cmd, 0, false); // NB: the second argument is
meaningless
// It just has to be an int <= 10
}
This requires the COM class to be available to your PHP instance, you may
need to enable extension=php_com_dotnet.dll in php.ini (since PHP
5.3.15/5.4.5) in order to make it available.
Also note that this will require a full file name of the file you wish to
execute, as the extension search list will not be used outside cmd.exe. So
instead of srcds -console ... you'll want srcds.exe -console ... -
personally I don't l
Use the where command on Windows.
WHERE [/R dir] [/Q] [/F] [/T] pattern
If you do not specify a search directory using /R, it searches the current
directory and in the paths specified by the PATH environment variable.
Here's a sample code that finds the two locations where notepad.exe resides
on Windows.
String searchCmd;
if (System.getProperty("os.name").contains("Windows")) {
searchCmd = "where";
} else { // I'm assuming Linux here
searchCmd = "which";
}
ProcessBuilder procBuilder = new ProcessBuilder(searchCmd, "notepad.exe");
Process process = procBuilder.start();
ArrayList<String> filePaths = new ArrayList<String>();
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
filePaths.add(scanner.nextLine());
}
scanner.close(
From the pyinstaller FAQ:.
In other words, you cannot simply run a command in Linux to build a Windows
executable (or a Mac executable for that matter) like you are trying to do.
The workaround they have provided for Windows (and o
Rename your main function or put another wrapper around it.
If you want your native function to be named as cansend(), your wrapper
function should be something like this:
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT
void
Java_com_aaa_bbb_ccc_cansend( JNIEnv* env, jobject thiz);
#ifdef __cplusplus
}
#endif
Here, com_aaa_bbb_ccc comes from your package name of your java code which
contains public native void cansend();.
For example, if your package name is com.example.test, your function name
will be:
Java_com_example_test_cansend();
phantomjs is completely separate from node:.
CasperJS is built on top of node, so it
There's no single valgrind command to do it, but it's trivial to do in
shell:
#!/bin/zsh
for exe in *(*)
do
valgrind --log-file="${exe}.log" --leak-check=full "${exe}"
done
No, for both licensing and technical reasons, you cannot embed and
redistribute IE10 executables. Doing so would violate Microsoft's
copyright, and it wouldn't work anyway because IE10 does not support a
non-installed "side-by-side" configuration.
The execve will drop all mappings in the kernel, so this technique will not
work. What you can do instead is open a file (as in Vaughn's suggestion)
and pass the descriptor to the child process. Open file descriptors are
unchanged across an exec. Then you can map it in the child.
Alternatively, investigate APIs like shm_open()/shm_unlink() which will
manage a global file mapping such that other processes can use it, not just
a child.
But basically: you have to mmap() in the child, you can't pass anything in
your address space to the child in Unix.
In short no. You cannot have two main functions in one executable.
You could rename the two mains to MethodA and MethodB then decide which to
call based on the arguments you send to main i.e. the argv in
int main(int argc, char** argv)
Since you say you don't want to edit the source code, perhaps you are
better off writing a script that calls the correct exe depending on the
parameters.
Have it generate a file with the following contents:
#!/bin/sh
node myscript.js "$@"
And then have it mark the file executable (chmod +x myscript).
Each argument you pass to the command should be a separate String element.
So you command array should look more like...
String[] a = new String[] {
"C:path hat hasspacesplink",
"-arg1",
"foo",
"-arg2",
"bar",
"path/on/remote/machine/iperf -arg3 hello -arg4 world"};
Each element will now appear as a individual element in the programs args
variable
I would also, greatly, encourage you to use ProcessBuilder instead, as it
is easier to configure and doesn't require you to wrap some commands in
""...""
Make sure that the perl script itself is set to be executable. You can do
this with a command like this:
chmod +x /Users/Wes/Desktop/Perl_dir/phylo.pl
And then make sure the first line of the script has an appropriate
"hash-bang" line to invoke perl, something like:
#!/usr/bin/perl -w
With both of those in place, I think your scripts should start working.
(Note: The -w isn't strictly necessary, and may cause warnings in your
script. I do suggest it, though, for developing new perl code, since it
encourages a certain brand of perl hygiene.)
CppUnit is a framework for automated unit testing, not automated system
testing.
System testing is just what its name implies. It's all about testing all
the code modules together as a complete system from a user's point of view.
Automated system testing is when you exercise your entire system from a
test harness, providing it with specific user inputs and testing that the
behaviors and outputs function as expected.
Unit testing is all about testing the smallest possible unit of code from a
code point of view, providing it with entry conditions and asserting the
exit conditions are properly met. At its best, one unit test should
exercise one path through a method on a public interface of a class, free
of external dependencies on hard-to-provide resources like databases or
services. U
If you're being rated as suspicious, the quickest way to resolve it would
probably be to submit a white listing request.
Since the software has been deemed suspicious by a heuristic/reputation
based system, there's no guarantee that signing it will automatically white
list it (although it will most likely raise the possibility)
After thinking why the hell would you want to do this?, I just surprised
myself and found what may actually be a solution!
The Cocotron
The Cocotron is an open source project which aims to implement a
cross-platform Objective-C API similar to that described by Apple Inc.'s
Cocoa documentation. This includes the AppKit, Foundation, Objective-C
runtime and support APIs such as CoreGraphics and CoreFoundation.
Also see this blog post: Win-win with Cocotron and Xcode 4.3 — code for
Mac, build for Windows (Part 1)
Although the last entry on the Cocotron site was from 2010 - so it may or
may not still be alive
Current versions of Cygwin gcc do not support -mno-cygwin anymore because
it never really worked correctly. Instead, you should use a proper
cross-compiler, which is provided by the mingw64-i686-gcc packages, then
run ./configure --host=i686-w64-mingw32.
I have this problem as well. While seemingly intuitive, it doesn't appear
to work for me at all. However, looking at other gems on GitHub, it looks
like you can just specify the gem itself and the default /bin directory
will be used
spec.executables = ['MyGem']
EDIT: Looking back at this, kevinrivers' answer is also valid. FYI Bundler
does assume you're using git, so both answers work (amongst many more - in
fact, after I posted this answer I soon dug more into how gemspecs work,
especially related to the inclusion of files, and I wrote a lot about it,
if you're interested -).
You need to edit the Build Settings of the project target.
Make sure that the IOS deployment target is over 4.3 or OSX is over 10.7.
Generate Position-Dependent Code is set to "NO", and Don't Create Position
Independent Executables is also "NO"
If this doesn't fix you problem it might be that libraries that you have
included in your project don't have these setting. What is the correct
Xcode setting for Position Independent Executables might help.
Yes you could easily use a decompiler to extract those kinds of constants,
especially strings (since they require a larger chunk of memory). This will
even work in machine-code binaries and is even easier for VM-languages like
Java and C#.
If you need to keep something secret in there you will need to go great
lengths. Simply encrypting the string for example would add a layer of
security, but for someone who knows what she does this won't be a big
barrier. For example scanning the the file for places with uncommon entropy
is likely to reveal the key which was used for encryption. There are even
systems which encode secrets by altering the used low-level commands in the
binary. Those tools replace certain combinations of commands with other
equivalent commands. But even thous systems are
Runtime tr = Runtime.getRuntime();
try {
Process p = tr.exec("c:\a.bat");
InputStream err = p.getErrorStream();
InputStream std = p.getInputStream();
//TODO here we go!
} catch (IOException e) {
e.printStackTrace();
}
You can do it with nginx and fcgi. The simplest way to do this is, by using
spawn-fcgi -
First you will need to setup your nginx.conf. Add the following inside the
server {} block -
location /index {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
location /contact {
fastcgi_pass 127.0.0.1:9001;
include fastcgi_params;
}
location /view_post {
fastcgi_pass 127.0.0.1:9002;
include fastcgi_params;
}
Restart nginx and then run your apps listening same ports as declared in
the nginx.conf.
Assuming your programs are in ~/bin/ folder -
~ $ cd bin
~/bin $ spawn-fcgi -p 9000 ./index
~/bin $ spawn-fcgi -p 9001 ./contact
~/bin $ spawn-fcgi -p 9002 ./view_post
Now the requests to localhost/index will forward to your index program and
its output will go back to ngi
I found a solution in Intel official articles.)
Use virtualenv
virtualenv -p python2.7 env
source env/bin/activate
python --version # prints «Python 2.7.3»
pip install pyopencv
If you need support of 2.4 (or other version), just create new environment..
Loop over filenames.
input_filenames = ['a.sam', 'b.sam', 'c.sam']
output_filenames = ['aout.sam', 'bout.sam', 'cout.sam']
for infn, outfn in zip(input_filenames, output_filenames):
out = open('/home/directory/{}'.format(outfn), 'w')
infile = open('/home/directory/{}'.format(infn), 'r')
...
UPDATE
Following code generate output_filenames from given input_filenames.
import os
def get_output_filename(fn):
filename, ext = os.path.splitext(fn)
return filename + 'out' + ext
input_filenames = ['a.sam', 'b.sam', 'c.sam'] # or glob.glob('*.sam')
output_filenames = map(get_output_filename, input_filenames)
You probably should have looked through the related questions before
posting. This seems to be a valid way to get class C to inherit from
classes A and B:
class A(object):
# stuff for A goes here
class B(object):
# stuff for B goes here
class C(A, B):
# stuff for C should come from A and B.
As Dek points out in the comment, the Python documentation already has a
page about this.
Actually I fixed the problem by reinstalling MySQLdb following the step
found here. I'm not sure how well this will work for additional modules
though
You'll need to swap the @decorator1 and @decorator2 lines if you want
decorator2 to check up on whatever decorator1 returned:
@decorator2
@decorator1
def my_method(self, request, *args, **kwargs):
return u'The result that must be returned if all the checks performed
by the decorator succeed'
Now decorator2 will wrap whatever method decorator1 returned, and you can
thus inspect what that method returns.
def decorator2(method_to_decorate):
@wraps(method_to_decorate)
def wrapper2(self, request, *args, **kwargs):
result = method_to_decorate(self, request, *args, **kwargs)
if isinstance(result, tuple) and result and result[0] == 'failure':
# decorator1 returned a failure
return result
else:
# decorator1 passed through
Assuming all the CSV files are of the same length and contain the same
first column in the same order, something like this might work for you:
list_of_files = ['csv1.csv', 'csv2.csv', 'csv3.csv']
# Use the first file as a template
with open(list_of_files[0], 'r') as f:
output_text = [line.strip() for line in f]
# Append the values to the end of the lines
for fn in list_of_files[1:]:
with open(fn, 'r') as f:
for i, line in enumerate(f):
key, value = line.strip().split(",")
output_text[i] += "," + value
# Dump result to new csv
with open("result.csv", 'w') as f:
f.write("
".join(output_text))
what minimal changes can we make to the C++ code to make it behave like
the Python code?
Short answer: You can't. B2 has no idea that it's going to form part of a
sub-class that also has B1 as super-class.
Long answer: You can, if you use some grotty downcasting (essentially
casting this to a D*). But it's probably not a good idea, as *this is not
necessarily a D.
The good news is that you don't need to do anything extra for thread
safety, and you either need nothing extra or something almost trivial for
clean shutdown. I'll get to the details later.
The bad news is that your code has a serious problem even before you get to
that point: fileLogger and consoleLogger are the same object. From the
documentation for getLogger():
Return a logger with the specified name or, if no name is specified,
return a logger which is the root logger of the hierarchy.
So, you're getting the root logger and storing it as fileLogger, and then
you're getting the root logger and storing it as consoleLogger. So, in
LoggingInit, you initialize fileLogger, then re-initialize the same object
under a different name with different values.
You can add multiple handlers
Use itertools.chain.from_iterable():
from itertools import chain
for elem in chain.from_iterable(nested_list):
Demo:
>>> from itertools import chain
>>> nested_list = [['a', 'b'], ['c', 'd']]
>>> for elem in chain.from_iterable(nested_list):
... print elem,
...
a b c d
You need to add y to an existing list, using list.extend():
words = []
while True:
y = input()
if y == "###":
break
y = y.lower()
y = y.split()
words.extend(y)
Now words is a list containing all the words of the lines your user
entered.
Demo:
>>> words = []
>>> while True:
... y = input()
... if y == "###":
... break
... y = y.lower()
... y = y.split()
... words.extend(y)
...
Here is a line like sparkling wine
Line up now behind the cow
###
>>> print(words)
['here', 'is', 'a', 'line', 'like', 'sparkling', 'wine', 'line', 'up',
'now', 'behind', 'the', 'cow'] | http://www.w3hello.com/questions/Why-do-I-have-multiple-python-executables- | CC-MAIN-2018-17 | refinedweb | 2,706 | 64.81 |
races war a
@reallhas
Damignr T i Beach Editing~Lester Smith h j w t CooAmtoriAndriaHayday
Interior Artttmi Randy Post, D e e Barnett Graphic &@I Dee Bamett Graphh coordinrtori Sarah F e w
Art Coordiuatori Peggy Cooper Electronic Prepmu Godhatori Tm Coumbe
'Qpgnphyr Nancy J. Kerkina cllrrosr.phy~John Knecht Proofmaderr Janic Wella
Pmductionr Paul Hanchette Playteathg~The guyl at Concentric, Hunicon. and WarCon,
Special T h d u to:Wolfgw Baur, Bruce Heard, Jeff Grubb,Bill Slavicnek, John Rateli, Rich Baker, Sue Weinkin, Biyc
: Nermith, Andria Hayday, Tim Brown, William W. Connorr, David Groan,Me.rahd1 Simpion, David Wise, David "Zeb"
Cook,Skip Willirmc, Julia Mutin, Colin McComb, Karen Boomgarden, Thomaa Reid, Patty Corbett, Dave Sutherhnd,
John Cereao,Brad Lavendar, Ky Hslcall, and Phi Mu Alpha Sinfonia.
Baaed in part on the "PrincenaArk"aerien by Bruce Heard,
and parrially derived from the work of Merle and Jackie Rumunnen
TSR Inc.
Pw.Ou. hO.m76n6
WI 6.3147
unitdsuo. O l M O
:
Induction 3 Immortal Spheres 106
The Five Sphere8 of the 106
chapter 11P h p r Chmctem 4 64
Character Racer Dueling with Firearms 106
Y4 Inheritom: Multiple Legacier 67 107
Strndard Character Rpocr ‘6 110
111
NewCharacterRacu I 4 7 112
h d n ga Character 7 112
&Generating ~biliv 1 113
7
ChoolingaCh.mct;CL 7
Choosing a Character Kit 8
Determining Legacies 9 Us+ Legaciei 68 Dueling with Swords 113
Determining Lmguages 68 Wildlife 113
DeterminingAnnor CLU 9 Magic and the Legaciei 68 Monstcm and Legpciea 113
11 k&s in the Campaign 60 Sample Adventures 114
Legacy Dewriptiom 114
haigning Other Characteriatice 11 fhpter4iPro~ Lord Flame 116
80 war P u g
chapter2iChW4CWKit. 12
12 Weapon Proficiencies 80 The ARlicted 116
Chapter Overview Natural Attack Forma 80 The Flying Bulette 117
Proficiencie. and Secondmy 13 Special Attack Forma 118
Skill8 81 Tower Ruins
S p e d Note The Inheritor 13 Weaponlers Attack. 82
Kit Deecriptions 13 Weapon Specialidon 83 A p p d h M C S h w u
Kit.for Multiple CLUci 13 Noqweapon Proficienciei 83 Aronu 120
Warrior Kite 21 Pmficicnqy dew rip ti^^ 84 Lupin 120
W d Kit. 29 122
124
Prieit Kite 33 ch.pur61 Tortle 126
Thief Kite 90 Feliquine 1%
Bud Kits 36 Eq*t.rd- 90
37 special Material8
42
Kite by Culture and Race Stone, Bone, and Wood 91 Tablea
Kiu by Nation 42 Ghiteel 91 1.1: RR.rccid.l AAbbiliityi MRsjqrlpukp;emnetnst. 7
Kit.for To&, Gobliinoida and Red Steel 92 1.2: ’ 7
Outride Nations 43 New Equipment 92 1 . 3 : R p c i . l c l s s a . n d ~ L i m i t a 8
43 Availability of Materials 93 1.4: Wiwd Racii Requirement. 8
Using Other Kit. 46 New Weapon8 93 lr6: Thieving Skill Racii
46 Weapon Delcriptiona
switching Kits
PlayingWithout Kits
93 4djsflilutmenu
Natural Weapons 97 1.6: M ~ l t i - c l aC~ombinations 8
ch.prar 33
Tb+curre.adtheLq?4ciw 46 1.7: Averap Hekht and W k h t 11
98 1.8: Age 11
h i c E&& of the Red Curre 46 W611CI.gif ~
speii8
Origins of the Curse 46 98 1.9: Aging EEects 11
2.1: Defender Spell P r o p r i o n 24
The Dragonfell 47 Detection and Identification
The Aranea and the W d h ~ 47 Spell8 98 3.1:lnirLlL.egaciubyRcgi~n 63
Other Divination8 99 3.2: Lekcy Reference Lint 69
Nimmur and the Manscorpions 47 OhpelMa& 100 4.1: Torasta Re8ulta Table
83
The Real Story 48 Remow cwc 100 4.!2?speciplktAstock8perRoud 83
Removingthe Red C w c 49
The Magical Substances 60 Other Spells 100 4.3: Nonwupon Proficiency
60 New Spells 84
Magical Item 100 croupl
Vermeil 102 4.4: Fast-Talking Modifier. 86
Cinnabryl 60 Red SteelArmor:Amtor
Red Steel 61 4.6: Crude Weapon Construction 89
ofC h
crimron &rencc 61 Crimson Euence 103 6.1: Weapon Materials 90
103 6.2: Special ltemi 91
Steel Seed 61 cb.pteX 78 ‘lb
The World 5.3: Weapona Lint 94
Smokepowder 51 104 6.4: Miidle WC~POM 96
Effect. of the Red Curae 62 Other Worldi
104 6.6: Natural Attack Forma 97
Benefits: The Legacies 52 106 7.1: Calendar of Mptara 106
&.:.:. ,
.- .~
&A.
&eating a ' h rcharacta-for a Savage cout ~ U W UinMthis cam&. Armen M d e d unbwnam. All of
-theee ~ - de&-, nem~humuu, and
campaign involva come special conli+ratioru. unhumuu fall under the gena$headingbumvw&.
For one thing, berideo the itandard AD&D'
game races, there are oeverd new races that play- The Savage Coast is a racially mixed area; members of
ers can choora from.Then are BO aaqmber of ,: moa raou are frirly conuwn, o r a t iewt known, and have
new &!a to adapt cmhareraifcotelkrqgal sciwei. And, of their own udizationa and -&menta. ABa conoequence,
coune, there we the panted ,, ,
most .peopledo ngt find it c n p r d l y notable to nee a lupin
by& &d Cww,.ThL Cbpter dctpila the
walk down the atmet, though a cayma or gurraah might
PC racer a d a b l q for wtivea ofthe Sav- ,. rabe a few qnbrqwa Msmbsw of other races are conoid-
-gs Cnut (and provides nom regard-., , eredjrut otha,people, BO they w& do not draw any ape-
, ing characten Lorn nearby Ian&). cL1attention,+tive or nyydve.
Tbir ir not to say that the Savage.CO+itio entirely free
from mjudiqe. Indeed, many d t h e m a b wars are related
@Lm*dhp , , to rwid pmjudieea n d r d i 1 u p i n i . dr h t a have bor-
1, Fuat, H)IMdefinitionr are in order. , , d r conilictb ~ h t geanaady W i e .h.zplu, and prranh
The traditional definitionof b d hate them. However, a lupin would not find it unusual to
in gobline urd thir&veii kobold., , . mest c r h t a . w the 4and tbc two might cooperate on
hobpbline epolln, urd ogres. , o n e t b i ,oranotheri &w a p&ticuI.Tmember of a race i
Butthe,$enn hapdmbcen&to treated d + w y on the iedhridurl.
define my intelligent M iwith one Follouspeare briefdeexipthi 0 f . hcharacter races
k d ,two .rmc, and at le& h%o1- "a+available in a RED STEEL'? camp.iel*rChesavailable
thin in the p r e f d definition. to each race are c o ~ r e dudder a Character
C b a " later in this chapter.
In thin accumny, however,
kobdd.,&liw orq, hobgobh, ' Kita M covered brieb
gn&, ogres and their&e mL- under "Choosing '
tivel,.nr s f e d to 88w. aChwaater
Elves, half-elm, hakhga, dwuveo,
and gnomes M refemd to cdec- more com-
t;Velyas&nibm. Other
character races-luph,
Ii$ pndtortlerr-areknoWna.ttar-
Most of the atandud character race8 are av h
Like dwarvea, elven have no culture of th$r owd on the
ilc one from Bel-
imum Number of even if the CompLtc
the sOv.ge Coprt cannot
ape11 progrenaion.
aNew !8 Ewm 1 e ABILITY RaqvI-
There are fournew player chpr.car racesin this clrmp.ignset- StrkCOPlnt\Ni.Cb..
Aranea 3/18 8/18 3/16 12/10 3/18 3/18
t;.B:lupins, r h t a , d e s , and aranea If the DM approves,it Lupin 8/18 3/18 8/18 3/18 3/18 3/18
Rakasta 9/18 8/18 3/18 3/18 3/18 3/18
may also be possibleto play lome lortof goblinoid. Torde 6/18 3/18 6/18 3/18 3/18 3/18
The new races are covered in detail at the end of this
chapter. Kit.pcceptpbls for each r a n am given in Chaptar 2
of this book.
Tabla 131R A c I A L A w L n Y ~
Aranea -2 Str, +2 a x , -2 Con, +2 Int
Aranea Lupin +I DSetrx,,+-12Cwonis, -1 Int, -1 Wis
Aranea are arachnid mages thought by most to be extinct. Fhkasta +2
Those who still exist are usually found in Herath, as Tortle -2 Dex, +1 Con, +1Wis
explained in Chapter 6 of the LMa,btbe S Q W&w~t book.
Goblinoid. every character gains a magical Legacy due to the Red
There are no kobolds native to the Savage Coast, but if the Cune. Kita an covered briefly later in thin chapter a+ w
DM allows, p b h , ora,hobgoblinr, gnolls, and ogrrs can be fully detailed in Chapter 2. See Chapter 3 for ruler a b u t
p k p d as PC.,usingthe rulesinthe Can& &wk qfHunww&. the Red Curae and Legacies.
However,memben of those races should use the kits T o m -
mended for them in Chapter 2 of this book, and the cultures Though detailn may vaxy according to the wirhcp of the
d d b e d in Chapter 6 of the L n & .ft& Sa- Coadt book.
DM, when creating a character. ability ncorea nhould be
hPLu
determined fimt, then character race, c h . and kit. Next,
Lupin. are furred humanoidn with doglike heads. the character’r Legacy rhould be determined, followed by
Descended from a nomadic culture, they now make up tha other detailn such as hit pointn and Armor C h i , weapon
vmt majority of the population of Renardy. There are also and nonwcapon pro&iencier, equipment, .ndbackpud.
rome lupine in Herath and the Savage Baronies, but elre-
where they are rare. tmCMhpaoraltcetdetmoathbeosteadvafogreoctohesrrtc. usiampprbig.carc.*lxteLthyecdaaudnaabrer
Lupin. have a culture similar to that of the Savage Bar- with the rula ofthe alternate ~ening.When tbc charmten
oniea. and there are a wide range of chasacter claaser and rrrivc on the Savage tout, theywill iufkfmmthe e f h a d
kita available to them.
thCRedCune*~nutrsrddgn:8d3UbpdEorddS.
R.LL.tp Generakipe&& &om8
&taw feline humanoids. Bellayne is populated m t l y
by rakaata, split between the settled town dwellers and the Nonhuman player charactern must meet certain minimum
nomads who carry on the rakasta’s ancient traditions.
Rakasta culture is unique, somewhat myntical, and concerned and maximum requirementsfor their abilityocorw. Far new
primarily with battle and honor. Some members of the race PC racei described in thin campaign iettiw,racial mini-
mums and maximumsan li~din Table 1.1: K iAbility
dwellin Herath, but the creature. are rare in other statu.
Requiaememts. Next. characten of them racen receive
Tonls. mandatory ability adjuitmenti, LI identified in Table 13:
Tortlei are bipedal turtlir, about the same height an Racial Abilig Mjuatmenta. Note that these adjwtmeatr
humans. They have inhabited the lands of the Savage C w t
for thouaanda ofyem.But tordes have no red government, may rake a .coreto 19, or lowerit to2, u SXpLMed ap a p
living in d l family dwellings, often within the borden of
nome other race’s state. The creatures are generally peace- 20 of the Play& Hadbook.
ful. scholarly fsrmen, but will defend their hornel.
C l m o s i q a CQlaracte~Claw
CrmkilrJIg a CLmact,r
All standud character &MI f m n the PLycrSHadbo~kare
Creating a character for the S a q e Coast is bsnicolly like available in a Savage Cout campaign. There ue no ckangu
making a character for any setting-as outlined in the to baric character clwea, other than some limitr found in
PLayeri Hadbook-but with more options for character race. kits in Chapter 2 of this book. No new character h a are
In addition, the use of kits is strongly encouraged to help given here, although Chapter 7 holdn a few guidelinw For
define the character’s cultural background, and almost creatingor adaptingspecipltyprieat..
Members of race8 prewnted here cannot advance in
every class. and they have limited advancement in moat
chases. Class and level l i i h are detailed in Table 1.3. Note
that individuah of some races are very limited in the choim
of kita available to them.
Lupin -13 12 -16 13 13 9
-16 16
Rnkuto - -11 9 2 13 13 U
. u* i 11
Tortle 12 9 9
r' ;
*A number indicate8the maximum level attainable by a given race in a given c h i ; "U" indicatei unliited dvancement; and
no number or letter means a character of that race cannot advance in that class.
**Thin entry coveri aU wizard hi;mme races are relaicted from certain wizard clasncn. For a lint of wiznrd clastei avail.
able to each race,see Table 1.4. Level limiti on the inme for dl wizards of the inme race, r e g d e w of ipecific clue.
Tabh 1.61 TH~~VINSKGRL RACIAL h J U S T h Z A W ni&h D8ta.a aimb
€i&open PI h Wdi Read
Raw SM -Noha +6%'
Aranea P h Lock. -RmmmTrapi Silently -6% LulgUqm
Lupin -+6% +20%** +6% +lo%
RakMca -- ----- - -+6% -+lo% -2Mt
Tortle +6% -+6%
+6% -6%
-6%
*Anaranea in dcmiapider form has a ~ 2 0 %bonui; one in arachnid form haa a 60% bonui.
**Thin ia the lupin's bonui at 1st level; the bonus increases by 2% per level thereafter.
t A tortle cannot lift his or her body weight with arms done.
Rncei d d u l in the Phytri Hanaboo&and the DUVGEON T h e pdoniciat can be uied in a RED STEEL c a m p i p if
MASTER. GI& have the uiual c h i and level reitrictioni, the DM to dcnirer. However, a peioniciit cannot take the
Inheritor kit and grin more than one Legacy. A character
with a few exceptions detailed under "Standard Character with a pnionic wild talent doci not gain an initid Lypcy (in
h e n , "above. The optional rule for exceeding level limiu eisence, the wild talent is the Legacy), but can take the
(ai explained in Chapter 2 of the DUNGEONMASTER Inheritor kit and later gain Legaciee.
Cui&) can be uied if deiired, but lupini and rakaita can Humani, rakaata, lupinr, and iome aranea CUI be dual-
never h e to p a t c r than 13thlevel druid.. c l u e chuacten; dud cluioptiona follow itandud pide-
lines. All dowed multi-cluecombrntiona fixnew mea are
Member8 of the new racei are nsmcted to certain wizard liated in Table 1.6. Race8 able to have multi-clau magee can
clruiea. The wizard entry on Table 1.3is general; d e d i on ala0 have multi-clan combinations with all other wizard
wizard h i e s available to each race are found in Table 1.4.
Elementdiiu and wild rnpgei are deicribed in the Tonu of clunea available to that race. For exnmde, an ucmea could
44
Magic, all other8 in the Phycri Handbook and Tbe Complete be a fightedlranimuter.
W d jHandbook. 6.
AU new character race8 deicribed in thii book have iome CLmsheg a almacker Kit
memberi who are r o p e i . However, iome are more iuited M Character kitr, mole-playiq tooh d d e d in Chapter 2, help
the pmfeiiion than aheri. Table 1.6 given the thieving ikill
adjwrmenu for the racer deicribed here. These adjuatmenti defmc characterr. Kib on based on the culturea in the area,
are dm applied to ranger and bard akilli of the name nunee. and reflect certain itandardi and beliefs found there. Note
m e 1.41WIwao RACIALR~QmraMEms that, ultimately, the culture a character ia raieed in in more
impartant than the character's race. Thus,if an infant tortle
Aranea Any. were for tome reason adopted by lupin pepunta, the tortle
might become a Local Hem fighter. Such initanca are rue,
Lupin Mage, diviner, abjurer, invoker, necromancer. however, and iomc kit8 are very reitrictive about their
Rakasta %e. conjurer,enchanter, illusionist,transmuter.
Tortle M a p , abjurer, conjurer,diviner, water dementdint. memberships. For example, the Skald iB very important to
Tdh 1.61MVLTI-CLASS-OM the culture of Eusdria, and it ir unlikely that an EutdriPn
Skald would teach the rkill to an oubider, whether the out-
Ac.IM. Tor&
Ma&Fighter Fightei/Cleric sider was a lupin, a tortle, or a human from the Saw Bar-
%/Cleric
MpgeiPnionicist onies. Limita are more fylly defined in Chapter 2 and in the
hi%qftbe Savage&wt book.
Magemhief
Since nome charactem are so reitricted in their kit choice, characten areexceptionel, having learned the Common Ian-
multi-class characters in a RED STEEL campaign are gurrge from a paning trader or m e other wch trawler, and
dowed to chooae a ungle kit. Theie selectionsare detailed it allows player character8tu communicate euily with one
another, and with moat other peopk they encounter. while
in Chapter 2 ofthin book,and in the cultural chapterr. playing a character who docn not know Common can be
W m i d n g Legacies intereet;rs for awhile, it noon geta old if other p h p r chuac-
ten conltultly haveto translate hr the individud.
Almont every character native to the cursed land. ntarts
with one Legacy, a magicd, spell-liepower. Thole charac- Thia should not prevent the DM hom occuiondly hav-
ters who choose the Inheritor kit (see Chapter 2) start the
game with two Legaciei, and they gain more as they ing the plqyer charactm meet a group of NPCl who do not
advance in level. Initial LegPcien are determined by a char- npeak Common. If they do, there may be only one or two
acter's homeland, p1 explained in Chapter 3 of thin book. PCS able to communicate r e d $ or talking might requiro
magidor other special means.
+Charactera not native to the Savage Coait will gain a
ThC Common tongue is u d by a +ty ofthe peopb in
Legacy after spending neverd in a curaed nrea. Again, rhc citpstaten, the S w a p Baronice, Robrenn, Eundiia,
the p m e u is detailed in Chapter 3.
Ruyrct),and Herath; it in known by tradm ad tradere in
Aranea do not receive an initid Legacy,but
southern Hule and the northern d e m e n t i of Yadom, an
well M unong t d e a and in Mayne. The other peoplea of the language of d w w e a , ia known and ipoken by a few
the Savage 6 u t and a u r r o u n h areas .el& speah Com- dw- in the mountain8 of Erudria. Hin,Sl.0 c&d L.lor,
the L d but forgotten a the Srv-
mon. Even in the MUwhere the Common tongue iwidcly knyseofthe -,
una&the wmmon folk oEten ape& an& Lngru(*. age Cout. E h k h i.spoken by a fm 0 t h elves, 4 y in
The I d h- hutpages ofthe Savage Coutincludethe Robrenn. and in common among Torre6n's upper cluaes.
following: Slyich (which ia &oat the u m e u the Tral- The ahpzakn have their own language, called S h a d ; it i
adaran t o n p e -ken &where in the world), w d by the nearly identical to the Malpheggi language used by the
[email protected] city-ntata V&, p k e n by commonem of more civilized l i d folk in the reat of the world. Bodo the
Vilaverde and Texeira.: Espr, uaed by moat p r u h and the cqymp~epmk their own d&a nf SbPwI.
One proficiency .lot apent on Shazak would enrbloachar-
people in the othw Savage b n i u : b,u d acter tospeakone dialout ha+ and undemand the hria
of dl three ddecta, while two dots would dow complete
by &oat everyone in Robrenn: and Euadrian fluencyindl three.
(similar to the Antalian language used in other
pub ofthe world). spoken by dl + There are SLO three rdated~bIinoi&ImgmpwY&
neighboring lands of Hule and Yavdlom hav gablinoid race. of the Ymak
their own Ianpmgea, Hulirn and Yavi.
The lupiaa of Renardy have two native eppes; Yaiug. T o k e n bythe
Lnguseea.RerurdoL (similar to the Glm-
&tongue S y k . ud rrlotedw Cam- orca of the Dark J u n g k ; and
YUq U l d by th6 (leMinoid.Who
mon, Enpa, and Vetdan) ia t live along tbc Coat i d P .
spoken by all but;#hc Each of the.c.baa a 60%
clasaes in Renudy. Th common& wiah each of
1 &tother two, Again, if the
DMh.ach.nct.rcan
learn dl three langupges by
spending just two profi-
ciency slots.'
," local^
d the Sawse Coaak are
ILkutayne,.uaed.in Bel-
..4ynsHer&& the tongue
,,:oHfe r d ; T d e , tho bntk
iu#uqe;..and Riail, J i b ,
a d Nirnmurian,,uaed o&
.the Om'l Hud Peniraula.
, a a ,
' ,Aifor ~dritten,lslrgug
I the Thyrtian (Common)
rr;pt ithe.nN%t~papulrolr
the Savrge 6 u t . It i s a d
for Common, E.pai~Ve&,
Eudtim, and moat idem&-
.-I Idu1i.n and'Yawihave
tkci,owasariph, Mb s H m t h i
Tbed6Lng\ugck&h
glyph. I d &,the shedLn.
e has a ay1hb-yusedby a h d a , -me
gumrh~NinnaurLn*Lrl.o
don,and Common, ao aomeone who ape& 0ns.pmeri, of 'icyl- RakPrtayne written Ianguee u oompomcdof
those thm lanpagea &n understandabout a qua& OF*, about 3,OOWeogr~it m uud in Wayne, and by the nn
literate inhibifant of the Ypzak Steppea who u l a i t to wria
iomeone says in Rendoiq. w;Yszpks.
Demihuman I a n y y e e are aeldom used along &e'&. Lupin. Jibar, Ypzug, and b a r e oonfl.yYiauplorkse.nM ~ Y h r ~
thqy have no witten form.Speak-
Because the demihumd races are 80 fully i n t e g r d into the inclination to d t e ; whaa they do, they UIC the R.lur-
other cultures of the tagion,theii racial tongues are .dcon- tayne acript.
aidered native lurguages. Canaequently,demihumuu $lust
spend a proficiency slot to learn their racial tongue. k a r ,
more on an order with barding for horsea. If a ck;Iirctc;'.
armor prwidclpmtcction leu thanor equaltothe character;
Ti r ~ t u r aAl rmor C h s , the individual m e h i a bonau of I
point of Annor C l u a . Thus,ouppoaeattordc,wit$& AC
3, whhes to wear leather armor.The standard Armor C t u a
for leather armor ia AC 8, worie than what the character
d u o m e & have. lowearinglcatherarmorgivemthe tar-
de AC 2: On the other hand, if the character weam armor R.E. stuthy* *"
that provides baar protection than normal,the armori rat-
ing ii used. For exunple, a to& wearing full plate armor Annea* B.le . v a
LypiIl
(specially made -of course) has m AC 1 (or bet#-, if the 16 4d4
e
chnct.rhunru,bcmuKs~Datuigr.nd/or~). 16 ld6 "
16 ld4
Inw-, it i diIficult to find -or to Fb ne&- 20 2 d 4
nSauvnagcebcuo.cutte.nW: htihletipt rimobdilfefmicuilst not so pronounced on the * Ah araneamay need to be "wntto live with
to find
cb;lmail madefor m e r a faster niaturationrate than t
.a d u d (bsuuie luther m o r weigh leu,i leu upen- latat.
8ilfuudpnwidmtheumepmtectumt o t h e s ~ ) < i t M n o t ** Though tortlea are capable of living
difficult to find &in mail made for a rakasta, or +te mail
mi& have u n d few ofthem .ctu, p. llydo. '
nudefpr a lupda W,Eh.naatr +,
at leut whenawqyfmsn theirbomclpndr. ormi& have ape-
cial requirement8 because of their Le&ea. In addition,
umoru.lmathyamdetooodcr.nywry.Mortummra
are able and willingto nuLC m& h p c d armwm hel-
mets, and often have lome needed piwee around, allowing
~ t o q ~ u u p n anbapbpmprktc auitofaru4oc.
Like molt other PC ram, lupini and r h t a have a hK
Annor C l ~ 1r0. h o e &mor c l u a for tortlw is 3, u&.p
they are pulled entirely into their ah&. in which.^ they
have an AC 1.Annea are AC 7 inwachnid form; &embe
rhey have the Armor Clasa of the race they, are
r ~' . h t a . . , , , ; , , :
..LZ yj .
ill
c,. CEWTEJkTwO ./ j , .
-
The use of kite is highly recommended for the Sav- area without a kit, the player can choose to take a Savage
age Coast setting. A kit is a role-playing tool, a set h t kit, subjectto any restrictionslisted, ofcoauae.
of culturalno& and minor abilities and reatric-
tionu uaed to further define a character. It is used This chapter contains deucriptionnof the Savage Coast kite.
in addition to a normal character class, and should Whilt many of the kits presented here an new,others are
adapted from other sourceu, orrepeated here in brief for the
be chosen after c h s and race. sake of convenience.
Kite are often restricted according to culture
and race. Some kite are so important to a pa&- The kit descriptiona are divided by class. First listed are
&combinetion of race and clans that k h a&& to rn&& c k (Inheritor, Local Hem, Noble,
they are alwaya used with it, even ifa and Swashbuckler). Following this arc the warrior kit4
characteris actually rnulti-ched. (Beast Rider, Defender, Gaucho, Honorbound, and Myr-
Dual-class chPractcrsalaochooaeakit midon), then w i r a d k i t d (Militant, Mystic, and Wokan),
when be& a career, and often
keep it even afterswitchingc h e s (nee with p r k t A& next (Fighting Monk, Shaman, Wer Priest,
“Switching Kite”later in thin chapter).
Because the RED STEELcam- and Webmaster), followed by tbkfkitd (Bandit and Scout),
p e n can be attached to a larger and &ally bum?k t b (Herald, Skald, and Trader).
world, the DM might also make kits
and classes from that world available The psionicist &, while allowable,is not an intewal part
of the e=tting,no there are no pionicist kita Ita.But the fol-
to Savage Coast cultures. When lowing kita have nom for ~llewith psionic charactrrs: h d
doing so, the DM should either Hero and Noble, for multiplecIac.aw.; Militant, Myltic, .ml
make sure the kits and classes fit Wokan for wizards; and FightingMonk for priem.
There sn no ranpr or paladin
the cultures, or adapt the local cul- kite presented here, and
ture to reflectthe kit and class. In only one druid kit
(the W e b m -
some cases, players might wish to ter), thowh
several of
import characters from other areas
of the world: such characters
should use the restrictions of
with tho52 b. ent to a char, h c h M available dhoo1s.d magic or &wing
Following the kit listingo are notes recommeading p6rtic- abilities. Any ruch chbngea, baburra, or reatridion8 are
I iin hi.e&y.
SX kits for .paific cultures and races, drtpilr 6n abandan- I.
ing and changing kit$, and commenh cbncerningune of the Wbepon Profidwciwi Some kit* *quire pMicdar
weapbn proficienc&s.W h h r&hed to'& Lwe+n pro-
setting without kits. ficiency, the character mwt dil,npnd the &uptiate num-
ber of proficiency slotr, unieir the kit s&fic.lly Itatel
o t h e h . Thb section dao liru waipon prefenncd, Forthe
chwacter, aa we11 a8 weaponeinitirlty forbidden tu r h ~ k i t
The optionalproficiency aystem, premted in Chapter 6 of
the Player2 Hadbook, is (~tronglyrecommended €orthe Sav- (those unavailable to a Int-level chapactat of t&r rype).
age Coast. Like kita, the proficiencyWtem h e l p define a Some hmay receive bonub proficiency dot*foAveq6noi
chbacter'u cultural background; many kits also offer bonua th+uaredetailedhere rho.
I,
proficiencien. DMs who do not une the proficiencysystem Nonnsrpon M c i . s c & n This sectiarr4kts skills that
can uae the informationin the kita as a guidelinefor deter- develop the role of the kit. Included (B. above) are bonus,
m i n i .ccondsry skills. required, recommended, and forbidden proficienci-.
-I Some sipen oflcharactets.ninelhad'tb u n
certain typh of equipment. ?hi. section c h n prekrencn
and reltrictiona regarding artnor and ai.ceflunatta Cqrcip.
The Inheritor is a particularly important and potentially merit. Soma kw gain certain quipnmrwi&&t ctwt.
quite powerful kit that makes use of the Legacier of the Red S p a W B&dita Moat kih have some b & t dwt in net
Curre. The kit in available to most races and CIMUKI. and is available to o:her charaitem. This can be anything #+om
unique to the cuned lands of the Savage Coast. In many speci.l ri&a in certain places, to an ununual #bile, to a
wap, the Inheritor kit is pivotal to the campaign, becauseit beneficial reaction from othsn.
illwtrates how somepeople have reacted to the Red Cune, spai.l- Jmt M ma$Uta have wma sp&I
and seek to do romething about it. Even ifyour campaign benefit, nYOIt a160 have oome .p&d dimdvantqe. T h n e
doer not use kiti, the Inheritor ideals should newt M the include such things p. a~ a&voru% &on EromNPC. or
basis for a region-wide MC~W. particalar matomser habits m e m bof &kitmu* f o l k .
Wealth O p t i e m r Some kih pwvide thslrmepbem
more money than nmmd for members &die same chiMcarr
class, while others might be mtrieted hnMHin# with
Erch kit begins with a short overvirw, explaininghow the m y m ~ a t d l .
kit reflecta in cultural baclrground and how it in used in the
campaign. Other sections are B. follows.
C h a c m r C h i Many kits are open to more than one
clur; the classes permbible are listed here. There are &e kits a d a b l e t o e d e r u y of e t u r even
h and Nltionrltkr Not all kite are available to all croising over groups of character dasus. Follou6hg is an
races, while some are required for certain combinationa of overviewof these kitw
race and dpu,and 0th- are penniuible only for particular Inberitord have ret themsdves the tank of fishtise
natiwlitiea. In ganeral, kite are more a function of culture against the Red Ourn. T6 do so, they le- howto bo&
than race, ao racial restrictions often can be ignored for
trol the Legack it provides, gdhing more than the ai-
charactarc ofa proucribed race who have been raised in the gle Legacy that 6thera acquire. Inheritors can be
kit's culture. But n m e kit. are ao restrictive that their fighterr, my., chrica, thieve&,or bad#. The InhUitod
secreta are taught oniy to actual nativen, never to these
-kit is unique to the Savage Cowt settibg. Sekauseofits
adopted into the culture. This entry lists dl such availabili-
npecial nature and importurea t~ the netting, tke l i k d -
tien and restrictions.
tor's deacriptkn in rather extenbive, and longer thaw
Rquinmontnr Any other requiremento for membenhip that of any other kit.
in the kit are listed here, including rocial clasn, gender,
alignment, and abilityscorea. Ability n c w requiremanh, if h a 1H e m are membra of the tower Am and u a d y
any, are in addition to tho= for the character's chosen c l ~ ~ . lire in rural they am h e w sfths'local populace.
Local He- can belonp to any char&ter clus, but are
h 1 e 1 This section d e d b e s how a chpracter of the given rarely psionicmt., +BI w i d , wikl w s , or
kit tendo to act in a camp+, indudins hbw chu.ctnr of cialty priertn. (This kit taken *he p l w o f t h e Pearant,
different races vary in their treatment of the kit. I t also
details any npecial appearance or mannerism npecific to Adventurer, True &rd, Paladin. and Vil+ M i d
memben of the kit.
from other wurcc..)ItL tka$d&&For we if PU 0 t h
CL.. Modificrtionsi Kih often af€ectthe abilities inher-
are inappmprktt for a e h h e r - i t allow themont
flexibility.
N& are membra of the upper c h w and r u l ihi- known u the Neutral Alliance. Individudn rn known M
lien, in t h m nations and ntaten thbt have ruch thing.. Crimson Inheritors. Most belive the Red Curne i.a test
Noble. can belong to any character C I M ~except bud., from the I m m d , both atcrt ofhi&.nB tmt ofpeople's
thievea, necro-ern, and wild q e q . (Th;kit takes we ofpeat power. Good Crinuoa Inheriton believeLey-
the ofthe Noble Warrior,Nobleman F'rient, Patri- ciea ahould be uwd to help othera, while thole of true neu-
cian, ud Noble Pdonicint ppbllhed in other lourcen.) tral alignment believe they must be vied to aupport the
spier are those charactem who infiltrate enemy p u p a to balance of nature, and thow rare crirmon Inheritom of evil
dincover their aecreta. In this retting, the spy kit ir not
limitedto thievw wimub of d typu,"CiIt., buda, bent think the Legaciea are cumen that nhould be uned to
tmt &hem A Crimson Inhentori symbolia- a t o l d
fiehtem, and ranger#can d~ take the Spy kit. cloth, such u b handkerchief, @ urh,or even a cape.
SwbbuckLw are dynamic and witty, oken known for The ordern are opponed in many way^, thaugh diviionn
their daring eocapadea. In thin aetthg, the Swuhbuckler are not ablolute; Crimaon Inhaiton in npecific often dly
kit can be rwdwith warrior, r o p e , or w i w d c h r . with the 0 t h orden, pod ones u n d y with the Ordw OE
the Ruby, evil ones generallywith the Order ofthe &ne.
Inheritor Each order determines a leader, who aolvendisputer
An Inheritor ia a character trained to hamens and control within the order and guide8 it toward it8 go&. The Ruby
the beneficial effectn of the Red Curie, gaining multiple Order elect. their leader, while the Flame Order leader in
Legacier, while ul;ns c i ~ r b r ytlo rtave of€the detrimend
effecta of the Red CUM. h a c of thio, Inheritors Kek to determined by combat. The leader of the crimlon Order i
the h i h u t level cleric ofthe d e r . the^ three I& have
control the rupply of cinnabryl, so they will alwaya have a monthly Condtw in the c a p i d of Bellayne, eaoh often
enoqh for their needs. T h i d~ Idthem to monitor the bringing wutmta or aid-. At the b+u+ of u c h year,
usera of Lcgacien and the trade of red steeecl m a k h Inheri- the leaden gather in a G d conclaur,alongwith any other
tors aomething like aelf-appointed "cune police" (a nick- Inheritor. who want to ba there. The Crimun Order'n
name they have acquired in MM rrs;On~), leader preaidei over Conclaves and Grand Conclwer,
Inheriton can be of q d i p n e n t , but they dl have two
major concernn in common: 1) controlling the trade of which mediate inter-order dinputor, exchange id- and
information, and dLcuu common problem.
cinnabryl and red steel,to emure their availability, and 2) For initance, nuppoae an evil Inheritor thief acquires
m ~ i t o r i n gthe uae of Lcgaciea. to prevent abuae of thone cinnabryl by ntealing amuleh frum the peuanta of a town.A
powerr (and the backlaah that abuse could incite). All
belong to one of three exclunive, wcretive societieswhich good Inheritor fighter from the village taken offenne. The
characten could fieht (after challenges have bccnisrued),
have aprung from three earlier organizationn that have .admight b+ their co& befm ohera. If thoy b e b to
uiated on the Savage cout for decadea. Hiatoricdly, these the w e order, that orderi k.der mediates the +ts ud
p u p a have aligned dong lies of Law veriui Chaos. Offi- makes a decinion. If they are ofdifferent ordm, the Cas-
cially, lean attention in paid to quentions of good vernun clave mediaten the diapute; if the C0nCl.w in far awqy (in
evil-wpeci.lly in the Neutral and Chaotic ump-though
that s-le taker p b at the penond level. time or diatance), a M k C w h u r , con- d a w m-
Lawful Inberltow belong to the Order of the Ruby, the involved member (wudly a cleric) of ewh order, CM be
called to mediate inform+. The mediatork) dpmh-
organisation once known u the Brotherhood of Order or bly decide e s t the thief, who nhould have uked pen&
the Lawful Brotherhood. Individudn arc known u Inheri- aion from the k h t e r bcEonrtuliDg cinmbrylin hluar.
t o r ~of the Ruby, or Ruby Inheritorb &ut of thew Inheri-
torn reek to one day revene the Red Curae. They believe The secretn of gaining multiple Legaciea are jealously
guarded by the ordera. They teulh the procedure only to
that gaining multiple Logaciea will help them more fully
underatand the Red Curne, and that fighting the curae is membera, beginning with their initirtion into an order.
Inluntor~must protect the I- of the ordm;thw who
pouible only by uning Legacier againat it. The symbol of a do not are wnudered reneg&* aad arc p u n t h d by th&
Ruby Inheritor ia a ruby carved with a rune indicating the order. Though Inheritor. with differing philolopbier urd
characteri n t a t w in the organization.The ruby CM be worn d i i n t a lometimu have dkputcl, their behavior t o w d
in jewelry, or nimply &ed. one another t guided by a ret of ~ l a t i me n M by the
Chtk I&ritow bFerleoednogmto, tthheecOb.rodte;cr AofutLhMeeF,loarm,ien, once orders. Prolpective Inheritor. are trained for a fdl year
Fhnda of before being initiated (and r u a h i 1stlevel), to ensurethat
called the mnne
p L c e 4 t b a ~ s L t c F b o o dI ~ ~ a r
Inheritors,or Inheritor. ofthe F h e . These poplo become theey will~adhereuto the ~Code of the Orden; few aecntl ue
Inharitopr brruucit M amad to power they can we fortheir revealedto eeophym beEorr that initiation.
The ordera d~ have .uociate membera, people who are
own d.Tk symbdofa FLmc Meritor Ma s w d e c o - not Inheritors, but who aid Inheriton in their endeavon.
ratedboxththdd.~~t,~udtindcr. Ilaociate membern dao have certain privilop ud mpon-
NeutrnIInkri&ow belong to the Order of Crimaon, once
sibilitiea. They can be uponlored by any Inheritot, but f ~ n
14
be inihted only by a bard or cleric of the order: umciate
membcrship i u n o W until recorded by a cleric. A mem-
ber or auociate member of an order d w a p WOUI or curies
th orderi iymnboolt d,LtphloswJrhtheeqryymmbuonlboepreonlnya. mipion
rcfnt
ce-dw
Beiidcl the aymbol of an order, an Inheritor often ha8 a
p e n d iymbol, or skil, u well; thin in uied to mark the
Inhentori works and posnemioni, and is often worn on a
ahield. on armor or a cape, or Mapeadant. No twopersonal
nymboln are d i e , and the miiuie of a &ilin considered a
great &nt to the owner,and a crime a&mt dl the orden;
bothowner and order neek to punbh offendem.
Inheriton M not common on h e Savage Cout (yet), but
the+ have manberr in svuynrtiw,andmaintainho&
in- &ea, $omepmnmenta are M e to the Inheritom
who w ~ u e n t l oyperate c d y in thoK placen.
Chumter Chair Single-clans fighten, magen. cleria,
thieves, and bards can be Inhsritorn. Othori are excluded
from rcylar memberkip, besPuie their ipecial interasti
interferewith tha +tion and concentration necennary to
control multiple L9e.r;Cn. However, *pyonecan h an u10-
&e member of,an order. It ia porrible, though very rare,
for an Inheritor to become a dual-claw character (but a
d u a l - c h chrrrctcr c m o t become an Isbaitor).
&QM .IdNuiolulltiu: The Inheritor kit is availablein
any land that nu&rs under the Red Cur=. Thin excludes
the ci+y-atata Hule,tbeYaukS t e m , and the Duk Jpn-
gle. %it of Nimmur, J i W , and the Imd.of the W d u r
are free of the cunei of there,only J i b u d ham any native
Inheriton, and h e are raw. Inheriton are $lo rare in the
ltrrd kin natjoni of Gy, S a u k , and Ator. steel fmm itr w l ~ u o pyitbout their Iuuawl+. Tha*
The orden lometimu &e members from autr,ide arwa, of crafting cinnabryl talimmann rlsofdi tom order“.
but they punt be trained for ayear bcfom joiming. Thun, thieven. Though thieven tend to be [email protected]&cJPmpctcnt,
Inheritor can come from Hule (or elnewhere) if the i n d i d -
u d h u lived and trained in a c d u u f o r aywu or more. avoidii notice, Inheritor b a d welcorw plrirlif att~~+.
They UH their abilitk8,toentert&n.othan, w s 5 Sail+
Some races (aranea, ee’aar,,endulu, and W ~ W U )do not information of interest for their orderr., Bwds are
renponaible for circulating infmmuGon wch 4 c9ecLv.
ntart with Legwiea. B0com;Pe Inheritor is the only ww y to members o fthe v u iw,ord.n. A.wc&ith.urdy
m d t e manban, tbmpor~&e i&
tM they can gain aqy ofthe powen. ud who ini-
h q h e n t w An Inheritor can have any nocid C I U , 9b
gender, or alignment. The kit can be tnken only by ht-level tiatian to onnaf the orderb ckr;cm. F&, in n(r/oPl.sy&h-
charactera. Charpten who want to become dud-dum can ,+.out Inheritors bues, thievei and bardadistrihc.poeisan
become Inheritom only when &y begin advwcemant in
and t.lirnua.to membm oftbe
&eir initial CLU. Inheritor nugci study the b g & tb#uclw, Ad:-
Each of Bn Inhefitori ability ncoren must be at l e u t 9. recognize manifestationi at early sta&:Thhoy&
The orderw;ll not accept uyr member who u weaker in aqy potion bue for crimwnunnfa d . t o&I the
area, becauie of the toll exacted by *he Legaciei. A high
Lyu
ciea. Some magei con+ thewelves superior tpo k
W&m and Intelligence are preferable. 1nhuitors.becaune of thrir s H t . r knowledge, but wny
Role: In maqy ways, an Inheritor u an individual with
feel a nenie of imwtqncebecruw tb.y:cnnnot prevent or
powern beyond tbwe of mortaln, almoat a nuper-being. ne.saate&theaer&e &e oftha Red Cum
Inheritom can be brou or vill.Lu,dependingon theirper- I-acOrdLopr. .&the&.
~nrlitiuand how 0th- perqeive thw. bl-4
They keephrck ofmeqrbsn,urocttD lasmbvr, and their
All Inheritors abhor the t h o ~ g hotf being locked up or b&E& U W d Mth l l U t l h d W d a b ! a ~.sMlhb
deprived of cinnabryl in iome other way, becruse of the
d~euence~potic*l*,andtharuler.odltiickwoftbe
horrible efFectr that can occur. Thia leadi many to believe OrdCN, Ckrica d e , U p $ h ebumuw.CY of w h d r , ucb
that Inheriton conider themnelvei above the l r m of l d K+ in a semi.o&id capaci* Thdy tend tobq arlm and
(uwell u ghnblowing, herbalitm,I d h u e ,ancienthk-
tory, and ancienth g u & n . The armorerproficiency u roc-
ommended for fightern.
Equipmenti Inheritor. ptefer to buy 'equipment of red
nteel ouch u armor and othef mapona. Theta are
I,
iidered atatui ijrmboln among Inheritorr. Of
unemotional,it+q out ofdieputen among othen. They are courne, it io eanier for Inheritor# to obtain
the preferredmediatom ofminor, local contlictc. cinnrbryl and related tubitancei, u the foUow-
@ iection expldni.
CL.0 Mod&donti Thin kit caunen no modificationn to
the k h t e r d u n . Thlever receive no bonusen or padtien, but Spe&~Bam5taiibmeniimed,achInhosG
tend to concentrate on the ntealth ikilli of d e n t movement
and hiding in ahadown. Lockpicking and trap finding and tor klonp to a aociqv tlpcK group o&r 1up
removing are ala0 popular nkills. Bards have the standard port in myywcyn. A m c m k r d a n order cm
nkilln for their c h i . Inheritor m a p i often prefer alteration rrcognize other Inheritom by their ardor iym-
and divination magic, though they are not limited in npell
boln (if not by other mcana). Inheriton can
choice. Likcwi.e, clerics can c h m e npclln from any aphere. expect other Inheriton to treat them by the
Code ofthe Ordcn, and in c u e ofdhputc., can
Cleria cam be devoted to a ipecific Immortal or to a puticu-
lor aliiment. Thole ofparticular culturen tend to itick with ..pcctmedi.tiand~condnm.
the I m m o d , dipnentn, and apelln ofthat culture. The orden ala0 KM u the m e of cinnab~~reld, .tal,
crimum euence, and nmokcpowder, thou& the httw 1tnod
Wupon ProMmcimiThere are no special weapon pro- only for trade. In many I&, thew r u b c e a are ~ a i h b l e
ficiencyaddition8or rentrictionn for Inheriton. However,an only -h, and to, Itlheritom. ( E muwciate members o€
Inheritor muit purchus a red steel weapon at lit level, and an order find it difficulr to ObLrin cinnabqylthlimuniMd the
fighter8 uiually npecialize at lit level, tending toward
nwordl.IllbChM tuw ham w ~ h & p r Q f ; e i L n e y . bane potion for crimion enience.) Though Inheritor mrgea
make nmokepoardtr and the base for crimron h e n c e , and
Nonweapon Proficiencier: Each claan of Inheritor
receive8 bonui proficiencien. Fightern receive rednmithing, Inheritor fighterr cr& red iteel weapom, th& item. are
mqen alchemy, thieven metalworking and dirguine, b d a o h avpilpble from Inheritorthkvuand bat&.
legacy lore m d inf-tion gathering, and clerici curw lore Crimnon einence ~d cinnabryl talinmann are integral to
and re.ding/w~iting.Inheritor fighten are mquirrd to take
weapon~mithingat lit level. Recommended praficienciea the moot important epccial benefit of the Inheritor, the abil-
include the bonui proficiencien for other Inheritor clunen, ity to acquire multiple Legocien. Before initiation into an
order, a proipective Inheritor in taught how to control the
magid power of the Red C u m . At the initiation, the indi-
vidual imbib- a vial of crimton ciience. Like anyone who
drinkn nuch a potion, the character gaini a Legacy-but
while anyone elic would receive it only temporarily, the
Inheritor gainn it permanen+.
The trainii in control of magic continuen u the Inheritor
advancen in level, and w e r y tkird level afterwards (at 3rd,
6th, 9th. etc.), the character m 4 connume another vial of
crimion ennence and grhr another permanent Legacy. If the
Inheritor trir to gain mother power before trainii in Eom-
plete, the potion panuthe Legacy only thporarib. (ufor
crimron stience connumed by non-Inheriturn). When the
Inheritor has reached an experiencelevel sufficient to gain
anotherpower penhanently, the character mutt purchue the
vial ofc h o n einence, which ia u n d y comumed duringa
ceremony performed by the Inheritoh order.
Crimnon eiience in made u i k c i n n r b d dinmani. The
potion b e ia made byan Inheritor m a p , u t k the dchemy
proficiency. A npecially crafted vid containillg the potion
b u s in then plrced into a n p e c t l cornparanentin a cinnabiyl
talinman (thin compartment i i the only real difference
between a cinnabryl talinman and a cinnabryl aaulet),
which the Inheritor then w ~ hT.he power emanating from
the cinnabxyk, and fmm the Inheritor (due to the Leg.cim),
imbuci the potion bane with magic, eventually turning it
into crimion eiaence. The churgc from potion b e to crim- 2. The Officid Challenge:An Inheritor cannot attack
ton ewnce taken about two month. d u h g which time the another Inheritor without fvlt iiwing o formal chd-
Inheritor munt wear the d i i m m : if it is removed for more lenge. If an Inheritor on an adventure diecoverr
than a few minute. (one turn), the magic diniptei, and the another Inheritor and A h - to attack, he or ihe muit
potion b u e muit begin the proceii again. (Thin dvei jurt firit ipend a round iinuing a challenge. A challenge
enough time to exchange a potion vir1 from a holder of typically h t i for only the given encounter, but the
depleted cinnabryl to a freih one.)
penon uiuingit CM ipecib an amount of time (Uin d
It in poaiible for a penon other than an Inheritor to create “youM my enemy until the end of the year? or even
crimwn eiience u i n g a taliaman, but it taken air monthi. It make it permanent. This rule in intended to keep
is alio p i i b l e for individual Inheriton to create more crim-
eon sreence than they personally need. Them potions can Inheriton from u n b u i h i other Inheriton-unleaa a
then be iold to othen who denire them. permanent chdengr h u been inued. Note that the
targct cannot reject the challenge.
Not#:Though Inheritor8 who quit the orden are consid-
ered renegaden (ice “Special Hindrancen”), a proepective 3. The Rendering of Aid: An Inheritor muit +e aid
member can quit before initiation without recrimination. to other Inheritori of the anme order. Thin in UIU& a
Since a proipective member hmihow to control a iecond
Legacy,it in poniible for that penon to later obtain a iecond temporary alliance for a oppccific encanter, but can
Legacy permanently with crimion eiaencei provided that
the character manwen to obtain the potion and remember d i o extend to giving ahelter to an Inheritor and that
hie or her training. Thui, a character with another kit can penon’i traveling companioni. The giver can decide
tometimes have two Legacies.
exactly how much aid to provide, but cannot turn
Specid Hindrancemi One minor dinadvantage of the down a requeet completcfy. Generally, the perion
requesting aid mrkea the need ipecific. The two par-
Inheritor kit in ita reatidon to the c l u ~aebove, excluding tie8 then negotiate on the exact help to be rendered.
all ~pecirluh(.If adding new claniei to the campaign, GMa Once a p e m e n t i i made, it cannotbe broken.
thould not allow them to be Inheriton.)
4. The SncredneiiofConclave: An Inheritor involvedin
Another hindrance in the kit itself, and the orden to which a conclave ofany type cannot be attacked by anorher
the Inheriton belong. Though the o r d m help in marq waya, Inheritor. Thin in for practical reuonn, to prwent du-
they can alio cauae problemn. For example, Inheriton are
ditliked in iome placei, becauie they are viewed M ndf- --ruption at the GrandConclave,and d ~ext)enda m pm-
appointed police who eelfiihly h o d cinnabryl and mlated
materialn. Since all Inheritore wear recognizable nymbole hctthose on the way to a conclave.Inheritorshave been
(exceptwhen on covert mionions), they uupuY EUI be recog. known to une thin rule to protect themielvea ftom
nired eanily. In placei where Inheriton are perceived a i
oppreiiors or criminal8 (an detailed in Chapter 7), they attack,&a leaderfor ndpment at a monthly Con-
receive a +2penalty to reaction rollt.
clave, volunteering for a Minor Conclave, or nimply
In addition, to remain in good itanding with the orden,
an Inheritor must followtheir regulationsand obey the deci- traveliq to onnd Conclave. ?he claim mdnt be
iionr ofthe Conchve8.T h i n might range from a directivefor
an Inheritor to move into a ipecial m a , to a command to able; an Inheritor 10mil- from the capital of Bellqyne
hunt down a renegade or other enemy of the orden, to a cannot expect protection by claimii to be traveuOg to
charge to dietribute mate&& in a &en region. Grand Conclavea month before it stwtd.
Th C& of th O&m: All Inheritorn muit dno follow the An Inheritor who defiei the code can be declared a rene.
gade, M can one who telli the necreta of the orden, or who
Code of the Orden. The code cxiiti primarily to protect condstently disobey8 directiven. Charge6 can be brought
Inheritori from other Inheritore, with most deciiioni againat an Inheritor o* by another Inheritor. At the next
conclave of order leaders (never a Minor Conclave), the
mgsrdmgother people left up to individd. With the q rccuied ii formally churgcd and given the opportunity for
self-defenie. If the conclave decide8 againit the individual,
diviaive philonophien among Inheriton, argumenti are puniahmenar m p from an order to correct the problem, to
inevitable, no a unified code of behavior in important. The a fine, to a sentence of death. The cleric8 of the order8
code ia primarily a net of courteniel; it appliei only to full record thin deckion, and word of it in dpread by the orders’
budr. Appul. are dowed o d y ifthe defendant can present
memben in good itanding, and hna only four purr. new evidence to an order leader. An Inheritor who rrfuaer
to accept puniihment io declared a renegade and in the
1. The Sanctity of Home: An Inheritor cannot violate
the home of another Inheritor. Thui, Inheritori and enemy of d other Inheriton, the nubject of a hunt by mem-
their p a e i i i o n i are lrEewithin their own home. Any- bere of d orderi. Renegadeslolc d protection of the code.
one who violaten thin rule become8 the enemy ofthat Unlean a conclave of order leaden ipecifidly decreer oth-
Inheritori entire order.
erwiie, a renegade i i wanted dead or alive.
hiociate memben OF an order mutt $80 keep its secreta
and fallow the code, though they do not themdvcn enjoy it. ity. Mnny LocrlJ+mmeapououur the “rob the rich and give
protection. Sponaori of uiociate members can be held to the poor”philolopby.
accountable for their actioni. An uvocipte member can be h h t Loqd Heme. ue from runlarea, but they cnn a l ~
charged with an offense and j u d p d at a Minor Conclave. come from inn& urbnn wmmunitiei.
AppuL can be made through the apomr, and are decided ch4ractuCLruAoychu.etaJnuuntakethe LacJ
by a conclave of order leaders. Hero kit, though apecialilt wizardi, wild mlgei, apecinlty
priem, and paionicista are r w .
Otbcr flkamcw: &aider the political hindrance. of the Rata and N . t i d t i ~Liocal Heroei are found in the
kit, there are dangen uiociatcd with acquiring Legaciea an city-atate., +e Savage Barqniu (though r d yin Gqo5a),
well. Rennrdy,Bcllayne, and Herath. The kit i meldon, u q d by
people of Robrenn or Euedria, becarus the h q l Hero
One in the issue of training. If the DM usea the optional often fights cgainnt oppreuion. or itruggbto improw liv-
ing condition. of peaan& and there no p u u n t SLU,and
training rulen, training for power gain and control muit little oppreuion, in either Robnn or & d i n , T& ohur
come from a higher level Inheritor, though clasi-related
training can be conducted normally. But even if the optional w the L a d Hero kit. Othcp-psrCr cbnracter r.cv CUI lllc
training rules are not used, qn Inheritor must som$low be the kit if raked in a lnnd that hu i o 4 cl.uca, rpd if the
taught to control the mcgic of the Legaciea. If a trainer i i individual iaccqpted the Iccolr.
~Locsl~~dmcatdwrJ
not avoilslble at the time Inheritor in ready to gain a t&d iocid qlaueq, rarely the middle claw, and nevm tbe u g p
level md acquire a new legacy, the,character muat learn CLUa.They tend tobe ofgood dignmqt,a n d m u w + ~
chaotic, thhough the kit haa no ps.r;culur&runen*.
without aid how to muter the power. In game t e r m , the %lei The Local Hero ii nonndy vewconlcipui of the
character iufferr an immediate penalty of -10% to experi- role he or she play6 u the hero of a praiCuLr commun*.
ence. Upon r q e the experience neceirary to attain the
new level, the character now acquire. the Legacy through W Hemen never formt where they c u w fmm, nad tb.y
his or her own itudy. (Note that if a trainer becomen avail- try to make things better b r their familisi nnd cormpuaiti#.
able during the interim, the chnracter in reitored to the min- They fight for common folk and pTotect the helplsu, and
imum expdrknce nrceddaryfor tbe new level and acquires the .o b n b v e lide &ence
Legacy with the trainer’s aid.)
nobility. Thin lomr&nei
A character who permanentb gaina a Legacy also lones bahndgarqtpheemotifnotor tchrmefwliecatlwthi6y oonththeer
one point from one ability score, u explained in Chapter 3. ekmentaof awiev,and the bCJ Hem t loaprtrmucutin
Since Inheritori gain multiple Legaciea, they lose reveral the rob of rebel leader (uin Nvvlez and AtmurQ).
pointa from pbility B C O o~ve~r the course of a long career. No matter how famoua or impoptant Local Heroes
The aide effecti of gaining a Legacy, such u red skin, Jao become, they remainnipple peraow in manqcr nnd appep
become more pronounced in an Inheritor. ance. If forced to drew in elqant clothly, or till 4 politid
office, a Local Hero io often uncomfortabJc,mu+, Ww.
Also,an the poii+wor ofmultiple k g a c i u , an Inheritor ing there in someone more dewrving.
muit be extremely careful to alwnyr we4r cinnahryl. As Some LqcplHerongo PI far PI t.lr;lewmi of-,
most jwt don’t c u e much aboutp n d gnh, pro* but
explained in C h a w 3,a character with a k m who lone0
to
contact with cinnabryi for too long ruffera from the malign Ih.rr d t h . Theytend to be ~ p -mdhow-- h
effecta of the Red h e . Among thoie are p b i c d transfor- in&or d i n & adwntqc ofloccl commonpr, orphckqtbem
mation and g M h r attributeIOM. If any of a charactmi ability in undue +r-and they to penuntje comprnipni to
follow their lard. If a treanure is dn w a d uxn.
ncom is reducedto 0 or below, the chnnaer imm+teb dies. [email protected],f)w W H e m often up- to lplitthe t m q mwith
Fw,imokepowder inter- i t r q e l y with Inheriton, t$cIDcoamn midunivtya, onr a^t lqmt returnd i n g [email protected] k i t .
group, the W Hero’i rl;hn p wd
because their bodiei carry multiple Legacies. Whenever 4 t a h d p the v p , and are nwer turned I+# comndoL
d e p o w d e r uplojon m u n withintwofeet of an Inheritor CL..ModSqtbnmiL e d Hero have no whod
(eventhe iirhq of a mokepowderHnrpon), aweek’sworthof iwtri+na, but prr&r ibpion, abjuration, urd i n d m
cation. Nccmwnqy and divination y e rela&+ unpopular.
the chuacteri cinnabryl (one ounce) i inatan& depleted. If Prieita CUI be devotpd to aqy Immortd, but ieldom revere
the ChUDcter hu leu thanaweek‘nworthofcinnabrylleft, the ImmorrrL of philoqhiea (like p o d or evil), or t h a d~p m -
amount reminiq ihta& depleted, and any time left over perity @ p f e & g Immort.la of honeit trade). A Hero
Lnppliedtothe d i p ef€ecta ofthe Rcd Cune. See Chapter thiefw+hunnNl;n~tofek;u*bu~~w
3for the p i n e e&@ of cinnab.yl &priv&on. streiiee the porn srechanid o n u ,(lockpicking,flnd;ae and
Wealth Optionis An Inheritor itarta with the name
removing trnpi) an the moit uiefd.W Hero piioniciata
amount of money PI a standard member of the nppropriate oftm p&r Paychometaholiwn and Pay&!&&.
character clans.
Locrl Huo
Local Heroen are champion8 of the masaei, perhapa the
most common type of wandering adventurer. Never forget-
[email protected] their rooti, they are advocate8 of commonen and equal-
The Local Hero rnngerb chosen enemy ii the biggeot worth of equipment. Othecitem are given to charitin or the
threat to the commun& Such a character addom h u an chuacteri home community; common, imexpeniive itemr
unusual pimvy terrain, inotud taking a terrain conducive ( d e r 10gp vrhw) a n be g i mtootharphysrdrsncten.
to habitdon. LwrlHem druida are involved with sgricul- Charactera who do start collectin8 vriwnbkea,w e a h g
ture or other I d fwdproduction, buraging locabfrom expeneivejewely, or othslwi.e ttying to rriK their emion,
CM .till be coluidared LwfHerom i f t h y act thc puc, but
huming the environment. Local Hem paladin0 arc uiuLUy
they lose the kiti r e d o n bonus, bscauu others p c & e
independent. or owe nllegiance to a mentor or I d church.
They seldom become attached to a large org-tion. iuchachurraCruno1ongerbciq"onedihcm."
Wealth Optionit The Local Hero receivmthe ota, ndwd
w- ' NI A beginning LwrlHero chnrac- atacting fund&
ter (of aqy character dur) m u t c h w from the followiag
weaponi initially: ihort bow, dagger, knife, hand u e ,
throwing axe,quarterat& h,b o k , club, dart, faotmani Noble
flail, ihort iword, long iword, +e, machete, and oickle. ANoblechar~rbelong.tothe~est~~ofthe
However, Local Heroei can take a proficiency in only one Lad. A.childmn, Nobla receivetutoring and train+ th.c
weapon not nornully dowed to theii c h i , and druida and give them nkillsandopporhdtimbcyondtbac ofmore com-
other priem u d y itick with the w ~ p o nni+ ~onfolk.Theyue.Lrodtothettrer~inlj6r.Noblce
avail- &.d a have a rocipl prejudics: They believein the aupcriaityOP
able to them, even at lit level. At higher levels, Local
Hetoea mrut take other wuponin o d y av.;lrble accord- the upper dwu,and in the& Ghtto Theyprefer the
ingto character o l w , but seldom take proficiency in exotic company ofother noblem .nd are &en d&l of psvna
weaporu, Swuhbuckler or Noble weapons, or & e m n o . However, Noblea feel a sense of duty to tb.;+Lad and
--N * eai A rural Local Hero's bonun family. giving them somethmg of P ienw of honor. They
Mapiculture or W i ,and weather seme or become adventurereb e u u d~ to hnd or fun+, or to
p&i&
a n i d lore. An urhan character receiveo agriculture (for find a n r u c i +~from th*.d.ilyobliga&nm.
gardening) or fiohing, and a one-dot craft ploficiency from
Not all percorns of the upper clnrnes need &e thie kit,
the "General" group, ouch M carpen-, leathemorking, or however. It exemplifiei M attitude that, while common, L
potteay. Recommended pmficiencieo include dl thaw in the
'General" categoay,phta weapanunithing (crude). notchbevldrtbysrdlCmLeUmibAenNoofbtlheeunonbb&ctayw. arrior, prht, hrd,
Eqdpment~Local H e m i prefer &tuple equipment, and
not a lot of it (except thieves, who nometimer have a pen- prionicut,orwi..rdoE.ny~~tnec~or~
map. Noble r u y v l are uncomman, and Noble drukL and
chant for gdptl). They have the itandard armor reitric- bud.are found only in Robrenn.
tiom oftheir particular CLU.When beginning p k , a Local
Hero can have no more than 6 in coins left unspent. See Racam and Natioditioai A Noble can come from the
c+rt.ten, the Swage & o n i t s (except f a Almutda, and
rL0 "SpedHindrancei." they are uncommon in Cimrrrbn and T d n , ram in Gu-
Spcirl B.nsBt.1Locpl Hemes are known in their home
community,and can expect sbelterand help from tha people gofin), Robrenn, Eudrh,Rcnudy, eollayne.and Herath. A
there. The citizcni will hide a Lwf Hem, provide food or
equipment, or even offer helpern. The Loccl Hem receiveo a non-native c& never d e the Noble kit; torrlen, and gobli-
Midl are never Noblsr, wen if .dopted
R6quimment.i The Noble murt he born to the ariatoe-
-2 reaction roll bonur from commoner8 of other areal, racy, or adopted into it, Nobles M seldom evil,and they
except in xenophobicplacei.
These benefitl Mreocinded if the Local Hem ia known have no ge& or rbility score requirrmenh.
to have harmed load fdka in aome way. The Lad Hero Roht Noblu M on duty tothcir funilyandtothsir
muit work to restore the wmmunityi confidence to regain
homcl.nd,hading morttoaatchivdnndy. S0cietyup.ct.a
Noble to be courageour, protective ofthe defrmenrdeao, and
the bemfit. gallant. Some Nobles are Iw dependable than0th- how.
SpeCM Hkdrmcer: A Locd Heroi community often
come8 to the character for help, whenever the village ia ever. Noblci of Behyne, Robrenn, hdrin, T a n b n , Ow.
poh.and SMgdm tend to be the mort mpoluible.
threatened by marauding monotern, bandito, or tyrante. Nobles arc often arrogant, even mobbiah, though thv try
to act well m a n n e d and courteoun, wen to those they do
LoulHeroes who turn aw.y iuch a request for help suf€er
a +2reaction p e d t y i n a t u d of the normal bonun untilback hot respect. They arb uaudy well educated. They dreu m
in their p a d graces.
cinWnribthrytlhte.leixucneuup)t,ionmoofnweeya(piocnls,umdaig~giceaml itkeempt f i e clothing and u ~ u d lyoathe any activity that cauaec
(including
for trade), them to get dirty or dunumrtkem (auch Mk d n g bodies).
Some Noble&enpecially thore from Robrenn and Eur-
d i t o r mneceuuytothe function ofthe c h (ouchu thiev- dria, are not arrogant or o p p o d to working with h e of
lower station, though key are itill c h n that they were
hgt d i or a budi mruical inntnment) no Local Hem can
rotainownenhip of an item worth more than 16gp. With the
named u b , the character can never own mora thn 76 ~p born to d e .
Claw Modificationir Noble wizards prefer powerful
schools, such M invocrtidevocation, alteration, and conju- Swuhbuckler
ration/summoning; they dislike necromancy. A Noble Thin chuncter ir r0gui.h and acrobatic, a daring individual
ranger’n chosen enemy is the creature that moat threaten8 who wields rapier and rapier wit with equal rkiH. Thongh
powibly caprble of wearing armor and w b l d ~ h e a v y
hh or her holdingn; foUowen muit be acceptableamong the weapons, a Swashbuckleris more ccmforable wh.n light&
nobility, Noble paladins almost always nerve the local gov- armed and armored. The S d b u c k k r Lthe sophirricrtsd,
but meldom serious, hem or villain who d e h %abut Mci-
ernment, sometimes a funily mentor. Noble bards have no etal standa&.
c h modiicationr. Psionicirt Nobles prefer the dincipliis
of Telepathy and Clairrentience, for their usefulness in churraCluas Any warrior, w i d , or c o p e CUI be a
keeping watch on their holdmp.
Swuhbuckler, thoogh Swuhbuckkr paladinn aad necro-
Weapon ProfciancieniA Noble of any character c h i is mancern are quite rare, and SwaBhbuckler rangera are
required to take proficiency in the sabre (except druids, who uncommon.
can take rcimitar instead). Punching specializationis com-
mon in most a r e a , martial art8 in Bellayne. Warrion and h d NItiopulltisu Swcmhbuckleh are NIT^ m the
priest.often become proficient in horneman’s flail and h a e -
manb mace. Lances are popular among Nobk warrion. city-ntaten. In the Savage Baronien, Swabhbucklern are
rather common in A l m d and Cargofin,but uncommon
Nonweapon F’rofi&&i Nobles receive etiquette and
heraldry an bonuses. Land-baaed riding is required. Reconi- in Torre6n, Nwaez. and Cimuron,and rarein GundaIante.
mended proficiencier include dancing, gaming, hunting, Characten from Bellayne, a d Hsrath can dro&e the k&,
local hutory, m m i d inntrument, and readinghvriting.
and Sw&uckkrs ue commm in Renardy. ft io rare, but
Equipmenti With starting money, a Noble munt buy a pouible, for tortlea to be Swaahbuaklen.
sabre (ncimitarfor druids) d a mount with full equipment hquhmontms Swdbuckler chanctem can be of either
(saddle and so forth). Characters who wear armor munt gen&r, any d i m a n t , and any waia.bdyaad, but hey
buy it, and will never accept anything woere than scale are neldom lawful and often have ariutowatic or wealthy
backgroundm. They munt have a 13 .sr better in %rea&,
(except psionicists, who m u t ga a ret of studded leather). Dexterity, InteUigence, and Charimna.
In all casea, the Noble muat pay extra for all equipment; see Roles Though nome have deep motivations rhat’are s&
“SpecialHindrances.” dom nhamd with othen, mat Swahbucklem uethrill seek-
ers, adventurers becauee of a whim. Eometimu characten
SpecidBen&tmi Nobkr receive more starting monsy than moonlight M Swuhbuckkra,leadin# an enthdyd%€mnt
other characters; ~ e “eWealth Optione.” They receive a -3 career by day. Swaahbuckkn are u s y J s chivdrolu. or at
reaction bonus from other memben of the nobiliq in their leut pretend to be, though this is kss because they believe
homeland, a -2 bonus from nobles of other lands and the in chivalry than because they like the artem.
common folk of their homeland. (Though commonem may
d&e the nobility, they are likely to treat them with mspect). A Swuhbuckler often pinu a nputrtion and notoriety,
Nobles can demand shelter from the people of their not always good. Cunning and daahiry, tHe + t o m e of
homeland, and can expect shelter from the nobility of any charm and grace. theme chupctera are often fdimd on the
land of the Savage h t . Other nobles will offer shelter to a wrong side of the law, becruse of their corn- d w t
Noble Pc’s companions as well, up to a number equal to for authority. They lometimes ally with bandits or pinten,
twice the Pc’r level. typicdy leadingsuch banda.
In theiihomeland, Nobles can administerjuatice. With charm and wit, L Swashbuckler often gravitates
Special Hindrancans To maintain their ntatun, Noble toward the position of group leader, or at least group
characten must buy aboveaverage goods and nervices, pay. spokerpenon. However, t h n e charactern tend to d d i k e
ing 10%to 100% more than normal, a determined by the nuch responsibilities, and are mom comfortable with wild
DM. This in part tip, but ala0 indicates that the Noble is theatrica and acrobatic. than eitherpolitics or mal tight&
actually receiviag higher quality materials and nervicee. A They are moat comfortable in cities, where they can &ne
Noble who buyl aubatandardgoodn (averegeor leeaer qual- amid qualor.
ity) starts looking shabby, and losesthe kiti reaction bonui.
A Noble h u oblitions and duties. If these are not fulfilled, CLU M o d i f h t i ~ Ar Swuhbuckler thief usually bd-
other nobler might considerthe charactera parasite, and the
reaction bonus from them is lost. Nobles who gain a bad ancon all skills, but tend. 6ommphanize picking pockets
reputation, whether derervedly or not, suffer a c6 reaction (morefor mleight of had). S W u t moving silently and h;$-
ing in shadows ten& to nu& becauae the characten like
roll penalty from all who know ofthe reputation. being noticed. Among Swashbucklerwizerdr, the d o o l n of
alteration, enchantmathharm, and illusion are popular.
O n e of the Noble’s obligation is to extend nhelter to other R.ngen umdy choosea npeC;a enemy that btingr notori-
members ofthe nobility. Thii can be rather co&. ety, a recognized but not terribly d q e r o u r foe. Thieves,
paladins, and other characten are almost d w a p indepen-
Wealth Optionni In addition to the ntandard funds dents. seldom working with guild. or other orpniutionn.
granted according to character class, a Noble receiver 200 Most cluses have an expanded range of weapon and non-
gp in starting funds.
weapon proficiencies available. Because of the nature of the Savage Coast, there arc mum
Weapon Rofieiencies: Tht weapons of the Swashbuck- kits available to warriors than to any other clans. Short
overviews of the kits follow.
ler are the rapier, sabre, main-gauche, and stiletto. At 1st
level, a Swashbuckler receives a bonus weapon proficiency B e d RacM are warriors bonded to a certain type of ani-
slot, which must be used for one of theae weapons; the most mal, which they use as a mount. They ue exotic people,
common choice is the rapier. Swashbuckler of any clasa and often seem more animal than humanoid in behwior.
fight with a warrior’s THACO with the chosen weapon. Dcfendcrd are warriors devoted to a specific religion,
Until a Swashbuckler is proficient in all four of these weap- something like paladins. But Defenders can be of any
ons,at least half the character’s proficiency slots must be alignment. Only fighters can becbme Defendek.
used on them. Swashbucklers can become proficient in the G n w h M horse-riding cattle herders of the grasslandd.
use of wheellock pistols, and many prefer them. Swash- These warriors tend to be crude and unruly. They are
buckler warriors and rogues of all types can take wheellock comfortable in the outdoors, and they enjoy the excite-
apecializatim (moat prefer the belt pistol, but a few use the ment of adventuring.
horse pistol instead). The character is also fond of special
maneuvers, such as fighting two-handed, or disarming Honorbound follow a strict code of honor and behavior.
opponents. They are something like the Samurai of Oriental satings,
Nonwuapon Proficiencien: The Swashbuckler’sbonus something like the Mamluks of Arabian ,ettinga, some-
proficiencies are etiquette and tumbling. Recommended thing like the honorabte knights of Westeh European
pmficiencies include alertness, artistic ability, blind-fight- cultures. Honorbound warriors usudly belong to special
ing, dancing, disguise, fast-talking,gaming, jumping, navi- companies of like-minded individuals.
gation, seamanship,tightrope walking, and gunsmithing. All MyrmiSond have b e d trained as soldiers, and usually
other rogue group proficiencies are appropriate as well, and adventure as mercenaries.
rogue pmficienciesdo not cost extra slots, no matter what
the character’s class.
Equipment: At 1st level, these characters must buy their
weapon of choice. All other gold can be spent as the individ-
ual sees fit, though Swashbucklers tend to buy stylish cloth-
ing and exotic equipment. Swashbucklers must adhere to
the armor restrictionsof their class.
Spccirl Benefit.: A Swashbuckler has two special bene-
fits. besides those mentioned under proficiencies. When
wearing light armor (leather or padded) or none, the char-
acter receives a -2 bonus to Armor Clasa. As a dashing fig-
ure, the Swashbuckler also receives a -2 bonus on reaction
rolls from NPCa of the opposite sex.
Special Hindranaeni Just as the Swashbuckler seeks
adventure, adventure comes looking for the Swashbuckler.
A reputation often precedes the character, kading Duelists
and other Swashbucklers to challenge the character‘s
prowess.
Strange luck affects these characters. For example, if a
member of the local nobility falls ill, a Swashbuckler might
...happen to look like her and be asked to imitate her in the
midst of an assarsination plot. A helpless person running
away from something might stumble into a Swashbucklerb charac-
ters.
Wealth Optionor The Swashbuckler receives the stan-
dard funds according to character class.
-Rider Equipmenti A Beaut Rider can wear o e leather, atud-
The Beast Rider in an elitewarrior in hm or her culture,one
ded leather, padded, or hide armor (plur helmet and
shield if preferred). Hide or leather armor madefromthe
hide of a mount who served f$thfuUy and continues to do
80 is preferred by many (but a mount ir never ahin to
tu- to leun moraa h t the world. The characters often make armor).
have trouble fin- lodging for tbc;mounts,though nettle- Specid Banefitor The h a s t Rider has an amaziw rap-
+port with one type of animd-that w e d aa a m u s t -
receiving a -6 bonus to reaction robwhenaver d&
thene animalr. If a roll is 9 or leu, &ut Rider. can per-
made attackingcDLn.L of that type to leavetham and their
&ea done.
Re+ prh t aorekes from & b e . If goblioids are Lupin Beaut Riders uae dire wolves aa mounta, while
allowed p. PC r.fer;Yaxi andl’axak gobfinoidn can be rakarta and elvea une feliquinea (me the appen& to this
Beaat Ridcn. book). Trained feliquiner have the rpeed and carryily
are seldom from the lowest capacity of medium warhoraes, but CM go full a p e d OL& if
carrying 220 pounds or I a n . Beat Riden almoot alwap
cl neutrd alignmento, but are
not re&ricted,acwrdiq tomidclw,dipmcnt, or gender. weigh leu than 200 pounds.
A &ut Rider character is bondedwith CUI an+ of the
A Benst Ridar mwt haver cb.riM..of13or %her. appropriatetypein arpecielccrrmony, and b e g i &~ w~ith
that creature PI a mount and purolul&end. ThC a n i 4 i
Rolei W i l e el& w u M n in their own locisry.&ut Riders devoted to the Burt Rider, and willrLLor even ucrificeiw
are often v i e d as intimidating in other cultures, or as
potentid e n e h in the land of other typm of Beut Rider.
A Beast Rider should be plu”.d as aeoutoider when away l i e for the character. If the a i d s alignment i diff-t
from home: nL.mand elfBurt Ridm UT conaidered out- from that of the rider. it nlowly changesto match (about one
niden even in the larger Kalamarhoftheir own homeland. alignment step per level gained by the r&r).
Beolt Riden like dl of urimrl,and are pro- Beast Ridern have a telepathic rapport with their
tective of thore m b d to their mount. The characters do mount, and when in phyiical or visual contact, can tell
not understand how amnecuw can miatmat a mount, and are what the animal is feeling and thinking, communicating
without appearing to do so. Even when B u r t Rider and
unfriendly toward there who do. If the rent of the party
accepts a Beut Rider, and minimizen hprm to normal ani- mount are not in right of each other, each knows the
mals and eipecially mounts, the character conniders the otheri emotional atatc, physical condition, direction, and
othen family. approximate dirtance.
Cham W C r t i o n r i A rangeri species enemy is never S p U i d H i d M C U l4 a an outlide~thc Bcost Rider ruf-
f u r a t3 d o n roll penalty fmmpwpk of otherc u l t u ~ ~ ,
the w e u his or her mount. If a neighboring Beut Rider including Beast Rider culturea who uac other [email protected]
culture is an enemy, rangern might choone that culture’n Beat Ridcn are expected to act the umc w a y d t h e i i
mount if it is different from their own. Moat B e a t Rider mountsas the mounts do toward them, be+ willing to ri.lr
rangen choocle plains or ateppes an a primary terrain.
A Burt Rider paladind o u not call a war horae. Inatead, or ucrifice their lie for their mimal,for inrt.nw. Beast
the paladin's mount bp.an added 2 Hit Dice anda -2 bonus Ridem who do not act appropriateb M conridnad to have
to ita Armor Clam Beast Rider paladiia u n u d y owe alle- abandoned the kit.
giMw to their specific clan or village. A Beast Rider can have only one mount at a the, Ifthe
Weapon P r 0 6 u i d i A rakanta Beast Rider must take mount d k ,the Burt Rider Mllred;tcly takes 2d6 point4 of
clam M a weapon proficiency,and often LUC war-clawa (ace damage from grief. In addition, the chuwter must d e a
Chapter8 4 and 6). Beut Ridera have no weapon rcatric- auccerrful uving throw agailut sp& or a d e r as if & c d
tionr (though if goblinoids are allowed, they should be by ajkbsrUninaspell for 2d6 houn (oruntil cured with
a &d
rentricted to the weaponn of their culture). They prefer or widb rpell). Upon recovering, the chuaoter mwt find
weapons asaociated with mounted combat: short bow or
short fompoaite bow, horieman’s flail, horseman’s mace, another mount (or abandon the kit); thii ir a quest worthy
of an entire adventure.
honemani pick, lance, npear, and uber. LiLnvise, a mount whose rider dieswill often find a new
Nonweapon PrOfifienciesi Bonua proficienciea include
4train+ and one. A Beast Rider pclodin who lous a mount cannot fmd
(each for the apecier of the Berut another of the aame exceptional quality p. tbe original, and
Rideri mount). Recommended proficiwcien are animal
handling, direction senae, fire-building, veterinary herling. munt nettle for a n o d specimen. though that creature can
animal lore, hunting, set unarei, survival, tracking, and be the beat pouible for a normdspecimen.
W e d t h Optionii The character ha8 normal starting
weaponimithing (crude).
fundi.
JMwdar poiarkitslhouldtNrrmictsdt0thesph~apcntotborLit..
Ifodlff~~bedda~aren0tdmtbuf.m-
fTahiteh,Drrel;feeiondne,[email protected],thofeagnuya.rlide-nmosfnat;
p.i9,aDsfendrrnatlimitedbyfaithorNttunbuucfar~
buttboundbythat.lignmsntandtheprwept.ofthed&n
thWeu+p.pshnacF.'rdobiMaten,cdiiuviiIfdathbe~I.nIdmpoardcwriooam. b-
the charaater supporn. &ai+, nucba character haa all the the Defender h u a favored w e a p , the D c f d o r m m s t
hindr- ofopaladin,t h q h not udrmc pSnaywbncdbhu.t,where became proficient in its UK. IEthe s p d t y pies* of the
Dcfandanare found thro+ut
they are n.pected.ad m e t i m e n f e d , but d w a p sup- Immonal are rertricted from aertain weaponi, so u e
@bythaewhohaw tbr u m e phibnepby. oood mLw- Dekndsrn dthat faith. A Defander's other weapon p d -
ciencies at 1st level are limited tothe w a a p o r~vailabk in
ful de€endera can nerve PI h e m i n a campaign, wide evil or the CharaCier'8 culture.
ckoticdefeudencanbeuaedaafortlununate~.
c h a a a r Chui Only single& fightam can take the Nmmmnpon PmBci.ecbrr Defender charactem n 4 v e
Defender kit. If the Immortal nupported by a Defender is
M"O bonus prohency doh in reliion, &ing tkan g e n d
the patron of a certain character clam, the DM n+ &low i d o r m t i o n about faitha of their homeland and nearby
multi-&c Defenden, aaeumingthat one of the clamen in ueu,phIs p+ knowledge of dlsk own faith. D d e h
Gghter and that the multi.clPn combination M open to the are alro required to take tlrv ceremony profiiarcy (rea
charactes's race. Similarly, a dual.cIana ohuactcr could Chapter 4) for th Immortal ofdmir kith.
become a Defender; for inatance, a thief could change Reoonrmended proficiencicr indude [email protected] d l c i i -
charen to become a fwhter, and if devoted to m immortal cien, the ceremony profioiency for enemy ImarorUlri uxl
patron of thieven, could take the Defender kit.
any appropriate to the faith (8uch as agriculture and
h mdN & ~ u l k h Defenden can beof MY race or weathumnw for druidic Defeadon).
natiodity, though the kit is illegal in Nuvaea. They are The Defender not bvet o ~ ~ + n c y d o b
quite important in Robrenn, though overdl thy atill make U the bfi.nda'8 I
up only a d l percentage dthe population. See Chapter3 for pried ,group p..t;.;.&. d i.
of the &nib oftbe Snwgc Cawt book for infohation on the rpatronof&c,thechu&arE.nt.Lewiurdproficwll-
Defender in Rnbmn.
cim without extra cost, while the Defeader of a puron of
thieve. can d e m y e proiicienai~without catmcon.
ReqnirementaiA&fender munt have miniumm abiiity En.ipl...tt DaEenden murt fdow rest&tionaef thci
ncoren of Strength 12 and Wiadom 18. All cocid clanaen,
gender#. and alignmenti *re open to the ki& But once a faith race,and homeland, but anot othwwimliitod.
Defenderh dipment i.chosen, it cuuwt be changed with-
out the loss of the kit. f"'S&id Eenafitar Defender chuactwn are recapixd
R o l m i A Defenderh role in a campa+ depends largely on in theirdwen..liS;.ua hiemthy, sothey anjcythe
rt of tho order. A Defender OLII expect tba f&&d to
offe shelter, and to render aid when called upon.When
the individual's alignment and ahoice BE Immortal. A char- encopering 0 t h follmvm ofthe mame m l ? ? D, efend-
acter devoted to the druidic w a y i r a Bort of "druidic
knight," a Defender of nature,whie chaotic aril Defendcn em d m a 3bonus toractionrolb.
wha wonhip an Immood of Entropy might be considered
"anti-paladinn." A Defender i~pporrithe religioue hiecar-
chy of a specific~Immortala,nd hu the s m a l i i m e n t s , Prhtsp.llLevd
the orderi prieate (if they can choose from M V d i~n - -1 2 3 4
menta, so can the Defender).
Certaind u bare ~mdmotno d lkkndam They munufc. 6 1 , I -.
7 2 2--
guard their religioun order, defending priesto, wonhip aim, -8 3 2 1 -
and ditamr. They mwt protect thsf.ithfulandobey the
pies& and nuy,be &upcn t0punic.b k who bmak th 9 46 , 2:"2'
1101 2'21
faith (aswmingthr d e r bdieveain such punirhmmt). 6 321
Same people treat Defchdcn PI a type of mrriorpriest,
the f%hting force of the faith, but &o a oubrdtmte when 12 a7 3 2.1 1
13 53 . ; 33 , 23 . 11
priests are unavailable. Defender character8preach the 14 9.
tenets oft k u faith when dm oppormnityp w a t . blf.
clusmdi6&*wd Defenderr can cmt a p d L at h i g h 16 9' 4 3 3 1
16 9. 4 . 3 3 2
levels,a d in =me -thy a m like .pecLldr priesacIElpa- 17 9. 4 4 3 2
cialty priests am ured in the campaign, D e f e n d e n d uae 18 9. 4 4 4 2
only n p b h m the T h e m available tqa [email protected] prien of 19 9. . , 4 4 4 , 3
their religion. Even if other aps0idt;tnprieats are not u d . 20. 9. 4 . 4 4 4 .
druidic Defendera are limited to the n p h m open todrpid..
Similarly, Defenders from culture8with l i i t e d choices of
A defender can detect beiign of an J i m e n t , & c t d by very few come from the upper c l ~ ~leei- , the "romm-
tic" life of the plainr. But, G a u d o l are alwayi c o n r ~ % d
the chuactw at lit level. Defender. may chooae to detect lowm0l.u.
law, ch.or,good, evil,or true neutral. Molt often, they elect
Moat G a d a u a male, but they can be of either gender.
to detect the alignment of enemier, but some choore the They have no alignment rebtriction8, but tend toward
d i p m e n t of friendr instead. A druidic Defender &ayi
c h e a the abilityto detectthe true neutral dpnwnt. chaotic alignment.. A Gaucho muit have a c o l w t i r u b of
, A Defender alno gainr the ability to c u t prieat ap& at at h t 13. A b h SaMyh aad DexIdyared & d h
higher levelr, u rhown on Table 2.1. See "C1.u Modifica- Role1 Gaucboaare unruly frontier ridom, who live m a t
tion." for ips11 rphere reatrictiona, Defenders with h k h oftheir life on hombfl,herding c d e . When not haltg.
Wdom mrer do not gain extra apella. a Gattcho might live M a bandit, or enter a rmdl town to
S p d d Hindruicaii Junt an nome people iupport and aample the local €ood, drink, and women. C.~&OcoDuld
even admire the Ddender, others revile the charmter. even join a milituy forre aa outriderr or light c a d y . But
Defendem murt prominently wear the iymbol of their faith few really have the twnpcrament for ruch activitiar: they
at dl time#,unlen the faith rpecificdy dawn othenvirs. wouldlikdypin ot$ in a- fortheir own indepdmca,
T h , the Defender CM be euily recognized by memier, or to u t n wme money and. cknce to ketthc-1
and receive8 a 4reaction roll p e d t y &om tho- not well An edventumome loc, with a love for excitement, rmqy
&pored tow& the cbuacteri rewon. Defenden are pm- Gaucho. beoome proferrional dventurerr becaurc the
thd-raskiq liestyle a p p d r to them. i n an adventuriw
hibited from amociating with enemiea of their faith, and goup, a Gwcho e h t .etM a naut. G a u c h l i e quick
v r d y hin henchmen of the ume faith.
There UT other w a y in which Defendera are o b l i t e d to adventure8 without conitquence, and urually c u e Htde
about gmnd poIiti4 movcrment* or hemilimy dratqim.
their religioun order. They munt obey the command. of
p h t n more hwhly npolatcdeedfiinnedthteheorhgiasnnizractibon).c(oofmhnQmhder. Gauchor M generally crude and a little rude, but often
have a &Wlac& hiddenundsrthat V h d o r .
hl,if the DMhu rowdies with litde urc for the
range fmm pard duty, to merwnpr rcrvice, torecovery of They are proud, iw-
nicetier of civilidon. hbt h e a d h manner, and are
w r e d iteme. The Defender muit dm rpread the faith, and
mininter to the faiW when a pries ir unavailable. happy to nolve problem with their fiiti,or witb their wheel-
In addition, Defendera must tithe totheirdi+in inlti- lock pistoh. Some u e m e 4 and rly, othen hoaert and
kind;the exwt pnrmulis.hleft to the player.
tution. giving 10% of their income,whether coins, jewelr, ChuModiBo.donuG m a c h o r . n ( * f i m u t h i ( n u -
&cd item, wage#,ma&,or taxen.
They mwt dao followthe tenet. of the faith. F h r e to do IM& M &primyr terrain.Gaucho p.l.dLw are alwap
IO PM ruult in faced abandonment of the Defender kit and independent, or have a mentor: they are never ruocuted
with a government or a church. The bonded mount for a
d Mtn that p with it, and may even reiult in a bunt by Gauchop.hdinhh a y a a how.
other faithful to puniah the offender far blaiphemy or
heresy. Defendera CUI also be declared blaaphemerr for Wmpon Profichacieer The Gaucho ir required to
become proficient with dagger, bolu, and th. wheellock
dereliction of duv. horw pirtol. Other weaponi allowed at lat level inchdo
Wealth Optionir Defendera have rtandard rtarting
club, dart, h w d or tkw+axe, bonunrni &I,-*or
funds. pick, j~&. k h t hone lance, morning atu, rourge, d
Gaucho (uber only), and whip A Gauchonever h a p&ent
with any type of polearm, and rarely buns how to uw a
The Gaucho ii a warrior of the pampu, the grualand. of weapon inappropriate for mounted combat, but can take
the Savage C w t i eutern regionn. Gaucho8 herd cattleand otherweaponi rfar lat level.
other beasti, living off the land for week. at a time, then eeNomupoa-
entering a town for a little rowdy relaxation. They are very * I A Oauchoi boarup m h .
comfortable on horaeback, and spend moat of their time ciea M direction YW and lud.bud (m"Special
mounted. Benefit.?. The duncanaremquiredtode
pmfi-
Clurwtar CI.ur Any warrior can be a Gaucho, though ciarcy (except for rangers, who &ea& pt it for fne). I&-
ommended prdicienciei include &.lh d l i n g , a n i d
rangem & the mort connnon. and Gauchopaladinn on ram. firr-bui,l d m k -
Rum and N.doluliti.mt Only humani and demihvmuu t r w , bhkdthhg,
. .ine,weather nenn, gaming, hunting, a m ,nwivrl,urd
(elves, &uvea, and Uflings) of the Savage Baronies can
be Gauchos. The kit in common in Cimarron and w q u w d u q (crude). At lltlevsl, a Gaucho cannot take
Guaddante, lenn LO in Torreh, Narvaer, Almurbn, and d q - d f e w t a k a ' ~* at l r t h l .
& e n . Gaucho8 are quite rare in Garpfia, and are found Eq+nmt~ At h t level, G U I Cm~M purchue either a
ody an viiiton in Vdaverde and Texekan. riding hone or a licyht war horae; they receivea a iaddle,
uddb blanket, bit and bridle, hmeshoen and shoeing, and
Requimmontri Gaucho characten usually come h m the a d d l e bag8 without expenditure. They prefer light war
lower clunen, though nometimes from the middle clannen. A
honec abow d d e n , and never own anything u &#e a8
a heavy war home.A Gaucho muat rlro p& bolu and
a dagger at l a level. As soon Mpouihle, the ch.nctcr muat
purchue a wheellock horme piltol u well. Gauchoa travel
light, so they keep other equipment to a minimutn. They
Gaucho never wear armor more b u l b than a d d e d kather.
Sp.d.l R e a m h i b i d e 8 the benefih l i d above, Gnu-
chon receive a -3 bonus on reaction rolls when they
encounter other Gauchon. The Gaucho ala0 recognizes the
quality of horm (adetailed on p a p 37 of the MG).
Finally, Gauchol are expert8 on hareback and receive a
+4 bonua to their proficiency more for land-bued riding.
Note that a natural roll of 20 ia rtill a failure, even if the
characteri proficiency score happenr to be above 20.
Special Hindrances: Because the Gaucho tends to be
rough amund the edges,the duncav &a +3pndtyto
reaction rolls when encountering anyone from the Savwe
Baronim,other thana Gaucho.Forthe moet part,p p k hum
other M ~ ~ O Mdo not know of the Gnuchoi’poor aeputation.
In addition, Gauchos apend money almoit u quickly M
they get it. At l e u t half ofwhat the Gaucho earns must be
spent on “frivoloua”thinp such M fme food or drink, a few
day8 of expeniive lodging, gambling,and Mforth.
Wealth Optioaii The Gaucho atarts the gune with
1Od10+100~ pb,ut muet ipend moat of it on initial equip.
ment.
Honorbound
The Honorbound ia a warrior who followa a atrict code of
honor, known aa the Warrior’s Honor. Honorbound war-
charactera, though only with combinatioaa of w&r and
riori generally belong to apecial Companiea that have wizard or pricat, never any that include rowe c l a a ~ ~ a .
ancient traditions (an Honorbound without a Company is
conaidered a “Companyof One?. Some group8 of Honor- (Priest8 yn unnetimea avoided to keep a Compuur freeof
bound owe allegiance to a particular government, while overtones,while -ea are denied beanie of&&
other8 work u elite mercenariea; aome are profeuionai rcrler parceiMd iack of honor).
duelists, and others are wanderera who fight h r what they
h d N a i o d i t h Cornpanin of Honorbound M
relatively common in,Wayne, and there is a Cmnpany in
believe is right, or simply for the nke of khting. Um-Shedu (composed ofee’ur and snduka), rad one in
The trrdition of Honorbound warrior8 began eenturiea
S h a d (of Ih.uki,of course). Honorbound Companies in
ago,and atarted amongthe elven and r h t a culturu ofthe W y n e accept r h , elvea, and tordes, Mwell u a L
humana, dwwe a. halfling., Some Companier Bellape
Savage Cout. T h e elves who bacame the ee’ur developed accept membem of of
one b~chof the tradition,while the r h t a and elveswho &a am& race.
aettled in Bellayne cvried on a aecond branch. The W u -
rior’a Honor ia ancient M well, and changed little over the Individual Honorbound are found in Renardy and the
Savage Buoniu. Not pUoCipted with q y Componiea, t h w
decadea, 80 that when ee’aar recently returned to the Savage
Honorbound are mostly proferaiod duelists. In the Savage
h t , the ee’aar and BeUaynese traditions were atill almost Baronies, humma, elves,d w m a , and halIlinp &anb e e m e
identical. The ee’aar had apread the traditiona to the enduki,
while ahazaks, tortlea, and a few goblinoids had acquired it Honorbound; in Renardy, moat Honorbound are lupine,
though a few are human or demihumm. There am no Cam-
from the rakaita. The dvei took the tradition to Eudria,
panics in Renardy or the Savage Baronies.
and gurruh later acquired it from the a h d a . In Euadria and Ator, each nation h u a ringle informal
Honorbound warrior. are cuily r e c o g n i d and highly
reBpected by the &a ofthe Saw Cout. Company.All membra have the name emblem, and con-
rider t h e m d m memben of the m e p u p , but thereino
Chuaccer C h a r Fighten, rangera. and paladins can Company hierarchy, and enemiea and weapon8 arc choaen
take the Honorbound kit. A Compaqy of Honorbound o h
by the individual.
conmstr ofonly one srpe ofwarrior (dlrangen, d pd.dins.
or a11 fighters). But some allow dual-class or multi-clsns If goblioida are allowed u PC.,the polls of Grande
CanPIcal near the Savage Baronies should also have a Com-
pany of Honorbound, much like thmfound m Eu& and
any.Ibruacnt~ulbrie~<
TO bacol~ean -orbound, must&I mini-
rsof at lcut i I q h ~ . ' i n s '
u-::; ,.
wuriors are oftqn toujhit byrrrnies.
h u mthaJtM+able Mle& and d & h&Honor-
bodad can * t q with .h&y M long M that or6antation
doer not mquiro the g+orhound tcLbreak any portion of
the Wurior'a Holla: H w r b o d &e sometimes granted
land to govern, .adthey d e aff4otive managers. The
char.ctera ut +!so s o m e t i m n . q ~ g bbt y.adventuring
groupi,.$,~uq hey ~ l r fieie,.Il+Jionorbound join
such gnnipke&'more aftbe wbrld,:fora apecific quest, or
to t p r u d teaching8 of the Wrniori Honor.
In q y group, an Honorbound ia tolerant of othera. The
cheracter d w i not expact 0th- (tthooawdhheOreCtfo..iOthlUe UWYadririuopr-i
Honor, and u ddo m iurpriled
pointed) when they do not. An Honorbound d i m that
other8 muit come to the Warrior'i Honor themaelm, and
d-8 not force it on anyone. An ucompanionsdo not
try to make the Honorbound forget the Warrior's Hoaor,
the Juncter can .t.y with the p u p .
.,
The Wuriori Honor i i rplit into two =ti of governing
reguhtionsi Precept8 and Protocols. Precepts are simple
rules, generally p h r a d Mthing. to do or to avoid, or .(I
beliefa. Protocols are procedures to he followed in certain
UtUrtiarU. Note that dl Honorbound,,of my alignment, fol-
low the Pmcepta and Protocols ,ofthe Warriori Hwor. fricmdor ally in coluideredlrepucd.Forhpdecombak,(L
deckation of war u nenury; once thi hu been done,the
The basic Pmepto are M follow: &ea of thee n e wareconsidered pnpued, and surpriee
Honor in mom important than lie. ottndu we dowable. An Honorhoundcannever p.kicip.te
.Fewis acceptable; c~wardiceu not.
Live to fwht, and fyht to live. manamb& encbpt againat sgemia in adecbredwg.
Respectyourenew.
Do not attack the defenseleis, the anok,or the innopent.
D o not threaten the defenieleu, the we&,orthe inno-
.cent to exert control over an enemy (do not take
hoat.ges).
Do not involveyourielf in the diehonorable actions of
others.
that an honored enemy, usually a leader of an opposing or wear the nymbol on armor. Goblinoida ~ , d m i l amreth-
force, is aaorded certain privileges. It in conaidered honor- ods to the lizard kin.A Rrkort. Honorbodrk..r. a circu-
able to touch hn honored enemy, without harming him or lar, red-painted, cepmic pendant QPr t b o n i or chain
her, during melee. An honored enemy should be felled only around the neck. Tor&.usuplly e onto the
in singk combat. If captured, an honored enemy in treated .th amund it,
t of their nhelh, and add- , ,
M a guest. If called for, a captured honored enemy can be ok .ormewhailiLepainte Whatever
executed, but only in a formal ceremony. Honored enemies e,rneedvaeirro&leptmy w-b4d. waya be a h , and muat
-.comP.av rlw has an ciaMea
can’bereturned to their people in return for materid or
other Mncesnionr.
The Protocol of Negotiation declares that negotiationa Lihe&ddtheisd An indkdd pulr$;l
with C0mp.q~#t h v e a pawd
rue . a c d They u e a UUM for a truce, and a truce nhould
not be broken. To inaure this, oppoaing forces exchange aigila of the Inherhas &e emehaa $the
hoaugca during negotiationa. There host.gea are warriors considered pnvaupmpwty, rspahmbdm p by
who understand that their liven are held as proof of their othera ia a g r u t dfenn. h c h Cotrp.ql of HwQrboyd
forcei honor. If the truce is broken by one aide, the livcl of alm haa a d e c k e d many. The C&panii m d indi;ldP.l
the hoacagu from that aide are forfeit. . . . *H o n o r b o d m h u e d mom thoroughly in the sectiolu
The Protocol of Betrayera refers to those who break the OD the d a u hJNTI in the rpdr4tkSPmp CWC book.
&-lllaeucno- &at-
oaths of the Honorbound. An Honorbound who abandons
the Pmepts or the Protocola ia declared a Betrayer, and i, @cluws, exsxp h t pol* u d r a q m +$o t a b the
subject to a hunt and eventual death, which can be adminir lit M nguired in a &le asrpoa.InJdirion,
tered by any Honorbound. Betrayera beamirch the honor of Qw -‘a oncemy might b p r e - c k n (me ‘Spe-
d Honorbound. and deanring is p a i b l e only if an Honor- d+wl Buedpit,s?.
bound kills the Betrayer.HOWMEto retin honor, individual Honorbound rmprtp i d i r e in
Honorbound muat ascertain the proof of betrayal for them- , - t-he-u.ft o rt 1m1lev& *ma the nor-
.~selves. Even if orders have come down from the leader of an
Honorbound‘s Company, individual Honorbound munt h ixation for more than cm
determine the truth when the suspected Betrayer is caught. d.Rakutr Ohenurr war clam, while iome prefef the
If the capturer cannot determine the truth, the suspected W H o n o r b o d who belong to a Company muu UK
Betrayer munt be brought before a group of at l e u t mix t h e w c a p o n ~ t h a t C o ~ y .
Honorbound, where the truth of the matter io decided, and The Hon8rbound of Renardy and the Snrrge Barunies,
a sentencecnrried out. most of whom are profendonatd u e l i , are dowed to rpd.l-
Individual Companies of Honorbound sometimes have ize in the use of the wheellock belt piatol, instead ofa mdce
additional regulations, but there are not considered on the weapon. These are the only Honorboundwho can do so.
same level with Preceptn and Protocol.. Company regula- Nmrnupon Profiaiondrar Honorbound receive banua
tions rue nometimen specificationsof the Precepts and Pro- proficiencien in dueling, etiquette, and heraldry (focusing
tocols;they .LMincludespecialweaponn, duties, allegiances, mainly on the Heraldry of the Honorbound). Recom-
and symboln. Each Company has at leaat a s p e d weapon mended proficiencies include a c i t n t history (specifically
and a symbol. milituy). militmy tactics, gunsmithing (for d u c k ) , animal
Every Honorbound (whether a member of a Company or handling, animal training, dancing, redingAvriting, Mind-
not) wears a white sash around the waist; this nymbolizes fighting, endurance, direction sense, and fua-building.
the p k t o~f honor For which the character naivee. In addi- Equipmentt Beginning Honorbound muu purchase their
tion, the Honorbound murt wear a red circle emblem, sym- weapon of apecidization. Charlctcra can weir any annor
available to their race, but nddom wear anything heavier
bolizing the blood shed by warriors. T h e emblem cannot be
made of cloth (to avoid confusiDn with Crimson Inheritors). than chain mail,because they prefer to retain mob&ty. They
An Honorbound’s race usually dcterminen the form and have no other equipment reltrictim, other than thoK man-
placement of the red cirde. Elven, dwarvea, humans, and dated by an individud’n culture. Most acquire any equip-
halflings wear red circle markings on rheir face or hands ment they need to survive an wanderen, but do not c q
(ouch M on the forehead), on a cheek (never both), or on enough to nlow themnelvm down.
the back of a hand. Becrrurc of the Red &me, a chvPccerh Specid B e ~ 1 6 tTuhe Honorbound wuria hu a few ~pc-
nkin might M y be red;in thii cane, the Honorbound sur-
cial benefits ffom the ancient traditions of the Warrior’s
rounds the red circle with a white border. Ee’.ar and Honor. Firrt, there is the Warrior’s Honor itself, which
enduka unually paint a red circle on one or both wings. demands that other Honorbovnd put the dur.drrin a cer-
Shazaks and gurraih usudly wear the red circle an body
tain way. In addition. the Warriori Honor (and the bpecid
punt; some paint a circle on a hand or on the face, while p b o h ofthe Honorbound) insure thrt the ch.racter is m-
b e d by others an an honorable warrior. U& reqnked
othen might create a aeries of red circles dl dong one arm,
t, sen foe before all others. Other Honorbound CUI make a
conscious choice about whether or not to Gght,the chosen
Lnmediatclycu foe, and CUI determine what theirown reactions are.
Lan e n q , Hon- Specid Hindrancear Juat an the Gomponier and the
Warrior’s Honor s(m help the Honorbound, no can they
orbound receive a hinder the character. An Honorbound who belonp to a
-3 bonus to reaction
Company muat follow the regulaiionsof that C o m m and
muat follow the orderr of +e CsmPMy~leadera. As Hon-
an enemy receive a -1 bonus to reaction rolls, orbound who belongs to a national Company muat defend
b e c P u ~of the respect that othersfed for the Honorbound. that nation and obey edicts of ita leadera (defending the
Honorbound characters also benefit from the Company nation taken precedence). The Honorbound m p t rl.0
to which they belone, The C o m p y provides a support net-
work and inatant allies if an Honorbound gets into trouble. follow the Precepta and Protocola of the Wemior’s
Honor, or be d e c W a Betqyer, subject to c q u m
An Honorbound who is a Company of One enjoys indepen-
and erecution by other Honorbound.
dence instead. An Honorbound of a national Compqy, like
those in Eusdria and Ator, gains the network of allies, but Inaddition, ahoat everyone onthe Savagecout
doea not have to follow Company orders (though they must
still defend their country in times of trouble). recognizee an Honorbound PI a wurior, whi& CM
caue a fewprobiema. Honorbound of other Can-
In addition, Honorbound gain a +4 bonus an attack rolls paniei, or wanion of other kita, might m a t to t u t
agoinat a declared type of enemy. Honorbound who belong I their combat proweas against a recogniz.4 profq-
to a Company have this enemy type chosen for them: the sionnlwarrior.Ifukcd, the Honorbound iplrobound
Comppny of One, and a member of a national Company, is
free to choose. The enemy van be a species ( I i e the ranger’s to mediateduds between d e r char-.
chosen foe), the people of a certain enemy nation, the mem- There we allo nope unuvory individualawho try to
ben of an enemy Company, or a particular type of creature
(like undead or giants). The declared enemy can never be I catch Honorbound on point. of honor. For inamce, a
changed by the Honorbound. unless an entire Company ’ p e r m might be able to extract a promile of protection,
decides to change. A Company of One can never change his
or her declared enemy. F or an invitation fram an Jionorbound host, thereby
gaining protection from enemies bent on murder. The
If the Honorbound in a ranger, this chosen enemy Honorbound must keep the promhe, or Protocol of Hwt
replaces the ranger’s ipecies enemy: the bonuses are not and Guest, even when he or ahc agree8 with the gusati
cumulstive, and a ranger character still incurs the reaction
penalty for the species enemy, and prefers to fight the cho- eneWmeieasl*th Optionmi The Honorbound receivu atandard
starting funds.
lcryrmidoll
The Myrmidon is a soldier: The character can be M officer
in an army. a career, nergeant. or a mercenmy. In timea of
wer, Myrmidonr are heroer; in times of peace, they are
viewed cu parasites who provide no uqeful aervice. On +p
Savage Coast, a Myrmidon is often a front-line qplorcr PI
well. The character bripgs d w i p h and an undsratpndmg
of milituy tactice to an adventuringparty.
When a %midon is created, the player and DM muat
decide if the character ic a mercenary or pp3 of a apnding
army. If the latter, the character has dutieato hL OT her unit,
Mcrcenuy M y r m i d o ~have much more frocdom in pxpt.
ing commiariona. The character’s rank in a given unit,
m-whcehthrenrcatnearrmcly.uoriaFmisehrteqasn,muydpruanpp,rio aurpetoofttenb DM.
dona. Myrmidon paladin? are allowed but uncommon,
becauae their greater +votion to a CUI= may not fit well
with the actione,ofan m y or mercenaryp u p .
h a n d I U d n u k k i -om .~forund m the city-
stake, the Savage BpmDiu (npecipllyT d n and Nuv.rz),
Eusdria, Renudy, Bellape (though uncommon there), and
Herath. Mcmben of any PC rpce c.llbe Mynnidorm,thovgh
haltlingsare rarely &n =no+ in such a profdon.
Roquirementu A Myrmidon can have bny wcL1c h s , all merceasriuor moLlierrare memrnhle a Myrmidon.
gender, or alignment, but many are lower clasn, male, and Wealth Optioru: The Myrmidon receive. the atandnrd
lawful. A Myrmidon must have scoren of at least 12 in
Strength and Constitution. starting funds.
Rolu The Myrmidon in a Btrategiat who prefen to think
for a bit and plen before launching an attack. Thw is a dinci- Wi-d KIks
plined character who in contemptuous of individualistn, or
those who do not take orders well. Of courne, such an atti- Wizards are often myrterioui fwm on the Savqe Chat,
tude can lead to friction in an adventuring party. Myrmi- though their help in welcomed in any war effort. Eceh oftho
dons are often gru€€in manner and rough in appearance. wizard kit. can be uaed for psioniciatr a8 well. A short
Mynnidonn welcome war, and nome travel great diatancen deacription ofeach Savage C w t wizard kit fdlm.
to s i p on with an army involved in a conflict. In peacetime,
nome turn to banditry or adventure for excitement urd the &&ant wizards are skilled in the military wti and arc
means to live. found am spellcastern for annies. Illusionists, enchanten.
A Myrmidon paladinin often the leader of a unit (or even and wild mages cannot uie the kit.
a whole army), while a myrmidon ranger often serve6 am a Myth ue wiaardr devoted to learning and aelf-enliiht-
scout, and in in demand for exploratory venturen. enment. Necromancers, evokera, and conjuaerr cannot
Clua Modificationit Myrmidon paladins usually owe be Myatica, and a Nyotic wild m y is rare.
degiance to a government, though 8ome have mentors or Milil
are independent. Ranprn can take any species enemy, but
. .many choone one that cauies particular problems for the The mwant coma Emm a culturethe. urn wiurda ertcn.
army they belong to, The Myrmidon ham no resaictionn
aively in its military. Generally, the culture is either a war-
wd.DopI- mongering nociety, or one constantly besieged hy othen.
or preferences for ~eaporut,hough a particularmilitary unit With the frequencyof wars on the Savqe coplt, e m CUI-
might have proficiency rquwment.. Maqy b+midons have turn with an army alu, haa Militant wizards,
proficiency in one or more ' ~ l x aof poleurn.
Nonweapon Profichnciew A Myrmidon's bonun proti- A Militant considers a trained body as important as a
ciencier are military tactics and tire-building. Recam- trained mind, and keepn combat nkills as r h u p an lrugicd
mended proficienciei include ancient hintory (specifically dents.
military), animal handling, cooking, heraldry, riding (usu-
ally land-based), aeamannhip, swimming, weather rense. Character Chai Mages and all specialist wizards mxoept
illusionirta and enchanten can &e this kit, though divinen
reading/writing, armorer, blind-fighting, bowyerlfletcher, rarely do. Pdoniciata CUI alm be Militante..
endurance, navigation, net snarei, iurvival, tracking, and
weaponnmithing. h a and N u i d h i The Militant kit i i f o d in the
Equipmanti A Myrmidon can buy whatever quipment city-rtaten, the Savage Baronies (though rare in Nuvrez),
is desired, but some militpry units might require that some- Robrenn, Eusdria, Renardy, and Herath. It is an uncommon
thingspecific be owned. kit in Bellayne. Tortlea are never Militanti, whde only rare
S p e d Eenefitsi The -idon geta a free weapon rpe- Militants teach their dt.ib to gobliiida, fearing t h m r U
cialidon when created, chosen from one of the following: might be turned lack on them.
battle axe, any bow, heavy or light crosnbow, wheellock
horse piatol. any lance, any p o l e m , apear, or any sword. Requirementii A Militant can come from any 8oaial
The specialization reflects the typc of unit for which the clans, and is not reatricted to a particulan gender or align-
-idon haa trained. ment. However, most Militant wizard8 are Inwfd, and they
Myrmidons ala0 (usually) have an employer, with specific are considered middle or upper c h i when aerving with an
benefits determined by the DM. If part of a standing army, q.A Militant wizard must have a Strengrh of at lcut 13.
a character might get free room and board, and could be
immune to civilianprcnecution. R&I A Militant wizard in a respected-aometlnei honored
Special Hindnsg.iThe Myrmidon'n employer can alno or feared-member oE society. The charactev can be a
be a hindrance, by making demand upon the character. [email protected] battler who e n j v violence, or a heroic noldier
The Myrmidon must follow the orders of nuperior officen who take8 liven only when neceasPry.
or rink c o u r t - d .
A Mynnidon nL0 gains a reputation. Such chpractenare The character might become an adventurer to earn extra
rememberedfor their milimy demeanorand disciplined man- money (perhaps to build an army), to PUN= pewnalgods,
ner, and can be easily recognized and dercribed, poniibly or to study the tighting techniquea ofother cultwen. Thollgh
mpk;np it cay for an enemy to identify and follow them. Not Militants are often pact of an artqy, they can &o belong to a
mercenary group, or t.kcjobson a freelance h.i.
However, thene characters have a militmy background.
They make p o d leaden, but &o understand how to follow
the orders of a respected commander. Militant. prefer
action to inaction. combat to negotiation, and are u s u d y
nurpicioru of schdarr, philolophero, and bureaucrats.
Chm Modifidonor An explained under weapon profi-
ciencier, a Militant has an extended range of available Pro6cienciew A Miliit'rboacu proficien-
weapons. A Militant w i d can allo learn the twoweapon cier are mdwance and militauy tactics. The followinguc
fighting style; nee Chapter 4 for details. recommended:ancienthii.rory (spcifiully erilibry), paiaul
Militants prefer magical schoolsthat give a good selection handling, direction sense. riding ( M - b a d ) , mrimaiq,
of offensive and defensive spells. such as abjuration, alter- weather me,redinghvrkg, bli-fighdry, .ahh-
ation, conjurationtsummoning, invocation/evocation,and p a p s . set snares, and trwking. The milit.at can trlt,wm-
necromancy. Miliant elementalist. are often pyromancers nor , p u pproficiendea without axtn CO.~.
Equipmen$: The Militant h u no 8pecial rwnictions or
(belementalists),though some specialize in the elemental benetit8 in regardtoequipment.
Spacial b f i b m Besida the benefits lilted above, the
tchools of water and earth. Characters of thiu kit cannot Militant character gains ur -a 1 bit point per leva.Thin
specialize in illusion or enchantmentlchann, and moat con- rslkct.the pemoni milimy training.
sider those schwlr relatively useless in combat. Few Mili- sped E u m b w a l Other than t h a c l i i u& "clru
tants tpecialize in greater dirination, though they recognize Modifications," the Militant hu no special hindr~ces.
the school's importance in m o n n h c e .
Wed& Optionbr The churcter rafeitmsr.ndud .M-
Militant rpeci&ts have greater restrictions on the spells ing fund..
available to them. SpecioLista and their forbidden schools
are listed below: +
Ab/;. illusion, alteration, greater divination. The Myetic is a chuactor who values phdomphy, ut,ad
C u y w alteration,greaterdivination,i n v o c a t i o d d o n .
scholarship, and uses them for d f 4 i g h t e n m e n t . The
Encbantcr: invocationlevocation, necromancy, greater character mngio,(ormental porvcn) .aduhmtmkgu
divination.
&bur: conjuratwdsummoning,abjuration. roads to knowledge. &nerdy peaceful and contamp&ive,
the m i c is uncommon on the S a w C O r r t , &can be
Inwkrr: illusion,enchantmentlchwm,c o n j u r M s m o n i n g . found in many different I d a .
Nmumnerr:enchmtmentlchum. illusion,alteration.
ThanmutcF:necromancy,abjuration, conjuratiod8ummoning. Chnctor CLU, M a p s , abjure-, divinm,en,-
illusionists, tranimuters, urd (rarely) wild mapm CUI be
Aeromanccr (air ekmcntalwt): elemental earth, elemental Mystic#, an can psioniclt..
water.
R r r d Natkmdlti8m1A h Mydcs Mfound in the
GdpmMcer (&b eLmn&t): elemental air, elemental fire. soVa#e Baronies of ou#ohmdsumg6m, in rkbync urd
ekemental &e, elemental0;.
Hyamnanur (w&r&&t):
&romancer (fim cktnentalwt): elemental water, elemental Herath, and among tortles. &Minoids can new become
Mynticu.
earth. Raq&ewatsr The Mystic can come from any m c i d
c h r . can be of either gender, and cur have any +matt.
In addition, Militant wizards are treated as if their Intelli- However, evil Myrtici are rare, and mort &&ca tend
gence were 2 points lower than it actudly is, in regard to mwt haw e Wbdmnof
spell level attainable, chance to learn spells, maximum num- toward law and neutrality. A
ber of spells per level, and spell immunity, PI detailed on
13or more.
T a b 4: Inbelligenw, in Chapter 1of the PHB. Mer Mystics are thoughtful and intmrpectiVe, .adsnpY
nothing more than .p.ndiag long houm coeCemp&iallthe
A Militant psionicist's p+nary discipline must be either mylteriea of the univarv h d attemptingto baolnenwxe in
Psychokinesia (for long-range attack) or Paychometabolism touA with thar inner oshru. Thc My.& u not-n
(for those preferring hand-to-hand combat). Psychoporta- a
tion is good for quick travel (and escape) of smdi unitr,
-student of religion or philaophy, but i n d seeks aware-A *tic han chosen the
Clairsentience for monnaisurnce, and Telepathy for spying
nesi that can be found &inMwIy.
out enemy plans. Because of the time Militant psionicista of rna&(ap.ionia) u tbb
key to s P ; ; d awwIIou. *ti- b a k &at 4casting
spend on martial pursuita, they gain one less PSP per level of a ~ p e Ua use ofapeionic power, ewh.csu;Ur;On&anew
technique, brhp tkcm clav to ultinubcawaremu.
than normal (including at 1st level); after the PSPs are Many people consider a Myntic to be a lluy eccentric
with no uwfulpurpeu. Mors enlighhwd nrlrum (amp-
determinedfor the new level, subtract 1PSP. c ; l b the ~ ' r i n rM, OW whom the kit is plentiful)
the *tic u a Keker of auk.
Weapon Pmficienciesr The Militant wizard (but not The Mystic avoids combat, but will protect oomr.de..
psioniciat) meivei one bonua Weapon protiiiency dot. Mil- H-r, on& m the mod sxtnme circunut~ceawill
itantu must choose their weapon proticienciea from the fol- tics a life, killing only to p r o t e a h i r own li,or that
lowing: battle axe, any bow, any crossbow, dpgger, javelin,
quarterstaff, &in#. spear, any word, and war hnnuner. of a companion.
Characters who abandon the Militant kit alm sive up the
weapons forbidden to wizardu (or psionicists) of their cul-
ture. Three experience levels after giving up the weapons,
they losethe proficienciesentirely.
c1.uiuoaut'mII N o nchooia w barred ftom the Mys-
tic wiurd, but the chchaer a- npelln designed to ca-
damage,nuch Mthose from the necromancy, iavocrtion/evo-
cation, ud conjuratiodamhnmm'ng nchools.
A Myltic pionidst prefsn the Tekpathy discipline above
all othm, t h t q h Clairsbnricnceis favored M well. Metap-
sionics are learned an loon Mis pactid,while Psych&', he-
s t t &e L*t diuciptinelearned.
Wmpon ProfkfcbndasrThe character has the normal
range of weapon dhoices allowed to the class and culture.
The Mystic seldom curie6 m m than one weapon. if that.
and prckrs blunt weapons.
NomrponProtkimdar The Mystic receives a bonun
prdiciency in astrologyand spellcraft.Recommen
cienciea indude egiculture, artistic ability, carpeht
quette, languages (ancient and modem), pottery,
rtoncmuonry, weaving, ancient or local history, herbalism,
+on, and rudingJw&ing.
Eqdpmentr The Mystic never buys more than one, or
ponnibly two, weapons. Other than this, the character h u
no special quipment restrictions.
'Specid Banefami Once per week, Mystics can trane
form their connciousnesn into a dpiritform, leaving their
physical body behind. The spitit form lookn like a mist in
the n h a p e ofthe Myltic. Through it, the character can see
and hear, but cannot attack. rpeak, c a d spetis, or use
pnionic powers. The form can, however, fly at a movement
rate of 24 (maneuverabilityclass B) and can palm through
the tinieat crack. Although the spirit form is idlnerable
to all attack types, &pf m& causes it to inrtnnfly return
to the body. otector of nature, a
pemon at peace with animala and among p h t a . Thew indi-
Unlm dirpekd, a spirit form can remain away ffom its viduds hever willin&lyh& natmi, aAd are a n e e d ' b y
body for up to 24 honrr, during which time the body t h o r who do. They rtrive to& otlirn how to libe in'*
remainn comatole, and in aubject to all regular attacks, nuf-
w,feMg dunsgedeornuUy. While out of thd it can lhove +ij, with nature, which might cause friction ill 'mome
u G Mallowed by itn movement rate,but -not PAM from &enbring put;.#.k w o k i i iunroyV advdnturei to view
the u m e plane of exirtence. Once the spitit form return6
natutal wonden;'though som&leire th& tiones to fiehi
(which it does instantly and automaticallyi t the end of 24 +init thoae who #;odd huin natuf.l Watk,hunt ail-
d m r o hainctim,'or &e-,ofFehd t R & h dflutuk.
houn if it hu not @oneso sooner), the Mystic reviver and ,1Aesecharacten r e m q i c , pionici, and &ti&'&
cannot UK the fom for anbther week.
To usethe abThy, the Mptic must dimpiy concentratefor C&' MpUt. Of lU#3J?6'S &lld IfhCd. '$O'thCy& kkw
of those d th such abaiea. H d r ; ~
1 round. that the a bilitir are not usedi n u nn ah d w fty dmd far
Specid Hindrancemi A Mystic must meditate for two
unn&al purpbia;. rjh.I
conaecutive houra i t the same time each day. When the W k a n l hatb dl'fohs of unded, and *riH i m c k them
character is created, the player decides upon the exbt h e before Othet~opPOmntlT. hey!ight'il&mil uhukifthrut-
period to be used each day; after that, the time cannot be
e n d , aiid &a& hunting Ear f a d (bht not t0I'bpoI-t). "
changed. If a Mystic neglect6 to (& cannot) mediiute, or is CbnDIOdfftiutbnn A.iaintiahed; a Wvkin WiahVi!
interrupted more than once during meditation (for a total of
more than one minute), on the following day the c h h t e r restricted in spell neIbefioriL and can choose only th$k
i+lt'inthe " r h d " OFiutud.Thio hcl& ah Ipiillrdfthe
can cut only the number of mpells altowe&to a wizard of d1aient.l schoolkof &; e&, b,anddater (Mdairihdin
one level lower than the Myltic'n own. For psionicintn; the
penalty in that they repin PSPr equal to the number they the Tomc ofMiqic;,ifrhat IOtlrCe is unhvaitkblc, spellsthat
had one level earlier. umethose elemehtn are allowed). Note &it laany of these
spells must be used with caution, so an to,not permanendy
Wealth Optionmi The mystic cares little for material harm the environment. Other npeHs aogilablo (rtlated to
wealth, and receives only (ld4+1)x5Bp in ststring funds.
I
Wokan are animal lore. herbaliim, and iurvivd- Recom-
mended profidenciei include .gricuJtum, animal handlii.
animal training, direction iensc, fire-building, fiihing,
CF leathemorkin& pottery,weather ienrc. healing (regular
. .'z-2
.4 and veterinuy); act pnarei, hunting, d-tr&ng
~ ,othorwoL.niw
Hermit Wokrni can tpLe
forbidden that prokiency at 1st level.
Equipment: Wokan piionicisti CUI u i e only leather,
;,);, padded,or hide armor, and wooden &Ida. Wokmi do not
7,,, we complex rwlr or made ofworked marl.
Beiides their bonui proficieaciea,
Sp*fW Berufitir
Wokani have the benefit of be& &le to craft enchanted
item at a relatively low level A WokOD of 6th)eve1
or higher g&i a ipdd e&an &em ab*, much
like the 6th-level wizard rpell, but with a few
odjuitrnentr.
Wokani believe that all natural objecti have
inherentmagicel power. C h q u e n & , d enchanted
i t e m d e by them mu& be created +g natural
materiala; they enchant the item by drawing the
innate magic from it. Thui, an item ihould have
a limb from a tree that hu been itruck by Iihtning
u the perfect romponent for a WMad.$?bt*, whilc
eaonbtamnld(foofrftuhramt tigyhpet boef wed to make arbyofnwmmal
mammalonly). The item to be
enchanted &odd be worked Mlinl.Mpossible; the
more naturalit. condition, the better.
in the
P'- e nTrhbeacnhta~irhacmt4er endchelaunitpsftihoen,itbeumt M CXpLined
a nnt-
must work in
urd environment,never a laboratny.and no other sp&
need be
ianncilmudaelst,hpellaant-tlse.vwelesaptehlelsr,cblaingghetd,ed&afrtikdnfaemss.&. qandbsbot,fmortah)- ud.C cwt into the irteecmeivIen4additlido1n0,p+w4 r n r u ~ c yneed not be
b g e d item charges, but can be
recharged with another ceremov. (The DM can similarly
hg, and dp&r climb; the 2nd-level apells alterdeg conthud rutrict the function of otheritem an neenuappropristc.)
ligbt, a a r k n u 15' ra&i, gli&dwt, and dummon dwarm; the Note that a paioniciat can rLo make-,i but the pmceu
creates paionicdly empowered itema, and is bued on the
3rd-level ipella .$?btning bolt and pmtectwnfmm twrmaltpii-
d&; the 4th-level spellsba&&&
te&, w n w t p b , plant Metapsionic science, empower. The paionicut must apend
garnowdtgb,mpowlytmb [email protected]~ol~ytmthwoerp6hthd-el&evtehlesp5etlhls-lcebvaelhrkpbetb- the time rsquired, butneed not apend PSPs. An item can be
ning and conjm anima&; the 7th-level spells cbarm phntd, given only one piionic power in thi nunner.
S1#Etl- :Wokani are unuaual outride of their
mwr&gmv&, and d&w d;the 8th-level speb mw cbarm homeland, receiving +2 penalty to reaction rolls in foreign
and pofymorpb any dj't; and the 9th-level spell d h p cbange.
T h e A m b k Aauentuw and OrientalAawntuw boob contain mgiona.
The Wokan doer not use material spell components, and
other elemental spellsthat can be adapted to this setting. doer not learn spell8 in the normal manner. Though this
A Wokan paionidat must have Paychometabolii an a pri- might Murid like a benefit, it can CBUK some problem.
mary discipline. Often taken next are Telepathy and Psy- Fint, the character must haw a fetieh. Th; is a a d nat-
choportation.Many p.ycbokineticand Mctpprionictalents are
felt to be unnaturalsap a t care must betakenintheiruae. ural item, such M an amulet compoaed of bit. of bone, fur,
wood, and feathers, or a amall leather bag containing the
Weapon Profmienciei: Hermit Wokani are limited to
standard m a p weapons, an hated in the PHB.TribalWokani rame, plus perhapa dirt. A pine cone wrapped with fur
could be appropriate. an could a birdi claw with feathers
are limited to weapons of their cultures. Wokani can use attached by leather strip;. The item must be somewhat
weapons made from atone. bone, or wood, but no other
unusual. and the Wokan must have it to cast a p e b . It is the
materials. only material component the Wqkan ever needs for spell
Nonweapon Proficienciea: Bonus proficiencies for the casting, and it in needed for c w y spell. If the fetish is lwt or
deatmyd a new one muit be created, a procew that taker a Fightkg Monks munt have a Dexterityof at leut 12
few h o r n each day for a week. Duringthat week, the char- Role: Thew chrractok are philwophiadud rcholu
acter can cant no spellr. devoted to df-colightwmcnt. While wconwd
p n u b b . t h c i r philomphy to others, Fightha Monks
Second,the charactermuit learn and memorize spebdif- teach it.to thw who u k to learn. They,kowmoa.tbic
ferently from other wizarde. Spells mwt be learacd from e,religious ceremoniei, and canconductthorn if nadad.
another Wokan, and are nevqr written down. Instead, the Some Fi+ Mods n m r b v e their mer
character leanu a specid dance and chant fmm the Wokan
mentor. To memorize the spell, the Wokan must perform the ~.~urwand~who.#.l.~l8dgam
dance and voice the chant. Thui, whik other wizerd.would crrrbcloE,theisrd.Thcy~ntuhtothh.mgyr-
opend their morning. reading from apellbooka, the Wokan
m u t go off to dance and chant for weral minutea. Mem- tsriestopsuontheirknowkdgetoothsrrdtbrirods.
riEation times, rest required, and all learning reitriftions A Pihting Monk's order providea.stab&ty a d acta
b e d on I n t e U i e apply norm&. place of formal learniug, The rplit becaurc.o€senders,
abiolute, and FiRhting Monkr &e VOWof cdibroy
A Wokan psi0niCi.t muat dw,haw a fetish in order to use Fcmaloi we not dowed i m d e IWIU~W~mWas &,,
p i & powen. T h w charactenwain PSPi at the n o d femde m o n u w i u , except inemergmcieh a d then for
rate during moat actiden, but regain none while deeping. lit& time .s.F i b l e , wi&out..ocew to more than Q
To get the recovery rqte for sleeping (12 PSPs per hour), two rooms. Male and female brmchercommunic.t
the chwactcr must either UPC the rejuvenation nonweapon
proficiency or spend the time chanting and dancing. sending mensengerc, who lwve M d s
Wultb O p t i o W~ o~kani receive no starting fundr. other monastery withwt p i n g in Becou
Monka are often uncomfortable around ~membar.sQ
Priests of the Savage coolt are often involved in the art of oppolite w.
war, minirtering to the needs of soldiers and warrioro. .chuModieutloaa: Them chuacten'erenot
Overviewsof the priert kite follow. or modified in any way,except that they u e ab
with twow e a p o ~(we Chapter 4).
FigbtingMonb belong to orders devoted to opiritual Wupmp.Ro5ahcieu The Fiihting,Modk.mcmvm
enlightenment through physical dmipline. They learn bonus weapon proficiency rbts, wbich must be I
lpecLlunarmedfight;ae styles. -unarmed C0mb.t rtyles. One munt be rusdto
tidutl (toraata), and t he o b rordwot em~usttb&.guL.%.
Wur Priodtd are the clerics of I m m o d i devoted to war ire in martial artus p u noh,
and strife. They are mercenariei found with moat of the for detaib on unarmed.combat ity1cl.b T h e e
choohe.0nl.yUdgwnm' gwuponl ( i u c b g w n p i m r Oluc
anniea of the Savage Coolt. are both bladgwniw m d piercing). Not aU~eyoopFafi.
Wcbm.wtm are dru;d.dedicated to protecting arachnid ciency dots mfl.t be .pent dt kst level!. they can be dand
life. No type ofpriert other than a druid can take t h i kit. usedatanylsvel , '8:
profidauc*n.TheF
Fi$htingMod tUlebl;le; md d a n b g M bonw P d C b
The Fighting Monk aeeka ipiritud enlightenment through is.required to takah t i c ab*
phyaicd discipline. Tbjs include4 I.uning a a p i d fighting gion, herbalism, and hdmg,ur,recommh
style. but consisto mainly of long houri of labor, exercile, Monka CM purchslo pruficiencieiSrom aqy and .U
meditation in uncomfortable p i t i o m , and practice. These a d d o notwmxtrr a h -.do
E q u i p a m t i Thew characterr tdce 4 HOW of p o w
charactor.lean the art of combat, but ordturily uw it only They cannot wear m o r , and.can own or+ what h y
for ielf-defense. They learn religion priinarily for nelf- caw*
enlightenment, rather than to preash to othen. Orderi of
Fighting Monka am found only in Bellyme. Sp.Ei.1 &n.fituOther than thaw detailed undet pmfi-
cienciu, the c h e e r hu no ~pecialibesafiir.
Chumtar CLu:Onlyclericow take thin kit. Special IIisdtuKvs: Fighting h l u M.subject to t
commandi of their . o r W r &en, and muat faithti& per-
Ruoes and Natioditiesi People living in Bellayne can form whatever service u required of b.Alm, they mwt,
become Fihting Monks. No race u refuaed admittance into
8 p d at l e u t two houri e r h day in meditation and mame
order, but the majority are rakaata, elven, and tortlcs. lort ofphpicd exercile.
Requirements: Characters can come from any social ,
dais, but give up iuch things when they take the kit, A W d t h Option= The Fighting Nonk mceives t b a s t e
Fighting Monk cannot be chaotic, and is rareb evil. All dard starting money, bua u n n o t retain mom than 1 gpiin
memben of a prrticukardcr have the name dignmant, and coinr rftsr +ng equipment (ace "Eg~pment,"above)..
there is one order for each dlowable diinment goth Money unspent beyond 1gp must be 6ven to thehecbuac-
d e n are permitted-all o r d m have hthw a d Siiten-
but they live in separatemonaateries,often miles apart.
war R i a ful c h a r d r fights to reitore order; a chaotic one p w o
Thew charactem are cleric6 of battle.on the Savage coP.t, Wt.entropyand
they are relatively common among nationn that maintain worthy -,
armed fomeir War Prieata are devoted to war, and often to dinmay. S i b ,a goodWU Rint For a
Immortalswho encourage it. They carry the faith to 801-
diem,fightingbelide them. whileen eviloneenjoys hutiugthe aneqf.
CLU ModHhtimt The War Prieit h u major accen to
These clerics have better than average combat skills, the opherea of all, combat, h e d i g , and protection, minor
including a militnay background, and they adminiiter to the accesi to divination, pudi.n, necromantic, and iun. If the
body u well u the BOULTo them, war ia a way to honor aelf, ZVIMojdfagk is u d , War Prieab ala0 have major
nation, and the Immortale. the spheres of travelern and war. to
War Priest. w ~ipectedby thore who value war, feared Even though there characten promote war, they do not
by thow who latk more peaceful dutiona to problem. neceuuily have to support an Immortal who dcer Instead,
the War Priest nupporta any &own 1mmort.l ty r;Bhtingin
Ch.ncraCLUt Only clerics can be War Priests. that Immortal'n name. The character can be a cleric of any
ImmortnJ except those opecifi& o p p o d to war. In &-
%CN d Nationdidmi War Prientn are common in the tion to their other sphene, WdRieat characterncan chavs
minor acceaa to one of the following spheres, and should
city-states, the Savyre Baroniea, Robrenn, and Eusdria. chooae the one moot appropriate for their alignment or
hmorral: elemental air,elemental e&, elemend Fue,ale*
Though prieitn are rare in Herath, aome of them are War mental water, animal, plant, sun, thought, time, weathet:
Prieata, u are aome clericn among Y u i and Yazak gobli- law, or c h m .
noida. Torrlea are never War Priest.. Weapon Roficimnciwt If a War Prieat'a Rnm0rtrl.ba
favored weapon, the cleric must take proficiency for that
LbquLan.mmt The War Prieit can come from any aocial weapon an a "weapon of choice." All other weapon choicu
background and the kit in open to both gender. and any are restricted to blunt, bludgeoning weaponn. If the deity
d i m e n t . War Prieats who nerve with ntanding armies tend han no preferred weapon, the cleric is limited to the o h -
toward law, while freelancera are often chaotic. A War
Prieit must have a Strength of at leut 12. dard nelection of blunt, bludgeoning ' w e n p a , and cafi
nelect one aa a weapon of choice. With the weapon of
&lei To War Prieatn, the act ofwnr (and by extenaion, choice, the character lights with a warrior'n THACO;
combat ofany kind) in a holy endeavor. Anyone uninvolved Nonweqon RoBdench The character meivn bonus
with war in virtually inaignificant to the charactern, and proficiencies in r e l i o n and military tactics. Recometended
even the nation they nerve in secondary in importance to proficiencies include ancient hi- (apecificdy military
battle itself. A War Prieat ministernto wuriom fir&, noldien e),hirtory), endurance, intimidation, land-bued ridiq (except
of other -a econd, other combatant. third, noncombat- for lizard kin), airborne riding (for nhazdu UmOTrr,
anti only when trying to convert them, and cowardn and
deserters not at all. The character in demanding of compan- blind-lighting,weaponnmithily,eyimering,he- (regu-
ions, often p u d n g them into battle, froquendy rhowing din- Iar and veterinary), and ipellcraft. Goblinoid War Print.
mpect for thow who avoid combat. But while War Prient. receive military hutory ody for their own tribe,unlesi edu-
enjoy battle, they dno recognize the value ofa gwd plan. cated in another land. A War Prieit can take proficiencien
A War Print can be devoted toany Immortal, or group of &om the warrior p u p without extra cwt.
I m m o d , except tho^ n p a c i f i e opposed to war or com- Equipm.ntt Ww Prieat.have no puticular reatrictiona or
bat. The characten support the I m m o d i through war, in allowanmn for m o r or equipment, except that goblin&
War Priestn are limitedto equipment avrjl.ble to their tribe.
an almost constant crusade for their particular faith. War Spacial h & t Other than abilitien de& under the
proficiencyhermjinge, the War %est hna no special benefits.
Prient. are lesa concerned with preaching to the converted Specid Hindranceit ,Benidei the limited nelelection of
than with bringing enlightenment to the unbeliever. They spelln. the War Priest h u no npecid hindrances.
can be very determined (necking combat to force the faith Wealth Optionst The War Prient han etandard atarting
on others), or more relaxed (waiting for othern to ask for funds.
aid, then preaching to companionn during a battle).
Webmutu
T h e War Priest determiner when the time is right to fiiht The Webmantcr druid in dedicated to the protection and fon-
tering d i n d o i d and arachnid life, wherever it is foand. A
in support of a paiticulu Immortal (though for Immortaln Webmuter alwayn comen from Herath. That n.ationi fomtn
ofwar,this can be almost any time). They prepare troops hacvehvnurmreerrouCnLinNKicOtnnalynda spiders, both normal and giant.
with inspirational nermoni, fwht alongside them, and nup- druid can be a Webmaster.
port the idea that dying in the wrvice of an Immortal bring8 Ruw and Nation&&: A Webmuter in alway a native
favor. War Prieit. can become adventurers at the bequest of of Herath.
their Immortala, and often join a group on a quest to recover
sacred itemn. to acout enemy forces, to punish or preach to
unbeliwern, or simply to gain fun& to support the church.
In the cyen ofthe church, the War Prient i i especially nuited
to adventuring chow.
Alignment Lvery importantto a War Priesti ON. A law-
Rcquirsmonta: Webmutern can be of either gender. Like check8 for agriculture;,animal training, and animal lore,
other druids, they have a true neutral alignment, and they when that knowledge ia hpplied to insects or ulchnidr. Th
muat meet the ability score requirementn of the druid claan. churcter can iko apply.niwltnining to +wnpidern.
A Webmuter uaually comen from the upper nocial CIMWJ
and io well respectedin Hcrath. S p e d Hindrmcemr The'Webmuter's mLWIf&&bb~
d p d witb anha&, m d dumnton animab d p e h dlow d m u
Roler Webmuters tend to be enigmatic and mysterious. nication with or nummoning of only n d , o rgiant inssd
Many attempt to inntillinsectoid virtuea in their followern- or spiders. The'character receiveitr a +3penalty on-pfofi
nuch PI patience, hard work, and clone cooperation. Web-
mantern often take on the patient, deadly personan of ciency checkn when using animal lore, a n i d brimkg, .Si
pndator arachnidsor insects, such as spidern or drpgonflien,
ruthlcnnly hunting down (or lying in wait to trapythc ene- cukure, and other animal proficiencier on creamten othe
mies of the druidic order. A Webmaater's @we is us*aUy in thrn i n m u and arachaidd.
a web-laden section of the foreeta of Hernth. For informa.
tion on the Webmaater'n role in Herathian culture, refer to W d t h 0ptiim.c Webmaaten receive ntandard I&.$
Chapter 6 of the Lzd dtbe S a w h t b o k . fund..
A Webmaster might go adventuring to preach the doc- Tbfwr . ,. , ",, ,
trine of protection of innect. and arachnidn to othcm, to gain . ,. , , 1,). . ! , .. , ,
a wider world view, or to track down an enemy. In a group,
Webmutern are hnrd worken, and very supportive. They An with thieves ofother Lndn, th- of the & v w Cout M
are generally fine (and patient) strategista, and enjoy rogues,people who usually live of€the work df othan, by
ambwhes and weil-placed trapn. Ctcpting or connivingtheir way thmugh lib.However.nuny
thieve. of the Savage Canat M involved with organhatiom
CLU Modi6dom1The W e b m t e r of Herath is a for-
other than guilda, auch u m i e l , government., m d hi&.
est druid, an dencribed in the PHB.With the exceptions
Following are overviews of the mmt common thief kitl of
noted here and under "Special Benefits" and "Special Hin- the region.
drances," the Webmaster haa the same abilities aa a stan-
dard druid. Banaitd are unually thugs who group together to rob
Upon reaching 7th level, the druid gains the ability to Pa&.
Scoutd are trailblnzera and army membtn who uae their
shapechange into n giant spider once per day. This shape skilln to C X D ~ Oan~d o h w e .
takea the place of one of the forms normal to druids (bird,
mammal, or reptile; player's choice). The character can still The bandit is a robber who accoItn panicrsby on lodub
usume only t h m forma per day.
mads. Bandita genet'dly group togwhet fdr effectiveness,
W e q o n F'roficionciew Webmaatern have the atandard netting up a camp in the wilderness, away from law
enforcera. They are not uncommon on the Snvagc Cosrt.
druidic weapon restrictions, except thnt they are also Some rn rnfugees of w m , &ern ntmply opportrmistr will-
allowed proficiency in h o , bolan, and acythe. They prefer irig to prey on .the4.
IMOaOci,mitar, and qunrtentrff.
CkamctmC h i Only thieven can take the Bandit kit.
Nonweapon Proficienciear A Webmaster character h c e i md Nctionditiemr Banditr are found in every
receives a bonua proficiency in rope use, and is required to
take the net mares pdciency. Recommended pdicicnciier region of the Savagt Canat.
include agriculture, animal training, healing (especially vet-
erinary), herbaliam, animal lore, endurance, survival Rcquirementm The bandit can come from any noeial
(font.), tracking, and wcaponsmithing(crude). clasn, but since the prohasion in more brutal urdlens
Equipmsntr The Webmartar han the n o d druidic limita thrilling than othcr thieving profeaaions, upper du bnnditn
on armor and equipment. The druidi initial dlotment of
money must be spent when the character is created, or it in are rare (usually only thole who have been diaenfran-
lost. c h i d ) . Bandit.can be ofany alignment, but Invfut*ndevil
uc common.Mort Badit. are d e , but there is no gender
Spacial Bendbr The Webmuter receives a +4bonun to restriction. A Bandit must have a minimum acorn of 10 in
wving throw againat poinonous stings or bites of n o d or both Strength and Constitution.
giant insect8 or arachnids. The character can aho pass
humlesnly through web. of all aorta, includiry thone created Role1 Bandits 1st often viciwa ehurcters, desperate,
by the web apell. cuaning, and cruel. They ate pmne to fyht or even betray
each other, but two things keep them k n d in bwp.:the
In addition, when the Webmuter cutn a d u m &e&, utter neceasity of cooperation in order toahrvive'the perils
giant &at, creeping horn, or imectplagu apell, the effecta of the wilderness, and the men& of whoever h u h e
occur an if the Webmuter were three levels h&er than hi0 leader amongthem by force urd cunning.
or her actual level.
Bandits do not joih guildn, and urnally operate by num-
Finally, the Webmanter gain3 a -4 bonus to proficiency bers and force of a r m , rather than by aubtlcty. They a n
rough folk, often the subject of bounties, and with a history
ofbreaking other lnws than junt thme againnt thievery,
Some bandimjoin adventuringp u p a because they want scout
to move @wayfrom the lawbre&ing activitiei of their Eel- The Scout in an independent rogue who opera*. p-JY
in a wiMernera setting. One might nay that Ssouwareto
lowr, and b e w u M adventuring party offers the name regular thieves M ranger. are to fightera-but scoutl mu-
galuljydaev.o,sidpitehae, ntrict ethics of the rawer c h , They work u
“ d e t y in numben” u a c o q u y r of bm&. In an &en- md doteura. a Scout might
turiry group, they tend to be the once who push for direct If un&&
+ i d confrontation.
&dit characters often try to eetablish who is ntrongeat turn Mpoachbgor hunting Minu& for bOu4tk. h u t . we
and weakmt in 4 group. A character might do this by order- oftene m p b d by armiei of the Savaga t h a t , but ccm plro
ing or bvllying others to dincover if they obey, and mkht work for privam ecrtcrprise or for themmlvea, with work for
start a fwht to diacover who is “toughest.”Hpwever, Ban- hire.
dim who have established their p b in a.gmup can be the
picture of cooperation, and readily go along with group Chuw+aCLVI Only thieven can &e the Scout b.
b o a and Natioo.1itio.i Scout. are found in every
decidons (thought they might revert to form if another d m and land of &e Savaga Cout. A thief of ryy rncn can
p u p member shown weaknean).
take the Scout kit, It is u r d extensively b j t~he tribes of tb.
C h s Modificationmi Banditn uaually ntress rogue skills Savqe t h a t . Lupina areacknowledgsd u the kScouw
most useful for,rcouting,wch M&bkq walls (truwclirnb- in the uu.
ing, in the Bandit’s case), moving ailently, and hiding in IbgrkuuntliThe Scout can atart with any idclaw,
ahadowr. The normal rogue &ii for finding and reqoving
thp+ mrmbcn dthe upper c b e a r d y bcco~wScouts.
trapn applies to UIOIY. and pita in the Bandit’. cue, and can Either gender io allowed. A Scout crr)be ofany d i n t ,
be uied for ambuah. Theie charactera avoid rogue akillr
but evil Scout. arc 1-1 wmmon than thore o€srutral or
uneful primarily in urban settinga. They receive the follow- good alignment. The Scout has no ability more regpire-
ing bonuses and penalties to thieving abilities: pick pocket+,
-6%; find and remove traps, +lo%;move ailently, +6% for menta.
Rolu On the whole, the scout is a pcd dad mom reUatde
wildernan settinga only; hide in shadows, +6%; climb w d i , than thieves in general-bpt m e h a w a, cunhlreu &eak
-6% and readI.peururcs,-6%. that d e n them dongerour and unpredictable. Scouteare
Weapon Proficienciew The Bandit receivei a free typically rugged individudiats, practical and serieur;
weapon proficiency in knife. They prefer heavy bludgeon- manner maken them endearing to daring adventurera.
ing weapons. and one of the Bandit’s initial weapon profi-
ciency doti must be chwen from the following: fld,mace, tBaelkcavueireytlhioeilre,;ptrhoefeysusieomn dtoemuaaendth. esiirlesntceea,ltShc~okuti4lltrdemndontot
morning tu, and war hammer. The other initial dot, md dl qnconacioudy.
A Scout might join an adverrturi~;groupwith.,afew
other slot.,can be npcnt on the weaponr no+ allowed
to thiaru.
Noawu~plrprofici.nciur Bandit. receive a bonw pmfi- f r i e d from a rrrilituyorguktioa. join.&mnturcn
f h t becauw t h e p r e hired, then some decide to join the
ciency in survival (for an appropriate terrain). The followv
groupfd’time,to w k excitementwith kindnd lode.
ing proficienciei are recommended: alertness, animal Most Scouts who turn adventurer,bave.putin some.tlne
handling, animal noise, animal trai*, Sre-building, intim- with the military,qr with a warrior W,iathe mwe moyle
idation, looting, riding, rope use, aet mami, ~wimminga, nd loa*tiea Thm who have a put 4of b d i n g dw law
uHuIly give up iuch activitica when phsv beginadventuring,
wupolurpithing (crude).
Equipqent: A Bandit ihould be well equipped for wilder-
ncii sqrvival. vital item include prov*ionr, backpack and Scoutr ,werespectdby thore who value *heir rervicer.
Shoe they hsve L well-demmsd reputotiob for indepen-
pouches, flint and ateel, tinder, a blanket, and a knife. Other dence, they are usually well tseated,,with good pay. IEr
u d d itam include thingr for scouting and ai51Jing. Ban-
Scout feels an rdvonturing party dma .nQthave e n w h
dits rarely buy (or qtcal) aq~thingof a frivolous nature. reapect for the &cei rendend, the character willlikely
They do not like to c q much, only itemswith a definite leave theg ~ ~ t l p .
purpoae.
Specid Bewfau Bscwre of their talent at rmburhcs, in Scout characten prefer clothing that blends with the wr.
a wilderness rettkg Bandit. inflict a -1 penalty to oppo- roundme. They care littla about appwancp, but ment
nent.’ surpriseroUa. bathe regularly so they do not build wenti lor doga.and
other trackento follow.
Specid Hbdrancea~Theae character. arc viewed-not
inaccurately--on outcanti, ruffianr, and crude robbera. C b MdsWa*omI Scouts p k e r itsdth sk& ruch ss
moving iilently and hiding in lhadowa (gaining a +IO%
They receive a +2 penaltyto reaction rolls from nonbandits. bonus tec r h in wildemeurminga). M wall M obaenvation
Wealth Option.: A Bandit receivei standard atw+g
fund.. ddh likedetectingnoire. Skill at climbingwdla is also quite
useful to a h u t .
Thenc characters seldom picka pocketa, ao they have no
need for the ikill. They u i d l y uonaider opening locked
doors a job for someone &e, but might add a few points to HWdd
the lockpicking ski11when joining an adventuring group. The Heralds of Bellayne are well k n o w thrqugbout the
(Goblinoid scout. cannot add points to their lackpicking Savage Chant as bringers of new. and brokerr of i n b .
&ilulntil reaching2nd level.) tion. &st Heralds belong to guild1 (all hudquwtcred in
Bellayne), while a few are “frechcers”who work for hue
In an urban aetting, the Scout auffera a -6% penalty to all
thieving ILiLL.
Weapon Proficiencieu Scouts from civilized areas can
use the weapons n o d y permitted to thieves. Goblimoids
are restricted to the weapons of their rerpective cultures at
1st level, but can use weapons available to standard thieves
after that.
Nonweapon Rofidendclr The Scout’s bonus profiqirn-
cies are alertness, direction sense, and tracking. Recom-
mended skills are animal handling, animal training, animal
lore, animal noise, boating, fire-buildw, f u h i , herbalism,
huntiq, mountaineering (where appropriate), observation,
riding, rope une, set snares, survival, swimming, weather
sense, and weaponsmithing (crude).
Equipment; No self-respecting Scout goeo anywhere
without a good assortment of wildernem survival gear, such
as adequate clothing, rations, fire-starting materials, and
such. T h e Scout duo likes toola apd gadgeta that aid in hid-
ing, rcouting, climbing, and so forth. Other than necessities,
the Scout carries little, preferringto travel liht.
Special Benefita Besides the bonuses listed elaewhere,
the $pout has an increased chance to surprise opponento,
who sufFer a -1 penalty on aurprise rolls when enwunteting
the character.
Special Hindrancear Other than the penalty for use of
thieving skills in urban settingr (listed under “ C hModifi-
cations’’), the Scout has no special hindrances.
Wealth Optiolu: The Scout receives standard starting
funds.
and oftsn have commerce with several ofthe guild6
Freelance Heralds nometimen wark for.noble., even
While the PHB presents the bard as optional character other,~ t i o n s o, r for nope o m i 4 o n (auch as an order
class, the bard is not optional in a Savage CoP.tmampqign. Inheritors or a particular temple). These chuacters&~r
information for a specificpurpore, ruch as to warn a e v -
Here, bard. anujor part of severalcullurea ofthe ~ 1 1In. ernmegt of attack, determinehow r e d e u the M in
piic&, they Mquite important in Robrenn. Eudria, and
Behyne, where they nerve as hmtoriana and infornrationbm- a certain area, or report on how a war i gping. Freelance
Herald. often receive training from a guild but then Eril to
kerb and among the revage tribea, where they are rupected be initiated into it (by their own chpise cu t l su~;ld’~).~fAey
tradm.FoUovhg pe ovwviewSof bard kit. of the region.
HeraDd are like medieval versions of reporters. They freelancers were once full guild memlpra t+ut left (again, by
the guilds choice or their own).
gather news and uncover atgriea, and relate talea of cur- Note that some campaigns treat freelance HerJda as
rent eventa to the -8, as well aa to interestedgovern-
ments. spier. That is not the case in the Savage Coast aetting.
Skatda are the historiatu of Eurdria. A Skdd is also an Though Heralda might hide their true,aftiliation, or ev
operate “undercover”for a time, it is common for them to
importantpart of a Eusdrian m i l i force, aa an inspire become well known pnd thereforeineffective as apirs.
tional voice.
T i r d travel among revage tribes with p o d s for barter. In the Savage Coast land., there we reveral Herald
guild., ofvuyine power. M e m h take an oath.tothe guild
They often know religious ceremonies as well. Moot and must follow its regulations. Most pow4rful ofthe piIda
come from the tribes themielvea, but some few are from
other rpcea. All are respectad among the tribes, because are the Herald. of the Sun (alsocdkd the Illuminators),
who pride themselves on brin8;le secreta to light;the Her.
of the service they perform.
al& of the Times, who gatherand tell tales of current event. allies, countering magtecll wng +Recta,and learning "a little
of all typea; and the Royd Herddo. who aoncentrateon cov- bib o ! f ~ e r y t h i *( l e g d lore). I n a d , thq hrve therbili-
erage of politics md war. tih $a& u n d e "SpecialB s ~ f h ,b"el&.
churctsr CLwr Only bards -'be IferaIda. The Herald receive6 the followin6 akiU Id)umaentl: pMk
h e n md Natk+i&o: Heraldn,&ile t ohherymrighhttbea pack&, -6%: detect hoke, +lo%; climb d l s , 40%;r&d
found anywhere m Be&ne. languages. +5%. Heralds tend to concentrate on lite-
and elves can be are Ihniecdto.* +I. d h OthCt skills.
Heraldsneverir;k!nx$cYtbr~iualnforthepm6uion. For spells, Heralds concentratm on the school ofillurion,
ome,from my cocial clplls and can lurnth& ipeM. from other Hard&. ktlun ME
the Herdd'r initid spell selection muit come from thii
achool. For purpores of learning illuiionn, H e r a h hceivr a
likeable and out- +2bonus to their Ialelligeiln m.
heir own edifica-
A Herald does not build a mtro&dd md attract Mow-
en Mdetailed in the FHB.Howevec at 9thlevel &ch.hc-
ter can ntart a new piid or new branch ofan exidng guild
(with that guild'r approval), attracting 1Od6 €ier.ldr .ad
prosp(ctive Herd& of 0-level to 3rd level (ld4-1) u bl-
lowers. . . Herald#, like a t n n M bard$ can
wv-
become proficient in any ~eapoaM. ont use*Naponl pre.
femd by dl r.kUt0, ruch Mwar daw*
Nmwcapoa proAcisaEiu~The Herald r e d i n bonun
end with nearly any pmficienciei in etiquette and heddrj., r&d (like .Hhrdi)
local hiatory and rdidghvriting. 'Fhe Herald dw han the
information-gatherin8 pdkiency (nee f h p t e W), d p b -
mented by the specid abilities iimd under 'Special bene.
&ti,' below. Recommended proficiaacicn knchrde
price, pvhaps ac&ing favors by letting involved partiea know
fort-talking, languages (ancient and modern), and musicrl
that the information has leaked. Heralds of the Times feel a inntnunenh. Hkrald. must i p n d at leut hdfottbCitaon-
duty to gather news for the common people, considering weapon proficiency alotr to leunhngu*gn. Moat d r d
themlelw deknden of the public's right to be informed. A hornr for their m u i i d instrummtl, h n e thene u e rribd
k d a n c e Herad e h t take 6n maryr diffrrent wtivit+es. to announce their p e n c e ifi m y ~ I L E C L . M m y b e
T h e character's guild &lition also afl'ectr the Herald's
appearanrr. A member of a Herald's guild dwayn hu a tvr;t proficient in art and craft skills.
Equipmenti Herald8 have no special restriction. or
of identification (which indicates that the char&er has dowancea in annor and equipment. They are n e t d w~it~h-~
acquired the bkih necessq'to beeome a Herald), and car-
r i e l a symbol or wtars a uniferm of the guild. Because of out writing material#,so beginning characters muit buy a
writingntennil. ink,and pcpk (or p&t).
these things, r'Herald can expect to be treated well bjr
peaple who want to hear the news (whiah is almoat e v q . S p e S ~ B e c a u l tehey Mw i t c d u bp.kycn
df news, guild H d d s UT pnently renpecte8and
one). Freelance Herald. alno carry 'awrit of identification, Mfc pusage, even in aread itiffeting fma war. Herd& id
(by cdari
but do not went the symbolof a guild. However, many free- powerful y i l d i are the mort d l y
lance Heralds effect a specific look and set of mmnerinr, bnd dymbols). and it ia aometima dimnbulr for Bklma
becoming f a m a s or inf.tnour'among the common people; Herald. to canvinre othen of theit profdon.
Molt prefer bright colon and ufpenrive fashions, but a few In addition, the Herald receivei f& U p L C l l ' a b h that
favor a "rumpled" look. rtplmx the a t d . r d c l u i rbiliries. l h e r c reflea the Her-
ald'a ability to &cover information andlearn &ut local
Herd& (enpecidly freelance* and Heralds of the %ea)
are very liktly to be6ome adventurera, because such'a event.. The new abilities are local lore, iden* rumom, per-
lifestyle given themthe'6pportunityto travel and h e l p hme
the ikiIls needed in their profesaion. In addition, ralen of nuade cmad, and bp.dcommunk.tion.
Lwnl&: The focal lore abilitj,dl- a Hmfd tb qui+
adventurers make good stories for themaaaea. learn about a new area, such or who the important people
For m o n infomution on the Hcralds' guil&, =e th.+iec- are, whait mont h i k l h p are u d k , the q d t y ofvarioun
tion on Bellayne and itr Heralds in Chapter 2 ohhe M,f establinhmenta, stly major rumors,and so forth. Gaining
tkSasawjn & w & o o k .
Clua M&tiomc ruch information taken one'day OF mooping per 1.000
Heralds do not gmn the standnd people in the area under mutiny.H& never need d e
bard abilities of influencing iudience reactions, rallying
a proficiency check to learn major rumolr; people just ~ m -
rally wane to p u r on i&ererting news to them, becaulc of wrdnare allowed a lovingthrow a#ainnt p u d y d o n , with
their penondity and reputation. A Herald l e u n i more a -1 penalty per threelevels of the character. Thmwho fail
rumom than other charactersin the mme b t i m ,php haw their reactionn adjuuted one level in hror of the Her-
twice u many u n o d . This .bility &odd be adjudicated ald’* .pi+; thoG’whoruccugdhave an eqqd chance of
by the DM accordingto the nquircmenta of the adventure,
but a Herald nhould be able to pick up about one rumor per remainii *,the ymo +&iodw& 01adjuct;ir one hvel
three levels of experience, even in nituationn in which
iometimes givcm the charac
NmON UT Icure.
aecreta to keep, tuffcring at leut a t3 reaction penalty fmm
M e r the initial period of information colleaing, to deter- them. Some powerful folk8 who wirh to,maintunHO~OII
mine if a Hemld known information the player deniren,the mighi have a Heraldd d from t h e h l d , or even nand
DM secretly maken a proficiency (Intelligence) check for uiassini after the character. .In such a cue, +he Herd&*
the character, If the checbin nuccesdd, the Herald remem- guild will not look favorablyon W o n m who uuultr one
ben nomething ofimprtance (ouch u the name of the c a p of their own-provided the &id fin& out.
tPin of the p a d , or the location of a good inn); if the roll is In addition, for a Herdd to remain a member of a guild,
thc charrcter’munt follow the guild’. d e n and rephtionn.
two pointr or more below the character’i Intelligence, the
Herald remembon urmething more detailed (ouch u what The guild H e r d munt a b aomebmw performtuk.fordIe
guild, whenever itn leaden r q u a t ruch dutisn.
the guud captain loolu like, or the approximate cost of the
Wewine,a freelancer muit remain on pod term with all
inn$ narvicer). Thin can be expanded for any information
desired: If tbe Herald w ~ ttol remember the name of the the guildn or cannot expot them to lend’helpof any kind.
local baron’r hone, there might be no penalty, while the So thcie chuactcrn munt adhere nomewhat -the ~ i l d r ’
name of a typical citizen might require the Intelligence re&tionn and r e q u ~ r
check to succeed by 10or more. Whenever the rollmi a 20,
the DM nhould secretlygivethe character Llne information. Wed& opriolw The He& receiven nund.rd d n g
The Herald can also dincovcr npecific dctailn more fund..
quicG, by uring the information gathering proficiency u
dariled in Chapter 4. Howewr, while the Heralds r e d o n Sad
bonvl due to Chuinmr adjurt.the pruficiencycheck u nor- The Skakl i.a hLtoripn.for a cultun ~4thr.rtruwonl tra-
mal, the character in connidered to have an extended home cdoituionntr.yIonft&hedRrEirD. STEEL m&+, thi includen only the
territory. For purpcmn of the proficiency check, the Her-
dd’n home territory include1Bellqym, Rcnardy, Eudria, ,,
Rabrenn, the Savage Buonien, the fm citier of the S w a p Sk&a .I.oamnnpqy war p r t k frumtkair b,in+-
Chat, and the h o m h d a of the tonles and the Yazi gobli-
&theircompatriots and memorirhy ea& kkabof the bade.
noidn. Areas considered outdde thio home territory are
The characten create p m r and ballads from bartlen and
HeFath, rb+ lands of the lizard kin, the whole of the Orc’n
Head peninmula, the Yazak Steppen, Huh, the city-states, queita, and am valued and nipectedmemblr of their a h .
and aqy lsndm not dacribed in thir boxednet. c!hachr.cLr, only buds can be SkrMn.
Mraldi need offer no bribe. or other incentivei when
R.f#.ndNUiOMMk sluldacome only from Eundrt.
uiing thin ability (and suffer no penaltien for failing to do
so), except when outoide the extended home territory. In
addition, in any area where another Herald of the name
guild operatee, Hsrddn receive a +2 bonun to I n t a l i n c e
for purponen of the check (freelance Heraldn never receive
thin bonus).
Z2entifi Runcord: The Herald’i local lore ability in dno
amplified by the aharacterb ability to identify rumon. A
Herald can determine the vdidity of a rumorby d i n g a
successful Wisdom check (the DM rolls and relap what
“gutinntinct”tells the character).
Pe~~uaaCCmd: With the penuade crowd ability, a Herald
can affect the mood of a crowd by telling the true (or
nlightb altered) I d rumon and wwa. The character muit
speak the language of the cmwd to une thin ability. If the
crewd’n initial mood mi unknown, the DM can use the
Encounter Reaction table (Table 69)in Chapter 11 of the
DMG.After ldlO minutes, those listening to the Heralds
w;wise, they llpo expecredto m m k thii often in&-
en- than toward a more dry and iubtle wit, rather than
rha be+ or a- humor preferred by lome orher hrd..
A Skddi~~mpnioulur d y fmd the character to be s u p
portiveand kind.
SU& &oat dwap dmm in the -of their rdon. A
blue cloak u the +ol of oSkdd of Eudr;.
C h i Modificcrionsi The Skald hu the .t.ndud bard
ability to iQuence audienoe ~ I UThe. ChPIftcr’n &I-
ity to learn a little bit ofeveqvthiq (legendlore) doel not
apply to all mugid items, but to th- relatedto COIR-
bat or warhSk.kli haw a more cpecs.licd abiligr to ndly
friend. m d &ea, de& under “ S p e 4 Ewie&” below,
but do not gain the .undrd&&ty to nllybUioa,Tkycam
not c o u a t m r ~ c sdongetkato, hut &anothcr&lityin
ita place, u UpLhKdunder “Spn&d Bcdta.”
The Sluld rsceivena +6%bonru to the “detectn&“ +I-
ity. Unlike thaw of other rwtntU,&E SLuld.bpve M
penaltytotheirae t o 4 luypugs* beaaude Eudrirt
a literate culture. The sluld often d e s w&bn m u d of
poems uld h l L d s , dwwh they M dwap taught to
pun on the pmper p s and intldons.
Tbc W e cukwe does not .tmra,* andaome
J%ucd&u view myicwirh swpicion. A Skalddom notbe&
learning apellr lllltil3I.dlevel, 40 the npeu pgIwdonohut
given in the PHB is off by one lcve1 for the $bald. For
c i n a t m ~ ea, 7th-lavel sud CUI memok0nb)umugr.pslh
u a 6rh-lcvst atandard bard (three Ist-levelepdb, two 2nd-
+lave1ipdla). In addieion, the Skdd cannot leva +la of
only humanr, elvca, and dwarvei can become Skaldo. Elvec
and dwarves cannot advance past 12th level. Non-nativea greater power thnn hth l e d 80 ;Samthe 6th-laML
given on that ahart. In addition to thew d c r i a u S M &
am never taught to be Skdda. prefer apeUn UreMin combatand cannot lam +&om the
RequimmontsiS W c can be of either gender, and have Ichoolr of&tmcntlchum or illruiarlpbmtum.
the same ability score and +ent rcatrictions M a atan- Weapon Proficioncies: Like other bards, sk.ldi Cah
dard bud.Theytend tohave a good Stre+ and Corutihr- become pmf&ent with any wwpon, but must hd inl-
tion, 10 that they can be effective warriors. The characten tial slot. to weaponn common in Eundri.: bow* mombovn,
uiudly come from the freehew claai in Euidrii, but can
come f m the noble clam htead. apears, awords (bastard, long, broad, and two-handd),
dinp, andwar hammen.
R o k Moat S u d s ntay with their clam, supporting them Nomnapon Mhimaiesr The S U d receivea boaua
in war and recording their hirtoriea. But aome join adven- .pmficiedcies in -nt hktoty, poetry, and s i n k and-
tu+ paden in order to participate in great quem, which like Shrda-in Id&tory .ad
they then turn into epic poem or ballada. The characters ‘ ‘ Rccom-
mended proficfenciea inalude armorer, blaokanithig,
are euily taken by the idea of dangeroun, etoiting, and blind-fighting, bowyerlfletcher, etiquette, hunting, leather-
important quests. Whether with an army or a small group, working. mluicd inammcnt, andweapon am it hi^.
the Skald expects, and usually receivea, respect and cow- Eqriprmentl % I d s preferequipment approprhtewar-
teay. Those who treat the Skdd well know their deeds will riors, but have nu rpcJ.l reatrictiotll or d-m
(indud-
be honored in the Skdds next recital, and it ia well known ing armor).
that those who m a l i p a Skdd are likeb to hear their name Special Benmfitw The S u d s abilityto rally &ende and
slandered in innumerable ballad. acroas the land. alliea comei from the character’s wucbunt. For the war
Skalda go to great length. to be worthy of the respect
given to them. They work almost constmdy on new poems chant to ha- &cot. the Skald musbbegin chanting at l s u t
dame rounds before combat b+w otherwilc, .Ilisram too
and baHadr that record the deed8 of their fellowi and caught up in the venta smpadthemto bmetitk t h e abil-
patran.; it ia an unwiee Skald who irritate. all thole who
help protect and iupport him or her. To retain respect, ity, The warcb.nt hu an e&c&e ruye ofen f ~ p c r l e w e l
ofthe Skaid. Ita &ecb end u loon M the S k l d receives a
Skalds must be brave and support their companions. Like- wound, or after a number ofround8 equal to the Skd&
40‘ @ha
kvel (whichever O C C U ~hit). Bas- I Tradem can be of either gender and have
Skddi can chooae from six effects for the war chant,
the m e &ity score requisplncntsan r d a d Mi.The
tribes fmm which Traden come have no true r0d.lh m ,
chooung d&rent .acts each battle, if denired. A lnt-level but Traders M connidered to be am of upper mid& h,
Skdd can ch- o.Iy one effect, but can add another effect p n e r d y leu renpected tam tribai le-, and h t q u a l
with warriori (though warrion generally view them an
with each three experience levela (two effectn at 3rd level.
three effect. at 6tblewl, eta.).The S U d cannot chwne the
belonging to a lower echelon).
name effect twice for the u m e battle, and can never ch-e ‘haden are laldomrhmtic and never evil, which h v e n
more than nix effecta. lawful neutral, neutral good, true neutral, and the rare
The effects apply to the Skdd and d allien within range chaotic neutral Mpornible d i n t s .
of the war chant. The m i x av.ilrble ab&tier are M fohvs:
Ibnur bdp& equal to the Skaldnlevel. *&lor TheTrader’a p r i m u y ~ o l oii-net Iueprilingly-
A mor& 6 0 n u of 1 for each nix leveln of the Skald
ttade. The characten tranapom goode be- tribor, bar-
(mnnded up). &.
A +I &mudtoa tering for good dedi when- they can find &,
l l a t t d a circuit of w i o u a t r i h about once each year. &11Il.ulnr
A +I &mw toIruaunOgCm b . deal almost an much in atorlea u in trade [email protected] each
atop, they pans along tales of excitement and ad-re,
A +I b o w to ddavhgtbrorcu. M
A -I k t o h r C h . well M teaching the mythology and fo&m of& &ea. If
Skaldn .I.oreceive combat bonulaa. Whenever or necennary, the lkader can a100apply the mythology and
folklore by advining L local Shaman of forptten &en, or
chantin8 during combat (including the war chant), the even d n g u k nubntitute Bhaman fur small cwtamonb-
Skald receivea a +1 bonun to attack rob. (Thu ability inot but ody if a true Shaman iunavahble.
Trade- never i d ,becaula dut would break the band ef
cumulative with a bonua to attack rolln due to the war truit that pmtecta them when traveling among foreign
chant.) Even if not in time to perform an effective war
chant, Skaldr almoat alwaya ring or chant during combat, tribes. They are pffordedcourwl‘esby the triben they vi&
sometimen junt a noft chant under the breath, 10 they nearly
alwaya receive thin bonua. including lodging and food. A lkader might D D O ~a l~ittle
around the t&e, to learn about what they are d- &nd
In addition, Skaldi gain a +ldamage bonur when uning a what they plan. However, the tribe being viiitedexpecti
spear, battle axe, or a word ( b t u d ,long, broad, or two-
thin, m d is careful to hide itn more important iecreti. A
handed). Trader in careful about apreading goiaip about a tribe,
Special Hindrmoem Skald characters have no hin- b e ~ther eh~ua~cterWMUto be wclcomed there a p h .
drancei other than thore already detailed in other aectiona
Some Traden want to expand their horitol*, finding bet-
of thu kit dwcription. ter goodi for barter, or better ntorien, or sometimaa even
W d t h Optiolur The S U d receivea itandud starting
retrievingan item imporrant to the tribe. They are the m e a
hndn. who become adventurern. In an adventuring group, a
Trader ‘hader often acta an c ~pokeaperaon,and i u+ deferml
Trader. are wandering atorytellera and merchantn among to for barpining, even in the more urban WOM of tho Srv-
the lenn civilized culturea of the Savage Cout. Molt are pge Cout. Adventuring Trade8 ala0 ex- their compan-
native to one of thore cultures, but some few are from PC ions to renpect them, but never fail to do thingi that &
races. Representing one of the few linka among different them valuable to the g~oupn, tch u w t i n g spcllr for the
primitive tribei, they are welcomed by all u bringer8 of party, scouting, or fighting.The chmoters uc enpging
news, trade goodr, and ancient lore. Traders are well m d perarmable, irapectful of the beliefr of ohm,Lnd yery
reipected by tribal culturea, and are generally safe even tolerant of people who are different. They CUI nometimen
when v i n i h t r i h hortile to their own. provide ihelter for companionn when viliting tribe. ( w e
”Special Benefits” below).
Trader charactera gather lore of all kindn, elpecidly reli- CL.8 Modifiorrionii The Trader has the standud bard
ability of infiueneingaudience r e d o n a . T h e lbader’r abil-
5ow. If a tribe vioited by a Tmder haa a tank for a Shaman ity to learn a little bit of everythiag ( h p n d lare) applin
only to tribal itemi, until the character hu bwn e x p o d to
or other priest, and none are available,the Tradercan usu- the more u.banledculturea. Spendingaye= or more m the
ally adviae the locrla or even act in place of a Shaman for a more “civilized d u r n (notjunt adventurLy with peopte
ahofi time. from them) in necessary for a ‘kder to be able to apply the
legend lore aWtyto itemn of t h m culturea.
Chra&w CLUi Only be+& can be Traden. Tradere have neither the ability to rally friendn and dliea
with innpiring song, nor to counter mpgicd ion8 effectn.
h U l d N U i O d i t h Tortlw can take the M e r kit. Instead, they have abilitien detailed under “SpecialEenek.”
It i i remotely poriible for a member of mother race to
become a Trader if adopted by tortlea, but tbe character auf-
fers the tortles’level limit (for the hrdc l ~ i )I.f goblinoid
PC.are dowed, Trader6 can be found in theYnzakSteppea
and among Yazi goblinoidn.
The chacacterndo not learn wiwdr' spells. I m d , they feet, and for every round the being remainr that clwe. The
build a apellbook of clerical Ipelb. The charactera do not Trader doa not automaticnlly know where the crrutwc is,
pray for these spalb, but imtead memorize them u if they just that it in CIW. Locating it.atill requiremther c l w . A
were wi.ud @a. Whenever a apell description calla for a ofin+
h+ rylnboL the Trader mrut irutud p e r k a nhort chant M e rCm J . 0 Use tbid&tyto ddeedte,c.tautchheapnr&rrcwna. Spiritl
or aoncorporul un ~
ible spirits
(thin doe6 not change the apall'a cutin8 time). A Trader ir
limited in ape11 aelection. with major acceas to the sphercl of and undead ue.alm&. never immediately hostile t o 4
Tradera, but defend themelve. if attacked. Otkr dun dm
diviuation and protection, minor aweanto the spheresof all, beneficialreaction8from ouch beinge, T r hhave no
U;n&combat, rad plant.
-Traden never build a strongholdor attract followen. attackordefenaeabilitk.gioltthem, . .
Beucka being able to k e e t auch be+, Trader8 have a
Wupon Pmfichaim: At lat level, Wra are remtricted npecial ability to speak with than,u per thwpdwivb aud
to those wenpone avukble to their tribe.Beginn+ tortle
Traders must c h w c from short bow, atoff, long nword, and apell. To learn mom ancient Ime and mythology,t h w use
bite. At Ltsr leveh, Tradera canbecome pdicient in werp- thin ability to t d k to u n d e d (or normal &ad:cm&uren).
They can ala0 une the ability to tdk.to.apiri~,oEvrrious
om unavailable to their tribe, but dmwt never learn how to aortd. Thii ability ia particularly uwful if the 'hi&nwde to
uae fiwrm. communicate with an ancient apSt to b u n risurls appro-
N--P- The Trader chuacter receivw priate to a specific tribe, allowing the Trader tu YIW better
directionaenae, atorytalling, rad religion01bonw p d c i e n - an a kccper of religiouslore.
cieb and, like other bud.. local hitory and re.ding/writine. sped.1Hindrmcemt Bed= thole mentioned vlier, the
Recommended proficienciu include animal handling. ani- liDdetbu no a p e i d hindrances.
d training, fire-buildy, bhq,rope ure, wuther wnw, W d t h 0ptiop.iAa erplained.under ''Equipment," the
an% lore, hunting, net -, h d i q (re& andvetcri- Tradcr'gaina no ttuting funds. Trader'i rely moa&.on
nary). herbdim, local hiatory (for areas other than their
homer), land-bued riding (among goblinoida), survivd, butn; but are quick to g r ~ thpe uau of money when they
come into contactwith it.
and we&* (orude).
Equipmenti Tradera receive no aurting money. Instead,
they atart with OM of each of the weapon8 with which they
are proficient. A Trader CUI ala0 have up to 20 item. of
other equipment common to the character's tribe. T h i lilt they can use, and wme kit.
munt be approved by the DM, but might includetope,food, lac culnwr.Followingin a
clothing, weapon shcathea, items important for the chacac-
ter'a nonweapon proficieaciea, and ao forth. The character merent races and culturea, to nave p b r a timein loan%
also bcgina the game with 10d6 gp worth of trade goodn
appropriate to the tribal cultures (featheeed cloaka, neck. Lit.appmprirk for their charactem. Under each he&@,
laces and other jewelry, or even weapona, an approved by
the DM). The Trader uses armor according to the restric- kite are lilted in the following order: thoae for mukiplo
tioni of the duracteri culture (nee the t o d e description in cluaen, warrior kin, wizard kits, priest kitn, thief kitn, then
the appendixto th;book). bard kitn.
Special Benefits: Among tribal peoplei (lizard kin,
phanatonm, wallara. aome tortlea, md goblinoidr), the Any noten about restrictions and frequenoiea am included
tThreatdreibrer8ecreievets +a -3thbeoncuhsartaocrteearcutioanTrroalldme.r,If&me ecmhbear8r of parentheticallyin the hting. If there ia no nu& note, usume
m
but all of thew nations h
can receive e reaction of "hoatile" or "threatening" only if
the Rader han person+ cauned problems for the tribe in p k r c b a c t e r race. ,
quertion. City-Statut (inbabdanwtly by bumam, w i d dome &&-
Trden are mlcomed by other tribes,and w pt a aibe maw) Locd Hem,Noble, Swuhbuckler (rare> Defender,
to extend this welcome to companion8by claiming them
andatant#(bearera, guuda, etc.). A Trader can claim up to -don; Militant; War %eat (common); ' b d i t , b u t .
one Mautant per level of experience, but muat have enovh S w a p Buonies (mdfree cities of the hy.0C0ut)l
bade goodo to make an entourageplaudble, or the tribewill
not offerthe welcome for very long. (kkbdd numtly b bwnan* wdbl ~ m da C k ) InBritor,
Buides their nafetyamong tribd pcopl+.,lkdenhave one
other ability, that of detecting npirits w undead. A Trader Lmxl Hero (rarein [email protected]), Noble (uccpt.forAhnarr6n;
autonmticaJlyget* a mving throw q a h t rpell.for detection
of a ap;it or u n d d when nuch a b e k approachemwithin 10 uncommon in.Cimuron and Torrebn. rare in Gargoda),
Swuihbuoklcr (common in hlmur6n and Gargoaa, rwe in
Guaddante, and unsmnrnon in Tarre6n. Narvaez, and
C i m m n ) ; Refcnder (lam of Narvan d e c b thin kit illc-
gal), Gaucho (humans and demihumanr &--common in
Cimarron and Guaddwte, rare in Gargofia, not native to
Vilaverde and Texeiras), Honorbound (humam, elvu.
dw- and h.lbponly), Mymidon,(e+pec+ in Tor-
rs6n and Narvaez); Militant (rare in Narvrez), Myotic
(o* in Gargofirand sPrag6n, and rare there); War Pneot
(common); Bandit. Scout.
Rohrnna (inbabiteaw t l y h bumam, witb many rlw a d
m m otkr&mibumanr) Inheritor (uncommon), Local Hero
(uncommon), Noble, Defender (relatively common); MilG
tant, Wqr Priest (commoa): Bandit, Scout.
Erud.iu (Ut&?by 6tima.w witb many elw, ba&
elw, r u l a & u ~ ~a~n,a r m ba&g.+) Inheritor, Local Hero
(uncommon), Noble, Defender, Honorbound, Myrmidon;
militant; War Prieit (common); Bandit, Scaut; Skald
(burnun, dwarver, and elvea only).
R o n u Q ~(inbabitdmodtly by l+) inheritor, Local
Hem, Noble, Swashbuckler(common); Beast Rider (lupin
o e ) , DoEcnder, Honorbound ( m a t l y lupino, rare hu-,
d v u , dwwa,and W i a ) , w i n ; Militant; Bmndit,
Scout (relatively common).
R&per(hbabit4mcutlyby&~witbmMy&anato~
b a r mu) Inhuitop, LocaHam, Nobk, SwuhbucLlU:Beant
Rider (&a and a few elvcr only), Defender, Honorbound
W4(rakahndctaf(.hmeglE),a)MnF;dytroimstdi+deornri%lp(nutiknvccol(mymcmowmotlnmy);onMnk;iluriratproen,the(uulmmnwa,nmt,odmrtwloeansd)),;
8.adit,Scout; H d d (nkprtrand e l m only).
Herathi Inheritor (uncommon), Local Hero, Noble,
Swashbuckler; Defender, Myrmidon; Militqnt, Myntic
(rwe); War Priest; Bandit, Scout.
Kttr for %A* <
Gobboids,aad WoideNati- ,
I n f o d o n given with each heading below f d s into three
buic categories: 1) kit. allowed to those individwla raird
tant (non-nativeah F ~ J ~ i b @ b n k .
in their home culture; 2) kit.token d y rarely, and only by
individuals raiwd in a culture other than their native one; New:Noble; Gaucho; My&: Herald, S u d .
and 3)kit8 never taken by memben of that race. Tortlea are H u b Characters from Huh are dlNap buman, 4can
an exception, being almost alwr~rur a i d in o t b r cultures. b a n the following kit. from thu book: Defender; Mystic;
Noten are included for DMs who wi.h to d o w goblinoid
PCn or those from Hub. Goblinoidn nometimes r4.e outr War Prieit; W i t , Scout.
aideniatheir culture-thae are us& priaoncri or .loves
taken from other culturea. BJainbO&er Uks
Todoe. Alhwa: Inheritor, Local Hero (very cqmmon),
Swuhbuckler (rare); Defender, Honorbound Myrmidon, It iu poanible for a DM to create additiod kit.for \ug with
tho RED STEF& campaign, A widc hngasfpcruihilitiu i
*tic ( r e 4 Fvhting Monk; Bandit, Scout; Tndcr. aovsred ha thia chapter, but &ere are othcrr Thew i.aL0
N e w : Noble; Beut Rider, Gaucho: Militant; Shaman, nothing prevent a DM fromnuming a l$EDBTEEL cam-
.War Prieat; Herald, Skrld.
y+st.pp.* * Na&k:6 h t Rider, Dafeqder, paign with &oracten imported from other&oni. Such
Honorbound (rare): Shaman (pbliioid. &), War PrLltr chamctenneednotworxyaboutcwfbrnieetooat*oki~
Bandit, Scout; Trader.
Non-na&ivc:Inheritor, Locd Hero, Swanhbuckler;,Myrmi- The DM caq pbo w kite from other ~ ~ u r c eua ,liatd
don; Militant; Fqhting M w k . hlw.Sourcwnot b e d contain no kitr &a& for a Sav-
N e w Noble; Gaucho; Myntic: Herald, Skald. age Gout campaign. Fcx example, w w a wch u the am-
pletcBook of Elver and the CompbteBlwk ofDwurue4 are
inappropriate, b e c a w dornihumanculturu alongthe cout
CI Kit#* 43
are different than general. Moat.Savage k t demihumani demihuman kita, only the elven Minutid might be found,
have lost the cultural identity that makes any of those kits amongthe nobiiity,ofRobrenu.
appropriate. Most other sourcw that have kits are too
-.closely tied tothe cvhuren of sources to be of much "he Complri.Book qfHmmzno&. Adaptitions of the
Shaman and the War Prieat appear in thin chapter. Them
are also several kite avdabk hekin that are simikr to done
:. Note that &nf.kiCr f& d w o u r c e a lispd have already in CBoH. The Mine Rowdy, Pit F d t e r , Saurid Paladin,
btqb daptedfor tb. setting r a d appear &I this chapter a d T u w l Rat Mnot suitableforthe setting. ALIt&mkita
(thwindude hitlW e the P- a d Noble, and'several from'C&iH -exckpt the Witch Doaos-can be u d mthe
Savage Coart, forgoblinoids and the other [email protected] t r i b .
The ComprCteR a n p r b Hadboo&. ,The fdlowing kits
from the CRH be u d with this ietting-Eleaath&dr ( i
Robrenn), Guudicn,Ju&r,,Pathfinder (cipcirllylupina
and r h t a ) , s+r Rangtr (unrrmunon), Skker#and Smker.
The ExpIorer, F.lconw, Fowit Runner, and ,%%dencould
be uned in Renardy, the city-nates region, utd ths&vage
Baronies. The Mounchin Mm m d Giaht Killdr codM be
found in Eusdria! The Ferdan ir a rare kit, but could be
found in a b e of the'leuMiMUof the Saw& Ccaat.
The Greenwood is dso 4.&&found only in RobremiAf
anywhere.
The COIN&& Pa&%> Hddbook. Paladina in gendral
Mrare in the Savage Caut dly.BdtaiyPill0a;llkit can
be used in the uca,except for the Skytider (no appropdte
culture) and the Wynnshyer (not enodgh dragons). pitbe
the Local Hen, or the Noblc'can be conridered an a&+
tion of the %e Paladin kit from CPaH. The Votary, Div-
inate, Expatriate, and Inquisitor are relatively c ~ m m ~inl l
Nuvaez, but only the Divinate is farad in d e r .riu;"he
Envoy and Emant would berommon +ins of thrrrgion,
while the Chevalier, Equerry, Ohdathunkr, Medicipn:Wi
Likewise, the Savage could be used. but the Shaman pre-
sented here is preferable. The Prophet could be u d for tarist, and Squire are alno possible.
Hule, and Scholars might be found in Bellayne, Renardy, The CornplCtc D r a d Hadbook. Druid8 are rare in thL
setting, except in Robrenn, where they dominate the coun-
and the Savege Bnmnia (clpcciplly in Gagofla). try. The CDH offers druidic branches, a i well as kits;
The CompIete W i i & Hadbook. Adaptation8 of the
branch is detenniiedby tht druid8 home envimnmeat. The
Militant, Mystic, Patrician, and Peasant appear in this forest bmnch is $he &&pat, end in erpeeiallfrstro~kgin
chapter. The Amazon and Anagnkok M not suitablefor this Robrenn. and to a Ideaer extent, Herath. Druid8 of J h n l
setting. Academicianscould be found in Gargofla, BeIhyne,
R e n d y , and esp.f;uy Her&. The Wu Jen could be used belong to the jungle branch, even though their region i i r&
tropical ruin forest. There are few,druidrof the swamp
as a hermit winard in Belhyne, while the Witch could be branch, and mountain or plains dmids are rare. Gmiy and
deaert drui&.re all but unknwri here, and there are no
uaedin all areas of the Savage k t . Also,the Savagecould &tic druids.
be used among the goblinoids. Savage wizards can read and
I
write, as per the Trader bard kit. In addition, the Academi- In terms of kits, only the Hivemuter and Mlly~drui&
cian, Wu Jen, and Savage could also be adapted for use have been adapted in this chapter, as the Webnruter uid
with psionicistn.'
The ~ m p k hBara'd Hadbook, Note that the kits from Local Hero, reipectively. The Advisor is commanin
Robrenn. The Outlaw in found in Nuvaen. There might be
bthuisdsCoIuMrKceS,abreecnaomt esaolmmouscthdkiotfatbhsemthteaykearaewraeyptkhaecebmaredn'st a few h t Druids m the &, and thwTotemic druid rould
Fmda pkcd in Burt Ridor cttltum (Rewdy, BeUty"e, and
standard abilities and replace them with aomething new. among pblinoids). The Natural Philosopher urd the Pnci-
This chapter include8 adaptations of the "rue Bard, Blade fist are ratheruniuitd to the,re&ti. Bmdn*cn. d;&*,
(as Swashbuckler), Herald, and & I d . The forlowing addi-
tional kita are ueble'with the a*: Charlatarti Gdlpnt ,(in Shapeshifter, and Wanderer can also bb uned, and would
likely come from Robrenn.
Renardy and the Savage Baronies), Gypsy (in Beltayne), A~bh
Jester, Jongleur, Loremaster, Meiaterninger (enpecidly in For the most part, the kite in thin
source are unsuitable for the Swage Coart cpmpoign. How-
Robrenn), Riddlemaater, and Thespian (rarely). Of the ever, the Aakar, Desert Rider, Fsrir, Holy Slayer; Rawun,
For example, Cierics who abandon the Sh- kit eucn- , ,. ., &mii&,rmulti-clam character can
tially renounce their home culture in favor of (L more ’’e;&-
lized” one. Similarly, warriors who leave the Noblekit
might be renounciag a birthigbt. In ~ 6 qhb c h w h d 8
character io close$ tied tb a kiu, and the kit to thr culture,
the DM is perfectly juatified in giving the character a
penalty auch aa the lour of two experience levels. In other
caseo, kita *remt pup^ l i e Inlreritora rad the Honor,
h d ,who punish h e who abedon dreir d o .
Far the mort put,k v i n g a kit at p* a new kith not
necewuy or -bk. The kit giwa the character an ihitld
mind-rt and a way of doing t h i . ; it does ISMprevent the
character from changing profeabionr, and it rddom pre-
cludes the character from c h & kbh,acquiring akillo
with m w c a p o n a , or learnh sometking common to
another fultute OF kit. Leaving kit. should be d i a c o m d ,
and switching kirc dhodd be dlowed only in the ram? of
Clrumrt.nces. any kit., priferriirg tkad each plmyer c
Keep m mind, however, that it i i poomble to join a kit
late, if, for inatance, a charnear io b m u g h to the sllvqc
Cout from iomd other area. E+ch caw mnat be handled
indiviaudty by the DM,according to the rituation. For
i n m c e , a charater cannot become an lnheritor afar tat
l e d , but ewld become an uioehte member of h e ohhe
ordbrr. A charrorer whewanted to become a Gaubho
could live with the range riderr for a time, leaming the
appropriate akilli and gaining acceptance from them.
Someone who wanted to beccrme a Shaman would have a
dificult time, but might be accepted by a tribe after a long
~ r i e nof ceremoniei and inktiation &hto. The DM might
d1 2 - e the charactqx.give up certain o k i h aplk, or hnbih
.iidb u l d require the character to much of th
ulti-clua ok so cerit
come informah. , & g d n $ t h r l l h
Mili-
DM coutd aIb%v b l a p r r h r r r
. The moat Lnpsrtant addition to the mien for thh proper rtep.are not taken taouptkromtescotamge&crhtpnefheeinc-,p4.;t.h.1e
d€ected q d i v i d d w d y
retting are t h m concerning the Red Curie that .ppaar~cco.r lome other detximentd &a, u wdl u an
overlie the rsgion. Becauae of that, much Q€ the attribute IOU. T h e n cue various side effects o€& Red
material in thin chapter ia information that only
the DM Bhould know. Re1eae.e of it to players Cum. For mat people, the acquisition of a LespeJr meanan
l h d d be canfully controlled. loaa of herlth. or of mental or phyeical prowera u well u
Though the Red Cune is potentially devu-
tating, thereare ways to channelitl nue;cl some unpl-t peY.ical manifeatation.
energies, and to aomc i ~ ~ l i v i dthde ~ For example, lomeone who receives a Legacy of great
strength might gain it only in one arm,w d that u m might
cune in more ofa blslning. That ia grow to huge proportiogr, while the re# of the body
bocauw the Swap C0p.r ii wgid
in wayn otherthan juat ita c u m . It is remains relatively normal. At the same time, the penon
would lose Intelligence, forgetting thow thisgr once
OLo home to twounique sub- learned. a d pouibly even hing the abilityto leun.
However, the magical nub- cinnabsyl protects from
atonce& vermeil and c i n n a b ~ ~anl ,d
the h e r can be uldd for protection the wont effects of the c u w , w h i allewjw indivi&& to
kom the Red Cum.
%chapter de* t h e w aure enjoy the benofita. Cianabryl, and other m a + l rub-
stances, w 4to manipulatethe c u m i nngic to brpeti-
d ita +, the msgid rub.tenclu cial p w p o ~ aeven dowing m e people togainmwe tbm
& ofthee o n , the acquisition ofh a - one Legacy.
cis, and the Lepcier thendw.
..
The fundamentaleRectl of the Red
Curse are twofold. First, every
pereon who spends time in the
c u r d M.b e ~ ntso mrnifent an
extaaordinary, magical power,
known M a Legacy. Second, if
the curse can be l i d . (Thin can lead to an interenting CPIII- mur
paign with a very definite god, if the player charactera
i e u c h for a mcana ofending the Red Curae.) But many IUU k p n a auws that m y oentuaiq ago,b e b p that were
people enjoy the bcnefita of the curse, from the peraond half man and half acorpion roamed the land that would
Legaciei it given them, to the way it harm3 their enemiei, become the Spvsgc C o a t . They became frienda with the
and the chnoa it im- on the region,doWinga dever per- ancient people of Nimmur,,the anceatora of the enduki,
aon to &to great political power. whom moat call minotaura. At fmt, &e mnwuoorpi-
oni were friendly, even helpful-but they hid a deep and
Following are a few commonly held theoriea concerning abiding love for chaoi. Eventually, they turned againat the
the origin8 of the curae. Each of them circulatca the region good people of Nimmur, and against the Immortalpatmn of
periodicallyu Iegond,and ..gelitudy them all. both racea, Luion, ruler of the Sun.
Ixion WPI angered, and he took hia bleiaing from the
%e Dqonnfall manicorpiom, d i n g them vulnerable to tbe l i t and heat
of the eun. Wherever they atood, xnanwppiona burnt to
&cording to t h i legend, manyyearn ago, dragoni roamed pilea of red aah, which we now know u vermeil, The power
the lands, and were often aeen in the iky, The dragonr met of Ixion WM p a t , and it .pnLintothe land. N w all people
in p a t conclavei, where they decided how they nhould be who live here gain power from the land.
governed, and how they ahould relate to others, whether But the red u h from the nxmacorpioni fliei through the
drpgona or other racea. air, and it polona all who live new it, giving them bizarre
PMictionr, u&aa they dig to find the receptpclu oflxiw'i
Then, the dragons began to war among themrelvei, for power, the magical metal cinnabryl, which still protecta
reuona lort in the mbtl oft h e . It ii wid that the leader of people from the traitorous manrcorpiona.
all the drsgona WM saddened by these conflicta, for he had
believed that the noble dragons were above the petty con-
flictl of other racei.
Eventually,the dragonr' leader w u able to fmd out who
a w e d the conflict, but to do i o coat him p a t l y , for he had
to battle other dragoni. Grievourly wounded, the dragon
leader left the acme of the battle, and flew to fmd the inati-
gator, leaving a great trail of hia blood.
The great dragon finally found hia hated enemy, a pow-
erful human. They fought for many daya. In the end, the
dragon won, but only at the coat of hie own mortal lie. AI
he lay breathing ht Iut, he laid an eternal curie on all the
landi where his blood had fallen. So great w u hi8 curie
that, in effect, he gained immortality. The red vermeil that
blows on the winds in the living remnant of hin blood, an
eternal reminder of hi8 pain. Becauie of it, the curie in
eternal.
The wording of the curie w u such that all who lived in
the area would iuffer, becoming twisted relic. of their for-
mer nelvea. Yet, the curse would d i o draw the greedy and
the power-hungry to the area, leading them away from the
reat of the world, to a aecluded place to eventually dentmy
themaelvea.
Another tale cloima that the wallaraa, known to many 40
chameleon men, once had a great and powerful civiliEation.
Dewended from drpgoni, the wallaru were alteredto have
imaller forma, so they might interact more freely with the
human and near-human racea, and apread the wiadom of
dragoni to them. They brought many great things to the
world.
Then came the aranea.
They were evil ipider b e i i a who, in their m g a n c e , con-
w,U n k curse f d doq the mt opthe & e ~ t o d
t h t h nunidorpione rtill at ruioua pima d o q it.
Eroh of the l ~ u d anbove contains at leut pur ofthe truth, Thiictmed~~thoae~~hfpwer~d
p t none'tall the complete Tht Red Curre ia actudy doomed by it, hLvLy theiibodiw-,.and dlek wnpl
mdp~mlrbilitieadcpltasd.
composed of .err4cursea and blcuingi. It i i a m u l t of AI might ba rxpcctud, Ixibn'i curse acted itpon
lapcnl a~nflictathat mbk plrace &ut 1,MH)yeu~ago,dut.
in((a h e of m+d tmublea. -who gained power, even tbore whts were undltin&
Roughly yeui before that time, the Nithima were at the
granted it -in the form of L6gacln by &e Wthian
mW aht t of their power. They built an empire centered on a enchantment. Thui, thd bgacied are the re.ult&one
river, comtructing immenae PJnnmidi thrm$houn the enchantment, mdthe d.&meht& d wid dent bm
surrounding dererts, lmda that would eventually become the renult of mother.
home to the Emiraten of Maruam. But the phuaoha of During the time of the Nithiian and NipuauriUr codlict~,
Nithia also ient out exploratory expedition. to other
there wan also a war between the mager ofHmth urd the
regiona, discovering the Savage a u t about 1,700 yeui wall4ru. Mort people believe who know anything ofthe
ago, and itartinga coloqy then. At abdut the ume time, the w,u u n a Mew fhat tht race bqan tci d e c h about S,,OQo
I f i d T h w t o a decided to &rtmy Nithian culture. It
yem 4eing supplanted byhuman .nd.ehaaMiludi.
took d n m t twweenhlriiei to complete, during which tide But thia ii nettbe cam. An explained in Oliapter6 o F t h
Tbanatoa led the Nithiam to irritate almoat dl thd other W oftbe Saw C w t book, the a r w a bcgn(b
1rmaOrt.L. Butin dk end, the N i t b weredeottoyed. On othet Pormn, and the " h u m s rml blves"who r u p p h t e d
the Savageh a t , their diaappeu'ance took $ace alMoBt them were a c t u d y armen them.elver. %e "b8thb;nr"
mannged to k e q their =ret d , m ditill do 10 +qy.
ohht. However, the walIuu -a wry wile peopk, able to
T h other I d a alm c o n w e d m incrediblypower-
M aa&antmedt known u Tbe SpeU~ObliyionT. hib magic diicern what w u real and what w u not. "hey ademood
&ected nrrry liviry, m o d b e i i in the world, robbing d the lcvct ofthe H e s a t h i # . But thqW hotking6 t hthe
of any memMyof the N i t h i i a d d w oftheir kndedge, bec~wtheywmapcsfel\lpl eople, c&m
powear knowlbdp without uaing it, deapite'tiie fwt that
monument# arid artifacta. Bot on the Savage Conat, the
deatraction w u not ahablute; L few PJnUnidi were I&, u H e n t W i hado c c u ius~edkPlLruu stock for mng-
WM L legacy of w t and philoaophy. The people of the Sap i d experiments.
"ethe Herathima, however; the airllrru' kn&W&e of
age Coant have no true memory of the ori#ina d thoae
thiag~h, owever. The mrnicorpiona of Nimmur believe. for their'wmtWAI intotenbk.&+dxht+ 1,myUnago,
example that they simply migratedwewt, rather than baing H e r a t h i lired w d u u in &uexperiment, idb
driven by the Nithimi. And molt people believe ancient in8tbeii euence into lizud h n tb creste theiaorr .dvmcrd
Nithian dach to be remnant6 ofw&an outpo6h. .pcC;..&who eventu+be&me the duulu.'Ihcw.ILk
While the Nithima on the Savage h u t were in power, nation prateated, and the Horathiana f a r e d th& the wal-
l u n a would ipread their aecret. So the magas of H e a t h
they were great worken of magic, involved in a conepiracy releued a m8gicd p l w e upon the w d h i ~ t hf.u,aidg
to wrebt power from their pharaoh. Theirwizsrda had even
created a powerful nugic which was the root of the Lep- that people to forget all they knew about Herath and its
cier, intended to give apell-like powerb to many oftheir inhabitanto. UnEortrinately, the plyue worked mo well.
troopi. The Swage Cout N i t h i i n dm net 1-e @a cre- Within two cent&&, it had480 much of the w d u d
ating a mqicsl mctrlthat could be mined and ah+ into knowledge that the race reverted to a Stoae @%vel af
magicd weapona. Thin wan the origin ofeinnabryl. Bat CLchnoiOgyand Wni g.Thin drew the attmt'wndftbdwdvlll.
doom fell u p d N i t h a befw the reb& could put into l u u ' ~ t r o r i&,e ~mmortaC~slled the Great One.
[email protected]& theiiplan to .tt.fk. The Great One itopped the devolution of thewdlaru,
leaving them frozen at their current level ofdevelopment.
-Meanwhile, the manacorpi6na having been driven He then laid an enchantment on the uu,CM+ hia blood
wHt by the Nithiana - h d been accepted by the endub of
Nimnrur. At about the inme time M the Nithian deatruc- over the region roughly 1,600yeUB ago, at about the u m e
tion, the manacorpiorii turned on the enduka and drove time u the Nimmuriawnd Nithin codlicti. That blood
of ma& in thd
them out. In fact, the enduka only i u r v i d thi. treachery wibecamevenke& and,it clouded d re*ofh t h , keepingthem
k u i e theywere aided by their frienda the ee'au, from area,greatly hide+ the
acroia the sea. fro&win((dMnationa on theit enemiea, even'demying
The I m m o d Ixion punished the manccorpioni with a their abilii to detect ma+. The Great Onek enhntmdnt
two-fold came. Fm,the nrPnrcorpiolu of NLnmur (on the dbb c8tdpeddn other magidforces-the N&
&ern+ of& Orc'a Head peninnula) beuMvulnera+ and Ixion'a cune-linking d three together, while altdng
Me to Ldon'B power, that of the nun. M.ny were incinerated,
and the reit were driven underground. The &ond part of them diihtly.
Enraged, the Herathianr gathered their powera and | https://anyflip.com/vjcbu/kpcq/basic | CC-MAIN-2022-27 | refinedweb | 35,093 | 63.8 |
Many Office 365 customers are using our hybrid deployment option since it offers the most flexible migration process, the best coexistence story, and the most seamless onboarding user experience. However, even with all of this flexibility, a few wrong choices in the planning and deployment phase could cause you to have a delayed migration, unsupported configuration or have poor experience. This article will help you make the best choices for your hybrid configuration so you can avoid some common mistakes. For more information on Exchange hybrid go here.
* As of this writing, Exchange 2016 is in Preview. It is not meant for production use. You would never install that in your production environments… right?
Ensure your on-premises Exchange Deployment is healthy
Some of our best guidance for configuring hybrid comes from the Exchange Deployment Assistant (EDA), however the Exchange Deployment Assistant separates the on-premises configuration from the hybrid configuration. There is an unwritten assumption that is made in our hybrid guidance that you have already properly deployed and completed the coexistence process with the current versions of Exchange in your on-premises environment. You really should ensure the existing environment is a healthy environment prior to starting Exchange hybrid configuration steps.
This means that if the newest version of Exchange in your environment is Exchange 2010, you need to deploy the right amount of 2010 servers to handle the normal connection and mail flow load for all of your on-premises mailboxes. Similarly, if the latest version in your environment is Exchange 2013, you need to deploy enough 2013 servers to handle the load. For more information on on-premises Exchange Server sizing go here.
Note: There is always an exception to the rule. In this case the exception is mail flow. There is a possibility that you may configure hybrid so all mail flows through your on-premises environment even after you move most of your mailboxes to Exchange Online. You may even have some applications that rely on the on-premises Exchange servers for SMTP relay. All of this needs to be accounted for and some extra thought may need to go into your sizing plans for these scenarios. Currently, our toolset for planning and sizing your mail routing environments do not cover these more complex scenarios.
If you think about a typical hybrid deployment, on day one there are essentially no mailboxes in the cloud. Therefore, you most likely have an environment that can handle all of the current on-premises workflow. Then as you move mailboxes to Exchange Online the load on the on-premises servers reduces since much of the client connectivity and mail flow tasks are now handed off to Exchange Online. The minor amount of processing power that is needed on-premises for things like cross premises free busy for an Exchange Online mailbox after it is moved will not come close to the demands of an on-premises mailbox, for example.
Should we have a hybrid specific URL?.
Some might ask: “Can I keep just my hybrid server up to date?” The answer: there is no such thing as a “hybrid server.” (More on that in a minute.) What this question is really asking is: “Can I just update the server were I plan to run the Hybrid Configuration Wizard (HCW) from?” The answer to that is “No.” As we move through this post, you will see how entering into a hybrid world means most of your servers are playing a part and communicating cross premises. In order for you to have a seamless experience and be supported, you need your whole environment to be up-to-date, not just a specific server or two.
If you have a healthy updated on-premises configuration, you will have a proper foundation for introducing a Hybrid configuration into your messaging environment in a supported and optimal way.
There is no such thing as a ‘hybrid server’
We often hear people say “I am going to deploy a hybrid server,” thinking they will designate specific three or four servers as “hybrid servers.” However, they fail to realize that hybrid is a set of organization-wide configurations and the server where the HCW is run from is just there to initiate these configurations.
To explain this, let’s briefly cover a free/busy scenario. When an on-premises user creates a meeting request and looks up a cloud user’s free/busy information, the request will go to the EWS URL returned from Autodiscover (step 1 below) and that server will facilitate the request by initiating the Availability service to talk to the O365 service (step 2 below). At this point, that could be ANY server in the environment. This means that when you configure hybrid, all 2010 CAS, 2013 Mailbox, and 2016 servers (when this will be supported) in the environment could be facilitating a federated free/busy request. There is no reasonable way to direct outbound federated free/busy requests to a particular set of servers.
Let’s look at the reverse scenario and explain what happens when a cloud user looks up an on-premises user’s free/busy information. In this scenario, the EXO server would perform an Autodiscover request to determine the on-premises EWS endpoint (step 1 below) and any server that responds to that Autodiscover.Consoto.com or Mail.Contoso.com endpoints would be responsible for facilitating the Autodiscover or free/busy request (step 2 below). The thing to keep in mind is that these are the same endpoints for all of the on-premises users for things like client connectivity, so you would not want to limit them to one or two servers in a larger environment. In short, you should deploy Exchange properly into your environment, then do your hybrid configuration.
Part of this confusion could be because in the HCW we ask users for CAS and Mailbox servers. The reason we ask for the CAS is so that the receive connectors on these servers can be configured. The reason we ask for the Mailbox is to ensure that we properly configure the send connectors. Selecting those servers is not selecting your “Hybrid servers” it is just for mail flow control explicitly. We do not have any concrete recommendation around which servers or how many of them should be added for mail flow purposes. There are just too many factors with mail flow such as seat count, migration schedules, geographies, etc.
Be sure to choose the correct version of Exchange
The Hybrid Configuration Wizard can be run from Exchange 2010, 2013, and soon 2016 so the question is often asked: “What version should I run the HCW from?” Let’s go through some of the decisions that will have to be made to help answer this.
Do you have Exchange 2003?
If Exchange 2003 is in your environment, then your only option for going hybrid will be to use Exchange 2010. This means that you would need to ensure that you have properly deployed and sized the Exchange 2010 environment, and then you can run the hybrid configuration process.
Is Exchange 2007 the oldest version you have deployed?
If you have Exchange 2007, and you do not already have Exchange 2010 deployed then we would recommend you properly deploy Exchange 2013, then deploy hybrid. This will give you the largest feature set, and since you have to introduce a newer version of Exchange, you should deploy a version that is supported under mainstream support.
Have you deployed Exchange 2010?
If this is the case, you need to ask yourself if Exchange 2010 fits your needs or if you need the features of Exchange 2013. Deploying hybrid with Exchange 2013 allows for features like cross-premises e-discovery, enhanced secure mail, or OAuth federation support. If these features are not important to you, then you can stick with Exchange 2010 on-premises and deploy hybrid.
In the event you want to upgrade your on-premises environment to Exchange 2013, you would need to deploy Exchange 2013 following our best practices guidance and deploy enough Exchange 2013 servers to handle all of the on-premises traffic. This includes going through the proper steps to size and deploy Exchange 2013 for your on-premises environment and following the guidance for properly setting up hybrid configuration. Often customers will use the Exchange deployment assistant two times for this. First time to introduce Exchange 2013 into the Exchange 2010 environment and the second time to introduce hybrid.
Is your newest deployed version Exchange 2013? Are you planning for Multi-Org hybrid?
Aside from the OAuth configuration previously mentioned, Multi-Org hybrid requires at least one Exchange 2013 (or later, when this is supported) server on-premises in every forest that will be entering into the multi forest hybrid configuration. HCW for Exchange 2010 does not have the proper logic to handle the naming conventions used for connectors and organization relationships. For more information on Multi-Forest hybrid go here.
A simpler story is ahead for Exchange 2016
When we release Exchange 2016 the deployment guidance for coexistence with Exchange 2013 will be a lot simpler than in the past. You will no longer have to move your URL’s to the newest version of Exchange, and instead, will be able to add one or two Exchange 2016 servers to the pool of servers that respond to the Autodiscover.contoso.com and Mail.Contoso.com endpoints. This means you will not have to stand up enough servers running the latest version to handle all traffic on day one.
While this will not benefit customers that are running older versions of Exchange, customers who are upgrading from Exchange 2013 to Exchange 2016 will go through a really easy and seamless process.
In summary
Taking a bit of time to cleanup your current infrastructure and understand your options for your hybrid deployment can save you a lot of time and aggravation later.
Thanks for sharing these design considerations. Would like some clarification on the following:
."
This is precisely how the Deployment Assistant recommends building out a hybrid deployment when the existing environment is 2010 and 2013 is chosen for the hybrid servers. Will the DA be updated based on this new guidance, or does this guidance trump the DA,
or….?
."
Is there an obvious benefit to moving the existing namespace to 2013 (other than reducing certificate SAN requirements)? Introducing a new hybrid.contoso.com namespace seems like it’s less impactful on end users since they can continue to point to the existing
namespace, and Autodiscover internally and externally can be re-pointed to hybrid.contoso.com to meet the HCW requirements.
@Varol
Thanks for pointing out that flawed information in that path of the Exchange Deployment assistant, I will work with our EDA team to get that information corrected so that it matches the proper guidance from this blog.
The benefit to moving the External URL to point to the latest in site version of Exchange that is properly deployed is…
1. You most likely already have your environment properly sized with the currently deployed version of Exchange
2. Exchange (up to Exchange 2013) was design to properly proxy traffic as long as the external endpoint is pointing at the latest version of Exchange
3. Deploying Exchange in the proper way, meaning following our guidance to deploy Exchange 2013 into an existing 2010 environment will be much less impactful than attempting to work around the designed coexistence logic we have in product
5. All of the validation that we do for Hybrid features is done against on-premises environments that are deployed in the expected way.
Again, thanks for the comments…
-Tim
Tim,
Appreciate the quick response and for working to get the EDA updated. I wanted to follow up on #3 and #4 – hopefully others are benefiting from this discussion as well :)
"3. Deploying Exchange in the proper way, meaning following our guidance to deploy Exchange 2013 into an existing 2010 environment will be much less impactful than attempting to work around the designed coexistence logic we have in product"
Could you please elaborate further? In my mind, this seems more impactful as we must move the existing namespace to 2013, meaning the modification of existing DNS records and firewall rules.. and in the case of existing 2007, the creation of a new legacy namespace.
After the change, users will see a new OWA login page, which may be a concern if end user communications have not been sent out. With a separate hybrid namespace, nothing changes from an existing DNS/firewall/end user perspective except we repoint Autodiscover
at 2013. When a user is moved to EXO, Autodiscover reconfigures Outlook and they use a new URL for OWA.
"
Agreed this may be true of larger enterprises, although it’s not something we run into too often.. for these customers, it’d be important to point out the licensing requirements during planning, as I believe the free hybrid license terms of use do not allow
for the migration of production mailboxes onto the hybrid servers.
Thanks again.
@Varol
Moving the existing namespace from 2010 to 2013 can certainly have an impact, which is why you needs to first determine which version of Exchange you should be running the HCW from. If the users are on Exchange 2010 then maybe 2010 is the right version to use
so, why even bring in Exchange 2013. If you however require an 2013 specific feature it will be less disruptive and more predictable to deploy Exchange the way it was designed to work. If you deploy Exchange in a way that we do not validate you run the risk
of things not working unexpectedly. This has happened in the past and it could certainly happen in the future.
Again if you look at one of the points of the article, there is no such thing as a Hybrid Server, just Exchange servers. There are proper ways to deploy Exchange so coexistence works in the most predictable way, that is the point we are trying to get across.
Great Article, thank you | https://blogs.technet.microsoft.com/exchange/2015/08/10/hybrid-deployment-best-practices/ | CC-MAIN-2017-51 | refinedweb | 2,356 | 58.72 |
How to: Raise Events Handled by a COM Sink
If you are not familiar with the delegate-based event model provided by the .NET Framework, see Handling and Raising Events. For specific details that apply to this topic, see Raising an Event in the same section.
The .NET Framework provides a delegate-based event system to connect an event sender (source) to an event receiver (sink). When the sink is a COM client, the source must include additional elements to simulate connection points. With these modifications, a COM client can register its event sink interface in the traditional way by calling the IConnectionPoint::Advise method. (Visual Basic hides connection point details, so you do not have to call these methods directly.)
To interoperate with a COM event sink
Define the event sink interface in managed code. This interface may contain a subset of the events sourced by a managed class. The method names of the interface must be the same as the event names.
Apply the ComSourceInterfacesAttribute to connect the event sink interface to the managed class.
Export the assembly containing the class to a type library. Use the Type Library Exporter (Tlbexp.exe) or an equivalent API to export the assembly.
Implement the event sink interface in COM.
For COM clients that sink events, implement the event sink interface defined by the event source in its type library. Then use the connection point mechanism to connect the sink interface to the event source.
The following example shows a managed server as the event source and a COM client as the event sink. The managed server declares ButtonEvents as an event sink interface and connects the interface to the Button class. The unmanaged client creates an instance of the Button class and implements the event sink interface.
using System; using System.Runtime.InteropServices; namespace EventSource { public delegate void ClickDelegate(int x, int y); public delegate void ResizeDelegate(); public delegate void PulseDelegate(); // Step 1: Defines an event sink interface (ButtonEvents) to be // implemented by the COM sink. [GuidAttribute("1A585C4D-3371-48dc-AF8A-AFFECC1B0967") ] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] public interface ButtonEvents { void Click(int x, int y); void Resize(); void Pulse(); } // Step 2: Connects the event sink interface to a class // by passing the namespace and event sink interface // ("EventSource.ButtonEvents, EventSrc"). [ComSourceInterfaces(typeof(ButtonEvents))] public class Button { public event ClickDelegate Click; public event ResizeDelegate Resize; public event PulseDelegate Pulse; public Button() { } public void CauseClickEvent(int x, int y) { Click(x, y); } public void CauseResizeEvent() { Resize(); } public void CausePulse() { Pulse(); } } }
' COM client (event sink) ' This Visual Basic 6.0 client creates an instance of the Button class and ' implements the event sink interface. The WithEvents directive ' registers the sink interface pointer with the source. Public WithEvents myButton As Button Private Sub Class_Initialize() Dim o As Object Set o = New Button Set myButton = o End Sub ' Events and methods are matched by name and signature. Private Sub myButton_Click(ByVal x As Long, ByVal y As Long) MsgBox "Click event" End Sub Private Sub myButton_Resize() MsgBox "Resize event" End Sub Private Sub myButton_Pulse() End Sub | https://msdn.microsoft.com/en-us/library/dd8bf0x3(v=vs.90).aspx | CC-MAIN-2018-13 | refinedweb | 510 | 53.81 |
How to convert text to speech in Java Tutorial using Netbeans IDE
How to convert text to speech in Java Tutorial using Netbeans IDE
This tutorial is all about How to convert text to speech in Java Tutorial using Netbeans IDE. In this tutorial you will learn how to make a sound or voice using FreeTTS library it convert the text to speech using java. This tutorial uses Textarea,Button and Netbeans IDE. Please follow all the steps below to complete this tutorial..
How to convert text to speech in Java Tutorial using Netbeans IDE steps
Create your project by clicking file at the top of your project and then click new project, you can name your project whatever you want. After that create your own form and drag 1 text area and 1 button then copy the code below and paste it inside your button events.
Note: you need to import this two package above your class in order to work this tutorial
import java.io.*;
import com.sun.speech.freetts.*;
[java]
Voice voice;
VoiceManager vm = VoiceManager.getInstance();
voice = vm.getVoice(VOICENAME);
voice.allocate();
try{
voice.speak(textareaTxt.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(null,.) Delete Confirmation Dialog using Java Tutorial in Netbeans IDE
2.) Automated Payroll System using Java Netbeans IDE | https://itsourcecode.com/tutorials/java-tutorial/how-to-convert-text-to-speech-in-java-tutorial-using-netbeans-ide/ | CC-MAIN-2020-45 | refinedweb | 213 | 56.05 |
Introduction: HackerBoxes 0021: Hacker Tracker
Hacker Tracker: This month, HackerBox Hackers are experimenting with data logging, satellite positioning, and location tracking. This Instructable contains information for working with HackerBoxes #0021. If you would like to receive a box like this right in your mailbox each month, now is the time to subscribe at HackerBoxes.com and join the revolution!
Topics and Learning Objectives for HackerBox 0021:
- Set up the Arduino integrated development environment
- Configure a USB-Serial bridge for the Arduino Nano
- Modify and upload program code to the Arduino Nano
- Read and Write data from the Nano to a flash memory card
- Retrieve data logged to flash memory into a computer
- Set up a GPS satellite positioning module
- Log GPS location data to flash memory
- Retrieve logged GPS data and load it into a mapping system
HackerBoxes is the monthly subscription box service for DIY electronics and computer technology. We are hobbyists, makers, and experimenters. And we are the dreamers of dreams.
Step 1:
Step 2: HackerBoxes 0021: Box Contents
- HackerBoxes #0021 Collectable Reference Card
- Arduino Nano V3 - 5V, 16MHz, MicroUSB
- NEO-6M GPS Module with Integrated Antenna
- MicroSD Card Reader Module
- GY-273 Three-Axis Magnetometer
- 16GB MicroSD Flash Card
- Deluxe Surface Mount PCB Ruler
- MicroUSB Cable
- Tiny USB MicroSD Card Adapter
- Solderless Breadboard
- Jumper Wire Set (65 pieces)
- Exclusive HackerBoxes "Hardware Hackers" Decal
Some other things that will be helpful:
- Soldering iron, solder, and basic soldering tools
- USB 5V Rechargeable Power Bank
- Computer with Arduino IDE
Most importantly, you will need a sense of adventure, DIY spirit, and hacker curiosity. Hardcore DIY electronics is not a trivial pursuit. It's a real challenge and when you persist and enjoy the adventure, a great deal of satisfaction can be derived from learning new technology and hopefully getting some projects working. Just take each step slowly, mind the details, and don't hesitate to ask for help.
FREQUENTLY ASKED QUESTIONS: We would like to ask all HackerBox subscribers a really big favor. Please take a moment to review the FAQ on the website prior to contacting support. The HackerBoxes membership numbers have grown and grown, which is awesome. THANK YOU! However, we are now spending an ever-increasing amount of time answering support emails. Sometimes, several hours a day. While we obviously want to help all members as much as needed, over 80% of our support emails ask simple questions that are very clearly addressed in the FAQ. Tending to these unnecessary inquiries is quite inefficient and takes time away from the creative aspects of our educational mission. And let's be frank, we know that you already understand how tracking numbers work. If you just want to reach out and make conversation, we can certainly come up with something a little more interesting to discuss. Thank you for understanding!
Step 3: Arduino Nano-flash version of blink.
Step 5: Battery Power
While working with the code on the Nano, we use the MicroUSB cable connected to a PC. This cable also supplies power to the Nano.
The easiest way to switch over to mobile (that is, battery powered) operation is to simply plug the USB cable into a USB 5V Power Bank, like this one.
A slightly more integrated option is to use the Nano's on-board voltage regulator connected to the VIN pin. Supplying a 6-9V unregulated power source (such as a battery) to the VIN pin can power the Nano. This is slightly more complicated because you need to consider how the battery is housed, how it is connected to the board, how to provide discharge protection for the battery (particularly if it is a LiPo), and also possibly how to charge the battery. Using a power bank, at least initially, abstracts these issues away in a single solution.
Step 6: Read and Write on MicroSD Flash Card
Adding a flash memory card to an embedded circuit is a great way to log data that can be accessed later. For example, the data may be stored on the card and then loaded, at a later time, into a computer for analysis.
This example shows how to read and write data to and from a MicroSD card.
We will use the code from the official Arduino tutorial.
To keep things simple, we will use the default SPI pin assignments from the tutorial.
SD MODULE - NANO VCC - 5V GND - GND MOSI - pin 11 MISO - pin 12 SCK - pin 13 CS - pin 4
Once the connections are made and the code is loaded, the results can be observed on the serial monitor (set to 9600 baud).
Hit the reset button on the Nano and each time you do, you will notice that there is another "testing 1, 2, 3." line added. This is because the file on the MicroSD card is being appended with the message each time.
Step 7: Reading the MicroSD Data Into a Comupter
The tiny USB adapter for MicroSD cards can be used to connect the MicroSD card to a computer system.
Insert the card into the adapter with the contacts down and plug the adapter into a USB port on any computer. No drivers are required on the computer. The card should show up as a standard USB storage device.
A blue LED will illuminate on the card adapter once everything is properly inserted.
Notice that the card has a file called "test.txt" containing all of the "testing 1, 2, 3." lines appended in the previous step.
Step 8: Satellite Navigation Systems
Satellite navigation (SatNav) uses a system of satellites to determine positioning information. A SatNav system with global coverage is referred to as a global navigation satellite system (GNSS). The United States operates the NAVSTAR Global Positioning System (GPS) and Russia operates GLONASS. China is in the process of expanding its regional BeiDou Navigation Satellite System into the Compass GNSS. The European Union operates the Galileo GNSS scheduled to be fully operational by 2020.
SatNav systems allow small electronic receivers to determine their location (longitude, latitude, and altitude/elevation) to high precision (within a few meters) using time signals transmitted along a line of sight by radio from satellites. The signals also allow the electronic receiver to calculate the current local time to high precision. GPS satellites continuously transmit).
Step 9: NEO-6M Satellite Navigation Module
The NEO-6M GPS receiver features high sensitivity, low power consumption, and advanced miniaturization. Its extremely high tracking sensitivity greatly enlarges the coverage of its positioning. It can operate where ordinary GPS receiver modules cannot, such as in narrow urban corridors or dense jungle environment.
The module can be plugged directly to a computer using a MicroUSB cable. This can be done without any wiring to the module, just a USB cable. When power is first applied to the module, the LED will glow steady. Once the satellite signals are acquired and positioning is locked, the LED will start to blink.
Using the Arduino IDE, the GPS module's USB port may be selected. The serial monitor may then be opened and set to 9600 baud rate. GPS data will appear in the NMEA format as specified by the National Marine Electronics Association (NMEA). This data will include the time which you should be able to recognize even though it is in UTC and thus likely shifted from your timezone by an integer number of hours.
Highlight and copy some of this NMEA data from the serial monitor and paste it into a text file.
Browse to the website for GPS Visualizer, select the text file with the NMEA data, and then view the geolocation results on a satellite map.
If you have a Windows computer, you may want to try out the ublox u-center software to read directly from the GPS module.
Step 10: Wire GPS Logger
A GPS position tracking logger can be implemented by combining the NEO-6M GPS module and the MicroSD card module. The measured GPS data can be logged to the MicroSD flash storage.
To use the GPS logger code shown here, the GPS module is wired up to the Nano A1 and A0 pins like so:
GPS - NANO VCC - 5V GND - GND TXD - A1 RXD - A0
The MicroSD card module is wired up as before with its chip select wired to pin 4 of the Nano.
Step 11: Mapping Logged GPS Data From a Computer
GPS data points are read from the NEO-6M and written to the MicroSD flash memory in a file called "gps.txt".
After data collection, the card can be connected to a computer using the USB adapter, and the "gps.txt" file can be selected for upload into GPS Visualizer for mapping.
In the illustrated example, we tracked GPS location points while driving a car from one side of a waterway near the HackerBoxes Headquarters to the other side of the watreway. It is easy to see that some routes are better suited to using a boat.
Step 12: Three-Axis Digital Compass
The GY-273 sensor module is based on the Honeywell HMC5883L (datasheet) 3-axis magnetometer. When it cooperates, the module can be used to implement an electronic compass. This can support adding direction, or orientation, readings to your embedded projects.
The GY-273 can communicate with the Arduino over I2C. This tutorial from Henry's Bench has some useful information on wiring up the module and using the appropriate libraries. This sparkfun guide also had some interesting information.
We have to warn however, that we have had a lot of problems with these HMC5883L modules. They are tricky to get working correctly and the MEMS sensors are prone to damage.
Step 13: Trust Your Technolust
Thank you for joining our adventures into the world of data logging, satellite positioning, and location tracking.!
14 People Made This Project!
TimGTech made it!
JonW27 made it!
g2em3 made it!
seaprimate made it!
djcc2012 made it!
moldavia made it!
kaigoth made it!
SlackerX made it!
RichW36 made it!
saraperrott made it!
ElijahH15 made it!
bitanalyst made it!
mainegeek made it!
BrianG282 made it!
See 5 more that made it
Recommendations
We have a be nice policy.
Please be positive and constructive.
52 Comments
To wire the GPS to the nano, it's written :
GPS - NANO
VCC - 5V
GND - GND
TXD - A1
RXD - A0
but in GPS_Logger.ino it's:
static const int GPS_RXPin = A1;
static const int GPS_TXPin = A0;
what is the correct wiring?
If you wire it according to the pin out, reverse the numbers in the code. Or you can reverse the wires and the code will work as written. I'm lazy...I just changed the numbers in the code.
I don't know if anyone else noticed, but the 'Kingston' micro SD card included this month is almost definitely a counterfeit. Check out this interesting article from a few years ago:
The hologram on the back of the package is fake. While I appreciate Hackerboxes sourcing us inexpensive hardware every month, I think they need to be careful about including hardware that's obviously counterfeit. There are laws about this that could get Hackerboxes or their customers in trouble for importing known counterfeit goods - especially now that they are making me do the dirty work to use a freight forwarded to get the package into Canada. Perhaps next time just include a 'generic' SD card instead of a fake branded one. (cross posting to the Facebook page also)
Those flash cards were extremely expensive and they work great. In fact, we paid more for them than they cost at Costco. Unfortunately, you cannot go into Costco and buy 3,000 flash cards. Also, please stop the whining about shipping. No one is "making" you do anything. If you don't like it, then don't buy it. Thank you!
I am now completely sure these are counterfeit Kingston SD.
tested the card model and class I/O speeds and error rate and it is quite below the expected values.
No worries tho, the SD works perfectly fine for these Logging tasks, but i would definitely not recommend placing these on a SmartPhone.
I don't think erazmus was commenting on the quality or price of the microSD cards, he was stating they appear to be counterfeit. I also immediately assumed they were fake due to packaging and hologram. Are they genuine Kingston cards? Can you comment on that?
Also, equating peoples displeasure with your new way of doing international shipping as "whining" kinda made me cringe. Are you trying to run a business? Maybe don't put your customers down.
lol - Like! No problems with what you've shipped. Thanks HB, so what is on the docket for 22? My soldering iron is ready to go ;)
No issues here. Everything is fantastic!
For those of you who were receiving 0's from the compass sensor, It was mis-lableled as HMC5883L. The chip on mine was QMC5883L which the registers were not in the same spots as the one linked. The Datasheet I used for the QMC5883L is found here: on post # 8.
I was able to modify the code listed in one of the examples I found to come up with with something that would read data from the compass sensor. Though it is not perfect it can be used as a start. Granted I was trying to get information out of the temperature registers as well... Modify it as you feel.
Digital Compass code:
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The HMC5883
void setup(){
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking
Wire.write(0x09); // Set the Register
Wire.write(0x81); // Tell the HMC5883 to Continuously Measure
Wire.endTransmission();
}
void loop(){
int x,y,z; //triple axis data
int Temp; //Temperature C
//Tell the HMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); /
}
//Tell the HMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x07); //start with register 3.
Wire.endTransmission();
/* //Read the data.. 2 bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 2);
if(2<=Wire.available()){
Temp = Wire.read()<<8; //MSB x
Temp |= Wire.read(); //LSB x
*/
}
float bearing = atan2(y,x);
bearing *= 57.3; //convert radians to degrees
if(bearing < 0)
bearing += 360; //set range to 0-360 instead of -180 to 180
// Show Values
Serial.print("X Value: ");
Serial.println(x);
Serial.print("Y Value: ");
Serial.println(y);
Serial.print("Z Value: ");
Serial.println(z);
Serial.println();
Serial.print("Temp: ");
Serial.println(Temp);
Serial.println();
Serial.println("Bearing: ");
Serial.println(bearing);
Serial.println();
delay(2500);
}
This was my first HackBox, Rating 8/10. Overall, very happy with the contents and what I learned. Value 10/10.
With this box I finally got comfortable with data logging and connecting SDs to Arduino. Sounds silly now, but it was a daunting task that seemed much harder before this kit. I also finally got my first GPS module. Like that the GPS can plug directly into USB, and I learned a bunch about NEMA strings, serial parsing, and looking for GPS location lock.
Now the bad part of this particular kit is the digitial compass module. It just caused frustration. My module sort of read 1 axis, 1 axis is just dead (always 0), and the 3rd axis is stuck at a fixed value. This was after much debugging and learning the address in the examples was wrong, and maybe the registers are wrong too. The actual chip is too small to verify the number.
But the bad/flaky/faulty digital compass was not a total loss as I discovered:
I2C scanner
Learn some more about Wire
Discovered the Adafruit Unified Sensor package and large selection of sensor libraries that are available.
Glad I fought through the bad compass and learned what I did, but the compass is being tossed into the trash to put an end to the frustration.
Onto HackerBoxx 22 :-) | http://www.instructables.com/id/HackerBoxes-0021-Hacker-Tracker/ | CC-MAIN-2018-13 | refinedweb | 2,667 | 64.71 |
for(;;) { pause = data; PORTB &= (1 << LED); for(i = 0; i < pause; i++) _delay_us(10); PORTB |= ~(1 << LED); for(i = 0; i < 255-pause; i++) _delay_us(10); }
PORTB &= (1 << LED);
for(;;) {
You don't need all the Code: [Select]for(;;) { rubbish. Just put the code in the loop() function, that will repeat it for ever.Why are you using direct port addressing?Code: [Select]PORTB &= (1 << LED);Will set a bit in PORTB that is a 1 shifted to the left 13 times. As this is only an 8 bit register this does nothing for you.Why did you not post all the code so we can see if you have set the data direction register in the setup?
PORTB &= B00100000;for(i = 0; i < pause; i++) _delay_us(10);PORTB |= B00100000;for(i = 0; i < 255-pause; i++) _delay_us(10);
#define LED 5 // LED is on Pin 13 or Pin 5 of Port B
_delay_us(1000);
I have no idea why you want to use code like this on an arduino but change this line to:-Code: [Select]#define LED 5 // LED is on Pin 13 or Pin 5 of Port Band change both the delays in the loop to:-Code: [Select]_delay_us(1000);And it works
but I have changed LED to be 6
Show us the whole code you are using because you have changed some things (the definition of the LED which was fine in the original code but wrong defined to 13).This code is not intended for the Arduino IDE, it's AVR C code to be compiled directly by the gcc-avr.
#include <stdio.h>#include <avr/io.h>#include <avr/interrupt.h>#include <util/delay.h>#define LED 6 // LED is on Pin 13 or Pin 5 of Port B/* * UART-Initialization from * Hint: They are awesome! :-) */#ifndef F_CPU#warning "F_CPU was not defined, defining it now as 16000000"#define F_CPU 16000000UL#endif#define BAUD 9600UL // baud rate// Calculations#define UBRR_VAL ((F_CPU+BAUD*8)/(BAUD*16)-1) // smart rounding#define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1))) // real baud rate#define BAUD_ERROR ((BAUD_REAL*1000)/BAUD) // error in parts per mill, 1000 = no error#if ((BAUD_ERROR<990) || (BAUD_ERROR>1010))#error Error in baud rate greater than 1%!#endifvoid uart_init(void) { UBRR0H = UBRR_VAL >> 8; UBRR0L = UBRR_VAL & 0xFF; UCSR0C = (0 << UMSEL01) | (0 << UMSEL00) | (1 << UCSZ01) | (1 << UCSZ00); // asynchron 8N1 UCSR0B |= (1 << RXEN0); // enable UART RX UCSR0B |= (1 << TXEN0); // enable UART TX UCSR0B |= (1 << RXCIE0); //interrupt enable}/* Receive symbol, not necessary for this example, using interrupt instead*/uint8_t uart_getc(void) { while (!(UCSR0A & (1 << RXC0))) // wait until symbol is ready ; return UDR0; // return symbol}uint8_t uart_putc(unsigned char data) { /* Wait for empty transmit buffer */ while (!(UCSR0A & (1 << UDRE0))) ; /* Put data into buffer, sends the data */ UDR0 = data; return 0;}void initIO(void) { DDRD |= (1 << DDD3); DDRB = 0xff; //all out}volatile uint8_t data = 10;int main(void) { initIO(); uart_init(); sei(); uint8_t i = 0; volatile uint8_t pause; for(;;) { pause = data; PORTB &= (1 << LED); for(i = 0; i < pause; i++) _delay_us(10000); PORTB |= ~(1 << LED); for(i = 0; i < pause; i++) _delay_us(10000); } return 0; // never reached}ISR(USART_RX_vect) {//attention to the name and argument here, won't work otherwise data = UDR0;//UDR0 needs to be read}
for(;;) { pause = data; PORTB &= (1 << LED); delay(1000); PORTB |= ~(1 << LED); delay(1000); }
Quotebut I have changed LED to be 6 So have you got an external LED then?Why are you using code that is writing in such a machine code way? There are much easier ways to achieve the same effect. As a learning exercise that code is useless.
This code is what I actually have, and I need to rewrite it to use an easier way.
QuoteThis code is what I actually have, and I need to rewrite it to use an easier way.Sounds like an assignment or homework.
PORTB maps to Arduino digital pins 8 to 13 The two high bits (6 & 7) map to the crystal pins and are not usable
Sorry I don't understand that.Not to worry there is no reason why I should.However the bit I don't understand is:-Quotebut I have changed LED to be 6 So quoting from:- maps to Arduino digital pins 8 to 13 The two high bits (6 & 7) map to the crystal pins and are not usable So I don't see how 6 could possibly work, you are targeting the wrong bit.
What is the problem? | http://forum.arduino.cc/index.php?topic=106755.msg801635 | CC-MAIN-2015-32 | refinedweb | 738 | 59.87 |
This code is taken from 2.4 kernel, which is enabled for all ia64 machines. The only difference is if (has_8259 && irq < 16) return isa_irq_to_vector(irq); return gsi_to_vector(irq); instead of just return gsi_to_vector(irq); I think bigsur is one of those uses 8259 and ISA. I don't believe any new ia64 machines do that. H.J. --- On Mon, Aug 04, 2003 at 12:07:19PM -0700, David Mosberger wrote: > Can someone look into/explain why this patch is needed for Big Sur? > Either the old code is wrong for other machines, too, or the old code > is broken and we just don't exercise it on the other ia64 machines? > > --david > > >>>>> On Mon, 4 Aug 2003 11:10:33 -0700, "H. J. Lu" <hjl@lucon.org> said: > > >> I just tried the latest on my big sur, and though I think modules work > >> (at least they build for other machines), big sur is broken because > >> non-ACPI based PCI enumeration has been removed from the tree. > > HJ> Can you try this patch for bigsur? > > > HJ> H.J. > HJ> --- > HJ> --- linux/drivers/acpi/osl.c.acpi Mon Jul 28 11:41:53 2003 > HJ> +++ linux/drivers/acpi/osl.c Mon Jul 28 15:12:44 2003 > HJ> @@ -250,7 +250,12 @@ acpi_os_install_interrupt_handler(u32 ir > HJ> irq = acpi_fadt.sci_int; > > HJ> #ifdef CONFIG_IA64 > HJ> - irq = gsi_to_vector(irq); > HJ> + irq = acpi_irq_to_vector (irq); > HJ> + if (irq < 0) { > HJ> + printk(KERN_ERR PREFIX "SCI (IRQ%d/%d) not registerd\n", > HJ> + irq, acpi_fadt.sci_int); > HJ> + return AE_OK; > HJ> + } > HJ> #endif > HJ> acpi_irq_irq = irq; > HJ> acpi_irq_handler = handler; - To unsubscribe from this list: send the line "unsubscribe linux-ia64" in the body of a message to majordomo@vger.kernel.org More majordomo info at on Mon Aug 4 15:56:07 2003
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:16 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0308/6341.html | CC-MAIN-2013-20 | refinedweb | 310 | 71.95 |
This Tech Tip reprinted with permission by java.sun.com
Applications that are based on JSP pages, and that follow what's termed a "Model 1 architecture," can typically be developed easily and in a short amount of time. A Model 1 architecture is a good choice if page navigation and business logic are simple, and if the application is unlikely to change significantly. But as discussed in the tip "Improving Designs with the MVC Design Pattern," an application composed entirely of JSP pages can quickly become difficult to manage.
Early in the history of J2EE, enterprise application developers learned that an MVC architecture improved their designs. They used JavaBeans for the application Model, and JSP pages for views. They also introduced a Controller servlet for user interaction, business logic dispatch, and view selection. This came to be known as a "Model 2 architecture." Soon after, various groups of developers created a variety of commercial and open-source MVC Web application frameworks: notably Struts, Velocity, and WebWork. These popular platforms have revolutionized server-side application development. The only thing lacking was a standard -- until now.
JavaServer Faces (JSF) technology is the newly-approved user interface framework for J2EE applications. It is particularly suited, by design, for use with applications based on an MVC architecture. JSF began as Java Community Process (JSR-127), and was approved earlier this month (March 2004) by the Executive Committee. A reference implementation (considerably different from the Beta releases) is now available for download at the JavaServer Faces Technology Download page. The JSF Reference Implementation is free to use and redistribute. (Read the license that comes with the distribution.) An open-source implementation called Smile is also available from SourceForge. JSF is still not a standard part of J2EE, however it is likely to be supported by all major platform vendors in the near future.
The committee that created the JSF specification included many of the experts that created the existing frameworks, so JSF complements, rather than supersedes, existing solutions. JSF brings the benefits of standardization to the world of MVC application frameworks.
JSF Features
JSF's scope is ambitious. It provides the following tools to application designers and developers:
- A standard GUI component framework for tool integration
- Simple, lightweight classes to represent input events and stateful, server-side GUI components
- A set of HTML form input elements that represent the server-side GUI components
- A JavaBeans model for translating input events to server-side behavior
- Validation APIs for both the client side and server side
- Internationalization and localization
- Automatic view presentation, customized to client type (for example, browser or media type)
- Integrated support for accessibility
The Basic Idea Behind JSF
JSF defines a set of APIs that model GUI components on the server. These components can have state, for example, a component called "phoneNumber" would contain a string representing a phone number. An application developer focuses on coding application-specific modules. At runtime, the framework interacts with the user, dispatches and generates views, and invokes business functions.
JSF usually uses JSP pages to generate browser-specific HTML. The input elements in the JSP pages correspond to the server-side GUI components. Although JSP pages are the most common form of presentation, JSF is specifically designed to be independent of JSP pages. A JSF application could use any presentation technology to interact with a user.
To create a JSF application, you typically perform the following steps:
- Define and implement the application Model classes
- Describe the Model to the framework
- Create application Views using JSP pages
- Define data validation rules
- Define View navigation for the Controller
The remainder of this tip covers these steps in detail, using as examples, the sample code that accompanies the tip. The sample code is a very simple JSF application. The application requests three values from the user: a string, an integer, and a real number. It validates those values, and then provides error messages or reports that the values are valid.
Defining the Model
Application Models in JSF are implemented as server-side JavaBeans. The Model class represents a collection of data from the application, and operations on that data. The application Model doesn't have to be a single class, some Models have hundreds of classes.
The Model for the sample code is a simple JavaBean:
This class represents application data. It would also implement the application's functionality (if there were any).
Describe the Model to JSF
You configure the JSF controller using a configuration file named faces-config.xml. This file resides in the Web Application Archive (WAR file) in the WEB-INF directory, alongside the Web deployment descriptor file, web.xml. Among other things that it does, faces-config.xml describes the model objects to the Controller, and defines page flow.
To tell the JSF Controller about a Model bean, use the <managed-bean> tag in faces-config.xml. Here is the <managed-bean> tag in the sample code:
<managed-bean> <managed-bean-name>data</managed-bean-name> <managed-bean-class> com.elucify.tips.mar2004.DataBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>
This tag defines a new Model class for the Controller of the given class. It tells the Controller to name the bean "data", and to store the bean in session scope. For each user session, the first time an application component (for example, a JSP page) accesses the name "data", the Controller automatically creates one and stores it in session scope. Later accesses of that name refer to the existing bean.
Create Application Views
JSP pages are the most common technology for JSF views. JSF defines two sets of standard tags. One set of tags, called core, handles such functions as converting between types, listening for user events, and validating user inputs. The other set of tags, called html, is a general input model that is used for generating HTML (or other) views. Notice where each of the two types of tags are used in the example below. (You can distinguish them by their namespace prefixes.)
The sample code input form, values.jsp, declares the two tag libraries, and then defines the view presentation. The first of the three input forms appears below. (The other two form elements are similar.)
<%@ taglib uri="" prefix="f" %> <%@ taglib uri="" prefix="h" %>
<html> <head> <title>Validating JSF Page</title> </head> <body> <h1>Please enter the requested data</h1> <f:view> <h:form> <b>Enter a string from three to twelve characters in length:</b><br/> <h:inputText <f:validateLength </h:inputText> <h:message <br/> <p> ... </f:view> </body></html>
Notice first the tag that says <f:view>. This tag must always be present around any collection of JSF tags. Just inside that tag is an <h:form> tag, which defines an input form. An HTML form would usually have METHOD and ACTION attributes, but the JSF runtime defines these attributes for you. Remember that in MVC designs, the Controller is responsible for translating inputs and selecting views. When the Controller receives inputs from a form, the Controller (not the form) decides what happens next. So the form doesn't need METHOD and ACTION attributes.
Next in the form is an element called , which defines a textual input element. Its id attribute uniquely identifies it on the page. It is in this tag that the View is bound to the Model. The following attribute assignment:
value="#{data.string}"
binds the contents of this input field to the value of the "data" bean's string property. Each time the Controller generates an HTML view from this JSP page, it includes the value indicated by the expression "#{data.string}" as the text item's value. If the user enters a valid value into the text item, the Controller updates the server-side representation of data.string when it receives the form.
The other attributes and contents of this tag define data validation rules.
Defining Data Validation
Take another look at the inputText tag in values.jsp:
<h:inputText <f:validateLength </h:inputText> <h:message <br/>
This block of code defines two data validation rules. The code also prints an error message if the variable's value fails validation.
The inputText tag's "required" attribute is "true". This means that the Controller requires that the user enter something in this input. The tag inside of inputText, <f:validateLength>, constrains the input to no less than three, and no more than twelve characters. This is a standard validation from the core tags package. The framework provides interfaces for you to define custom validation rules if you need them.
When the user posts an input form to the Controller, the Controller validates each of the inputs. If any inputs are not valid, the Controller serves the same page again. Before it generates the new page, the Controller marks each failed input as invalid, attaching an appropriate error message.
The tag in the code sample above includes an error message for the view HTML. The "for" attribute (in this case, string) matches the id attribute of one of the other components on the page. In this case, the Controller supplies <h:message> with any error message from the <h:inputText> element whose id is string. The style attribute in <h:message> indicates that the error message should be rendered in red. (JSF also supports Cascading Style Sheets, so you could use a class attribute here, instead.)
This example shows how to perform server-side validation. JSF also provides a way to perform the requested validations on the client side. The default implementation of client-side validation runs as JavaScript in the Web browser.
Defining View Navigation for the Controller
The final development step is to tell the Controller which views to dispatch in response to user inputs. The previous section explained what the Controller does when it finds input validation errors. If all of the inputs are valid, the Controller uses the action it received from the form to determine what to do next. This "action" is essentially a semantic event sent by the HTML component (the commandButton) to the Controller.
The JSP page, values.jsp, includes a tag in its form. This is the button that posts the form to the Controller. The action attribute in the tag is a symbolic command that tells the Controller what to do if all of the inputs validate:
<h:commandButton
In this case, the commandButton tells the Controller to execute the "validated" action if all inputs are valid.
As mentioned earlier, page navigation is defined in faces-config.xml, as a series of navigation rules. Here is the rule that applies in this case:
<navigation-rule> <from-view-id>/jsp/values.jsp</from-view-id> <navigation-case> <from-outcome>validated</from-outcome> <to-view-id>/jsp/valid.jsp</to-view-id> </navigation-case> </navigation-rule>
This rule tells the Controller the following: if you receive valid inputs from a form in the page /jsp/values.jsp, and the action is 'validated', then go to page /jsp/valid.jsp.
Additional Plumbing
Because a JSF application is a Web application, it requires a web.xml deployment descriptor. A JSF application's descriptor uses a servlet mapping to map the JSF controller to the URL /faces/, relative to the context root. The Controller removes this part of the URL when it serves JSP pages. Although the URL in your browser indicates:
the file path inside the WAR file is actually:
/jsp/values.jsp
This detail can be confusing. The servlet mapping in the web.xml deployment descriptor looks like this:
>
Every WAR file that uses the JSF Reference Implementation must include the two libraries, jsf-api.jar and jsf-impl.jar, in its directory /WEB-INF/lib. These JAR files implement the Controller servlet and all of its support classes and files. They come as part of the JSF Reference Implementation download.
Differences From Earlier Releases
If you used last summer's early access (EA) release of JavaServer Faces, you'll notice that release 1.0 is quite different. In fact, if you have existing applications written using the EA version, you need to port your application to version 1.0. This section discusses a few of the changes between the two versions.
- The DTD for the configuration file faces-config.xml has changed. Many of the tag names are different. For example, the <from-tree-id> tag is now <from-view-id>.
- The tag that enclosed a JSF view was <f:use_faces> in the EA version. That tag was changed to <f:view>. The change was made because the name "view" is more descriptive of the tag's role in the application.
- Previously, tag names were all lower case, with words separated by underscores ('_'). The 1.0 release changed this convention, redefining tag names to use so-called "modified Camel case", the same naming convention recommended for Java method names. The new naming convention eliminates underscores, and instead separates words within a tag name by capitalizing the first letter of each word. For example, the tag <selectone_radio> in the EA version is now called <selectOneRadio>.
See the JSF 1.0 Reference Implementation Release Note for details on all of the changes.
RUNNING THE SAMPLE CODE
Download the sample archive for these tips. The application's context root is ttmar2004. The downloaded ear file also contains the complete source code for the sample.
You can deploy the application archive (ttmar2004.ear) on the J2EE 1.4 Application Server using the deploytool program or the admin console. You can also deploy it by issuing the asadmin command as follows:
asadmin deploy install_dir/ttmar2004.ear
Replace install_dir with the directory in which you installed the war file.
You can access the application at.
For a J2EE 1.4-compatible implementation other than the J2EE 1.4 Application Server, use your J2EE product's deployment tools to deploy the application on your platform.
When you start the application, you should see a page that looks like this (only part of the page is shown):
Click on the link for "Tip 2: JavaServer Faces." Notice that the resulting page displays input elements that already contain data.
The JSF controller created the data bean in session scope when values.jsp first accessed one of its fields. The data you see is the default values for the fields.
Try typing some invalid data into the input fields and hitting the command button. You'll see that the Controller catches the invalid entries and adds an appropriate error message.
Then enter valid data for all fields and click the button again. This time all fields validate, so the Controller receives a "validated" action. It uses the navigation rules defined in faces-config.xml to find the next page, /jsp/valid.jsp, and it forwards the request there. That file reports, however anticlimactically, that all data elements were valid.
Application note: If you are working on a UNIX or UNIX-derived system, especially Mac OS 10.2, you need to be sure that the server has enough file descriptors available. Before starting the J2EE server, execute the command:
$ ulimit -n 1024
This will prevent "too many open files" errors when you deploy your application. | http://www.java-tips.org/java-ee-tips-100042/149-javaserver-faces/1468-introducing-javaserver-faces-technology.html | CC-MAIN-2015-27 | refinedweb | 2,532 | 57.06 |
10-28-2015 11:17 PM - edited 10-28-2015 11:18 PM
Hi,
suppose that I have the following stock return data for 3 stocks:
data returns;
input abc def zzz;
datalines;
10 2 5
3 -5 7
-1 -7 6
1 3 -2
;
run;
I used the following code to calculate the efficient frontier, i.e, for each level of risk (variance) to find the optimal return and the weights of the stocks that correspond to each risk-return combination:
Proc IML;
use returns;
read all var _num_ into RMAT[colname=varNames];
Print RMAT;
f = 1;
g = 2;
n = 4; /* number of rows*/
k = 3; /* number of columns*/
RAVG = j(f,k,0);
RAVG=RMAT[:,]; /* to calculate column average returns, a 1 x k matrix*/
Print RAVG;
xbar = REPEAT(RAVG,n,f); /* to create an n x k matrix*/
Print xbar;
RMX = j(n,k,0);
RMX = RMAT-xbar; /* to calculate RMX*/
Print RMX;
V = j(k,k,0);
V=RMX`*RMX /(n-1); /* to calculate covariance matrix*/
Print V;
VINV =j(k,k,0);
VINV = INV(V); /* to take inverse of V*/
Print VINV;
P = 0.05;
M={1,.05}; /* to define M and required return (must change)*/
Print M;
DIG = j(1,k,1);
R = j(g,k,0);
R =DIG//RAVG; /* to concatenate (combine) DIG and RAVG to a 2 x k matrix*/
Print R;
H =j(2,2,0);
H = R*inv(V)*R`; /* to calculate H*/
Print H;
HINV = j(2,2,0);
HINV = INV(H); /* to take inverse of H*/
PRINT HINV;
Do until (P<=0);
W = j(1,k,0);
W = VINV*R`*HINV*M; /* to calculate portfolio weights*/
Print W;
PVAR = j(1,1,0);
PVAR = W`*V*W; /* to calculate portfolio variance given a return and weights*/
Print PVAR;
P = P-.005;
M = M - {0, .005};
end;
quit;
Basically the core of the code is done, what I need are 2 special additions:
1) I would like to create a table which will contain the information in the following way:
2) I would like to add the constraint of no short selling, i.e, the weights should all be greater or equal to 0. I just don't know how to add constraints into Proc IML
Thank you very much!!
10-29-2015 04:30 AM - edited 10-29-2015 04:34 AM
I don't have a complete understanding of what you are trying to do here, but I think I can answer your first question. You need to create a matrix large enough to hold all the results and then use a do loop with a counter. Then as the loop iterates, write submatrices of the results table.
rtab = j(k+1, 10); do i = 1 to 10; <existing code from do loop here> rtab[1:k, i] = W; rtab[k+1, i] = PVAR; end; print rtab [rowname=varNames];
A few other comments. V = COV(RMAT) will give the covariance matrix in just one statement, and note that there is no need to write declarative statements like V = j(k, k, 0);
10-29-2015 01:37 PM
And here are some general programming tips to simplify your code:
1) Use the NROW and NCOL functions to get the number of rows and columns for RMAT
2) Use the MEAN and COV functions for the computations of RAVG and V.
3) You don't need to use the REPEAT statement to make the mean vector a full matrix. SAS/IML knows how to subtract a mean vector from each row of a matrix.
4) There is no need to "pre-allocate" every variable before you assign to it. Just make the assignment and the dimensions of the variable will be determined automatically.
5) [Optional] You can get rid of the final loop if you want. You can create a 2 x 10 matrix of all the values of W and use that matrix in the computations.
The simplified code looks like this:))];
10-29-2015 01:40 PM
For (2), do you mean that you want to replace any negative weights with zeros? If so, you can use the elementwise maximum operator as follows:
W = W <> 0;
10-30-2015 09:31 PM
Hi Rick,
thank you for your code, now I have the weights in W and the variances in PVAR, for any given level of return. But is it possible to cretae data tables for both W and PVAR becasue when I tried doing:
data all;
set w pvar;
run;
I got an error message that tables w and pvar don't exist.
For the second part of the question, I just realized that I forgot to mention that there is another constraint: the sum of all weights should be equal to one - and this constraint is also applicable to the code that I put in the beginning of this topic.
So the additional constraint that each weight is >=0 would affect the entire calculaton from the beginning, otherwise the result would lose its meaning if all the negative weights are made = 0 and all the others kept as they are.
Thank you very much!!!
11-01-2015 07:06 AM
See this article about how to write data from SAS/IML matrices to SAS data sets.
If your goal is to find the optimal solution for a linear problem with constraints, that operation is called "linear programming." See the "Linear programming" example in the SAS/IML documentation. In SAS/IML 13.1 and beyond, use the LPSOLVE call to solve linear programming problems.
11-01-2015 11:58 AM
Hi Rick,
I went to the link for the discussion on your blog and managed to create 2 tables. But now I have 2 small problems with the names of the columns and rows.
Here is my code:
data returns;
input abc def zzz;
datalines;
10 2 5
3 -5 7
-1 -7 6
1 3 -2
;
run;)) rowname={'variance'}];
create Weights from W [colname=(char(p)) ] ;
append from W;
close Weights;
create Variance from pvar [colname=(char(P))] ;
append from pvar;
close Variance;
1) the column names for both new tables are output in a strange way. For ex, it should be 0.05 but I get _0D05
2) for the new table Weights instead of getting the stock names on the left I get numbers 1,2,3.
I tried doing
create Weights from W [colname=(char(p)) rowname=varNames ] ;
but then didn't get any table at all and an error message saying that "number of columns in W does not match witht he number of variables in the data set".
Thank you!
11-01-2015 06:05 PM - edited 11-01-2015 06:11 PM
Hi Rick,
concerning my first reply to your last poste I think that I managed to the tables that I wanted with the necessary column and row names:
/*creating tables return and Variance - the vector P contains the returns!!!*/
create ret from p ;
append from p;
close ret;
create variance from pvar ;
append from pvar;
close variance; quit;
/*to put return and variance together*/
/*transposing and renaming*/
proc transpose data=variance
out=var_transposed;run;
data ret_transposed;
set ret_transposed (rename=(col1=return)); run;
/*adding n*/
data var_transposed;
set var_transposed;
n=_n_;run;
/*merging*/
data return_variance;
merge ret_transposed var_transposed;
by n; run;
/*to put all together*/
/*extracting the stock names*/
proc contents data=returns out=stocks (keep=NAME) ;
run ;
proc print data=stocks ; run ;
/*creating the name "variance"*/
data v;
input name$;
datalines;
variance
; run;
data names;
set stocks v;
n=_n_; run;
/*setting the weights and variance*/
data weights_variance;
set weights variance;
n=_n_; run;
/*combining all into a table*/
data swv;
merge weights_variance names;
by n; run;
As for my question about the constraint, is it possible to do an efficient frontier in proc iml with the constraint (becasue linear optimization is a one-by-one case)?
Thank you!!!
11-12-2015 10:19 AM
It would have been helpful if you had linked to this paper when you asked your question: "SAS and the Efficient Portfolio by Thomas H. Thompson and Ashraf El-Houbi".
11-13-2015 08:53 PM
Hi Rick,
what a coincidence, I actually also found this paper before posting this question but the paper handles only the unrestricted case (i.e, short selling allowed so that the weights of the stocks can be negative) and that's the reason why I posted this question, in order to do the restricted case when short selling is not allowed.
Thank you! | https://communities.sas.com/t5/SAS-IML-Software-and-Matrix/efficient-frontier-of-portfolio-with-proc-iml-results-summary/td-p/232161?nobounce | CC-MAIN-2017-22 | refinedweb | 1,428 | 56.73 |
Vaadin CDI 10.0.0.beta1 is now available. Vaadin CDI integration library has been an important tool for many Vaadin developers, but we wanted to scope it out of initial Vaadin 10 release to get the first version of the new platform out sooner.
The new version builds on the same old principles as the old version. Active Vaadin contributor Tamás Kimmel built the first CDI integration for Vaadin 10 even before final stable version of Vaadin 10 was out. Now he has been working actively with the Flow team to bake it into a stable Vaadin supported official CDI integration.
Code examples and initial features
Integration to a CDI is now easier than ever. The fundamental changes we did in Vaadin Flow, allows better integration tools like CDI. You’ll only need the very same @Route annotation that you’ll use with plain servlet setups as well. MainView automatically becomes a managed bean and you can, for example, inject other CDI beans into your UI classes.
@Route public class MainView extends VerticalLayout { @Inject public MainView(Greeter greeter) { add(new Span(greeter.sayHello())); } }
You have the same scopes you had before, except that view scope is now replaced with Route scope and we expect it to be the most commonly used scope for Vaadin UI beans.
- VaadinServiceScoped
- VaadinSessionScoped
- UIScoped
- RouteScoped
- NormalUIScoped
- NormalRouteScoped
Refer to the readme file of the project to see more a complete list of features.
The tutorial and documentation are still under construction, but you can already use the tutorial app and integration tests as examples.
Try it out today
Vaadin Flow compatible version will be officially released among an upcoming platform release, but you can already use it with Vaadin 10 and we want your help to test it. The Vaadin CDI 10.0.0.beta1 is available via our pre-release repository already, and it is compatible with the Vaadin 10. With following pom.xml snippets, you can start using your CDI skills with your current Vaadin 10 project.
Vaadin pre-release repository:
<repositories> <repository> <id>vaadin-prereleases</id> <url> </repository> </repositories>
Vaadin Flow compatible Vaadin CDI dependency:
<dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-cdi</artifactId> <version>10.0.0.beta1</version> </dependency>
If you want to start with a fresh project, the easiest option is to use the new CDI starter via vaadin.com/start.
Report issues and enhancement ideas
If you find any issues, inconveniences or improvement ideas, don’t hesitate to report them via the Vaadin CDI GitHub project! If you are looking into the code, note that the master branch is used for Vaadin Flow compatible version and Vaadin 8 compatible 3.0 is still the default branch shown in the GitHub. | https://vaadin.com/blog/vaadin-cdi-for-vaadin-10-now-available-for-testing | CC-MAIN-2022-21 | refinedweb | 453 | 54.42 |
- Posted In
- Red Hat Enterprise Linux
- active_directory
Active Directory accounts locked out after four successive logins
Good afternoon,
Encountering a strange issue. We have winbind running on all of our linux vm’s. The first four logons to different servers work fine, there are no fat finger errors entering the password, the user windows domain account from the windows perspective has no failed logins. When we logon to a fifth server for no reason that we can see the user domain is account is locked and requires one of our windows admins to unlock the account. Has anyone seen this before?
Here is our system-auth file
#%PAM-1.0 # This file is auto-generated. # User changes will be destroyed the next time authconfig is run. broken_shadow account sufficient pam_localuser.so account sufficient pam_succeed_if.so uid < 500 quiet account required pam_access.so account [default=bad success=ok user_unknown=ignore] pam_winbind.so account required pam_permit.so password requisite pam_cracklib.so retry=5 minlen=8 lcredit=-1 ucredit=-1 dcredit=-1 ocredit=-1 difok=5 optional pam_oddjob_mkhomedir.so session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid session required pam_unix.so session optional pam_winbind.so
Here is the error message were seeing:
pam_winbind(sshd:auth): request wbcLogonUser failed: WBC_ERR_AUTH_ERROR, PAM error: PAM_MAXTRIES (11), NTSTATUS: NT_STATUS_ACCOUNT_LOCKED_OUT, Error message was: Account locked out
Thank you for any all input
Norm
Responses
Hello
First of all, If possible try to configure pam_tally2 as explained in
Second, User blocks only in AD or in pam_tally2 also.
As root
[root@atolani python]# pam_tally2 -u username
Try to check if user is locked when using SSH only or it happens with console also, Check
Try to get TGT using kinit 4-5 times & check if that also locks the user on AD or not.
kinit username
Hope that helps.
Thought that pam_faillock supplanted pam_tally2 (at least, pam_faillock's called out for use in the SCAP guidance)?
The other question to ask would be "do users with the same logical name exist in both AD and /etc/passwd". What we've found in our various environments is that people sometimes make the mistake of making an /etc/passwd userid that collides with the AD namespace. Thus, even if they auth correctly against AD, as the rest of the PAM-stack is dropped through, pam_tally/pam_faillock will get incremented because the authentication against the local version of the userid fails. Looking at the OPs authfail configuration, if he's cycling through multiple login attempts in shorter order than 300 seconds, he'd end up locking the userid if there were collisions. | https://access.redhat.com/discussions/1361153 | CC-MAIN-2021-25 | refinedweb | 434 | 56.05 |
Transiente FEM Analyse.
Hintergrund
Erstellung des Modells
- Starting with a blank FreeCAD project, we build our bimetal strip in the
Part Workbench
- Draw a
Cube Solid and rename it to
aluminium.
- Give it the dimensions 100 x 10 x 2 mm (length x width x height).
- Create a second Cube Solid 'steel' with the same dimensions
- Offset this part by 2 mm along the Z-axis (via Placement → Position → z).
- Select both solids (using the Shift key + mouse click) and create
Boolean Fragments from them
- Rename these Boolean Fragments to
bimetal strip
- In the Property editor, we change the mode from AnsichtStandard to AnsichtCompSolid. (It should also work by using the Part Compound command instead of
Boolean Fragments, however, with more complex intersecting shapes, there might be trouble with the FEM analysis later. So, better get used to using Boolean Fragments in the first place.) The result should look like this:
Vorbereitung und Durchführung der FEM Analyse
Zuweisung der Materialien
In the FEM workbench we create a new
analysis and add a new
material to the analysis. In the upcoming task window, we select one of the predefined aluminium alloys. Under 'geometry reference selector', we assign the material to the lower strip of our model by setting the selection mode to 'solid', clicking 'add' and selecting a face or an edge of the lower strip. In the list view, 'BooleanFragments:Solid1' should show up.
We close the task window and repeat the steps to create a second material 'Steel' (material card 'CalculiX-Steel') and assign it to the top strip ('BooleanFragments:Solid2').
Erstellung des Polygonnetzes
Since a Finite Element Analysis obviously needs elements to work with, we have to dissect our model into a so-called mesh. The FEM workbench offers two meshing tools: Netgen and GMSH. We will go with Netgen here: With the Boolean Fragments objects 'bimetal strip' selected, we click on the
Netgen icon in the FEM workbench. In the upcoming task window, we have to make different selections, starting from the top:
- Max. size is the maximum size (in millimetres) of an element. The smaller the maximum element size, the more elements we get – usually the result will get more precise, but with a dramatic increase in computing time. We set it to 10.
- Second order means, that in each element, additional nodes will be created. This increases computing time, but is usually a good choice if it comes to bending as in our analysis. We leave it checked.
- Fineness: Select, how finely the model should be cut into elements. For more complex models with curvatures and intersections, we can increase the element number in those regions to get better results (at the cost of more computing time, of course). Expert users can also set it to User-defined and set the following parameters. For our simple rectangular model, the fineness selection has not much of an impact, we keep it at moderate level.
- Optimize: Some kind of post-processing after meshing. We keep it checked.
A click on 'Apply' runs the mesher, and – the time depending on your computer – a wireframe appears on our model. The mesher should have created about 4,000 nodes.
Zuweisen von Randbedingungen
An FEM analysis now would result in nothing, because nothing is happening to our model yet. So let’s add some temperature: Use the
initial temperature from the FEM workbench and set the temperature to 300 K. Here, no parts of the model can be selected, since this setting applies to the complete model.
Next, we use
temperature acting on a face. We select the two faces at one end of the strip (Ctrl + Left mouse key) and click 'add' in the task window. Two faces of the Boolean Fragments object should appear in the list and little temperature icons on the model. We set the temperature to 400 K and close the task window. At the beginning of the analysis, the selected faces will get an instantaneous temperature rise from 300 to 400 K. The heat will be conducted along the metal strips and cause the bending of the strip.
Before we can run the analysis, an additional boundary condition has to be set: The analysis can only run, if our model is fixed somewhere in space. With
we select the same two faces as for the 400 K above, and add them to the list. Red bars will appear on the model, visualising that those faces are fixed in space and not able to move around during the analysis.
Durchführung der Analyse
The analysis should already contain a solver object 'CalculiXccx Tools'. If not, we add one by using the
solver icon from the toolbar. (There are two identical icons, the experimental solver should also work.) The solver object has a list of properties below in the left section of the window. Here we select the following options (leave the ones unmentioned unchanged):
- Analysis Type: We want to run a thermomechanical analysis. Other options would be only static (no temperature effects), frequency (oscillations), or only to check the model validity.
- Thermo Mech Steady State: Steady state means, the solver will return one single result with the physics reaching equilibrium. We do NOT want to do that, we would like to get multiple, time-resolved results (transient analysis). So set it to false.
- Time end: We would like our analysis to stop after 60 seconds (i.e., simulation time, not real time).
After double-clicking the solver object, we check that 'thermomechanical' is selected and run 'write .inp file'. This usually takes some seconds (or a lot more for bigger models) and returns a message 'write completed' in the box below. Now we start the calculation with 'run CalculiX'. After some time, the last messages 'CalculiX done without error!' and 'Loading result sets...' should appear. When the timer at the bottom has stopped, we close the task window. (With larger models and/or slower computers, FreeCAD may freeze and we won’t see the timer running. But be patient, in most of the cases, CalculiX is still running in the background and will eventually produce results.)
We should now have multiple
FEM result objects listed. By double-clicking, we can open each one of it and visualise the calculated temperatures, displacements, and stresses. We can visualise the bending by selecting 'Show' in the 'Displacement' section. Since the absolute displacements are small, we use the 'Factor' to exaggerate the values.
Within FreeCAD, we can use
pipelines to do some post-processing of the results. Alternatively, we can export the results in the VTK format and import them into dedicated post-processors like ParaView. For the export of multiple results (as for this analysis), there is a macro available.
Downloads
Anderes Beispiel
- Analytical bimetall example. The analytical example presented in the forum is included in FreeCAD FEM examples. It can be started by Python with
from femexamples.thermomech_bimetall import setup setup()
- | https://wiki.freecadweb.org/Transient_FEM_analysis/de | CC-MAIN-2022-27 | refinedweb | 1,152 | 63.9 |
I like developer tests, but I don’t like
the primitive assertions -
assert_equal,
assert_match,
assert_not_nil, etc. They
only exist for one reason - to print out their input values when
they fail. And they don’t even reflect their variable names.
So I wrote an assertion to replace all of them. Put whatever you want into it; it prints out your expression, and all its values. Essentially like this:
The classic versions require a lot more typing, and reflect much less information:
assert_equal(x, 42) --> <43> expected but was \n<42> assert_not_equal(x, 43) --> <43> expected to be != to \n<43>
Install this system with:
gem install assert2
Some systems might require
sudo, to tell the ‘puter who’s boss.
The “
assert2” gem will pull in RubyNode, the library that inspects Ruby blocks.
Then add
require 'assert2'
to your test suites, or to your
test_helper.rb file.
A student on a forum
recently asked why anyone should ever use any assertion besides
assert_equal. The answer relates to why we use
assert_equal
instead of just
assert. When the classic statement
assert x == 42 fails, it can only print out “false!”.
The
assert() method cannot
see the name of
x, its value, the
==, or the
42. So
assert_equal is a feeble compromise. It attempts to reconstruct
an expression from two input arguments.
This is a problem in all of unit testing - the cobbler’s
own children always get the worst shoes! Our platform knows
everything we know about
assert x == 42, but it
can’t tell us everything for one reason: Languages optimize
for the needs of production code, not test code. So our
customers will always get better tools than we get!
Ruby supplies just enough reflection for an assertion to reconstruct a block of code.Version 2.0
This new assertion simplifies the heck out of developer tests. Before:
def test_attributes topics = create_topics assert_equal 'a topic', topics['first'] assert_not_nil topics['second'] assert_match 'substring', topics['third'] end
After:
def test_attributes topics = create_topics assert{ 'a topic' == topics['first'] } assert{ topics['second'] } assert{ topics['third'].index('substring') } end
If the
first
assert_equal failed,
it would only print out the two
values. When
assert{ 2.0 } fails,
it prints its complete expression,
with each intermediate term and its value:
assert{ "a topic" == ( topics["first"] ) } --> false - should pass topics --> {"first"=>"wrong topic"} topics["first"] --> "wrong topic"
And if the
assert_not_nil failed,
it would only reward us with
the infamous diagnostic
"<nil> expected to not be nil".
Traditional assertions don’t work very well with elaborate,
multiple arguments.
assert{ 2.0 } works best using elaborate
arguments, with lots of variables, because it will print out each of
their intermediate values.
This research makes lowly test suites more competitive with a professional debugger. A failure diagnostic is more useful than a breakpoint and a list of watched variables!Influence
assert{ 2.0 } improves
Test-Driven Development.
Instead of carefully picking an assertion, just write whatever you like, and
inspect the diagnostic. If your production code is failing for
the correct reason, the diagnostic should clearly reflect this. If it does not,
upgrade the source in the assertion. This process reviews the test
diagnostic, to improve the odds it assists maintenance. That, in turn, encourages
helpful variable names and suggestive sample data values.
When a test fails unexpectedly, that diagostic will help decrease the research required to determine whether to debug the test failure, or revert the code.
To help more,
assert{ 2.0 } and
deny{ 2.0 }
both take diagnostic message strings.
Use
assert("my colleague made me do this"){...}, to ensure
test failures route to the correct department!
When
assert{ 2.0 } fails, it calls
.inspect
on each variable in its block. To help diagnose your application objects, such as your
Models, override their
.inspect methods,
and put descriptive strings in there. My
ActiveRecord projects inspect like this:
module ActiveRecord class Base alias :old_inspect :inspect def inspect return "#{self.class.name}" unless self.respond_to? :id return "#{self.class.name}: #{id} '#{title}'" if self.respond_to? :title return "#{self.class.name}: #{id} '#{name}'" if self.respond_to? :name return "#{self.class.name}: #{id}" end end endFine Print
The assertion was developed under Ruby 1.8.6…
When an assertion passes, Ruby only evaluates it once. However, when
an assertion fails, the module
RubyNodeReflector will re-evaluate
each element in your block. (You knew there was a “gotcha”, right?;)
This effect will hammer your side-effects, and will disable boolean
short-circuiting. So once again sloppy developer tests help inspire us to write
clean and decoupled code!
Don’t go enthusiastically replacing all your classic assertions
with
assert{ 2.0 }. Use it only on
fresh code, so you can review how it works with your expressions.
The following RubyUnit assertions are now obsolete:
- assert
- assert_block
- assert_equal
- assert_instance_of
- assert_kind_of
- assert_operator
- assert_match
- assert_nil
- assert_no_match
- assert_not_equal
- assert_not_nil
The next time you think to type any of them, use
assert{ 2.0 }
instead, and put whatever you need inside the
{ block
}!
assert_equal(x, 42) --> expected but was \n
assert_not_equal(x, 43) --> expected to be != to \n
Dunno if it was intentional or not, but you made the classical mistake of having the arguments backwards in the assertions. You don't expect 42 to be x, you expect x to be 42.
The fact that assert_equal and friends have the arguments in so counterintuitive order was one of the reasons that drove me to BDD and RSpec. And I couldn't be happier :-)
@Jarkko: no offense, but I have serious doubts about the wisdom of RSpec. Others just think it's a terrible idea.
You're spot on about the arguments being reversed, though :)
@Ovid, I'm not sure that RSpec is a terrible idea as such, but its implementation (at least at the syntax level) has some bogosity. I still think that the Perl test style has the greatest advantages over the default xUnit style.
you made the classical mistake of having the arguments backwards in the assertions
Two mistakes - one mine and one belonging to assert_equal.
All my classic assert_equalses, in every project I ever wrote, go assert_equal(reference, sample). The above is the only time I ever wrote (sample, reference). I did it as a lexical technique, to obey "use parallel construction on parallel concepts".
The other mistake is assert_equal's own verbiage. If you must invent a new assert_equal (if, for example, your library does not support the reflection that assert{ 2.0 } requires), then you should make your verbiage as neutral as possible. " should equal ". That way the argument order should not matter - even if all your test cases use a standard order!
the Perl test style
Oh, guys, please feel free to have an unrelated language shoot-out, here, so my blog entry will go to the top of "The Hot 25"! Thanks!
@Ovid: The link you reference is full of incorrect assumptions about RSpec. Source filtering? Perhaps you'd have to do that in Perl to achieve that kind of syntax, but Rspec is valid Ruby. And you don't have to define "should" and "should_not" methods. RSpec adds them automatically to every Object, something you cannot do in Perl without a lot of AUTOLOAD hackery. RSpec is more elegant than he gives it credit for, because it takes advantage of these Rubyisms.
This looks very cool! I'm a bdd guy myself but will take a look at using this w/ my test/spec helpers, as it looks so much more developer friendly. Nice work.
@Mark Thomas: you wrote RSpec adds [methods] automatically to every Object, something you cannot do in Perl without a lot of AUTOLOAD hackery.
I'm not sure where you get this idea. It's trivial in Perl to add new methods to classes on the fly (no AUTOLOAD required).
*Some::Class::new_method = sub { ... };
My objection is not about source filtering. It's about adding new methods to these classes. While it's a cool idea, I don't think it's necessary or warranted. When I read tests, I want to see the behavior of the code, but adding new behavior to classes solely for the purposes of test suites seems a bit dodgy.
That being said, maybe it will turn out to be a non-issue. There's a big difference between me thinking about how code should be and actually trying it :)
@Ovid:
Your example only adds a method to *one* hardcoded class. RSpec adds a method to Object, which is inherited by *all* classes.
but adding new behavior to classes solely for the purposes of test suites seems a bit dodgy
Hee hee... Ruby's open classes make it easy to do and it is used to great effect in many places (including Rails)
@Mark Thomas wrote: "Your example only adds a method to *one* hardcoded class."
sub UNIVERSAL::new_method { ... }
That sort of thing is frowned upon in Perl circles, but that doesn't mean it's not trivial to do.
Why even bother with deny{ x == 43 } ? Why not just assert{ x != 43 } ?
deny{} is for situations like assert_nil().
In terms of style, all programming statements should be positive. Sometimes assert{ x != 42 } is clear and expressive, and sometimes it isn't. assert{ object.nil? } might not be. deny{ object } might be.
(The source code to deny{} quote the Black Knight from "Monty Python and the Holy Grail" - "None shall pass!")
RSpec
assert2 0.2.0 might work with RSpec, like this:
assert do
my_object.my_method.should eql(42)
end
(Or whatever the syntax is. Yes I have worked with RSpec before...)
The .should should raise an exception, and assert will decorate it with the assertion reflections, and raise it again.
You can customize the messages for the old assertions:
assert_not_nil(topics[topic], "topics[topic] expected not to be nil")
Of course, that's not DRY. To me thought, that's just a great hint that we could do a lot better fine tuning the message, which shouldn't really be code centric anyway:
assert_not_nil(topics[topic], "Your topic (#{topic}) was not found in the list of topics")
I may be missing something, but I'm not sure that assert { 2.0 } offers much different over Test::Unit's assert_block().
This method is what's used to implement all of Test::Unit's custom assertions.
assert_block does not reflect its variables' values when it flunks.
And few custom assertions use assert_block. That's just wishful thinking in assert_block's documentation. (There are also plenty of reasons not to use it, including it will waste time formatting an error message, each time the assertion passes.)
Honestly, even if assert_block has the same functionality as assert 2.0, or even if a thousand other hacks and work arounds achieved the same overall result, the main idea here is that assert 2.0 makes this stuff *easy*...why hack when you can do things cleanly?
You can customize the messages for the old assertions
You can, but again, its down to convenience...why should I waste time trying to invent a meaningful error message when the most meaningful thing I could get back would be the expression I wrote and a clear reason why it failed?
One theme of misunderstanding here. assert{ 2.0 } is not...
- a DSL like RSpec
- a replacement for "custom assertions"
It lets you write whatever DSL works for you inside the {}. And it should not compete with domain-specific assertions, or application-specific assertion. They should report specific details when they fail, not complex generalities.
assert{ 2.0 } replaces all the primitive RubyUnit assertions except the block-oriented ones, like assert_raise, and the domain-specific ones, like assert_in_delta. That is specific to the domain of floating point numbers.
assert{ 2.0 } looks pretty similar to doctesting, except with doctesting you can just grab an interactive session and paste it into a file and it becomes a test suite.
>> topics = create_topics
>> topics['first']
=> 'a topic'
>> topics['second']
=> nil
>> topics['third'].index('substring')
5
In the interests of keeping the language/DSL war going *groan*...
@Ovid: I've been using RSpec on numerous projects for quite a while now and while there are times when it doesn't behave exactly as expected, and delving into the internals to see what has really happened can be troublesome, I thought I'd pick up this point:
"When I read tests, I want to see the behavior of the code, but adding new behavior to classes solely for the purposes of test suites seems a bit dodgy."
When I read tests, I want to see the intention of the code. RSpec lets me sit down with the client, detail the business requirements in language they understand, and then implement the tests in the same language. I can then setup continuous integration to generate a specdoc report so that they can monitor progress on demand and see what core bits of functionality are working, and what I know isn't. It keeps them in the feedback loop without disturbing me, and gives them a point of reference so they can differentiate between "this isn't working" and "this isn't working as I expected".
The only time I want to see the behaviour of the code in this scenario is when things aren't working, and if the RSpec DSL doesn't give me the language or output I desire then it's trivial to write my own custom matcher.
As for the merits of assert{ 2.0 } it obviously depends on your desire. It doesn't suit me as it's not code that could be read and understood by someone that doesn't understand ruby and removes legibility in the interests of improving debugging when there is an error. I use tests as much for documentation as I do error trapping.
You can customize the messages for the old assertions:
assert_not_nil(topics[topic], "topics[topic] expected not to be nil")
That's not very DRY. It repeats...
"assert" and "expected"
not nil
"topics[topic]"
To improve that diagnostic message, you'd also have to reflect the contents of topics, and the value found at topics[topic]. And that wouldn't be DRY, either.
After improving that diagnostic, you must find every other primitive assert_*() in your program. You must upgrade each and every one of their diagnostic messages, to achieve that level of detail. You must do all of them, because you don't know which one will bite you at code maintenance time.
And all of those diagnostic messages would not be DRY. That means you get all the common problems with duplicated code. The code might change, leaving the diagnostic messages behind. Then, when they fail, instead of saying "that should not be nil!", they might say something misleading.
Diagnostic messages are like comments - they can lie more easily than code can!
The only time I want to see the behaviour of the code in this scenario is when things aren't working, and if the RSpec DSL doesn't give me the language or output I desire then it's trivial to write my own custom matcher.
In the TestFoodPyramid , the peak is QA tests, soak tests, integration tests, permutation tests, etc.
Down in the middle are the customer-facing tests, acceptance tests, functional tests, etc. You are describing that layer. No assertion should be primitive!
At the bottom layer, every line of code should have matching, primitive tests. These must be dirt-simple to write. assert_equal was invented to provide these conveniences. Your comments also apply to assert_equal. Of _course_ you should productize and self-document the higher-level tests.
You can't DSL the bottom layer of that pyramid, very simply because unit test code should run as close as possible to the tested code. Any layer of abstraction adds noise to the signal from the raw tests...
The problem with RSpec, in my rose-colored syntax world, is it's the fact it's a huge collection of DSL anti-patterns. At any given moment you wonder, "Do I use a period, and underscore, or a space to separate these words?" I'm all for "fluent" syntax, but I think there's a line it crosses (just like AppleScript does), and it's sad, given the smart people involved in the project and some other very cool things I think RSpec is doing right.
Another gripe: like being able to scan the left side of a chunk of tests and see what's expected all in one place; RSpec makes me read across every line (since it feels the inexplicable need to be a sentence), which just slows me down.
I wish the community would have jumped on a lighter weight BDD framework; thankfully it's losing some weight (mocking) and has lost some of it's NIH syndrome oddities (ie, inexplicably writing a new runner vs sitting on top of Test::Unit). I won't hold my breath on the syntax (whereas spacing out an 'assert' and the curly brace is easy to do for this library ;-)
Will be nice to see if this works with test/spec.
The problem with RSpec is it has very little to do with my assertion, I did not target it, I was not even thinking about it, and it is welcome to its niche. I also did not mention it in my original post, but that hasn't stopped everyone from replying as if I did!
That said, I just now spent this evening upgrading a Beast test case into a spec ... case. Thing. Here's the result:
it 'should require body for post' do
post.valid?
post.errors.on(:body).should match(/can't be blank/)
end
We may eventually install the RubyReflector inside RSpec, so it actually help provide all those "well-formed English sentences" at fault time. However, RSpec's usefulness is when it passes, and emits a client-readable list of everything they are getting. Errors are developer-facing.
To demonstrate this, I put assert{} inside it{}, inserted a fault, and pulled the rip-cord:
it 'should require body for post' do
assert do
@post.valid?
@post.errors.on(:body).should match(/can't be blonk/)
end
end
I got an unholy blast of stack traces, object inspections, and (yes) reflected source with its values. Here's an excerpt:
Test::Unit::AssertionFailedError in 'Post should require body for post'
#
/home/phlip/projects/beast/stable-1.0/vendor/plugins/rspec/lib/spec/expectations.rb:52:in `fail_with'
...
/home/phlip/projects/beast/stable-1.0/vendor/plugins/rspec/lib/spec/expectations/handler.rb:21:in `handle_matcher'
/home/phlip/projects/beast/stable-1.0/vendor/plugins/rspec/lib/spec/runner/command_line.rb:19:in `run'
/home/phlip/projects/beast/stable-1.0/vendor/plugins/rspec/bin/spec:4
assert{ @post.valid?()
@post.errors().on(:body).should(match(/can't be blonk/))
} --> nil - should pass
@post --> # false
@post.errors() --> #["can't be blank"], "user_id"=>["can't b***
@post.errors().on(:body) --> "can't be blank"
match(/can't be blonk/) --> #
@post.errors().on(:body).should(match(/can't be blonk/))
m--? expected "can't be blank" to match /can't be blonk/.
./spec/models/post_spec.rb:12:
That's obviously pure heaven for a Real Programmer, but don't show that to a civilian client unless you are very good at CPR!
Ever since inventing assert{ 2.0 }, my career path has not lead me to write any new modules for anything with it! When that happens, I will be better prepared to demonstrate how to write DRY code inside its block that reflects error messages cleanly. And my RubyReflector is also available for other assertion systems to use, too...
very nice code construction
Consider this assertion:
assert complex_thing
Under any classical assertion system, this upgrade would be unwise:
assert complex_thing and another_complex_thing
You must put the other complex thing into its own disjoint assertion.
The assert{ 2.0 } fix:
assert{ complex_thing and another_complex_thing }
That's less risky. There's other reasons not to make assertions too complex, but "bad diagnosis at fault time" is no longer one of them. If the assertion fails, the diagnostic will state which branch of the and failed. | http://www.oreillynet.com/ruby/blog/2008/02/assert2.html | crawl-001 | refinedweb | 3,367 | 64.71 |
Is it possible to add a custom text area (like a legend but I should be able to add my own text) in a python plotly plot ?
How to add a text area with custom text as a kind of legend in a plotly plot
Yes, you can do this with a text annotation in paper coordinates. There is an example at where annotations are used as replacements for axis labels.
Also, if you need to have text spread across multiple lines you can add line breaks by inserting
<br> sequences.
Hope that helps!
-Jon
I am a bit confused at the explanation you have given
Basically, I was looking for something similar across the lines of this image :
Here there are 2 text boxes besides the plot with some custom information. Is there a way to achieve something similar to this ?
Here’s a full example of what I was talking about:
import plotly.io as pio import plotly.graph_objs as go from plotly.offline import init_notebook_mode, iplot init_notebook_mode() fig = go.Figure( data=[ go.Scatter(y=[2, 1, 3]) ], layout=go.Layout( annotations=[ go.layout.Annotation( text='Some<br>multi-line<br>text', align='left', showarrow=False, xref='paper', yref='paper', x=1.1, y=0.8, bordercolor='black', borderwidth=1 ) ] ) ) iplot(fig)
Hope that helps,
-Jon
Is it possible to embed more complex html in the text attribute ?
Here is the subset of HTML that is supported:.
-Jon
Also, what is the role of the x, y coordinates? Based on your example above, they don’t appear to determine the location of the box.
Upon further exploration, it appears that they represent fractions of the plot e.g. if x=0.9, the x-coordinate of the box will start at the 90% of the width of the plot. | https://community.plotly.com/t/how-to-add-a-text-area-with-custom-text-as-a-kind-of-legend-in-a-plotly-plot/24349 | CC-MAIN-2020-45 | refinedweb | 301 | 67.04 |
]
Describes the resource permissions for a data source.
See also: AWS API Documentation
See 'aws help' for descriptions of global parameters.
describe-data-source-permissions --aws-account-id <value> --data-source-id <value> [--cli-input-json <value>] [--generate-cli-skeleton <value>]
--aws-account-id (string)
The AWS account ID.
--data-source-id (string)
The ID of the data source. This ID is unique per AWS Region for each AWS.
DataSourceArn -> (string)
The Amazon Resource Name (ARN) of the data source.
DataSourceId -> (string)
The ID of the data source. This ID is unique per AWS Region for each AWS account.
Permissions -> (list)
A list of resource permissions on the data source.
(structure)
Permission for the resource.
Principal -> (string)
The Amazon Resource Name (ARN) of the principal. This can be one of the following:
- The ARN of an Amazon QuickSight user, group, or namespace. (This is most common.)
- The ARN of an AWS account root: This is an IAM ARN rather than a QuickSight ARN. Use this option only to share resources (templates) across AWS accounts. (This is less common.)
Actions -> (list)
The action to grant or revoke permissions on, for example "quicksight:DescribeDashboard" .
(string)
RequestId -> (string)
The AWS request ID for this operation.
Status -> (integer)
The HTTP status of the request. | https://docs.aws.amazon.com/cli/latest/reference/quicksight/describe-data-source-permissions.html | CC-MAIN-2020-34 | refinedweb | 210 | 69.58 |
95582/check-if-a-given-key-already-exists-in-a-dictionary = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
If you wanted a default, you can always use dict.get():
d = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
and if you wanted to always ensure a default value for any key you can either use dict.setdefault() repeatedly or defaultdict from the collections module, like so:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
but in general, the in keyword is the best way to do it.
You can use re module of python ...READ MORE
Hello @kartik,
Basically instead of raising exception I ...READ MORE
We cannot. Dictionaries aren't meant to be ...READ MORE
Try this:
if cookie and not cookie.isspace():
# the ...READ MORE
You can go through this:
def num(number):
...READ MORE
If you write x.insert(2,3)
and then print x ...READ MORE
Hi, you might have found another way ...READ MORE
Instead of using the /regex/g syntax, you can construct ...READ MORE
Python doesn’t have a specific function to ...READ MORE
Try using in like this:
>>>>> y ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/95582/check-if-a-given-key-already-exists-in-a-dictionary | CC-MAIN-2021-21 | refinedweb | 226 | 76.62 |
Sheet from
A range reference that refers to the same cell or range on multiple sheets is called a 3- D reference. Appending group of values at the bottom of the current sheet # import Workbook from openpyxl import Workbook # create Workbook object. Do you have any tips for OVERWRITING the Excel destinations? Try naming your ranges in the worksheet to something like Test_ folder and Test_ subfolder. Import range from the same sheet. Repetition operator Preceding item will be matched? 000 companies in the signmaking digital large format printing, screen- printing, engraving production industries prefer EasySIGN software for their efficient production. When you place text you can select Show Import Options to determine whether the imported text maintains its styles formatting.
The same value for range_ string must either be enclosed in quotation marks or be a reference to a cell containing the appropriate text. Import Range is a great solution to for one time however, sporadic needs to import data from same one sheet to another it’ s not recommended if you need to perform multiple imports in multiple spreadsheets ( as will be explained below). A 3- D reference is a useful convenient way to reference several worksheets that follow the same pattern contain the same type of data— such as when you consolidate budget data from different departments in your organization. This cheat sheet demonstrates 11 different classical time series forecasting methods; they are: Autoregression ( AR) Moving Average ( MA) Autoregressive Moving Average ( ARMA). Output of above code. For Each sheet In Workbooks. What from I want to do I' m trying to use the Microsoft. Then you can refer to these cells in the VBA as Range( “ Test_ folder” ) and Range( “ Test_ subfolder” ). Forms can only send information to one Google spreadsheet. is import optional) * Zero or more times. Any character in the range given by m and n. I am using import range to clone the submission same sheet but its not working as before What is JotForm? I’ d like to update an same existing worksheet inside a workbook either by using sheet name like [ Sheet1$ ] range name? Before you paste text you can select All Information , Text Only under Clipboard Handling Preferences to determine whether the pasted text includes additional information such as swatches styles.
From above code create a new sheet with same data as Sheet. for j in range( 1, max_ from column+ 1) :. At most once ( i. The one- page guide to Go: usage links, , snippets, examples more. I import am using import range from multiple spreadsheets ( Provider A B, C etc has its one daily recon) to collate same data for multiple accounts into one spreadsheet ( from same sheet name in each recon same range string in each) The spreadsheets are copied daily to have a back up of the prior day. Import range from the same sheet. The sheet_ name component of range_ string is optional; by default IMPORTRANGE will import from the given range of the first sheet. from ; 6 April Additional information added relating.
I don' t have control over the. Import the sheets from the Excel file into same import- sheet. Appending group of values at same the bottom of the current sheet # import Workbook. JotForm is a free online form builder which helps you create from online forms without writing a single line of code. 18 January range ' Loose hand- rolling pipe tobacco' section has been updated with more information on cartridges refills in water pipes. To set the folder try. Using Import Range, you can create a master sheet from which pulls information from other sources.
Import a cell range from one sheet to another sheet based on one cells answer? sheets of the same spreadsheet. from the range B2: L2 from Sheet 1. Hello, I have several different sheets all with the same data.
import range from the same sheet
I am looking to pull the data within the same cell across multiple sheets into a single column on a separate " master" sheet. Pull cell C3 from sheet1, sheet2, sheet3, sheet4 into a column in sheet" master" so the data lines up. Need sheet music maker software? | http://lpcity.tk/import-range-from-the-same-sheet.html | CC-MAIN-2019-26 | refinedweb | 693 | 63.9 |
26 October 2010 07:24 [Source: ICIS news]
By Heng Hui
?xml:namespace>
SINGAPORE
Petronas of Malaysia was not concerned about the new trade policy on methanol, given current strong margins as Chinese prices remained high, a company source said.
“The net effect is only over 4%, and
As of last week, methanol was trading at around $360/tonne (€259/tonne) CFR China, its highest level since October 2008. This represented a 16% jump from the start of the year, based on ICIS data.
PT Kaltim Methanol Industri of Indonesia, meanwhile, was looking at an extreme measure of stopping exports to
Kaltim Methanol would be required to pay 9.4% tariff for product shipments into
Methanex New
Meanwhile,
“Everyone will complain except for the Saudis, and the real tax rate will be determined from 24 December,” said the Kaltim Methanol source.
China had launched the investigations on suspected dumping activities by Malaysia, Indonesia, New Zealand and Saudi Arabia in June 2009, as production rates at local plants tanked to just 30% in the first quarter and methanol prices declined $165-175/tonne (€134-142/tonne) CFR (cost and freight) China.
In 2009,
Methanol is used in the production of formaldehyde, methyl tertiary butyl ether (MTBE) and acetic acid. It also has fuel applications - dimethyl ether (DME), biodiesel - and could be blended directly into gasoline.. | http://www.icis.com/Articles/2010/10/26/9403980/china-methanol-add-draws-mixed-reactions-from-se-asia-producers.html | CC-MAIN-2013-20 | refinedweb | 224 | 64.14 |
Hi, Im currently taking an introductory course in python and i need help with some stuff.
Basically for an assignment the first function we have is supposed to get an an average red value of all the pixels in the image. red being the R in (RGB). So basically the red pigment value. So basically i need to find the R value for all the pixels in the image and then add them up and divide by the total number of pixels. Now we are using the pygraphics module for this so this is what i have so far.
import media def red_average(): pic = media.load_picture(media.choose_file()) for p in media.get_pixels(pic): x = (sum(range(media.get_red(p)))) print x
Now instead of giving me 1 big number it gives me a list of numbers instead when i call the function. Basically does that mean its adding up all the red values from each row of pixels and displaying them? | https://www.daniweb.com/programming/software-development/threads/314838/python-newbie-need-help | CC-MAIN-2018-47 | refinedweb | 162 | 65.83 |
SSL Error (known SSL OSX issue?)
- chuckloyola last edited by chuckloyola
trying to run this code:
import urllib.request
req = urllib.request.Request('')
with urllib.request.urlopen(req) as response:
the_page = response.read()
print(the_page)
will get me:
Traceback (most recent call last):
File "urllib/request.pyc", line 1318, in do_open
File "http/client.pyc", line 1239, in request
File "http/client.pyc", line 1285, in _send_request
File "http/client.pyc", line 1234, in endheaders
File "http/client.pyc", line 1026, in _send_output
File "http/client.pyc", line 964, in send
File "http/client.pyc", line 1400, in connect
File "ssl.pyc", line 407, in wrap_socket
File "ssl.pyc", line 814, in init
File "ssl.pyc", line 1068, in do_handshake
File "ssl.pyc", line 689, in do_handshake
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<untitled>", line 4, in <module>
File "urllib/request.pyc", line 223, in urlopen
File "urllib/request.pyc", line 532, in open
File "urllib/request.pyc", line 642, in http_response
File "urllib/request.pyc", line 564, in error
File "urllib/request.pyc", line 504, in _call_chain
File "urllib/request.pyc", line 756, in http_error_302
File "urllib/request.pyc", line 526, in open
File "urllib/request.pyc", line 544, in _open
File "urllib/request.pyc", line 504, in _call_chain
File "urllib/request.pyc", line 1361, in https_open
File "urllib/request.pyc", line 1320, in do_open
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>
runs fine on my local python
reference (relevant?):
why am i doing this in drawbot?
trying to get my students to get data from public APIs to generate text/images and post to twitter.
i could:
install drawbot as a module?
roll my own version?
- justvanrossum last edited by
@chuckloyola It fails for me in the same way, but also in Terminal. I have no idea why. It's more a general Python issue rather than one with DrawBot it seems.
- justvanrossum last edited by
The link you reference indeed explains the problem. I tried the first solution but it doesn't help. I don't have that command file in my machine to try that. | https://forum.drawbot.com/topic/44/ssl-error-known-ssl-osx-issue/3 | CC-MAIN-2019-04 | refinedweb | 374 | 63.86 |
37278/annotation-excluding-specific-fields-from-serialization
I'm trying to learn Gson and I'm struggling with field exclusion. Here are my classes
public class Student {
private Long id;
private String firstName = "Philip";
private String middleName = "J.";
private String initials = "P.F";
private String lastName = "Fry";
private Country country;
private Country countryOfBirth;
}
public class Country {
private Long id;
private String name;
private Object other;
}
I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or countrybut I can't seem to manage to exclude properties of certain fields like country.name.
Using the method public boolean shouldSkipField(FieldAttributes fa), FieldAttributes doesn't contain enough information to match the field with a filter like country.name.
I would appreciate any help with a solution for this problem.
P.S: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out.
Thank you
Simply mark the desired fields with the @Expose annotation, such as:
@Expose private Long id;
Leave out any fields that you do not want to serialize. Then just create your Gson object this way:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
You could turn the String into a ...READ MORE
@Override annotation is used when we override ...READ MORE
ADD 3 jars found in the following ...READ MORE
Of the three, LinkedList is generally going to give ...READ MORE
Hi @Daisy
You can use Google gson
for more ...READ MORE
You could probably check out Google's Gson: ...READ MORE
Serializable is a marker interface that has ...READ MORE
The docs for java.io.Serializable are probably about as good ...READ MORE
242
StringEscapeUtils from Apache Commons Lang:
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source ...READ MORE
o let the FirebaseRecyclerAdapter and FirebaseListAdapter show ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/37278/annotation-excluding-specific-fields-from-serialization | CC-MAIN-2022-21 | refinedweb | 327 | 56.96 |
-
Creating Dates with Calendar
You still receive deprecation warnings each time you compile. Bad, bad. You should get rid of the warnings before someone complains. The benefit of having moved the date creation into a separate method, createDate, is that now you will only have to make a change in one place in your code, instead of two, to eliminate the warnings.
Instead of creating a Date object using the deprecated constructor, you will use the GregorianCalendar class. You can build a date or timestamp from its constituent parts by using the set method defined in Calendar. The API documentation for Calendar lists the various date parts that you can set. The createDate method builds a date by supplying a year, a month, and a day of the month.
Date createDate(int year, int month, int date) { GregorianCalendar calendar = new GregorianCalendar(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, date); return calendar.getTime(); }
The GregorianCalendar is a bit more sensible than Date in that a year is a year. If the real year is 2005, you can pass 2005 to the calendar object instead of 105.
You will need to modify the import statements in CourseSessionTest in order to compile and test these changes. The simplest way is to import everything from the java.util package:
import java.util.*;
Compile and test. Congratulations—no more embarrassing deprecation warnings! | https://www.informit.com/articles/article.aspx?p=406343&seqNum=21 | CC-MAIN-2021-43 | refinedweb | 242 | 51.04 |
Hello all.
I'm feeling pretty confused about how UDP port forwarding is done. My situation is: I have Comp1 with a local IP (192.168.0.2) connected to Comp2 with external IP and internet connection, and some unknown Internet Client (IC) (three of them actually), who needs to send data to the Server hosted at Comp1 through UDP port 7777 and then receive a response.
I managed to forward UDP data from Comp2 to Comp1 by simply accepting IC's packets at Comp2's port 7777 and sending them to Comp1's port 7777, but the problem is that Comp1's Server sees sender as Comp2 and sends response to it (192.168.0.1), rather than to IC. I can't modify Server application and it judges about packets' source by UDP's IEP. Server then stores IEPs and sends data itself (it's p2p application actually).
I would think that the task is impossible, but this kind of forwarding is implemented in applications like AUTAPF (for both UDP and TCP ports).
So how do I forward ICs' data from Comp2 to Comp1 with Comp1's Server knowing, that response must be sent to ICs?
Here's what I managed to do:
namespace PortForwarder { class Program { public static UdpClient UDP1 = new UdpClient(7777); static void Main(string[] args) { Console.Title = "Port Forwarder"; Console.WriteLine("-= Port Forwarder started. =-"); Console.WriteLine("UDP ports forwarded: 7777"); UDP1.BeginReceive(ReceiveDataUDP1, null); while (true) { }; } static void ReceiveDataUDP1(IAsyncResult ar) { IPEndPoint IEP = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = UDP1.EndReceive(ar, ref IEP); // Trying to "lie" about local IEP results in exception // UdpClient US1 = new UdpClient(IEP); // US1.Send(receiveBytes, receiveBytes.Length, "192.168.0.2", 7777); UDP1.Send(receiveBytes, receiveBytes.Length, "192.168.0.2", 7777); UDP1.BeginReceive(ReceiveDataUDP1, null); } }
P.S. Comp1 is connected to the internet through Comp2's ICS (Internet Connection Sharing). Comp2 is running Windows Server 2008 and connects to the internet through VPN connection. I tried to set up NAT there, but VPN connection cannot be shared for some reason (and sharing public adapter doesn't help). If, by any chance, anybody knows how it's configured, I would be really grateful. :) | https://www.daniweb.com/programming/software-development/threads/235716/udp-port-forwarding | CC-MAIN-2018-43 | refinedweb | 366 | 57.47 |
AWS Database Blog
Streaming Changes in a Database with Amazon Kinesis
Emmanuel Espina is a software development engineer at Amazon Web Services.
In this blog post, I will discuss how to integrate a central relational database with other systems by streaming its modifications through Amazon Kinesis.
The following diagram shows a common architectural design in distributed systems. It includes a central storage referred to as a “single source of truth” and several derived “satellite” systems that consume this central storage.
You could use this design architecture and have a relational database as the central data store, taking advantage of the transactional capabilities of this system for maintaining the integrity of the data. A derived system in this context could be a full-text search system that observes this single source of truth for changes, transforms and filters those modifications, and finally updates its internal indexes. Another example could be a columnar storage more appropriate for OLAP queries. In general, any system that requires taking action upon modification of individual rows of the central relational system is a good candidate to become a derived data store.
A naive implementation for these kinds of architectures will have the derived systems issuing queries periodically to retrieve modified rows, essentially polling the central database with a SELECT-based query.
A better implementation for this architecture is one that uses an asynchronous stream of updates. Because databases usually have a transaction log where all of the changes in rows are stored, if this stream of changes is exposed to external observer systems, those systems could attach to these streams and start processing and filtering row modifications. I will show a basic implementation of this schema using MySQL as the central database and Amazon Kinesis as the message bus.
Normally, MYSQL binlog is exposed to read replicas that read all of the changes on the master and then apply them locally. In this post, I am going to create a generalized read replica that will publish changes to an Amazon Kinesis stream instead of applying the modifications to a local database.
One important detail of this method is that the consumers won’t receive SQL queries. Those can be exposed too, but in general observers won’t be very interested in SQL unless they maintain a SQL-compatible replica of the data themselves. Instead, they will receive modified entities (rows) one by one. The benefits of this approach are that consumers do not need to understand SQL and the single source of truth does not need to know who will be consuming its changes. That means that different teams can work without coordinating among themselves on the required data format. Even better, given the capabilities of Amazon Kinesis clients to read from a specific point in time, each consumer will process messages at its own pace. This is why a message bus is one of the less coupled ways to integrate your systems.
In the example used in this post, the rows fetcher is a regular Python process that will attach to the central database, simulating a read replica.
The database can be either Amazon RDS or any installation of MySQL. In the case of RDS, the fetcher process must be installed on a different host (for example, EC2) because it is not possible to install custom software on RDS instance hosts. For external installations, the fetcher process can be installed on the same host as the database.
Prepare the master MySQL instance
The MySQL master (the single source of truth) must be configured as if it were a master for regular replication. Binlogs must be enabled and working in ROW format to receive individual modified rows. (Otherwise, you would end up with SQL queries only.) For information, see The Binary Log on the MySQL site.
To enable the binlog, add these two lines to your my.cnf configuration file:
log_bin=<path to binlog>
binlog_format=ROW
It is possible to get row-based logging by setting the transaction isolation level to READ-COMMITTED at the global or session level for all connections (for example, using init_connect or a database API like JDBC).
If you are using RDS (MySql 5.6+), things are easy! You can create the required configuration by enabling periodic backups (binlogs are disabled if backups are not enabled) and updating the parameter group variable binlog_format to ROW. (You can do this from the RDS Dashboard under Parameter Groups.)
Add permissions
If you are using the default user created by RDS, you might already have these permissions. If not, you’ll need to create a user with REPLICATION SLAVE permissions. For information, see Creating a User for Replication.
mysql> CREATE USER 'repl'@'%.mydomain.com' IDENTIFIED BY 'slavepass';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%.mydomain.com';
Create an Amazon Kinesis stream
You need an Amazon Kinesis stream and boto3 client credentials. For information about client credentials, see the Boto 3 documentation.
Open the Amazon Kinesis console and choose Create Stream.
Enter the name of your stream and the number of shards. In this example, there is a single shard.
After a few minutes, your stream will be ready to accept row modifications!
Assign permissions to your CLI user
You can use the AWS Identity and Access Management (IAM) to give permissions to the CLI user that will be accessing this stream.
In this example, that user is KinesisRDSIntegration. You can create a user or use an existing one, but you need to add permissions for writing to the Amazon Kinesis stream.
You can create a policy specific for your stream. This example uses a standard policy that gives complete access to Amazon Kinesis.
Connecting to the master and publishing changes
To install libraries required by the Python publisher, run the following command:
pip install mysql-replication boto3
For more detailed instructions, see:
Here is the Python script that performs the magic. Remember to replace the <HOST>, <PORT>, <USER>, <PASSWORD> and <STREAM_NAME> variables with the values for your configuration.
import json import boto3 from pymysqlreplication import BinLogStreamReader from pymysqlreplication.row_event import ( DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent, ) def main(): kinesis = boto3.client("kinesis") stream = BinLogStreamReader( connection_settings= { "host": "<HOST>", "port": <PORT>, "user": "<USER>", "passwd": "<PASSWORD>"}, server_id=100, blocking=True, resume_stream=True, only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent]) for binlogevent in stream: for row in binlogevent.rows: event = {"schema": binlogevent.schema, "table": binlogevent.table, "type": type(binlogevent).__name__, "row": row } kinesis.put_record(StreamName="<STREAM_NAME>", Data=json.dumps(event), PartitionKey="default") print json.dumps(event) if __name__ == "__main__": main()
This script will publish each modified row as an Amazon Kinesis record, serialized in JSON format.
Consuming the messages
Now you are ready to consume the modified records. Any consumer code would work. If you use the code in this post, you will get messages in this format:
{"table": "Users", "row": {"values": {"Name": "Foo User", "idUsers": 123}}, "type": "WriteRowsEvent", "schema": "kinesistest"}
{"table": "Users", "row": {"values": {"Name": "Bar user", "idUsers": 124}}, "type": "WriteRowsEvent", "schema": "kinesistest"}
{"table": "Users", "row": {"before_values": {"Name": "Foo User", "idUsers": 123}, "after_values": {"Name": "Bar User", "idUsers": 123}}, "type": "UpdateRowsEvent", "schema": "kinesistest"}
Summary
In this blog post, I have shown how to expose the changes stream to the records of a database using a fake read replica and Amazon Kinesis. Many data-oriented companies are using architectures similar to this. The example provided in this post, while not ready for a real production environment, can be used to experiment with this integration style and improve the scaling capabilities of your enterprise architecture. The most complex part is probably what is already solved behind the scenes by Amazon Kinesis. You only need to provide the glue!
Additional resources
What every software engineer should know about real-time data’s unifying abstraction
All aboard the Databus: LinkedIn’s scalable consistent change data capture platform | https://aws.amazon.com/blogs/database/streaming-changes-in-a-database-with-amazon-kinesis/ | CC-MAIN-2020-45 | refinedweb | 1,289 | 53.41 |
IRC log of xhtml on 2007-06-20
Timestamps are in UTC.
13:50:29 [RRSAgent]
RRSAgent has joined #xhtml
13:50:29 [RRSAgent]
logging to
13:50:39 [Steven]
rrsagent, make log public
13:50:47 [Steven]
zakim, this will be xhtml
13:50:47 [Zakim]
ok, Steven; I see IA_XHTML2()10:00AM scheduled to start in 10 minutes
13:51:01 [Steven]
Meeting: Weekly XHTML2 WG Teleconference
13:51:33 [Steven]
Regrets: Susan, Alessio
13:51:55 [Steven]
Agenda:
13:52:04 [Steven]
Steven has changed the topic to: Agenda:
13:52:52 [Steven]
->
13:54:15 [Tina]
Tina has joined #xhtml
13:58:08 [ShaneM]
ShaneM has joined #xhtml
13:59:47 [Steven]
zakim, call steven-617
13:59:48 [Zakim]
ok, Steven; the call is being made
13:59:49 [Zakim]
IA_XHTML2()10:00AM has now started
13:59:50 [Zakim]
+Dialer
13:59:51 [Zakim]
-Dialer
13:59:55 [Zakim]
+Steven
14:00:29 [Zakim]
+ShaneM
14:00:47 [Zakim]
+Tina
14:01:22 [yamx]
yamx has joined #xhtml
14:02:25 [Zakim]
+??P16
14:02:28 [markbirbeck]
zakim, i am ?
14:02:29 [Zakim]
+markbirbeck; got it
14:03:31 [Zakim]
+??P17
14:03:44 [yamx]
this is yam
14:04:05 [yamx]
zakim, i am ??P17
14:04:05 [Zakim]
+yamx; got it
14:04:10 [Steven]
zakim, ??P17 is yamx
14:04:10 [Zakim]
I already had ??P17 as yamx, Steven
14:04:43 [Rich]
Rich has joined #xhtml
14:06:43 [Steven]
Scribe: Steven
14:06:56 [Steven]
Topic: Chair
14:07:07 [Zakim]
+??P18
14:08:20 [Steven]
zakim, ??P18 is Rich
14:08:20 [Zakim]
+Rich; got it
14:08:32 [Steven]
Steven: Roland Merrick of IBM will be joining me as co-chair
14:09:15 [Steven]
Topic: Roadmap
14:10:55 [Steven]
14:11:38 [Steven]
Here is the latest one:
14:16:25 [Steven]
Shane: There is a mismatch between the documents section and the milestones
14:16:33 [Steven]
Steven: All the more reason to update the roadmap document
14:17:05 [Steven]
Mark: It looks like the documents section is OK, only the milestones are missing some
14:17:13 [Steven]
ACTION: Steven to update the roadmap document
14:17:30 [Steven]
Topic: Wiki/Blog
14:20:42 [Steven]
Steven: DO we think this is a good idea?
14:20:47 [Steven]
... example:
14:21:23 [Steven]
Shane: It's a good idea
14:21:28 [Steven]
s/DO/Do/
14:21:50 [Steven]
ACTION: Steven investigate starting a blog and wiki
14:22:36 [Steven]
Topic: Vote on last call for Role and Access
14:23:03 [Steven]
Steven: I saw this as an action from last week
14:23:29 [Steven]
Shane: The final version of role is not ready, sorry
14:24:05 [Steven]
Tina: I had an action item to review the role document
14:25:56 [Steven]
... I'm not convinced wee need it
14:26:23 [Steven]
... I don't like representing semantics in attributes rather than elements
14:26:44 [Steven]
Steven: But it offeres extensibility in semantics without having to constantly revise the language
14:26:51 [Steven]
s/offeres/offers/
14:29:51 [Steven]
Tina: I'm worried that people will create semantics with <div role=
14:30:13 [Steven]
Steven: Agreed we have to talk about best practices
14:30:38 [Steven]
Rich: You can't stop people doing the wrong thing; at least we now have a way to extract the real semantics, rather than having to guess
14:32:34 [Steven]
Steven: The nice thing that this offers is a link to the semantic web way of defining semantics
14:33:40 [Steven]
Tina: For people who don't understand h1, rdf doesn't give them any value
14:33:51 [Steven]
Mark: I think you are missing the point
14:34:03 [Steven]
.... you don't have to understand rdf
14:34:11 [Steven]
... there are values you can use
14:34:40 [Steven]
... so we have the best of both worlds: a predefined list, and hooks into rdf which makes it extensible for the future
14:35:06 [Steven]
Tina: I'm worried that people will ad semantics with role
14:36:43 [Steven]
... if someone makes up their own semantics, there is no way to get out the real meaning
14:37:21 [Steven]
Steven: Yes there is! That's the nice thing about semweb tools: you can define the relationship between different semantics ('ontologies')
14:38:26 [Steven]
Rich: The nice thing about this apporach is that you don't need 'skip to' links for instance, and the browser still offers a shortcut to the main content
14:40:45 [Steven]
Steven: Are you going to do a review, or was this it Tina?
14:40:58 [Steven]
Tina: THe document is fine, I'm just worried about the principle.
14:41:51 [Steven]
Topic: Name and namespace
14:41:54 [Zakim]
-ShaneM
14:42:16 [Steven]
14:43:57 [Steven]
Shane: You know my opinion; they should not calll it XHTML unless they use modularization
14:44:36 [Steven]
Tina: There are two markup languages, HTML and XHTML. I'm not sure that HTLM5 is even HTML, but that is a different discussion
14:47:30 [Steven]
Rich: I'm worried about the confusion. I have no problems with HTML5/xml or so
14:47:43 [Steven]
... but not XHTML5
14:48:07 [Steven]
Mark: I don't see why they need two names. They have HTML5, with two serializations. No need for two names
14:48:17 [Steven]
Tina: I agree with the problem of confusion
14:48:30 [Steven]
... I've already seen it amongst developers.
14:49:23 [Steven]
Rich: ALl existing XHTMLs have been modular, and HTML5 is not. Its's a mess.
14:50:00 [Steven]
S/ALl/All
14:50:19 [Steven]
Yam: It doesn't make any sense for them to produce something called XHTML5
14:50:55 [yamx]
yamx has joined #xhtml
14:51:17 [Steven]
14:53:11 [Steven]
Steven: And now the namespace
14:53:34 [Steven]
... we were criticised in the past for having a different namespace, and therefore we changed it back (correctly in my view)
14:53:43 [ShaneM]
I concur.
14:53:50 [Steven]
Rich: I think HTML5 is not backwards compatible
14:54:01 [Steven]
Tina: Agreed, especially with elements changing meaning
14:55:43 [Steven]
Steven: I believe that XHTML2 is more backwards compatible than HTML5
14:56:16 [Steven]
Rich: If the browser manufacturers are going to have to make lal these changes for au=dio, video, canvas and so on, what''s the problem with a new namespace?
14:56:22 [Steven]
Steven: Good point
14:56:58 [Steven]
Topic: URL is overspecified
15:00:02 [Zakim]
-markbirbeck
15:00:03 [Zakim]
-Steven
15:00:04 [Zakim]
-yamx
15:00:06 [Zakim]
-Tina
15:01:09 [Steven]
StevenL udo the conversion to ascii
15:01:13 [Steven]
Yam: Quite agree
15:01:18 [Steven]
Mark: Sounds like a good idea
15:01:37 [Steven]
ACTION: Steven to get advice from I18N group about international form of URIs
15:01:50 [Steven]
s/StevenL/Steven:/
15:02:00 [Steven]
zakim, who is here?
15:02:02 [Zakim]
On the phone I see Rich
15:02:08 [Zakim]
On IRC I see ShaneM, Tina, RRSAgent, Zakim, Steven, markbirbeck, krijnh
15:02:08 [Steven]
zakim, drop rich
15:02:14 [Zakim]
Rich is being disconnected
15:02:16 [Zakim]
IA_XHTML2()10:00AM has ended
15:02:20 [Zakim]
Attendees were Dialer, Steven, ShaneM, Tina, markbirbeck, yamx, Rich
15:02:45 [Steven]
rrsagent, make minutes
15:02:45 [RRSAgent]
I have made the request to generate
Steven
15:03:24 [Steven]
Chair: Steven
15:06:13 [Steven]
rrsagent, make minutes
15:06:13 [RRSAgent]
I have made the request to generate
Steven
16:16:32 [Lachy]
Lachy has joined #xhtml
17:30:33 [Zakim]
Zakim has left #xhtml
19:23:03 [markbirbeck]
markbirbeck has joined #xhtml
20:21:19 [ShaneM]
ShaneM has joined #xhtml
21:11:39 [Steven]
Steven has left #xhtml | http://www.w3.org/2007/06/20-xhtml-irc | CC-MAIN-2015-48 | refinedweb | 1,369 | 63.56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.