Sign up to create your own snipts, or login.

Public snipts » Fotinakis's snipts The latest snipts from Fotinakis.

showing 1-20 of 23 snipts
  • Dynamic Django mod_wsgi hook files
    # --- django.wsgi - in any project
    from some_common_module import wsgi_helper
    application = wsgi_helper.setup(__file__)
    
    
    # --- wsgi_helper.py - in some_common_module
    import os, sys
    import django.core.handlers.wsgi
    
    def setup(filename):
    	project_root = os.sep.join(filename.split(os.sep)[:-2])
    	project_dir = None
    	
    	for path in os.listdir(project_root):
    		# Find each dir off the root, and check it for settings.py
    	
    		path = os.path.join(project_root, path)
    	
    		if os.path.isdir(path):
    			file = "".join([path, os.sep, "settings.py"])
    			if os.path.exists(file):
    				# We have found /project_name/settings.py
    				project_dir = path
    				os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % path.split(os.sep)[-1]
    	
    	if not project_dir:
    		raise Exception("Could not find project settings file! Checked path: %s" % path)
    	
    	if project_root not in sys.path: sys.path.insert(0, project_root)
    	if project_dir not in sys.path: sys.path.insert(0, project_dir)
    
    	return django.core.handlers.wsgi.WSGIHandler()
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Feb 26, 2010 at 6:39 p.m. EST
  • Drop all tables and constraints within an Oracle schema
    BEGIN
    FOR c IN (SELECT table_name FROM user_tables) LOOP
    EXECUTE IMMEDIATE ('DROP TABLE ' || c.table_name || ' CASCADE CONSTRAINTS');
    END LOOP;
    END;
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jan 29, 2010 at 5:22 p.m. EST
  • Output PostgreSQL command as CSV
    psql -F\; -A --pset footer -f input_file.sql -o output_file.csv database_name
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Nov 10, 2009 at 4:04 p.m. EST
  • Tokenize a string in C++
    #include <string>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    #include <vector>
    using namespace std;
    
    int main() {
    	string sentence = "All of this has happened before...";
    	
    	vector<string> tokens;
    	istringstream iss(sentence);
    	copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(tokens));
    }
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Sep 13, 2009 at 7:34 p.m. EDT
  • Quick find a manufacturer's OUI
    grep -i foundry /usr/share/nmap/nmap-mac-prefixes
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 20, 2009 at 11:43 a.m. EDT
  • Mount SSH volume on Mac with sshfs
    # With sshfs installed:
    
    MOUNTPOINT=/Volumes/mountdir
    REMOTE=user@hostname:/home/dir
    OPTIONS=-oping_diskarb,volname=mountdir
    TESTHOST=hostname
    #test if sshfs already mounted
    if ! [ -e $MOUNTPOINT ]
    then
            #test if connected to internet
            if ! [ -z "`ping -c 1 $TESTHOST 2>/dev/null | grep "time="`" ]
            then
                    mkdir $MOUNTPOINT
                    sshfs $REMOTE $MOUNTPOINT $OPTIONS
                    echo "$REMOTE mounted on $MOUNTPOINT"
            else
                    echo "Network down, unable to mount $REMOTE"
            fi
    fi
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 18, 2009 at 6:59 p.m. EDT
  • Change SSH port on OS X
    # Add a service on an unused port in:
    sudo vim /etc/services
    
    # Change the string "ssh" below "SockServiceName" to whatever name used in the above file
    sudo vim /System/Library/LaunchDaemons/ssh.plist
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 18, 2009 at 6:14 p.m. EDT
  • Change Active Directory password via LDAP modify call
    #!/usr/bin/python
    
    import ldap
    
    host = 'ldaps://ldap.example.com:636'
    
    con = ldap.initialize(host)
    con.set_option( ldap.OPT_X_TLS_DEMAND, True )
    con.set_option( ldap.OPT_DEBUG_LEVEL, 255 )
    
    # Encode the password in UTF-16 Little Endian
    #
    # ASCII "new":     0x6E 0x65 0x77
    # UTF-16 "new":    0x6E 0x00 0x65 0x00 0x77 0x00
    # UTF-16 "new"
    #     with quotes: 0x22 0x00 0x6E 0x00 0x65 0x00 0x77 0x00 0x22 0x00
    #
    # http://msdn.microsoft.com/en-us/library/cc200469%28PROT.10%29.aspx
    #
    # NOTE: The article says to BER encode the password octet stream before
    # sending for change, but doing so causes the server to give its standard
    # "will not perform" error on password change. So, no BER encoding is done here.
    username = 'someUser'
    new_pass = 'ne$wP4assw0rd3!'
    new_password = ('"%s"' % new_pass).encode("utf-16-le")
    
    try:
    	con.simple_bind_s( "admin@ldap.example.com", "password" )
    	
    	# For some reason, two MOD_REPLACE calls are necessary to change the password.
    	# If only one call is performed, both the old and new password will work.
    	mod_attrs = [( ldap.MOD_REPLACE, 'unicodePwd', new_password)],( ldap.MOD_REPLACE, 'unicodePwd', new_password)]
    	con.modify_s('CN=%s,OU=Users,DC=ldap,DC=example,DC=com' % username, mod_attrs)
    except:
    	raise
    else:
    	print "Successfully changed password."
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 03, 2009 at 4:56 p.m. EDT
  • Make copy and transfer entire PostgreSQL DB
    pg_dump -d prod_db -U prod_db -h localhost > /tmp/transferdump.sql
    
    psql -U prod_db_user -h localhost -t -d other_db -c "SELECT 'DROP TABLE ' || n.nspname || '.' ||
    c.relname || ' CASCADE;' FROM pg_catalog.pg_class AS c LEFT JOIN
    pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE relkind =
    'r' AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
    pg_catalog.pg_table_is_visible(c.oid)" >/tmp/dropothertables.sql;
    
    psql -d other_db -h localhost -U other_db_user < /tmp/dropothertables.sql;
    psql -d other_db -h localhost -U other_db_user < /tmp/transferdump.sql
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 28, 2009 at 6:15 p.m. EDT
  • Disassembler for Python bytecode
    $ python -m dis test.py 
      1           0 LOAD_CONST               0 ('Hello world')
                  3 PRINT_ITEM          
                  4 PRINT_NEWLINE       
                  5 LOAD_CONST               1 (None)
                  8 RETURN_VALUE        
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 14, 2009 at 1:50 a.m. EDT
  • Bash—please save my history for ever and eternity (or, at least a really long time)
    # In .bashrc or .bash_profile
    export HISTSIZE=2048
    export HISTFILESIZE=1048576
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 02, 2009 at 6:33 p.m. EDT
  • Dynamic directories in Django settings.py
    # In settings.py
    PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
    ROOT_DIR = os.path.split(PROJECT_DIR)[0]
    
    
    MEDIA_ROOT = ROOT_DIR + '/static/'
    MEDIA_URL = '/static/'
    
    TEMPLATE_DIRS = (
    	# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    	# Always use forward slashes, even on Windows.
    	# Don't forget to use absolute paths, not relative paths.
    	PROJECT_DIR + '/templates/',
    )
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 29, 2009 at 5:51 p.m. EDT
  • Simple generation of random string in Python
    import string
    import random
    
    print "".join(random.sample(string.letters+string.digits, 8))
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 18, 2009 at 1:14 p.m. EDT
  • Install VMWare Tools on Debian
    # Make sure you have contrib and non-free in /etc/apt/sources.list
    # Then:
    
    apt-get install module-assistant
    m-a a-i open-vm
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 15, 2009 at 1:21 p.m. EDT
  • Change Linux hostname without reboot
    vim /etc/hostname
    vim /etc/hosts
    hostname new-hostname
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 15, 2009 at 1:18 p.m. EDT
  • Change initial page state based on location.hash
    $(function() {
    	// Hash state determination
    	if (location.hash && location.hash != "") {
    		$('a[href$="'+location.hash+'"]').click();
    	}
    });
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on May 18, 2009 at 4:25 p.m. EDT
  • Django template tag for dynamic attribute lookups
    import re
    from django import template
    from django.conf import settings
    
    numeric_test = re.compile("^\d+$")
    register = template.Library()
    
    def getattribute(value, arg):
    	"""Gets an attribute of an object dynamically from a string name"""
    	
    	if hasattr(value, str(arg)):
    		return getattr(value, arg)
    	elif hasattr(value, 'has_key') and value.has_key(arg):
    		return value[arg]
    	elif numeric_test.match(str(arg)) and len(value) > int(arg):
    		return value[int(arg)]
    	else:
    		return settings.TEMPLATE_STRING_IF_INVALID
    
    register.filter('getattribute', getattribute)
    
    # Then, in template:
    # {% load getattribute %}
    # {{ object|getattribute:dynamic_string_var }}
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on May 11, 2009 at 6:32 p.m. EDT
  • Drop all tables from PostgreSQL DB without superuser
    psql -t -d my_dbname -c "SELECT 'DROP TABLE ' || n.nspname || '.' ||
    c.relname || ' CASCADE;' FROM pg_catalog.pg_class AS c LEFT JOIN
    pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE relkind =
    'r' AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
    pg_catalog.pg_table_is_visible(c.oid)" >/tmp/droptables
    
    psql -d my_dbname -f /tmp/droptables
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Apr 28, 2009 at 12:09 p.m. EDT
  • Grant all permissions on PostgreSQL DB
    ER="$2"
    PSQL="psql -q -n -A -t"
    SCHEMES="'public'"
    
    if [ -z "$1" ]; then
            echo "Something like: ./grant mydatabase myuser | psql mydatabase"
            exit
    fi
    
    if [ -z "$2" ]; then
            USER="$1"
    fi
    echo "-- Granting rights on $DB to $USER ($SCHEMES)"
    # tables
    Q="select 'grant all on '||schemaname||'.'||tablename||' to \\\"$USER\\\";' from pg_tables where schemaname in ($SCHEMES);"
    $PSQL -c "$Q" "$DB";
    
    # views
    Q="select 'grant all on '||schemaname||'.'||viewname||' to \\\"$USER\\\";' from pg_views where schemaname in ($SCHEMES);"
    $PSQL -c "$Q" "$DB";
    
    # sequences
    Q="select 'grant all on function '||n.nspname||'.'||p.proname||'('||oidvectortypes(p.proargtypes)||') to \\\"$USER\\\";' from pg_proc p, pg_namespace n where n.oid = p.pronamespace and n.nspname in ($SCHEMES);"
    $PSQL -c "$Q" "$DB";
    
    # functions
    Q="select 'grant all on '||n.nspname||'.'||c.relname||' to \\\"$USER\\\";' from pg_class c, pg_namespace n where n.oid = c.relnamespace and c.relkind IN ('S') and n.nspname in ($SCHEMES);"
    $PSQL -c "$Q" "$DB";
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Apr 28, 2009 at 12:05 p.m. EDT
  • Protect Apache directory with LDAP credentials
    # sudo a2enmod authnz_ldap
    
    SSLRequireSSL
    AuthType Basic
    AuthName "Authentication"
    AuthBasicProvider ldap
    AuthLDAPBindDN name@example.com
    AuthLDAPBindPassword password
    AuthLDAPURL ldaps://host:port/ou=MainOU,dc=example,dc=com?sAMAccountName?sub?(objectClass=*)
    AuthzLDAPAuthoritative off
    Require valid-user
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Apr 28, 2009 at 11:51 a.m. EDT
Sign up to create your own snipts, or login.