Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Mario Orlandi

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS 

Packing ZODB from command line

Packing ZODB from command line

$wget.exe --delete-after --user=admin --password=***** "http://localhost:8090/Control_Panel/manage_pack?days:float=0"


or

"D:\services\support\curl-7.17.0\curl" -d -v -f -u admin:password http://localhost:8090/Control_Panel/manage_pack?days:float=0

send django queries to OutputDebugString (Win32)

Modify django/db/backends/util.py as follows:

import win32api

class CursorDebugWrapper(object):
    def __init__(self, cursor, db):
        self.cursor = cursor
        self.db = db # Instance of a BaseDatabaseWrapper subclass

    def debug_trace(self,category,message):
        win32api.OutputDebugString('|django              |%s|%s\n' % (category,message))

    def trace_entry (self, sql, elapsed): 
        self.debug_trace('Q',sql)
        if elapsed >= 0.01:
            self.debug_trace(' ','elapsed: %.3f' % elapsed)

    def execute(self, sql, params=()):
        start = time()
        try:
            return self.cursor.execute(sql, params)
        finally:
            stop = time()
            sql = self.db.ops.last_executed_query(self.cursor, sql, params)
            self.db.queries.append({
                'sql': sql,
                'time': "%.3f" % (stop - start),
            })
            self.trace_entry(sql, stop - start) 

    def executemany(self, sql, param_list):
        start = time()
        try:
            return self.cursor.executemany(sql, param_list)
        finally:
            stop = time()
            self.db.queries.append({
                'sql': '%s times: %s' % (len(param_list), sql),
                'time': "%.3f" % (stop - start),
            })
            self.trace_entry(sql, stop - start) 


Fill combobox with enum values

public enum CardDataType
{
    Unknown,
    Raw,
    RowChp
}

ctlDataType.DataSource = Enum.GetValues(typeof(CardDataType));
ctlDataType.SelectedItem = CardDataType.Unknown;

...
...
string strType = ctlDataType.SelectedItem.ToString();

or

CardDataType dataType;
string strDataType = "Raw";
dataType = (CardDataType)Enum.Parse(typeof(CardDataType), strDataType, true);

and eventually

ctlDataType.SelectedItem = dataType; 

// a volte da' problemi in fase di inizializzazione della UI;
// in questi casi si puo' ricorrere a Enum.GetNames()
foreach ( string name in Enum.GetNames(typeof(CardDataType)) ) 
{
    ctlDataType.Items.Add(name);
}

...

string strDataType = "Raw";
ctlDataType.SelectedItem = strDataType; 

IPython shell

// "%PYTHON%" -i -c ..."
from Zope2 import configure; 
import os; 
configure(os.environ['ZOPE_CONFIG_FILE']); 

import Zope2; 
app=Zope2.app(); 

ns={'__name__':'blah','app':app};

import IPython; 
IPython.Shell.IPShell(user_ns=ns).mainloop(sys_exit=1);

review_state

// retrieve review state
from Products.CMFCore.utils import getToolByName
wtool = getToolByName(context, "portal_workflow")
wf_state = wtool.getInfoFor(obj,'review_state',None)

object_delete

// object_delete
from AccessControl import Unauthorized
from Products.CMFPlone.utils import transaction_note
from Products.CMFPlone import PloneMessageFactory as _

REQUEST = context.REQUEST
if REQUEST.get('REQUEST_METHOD', 'GET').upper() == 'GET':
    raise Unauthorized, 'This method can not be accessed using a GET request'

parent = context.aq_inner.aq_parent
parent.manage_delObjects(context.getId())

message = _(u'${title} has been deleted.',
            mapping={u'title' : context.title_or_id()})
transaction_note('Deleted %s' % context.absolute_url())

context.plone_utils.addPortalMessage(message)
return state.set(status = 'success')

ArrayList

using System.Collections;

ArrayList arrList = new ArrayList();

arrList.Add("one");
arrList.Add("two");
arrList.Add("three");

string[] strArray = arrList.ToArray(Type.GetType("System.String")) as string[];
return strArray;
       

autoscroll text

    textBox1.SelectionStart = textBox1.Text.Length;
    textBox1.SelectionLength = 0;
    textBox1.ScrollToCaret();    

Abilitazione accesso remoto per PostgreSQL

// in "pg_hba.conf"
host    all         all         192.168.98.0/24       md5

// in "postgresql.conf"
listen_addresses = '*'		# what IP address(es) to listen on; 

Result Object Methods

// Assuming that we have set result to being a result object we can use the following methods:

len(result)
     this will show the number rows returned (which would be 3 in the example above).

result.names()
    a list of all the column headings, returning a list containing emp_id, first, last and salary

result.tuples()
    returns a list of tuples in our example:

    [(43, 'Bob', 'Roberts', 50000),
     (101, 'Cheeta', 'leCat', 100000),
     (99, 'Jane', 'Junglewoman', 100001)]

result.dictionaries()
    will return a list of dictionaries, with one dictionary for each row:

    [{'emp_id': 42, 'first': 'Bob','last': 'Roberts', 'salary': 50000},
     {'emp_id': 101, 'first: 'Cheeta', 'last': 'leCat', 'salary': 100000},
     {'emp_id': 99, 'first': 'Jane', 'last': 'Junglewoman', 'salary': 100001}]

result.data_dictionary()
    returns a dictionary describing the structure of the results table. 

The dictionary has the key name, type, null and width. 
Name and type are self explanatory, null is true if that field may contain a null value and width is the width in characters of the field. 
Note that null and width may not be set by some Database Adapters.

result.asRDB()
    displays the result in a similar way to a relational database. 

The DTML below displays the result below:
    <pre>
      <dtml-var "list_all_employees().asRDB()">
    </pre>

    ... displays ...

    emp_id first last salary
    42 Bob Roberts 50000
    101 Cheeta leCat 100000
    99 Jane Junglewoman 100001

result[0][1]
    return row 0, column 1 of the result, bob in this example. 

Be careful using this method as changes in the schema will cause unexpected results. 
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS