potator/Encryption Package ( Java)
package cryptex;
public class substitution
{
public static String encrypt(String plaintext, String key)
{
//checks for a valid key
key = key.toLowerCase();
for(char x = 'a'; x <= 'z'; x++){
if(key.indexOf(x) == -1)
return "The key must contain all letters between a and z.";
}
//removes duplicate letters from the key
for(int x = 0; x < key.length(); x++){
for(char y = 'a'; y <= 'z'; y++){
for(int z = key.indexOf(y) + 1; z < key.length(); z++){
if(key.charAt(z) == y)
key = key.substring(0,z) + key.substring(z+1,key.length());
}
}
}
//removes spaces from the key
for(int x = 0; x < key.length(); x++){
if(key.charAt(x) == ' '){
key = key.substring(0,x) + key.substring(x+1,key.length());
x--;
}
}
//adds simple gramatical symbols to the key
key += "01928 !.?37465";
String key2 = ". ?!abcdefghijklmnopqrstuvwxyz";
plaintext = plaintext.toLowerCase();
String ciphertext = "";
for(int x = 0; x < plaintext.length(); x++){
ciphertext += key2.charAt(key.indexOf(plaintext.charAt(x)));
}
return ciphertext;
}
public static String decrypt(String ciphertext, String key)
{
//checks for a valid key
key = key.toLowerCase();
for(char x = 'a'; x <= 'z'; x++){
if(key.indexOf(x) == -1)
return "The key must contain all letters between a and z.";
}
//removes duplicate letters from the key
for(int x = 0; x < key.length(); x++){
for(char y = 'a'; y <= 'z'; y++){
for(int z = key.indexOf(y) + 1; z < key.length(); z++){
if(key.charAt(z) == y)
key = key.substring(0,z) + key.substring(z+1,key.length());
}
}
}
//removes spaces from the key
for(int x = 0; x < key.length(); x++){
if(key.charAt(x) == ' '){
key = key.substring(0,x) + key.substring(x+1,key.length());
x--;
}
}
//adds simple gramatical symbols and numbers to the key
key += "01928 !.?37465";
String key2 = ". ?!abcdefghijklmnopqrstuvwxyz";
ciphertext = ciphertext.toLowerCase();
String plaintext = "";
for(int x = 0; x < ciphertext.length(); x++){
plaintext += key.charAt(key2.indexOf(ciphertext.charAt(x)));
}
return plaintext;
}
}
package cryptex;
import java.util.TreeMap;
public class polyalphabetic
{
public static String encrypt(String plaintext, String key)
{
//convert the key to useable forms
StringBuffer sb = new StringBuffer(key);
for(int x = 0; x < sb.length(); x++){
if(sb.charAt(x) == ' '){
sb.deleteCharAt(x);
x--;
}
}
key = sb.toString();
while(key.length() < plaintext.length()){
key += key;
}
key = key.substring(0, plaintext.length());
//variables
String ciphertext = new String();
char[] plain = new char[plaintext.length()];
plain = plaintext.toCharArray();
char[] keyArray = new char[key.length()];
keyArray = key.toCharArray();
//initialize TreeMap map
TreeMap map = new TreeMap();
for(int x = '!'; x <= '~'; x++){
map.put(new Character((char)x), new Integer(x - '!'));
}
map.put(' ', 0);
//encrypt the message
for(int x = 0; x < plaintext.length(); x++){
int value = (int)plain[x] + Integer.parseInt(map.get(keyArray[x]).toString());
if(value > '~'){value -= (94);}
if(plain[x] == ' '){value = ' ';}
char temp = (char) value;
ciphertext += temp;
}
return ciphertext;
}
public static String decrypt(String ciphertext, String key)
{
//convert the key to a useable form
StringBuffer sb = new StringBuffer(key);
for(int x = 0; x < sb.length(); x++){
if(sb.charAt(x) == ' '){
sb.deleteCharAt(x);
x--;
}
}
key = sb.toString();
while(key.length() < ciphertext.length()){
key += key;
}
key = key.substring(0, ciphertext.length());
//variables
String plaintext = new String();
char[] cipher = new char[ciphertext.length()];
cipher = ciphertext.toCharArray();
char[] keyArray = new char[key.length()];
keyArray = key.toCharArray();
//initialize TreeMap map
TreeMap map = new TreeMap();
for(int x = '!'; x <= '~'; x++){
map.put(new Character((char)x), new Integer(x - '!'));
}
map.put(' ', 0);
//decrypt the message
for(int x = 0; x < ciphertext.length(); x++){
int value = (int)cipher[x] - Integer.parseInt(map.get(keyArray[x]).toString());
if(value < '!'){value += (94);}
if(cipher[x] == ' '){value = ' ';}
plaintext += (char) value;
}
return plaintext;
}
}
import cryptex.*;
public class tester
{
public static void main(String[] args)
{
//how to use the encrypt and decrypt methods:
String i = cryptex.substitution.encrypt("This is a sample!!!","the quick brown fox jumps over the lazy dog");
i = cryptex.polyalphabetic.encrypt(i,"COLTOR is teh W00t!!");
System.out.println(i);
i = cryptex.polyalphabetic.decrypt(i,"COLTOR is teh W00t!!");
i = cryptex.substitution.decrypt(i,"the quick brown fox jumps over the lazy dog");
System.out.println(i);
}
I wrote these quite some time ago. They are classes that accomplish standard and polyalphabetic substitution methods.
certainlyakey/Turn off wpautop (automatic converting of double line breaks into in paragraphs) in Wordpress ( PHP)
Open wp-includes/formatting.php, find this:
function wpautop
and comment its contents this way:
function wpautop($pee, $br = 1) {
//Removing wpautop - the only method working is modifying core formatting.php file
/*if ( trim($pee) === '' )
return '';
$pee = $pee . "\n"; // just to make things a little easier, pad the end
$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
// Space things out a little
$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend)';
$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
$pee = str_replace(array("
", "\r"), "\n", $pee); // cross-platform newlines
if ( strpos($pee, '<object') !== false ) {
$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
}
$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
// make paragraphs, including one at the end
$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
$pee = '';
foreach ( $pees as $tinkle )
$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
if ($br) {
$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
}
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
if (strpos($pee, '<pre') !== false)
$pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
*/
return $pee;
}
MostThingsWeb/dialogWrapper - version 1.6 ( JavaScript)
/*
* Version 1.6
*
* http://mosttw.wordpress.com/
*
* Licensed under MIT License: http://en.wikipedia.org/wiki/MIT_License
*
* Copyright (c) 2010 MostThingsWeb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
* Changelog:
*
* Version 1.6
* - Fixed overlay overflow issues in IE
* - Fixed overlay fadeIn in IE
*
*
* Version 1.5
* - Release
*
*/
/*
*
* Portions of this software come from jQuery UI Dialog 1.8.4
* License (below):
*
* jQuery UI Dialog 1.8.4
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Dialog
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.button.js
* jquery.ui.draggable.js
* jquery.ui.mouse.js
* jquery.ui.position.js
* jquery.ui.resizable.js
*/
(function($) {
// Get the dialog widget factory prototype
var proto = $.ui.dialog.prototype;
// Members need access to these class names
var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ';
// Internal function used to generate a random ID
function randomID() {
var id = "";
for ( var i = 1; i <= 10; i++)
id += (Math.floor(Math.random() * 10) + 1);
return id;
}
// To fade in the overlay without it going crazy, we need to know the opacity level
// set in the CSS
var overlayOpacity;
var overlayTestID = randomID();
var overlayReg = /Opacity=(\d+)/;
// Extract the opacity level
$("body").append("<div id='" + overlayTestID + "' class='ui-widget-overlay' style='display: none;'></div>");
try {
var overlayFilter = $("#" + overlayTestID).css("filter");
if (overlayReg.test(overlayFilter))
overlayOpacity = overlayReg.exec(overlayFilter)[1];
}
catch (ex){}
// If no overlay opacity is defined, assume 0 opacity
if (!overlayOpacity)
overlayOpacity = 0;
$("#" + overlayTestID).remove();
// Store the modified create() method
var _createMod = function() {
this.originalTitle = this.element.attr('title');
// #5742 - .attr() might return a DOMElement
if (typeof this.originalTitle !== "string")
this.originalTitle = "";
var self = this, options = self.options,
title = options.title || self.originalTitle || '&#160;', titleId = $.ui.dialog
.getTitleId(self.element),
uiDialog = (self.uiDialog = $('<div></div>')).appendTo(document.body)
.hide().addClass(uiDialogClasses + options.dialogClass).css( {
zIndex : options.zIndex
})
// setting tabIndex makes the div focusable
// setting outline to 0 prevents a border on focus in Mozilla
.attr('tabIndex', -1).css('outline', 0).keydown(
function(event) {
if (options.closeOnEscape && event.keyCode
&& event.keyCode === $.ui.keyCode.ESCAPE) {
self.close(event);
event.preventDefault();
}
}).attr( {
role : 'dialog',
'aria-labelledby' : titleId
}).mousedown(function(event) {
self.moveToTop(false, event);
}),
uiDialogContent = self.element.show().removeAttr('title').addClass(
'ui-dialog-content ' + 'ui-widget-content').appendTo(uiDialog),
uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>'))
.addClass(
'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix')
.prependTo(uiDialog);
// Control the creation of the close 'X'
if (options.hasClose)
var uiDialogTitlebarClose = $('<a href="#"></a>').addClass(
'ui-dialog-titlebar-close ' + 'ui-corner-all').attr('role',
'button').hover(function() {
uiDialogTitlebarClose.addClass('ui-state-hover');
}, function() {
uiDialogTitlebarClose.removeClass('ui-state-hover');
}).focus(function() {
uiDialogTitlebarClose.addClass('ui-state-focus');
}).blur(function() {
uiDialogTitlebarClose.removeClass('ui-state-focus');
}).click(function(event) {
self.close(event);
return false;
}).appendTo(uiDialogTitlebar),
uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>'))
.addClass('ui-icon ' + 'ui-icon-closethick').text(
options.closeText).appendTo(uiDialogTitlebarClose);
var uiDialogTitle = $('<span></span>').addClass('ui-dialog-title')
.attr('id', titleId).html(title).prependTo(uiDialogTitlebar);
// handling of deprecated beforeclose (vs beforeClose) option
// Ticket #4669 http://dev.jqueryui.com/ticket/4669
// TODO: remove in 1.9pre
if ($.isFunction(options.beforeclose)
&& !$.isFunction(options.beforeClose))
options.beforeClose = options.beforeclose;
uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();
if (options.draggable && $.fn.draggable)
self._makeDraggable();
if (options.resizable && $.fn.resizable)
self._makeResizable();
self._createButtons(options.buttons);
self._isOpen = false;
if ($.fn.bgiframe)
uiDialog.bgiframe();
};
// Override the destroy method to control the overlay
proto.destroy = function() {
var self = this;
self.uiDialog.hide();
self.element.unbind('.dialog').removeData('dialog').removeClass(
'ui-dialog-content ui-widget-content').hide().appendTo('body');
self.uiDialog.remove();
if (self.originalTitle)
self.element.attr('title', self.originalTitle);
return self;
};
proto.close = function() {
$.hideDialog();
};
// Override the open method to add fadeIn effect
proto.open = function(){
if (this._isOpen)
return;
var self = this, options = self.options, uiDialog = self.uiDialog;
// If an overlay is open, remember that
var overlayOpen = $(".ui-widget-overlay:visible").size() != 0;
// Open overlay
self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null;
if (uiDialog.next().length)
uiDialog.appendTo('body');
self._size();
self._position(options.position);
var $dialog = uiDialog.show(options.show);
// Fix the modal positioning in IE
if (options.modal)
$(".ui-widget-overlay").css("position", "fixed")
// Add fadeIn effect
if (options.fadeIn) {
if (!overlayOpen && options.modal){
// IE needs to have the filter attribute applied before it fades in
$(".ui-widget-overlay").hide().css('filter', 'alpha(opacity=' + overlayOpacity + ')').fadeIn("normal");
}
$dialog.hide().fadeIn("normal");
}
self.moveToTop(true);
// prevent tabbing out of modal dialogs
if (options.modal) {
uiDialog.bind('keypress.ui-dialog', function(event) {
if (event.keyCode !== $.ui.keyCode.TAB)
return;
var tabbables = $(':tabbable', this), first = tabbables
.filter(':first'), last = tabbables.filter(':last');
if (event.target === last[0] && !event.shiftKey) {
first.focus(1);
return false;
} else if (event.target === first[0] && event.shiftKey) {
last.focus(1);
return false;
}
});
}
// set focus to the first tabbable element in the content area or the
// first button
// if there are no tabbable elements, set focus on the dialog itself
$(
self.element.find(':tabbable').get().concat(
uiDialog.find('.ui-dialog-buttonpane :tabbable').get()
.concat(uiDialog.get()))).eq(0).focus();
self._trigger('open');
self._isOpen = true;
return self;
};
// Internal function used for getting the element on top
function getTopElement(elems) {
// Store the greates z-index that has been seen so far
var maxZ = 0;
// Stores a reference to the element that has the greatest z-index so
// far
var maxElem;
// Check each element's z-index
elems.each(function() {
// If it's bigger than the currently biggest one, store the value
// and reference
if ($(this).css("z-index") > maxZ) {
maxElem = $(this);
maxZ = $(this).css("z-index");
}
});
// Finally, return the reference to the element on top
return maxElem;
}
$.showDialog = function(title, prompt, args) {
var options = {
resizable : false,
draggable : true,
closeOnEscape : false,
moveToTop : true,
title : title,
hasClose : true,
fadeIn : true
};
$.extend(options, args);
// Add some custom options
if (!options.hasClose)
$dialog._create = _createMod;
var id = randomID();
if ($("#dialogContainer").size() == 0)
$("body").append("<div id='dialogContainer'></div>");
// Add a div for the dialog after the special dialogContainer target div
$("#dialogContainer").after(
"<div id='m" + id + "'><p><div id='mp" + id + "'>" + prompt
+ "</div></p></div>");
$("#m" + id).dialog(options);
// Remove duplicate overlays
if ($(".ui-widget-overlay").size() > 1)
$(".ui-widget-overlay:first").remove();
return id;
};
$.hideDialog = function(id, fadeOut) {
// If an ID was not supplied, get the ID of the dialog currently on top
id = id
|| "#"
+ getTopElement($(".ui-dialog")).find(".ui-dialog-content")
.attr("id");
fadeOut = fadeOut || true;
// Remove the dialog
$(id).parent().andSelf().remove();
// If no dialogs are currently visible, remove the overlay
if ($(".ui-dialog:visible").size() === 0) {
if (fadeOut)
$(".ui-widget-overlay").fadeOut("normal");
else
$(".ui-widget-overlay").hide();
} else {
// If one or more overlays exist, change the z-index of the overlay
// so it is below the top-most dialog
$(".ui-widget-overlay")
.css(
{
"z-index" : parseInt(
getTopElement($(".ui-dialog:visible"))
.css("z-index"), 10) - 1
});
}
// Remove event blocking left over from the overlay
$.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
function(event) {
$(document).unbind(event + '.dialog-overlay');
});
};
$.clearDialogs = function(fadeOut) {
fadeOut = fadeOut || true;
// Find all the dialogs
$(".ui-dialog").each(function() {
// Remove them
$(this).find(".ui-dialog-content").parent().andSelf().remove();
});
// Remove the overlay
if (fadeOut)
$(".ui-widget-overlay").fadeOut("normal");
else
$(".ui-widget-overlay").hide();
// Remove event blocking left over from the overlay
$.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
function(event) {
$(document).unbind(event + '.dialog-overlay');
});
};
$.alert = function(prompt, arg) {
var args;
args = $.extend(args, arg, {
buttons : {
"Ok" : function() {
// When the Ok button is clicked, just hide this dialog
$.hideDialog(this);
}
}
} );
return $.showDialog("Info", prompt, args);
};
$.confirm = function(prompt, yes, no, arg) {
var args;
args = $.extend(args, arg, {
buttons : {
"No" : function() {
(no || $.noop).call();
$.hideDialog(this);
},
"Yes" : function() {
(yes || $.noop).call();
$.hideDialog(this);
}
}
});
return $.showDialog("Confirm", prompt, args);
};
})(jQuery);
Andrew Dalke/OrderedMultiDict and UnorderedMultiDict ( python)
# Written in 2003 by Andrew Dalke, Dalke Scientific Software, LLC.
# This software has been released to the public domain. No
# copyright is asserted.
from __future__ import generators
# Implementation inheritence -- not asserting a class hierarchy here
#
# If there is a class hierarchy, OrderedMultiDict is a child of
# UnorderedMultiDict because it makes stronger but not different
# guarantees on how the data works, at least data-wise.
# Performance-wise, Ordered has a slower (O(n)) than Unordered (O(1)).
# Convince me otherwise and I'll change. Besides, hierarchies are
# overrated.
class _BaseMultiDict:
def __str__(self):
"""shows contents as if this is a dictionary
If multiple values exist for a given key, use the last
one added.
"""
d = {}
for k in self.data:
d[k] = self.data[k][-1]
return str(d)
def __len__(self):
"""the number of unique keys"""
return len(self.data)
def __getitem__(self, key):
"""value for a given key
If more than one value exists for the key, use one added most recently
"""
return self.data[key][-1]
def get(self, key, default = None):
"""value for the given key; default = None if not present
If more than one value exists for the key, use the one added
most recently.
"""
return self.data.get(key, [default])[-1]
def __contains__(self, key):
"""check if the key exists"""
return key in self.data
def keys(self):
"""unordered list of unique keys"""
return self.data.keys()
def values(self):
"""unordered list of values
If more than one value exists for a given key, use the value
added most recently.
"""
return [x[-1] for x in self.data.values()]
def items(self):
"""unordered list of key/value pairs
If more than one value exists for a given key, use the value
added most recently.
"""
return [(k, v[-1]) for k, v in self.data.items()]
def getall(self, key):
"""Get all values for a given key
Multiple values are returned in input order.
If the key does not exists, returns an empty list.
"""
return self.data[key]
def __iter__(self):
"""iterate through the list of unique keys"""
return iter(self.data)
class OrderedMultiDict(_BaseMultiDict):
"""Store key/value mappings.
Acts like a standard dictionary with the following features:
- duplicate keys are allowed;
- input order is preserved for all key/value pairs.
>>> od = OrderedMultiDict([("Food", "Spam"), ("Color", "Blue"),
... ("Food", "Eggs"), ("Color", "Green")])
>>> od["Food"]
'Eggs'
>>> od.getall("Food")
['Spam', 'Eggs']
>>> list(od.allkeys())
['Food', 'Color', 'Food', 'Color']
>>>
The order of keys and values(eg, od.allkeys() and od.allitems())
preserves input order.
Can also pass in an object to the constructor which has an
allitems() method that returns a list of key/value pairs.
"""
def __init__(self, multidict = None):
self.data = {}
self.order_data = []
if multidict is not None:
if hasattr(multidict, "allitems"):
multidict = multidict.allitems()
for k, v in multidict:
self[k] = v
def __eq__(self, other):
"""Does this OrderedMultiDict have the same contents and order as another?"""
return self.order_data == other.order_data
def __ne__(self, other):
"""Does this OrderedMultiDict have different contents or order as another?"""
return self.order_data != other.order_data
def __repr__(self):
return "<OrderedMultiDict %s>" % (self.order_data,)
def __setitem__(self, key, value):
"""Add a new key/value pair
If the key already exists, replaces the existing value
so that d[key] is the new value and not the old one.
To get all values for a given key, use d.getall(key).
"""
self.order_data.append((key, value))
self.data.setdefault(key, []).append(value)
def __delitem__(self, key):
"""Remove all values for the given key"""
del self.data[key]
self.order_data[:] = [x for x in self.order_data if x[0] != key]
def allkeys(self):
"""iterate over all keys in input order"""
for x in self.order_data:
yield x[0]
def allvalues(self):
"""iterate over all values in input order"""
for x in self.order_data:
yield x[1]
def allitems(self):
"""iterate over all key/value pairs in input order"""
return iter(self.order_data)
class UnorderedMultiDict(_BaseMultiDict):
"""Store key/value mappings.
Acts like a standard dictionary with the following features:
- duplicate keys are allowed;
- input order is preserved for all values of a given
key but not between different keys.
>>> ud = UnorderedMultiDict([("Food", "Spam"), ("Color", "Blue"),
... ("Food", "Eggs"), ("Color", "Green")])
>>> ud["Food"]
'Eggs'
>>> ud.getall("Food")
['Spam', 'Eggs']
>>>
The order of values from a given key (as from ud.getall("Food"))
is guaranteed but the order between keys (as from od.allkeys()
and od.allitems()) is not.
Can also pass in an object to the constructor which has an
allitems() method that returns a list of key/value pairs.
"""
def __init__(self, multidict = None):
self.data = {}
if multidict is not None:
if hasattr(multidict, "allitems"):
multidict = multidict.allitems()
for k, v in multidict:
self[k] = v
def __eq__(self, other):
"""Does this UnorderedMultiDict have the same keys, with values in the same order, as another?"""
return self.data == other.data
def __ne__(self, other):
"""Does this UnorderedMultiDict NOT have the same keys, with values in the same order, as another?"""
return self.data != other.data
def __repr__(self):
return "<UnorderedMultiDict %s>" % (self.data,)
def __setitem__(self, key, value):
"""Add a new key/value pair
If the key already exists, replaces the existing value
so that d[key] is the new value and not the old one.
To get all values for a given key, use d.getall(key).
"""
self.data.setdefault(key, []).append(value)
def __delitem__(self, key):
"""Remove all values for the given key"""
del self.data[key]
def allkeys(self):
"""iterate over all keys in arbitrary order"""
for k, v in self.data.iteritems():
for x in v:
yield k
def allvalues(self):
"""iterate over all values in arbitrary order"""
for v in self.data.itervalues():
for x in v:
yield x
def allitems(self):
"""iterate over all key/value pairs, in arbitrary order
Actually, the keys are iterated in arbitrary order but all
values for that key are iterated at sequence of addition
to the UnorderedMultiDict.
"""
for k, v in self.data.iteritems():
for x in v:
yield (k, x)
This implements two types of dictionary-like objects where there can be more than one entry with the same key. One is OrderedMultiDict, which preserves the order of all entries across all keys. The other is UnorderedMultidict, which only preserves the order of entries for the same key.
Download MultiDict.py Example:
>>> import MultiDict
>>> od = MultiDict.OrderedMultiDict()
>>> od["Name"] = "Andrew"; od["Color"] = "Green"
>>> od["Name"] = "Karen"; od["Color"] = "Brown"
>>> od["Name"]
'Karen'
>>> od.getall("Name")
['Andrew', 'Karen']
>>> for k, v in od.allitems():
... print "%r == %r", (k, v)
...
'Name' == 'Andrew'
'Color' == 'Green'
'Name' == 'Karen'
'Color' == 'Brown'
>>> ud = MultDict.UnorderedMultiDict(od)
>>> for k, v in ud.allitems():
... print "%r == %r", (k, v)
...
'Name' == 'Andrew'
'Name' == 'Karen'
'Color' == 'Green'
'Color' == 'Brown'
>>>
Patrick Finnegan/Install J2c Auth Id. ( python)
#
# Install J2C Auth ID.
#
####################################################################
# Patrick Finnegan 23/05/2005. V1.
####################################################################
####################################################################
# Create Security Object for database connection.
####################################################################
proc createSecurityObj {j2cAlias userid password description} {
puts "\nCreate Security Object\n"
global AdminConfig
puts "\nList installed JAASAuthData authentication entries\n"
set JAASentries [ $AdminConfig list JAASAuthData ]
foreach e $JAASentries {
set subList [ $AdminConfig show $e ]
foreach e $subList {
puts [ format "%-5s %-30s %-20s" " " [ lindex $e 0 ] [ lindex $e 1 ] ]
}
puts "\n"
}
puts "\nRemove Possible Duplicate Entries\n"
set i 0
while { $i < [llength $JAASentries] } {
puts " index is [ lindex [ $AdminConfig show [lindex $JAASentries $i ] ] 0 ]"
catch { lsearch [ lindex [ $AdminConfig show [lindex $JAASentries $i ] ] 0 ] $j2cAlias } r
if { $r == -1 } {
puts "\n no match for $j2cAlias\n"
} else {
puts "\n **** Delete $j2cAlias **** \n"
catch { $AdminConfig remove [ lindex $JAASentries $i ] } r
puts $r
}
incr i
}
# set attributes for userid
set alias [list alias $j2cAlias ]
set description [list description $description ]
set userid [list userId $userid ]
set password [list password $password ]
set jaasAttrs [list $alias $description $userid $password]
# create JAASAuthData object under security parent
$AdminConfig create JAASAuthData [$AdminConfig list Security] $jaasAttrs
puts "\nList installed JAASAuthData authentication entries - confirm change \n"
foreach e [ $AdminConfig list JAASAuthData ] {
set subList [ $AdminConfig show $e ]
foreach e $subList {
puts [ format "%-5s %-30s %-20s" " " [ lindex $e 0 ] [ lindex $e 1 ] ]
}
puts "\n"
}
}
####################################################################
# Main Control.
####################################################################
puts "\n argc = $argc \n"
if {$argc < 4 } {
return -code error "error - not enough arguments supplied. Supply j2cAlias description userid password"
}
puts "\n Check"
set j2cAlias [lindex $argv 0 ]
set j2cDesc [lindex $argv 1 ]
set userid [lindex $argv 2 ]
set password [lindex $argv 3 ]
set cellId [ lindex [ $AdminConfig list Cell ] 0 ]
set nodes [ $AdminConfig list Node ]
# delete the manager node from the list.
set manIndex [ lsearch -glob $nodes *Manager* ]
set nodeId [ lindex [ lreplace $nodes $manIndex $manIndex ] 0 ]
# delete the manager node from the list.
set cellName [ $AdminConfig showAttribute $cellId name ]
set nodeName [ $AdminConfig showAttribute $nodeId name ]
puts "\n Cell Name: $cellName"
puts "\n Node Name: $nodeName \n"
puts " j2cAlias = $j2cAlias "
puts " j2cDesc = $j2cDesc "
puts " userid = $userid "
puts " password = $password "
####################################################################
# Create DB connection Id.
# Must exist before assignment to datasource.
####################################################################
createSecurityObj $j2cAlias $userid $password $j2cDesc
####################################################################
# Save Admin config.
####################################################################
$AdminConfig save
puts [ format "\n %-30s %-30s" " " "*** THE END ***\n" ]
Installs a J2C Authorization ID.
thesmu/WordPress, IIS, Permalinks and index.php | Richard Shepherd ( PHP)
Here’s the problem:
You need to install WordPress on a Windows machine running IIS. I’d never normally do this, but sometimes you just don’t have a choice.
There are plenty of links out there about how to do this, and the one I referred to most was How To Install WordPress on IIS 6.0. It is, more or less, straightforward.
However, there’s an issue with IIS and permalinks.The issue is that if you want to take advantage of the WordPress pretty permalinks, you have to suffer a folder in the path called ‘index.php’. So, instead of the rather lovely:
http://www.yourblog.com/yourcategories/the-best-post-in-the-world/
you have to grit your teeth and accept:
http://www.yourblog.com/index.php/yourcategories/the-best-post-in-the-world/
I don’t know why, I really don’t. I’m not that smart. But I did work out how to fix it. It’s easy enough, but you have to put a couple of rules in the ISAPI ReWrite Engine to deal with the quirks.
First we need to head into our WordPress admin tool, and go to Settings > Permalinks. There, you’ll see the craft insertion of /index.php/ in the links. We need to create a custom permalink and delete the index.php bit. Just like this…
Now save that off and head over to your .htaccess file – we need to weave some magic!
At the bottom of this post is the whole file, but the two lines I particularly want to point out are:
1
2
RewriteCond %{REQUEST_URI} !/wp-admin
RewriteRule ^/(.*)/$ /index.php/$1 [NC]
The second line works the juju. It takes the URL from the browser, shoves an /index.php/ into it, and displays the contents. For more on how and why this works, check out http://www.workingwith.me.uk/articles/scripting/mod_rewrite for the basics.
Now the first line is really important, because it tells the server not to do this if we’re in the admin section. If we remove this line, there are all kinds of problems reaching /wp-admin/index.php. Trust me.
I have two other lines in the following code which get rid of index.php from URLS, which stops the google duplicate content issue. They’re always worth having.
Finally, make sure that wherever your site is hosted, that the correct permissions are set on the wp-admin and wp-content directories and their sub-directories. You must have read/write/modify permissions set for internal user accounts.
If you implement these small tweaks, then your WordPress IIS install should work like a charm.
Good luck!
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -------------------------------------------------------------------------
# Kickstart the Rewrite Engine and set initial options
# -------------------------------------------------------------------------
RewriteEngine On
RewriteCompatibility2 On
RepeatLimit 200
RewriteBase
# -------------------------------------------------------------------------
# WORDPRESS, WINDOWS & ISAPI DOCUMENTATION
# -------------------------------------------------------------------------
# These are the WordPress redirects we need in place for a Windows Server
# running PHP & MySQL
# We had some issues configuring ISAPI with WordPress and so here are the
# solutions in case we need them again!!
# -------------------------------------------------------------------------
# PERMISSIONS SETTINGS
# -------------------------------------------------------------------------
# The following folders:
# wp-admin
# wp-content
# MUST HAVE read/write/modify permissions set for internal user accounts
# -------------------------------------------------------------------------
# ESSENTIAL WORDPRESS REWRITES
# -------------------------------------------------------------------------
# Redirects 'www.yourblogsite.com/index.php' to 'www.yourblogsite.com/'
RewriteRule ^/index.php$ / [NC,P,R=301]
# Rewrite 'www.yourblogsite.com/anything/' to 'www.yourblogsite.com/index.php/anything/'
# NB. The user does not see this rewrite.
# Must also go into WordPress > Settings > Permalinks and select 'custom'
# and then REMOVE 'index.php' from the custom URL it generates
# The first line is a condition so it doesn't apply the rule to the wp-admin part of the site
RewriteCond %{REQUEST_URI} !/wp-admin
RewriteRule ^/(.*)/$ /index.php/$1 [NC]
# Finally, redirect 'www.yourblogsite.com/anything/anything/index.php'
# to 'www.yourblogsite.com/anything/anything/'
RewriteRule ^/(.*)/index.php$ /$1/ [NC,P,R=301]
# -------------------------------------------------------------------------
# END OF ESSENTIAL REWRITES
# -----------------------------
WordPress, IIS, Permalinks and index.php | Richard Shepherd
FB36/Binary Search Tree ( python)
// bst.cpp
// binary search tree
// FB - 201101263
#include<iostream>
#include<iomanip> //width()
using namespace std;
#define width_unit 5
class Tree
{
private:
class Node
{
public:
int data;
Node *left, *right;
Node(int d=0) //constructor
:data(d), left(NULL), right(NULL) {}
};
Node *root;
Node * trav(int, Node * &);
void chop(Node * N);
void copy(Node * N);
void print(ostream &, Node *, int) const;
void print(Node *, int) const;
public:
Tree(void); //constructor
~Tree(void); //destructor
bool find(int);
void insert(int);
void remove(int);
bool empty(void) const;
Tree(const Tree &); //copy constructor
const Tree & operator=(const Tree &); //assignment operator overload
friend ostream & operator<<(ostream &, const Tree &);
};
Tree::Tree(void)
{
root=NULL;
}
bool Tree::empty(void) const
{
return !root;
}
Tree::Node * Tree::trav(int foo, Node * & par)
{
Node * curr=root;
par=NULL;
while(curr && curr->data != foo)
{
par=curr;
if(foo < curr->data)
curr=curr->left;
else
curr=curr->right;
}
return curr;
}
bool Tree::find(int foo)
{
Node * par=NULL;
Node * curr=trav(foo, par);
return curr;
}
void Tree::insert(int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(!curr) //no duplicates
{
curr= new Node(foo);
if(!par)
root=curr;
else if(foo < par->data)
par->left=curr;
else
par->right=curr;
}
}
void Tree::remove(const int foo)
{
Node * par=NULL; //parent is null by default
Node * curr=trav(foo,par); //locate the node of the foo
if(curr) //if it is not null then
{
if(curr->left && curr->right) //2 children case
{
Node * tmp=curr;
par=curr;
curr=curr->left;
while(curr->right)
{
par=curr;
curr=curr->right;
}
tmp->data=curr->data;
}
//1 or 0 child case
Node *tmp=(curr->left ? curr->left : curr->right);
if(!par)
root=tmp;
else if(par->data < curr->data)
par->right=tmp;
else
par->left=tmp;
delete curr;
}
}
void Tree::chop(Node *N)
{
if(N)
{
chop(N->left);
chop(N->right);
delete N;
}
}
//destructor
Tree::~Tree(void)
{
chop(root);
}
Tree::Tree(const Tree & T)
{
root=NULL;
copy(T.root);
}
void Tree::copy(Node * N)
{
if(N)
{
insert(N->data);
copy(N->left);
copy(N->right);
}
}
const Tree & Tree::operator=(const Tree & T)
{
if(this != &T)
{
chop(root);
root=NULL;
copy(T.root);
}
return *this;
}
//the recursive tree output
void Tree::print(ostream & ost, Node * curr, int level) const
{
if(curr) //if the current node is not null then
{
print(ost,curr->right,level+1); //try to go to right node
//output the node data w/ respect to its level
ost<<setw(level*width_unit)<<curr->data<<endl;
print(ost,curr->left,level+1); //try to go to left node
}
}
//the recursive tree print
void Tree::print(Node * curr, int level) const
{
if(curr) //if the current node is not null then
{
print(curr->right,level+1); //try to go to right node
//print the node data w/ respect to its level
cout<<setw(level*width_unit)<<curr->data<<endl;
print(curr->left,level+1); //try to go to left node
}
}
ostream & operator<<(ostream &ost, const Tree &t)
{
t.print(ost, t.root, 1);
return ost;
}
//Test
int main()
{
Tree mytree;
mytree.insert(5);
mytree.insert(3);
mytree.insert(2);
mytree.insert(7);
mytree.insert(0);
mytree.insert(2);
cout<<mytree<<endl<<endl;
mytree.remove(0);
cout<<mytree<<endl<<endl;
mytree.remove(5);
cout<<mytree<<endl<<endl;
mytree.insert(9);
mytree.insert(10);
mytree.insert(4);
cout<<mytree<<endl<<endl;
mytree.remove(9);
cout<<mytree<<endl<<endl;
Tree mytree2=mytree; //calls the copy constructor, not the assignment
cout<<mytree2<<endl<<endl;
Tree mytree3;
mytree3=mytree2; //calls the assignment operator overload
cout<<mytree3<<endl<<endl;
return 0;
}
Binary Search Tree.
Andres Tuells/Scheduled Queue ( python)
"""
A scheduled queue is a queue with priorities that are scheduled. It is not preemtitive, higher priorities are not
executed always before than lower priorities (only more often).
USAGE:
init args:
maxsize: maximum size of the queue, if maxsize<=0 then the queue size is infinite
realtime: if true then the queue has a priority REAL_TIME. REAL_TIME priorities are executed before any other priorities.items
idle: if true then the queue has a priority IDLE. IDLE priorities are executed when there are no other priorities left.
priorities: a dictionary with the definitions of the priorities. The key defines the priority name and the value (an int>0)
defines the relative importance of the priority. A higher number implies that the priority will be checked first more often.
In this implementation:
36 = VERY_HIGH + HIGH + ABOVE_DEFAULT + BELOW_DEFAULT + DEFAULT + BELOW_DEFAULT + LOW + VERY_LOW
VERY_HIGH priorities are checked first 10/36 times
VERY_LOW only of 1/36
Of every 36 gets at least one will be VERY_LOW (if VERY_LOW queue is not empty). Even if there are higher non
empty queue of higher priority VERY_LOW will be checked once every 36 gets.
"""
from Queue import Queue, Full, Empty
#standard priorities
REAL_TIME = 999
VERY_HIGH = 10
HIGH = 8
ABOVE_DEFAULT = 6
DEFAULT = 5
BELOW_DEFAULT = 4
LOW = 2
VERY_LOW = 1
IDLE = -1
standard_priorities = {VERY_HIGH :10,
HIGH :8,
ABOVE_DEFAULT :6,
DEFAULT :5,
BELOW_DEFAULT :4,
LOW :2,
VERY_LOW :1}
class ScheduledQueue(Queue):
def __init__(self, maxsize=0, priorities = standard_priorities, realtime = 1, idle = 1):
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
priorities: a dictionary with definition of priorities
"""
assert self._check_priorities(priorities) #check only if not -OO
import thread
self._init(priorities, maxsize, realtime, idle)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire()
self.fsema = thread.allocate_lock()
def put(self, item, priority = DEFAULT, block=1):
"""Put an item into the queue.
If optional arg 'block' is 1 (the default), block if
necessary until a free slot is available. Otherwise (block
is 0), put an item on the queue if a free slot is immediately
available, else raise the Full exception.
"""
assert self._queues.has_key(priority),"inexistent priority "+str(priority)
self._acquirePUT(block)
was_empty = self._empty()
try:
self._put(item, priority)
finally:
self._releasePUT(was_empty)
def put_nowait(self, item, priority = DEFAULT):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, priority, 0)
def get(self, block=1):
"""Remove and return an item from the queue.
If optional arg 'block' is 1 (the default), block if
necessary until an item is available. Otherwise (block is 0),
return an item if one is immediately available, else raise the
Empty exception.
"""
self._acquireGET(block)
was_full = self._full()
try:
item = self._get()
finally:
self._releaseGET(was_full)
return item
def drain(self):
self.mutex.acquire()
self._drain()
self.mutex.release()
def _acquirePUT(self, block):
if block:
self.fsema.acquire()
elif not self.fsema.acquire(0):
raise Full
self.mutex.acquire()
def _acquireGET(self, block):
if block:
self.esema.acquire()
elif not self.esema.acquire(0):
raise Empty
self.mutex.acquire()
was_full = self._full()
def _releasePUT(self, was_empty):
if was_empty:
self.esema.release()
if not self._full():
self.fsema.release()
self.mutex.release()
def _releaseGET(self, was_full):
if was_full:
self.fsema.release()
if not self._empty():
self.esema.release()
self.mutex.release()
def __len__(self):
return self.qsize()
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
def _qsize(self):
return self._len
def _empty(self):
"""Check whether the queue is empty"""
return not self._len
def _full(self):
"""Check whether the queue is full"""
return self.maxsize > 0 and self._len >= self.maxsize
def _put(self, item, priority):
"""Put a new item in the queue"""
self._queues[priority].append(item)
self._len += 1
# Get an item from the queue
def _get(self):
item = filter(None,self._roundRobinQueues.get())[0].pop(0)
self._len -= 1
return item
def _drain(self):
for queue in self._queues.values():
while len(queue)>0:queue.pop()
self._len = 0
# Initialize the queue representation
def _init(self, priorities, maxsize, realtime, idle):
self.maxsize = maxsize
self._index = 0
self._len = 0
self._queues = self._buildDictQueues(priorities, realtime, idle)
self._roundRobinQueues = RoundRobin(self._buildMatrix(priorities))
self._drain()
def _buildDictQueues(self, priorities, realtime, idle):
result = {}
if realtime: result[REAL_TIME] = [REAL_TIME]
if idle: result[IDLE] = [IDLE]
for key in priorities.keys():
result[key]=[key]
return result
def _buildMatrix(self, priorities):
result = []
_list = self._buildQueueList(priorities)
for i in index(_list):
result.append((remove_duplicates(_list[i:]+ _list[:i])))
self._addRealTimeIdle2Matrix(result)
return matrix2tuple(result)
def _buildQueueList(self, priorities):
result = []
for key, value in priorities.items():
for i in range(value):
result.append(self._queues[key])
return shuffle_list(result)
def _addRealTimeIdle2Matrix(self, matrix):
realtime = self._queues.has_key(REAL_TIME)
idle = self._queues.has_key(IDLE)
if not realtime and not idle:return
for row in matrix:
if realtime:
row.insert(0,self._queues[REAL_TIME])
if idle:
row.append(self._queues[IDLE])
def _check_priorities(self, priorities):
for value in priorities.values():
assert value>0 and type(value)==type(1),"Incorrect definition of priorities"+str(priorities)
return 1
#utility classes and methods
def index(list):
return range(len(list))
def index_list(list):
return zip(index(list),list)
def matrix2tuple(matrix):
for i,row in index_list(matrix):
matrix[i]=tuple(row)
return tuple(matrix)
def shuffle_list(_list):
import random
for i in index(_list):
j = int(random.random()*len(_list))
_list[i],_list[j]=_list[j],_list[i]
return _list
def remove_duplicates(list):
assert type(list)==type([]) or type(list)==type(()), "List should be a [] or ()"
result = []
for elem in list:
if elem not in result:result.append(elem)
if type(list)==type(()):result=tuple(result)
return result
class RoundRobin:
def __init__(self, round_robin_list):
assert len(round_robin_list), str(round_robin_list)
self._index = -1
self._list = tuple(round_robin_list)
self._size = len(self._list)
def get(self):
self._index += 1
self._index %= self._size
return self._list[self._index]
#tests
def _test():
q = ScheduledQueue()
_empty_test()
_idle_last()
_real_first()
_max_size_test()
def _empty_test(q = ScheduledQueue()):
try:
q.get(0)
except Empty:
print "Empty test OK"
def _idle_last(q = ScheduledQueue()):
q.put(0,IDLE)
q.put(1)
q.get()
if not q.get():print "IDLE LAST OK"
def _real_first(q = ScheduledQueue()):
q.put(0)
q.put(1,REAL_TIME)
if q.get():print "REAL_TIME test OK"
q.get()
def _max_size_test(q = ScheduledQueue(maxsize = 1)):
q.put(0)
try:
q.put(0, block=0)
except Full:
print "Full test OK"
if __name__=='__main__':
_test()
A scheduled queue is a queue with priorities that are scheduled. It is not preemtitive, higher priorities are not executed always before than lower priorities (only more often).
Chad J. Schroeder/A Python-based descriptive statistical analysis tool. ( python)
"""Descriptive statistical analysis tool.
"""
__author__ = "Chad J. Schroeder"
__revision__ = "$Id$"
__version__ = "0.1"
__all__ = [ "StatisticsException", "Statistics" ]
class StatisticsException(Exception):
"""Statistics Exception class."""
pass
class Statistics(object):
"""Class for descriptive statistical analysis.
Behavior:
Computes numerical statistics for a given data set.
Available public methods:
None
Available instance attributes:
N: total number of elements in the data set
sum: sum of all values (n) in the data set
min: smallest value of the data set
max: largest value of the data set
mode: value(s) that appear(s) most often in the data set
mean: arithmetic average of the data set
range: difference between the largest and smallest value in the data set
median: value which is in the exact middle of the data set
variance: measure of the spread of the data set about the mean
stddev: standard deviation - measure of the dispersion of the data set
based on variance
identification: Instance ID
Raised Exceptions:
StatisticsException
Bases Classes:
object (builtin)
Example Usage:
x = [ -1, 0, 1 ]
try:
stats = Statistics(x)
except StatisticsException, mesg:
<handle exception>
print "N: %s" % stats.N
print "SUM: %s" % stats.sum
print "MIN: %s" % stats.min
print "MAX: %s" % stats.max
print "MODE: %s" % stats.mode
print "MEAN: %0.2f" % stats.mean
print "RANGE: %s" % stats.range
print "MEDIAN: %0.2f" % stats.median
print "VARIANCE: %0.5f" % stats.variance
print "STDDEV: %0.5f" % stats.stddev
print "DATA LIST: %s" % stats.sample
"""
def __init__(self, sample=[], population=False):
"""Statistics class initializer method."""
# Raise an exception if the data set is empty.
if (not sample):
raise StatisticsException, "Empty data set!: %s" % sample
# The data set (a list).
self.sample = sample
# Sample/Population variance determination flag.
self.population = population
self.N = len(self.sample)
self.sum = float(sum(self.sample))
self.min = min(self.sample)
self.max = max(self.sample)
self.range = self.max - self.min
self.mean = self.sum/self.N
# Inplace sort (list is now in ascending order).
self.sample.sort()
self.__getMode()
self.__getMedian()
self.__getVariance()
self.__getStandardDeviation()
# Instance identification attribute.
self.identification = id(self)
def __getMode(self):
"""Determine the most repeated value(s) in the data set."""
# Initialize a dictionary to store frequency data.
frequency = {}
# Build dictionary: key - data set values; item - data frequency.
for x in self.sample:
if (x in frequency):
frequency[x] += 1
else:
frequency[x] = 1
# Create a new list containing the values of the frequency dict. Convert
# the list, which may have duplicate elements, into a set. This will
# remove duplicate elements. Convert the set back into a sorted list
# (in descending order). The first element of the new list now contains
# the frequency of the most repeated values(s) in the data set.
# mode = sorted(list(set(frequency.values())), reverse=True)[0]
# Or use the builtin - max(), which returns the largest item of a
# non-empty sequence.
mode = max(frequency.values())
# If the value of mode is 1, there is no mode for the given data set.
if (mode == 1):
self.mode = []
return
# Step through the frequency dictionary, looking for values equaling
# the current value of mode. If found, append the value and its
# associated key to the self.mode list.
self.mode = [(x, mode) for x in frequency if (mode == frequency[x])]
def __getMedian(self):
"""Determine the value which is in the exact middle of the data set."""
if (self.N%2): # Number of elements in data set is odd.
self.median = float(self.sample[self.N/2])
else:
midpt = self.N/2 # Number of elements in data set is even.
self.median = (self.sample[midpt-1] + self.sample[midpt])/2.0
def __getVariance(self):
"""Determine the measure of the spread of the data set about the mean.
Sample variance is determined by default; population variance can be
determined by setting population attribute to True.
"""
x = 0 # Summation variable.
# Subtract the mean from each data item and square the difference.
# Sum all the squared deviations.
for item in self.sample:
x += (item - self.mean)**2.0
try:
if (not self.population):
# Divide sum of squares by N-1 (sample variance).
self.variance = x/(self.N-1)
else:
# Divide sum of squares by N (population variance).
self.variance = x/self.N
except:
self.variance = 0
def __getStandardDeviation(self):
"""Determine the measure of the dispersion of the data set based on the
variance.
"""
from math import sqrt # Mathematical functions.
# Take the square root of the variance.
self.stddev = sqrt(self.variance)
if __name__ == "__main__":
import os # Miscellaneous OS interfaces.
import sys # System-specific parameters and functions.
# Self-test
a = [ -1, 0, 1 ]
b = [ -1.0, 0.0, 1.1 ]
c = []
d = [ 12.23 ]
e = [ 12.23, 99.543, 66.08 ]
f = [ -1, 0, 2, -2, 1, 3, 0, -3, 2 ]
g = [ 0, 9, 1, 8, 2, 7, 3, 6, 4, 5 ]
h = [ -1, -1 ]
for x in a, b, c, d, e, f, g, h:
try:
stats = Statistics(x)
except StatisticsException, mesg:
print; print "Exception caught: %s" % mesg; print
continue
print
print "N: %s" % stats.N
print "SUM: %s" % stats.sum
print "MIN: %s" % stats.min
print "MAX: %s" % stats.max
print "MODE: %s" % stats.mode
print "MEAN: %0.2f" % stats.mean
print "RANGE: %s" % stats.range
print "MEDIAN: %0.2f" % stats.median
print "VARIANCE: %0.5f" % stats.variance
print "STDDEV: %0.5f" % stats.stddev
print "DATA LIST: %s\n" % stats.sample
print
sys.exit(0)
A Python module implementing a class which can be used for computing numerical statistics for a given data set.
Bill Bell/Accepting Four Points in 2-space ( python)
from sets import Set
class onePoint :
def __init__ ( self, X, Y ) :
self . x = X
self . y = Y
def __repr__ ( self ) :
return 'onePoint ( %s, %s )' % ( self . x, self . y )
def DistanceSq ( P0, P1 ) :
return ( P0 . x - P1 . x ) ** 2 + ( P0 . y - P1 . y ) ** 2
class FourCorners :
"""http://www.mathpages.com/home/kmath201.htm:
... area of the ... triangle
(x2-x3)(y1-y2) - (x1-x2)(y2-y3)
A = -------------------------------
2
In this same way it's easy to deduce that the area enclosed by a
general quadralateral can be expressed in terms of the coordinates
of its verticies as
(x2-x4)(y1-y3) - (x1-x3)(y2-y4)
A = -------------------------------
2
1 / \
= - ( (x2y1-x1y2) + (x3y2-x2y3) + (x4y3-x3y4) + (x1y4-x4y1) )
2 \ /
It's worth noting that, assuming all the verticies are in the ++
quadrant of the xy coordinate system (i.e., all the coordinates are
positive), these formulas give the positive area only if the verticies
are numbered clockwise around the perimeter. If they are counter-
clockwise, the computed area is negative. Of course, a quadralateral
can have crossing edges, such that the verticies are clockwise around
one region and counter-clockwise around the other. Thus, the computed
area of a non-degenerate quadralateral can vanish, as in the case of
the quadralateral shown in Figure 3.
"""
def __init__ ( self, alignmentImageSize, originalImageSize ) :
self . _four = [ ]
self . alignmentImageSize = alignmentImageSize
self . originalImageSize = originalImageSize
def buildResult ( self, status ) :
pointsCriterion = PointsCriterion ( * self . _four )
result = { }
for item in self . __dict__ :
result [ item ] = self . __dict__ [ item ]
for item in pointsCriterion . __dict__ :
result [ item ] = pointsCriterion . __dict__ [ item ]
result [ 'number' ] = len ( self . _four )
return result
def send ( self, pointTuple ) :
point = onePoint ( * pointTuple )
for aFour in self . _four :
if aFour . x == point . x and aFour . y == point . y :
if len ( self . _four ) < 4 :
return { 'number': len ( self . _four ), 'status': "Duplicate point (rejected)", }
else :
return self . buildResult ( "Duplicate point (rejected)" )
if len ( self . _four ) == 4 :
distances = { }
for aFour in self . _four :
distances [ DistanceSq ( aFour, point ) ] = aFour
self . _four . remove ( distances [ min ( distances ) ] )
self . _four . append ( point )
if len ( self . _four ) < 4 :
return { 'number': len ( self . _four ), 'status': "Need four distinct points", }
return self . buildResult ( 'Have four points' )
class PointsCriterion :
def QuadrilateralAreaAux ( self, P0, P1, P2, P3 ) :
return 0.5 * ( ( P1 . x - P3 . x ) * ( P0 . y - P2 . y ) - ( P0 . x - P2 . x ) * ( P1 . y - P3 . y ) )
def TriangleAreaAux ( self, P0, P1, P2 ) :
return 0.5 * ( ( P1 . x - P2 . x ) * ( P0 . y - P1 . y ) - ( P0 . x - P1 . x ) * ( P1 . y - P2 . y ) )
def __init__ ( self, P0, P1, P2, P3 ) :
areas = { }
tours = [ [ 0, 1, 2, 3 ], [ 0, 1, 3, 2 ], [ 0, 2, 1, 3 ], [ 0, 3, 1, 2 ], ]
points = [ P0, P1, P2, P3 ]
for tour in tours :
area = self . QuadrilateralAreaAux ( * tuple ( [ points [ t ] for t in tour ] ) )
if area :
if area < 0 :
tour . reverse ( )
areas [ abs ( area ) ] = tour
area = max ( areas )
clockwiseCorners = areas [ area ]
comparisonArea = 2. * self . TriangleAreaAux ( * tuple ( [ points [ t ] for t in clockwiseCorners [ : 3 ] ] ) )
corners = [ points [ p ] for p in clockwiseCorners ]
horizontals = [ corner . x for corner in corners ]
horizontals . sort ( )
verticals = [ corner . y for corner in corners ]
verticals . sort ( )
lefts = Set ( [ corner for corner in corners if corner . x in horizontals [ : 2 ] ] )
rights = Set ( [ corner for corner in corners if corner . x in horizontals [ -2 : ] ] )
uppers = Set ( [ corner for corner in corners if corner . y in verticals [ : 2 ] ] )
lowers = Set ( [ corner for corner in corners if corner . y in verticals [ -2 : ] ] )
self . upperLeft = lefts . intersection ( uppers ) . pop ( )
self . lowerLeft = lefts . intersection ( lowers ) . pop ( )
self . upperRight = rights . intersection ( uppers ) . pop ( )
self . lowerRight = rights . intersection ( lowers ) . pop ( )
self . horizontalRacking = self . lowerLeft . x - self . upperLeft . x
self . verticalRacking = self . upperRight . y - self . upperLeft . y
self . upperMost = min ( [ P . y for P in corners ] )
self . leftMost = min ( [ P . x for P in corners ] )
self . rightMost = max ( [ P . x for P in corners ] )
self . lowerMost = max ( [ P . y for P in corners ] )
self . quality = area / comparisonArea
self . corners = corners
if __name__ == "__main__" :
fourCorners = FourCorners ( ( 110, 110 ), ( 500, 500 ) )
for corner in [ ( 0, 0 ), ( 0, 0 ), ( 100, 100 ), ( 0, 100 ), ( 0, 100 ), ( 100, 0 ), ( 5, 0 ), ( 100, 0 ), ( 100, 120 ), ( 100, 101 ), ( 100, 0 ), ] :
result = fourCorners . send ( corner )
for item in result :
print item, result [ item ]
print 100 * '='
Photographic document images are often rotated, if only slightly. This code mediates an input of a series of four points--assumed to be the corners of a rectangular document--in any order, as mouse clicks. Then it determines the orientation of the points and calculates a "quality" value, as an indication to the user of how well the four points s/he has chosen approximate to the corners of a rotated rectangle. Finally, it makes the information that it has been passed, or that it has been able to glean, available to the script that invoked it.
Jean Brouwers/Size of Python objects (revised). ( python)
#!/usr/bin/env python
# Copyright, license and disclaimer are at the end of this file.
# This is the latest, enhanced version of the asizeof.py recipes at
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/546530>
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/544288>
'''This module exposes 10 functions and 2 classes to obtain lengths
and sizes of Python objects (for Python 2.2 or later [1]).
The main changes in this version are new function calcsize(),
use gc.get_objects() to get all objects and improvements in
this documentation.
Public Functions [2]
Function asizeof calculates the combined (approximate) size
in bytes of one or several Python objects.
Function asizesof returns a tuple containing the (approximate)
size in bytes for each given Python object separately.
Function asized returns for each object an instance of class
Asized containing all the size information of the object and a
tuple with the referents.
Functions basicsize and itemsize return the basic respectively
item size of the given object.
Function flatsize returns the flat size of a Python object in
bytes defined as the basic size plus the item size times the
length of the given object.
Function leng returns the length of an object, like standard
len but extended for several types, e.g. the leng of a multi-
precision int (or long) is the number of digits [3]. The length
of most mutable sequence objects includes an estimate of the
over-allocation and therefore, the leng value may differ from
the standard len result.
Function refs returns (a generator for) the referents of the
given object, i.e. the objects referenced by the given object.
Function calcsize is equivalent to standard struct.calcsize
but handles format characters 'z' for signed C type Py_ssize_t
and 'Z' for unsigned C type size_t.
Certain classes are known to be sub-classes of or to behave as
dict objects. Function adict can be used to install other
class objects to be treated like dict.
Public Classes [2]
An instance of class Asized is returned for each object sized
with the asized function or method.
Class Asizer can be used to accumulate the results of several
asizeof or asizesof calls. After creating an Asizer instance,
use methods asizeof and asizesof to size additional objects.
Call methods exclude_refs and/or exclude_types to exclude
references to or instances or types of certain objects.
Use one of the print\_... methods to report the statistics.
Duplicate Objects
Any duplicate, given objects are sized only once and the size
is included in the combined total only once. But functions
asizesof and asized do return a size value respectively an
Asized instance for each given object, the same for duplicates.
Definitions [4]
The size of an object is defined as the sum of the flat size
of the object plus the sizes of any referents. Referents are
visited recursively up to a given limit. However, the size
of objects referenced multiple times is included only once.
The flat size of an object is defined as the basic size of the
object plus the item size times the number of allocated items.
The flat size does include the size for the items (references
to the referents), but not the referents themselves.
The flat size returned by function flatsize equals the result
of the asizeof function with options code=True, ignored=False,
limit=0 and option align set to the same value.
The accurate flat size for an object is obtained from function
sys.getsizeof() where available. Otherwise, the length and
size of sequence objects as dicts, lists, sets, etc. is based
on an estimate for the number of allocated items. As a result,
the reported length and size may substantially differ from the
actual length and size.
The basic and item sizes are obtained from the __basicsize__
respectively __itemsize__ attribute of the (type of the) object.
Where necessary (e.g. sequence objects), a zero __itemsize__
is replaced by the size of a corresponding C type.
The basic size (of GC managed objects) objects includes the
overhead for Python's garbage collector (GC) as well as the
space needed for refcounts (only in certain Python builds).
Optionally, sizes can be aligned to any power of 2 multiple.
Size of (byte)code
The (byte)code size of objects as classes, functions, methods,
modules, etc. can be included by setting option code.
Iterators are handled similar to sequences: iterated object(s)
are sized like referents if the recursion limit permits. Also,
function gc.get_referents() must return the referent object
of iterators.
Generators are sized as (byte)code only, but generated objects
are never sized.
Old- and New-style Classes
All old- and new-style class, instance and type objects, are
handled uniformly such that (a) instance and class objects can
be distinguished and (b) instances of different old-style
classes can be dealt with separately.
Class and type objects are represented as <class ....* def>
respectively as <type ... def> where an '*' indicates an old-
style class and the def suffix marks the definition object.
Instances of old-style classes are shown as new-style ones but
with an '*' at the end of the name, like <class module.name*>.
Ignored Objects
To avoid excessive sizes, several object types are ignored [4]
by default, e.g. built-in functions, built-in types and classes
[5], function globals and module referents. However, any
instances thereof are sized and module objects will be sized
when passed as given objects. Ignored object types are included
if option ignored is set accordingly.
In addition, many __...__ attributes of callable objects are
ignored, except crucial ones, e.g. class attributes __dict__,
__doc__, __name__ and __slots__. For more details, see the
type-specific _..._refs() and _len_...() functions below.
Option all can be used to size all Python objects and/or get
the referents from gc.get_referents() and override the type-
specific __..._refs() functions.
Notes
[1] Tested with Python 2.2.3, 2.3.7, 2.4.5, 2.5.1, 2.5.2, 2.6.2,
3.0.1 or 3.1a2 on CentOS 4.6, SuSE 9.3, MacOS X 10.4.11 Tiger
(Intel) and 10.3.9 Panther (PPC), Solaris 10 (Opteron) and
Windows XP all 32-bit Python and on RHEL 3u7 and Solaris 10
(Opteron) both 64-bit Python.
[2] The functions and classes in this module are not thread-safe.
[3] See Python source file .../Include/longinterp.h for the
C typedef of digit used in multi-precision int (or long)
objects. The size of digit in bytes can be obtained in
Python from the int (or long) __itemsize__ attribute.
Function leng (rather _len_int) below deterimines the
number of digits from the int (or long) value.
[4] These definitions and other assumptions are rather arbitrary
and may need corrections or adjustments.
[5] Types and classes are considered built-in if the module of
the type or class is listed in _builtin_modules below.
''' #PYCHOK expected
from __future__ import generators #PYCHOK for yield in Python 2.2
from inspect import isbuiltin, isclass, iscode, isframe, \
isfunction, ismethod, ismodule, stack
from math import log
from os import linesep
from struct import calcsize as _calcsize
import sys
import types as Types
import weakref as Weakref
__version__ = '5.12 (Apr 27, 2009)'
__all__ = ['adict', 'asized', 'asizeof', 'asizesof',
'Asized', 'Asizer', # classes
'basicsize', 'flatsize', 'itemsize', 'leng', 'refs',
'calcsize'] # handles 'z' and 'Z'
# any classes or types in modules listed in _builtin_modules are
# considered built-in and ignored by default, as built-in functions
if __name__ == '__main__':
_builtin_modules = (int.__module__, 'types', Exception.__module__) # , 'weakref'
else: # treat this very module as built-in
_builtin_modules = (int.__module__, 'types', Exception.__module__, __name__) # , 'weakref'
# sizes of some primitive C types
# XXX len(pack(T, 0)) == Struct(T).size == _calcsize(T)
# but type/class Struct only available since Python 2.5
_sizeof_Cbyte = _calcsize('c') # sizeof(unsigned char)
_sizeof_Clong = _calcsize('l') # sizeof(long)
_sizeof_Cvoidp = _calcsize('P') # sizeof(void*)
# sizeof(long) != sizeof(ssize_t) on LLP64
if _sizeof_Clong < _sizeof_Cvoidp:
_Zz = 'PP'
else:
_Zz = 'Ll'
def calcsize(fmt):
'''struct.calcsize() handling 'z' for signed Py_ssize_t and 'Z' for unsigned size_t.
'''
return _calcsize(fmt.replace('Z', _Zz[0]).replace('z', _Zz[1]))
# defaults for some basic sizes with 'z' for C Py_ssize_t
_sizeof_CPyCodeObject = calcsize('Pz10P5i0P') # sizeof(PyCodeObject)
_sizeof_CPyFrameObject = calcsize('Pzz13P63i0P') # sizeof(PyFrameObject)
_sizeof_CPyModuleObject = calcsize('PzP0P') # sizeof(PyModuleObject)
# defaults for some item sizes with 'z' for C Py_ssize_t
_sizeof_CPyDictEntry = calcsize('z2P') # sizeof(PyDictEntry)
_sizeof_Csetentry = calcsize('lP') # sizeof(setentry)
# XXX use sys.int_info.sizeof_digit in Python 3.1
try: # C typedef digit for multi-precision int (or long)
_sizeof_Cdigit = long.__itemsize__
except NameError: # no long in Python 3.0
_sizeof_Cdigit = int.__itemsize__
if _sizeof_Cdigit < 2:
raise AssertionError('sizeof(%s) bad: %d' % ('digit', _sizeof_Cdigit))
try: # sizeof(unicode_char)
u = unicode('\0')
except NameError: # no unicode() in Python 3.0
u = '\0'
u = u.encode('unicode-internal') # see .../Lib/test/test_sys.py
_sizeof_Cunicode = len(u)
del u
if (1 << (_sizeof_Cunicode << 3)) <= sys.maxunicode:
raise AssertionError('sizeof(%s) bad: %d' % ('unicode', _sizeof_Cunicode))
if hasattr(sys, 'maxsize'): # new in Python 2.6
Z = calcsize('Z') # check sizeof(size_t)
if (1 << (Z << 3)) <= sys.maxsize:
raise AssertionError('sizeof(%s) bad: %d' % ('size_t', Z))
del Z
try: # size of GC header, sizeof(PyGC_Head)
import _testcapi as t
_sizeof_CPyGC_Head = t.SIZEOF_PYGC_HEAD # new in Python 2.6
except (ImportError, AttributeError): # sizeof(PyGC_Head)
# alignment should be to sizeof(long double) but there
# is no way to obtain that value, assume twice double
t = calcsize('2d') - 1
_sizeof_CPyGC_Head = (calcsize('2Pz') + t) & ~t
del t
# size of refcounts (Python debug build only)
if hasattr(sys, 'gettotalrefcount'):
_sizeof_Crefcounts = calcsize('2z')
else:
_sizeof_Crefcounts = 0
# some flags from .../Include/object.h
_Py_TPFLAGS_HEAPTYPE = 1 << 9 # Py_TPFLAGS_HEAPTYPE
_Py_TPFLAGS_HAVE_GC = 1 << 14 # Py_TPFLAGS_HAVE_GC
_Type_type = type(type) # == type and new-style class type
# compatibility functions for more uniform
# behavior across Python version 2.2 thu 3.0
def _items(obj): # dict only
'''Return iter-/generator, preferably.
'''
return getattr(obj, 'iteritems', obj.items)()
def _keys(obj): # dict only
'''Return iter-/generator, preferably.
'''
return getattr(obj, 'iterkeys', obj.keys)()
def _values(obj): # dict only
'''Use iter-/generator, preferably.
'''
return getattr(obj, 'itervalues', obj.values)()
try: # callable() builtin
_callable = callable
except NameError: # callable() removed in Python 3.0
def _callable(obj):
'''Substitute for callable().'''
return hasattr(obj, '__call__')
try: # get 'all' current objects
from gc import get_objects as _getobjects
except ImportError:
def _getobjects():
# modules first, globals and stack
# (may contain duplicate objects)
return tuple(_values(sys.modules)) + (
globals(), stack(sys.getrecursionlimit()))
try: # get 'all' referents of objects
# note that gc.get_referents()
# returns () for dict...-iterators
from gc import get_referents as _getreferents
except ImportError: # no get_referents() in Python 2.2
def _getreferents(unused):
return () # sorry, no refs
# sys.getsizeof() new in Python 2.6
_getsizeof = getattr(sys, 'getsizeof', None)
try: # str intern()
_intern = intern
except NameError: # no intern() in Python 3.0
def _intern(val):
return val
def _kwds(**kwds): # no dict(key=value, ...) in Python 2.2
'''Return name=value pairs as keywords dict.
'''
return kwds
try: # sorted() builtin
_sorted = sorted
except NameError: # no sorted() in Python 2.2
def _sorted(vals, reverse=False):
'''Partial substitute for missing sorted().'''
vals.sort() # inplace OK
if reverse:
vals.reverse()
return vals
try: # sum() builtin
_sum = sum
except NameError: # no sum() in Python 2.2
def _sum(vals):
'''Partial substitute for missing sum().'''
s = 0
for v in vals:
s += v
return s
# private functions
def _basicsize(t, base=0, heap=False, obj=None):
'''Get non-zero basicsize of type,
including the header sizes.
'''
s = max(getattr(t, '__basicsize__', 0), base)
# include gc header size
if t != _Type_type:
h = getattr(t, '__flags__', 0) & _Py_TPFLAGS_HAVE_GC
elif heap: # type, allocated on heap
h = True
else: # None has no __flags__ attr
h = getattr(obj, '__flags__', 0) & _Py_TPFLAGS_HEAPTYPE
if h:
s += _sizeof_CPyGC_Head
# include reference counters
return s + _sizeof_Crefcounts
def _derive_typedef(typ):
'''Return single, existing super type typedef or None.
'''
v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)]
if len(v) == 1:
return v[0]
return None
def _dir2(obj, pref='', excl=(), slots=None, itor=''):
'''Return an attribute name, object 2-tuple for certain
attributes or for the '__slots__' attributes of the
given object, but not both. Any iterator referent
objects are returned with the given name if the
latter is non-empty.
'''
if slots: # __slots__ attrs
if hasattr(obj, slots):
# collect all inherited __slots__ attrs
# from list, tuple, or dict __slots__,
# while removing any duplicate attrs
s = {}
for c in type(obj).mro():
for a in getattr(c, slots, ()):
if hasattr(obj, a):
s.setdefault(a, getattr(obj, a))
# assume __slots__ tuple/list
# is holding the attr values
yield slots, _Slots(s) # _keys(s)
for t in _items(s):
yield t # attr name, value
elif itor: # iterator referents
for o in obj: # iter(obj)
yield itor, o
else: # regular attrs
for a in dir(obj):
if a.startswith(pref) and a not in excl and hasattr(obj, a):
yield a, getattr(obj, a)
def _infer_dict(obj):
'''Return True for likely dict object.
'''
for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'values'),
('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')):
for a in ats: # no all(<generator_expression>) in Python 2.2
if not _callable(getattr(obj, a, None)):
break
else: # all True
return True
return False
def _isdictclass(obj):
'''Return True for known dict objects.
'''
c = getattr(obj, '__class__', None)
return c and c.__name__ in _dict_classes.get(c.__module__, ())
def _issubclass(sub, sup):
'''Safe issubclass().
'''
if sup is not object:
try:
return issubclass(sub, sup)
except TypeError:
pass
return False
def _itemsize(t, item=0):
'''Get non-zero itemsize of type.
'''
# replace zero value with default
return getattr(t, '__itemsize__', 0) or item
def _kwdstr(**kwds):
'''Keyword arguments as a string.
'''
return ', '.join(_sorted(['%s=%r' % kv for kv in _items(kwds)])) # [] for Python 2.2
def _lengstr(obj):
'''Object length as a string.
'''
n = leng(obj)
if n is None: # no len
r = ''
elif n > _len(obj): # extended
r = ' leng %d!' % n
else:
r = ' leng %d' % n
return r
def _nameof(obj, dflt=''):
'''Return the name of an object.
'''
return getattr(obj, '__name__', dflt)
def _objs(objs, all=None, **unused):
'''Return the given or 'all' objects.
'''
if all in (False, None):
t = objs or ()
elif all is True: # 'all' objects
t = objs or _getobjects()
else:
raise ValueError('invalid option: %s=%r' % ('all', all))
return t
def _p100(part, total, prec=1):
'''Return percentage as string.
'''
r = float(total)
if r:
r = part * 100.0 / r
return '%.*f%%' % (prec, r)
return 'n/a'
def _plural(num):
'''Return 's' if plural.
'''
if num == 1:
s = ''
else:
s = 's'
return s
def _power2(n):
'''Find the next power of 2.
'''
p2 = 16
while n > p2:
p2 += p2
return p2
def _prepr(obj, clip=0):
'''Prettify and clip long repr() string.
'''
return _repr(obj, clip=clip).strip('<>').replace("'", '') # remove <''>
def _printf(fmt, *args, **print3opts):
'''Formatted print.
'''
if print3opts: # like Python 3.0
f = print3opts.get('file', None) or sys.stdout
if args:
f.write(fmt % args)
else:
f.write(fmt)
f.write(print3opts.get('end', linesep))
elif args:
print(fmt % args)
else:
print(fmt)
def _refs(obj, named, *ats, **kwds):
'''Return specific attribute objects of an object.
'''
if named:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _NamedRef(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _NamedRef(a, o)
else:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield getattr(obj, a)
if kwds: # kwds are _dir2() args
for _, o in _dir2(obj, **kwds):
yield o
def _repr(obj, clip=80):
'''Clip long repr() string.
'''
try: # safe repr()
r = repr(obj)
except TypeError:
r = 'N/A'
if 0 < clip < len(r):
h = (clip // 2) - 2
if h > 0:
r = r[:h] + '....' + r[-h:]
return r
def _SI(size, K=1024, i='i'):
'''Return size as SI string.
'''
if 1 < K < size:
f = float(size)
for si in iter('KMGPTE'):
f /= K
if f < K:
return ' or %.1f %s%sB' % (f, si, i)
return ''
def _SI2(size, **kwds):
'''Return size as regular plus SI string.
'''
return str(size) + _SI(size, **kwds)
# type-specific referent functions
def _class_refs(obj, named):
'''Return specific referents of a class object.
'''
return _refs(obj, named, '__class__', '__dict__', '__doc__', '__mro__',
'__name__', '__slots__', '__weakref__')
def _co_refs(obj, named):
'''Return specific referents of a code object.
'''
return _refs(obj, named, pref='co_')
def _dict_refs(obj, named):
'''Return key and value objects of a dict/proxy.
'''
if named:
for k, v in _items(obj):
s = str(k)
yield _NamedRef(s, k, 1) # key
yield _NamedRef(s, v, 2) # value
else:
for k, v in _items(obj):
yield k
yield v
def _enum_refs(obj, named):
'''Return specific referents of an enumerate object.
'''
return _refs(obj, named, '__doc__')
def _exc_refs(obj, named):
'''Return specific referents of an Exception object.
'''
# .message raises DeprecationWarning in Python 2.6
return _refs(obj, named, 'args', 'filename', 'lineno', 'msg', 'text') # , 'message', 'mixed'
def _file_refs(obj, named):
'''Return specific referents of a file object.
'''
return _refs(obj, named, 'mode', 'name')
def _frame_refs(obj, named):
'''Return specific referents of a frame object.
'''
return _refs(obj, named, pref='f_')
def _func_refs(obj, named):
'''Return specific referents of a function or lambda object.
'''
return _refs(obj, named, '__doc__', '__name__', '__code__',
pref='func_', excl=('func_globals',))
def _gen_refs(obj, named):
'''Return the referent(s) of a generator object.
'''
# only some gi_frame attrs
f = getattr(obj, 'gi_frame', None)
return _refs(f, named, 'f_locals', 'f_code')
def _im_refs(obj, named):
'''Return specific referents of a method object.
'''
return _refs(obj, named, '__doc__', '__name__', '__code__',
pref='im_')
def _inst_refs(obj, named):
'''Return specific referents of a class instance.
'''
return _refs(obj, named, '__dict__', '__class__',
slots='__slots__')
def _iter_refs(obj, named):
'''Return the referent(s) of an iterator object.
'''
r = _getreferents(obj) # special case
return _refs(r, named, itor=_nameof(obj) or 'iteref')
def _module_refs(obj, named):
'''Return specific referents of a module object.
'''
# ignore this very module
if obj.__name__ == __name__:
return ()
# module is essentially a dict
return _dict_refs(obj.__dict__, named)
def _prop_refs(obj, named):
'''Return specific referents of a property object.
'''
return _refs(obj, named, '__doc__', pref='f')
def _seq_refs(obj, unused): # named unused for PyChecker
'''Return specific referents of a frozen/set, list, tuple and xrange object.
'''
return obj # XXX for r in obj: yield r
def _stat_refs(obj, named):
'''Return referents of a os.stat object.
'''
return _refs(obj, named, pref='st_')
def _statvfs_refs(obj, named):
'''Return referents of a os.statvfs object.
'''
return _refs(obj, named, pref='f_')
def _tb_refs(obj, named):
'''Return specific referents of a traceback object.
'''
return _refs(obj, named, pref='tb_')
def _type_refs(obj, named):
'''Return specific referents of a type object.
'''
return _refs(obj, named, '__dict__', '__doc__', '__mro__',
'__name__', '__slots__', '__weakref__')
def _weak_refs(obj, unused): # named unused for PyChecker
'''Return weakly referent object.
'''
try: # ignore 'key' of KeyedRef
return (obj(),)
except: # XXX ReferenceError
return () #PYCHOK OK
_all_refs = (None, _class_refs, _co_refs, _dict_refs, _enum_refs,
_exc_refs, _file_refs, _frame_refs, _func_refs,
_gen_refs, _im_refs, _inst_refs, _iter_refs,
_module_refs, _prop_refs, _seq_refs, _stat_refs,
_statvfs_refs, _tb_refs, _type_refs, _weak_refs)
# type-specific length functions
def _len(obj):
'''Safe len().
'''
try:
return len(obj)
except TypeError: # no len()
return 0
def _len_array(obj):
'''Array length in bytes.
'''
return len(obj) * obj.itemsize
def _len_bytearray(obj):
'''Bytearray size.
'''
return obj.__alloc__()
def _len_code(obj): # see .../Lib/test/test_sys.py
'''Length of code object (stack and variables only).
'''
return obj.co_stacksize + obj.co_nlocals \
+ _len(obj.co_freevars) \
+ _len(obj.co_cellvars) - 1
def _len_dict(obj):
'''Dict length in items (estimate).
'''
n = len(obj) # active items
if n < 6: # ma_smalltable ...
n = 0 # ... in basicsize
else: # at least one unused
n = _power2(n + 1)
return n
def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n
_digit2p2 = 1 << (_sizeof_Cdigit << 3)
_digitmax = _digit2p2 - 1 # == (2 * PyLong_MASK + 1)
_digitlog = 1.0 / log(_digit2p2)
def _len_int(obj):
'''Length of multi-precision int (aka long) in digits.
'''
if obj:
n, i = 1, abs(obj)
if i > _digitmax:
# no log(x[, base]) in Python 2.2
n += int(log(i) * _digitlog)
else: # zero
n = 0
return n
def _len_iter(obj):
'''Length (hint) of an iterator.
'''
n = getattr(obj, '__length_hint__', None)
if n:
n = n()
else: # try len()
n = _len(obj)
return n
def _len_list(obj):
'''Length of list (estimate).
'''
n = len(obj)
# estimate over-allocation
if n > 8:
n += 6 + (n >> 3)
elif n:
n += 4
return n
def _len_module(obj):
'''Module length.
'''
return _len(obj.__dict__) # _len(dir(obj))
def _len_set(obj):
'''Length of frozen/set (estimate).
'''
n = len(obj)
if n > 8: # assume half filled
n = _power2(n + n - 2)
elif n: # at least 8
n = 8
return n
def _len_slice(obj):
'''Slice length.
'''
try:
return ((obj.stop - obj.start + 1) // obj.step)
except (AttributeError, TypeError):
return 0
def _len_slots(obj):
'''Slots length.
'''
return len(obj) - 1
def _len_struct(obj):
'''Struct length in bytes.
'''
try:
return obj.size
except AttributeError:
return 0
def _len_unicode(obj):
'''Unicode size.
'''
return len(obj) + 1
_all_lengs = (None, _len, _len_array, _len_bytearray,
_len_code, _len_dict, _len_frame,
_len_int, _len_iter, _len_list,
_len_module, _len_set, _len_slice,
_len_slots, _len_struct, _len_unicode)
# more private functions and classes
_old_style = '*' # marker
_new_style = '' # no marker
class _Claskey(object):
'''Wrapper for class objects.
'''
__slots__ = ('_obj', '_sty')
def __init__(self, obj, style):
self._obj = obj # XXX Weakref.ref(obj)
self._sty = style
def __str__(self):
r = str(self._obj)
if r.endswith('>'):
r = '%s%s def>' % (r[:-1], self._sty)
elif self._sty is _old_style and not r.startswith('class '):
r = 'class %s%s def' % (r, self._sty)
else:
r = '%s%s def' % (r, self._sty)
return r
__repr__ = __str__
# For most objects, the object type is used as the key in the
# _typedefs dict further below, except class and type objects
# and old-style instances. Those are wrapped with separate
# _Claskey or _Instkey instances to be able (1) to distinguish
# instances of different old-style classes by class, (2) to
# distinguish class (and type) instances from class (and type)
# definitions for new-style classes and (3) provide similar
# results for repr() and str() of new- and old-style classes
# and instances.
_claskeys = {} # [id(obj)] = _Claskey()
def _claskey(obj, style):
'''Wrap an old- or new-style class object.
'''
i = id(obj)
k = _claskeys.get(i, None)
if not k:
_claskeys[i] = k = _Claskey(obj, style)
return k
try: # no Class- and InstanceType in Python 3.0
_Types_ClassType = Types.ClassType
_Types_InstanceType = Types.InstanceType
class _Instkey(object):
'''Wrapper for old-style class (instances).
'''
__slots__ = ('_obj',)
def __init__(self, obj):
self._obj = obj # XXX Weakref.ref(obj)
def __str__(self):
return '<class %s.%s%s>' % (self._obj.__module__, self._obj.__name__, _old_style)
__repr__ = __str__
_instkeys = {} # [id(obj)] = _Instkey()
def _instkey(obj):
'''Wrap an old-style class (instance).
'''
i = id(obj)
k = _instkeys.get(i, None)
if not k:
_instkeys[i] = k = _Instkey(obj)
return k
def _keytuple(obj):
'''Return class and instance keys for a class.
'''
t = type(obj)
if t is _Types_InstanceType:
t = obj.__class__
return _claskey(t, _old_style), _instkey(t)
elif t is _Types_ClassType:
return _claskey(obj, _old_style), _instkey(obj)
elif t is _Type_type:
return _claskey(obj, _new_style), obj
return None, None # not a class
def _objkey(obj):
'''Return the key for any object.
'''
k = type(obj)
if k is _Types_InstanceType:
k = _instkey(obj.__class__)
elif k is _Types_ClassType:
k = _claskey(obj, _old_style)
elif k is _Type_type:
k = _claskey(obj, _new_style)
return k
except AttributeError: # Python 3.0
def _keytuple(obj): #PYCHOK expected
'''Return class and instance keys for a class.
'''
if type(obj) is _Type_type: # isclass(obj):
return _claskey(obj, _new_style), obj
return None, None # not a class
def _objkey(obj): #PYCHOK expected
'''Return the key for any object.
'''
k = type(obj)
if k is _Type_type: # isclass(obj):
k = _claskey(obj, _new_style)
return k
class _NamedRef(object):
'''Store referred object along
with the name of the referent.
'''
__slots__ = ('name', 'ref', 'typ')
def __init__(self, name, ref, typ=0):
self.name = name
self.ref = ref
self.typ = typ # see Asized.format
class _Slots(tuple):
'''Wrapper class for __slots__ attribute at
class instances to account for the size
of the __slots__ tuple/list containing
references to the attribute values.
'''
pass
# kinds of _Typedefs
_i = _intern
_all_kinds = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = (
_i('static'), _i('dynamic'), _i('derived'), _i('ignored'), _i('inferred'))
del _i
class _Typedef(object):
'''Type definition class.
'''
__slots__ = {
'base': 0, # basic size in bytes
'item': 0, # item size in bytes
'leng': None, # or _len_...() function
'refs': None, # or _..._refs() function
'both': None, # both data and code if True, code only if False
'kind': None, # _kind_... value
'type': None} # original type
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused): # for Python 3.0
return True
def __repr__(self):
return repr(self.args())
def __str__(self):
t = [str(self.base), str(self.item)]
for f in (self.leng, self.refs):
if f:
t.append(f.__name__)
else:
t.append('n/a')
if not self.both:
t.append('(code only)')
return ', '.join(t)
def args(self): # as args tuple
'''Return all attributes as arguments tuple.
'''
return (self.base, self.item, self.leng, self.refs,
self.both, self.kind, self.type)
def dup(self, other=None, **kwds):
'''Duplicate attributes of dict or other typedef.
'''
if other is None:
d = _dict_typedef.kwds()
else:
d = other.kwds()
d.update(kwds)
self.reset(**d)
def flat(self, obj, mask=0):
'''Return the aligned flat size.
'''
s = self.base
if self.leng and self.item > 0: # include items
s += self.leng(obj) * self.item
if _getsizeof: # _getsizeof prevails
s = _getsizeof(obj, s)
if mask: # align
s = (s + mask) & ~mask
return s
def format(self):
'''Return format dict.
'''
c = n = ''
if not self.both:
c = ' (code only)'
if self.leng:
n = ' (%s)' % _nameof(self.leng)
return _kwds(base=self.base, item=self.item, leng=n,
code=c, kind=self.kind)
def kwds(self):
'''Return all attributes as keywords dict.
'''
# no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0
return _kwds(base=self.base, item=self.item,
leng=self.leng, refs=self.refs,
both=self.both, kind=self.kind, type=self.type)
def save(self, t, base=0, heap=False):
'''Save this typedef plus its class typedef.
'''
c, k = _keytuple(t)
if k and k not in _typedefs: # instance key
_typedefs[k] = self
if c and c not in _typedefs: # class key
if t.__module__ in _builtin_modules:
k = _kind_ignored # default
else:
k = self.kind
_typedefs[c] = _Typedef(base=_basicsize(type(t), base=base, heap=heap),
refs=_type_refs,
both=False, kind=k, type=t)
elif isbuiltin(t) and t not in _typedefs: # array, range, xrange in Python 2.x
_typedefs[t] = _Typedef(base=_basicsize(t, base=base),
both=False, kind=_kind_ignored, type=t)
else:
raise KeyError('asizeof typedef %r bad: %r %r' % (self, (c, k), self.both))
def set(self, safe_len=False, **kwds):
'''Set one or more attributes.
'''
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len
def reset(self, base=0, item=0, leng=None, refs=None,
both=True, kind=None, type=None):
'''Reset all specified attributes.
'''
if base < 0:
raise ValueError('invalid option: %s=%r' % ('base', base))
else:
self.base = base
if item < 0:
raise ValueError('invalid option: %s=%r' % ('item', item))
else:
self.item = item
if leng in _all_lengs: # XXX or _callable(leng)
self.leng = leng
else:
raise ValueError('invalid option: %s=%r' % ('leng', leng))
if refs in _all_refs: # XXX or _callable(refs)
self.refs = refs
else:
raise ValueError('invalid option: %s=%r' % ('refs', refs))
if both in (False, True):
self.both = both
else:
raise ValueError('invalid option: %s=%r' % ('both', both))
if kind in _all_kinds:
self.kind = kind
else:
raise ValueError('invalid option: %s=%r' % ('kind', kind))
self.type = type
_typedefs = {} # [key] = _Typedef()
def _typedef_both(t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False):
'''Add new typedef for both data and code.
'''
v = _Typedef(base=_basicsize(t, base=base), item=_itemsize(t, item),
refs=refs, leng=leng,
both=True, kind=kind, type=t)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):
'''Add new typedef for code only.
'''
v = _Typedef(base=_basicsize(t, base=base),
refs=refs,
both=False, kind=kind, type=t)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef
# static typedefs for data and code types
_typedef_both(complex)
_typedef_both(float)
_typedef_both(list, refs=_seq_refs, leng=_len_list, item=_sizeof_Cvoidp) # sizeof(PyObject*)
_typedef_both(tuple, refs=_seq_refs, leng=_len, item=_sizeof_Cvoidp) # sizeof(PyObject*)
_typedef_both(property, refs=_prop_refs)
_typedef_both(type(Ellipsis))
_typedef_both(type(None))
# _Slots is a special tuple, see _Slots.__doc__
_typedef_both(_Slots, item=_sizeof_Cvoidp,
leng=_len_slots, # length less one
refs=None, # but no referents
heap=True) # plus head
# dict, dictproxy, dict_proxy and other dict-like types
_dict_typedef = _typedef_both(dict, item=_sizeof_CPyDictEntry, leng=_len_dict, refs=_dict_refs)
try: # <type dictproxy> only in Python 2.x
_typedef_both(Types.DictProxyType, item=_sizeof_CPyDictEntry, leng=_len_dict, refs=_dict_refs)
except AttributeError: # XXX any class __dict__ is <type dict_proxy> in Python 3.0?
_typedef_both(type(_Typedef.__dict__), item=_sizeof_CPyDictEntry, leng=_len_dict, refs=_dict_refs)
# other dict-like classes and types may be derived or inferred,
# provided the module and class name is listed here (see functions
# adict, _isdictclass and _infer_dict for further details)
_dict_classes = {'UserDict': ('IterableUserDict', 'UserDict'),
'weakref' : ('WeakKeyDictionary', 'WeakValueDictionary')}
try: # <type module> is essentially a dict
_typedef_both(Types.ModuleType, base=_dict_typedef.base,
item=_dict_typedef.item + _sizeof_CPyModuleObject,
leng=_len_module, refs=_module_refs)
except AttributeError: # missing
pass
# newer or obsolete types
try:
from array import array # array type
_typedef_both(array, leng=_len_array, item=_sizeof_Cbyte)
except ImportError: # missing
pass
try: # bool has non-zero __itemsize__ in 3.0
_typedef_both(bool)
except NameError: # missing
pass
try: # ignore basestring
_typedef_both(basestring, leng=None)
except NameError: # missing
pass
try:
if isbuiltin(buffer): # Python 2.2
_typedef_both(type(buffer('')), item=_sizeof_Cbyte, leng=_len) # XXX len in bytes?
else:
_typedef_both(buffer, item=_sizeof_Cbyte, leng=_len) # XXX len in bytes?
except NameError: # missing
pass
try:
_typedef_both(bytearray, item=_sizeof_Cbyte, leng=_len_bytearray) #PYCHOK bytearray new in 2.6, 3.0
except NameError: # missing
pass
try:
if type(bytes) is not type(str): # bytes is str in 2.6 #PYCHOK bytes new in 2.6, 3.0
_typedef_both(bytes, item=_sizeof_Cbyte, leng=_len) #PYCHOK bytes new in 2.6, 3.0
except NameError: # missing
pass
try: # XXX like bytes
_typedef_both(str8, item=_sizeof_Cbyte, leng=_len) #PYCHOK str8 new in 2.6, 3.0
except NameError: # missing
pass
try:
_typedef_both(enumerate, refs=_enum_refs)
except NameError: # missing
pass
try: # Exception is type in Python 3.0
_typedef_both(Exception, refs=_exc_refs)
except: # missing
pass #PYCHOK OK
try:
_typedef_both(file, refs=_file_refs)
except NameError: # missing
pass
try:
_typedef_both(frozenset, item=_sizeof_Csetentry, leng=_len_set, refs=_seq_refs)
except NameError: # missing
pass
try:
_typedef_both(set, item=_sizeof_Csetentry, leng=_len_set, refs=_seq_refs)
except NameError: # missing
pass
try: # not callable()
_typedef_both(Types.GetSetDescriptorType)
except AttributeError: # missing
pass
try: # if long exists, it is multi-precision ...
_typedef_both(long, item=_sizeof_Cdigit, leng=_len_int)
_typedef_both(int) # ... and int is fixed size
except NameError: # no long, only multi-precision int in Python 3.0
_typedef_both(int, item=_sizeof_Cdigit, leng=_len_int)
try: # not callable()
_typedef_both(Types.MemberDescriptorType)
except AttributeError: # missing
pass
try:
_typedef_both(type(NotImplemented)) # == Types.NotImplementedType
except NameError: # missing
pass
try:
_typedef_both(range)
except NameError: # missing
pass
try:
_typedef_both(xrange)
except NameError: # missing
pass
try:
_typedef_both(reversed, refs=_enum_refs)
except NameError: # missing
pass
try:
_typedef_both(slice, item=_sizeof_Cvoidp, leng=_len_slice) # XXX worst-case itemsize?
except NameError: # missing
pass
try:
from os import curdir, stat, statvfs
_typedef_both(type(stat( curdir)), refs=_stat_refs) # stat_result
_typedef_both(type(statvfs(curdir)), refs=_statvfs_refs, # statvfs_result
item=_sizeof_Cvoidp, leng=_len)
except ImportError: # missing
pass
try:
from struct import Struct # only in Python 2.5 and 3.0
_typedef_both(Struct, item=_sizeof_Cbyte, leng=_len_struct) # len in bytes
except ImportError: # missing
pass
try:
_typedef_both(Types.TracebackType, refs=_tb_refs)
except AttributeError: # missing
pass
try:
_typedef_both(unicode, leng=_len_unicode, item=_sizeof_Cunicode)
_typedef_both(str, leng=_len, item=_sizeof_Cbyte) # 1-byte char
except NameError: # str is unicode
_typedef_both(str, leng=_len_unicode, item=_sizeof_Cunicode)
try: # <type 'KeyedRef'>
_typedef_both(Weakref.KeyedRef, refs=_weak_refs, heap=True) # plus head
except AttributeError: # missing
pass
try: # <type 'weakproxy'>
_typedef_both(Weakref.ProxyType)
except AttributeError: # missing
pass
try: # <type 'weakref'>
_typedef_both(Weakref.ReferenceType, refs=_weak_refs)
except AttributeError: # missing
pass
# some other, callable types
_typedef_code(object, kind=_kind_ignored)
_typedef_code(super, kind=_kind_ignored)
_typedef_code(_Type_type, kind=_kind_ignored)
try:
_typedef_code(classmethod, refs=_im_refs)
except NameError:
pass
try:
_typedef_code(staticmethod, refs=_im_refs)
except NameError:
pass
try:
_typedef_code(Types.MethodType, refs=_im_refs)
except NameError:
pass
try: # generator, code only, no len(), not callable()
_typedef_code(Types.GeneratorType, refs=_gen_refs)
except AttributeError: # missing
pass
try: # <type 'weakcallableproxy'>
_typedef_code(Weakref.CallableProxyType, refs=_weak_refs)
except AttributeError: # missing
pass
# any type-specific iterators
s = [_items({}), _keys({}), _values({})]
try: # reversed list and tuples iterators
s.extend([reversed([]), reversed(())])
except NameError: # missing
pass
try: # range iterator
s.append(xrange(1))
except NameError: # missing
pass
try: # callable-iterator
from re import finditer
s.append(finditer('', ''))
except ImportError: # missing
pass
for t in _values(_typedefs):
if t.type and t.leng:
try: # create an (empty) instance
s.append(t.type())
except TypeError:
pass
for t in s:
try:
i = iter(t)
_typedef_both(type(i), leng=_len_iter, refs=_iter_refs, item=0) # no itemsize!
except (KeyError, TypeError): # ignore non-iterables, duplicates, etc.
pass
del i, s, t
def _typedef(obj, derive=False, infer=False):
'''Create a new typedef for an object.
'''
t = type(obj)
v = _Typedef(base=_basicsize(t, obj=obj),
kind=_kind_dynamic, type=t)
##_printf('new %r %r/%r %s', t, _basicsize(t), _itemsize(t), _repr(dir(obj)))
if ismodule(obj): # handle module like dict
v.dup(item=_dict_typedef.item + _sizeof_CPyModuleObject,
leng=_len_module,
refs=_module_refs)
elif isframe(obj):
v.set(base=_basicsize(t, base=_sizeof_CPyFrameObject, obj=obj),
item=_itemsize(t),
leng=_len_frame,
refs=_frame_refs)
elif iscode(obj):
v.set(base=_basicsize(t, base=_sizeof_CPyCodeObject, obj=obj),
item=_sizeof_Cvoidp,
leng=_len_code,
refs=_co_refs,
both=False) # code only
elif _callable(obj):
if isclass(obj): # class or type
v.set(refs=_class_refs,
both=False) # code only
if obj.__module__ in _builtin_modules:
v.set(kind=_kind_ignored)
elif isbuiltin(obj): # function or method
v.set(both=False, # code only
kind=_kind_ignored)
elif isfunction(obj):
v.set(refs=_func_refs,
both=False) # code only
elif ismethod(obj):
v.set(refs=_im_refs,
both=False) # code only
elif isclass(t): # callable instance, e.g. SCons,
# handle like any other instance further below
v.set(item=_itemsize(t), safe_len=True,
refs=_inst_refs) # not code only!
else:
v.set(both=False) # code only
elif _issubclass(t, dict):
v.dup(kind=_kind_derived)
elif _isdictclass(obj) or (infer and _infer_dict(obj)):
v.dup(kind=_kind_inferred)
elif getattr(obj, '__module__', None) in _builtin_modules:
v.set(kind=_kind_ignored)
else: # assume an instance of some class
if derive:
p = _derive_typedef(t)
if p: # duplicate parent
v.dup(other=p, kind=_kind_derived)
return v
if _issubclass(t, Exception):
v.set(item=_itemsize(t), safe_len=True,
refs=_exc_refs,
kind=_kind_derived)
elif isinstance(obj, Exception):
v.set(item=_itemsize(t), safe_len=True,
refs=_exc_refs)
else:
v.set(item=_itemsize(t), safe_len=True,
refs=_inst_refs)
return v
class _Prof(object):
'''Internal type profile class.
'''
total = 0 # total size
high = 0 # largest size
number = 0 # number of (unique) objects
objref = None # largest object (weakref)
weak = False # objref is weakref(object)
def __cmp__(self, other):
if self.total < other.total:
return -1
if self.total > other.total:
return +1
if self.number < other.number:
return -1
if self.number > other.number:
return +1
return 0
def __lt__(self, other): # for Python 3.0
return self.__cmp__(other) < 0
def format(self, clip=0, grand=None):
'''Return format dict.
'''
if self.number > 1: # avg., plural
a, p = int(self.total / self.number), 's'
else:
a, p = self.total, ''
o = self.objref
if self.weak: # weakref'd
o = o()
t = _SI2(self.total)
if grand:
t += ' (%s)' % _p100(self.total, grand, prec=0)
return _kwds(avg=_SI2(a), high=_SI2(self.high),
lengstr=_lengstr(o), obj=_repr(o, clip=clip),
plural=p, total=t)
def update(self, obj, size):
'''Update this profile.
'''
self.number += 1
self.total += size
if self.high < size: # largest
self.high = size
try: # prefer using weak ref
self.objref, self.weak = Weakref.ref(obj), True
except TypeError:
self.objref, self.weak = obj, False
# public classes
class Asized(object):
'''Store the results of an asized object
in these 4 attributes:
size - total size of the object
flat - flat size of the object
name - name or repr of the object
refs - tuple containing an instance
of Asized for each referent
'''
strf = ( '%s', # default name format
'[K] %s', # dict key, see _dict_refs
'[V] %s') # dict value, see _dict_refs
def __init__(self, size, flat, refs=(), name=None):
self.size = size # total size
self.flat = flat # flat size
self.name = name # name, repr or None
self.refs = tuple(refs)
def __str__(self):
return 'size %r, flat %r, refs[%d], name %r' % (
self.size, self.flat, len(self.refs), self.name)
def format(self, named):
'''Format name from _NamedRef instance.
'''
return self.strf[named.typ] % named.name
class Asizer(object):
'''Sizer state and options.
'''
_align_ = 8
_all_ = False
_clip_ = 80
_code_ = False
_derive_ = False
_detail_ = 0 # for Asized only
_infer_ = False
_limit_ = 100
_stats_ = 0
_cutoff = 0 # in percent
_depth = 0 # recursion depth
_duplicate = 0
_excl_d = None # {}
_ign_d = _kind_ignored
_incl = '' # or ' (incl. code)'
_mask = 7 # see _align_
_missed = 0 # due to errors
_profile = False
_profs = None # {}
_seen = None # {}
_total = 0 # total size
def __init__(self, **opts):
'''See method reset for the available options.
'''
self._excl_d = {}
self.reset(**opts)
def _clear(self):
'''Clear state.
'''
self._all_ = False
self._depth = 0 # recursion depth
self._duplicate = 0
self._incl = '' # or ' (incl. code)'
self._missed = 0 # due to errors
self._profile = False
self._profs = {}
self._seen = {}
self._total = 0 # total size
for k in _keys(self._excl_d):
self._excl_d[k] = 0
def _nameof(self, obj):
'''Return the object's name.
'''
return _nameof(obj, '') or self._repr(obj)
def _prepr(self, obj):
'''Like prepr().
'''
return _prepr(obj, clip=self._clip_)
def _prof(self, key):
'''Get _Prof object.
'''
p = self._profs.get(key, None)
if not p:
self._profs[key] = p = _Prof()
return p
def _repr(self, obj):
'''Like repr().
'''
return _repr(obj, clip=self._clip_)
def _sizer(self, obj, deep, sized):
'''Size an object, recursively.
'''
s, f, i = 0, 0, id(obj)
# skip obj if seen before
# or if ref of a given obj
if i in self._seen:
if deep:
self._seen[i] += 1
if sized:
s = sized(s, f, name=self._nameof(obj))
return s
else:
self._seen[i] = 0
try:
k, rs = _objkey(obj), []
if k in self._excl_d:
self._excl_d[k] += 1
else:
v = _typedefs.get(k, None)
if not v: # new typedef
_typedefs[k] = v = _typedef(obj, derive=self._derive_,
infer=self._infer_)
if (v.both or self._code_) and v.kind is not self._ign_d:
s = f = v.flat(obj, self._mask) # flat size
if self._profile: # profile type
self._prof(k).update(obj, s)
# recurse, but not for nested modules
if deep < self._limit_ and not (deep and ismodule(obj)):
# add sizes of referents
r, z, d = v.refs, self._sizer, deep + 1
if self._all_: # use 'all' referents
r = _getreferents(obj)
if r:
t = id(r)
if t in self._seen:
for o in r: # no sum(<generator_expression>) in Python 2.2
s += z(o, d, None)
else: # exclude container
self._seen[t] = 0
for o in r: # no sum(<generator_expression>) in Python 2.2
s += z(o, d, None)
del self._seen[t]
elif r: # and _callable(r):
if sized and deep < self._detail_:
# use named referents
for o in r(obj, True):
if isinstance(o, _NamedRef):
t = z(o.ref, d, sized)
t.name = t.format(o)
else:
t = z(o, d, sized)
t.name = self._nameof(o)
rs.append(t)
s += t.size
else: # no sum(<generator_expression>) in Python 2.2
for o in r(obj, False):
s += z(o, d, None)
# recursion depth
if self._depth < d:
self._depth = d
self._seen[i] += 1
except RuntimeError: # XXX RecursionLimitExceeded:
self._missed += 1
if sized:
s = sized(s, f, name=self._nameof(obj), refs=rs)
return s
def _sizes(self, objs, sized=None):
'''Return the size or an Asized instance for each
given object and the total size. The total
includes the size of duplicates only once.
'''
self.exclude_refs(*objs) # skip refs to objs
s, t = {}, []
for o in objs:
i = id(o)
if i in s: # duplicate
self._seen[i] += 1
self._duplicate += 1
else:
s[i] = self._sizer(o, 0, sized)
t.append(s[i])
if sized:
s = _sum([i.size for i in _values(s)]) # [] for Python 2.2
else:
s = _sum(_values(s))
self._total += s # accumulate
return s, tuple(t)
def asized(self, *objs, **opts):
'''Size each object and return an Asized instance with
size information and referents up to the given detail
level (and with modified options, see method set).
If only one object is given, the return value is the
Asized instance for that object.
'''
if opts:
self.set(**opts)
if self._all_:
raise KeyError('invalid option: %s=%r' % ('all', self._all_))
_, t = self._sizes(objs, Asized)
if len(t) == 1:
t = t[0]
return t
def asizeof(self, *objs, **opts):
'''Return the combined size of the given objects
(with modified options, see also method set).
'''
if opts:
self.set(**opts)
s, _ = self._sizes(objs, None)
return s
def asizesof(self, *objs, **opts):
'''Return the individual sizes of the given objects
(with modified options, see also method set).
'''
if opts:
self.set(**opts)
_, t = self._sizes(objs, None)
return t
def exclude_refs(self, *objs):
'''Exclude any references to the specified objects from sizing.
While any references to the given objects are excluded, the
objects will be sized if specified as positional arguments
in subsequent calls to methods asizeof and asizesof.
'''
for o in objs:
self._seen.setdefault(id(o), 0)
def exclude_types(self, *objs):
'''Exclude the specified object instances and types from sizing.
All instances and types of the given objects are excluded,
even objects specified as positional arguments in subsequent
calls to methods asizeof and asizesof.
'''
for o in objs:
for t in _keytuple(o):
if t and t not in self._excl_d:
self._excl_d[t] = 0
def print_profiles(self, w=0, cutoff=0, **print3opts):
'''Print the profiles above cutoff percentage.
w=0 -- indentation for each line
cutoff=0 -- minimum percentage printed
print3options -- print options, as in Python 3.0
'''
# get the profiles with non-zero size or count
t = [(v, k) for k, v in _items(self._profs) if v.total > 0 or v.number > 1]
if (len(self._profs) - len(t)) < 9: # just show all
t = [(v, k) for k, v in _items(self._profs)]
if t:
s = ''
if self._total:
s = ' (% of grand total)'
c = max(cutoff, self._cutoff)
c = int(c * 0.01 * self._total)
else:
c = 0
_printf('%s%*d profile%s: total%s, average, and largest flat size%s: largest object',
linesep, w, len(t), _plural(len(t)), s, self._incl, **print3opts)
r = len(t)
for v, k in _sorted(t, reverse=True):
s = 'object%(plural)s: %(total)s, %(avg)s, %(high)s: %(obj)s%(lengstr)s' % v.format(self._clip_, self._total)
_printf('%*d %s %s', w, v.number, self._prepr(k), s, **print3opts)
r -= 1
if r > 1 and v.total < c:
c = max(cutoff, self._cutoff)
_printf('%+*d profiles below cutoff (%.0f%%)', w, r, c)
break
z = len(self._profs) - len(t)
if z > 0:
_printf('%+*d %r object%s', w, z, 'zero', _plural(z), **print3opts)
def print_stats(self, objs=(), opts={}, sized=(), sizes=(), stats=3.0, **print3opts):
'''Print the statistics.
w=0 -- indentation for each line
objs=() -- optional, list of objects
opts={} -- optional, dict of options used
sized=() -- optional, tuple of Asized instances returned
sizes=() -- optional, tuple of sizes returned
stats=3.0 -- print statistics and cutoff percentage
print3options -- print options, as in Python 3.0
'''
s = min(opts.get('stats', stats) or 0, self._stats_)
if s > 0: # print stats
t = self._total + self._missed + _sum(_values(self._seen))
w = len(str(t)) + 1
t = c = ''
o = _kwdstr(**opts)
if o and objs:
c = ', '
# print header line(s)
if sized and objs:
n = len(objs)
if n > 1:
_printf('%sasized(...%s%s) ...', linesep, c, o, **print3opts)
for i in range(n): # no enumerate in Python 2.2.3
_printf('%*d: %s', w-1, i, sized[i], **print3opts)
else:
_printf('%sasized(%s): %s', linesep, o, sized, **print3opts)
elif sizes and objs:
_printf('%sasizesof(...%s%s) ...', linesep, c, o, **print3opts)
for z, o in zip(sizes, objs):
_printf('%*d bytes%s%s: %s', w, z, _SI(z), self._incl, self._repr(o), **print3opts)
else:
if objs:
t = self._repr(objs)
_printf('%sasizeof(%s%s%s) ...', linesep, t, c, o, **print3opts)
# print summary
self.print_summary(w=w, objs=objs, **print3opts)
if s > 1: # print profile
c = int(s - int(s)) * 100
self.print_profiles(w=w, cutoff=c, **print3opts)
if s > 2: # print typedefs
self.print_typedefs(w=w, **print3opts)
def print_summary(self, w=0, objs=(), **print3opts):
'''Print the summary statistics.
w=0 -- indentation for each line
objs=() -- optional, list of objects
print3options -- print options, as in Python 3.0
'''
_printf('%*d bytes%s%s', w, self._total, _SI(self._total), self._incl, **print3opts)
if self._mask:
_printf('%*d byte aligned', w, self._mask + 1, **print3opts)
_printf('%*d byte sizeof(void*)', w, _sizeof_Cvoidp, **print3opts)
n = len(objs or ())
if n > 0:
d = self._duplicate or ''
if d:
d = ', %d duplicate' % self._duplicate
_printf('%*d object%s given%s', w, n, _plural(n), d, **print3opts)
t = _sum([1 for t in _values(self._seen) if t != 0]) # [] for Python 2.2
_printf('%*d object%s sized', w, t, _plural(t), **print3opts)
if self._excl_d:
t = _sum(_values(self._excl_d))
_printf('%*d object%s excluded', w, t, _plural(t), **print3opts)
t = _sum(_values(self._seen))
_printf('%*d object%s seen', w, t, _plural(t), **print3opts)
if self._missed > 0:
_printf('%*d object%s missed', w, self._missed, _plural(self._missed), **print3opts)
if self._depth > 0:
_printf('%*d recursion depth', w, self._depth, **print3opts)
def print_typedefs(self, w=0, **print3opts):
'''Print the types and dict tables.
w=0 -- indentation for each line
print3options -- print options, as in Python 3.0
'''
for k in _all_kinds:
# XXX Python 3.0 doesn't sort type objects
t = [(self._prepr(a), v) for a, v in _items(_typedefs) if v.kind == k and (v.both or self._code_)]
if t:
_printf('%s%*d %s type%s: basicsize, itemsize, _len_(), _refs()',
linesep, w, len(t), k, _plural(len(t)), **print3opts)
for a, v in _sorted(t):
_printf('%*s %s: %s', w, '', a, v, **print3opts)
# dict and dict-like classes
t = _sum([len(v) for v in _values(_dict_classes)]) # [] for Python 2.2
if t:
_printf('%s%*d dict/-like classes:', linesep, w, t, **print3opts)
for m, v in _items(_dict_classes):
_printf('%*s %s: %s', w, '', m, self._prepr(v), **print3opts)
def set(self, align=None, code=None, detail=None, limit=None, stats=None):
'''Set some options. Any options not set
remain the same as the previous setting.
align=8 -- size alignment
code=False -- incl. (byte)code size
detail=0 -- Asized refs level
limit=100 -- recursion limit
stats=0.0 -- print statistics and cutoff percentage
'''
# adjust
if align is not None:
self._align_ = align
if align > 1:
self._mask = align - 1
if (self._mask & align) != 0:
raise ValueError('invalid option: %s=%r' % ('align', align))
else:
self._mask = 0
if code is not None:
self._code_ = code
if code: # incl. (byte)code
self._incl = ' (incl. code)'
if detail is not None:
self._detail_ = detail
if limit is not None:
self._limit_ = limit
if stats is not None:
self._stats_ = s = int(stats)
self._cutoff = (stats - s) * 100
if s > 1: # profile types
self._profile = True
else:
self._profile = False
def _get_duplicate(self):
'''Number of duplicate objects.
'''
return self._duplicate
duplicate = property(_get_duplicate, doc=_get_duplicate.__doc__)
def _get_missed(self):
'''Number of objects missed due to errors.
'''
return self._missed
missed = property(_get_missed, doc=_get_missed.__doc__)
def _get_total(self):
'''Total size accumulated so far.
'''
return self._total
total = property(_get_total, doc=_get_total.__doc__)
def reset(self, align=8, all=False, clip=80, code=False, derive=False, #PYCHOK expected
detail=0, ignored=True, infer=False, limit=100, stats=0):
'''Reset options, state, etc.
The available options and default values are:
align=8 -- size alignment
all=False -- all current GC objects and referents
clip=80 -- clip repr() strings
code=False -- incl. (byte)code size
derive=False -- derive from super type
detail=0 -- Asized refs level
ignored=True -- ignore certain types
infer=False -- try to infer types
limit=100 -- recursion limit
stats=0.0 -- print statistics and cutoff percentage
See function asizeof for a description of the options.
'''
# options
self._align_ = align
self._all_ = all
self._clip_ = clip
self._code_ = code
self._derive_ = derive
self._detail_ = detail # for Asized only
self._infer_ = infer
self._limit_ = limit
self._stats_ = stats
if ignored:
self._ign_d = _kind_ignored
else:
self._ign_d = None
# clear state
self._clear()
self.set(align=align, code=code, stats=stats)
# public functions
def adict(*classes):
'''Install one or more classes to be handled as dict.
'''
a = True
for c in classes:
# if class is dict-like, add class
# name to _dict_classes[module]
if isclass(c) and _infer_dict(c):
t = _dict_classes.get(c.__module__, ())
if c.__name__ not in t: # extend tuple
_dict_classes[c.__module__] = t + (c.__name__,)
else: # not a dict-like class
a = False
return a # all installed if True
_asizer = Asizer()
def asized(*objs, **opts):
'''Return a tuple containing an Asized instance for each
object passed as positional argment using the following
options.
align=8 -- size alignment
all=False -- all current GC objects and referents
clip=80 -- clip repr() strings
code=False -- incl. (byte)code size
derive=False -- derive from super type
detail=0 -- Asized refs level
ignored=True -- ignore certain types
infer=False -- try to infer types
limit=100 -- recursion limit
stats=0.0 -- print statistics and cutoff percentage
If only one object is given, the return value is the Asized
instance for that object.
Set detail to the desired referents level (recursion depth).
See function asizeof for descriptions of the other options.
The length of the returned tuple matches the number of given
objects, if more than one object is given.
'''
t = _objs(objs, **opts)
if t:
_asizer.reset(**opts)
s = _asizer.asized(*t)
_asizer.print_stats(objs=t, opts=opts, sized=s)
_asizer._clear()
else:
s = ()
return s
def asizeof(*objs, **opts):
'''Return the combined size in bytes of all objects passed
as positional argments.
The available options and defaults are the following.
align=8 -- size alignment
all=False -- all current GC objects and referents
clip=80 -- clip ``repr()`` strings
code=False -- incl. (byte)code size
derive=False -- derive from super type
ignored=True -- ignore certain types
infer=False -- try to infer types
limit=100 -- recursion limit
stats=0.0 -- print statistics and cutoff percentage
Set align to a power of 2 to align sizes. Any value less
than 2 avoids size alignment.
All current GC objects are sized if all is True and if no
positional arguments are supplied. Also, if all is True
the GC referents are used instead of the limited ones.
A positive clip value truncates all repr() strings to at
most clip characters.
The (byte)code size of callable objects like functions,
methods, classes, etc. is included only if code is True.
If derive is True, new types are handled like an existing
(super) type provided there is one and only of those.
By default, certain base types like object are ignored for
sizing. Set ignored to False to force all ignored types
in the size of objects.
By default certain base types like object, super, etc. are
ignored. Set ignored to False to include those.
If infer is True, new types are inferred from attributes
(only implemented for dict types on callable attributes
as get, has_key, items, keys and values).
Set limit to a positive value to accumulate the sizes of
the referents of each object, recursively up to the limit.
Using limit zero returns the sum of the flat [1] sizes of
the given objects. High limit values may cause runtime
errors and miss objects for sizing.
A positive value for stats prints up to 8 statistics, (1)
a summary of the number of objects sized and seen, (2) a
simple profile of the sized objects by type and (3+) up to
6 tables showing the static, dynamic, derived, ignored,
inferred and dict types used, found respectively installed.
The fractional part of the stats value (x 100) is the cutoff
percentage for simple profiles. Objects below the cutoff
value are not reported.
[1] See the documentation of this module for the definition
of flat size.
'''
t = _objs(objs, **opts)
if t:
_asizer.reset(**opts)
s = _asizer.asizeof(*t)
_asizer.print_stats(objs=t, opts=opts)
_asizer._clear()
else:
s = 0
return s
def asizesof(*objs, **opts):
'''Return a tuple containing the size in bytes of all objects
passed as positional argments using the following options.
align=8 -- size alignment
all=False -- use GC objects and referents
clip=80 -- clip ``repr()`` strings
code=False -- incl. (byte)code size
derive=False -- derive from super type
ignored=True -- ignore certain types
infer=False -- try to infer types
limit=100 -- recursion limit
stats=0.0 -- print statistics and cutoff percentage
See function asizeof for a description of the options.
The length of the returned tuple equals the number of given
objects.
'''
t = _objs(objs, **opts)
if t:
_asizer.reset(**opts)
s = _asizer.asizesof(*t)
_asizer.print_stats(objs=t, opts=opts, sizes=s)
_asizer._clear()
else:
s = ()
return s
def _typedefof(obj, save=False, **opts):
'''Get the typedef for an object.
'''
k = _objkey(obj)
v = _typedefs.get(k, None)
if not v: # new typedef
v = _typedef(obj, **opts)
if save:
_typedefs[k] = v
return v
def basicsize(obj, **opts):
'''Return the basic size of an object (in bytes).
Valid options and defaults are
derive=False -- derive type from super type
infer=False -- try to infer types
save=False -- save typedef if new
'''
v = _typedefof(obj, **opts)
if v:
v = v.base
return v
def flatsize(obj, align=0, **opts):
'''Return the flat size of an object (in bytes),
optionally aligned to a given power of 2.
See function basicsize for a description of
the other options. See the documentation of
this module for the definition of flat size.
'''
v = _typedefof(obj, **opts)
if v:
if align > 1:
m = align - 1
if (align & m) != 0:
raise ValueError('invalid option: %s=%r' % ('align', align))
else:
m = 0
v = v.flat(obj, m)
return v
def itemsize(obj, **opts):
'''Return the item size of an object (in bytes).
See function basicsize for a description of
the options.
'''
v = _typedefof(obj, **opts)
if v:
v = v.item
return v
def leng(obj, **opts):
'''Return the length of an object (in items).
See function basicsize for a description
of the options.
'''
v = _typedefof(obj, **opts)
if v:
v = v.leng
if v and _callable(v):
v = v(obj)
return v
def refs(obj, all=False, **opts):
'''Return (a generator for) specific referents of an
object.
If all is True return the GC referents.
See function basicsize for a description of the
options.
'''
v = _typedefof(obj, **opts)
if v:
if all: # == True
v = _getreferents(obj)
else:
v = v.refs
if v and _callable(v):
v = v(obj, False)
return v
if __name__ == '__main__':
argv, MAX = sys.argv, sys.getrecursionlimit()
def _print_asizeof(obj, infer=False, stats=0):
a = [_repr(obj),]
for d, c in ((0, False), (MAX, False), (MAX, True)):
a.append(asizeof(obj, limit=d, code=c, infer=infer, stats=stats))
_printf(" asizeof(%s) is %d, %d, %d", *a)
def _print_functions(obj, name=None, align=8, detail=MAX, code=False, limit=MAX,
opt='', **unused):
if name:
_printf('%sasizeof functions for %s ... %s', linesep, name, opt)
_printf('%s(): %s', ' basicsize', basicsize(obj))
_printf('%s(): %s', ' itemsize', itemsize(obj))
_printf('%s(): %r', ' leng', leng(obj))
_printf('%s(): %s', ' refs', _repr(refs(obj)))
_printf('%s(): %s', ' flatsize', flatsize(obj, align=align)) # , code=code
_printf('%s(): %s', ' asized', asized(obj, align=align, detail=detail, code=code, limit=limit))
##_printf('%s(): %s', '.asized', _asizer.asized(obj, align=align, detail=detail, code=code, limit=limit))
def _bool(arg):
a = arg.lower()
if a in ('1', 't', 'y', 'true', 'yes', 'on'):
return True
elif a in ('0', 'f', 'n', 'false', 'no', 'off'):
return False
else:
raise ValueError('bool option expected: %r' % arg)
def _opts(*opts):
'''Return True if any oof the given options
was present in the command line arguments.
'''
for o in opts + ('-', '--'):
if o in argv:
return True
return False
if '-im' in argv or '-import' in argv:
# import and size modules given as args
def _aopts(argv, **opts):
'''Get argv options as typed values.
'''
i = 1
while argv[i].startswith('-'):
k = argv[i].lstrip('-')
if 'import'.startswith(k):
i += 1
elif k in opts:
t = type(opts[k])
if t is bool:
t = _bool
i += 1
opts[k] = t(argv[i])
i += 1
else:
raise NameError('invalid option: %s' % argv[i])
return opts, i
opts, i = _aopts(argv, align=8, clip=80, code=False, derive=False, detail=MAX, limit=MAX, stats=0)
while i < len(argv):
m, i = argv[i], i + 1
if m == 'eval' and i < len(argv):
o, i = eval(argv[i]), i + 1
else:
o = __import__(m)
s = asizeof(o, **opts)
_printf("%sasizeof(%s) is %d", linesep, _repr(o, opts['clip']), s)
_print_functions(o, **opts)
argv = []
elif len(argv) < 2 or _opts('-h', '-help'):
d = {'-all': 'all=True example',
'-basic': 'basic examples',
'-C': 'Csizeof values',
'-class': 'class and instance examples',
'-code': 'code examples',
'-dict': 'dict and UserDict examples',
##'-gc': 'gc examples',
'-gen[erator]': 'generator examples',
'-glob[als]': 'globals examples, incl. asized()',
'-h[elp]': 'print this information',
'-im[port] <module>': 'imported module example',
'-int | -long': 'int and long examples',
'-iter[ator]': 'iterator examples',
'-loc[als]': 'locals examples',
'-pair[s]': 'key pair examples',
'-slots': 'slots examples',
'-stack': 'stack examples',
'-sys': 'sys.modules examples',
'-test': 'test flatsize() vs sys.getsizeof()',
'-type[def]s': 'type definitions',
'- | --': 'all examples'}
w = -max([len(o) for o in _keys(d)]) # [] for Python 2.2
t = _sorted(['%*s -- %s' % (w, o, t) for o, t in _items(d)]) # [] for Python 2.2
t = '\n '.join([''] + t)
_printf('usage: %s <option> ...\n%s\n', argv[0], t)
class C: pass
class D(dict):
_attr1 = None
_attr2 = None
class E(D):
def __init__(self, a1=1, a2=2): #PYCHOK OK
self._attr1 = a1 #PYCHOK OK
self._attr2 = a2 #PYCHOK OK
class P(object):
_p = None
def _get_p(self):
return self._p
p = property(_get_p) #PYCHOK OK
class O: # old style
a = None
b = None
class S(object): # new style
__slots__ = ('a', 'b')
class T(object):
__slots__ = ('a', 'b')
def __init__(self):
self.a = self.b = 0
if _opts('-all'): # all=True example
_printf('%sasizeof(limit=%s, code=%s, %s) ... %s', linesep, 'MAX', True, 'all=True', '-all')
asizeof(limit=MAX, code=True, stats=MAX, all=True)
if _opts('-basic'): # basic examples
_printf('%sasizeof(%s) for (limit, code) in %s ... %s', linesep, '<basic_objects>', '((0, False), (MAX, False), (MAX, True))', '-basic')
for o in (None, True, False,
1.0, 1.0e100, 1024, 1000000000,
'', 'a', 'abcdefg',
{}, (), []):
_print_asizeof(o, infer=True)
if _opts('-C'): # show all Csizeof values
_sizeof_Cdouble = calcsize('d') #PYCHOK OK
_sizeof_Csize_t = calcsize('Z') #PYCHOK OK
_sizeof_Cssize_t = calcsize('z') #PYCHOK OK
t = [t for t in locals().items() if t[0].startswith('_sizeof_')]
_printf('%s%d C sizes: (bytes) ... -C', linesep, len(t))
for n, v in _sorted(t):
_printf(' sizeof(%s): %r', n[len('_sizeof_'):], v)
if _opts('-class'): # class and instance examples
_printf('%sasizeof(%s) for (limit, code) in %s ... %s', linesep, '<non-callable>', '((0, False), (MAX, False), (MAX, True))', '-class')
for o in (C(), C.__dict__,
D(), D.__dict__,
E(), E.__dict__,
P(), P.__dict__, P.p,
O(), O.__dict__,
S(), S.__dict__,
S(), S.__dict__,
T(), T.__dict__):
_print_asizeof(o, infer=True)
if _opts('-code'): # code examples
_printf('%sasizeof(%s) for (limit, code) in %s ... %s', linesep, '<callable>', '((0, False), (MAX, False), (MAX, True))', '-code')
for o in (C, D, E, P, S, T, # classes are callable
type,
_co_refs, _dict_refs, _inst_refs, _len_int, _seq_refs, lambda x: x,
(_co_refs, _dict_refs, _inst_refs, _len_int, _seq_refs),
_typedefs):
_print_asizeof(o)
if _opts('-dict'): # dict and UserDict examples
_printf('%sasizeof(%s) for (limit, code) in %s ... %s', linesep, '<Dicts>', '((0, False), (MAX, False), (MAX, True))', '-dict')
try:
import UserDict # no UserDict in 3.0
for o in (UserDict.IterableUserDict(), UserDict.UserDict()):
_print_asizeof(o)
except ImportError:
pass
class _Dict(dict):
pass
for o in (dict(), _Dict(),
P.__dict__, # dictproxy
Weakref.WeakKeyDictionary(), Weakref.WeakValueDictionary(),
_typedefs):
_print_asizeof(o, infer=True)
##if _opts('-gc'): # gc examples
##_printf('%sasizeof(limit=%s, code=%s, *%s) ...', linesep, 'MAX', False, 'gc.garbage')
##from gc import collect, garbage # list()
##asizeof(limit=MAX, code=False, stats=1, *garbage)
##collect()
##asizeof(limit=MAX, code=False, stats=2, *garbage)
if _opts('-gen', '-generator'): # generator examples
_printf('%sasizeof(%s, code=%s) ... %s', linesep, '<generator>', True, '-gen[erator]')
def gen(x):
i = 0
while i < x:
yield i
i += 1
a = gen(5)
b = gen(50)
asizeof(a, code=True, stats=1)
asizeof(b, code=True, stats=1)
asizeof(a, code=True, stats=1)
if _opts('-glob', '-globals'): # globals examples
_printf('%sasizeof(%s, limit=%s, code=%s) ... %s', linesep, 'globals()', 'MAX', False, '-glob[als]')
asizeof(globals(), limit=MAX, code=False, stats=1)
_print_functions(globals(), 'globals()', opt='-glob[als]')
_printf('%sasizesof(%s, limit=%s, code=%s) ... %s', linesep, 'globals(), locals()', 'MAX', False, '-glob[als]')
asizesof(globals(), locals(), limit=MAX, code=False, stats=1)
asized(globals(), align=0, detail=MAX, limit=MAX, code=False, stats=1)
if _opts('-int', '-long'): # int and long examples
try:
_L5d = long(1) << 64
_L17d = long(1) << 256
t = '<int>/<long>'
except NameError:
_L5d = 1 << 64
_L17d = 1 << 256
t = '<int>'
_printf('%sasizeof(%s, align=%s, limit=%s) ... %s', linesep, t, 0, 0, '-int')
for o in (1024, 1000000000,
1.0, 1.0e100, 1024, 1000000000,
MAX, 1 << 32, _L5d, -_L5d, _L17d, -_L17d):
_printf(" asizeof(%s) is %s (%s + %s * %s)", _repr(o), asizeof(o, align=0, limit=0),
basicsize(o), leng(o), itemsize(o))
if _opts('-iter', '-iterator'): # iterator examples
_printf('%sasizeof(%s, code=%s) ... %s', linesep, '<iterator>', False, '-iter[ator]')
o = iter('0123456789')
e = iter('')
d = iter({})
i = iter(_items({1:1}))
k = iter(_keys({2:2, 3:3}))
v = iter(_values({4:4, 5:5, 6:6}))
l = iter([])
t = iter(())
asizesof(o, e, d, i, k, v, l, t, limit=0, code=False, stats=1)
asizesof(o, e, d, i, k, v, l, t, limit=9, code=False, stats=1)
if _opts('-loc', '-locals'): # locals examples
_printf('%sasizeof(%s, limit=%s, code=%s) ... %s', linesep, 'locals()', 'MAX', False, '-loc[als]')
asizeof(locals(), limit=MAX, code=False, stats=1)
_print_functions(locals(), 'locals()', opt='-loc[als]')
if _opts('-pair', '-pairs'): # key pair examples
# <http://jjinux.blogspot.com/2008/08/python-memory-conservation-tip.html>
_printf('%sasizeof(%s) vs asizeof(%s) ... %s', linesep, 'dict[i][j]', 'dict[(i,j)]', '-pair[s]')
n = m = 200
p = {} # [i][j]
for i in range(n):
q = {}
for j in range(m):
q[j] = None
p[i] = q
p = asizeof(p, stats=1)
t = {} # [(i,j)]
for i in range(n):
for j in range(m):
t[(i,j)] = None
t = asizeof(t, stats=1)
_printf('%sasizeof(dict[i][j]) is %s of asizeof(dict[(i,j)])', linesep, _p100(p, t))
if _opts('-slots'): # slots examples
_printf('%sasizeof(%s, code=%s) ... %s', linesep, '<__slots__>', False, '-slots')
class Old:
pass # m = None
class New(object):
__slots__ = ('n',)
class Sub(New): #PYCHOK OK
__slots__ = {'s': ''} # duplicate!
def __init__(self): #PYCHOK OK
New.__init__(self)
# basic instance sizes
o, n, s = Old(), New(), Sub()
asizesof(o, n, s, limit=MAX, code=False, stats=1)
# with unique min attr size
o.o = 'o'
n.n = 'n'
s.n = 'S'
s.s = 's'
asizesof(o, n, s, limit=MAX, code=False, stats=1)
# with duplicate, intern'ed, 1-char string attrs
o.o = 'x'
n.n = 'x'
s.n = 'x'
s.s = 'x'
asizesof(o, n, s, 'x', limit=MAX, code=False, stats=1)
# with larger attr size
o.o = 'o'*1000
n.n = 'n'*1000
s.n = 'n'*1000
s.s = 's'*1000
asizesof(o, n, s, 'x'*1000, limit=MAX, code=False, stats=1)
if _opts('-stack'): # stack examples
_printf('%sasizeof(%s, limit=%s, code=%s) ... %s', linesep, 'stack(MAX)', 'MAX', False, '')
asizeof(stack(MAX), limit=MAX, code=False, stats=1)
_print_functions(stack(MAX), 'stack(MAX)', opt='-stack')
if _opts('-sys'): # sys.modules examples
_printf('%sasizeof(limit=%s, code=%s, *%s) ... %s', linesep, 'MAX', False, 'sys.modules.values()', '-sys')
asizeof(limit=MAX, code=False, stats=1, *sys.modules.values())
_print_functions(sys.modules, 'sys.modules', opt='-sys')
if _opts('-type', '-types', '-typedefs'): # show all basic _typedefs
t = len(_typedefs)
w = len(str(t)) * ' '
_printf('%s%d type definitions: basic- and itemsize (leng), kind ... %s', linesep, t, '-type[def]s')
for k, v in _sorted([(_prepr(k), v) for k, v in _items(_typedefs)]): # [] for Python 2.2
s = '%(base)s and %(item)s%(leng)s, %(kind)s%(code)s' % v.format()
_printf('%s %s: %s', w, k, s)
if _opts('-test'):
# compare the results of flatsize() *without* using sys.getsizeof()
# with the accurate sizes returned by sys.getsizeof() but expect
# differences for sequences as dicts, lists, sets, tuples, etc.
# while this is no proof for the accuracy of flatsize() on Python
# builds without sys.getsizeof(), it does provide some evidence
# that that flatsize() produces reasonable and usable results
_printf('%sflatsize() vs sys.getsizeof() ... %s', linesep, '-test')
t, g, e = [], _getsizeof, 0
if g:
for v in _values(_typedefs):
t.append(v.type)
try: # creating one instance
if v.type.__module__ not in ('io',): # avoid 3.0 RuntimeWarning
t.append(v.type())
except (AttributeError, SystemError, TypeError, ValueError): # ignore errors
pass
t.extend(({1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8},
[1,2,3,4,5,6,7,8], ['1', '2', '3'], [0] * 100,
'12345678', 'x' * 1001,
(1,2,3,4,5,6,7,8), ('1', '2', '3'), (0,) * 100,
_Slots((1,2,3,4,5,6,7,8)), _Slots(('1', '2', '3')), _Slots((0,) * 100),
0, 1 << 8, 1 << 16, 1 << 32, 1 << 64, 1 << 128,
complex(0, 1), True, False))
_getsizeof = None # zap _getsizeof for flatsize()
for o in t:
a = flatsize(o)
s = sys.getsizeof(o, 0) # 0 as default #PYCHOK expected
if a != s:
# flatsize approximates the length of sequences
# (sys.getsizeof(bool) on 3.0b3 is not correct)
if type(o) in (dict, list, set, frozenset, tuple) or (
type(o) in (bool,) and sys.version_info[0] == 3):
x = 'expected failure'
else:
x = '%r' % _typedefof(o)
e += 1
_printf('flatsize() %s vs sys.getsizeof() %s for %s: %s, %s',
a, s, _nameof(type(o)), _repr(o), x)
_getsizeof = g # restore
n, p = len(t), 'python %s' % sys.version.split()[0]
if e:
_printf('%s%d of %d tests failed or %s on %s', linesep, e, n, _p100(e, n), p)
elif g:
_printf('no unexpected failures in %d tests on %s', n, p)
else:
_printf('no sys.%s() in this %s', 'getsizeof', p)
# License file from an earlier version of this source file follows:
#---------------------------------------------------------------------
# Copyright (c) 2002-2009 -- ProphICy Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# - Neither the name of ProphICy Semiconductor, Inc. nor the names
# of its contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
#---------------------------------------------------------------------
This recipe is an enhancement of recipe #544288 to determine the size of Python objects in bytes, The main differences are (1) classes and instances are handled separately, (2) old-style classes are treated as new-style ones, (3) a simple profile of the objects can be printed, and (4) 8 functions plus 1 class are exposed by this module. More information can be found in the documentation and the examples.
Version 5.0+ of this recipe includes several major enhancements including some tests to compare the result of functions flatsize and sys.getsizeof on Python 2.6 or 3.0. See command line option -test.
Johan Geldenhuys/Writes logfiles and keep backups ( python)
""" logger.py
This module is responsible for controlling the action logging for the
application.
"""
"""
Author: Johan Geldenhuys
"""
##
#Imports
################################################################################
import os, time, threading
#Constants
################################################################################
""" Tuple containing the backup filename extensions"""
OLD_FILE_TUP = ('.1bak','.2bak','.3bak','.4bak')
STR_TIME_FORMAT = '%d/%m/%Y %H:%M:%S'
CR = '\n'
TIMESTAMP = 'TIMESTAMP: '
SPACE = ' '
#Classes
################################################################################
class ActionLogManager (object):
""" Script action log storage manager class
"""
##
#Constructor
############################################################################
def __init__ (self):
""" LogStorageManager constructor
Initialising the LogStorageManager class
:Parameters:
-
:Returns:
- None
"""
##
#Private Members
########################################################################
self._actionLogName = ('ActivityLogFile')
self._logHandle = None
self._maxEntries = 20
self._maxEntryCount = 0
self._logStr = None
self._threadObject = None
self._threadFlag = False
""" check if the log file exists. If yes read the entries and update the
entry counter."""
if os.path.exists(self._actionLogName):
""" The log file exists already """
logFile = open(self._actionLogName, 'r')
""" Read the number of entries from the log file"""
self._maxEntryCount = len(logFile.readlines())
print('No. of entries in Action log file:%d' %\
self._maxEntryCount )
""" Close it"""
logFile.close()
""" Flag which will be usd to determine that the application is shutting down """
self._isRunning = True
print('LogStorageManager Class Initialised..')
##
#Methods
############################################################################
def writeActionLog(self):
""" This method just logs the logStr into log-action-file and increments
the entry-count
:Parameters:
- None
:Returns:
- None
:Raises:
-`FileHandlingException` : Raised when the script encounters an
IOError.
"""
try:
""" Opening the file in append mode and writing to it """
self._logHandle = open(self._actionLogName, 'a+')
self._logHandle.write(self._logStr)
""" Incrementing the entry count """
self._maxEntryCount += 1
print('The action log string written to the file')
self._logHandle.close()
except IOError:
print('ActionLogFile could not be written to.')
############################################################################
def logMessage(self, msg):
""" This method will log the data together with time stamp.
The eventual checking, file transfer and backup will also be done by
this method.
:Parameters:
- `msg` : Contains the text message.
:Returns:
- None.
:Raises:
- `FileHandlingException` : Raised when file operation fails.
"""
""" Getting the Time-Stamp """
timeStr = time.strftime(STR_TIME_FORMAT, time.localtime())
string = msg
self._logStr = TIMESTAMP + timeStr + SPACE + string + CR
print self._logStr
""" Calling the writeActionLog method """
self.writeActionLog()
""" Checking for Maximum entries """
if( self._maxEntryCount >= self._maxEntries):
""" If the maximum entries is reached start the thread"""
try:
if self._threadFlag is not True:
""" Creating a new thread object """
self._threadObject = WriteThread(self)
""" Starting the new thread """
self._threadObject.start()
""" Sleeping so that the thread runs """
time.sleep(1)
else:
print('Log file already resized, Write thread active !!')
except Exception :
printException()
############################################################################
def threadRun (self):
"""run method of the thread
This method will run as a separate thread which will handle the file overwrite function.
:Parameters:
- None
:Returns:
- None
Setting the threadFlag so that any accidental duplicate spawning doesnt occur.
"""
self._threadFlag = True
print('Maximum entry count exceeded. Starting the '\
+ 'Write thread..')
try:
try:
""" Checks whether the files exist """
if(os.path.exists(self._actionLogName)):
""" if 4th bak file exists remove it """
if(os.path.exists(self._actionLogName + OLD_FILE_TUP[3])):
os.remove(self._actionLogName + OLD_FILE_TUP[3])
print('Removing %s file' \
%self._actionLogName + OLD_FILE_TUP[3])
""" Renaming the bak files to accomodate the new file """
for index in range(2, -1, -1):
if(os.path.exists(self._actionLogName \
+ OLD_FILE_TUP[index])):
os.rename(self._actionLogName + OLD_FILE_TUP[index],
self._actionLogName + OLD_FILE_TUP[index + 1])
os.rename(self._actionLogName, self._actionLogName \
+ OLD_FILE_TUP[0])
except IOError:
printException()
""" Making the entry count to 0 """
self._maxEntryCount = 0
finally:
""" Clearing the threadFlag when the thread ends """
self._threadFlag = False
############################################################################
def stop (self):
""" method for stopping the WriteThread
:Parameters:
- None
:Returns:
- None
"""
""" Calling the stop method of the thread """
print('Stopping ActionLogManager ..')
if (self._threadFlag == True):
""" Notify the Write thread that it needs to be stopped """
self._isRunning = False
self._threadObject.join()
################################################################################
class WriteThread (threading.Thread):
""" WriteThread class
This class will overwrite old backup files and rename the other files in
separate threads.
"""
##
#Constructor
############################################################################
def __init__ (self , caller):
""" WriteThread constructor
:Paramters:
- `caller` : Reference to the calling object
:Returns:
- None
"""
""" Calling the constructor of the base class """
threading.Thread.__init__ (self)
self._caller = caller
print('Initialising the WriteThread class ..')
############################################################################
def run (self):
""" run method of the WriteThread class
:Parameters:
- None
:Returns:
- None
"""
print('Inside the run method of the WriteThread')
""" Calling the threadRun method of the LogStorageManager class """
self._caller.threadRun()
################################################################################
This module is called with a string message and it is written to a file with a date and timestamp. After a certain number of entries, it creates a backup of the file.
Broly/Brick ( ActionScript)
// ********* BRICK (aka ARKANOID) GAME ********* //
// Author: Broly
// Contact : davb86@supereva.it
//
// Snippet made in May 2005 for the dream.in.code
// spring.this('05') contest
//
// ********************************************** //
// ******************* DESCRIPTION ************************ //
//
// This snippet create a complete arkanoid-style game,
// the levels are made with XML files, the brick can have different
// colors and resistance.
// The game is entirely generated
// in Actionscript, so it's quite light (2 kb).
// The graphic is very minimal.
//
// You can see an example of the game at
// http://www.brolyweb.com/Script/Brick/Brick_Alpha.html
// NOTE: This sample has only 2 levels.
//
// ******************************************************* //
// Attention: modifying the code you can cause
// some error. Modify with care :-p
// The parts you can/must modify for customize the game
// are signed
function brick(){
// Game field vars
gamefield_w = 300
stage_h = 400
panel_h = 40
// You can modify those vars for
// set the numbers of level (that must correspond to the .xml files, every level will have its .xml)
// and total lives.
total_levels = 2
lives = 3
// Graphic vars, you can modify for change the border
// width, alpha and color
border_w = 3
border_color = 0x000000
border_alpha = 100
// As before, but for the pad (you can also set pad width and height)
pad_border_w = 1
pad_border_color = 0x000000
pad_border_alpha = 100
pad_color = 0xFF0000
pad_alpha = 70
pad_w = 50
pad_h = 10
// The available field is smaller, because we
// leave some space between the pad (with the ball) and the bricks
// DON'T MODIFY
gamefield_h = stage_h - panel_h
available_field = gamefield_h - 100
// Those vars set the starting level and score
// You can modify them but it's recommended don't
currentlevel = 1
points = 0
// This var is needed by the game, don't modify ordelete
ini_lives = lives
// This function generate the gamefield (borders and panel)
// following the values we setted in the graphic vars
// The function create also the text fields
// for the panel (score, lives and level)
function generateGameField(){
createEmptyMovieClip('borderup',-1)
createEmptyMovieClip('bordersx',-2)
createEmptyMovieClip('panel',-102)
with(borderup){
lineStyle(border_w,border_color,border_alpha)
lineTo(gamefield_w,0)
}
with(bordersx){
lineStyle(border_w,border_color,border_alpha)
lineTo(0,gamefield_h)
}
with(panel){
lineStyle(border_w,0x000000,100)
beginFill(0x9999999,80)
lineTo(gamefield_w,0)
lineTo(gamefield_w,panel_h)
lineTo(0,panel_h)
lineTo(0,0)
endFill()
_y = gamefield_h
}
createTextField('score',-100,0,0,0,0)
createTextField('lev',-101,0,0,0,0)
createTextField('liv',-99,0,0,0,0)
score.autoSize = true
score.selectable = false
score.text = "Score : " + points
score._x = panel._x + 20
score._y = panel._y + panel._height/2 - score._height/2
lev.autoSize = true
lev.selectable = false
lev.text = "Level 1"
lev._x = panel._x + panel._width - lev._width - lev._width/2
lev._y = panel._y + panel._height/2 - lev._height/2
liv.autoSize = true
liv.text = "Lives left : " + lives
liv._x = panel._x + panel._width/2 - liv._width/2
liv._y = panel._y + panel._height/2 - liv._height/2
duplicateMovieClip(borderup,'borderbottom',-4)
duplicateMovieClip(bordersx,'borderdx',-5)
borderbottom._y = gamefield_h
borderdx._x = gamefield_w
}
// This function create the pad
// using the values we setted in the graphic vars for the pad
function createPad(){
createEmptyMovieClip('pad',1)
with(pad){
lineStyle(pad_border_w,pad_border_color,pad_border_alpha)
beginFill(pad_color,pad_alpha)
lineTo(pad_w,0)
lineTo(pad_w,pad_h)
lineTo(0,pad_h)
lineTo(0,0)
endFill()
_x = gamefield_w/2 - pad_w/2
_y = gamefield_h - (pad_h+10)
startDrag(this,false,_y,gamefield_w - pad_w,_y,0)
}
pad.onEnterFrame = function(){
ball._x = pad._x + pad_w/2
}
}
// This function will be called when the lives will be 0
function gameOver(){
createTextField('gover',getNextHighestDepth(),0,0,0,0,0)
gover.autoSize = true
gover.bold = true
gover.selectable = false
gover.text = "Sorry, game over." + newline + "Click for new game"
gover._x = gamefield_w/2-gover._width/2
gover._y = available_field/2 - gover._height/2
g = new Object()
g.onMouseDown = function(){
lives = ini_lives
liv.text = "Lives left: " + lives
currentlevel = 1
level(currentlevel)
newball()
delete this.onMouseDown
gover.removeTextField()
}
Mouse.addListener(g)
}
// This function will be called when all the brick
// in a level will be destroyed
function endLevel(){
createTextField('completed',getNextHighestDepth(),0,0,0,0,0)
completed.autoSize = true
completed.bold = true
completed.selectable = false
delete ball.onEnterFrame
if(currentlevel<total_levels){
completed.text = "Level " + currentlevel + " completed" + newline + "Click to start next level"
l = new Object()
l.onMouseDown = function(){
completed.removeTextField()
currentlevel++
level(currentlevel)
lev.text = "Level " + currentlevel
newball()
delete this.onMouseDown
Mouse.removeListener(l)
}
Mouse.addListener(l)
}else{
completed.text = "You won! Congratulations!"
}
completed._x = gamefield_w/2-completed._width/2
completed._y = available_field/2 - completed._height/2
}
// when the ball hit a brick, this function is called
// and check what bricks must be deleted
function removeBrick(who){
speed_y = -speed_y
points+= 100
score.text = "Score : " + points
who.res--
if(who.res == 0) {
who.removeMovieClip()
total_bricks--
if(total_bricks==0){
endLevel()
}
}
}
// This function create the ball
function createBall(){
radius = 4 // you can change this value for make the ball bigger or smaller, but is better leave it to 4
// Those lines create the ball movieclip
createEmptyMovieClip('ball',2)
with(ball){
lineStyle(0,0x000000,0)
beginFill(0x000000,100)
lineTo(0,radius)
curveTo(radius,radius, radius, 0)
curveTo(radius,-radius,0,-radius)
curveTo(-radius,-radius,-radius,0)
curveTo(-radius,radius,0,radius)
endFill()
// The ball is positioned over the pad
_x = pad._x + pad_w/2
_y = pad._y - _height/2
}
}
// We set a listener to the mouse so when the user
// click, the game begin
s = new Object()
s.onMouseDown = startgame
Mouse.addListener(s)
// This function let the game begin
function startgame(){
// We delete pad.onEnterFrame so the ball won't follow it
delete pad.onEnterFrame
// We remove the listener so the user can click without cause errors
Mouse.removeListener(s)
// Set speed_x and speed_y for the ball. You can change this values
speed_x = 8
speed_y = -7
// Set the ball actions. Don't modify this lines.
ball.onEnterFrame = function(){
// Move the ball
this._y = this._y + speed_y
this._x = this._x + speed_x
// If the ball it a border, bounce
this._x-this._width/2 <= bordersx._x || this._x+this._width>borderdx._x ? speed_x = -speed_x : null
this._y-this._height/2 < borderup._y ? speed_y = Math.abs(speed_y) : null
// If the ball fall, lose a live and start a newball
if(this._y > borderbottom._y) {
lives--
liv.text = "Lives left: " + lives
newball()
}
// Check what brick delete
colonna = int((this._x - brick_iniX) / brick_w)
riga = int((this._y - brick_iniY) / brick_h)
if(this._y < 300){
targetmc = eval("brick"+riga+"|"+colonna)
if(this._y>targetmc._y){
removeBrick(targetmc)
}
}
// Check if the ball hit the pad and where and make the ball bounce
if(pad.hitTest(this._x,this._y+(this._height/2)+3)){
if((this._x-pad._x<10 && this._x<pad._x+1) || (this._x - pad._x > pad._width/3&& this._x>pad._x+pad._width-5)){
speed_x = -speed_x
}
speed_y = -speed_y
}
}
}
// This function is called when the ball fasll
function newball(){
// Re-set the pad.onEnterFrame so the ball will follow it
// until the user will click
pad.onEnterFrame = function(){
ball._x = pad._x + pad_w/2
}
// Stop the ball
delete ball.onEnterFrame
// If the player have more than 0 lives, the game can continue
if(!lives == 0){
// Re-set the listener so when the player click the game begin
Mouse.addListener(s)
// Position the ball over the pad
ball._x = pad._x + pad_w/2
ball._y = pad._y - ball._height/2
}else{
// Otherwhise the game is over
gameOver()
}
}
// Load the info about a level
level_info = new XML()
level_info.ignoreWhite = true
level_info.onLoad = setLevelInfo
function level(n){
level_info.load('level'+n+'.xml')
}
// Put the info about the level into arrays
function setLevelInfo(){
bricks_type = []
brickinfos = this.firstChild.childNodes[0].childNodes
brick_w = Number(brickinfos[0].attributes.width)
brick_h = Number(brickinfos[0].attributes.height)
brick_iniY = Number(brickinfos[0].attributes.borderup)
brick_iniX = Number(brickinfos[0].attributes.bordersx)
trace(brick_w)
for(b=1;b<brickinfos.length;b++){
bricks_type[Number(brickinfos[b].attributes.id)] = new Array()
bricks_type[b]["res"] = brickinfos[b].attributes.res
bricks_type[b]["color"] = brickinfos[b].attributes.col
}
level_structure = this.firstChild.childNodes[1].childNodes
level_lines = new Array()
// Count how many lines of brick the level has
for(l=0;l<level_structure.length;l++){
// Put the structure of the line into an array
level_lines[l] = new Array()
level_lines[l] = level_structure[l].firstChild.toString().split("")
// Build the line
createLine(l)
}
}
// Set total_bricks to 0 (the level must be build yet
total_bricks = 0
// Create a line of bricks
function createLine(l){
xid = 0
for(cur=0;cur<level_lines[l].length;cur++){
if(level_lines[l][cur] != 0){
// Add one to the total_bricks var
total_bricks++
// Set the brick color
color = bricks_type[level_lines[l][cur]]["color"]
// Create and draw the brick
_root.createEmptyMovieClip('brick'+l+"|"+xid,getNextHighestDepth())
with(eval('brick'+l+"|"+xid)){
lineStyle(1,0x000000,100)
beginFill(color,100)
lineTo(brick_w,0)
lineTo(brick_w,brick_h)
lineTo(0,brick_h)
lineTo(0,0)
endFill()
// Position the brick
_x = brick_iniX + cur*20
_y = brick_iniY + l*brick_h
}
// Set the brick resistance
eval('brick'+l+"|"+xid).res = res = bricks_type[level_lines[l][cur]]["res"]
}
xid++
}
}
// Call the basic functions of the snippet
generateGameField()
createPad()
createBall()
level(currentlevel)
}
// USAGE
// Set the framerate to 30fps (or higher)
// Paste this code on the first frame
// Write brick() in the frame actions
// It's suggested to set the stage size
// to 300x200, but it's not obligatory
// EXAMPLE
brick()
This snippet made a Brick (aka Arkanoid) game, building the levels basing on XML files that set the bricks color, resistance and position into the stage. You can see a sample here: http://www.brolyweb.com/Script/Brick/Brick_Alpha.html
willcodeforfood/AWK more of it ( Other)
MORE AWK
HANDY ONE-LINERS FOR AWK 22 July 2003
compiled by Eric Pement <pemente@northpark.edu> version 0.22
Latest version of this file is usually at:
http://www.student.northpark.edu/pemente/awk/awk1line.txt
USAGE:
Unix: awk '/pattern/ {print "$1"}' # standard Unix shells
DOS/Win: awk '/pattern/ {print "$1"}' # okay for DJGPP compiled
awk "/pattern/ {print \"$1\"}" # required for Mingw32
Most of my experience comes from version of GNU awk (gawk) compiled for
Win32. Note in particular that DJGPP compilations permit the awk script
to follow Unix quoting syntax '/like/ {"this"}'. However, the user must
know that single quotes under DOS/Windows do not protect the redirection
arrows (<, >) nor do they protect pipes (|). Both are special symbols
for the DOS/CMD command shell and their special meaning is ignored only
if they are placed within "double quotes." Likewise, DOS/Win users must
remember that the percent sign (%) is used to mark DOS/Win environment
variables, so it must be doubled (%%) to yield a single percent sign
visible to awk.
If I am sure that a script will NOT need to be quoted in Unix, DOS, or
CMD, then I normally omit the quote marks. If an example is peculiar to
GNU awk, the command 'gawk' will be used. Please notify me if you find
errors or new commands to add to this list (total length under 65
characters). I usually try to put the shortest script first.
FILE SPACING:
# double space a file
awk '1;{print ""}'
awk 'BEGIN{ORS="\n\n"};1'
# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
# NOTE: On Unix systems, DOS lines which have only CRLF (
) are
# often treated as non-blank, and thus 'NF' alone will return TRUE.
awk 'NF{print $0 "\n"}'
# triple space a file
awk '1;{print "\n"}'
NUMBERING AND CALCULATIONS:
# precede each line by its line number FOR THAT FILE (left alignment).
# Using a tab (\t) instead of space will preserve margins.
awk '{print FNR "\t" $0}' files*
# precede each line by its line number FOR ALL FILES TOGETHER, with tab.
awk '{print NR "\t" $0}' files*
# number each line of a file (number on left, right-aligned)
# Double the percent signs if typing from the DOS command prompt.
awk '{printf("%5d : %s\n", NR,$0)}'
# number each line of file, but only print numbers if line is not blank
# Remember caveats about Unix treatment of \r (mentioned above)
awk 'NF{$0=++a " :" $0};{print}'
awk '{print (NF? ++a " :" :"") $0}'
# count lines (emulates "wc -l")
awk 'END{print NR}'
# print the sums of the fields of every line
awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'
# add all fields in all lines and print the sum
awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'
# print every line after replacing each field with its absolute value
awk '{for (i=1; i<=NF; i++) if ($i < 0) $i = -$i; print }'
awk '{for (i=1; i<=NF; i++) $i = ($i < 0) ? -$i : $i; print }'
# print the total number of fields ("words") in all lines
awk '{ total = total + NF }; END {print total}' file
# print the total number of lines that contain "Beth"
awk '/Beth/{n++}; END {print n+0}' file
# print the largest first field and the line that contains it
# Intended for finding the longest string in field #1
awk '$1 > max {max=$1; maxline=$0}; END{ print max, maxline}'
# print the number of fields in each line, followed by the line
awk '{ print NF ":" $0 } '
# print the last field of each line
awk '{ print $NF }'
# print the last field of the last line
awk '{ field = $NF }; END{ print field }'
# print every line with more than 4 fields
awk 'NF > 4'
# print every line where the value of the last field is > 4
awk '$NF > 4'
TEXT CONVERSION AND SUBSTITUTION:
# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
awk '{sub(/\r$/,"");print}' # assumes EACH line ends with Ctrl-M
# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
awk '{sub(/$/,"\r");print}
# IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
awk 1
# IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
# Cannot be done with DOS versions of awk, other than gawk:
gawk -v BINMODE="w" '1' infile >outfile
# Use "tr" instead.
tr -d \r <infile >outfile # GNU tr version 1.22 or higher
# delete leading whitespace (spaces, tabs) from front of each line
# aligns all text flush left
awk '{sub(/^[ \t]+/, ""); print}'
# delete trailing whitespace (spaces, tabs) from end of each line
awk '{sub(/[ \t]+$/, "");print}'
# delete BOTH leading and trailing whitespace from each line
awk '{gsub(/^[ \t]+|[ \t]+$/,"");print}'
awk '{$1=$1;print}' # also removes extra space between fields
# insert 5 blank spaces at beginning of each line (make page offset)
awk '{sub(/^/, " ");print}'
# align all text flush right on a 79-column width
awk '{printf "%79s\n", $0}' file*
# center all text on a 79-character width
awk '{l=length();s=int((79-l)/2); printf "%"(s+l)"s\n",$0}' file*
# substitute (find and replace) "foo" with "bar" on each line
awk '{sub(/foo/,"bar");print}' # replaces only 1st instance
gawk '{$0=gensub(/foo/,"bar",4);print}' # replaces only 4th instance
awk '{gsub(/foo/,"bar");print}' # replaces ALL instances in a line
# substitute "foo" with "bar" ONLY for lines which contain "baz"
awk '/baz/{gsub(/foo/, "bar")};{print}'
# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
awk '!/baz/{gsub(/foo/, "bar")};{print}'
# change "scarlet" or "ruby" or "puce" to "red"
awk '{gsub(/scarlet|ruby|puce/, "red"); print}'
# reverse order of lines (emulates "tac")
awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
# if a line ends with a backslash, append the next line to it
# (fails if there are multiple lines ending with backslash...)
awk '/\\$/ {sub(/\\$/,""); getline t; print $0 t; next}; 1' file*
# print and sort the login names of all users
awk -F ":" '{ print $1 | "sort" }' /etc/passwd
# print the first 2 fields, in opposite order, of every line
awk '{print $2, $1}' file
# switch the first 2 fields of every line
awk '{temp = $1; $1 = $2; $2 = temp}' file
# print every line, deleting the second field of that line
awk '{ $2 = ""; print }'
# print in reverse order the fields of every line
awk '{for (i=NF; i>0; i--) printf("%s ",i);printf ("\n")}' file
# remove duplicate, consecutive lines (emulates "uniq")
awk 'a !~ $0; {a=$0}'
# remove duplicate, nonconsecutive lines
awk '! a[$0]++' # most concise script
awk '!($0 in a) {a[$0];print}' # most efficient script
# concatenate every 5 lines of input, using a comma separator
# between fields
awk 'ORS=NR%5?",":"\n"' file
SELECTIVE PRINTING OF CERTAIN LINES:
# print first 10 lines of file (emulates behavior of "head")
awk 'NR < 11'
# print first line of file (emulates "head -1")
awk 'NR>1{exit};1'
# print the last 2 lines of a file (emulates "tail -2")
awk '{y=x "\n" $0; x=$0};END{print y}'
# print the last line of a file (emulates "tail -1")
awk 'END{print}'
# print only lines which match regular expression (emulates "grep")
awk '/regex/'
# print only lines which do NOT match regex (emulates "grep -v")
awk '!/regex/'
# print the line immediately before a regex, but not the line
# containing the regex
awk '/regex/{print x};{x=$0}'
awk '/regex/{print (x=="" ? "match on line 1" : x)};{x=$0}'
# print the line immediately after a regex, but not the line
# containing the regex
awk '/regex/{getline;print}'
# grep for AAA and BBB and CCC (in any order)
awk '/AAA/; /BBB/; /CCC/'
# grep for AAA and BBB and CCC (in that order)
awk '/AAA.*BBB.*CCC/'
# print only lines of 65 characters or longer
awk 'length > 64'
# print only lines of less than 65 characters
awk 'length < 64'
# print section of file from regular expression to end of file
awk '/regex/,0'
awk '/regex/,EOF'
# print section of file based on line numbers (lines 8-12, inclusive)
awk 'NR==8,NR==12'
# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}' # more efficient on large files
# print section of file between two regular expressions (inclusive)
awk '/Iowa/,/Montana/' # case sensitive
SELECTIVE DELETION OF CERTAIN LINES:
# delete ALL blank lines from a file (same as "grep '.' ")
awk NF
awk '/./'
CREDITS AND THANKS:
Special thanks to Peter S. Tillier for helping me with the first release
of this FAQ file.
For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult:
"sed & awk, 2nd Edition," by Dale Dougherty and Arnold Robbins
O'Reilly, 1997
"UNIX Text Processing," by Dale Dougherty and Tim O'Reilly
Hayden Books, 1987
"Effective awk Programming, 3rd Edition." by Arnold Robbins
O'Reilly, 2001
To fully exploit the power of awk, one must understand "regular
expressions." For detailed discussion of regular expressions, see
"Mastering Regular Expressions, 2d edition" by Jeffrey Friedl
(O'Reilly, 2002).
The manual ("man") pages on Unix systems may be helpful (try "man awk",
"man nawk", "man regexp", or the section on regular expressions in "man
ed"), but man pages are notoriously difficult. They are not written to
teach awk use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.
USE OF '\t' IN awk SCRIPTS: For clarity in documentation, we have used
the expression '\t' to indicate a tab character (0x09) in the scripts.
All versions of awk, even the UNIX System 7 version should recognize
the '\t' abbreviation.
#---end of file---
http://snippets.dzone.com/posts/show/4893
max302/Image Rotation ( PHP)
<?php
/*
AUTOMATIC IMAGE ROTATOR
Version 2.2 - December 4, 2003
Copyright (c) 2002-2003 Dan P. Benjamin, Automatic, Ltd.
All Rights Reserved.
http://www.hiveware.com/imagerotator.php
http://www.automaticlabs.com/
DISCLAIMER
Automatic, Ltd. makes no representations or warranties about
the suitability of the software, either express or
implied, including but not limited to the implied
warranties of merchantability, fitness for a particular
purpose, or non-infringement. Dan P. Benjamin and Automatic, Ltd.
shall not be liable for any damages suffered by licensee
as a result of using, modifying or distributing this
software or its derivatives.
ABOUT
This PHP script will randomly select an image file from a
folder of images on your webserver. You can then link to it
as you would any standard image file and you'll see a random
image each time you reload.
When you want to add or remove images from the rotation-pool,
just add or remove them from the image rotation folder.
VERSION CHANGES
Version 1.0
- Release version
Version 1.5
- Tweaked a few boring bugs
Version 2.0
- Complete rewrite from the ground-up
- Made it clearer where to make modifications
- Made it easier to specify/change the rotation-folder
- Made it easier to specify/change supported image types
- Wrote better instructions and info (you're them reading now)
- Significant speed improvements
- More error checking
- Cleaner code (albeit more PHP-specific)
- Better/faster random number generation and file-type parsing
- Added a feature where the image to display can be specified
- Added a cool feature where, if an error occurs (such as no
images being found in the specified folder) *and* you're
lucky enough to have the GD libraries compiled into PHP on
your webserver, we generate a replacement "error image" on
the fly.
Version 2.1
- Updated a potential security flaw when value-matching
filenames
Version 2.2
- Updated a few more potential security issues
- Optimized the code a bit.
- Expanded the doc for adding new mime/image types.
Thanks to faithful ALA reader Justin Greer for
lots of good tips and solid code contribution!
INSTRUCTIONS
1. Modify the $folder setting in the configuration section below.
2. Add image types if needed (most users can ignore that part).
3. Upload this file (rotate.php) to your webserver. I recommend
uploading it to the same folder as your images.
4. Link to the file as you would any normal image file, like this:
<img src="http://example.com/rotate.php">
5. You can also specify the image to display like this:
<img src="http://example.com/rotate.php?img=gorilla.jpg">
This would specify that an image named "gorilla.jpg" located
in the image-rotation folder should be displayed.
That's it, you're done.
*/
/* ------------------------- CONFIGURATION -----------------------
Set $folder to the full path to the location of your images.
For example: $folder = '/user/me/example.com/images/';
If the rotate.php file will be in the same folder as your
images then you should leave it set to $folder = '.';
*/
$folder = '.';
/*
Most users can safely ignore this part. If you're a programmer,
keep reading, if not, you're done. Go get some coffee.
If you'd like to enable additional image types other than
gif, jpg, and png, add a duplicate line to the section below
for the new image type.
Add the new file-type, single-quoted, inside brackets.
Add the mime-type to be sent to the browser, also single-quoted,
after the equal sign.
For example:
PDF Files:
$extList['pdf'] = 'application/pdf';
CSS Files:
$extList['css'] = 'text/css';
You can even serve up random HTML files:
$extList['html'] = 'text/html';
$extList['htm'] = 'text/html';
Just be sure your mime-type definition is correct!
*/
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
// You don't need to edit anything after this point.
// --------------------- END CONFIGURATION -----------------------
$img = null;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
A nice image rotating script. I'm setting it up to rotate images on my wordpress. This script was written by Dan P. Benjamin.