quinta-feira, 26 de julho de 2012

Python Script to get the lastest chromium snapshot

# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 18:08:13 2012

@author: killown
"""

import urllib
import os, pwd
import os.path
import urllib2
import shutil
import zipfile



chromium_browser = """#!/bin/sh

# Chromium launcher

# Authors:
# Fabien Tassin
# License: GPLv2 or later

APPNAME=chrome
LIBDIR=~/.chromium-browser
GDB=/usr/bin/gdb
BUILD_DIST="Ubuntu 12.04"

usage () {
echo "$APPNAME [-h|--help] [-g|--debug] [--temp-profile] [options] [URL]"
echo
echo " -g or --debug Start within $GDB"
echo " -h or --help This help screen"
echo " --temp-profile Start with a new and temporary profile"
echo
echo " Other supported options are:"
MANWIDTH=80 man chromium-browser | sed -e '1,/OPTIONS/d; /ENVIRONMENT/,$d'
echo " See 'man chromium-browser' for more details"
}

if [ -f /etc/$APPNAME/default ] ; then
. /etc/$APPNAME/default
fi

# Prefer user defined CHROMIUM_USER_FLAGS (fron env) over system
# default CHROMIUM_FLAGS (from /etc/$APPNAME/default)
CHROMIUM_FLAGS=${CHROMIUM_USER_FLAGS:-"$CHROMIUM_FLAGS"}

# FFmpeg needs to know where its libs are located
if [ "Z$LD_LIBRARY_PATH" != Z ] ; then
LD_LIBRARY_PATH=$LIBDIR:$LD_LIBRARY_PATH
else
LD_LIBRARY_PATH=$LIBDIR
fi

export LD_LIBRARY_PATH

# For the Default Browser detection to work, we need to give access
# to xdg-settings if it's not present on the system (ensures that the system
# xdg-utils is recent enough). Also set CHROME_WRAPPER in case xdg-settings is
# not able to do anything useful
if [ ! -e /usr/bin/xdg-settings ] ; then
export PATH="$LIBDIR:$PATH"
fi
export CHROME_WRAPPER="`readlink -f "$0"`"
export CHROME_DESKTOP=$APPNAME.desktop

# lsb_release is slow so try to source the static file /etc/lsb-release
# instead, and fallback to lsb_release if we didn't get the information we need
if [ -e /etc/lsb-release ] ; then
. /etc/lsb-release
fi
DIST=${DISTRIB_ID:-"`lsb_release -si`"}
RELEASE=${DISTRIB_RELEASE:-"`lsb_release -sr`"}

# Set CHROME_VERSION_EXTRA visible in the About dialog and in about:version
if [ "$DIST $RELEASE" = "$BUILD_DIST" ] ; then
export CHROME_VERSION_EXTRA="$DIST $RELEASE"
else
export CHROME_VERSION_EXTRA="Built on $BUILD_DIST, running on $DIST $RELEASE"
fi

want_debug=0
want_temp_profile=0
while [ $# -gt 0 ]; do
case "$1" in
-h | --help | -help )
usage
exit 0 ;;
-g | --debug )
want_debug=1
shift ;;
--temp-profile )
want_temp_profile=1
shift ;;
-- ) # Stop option prcessing
shift
break ;;
* )
break ;;
esac
done

if [ $want_temp_profile -eq 1 ] ; then
TEMP_PROFILE=`mktemp -d`
CHROMIUM_FLAGS="$CHROMIUM_FLAGS --user-data-dir=$TEMP_PROFILE"
fi

if [ $want_debug -eq 1 ] ; then
if [ ! -x $GDB ] ; then
echo "Sorry, can't find usable $GDB. Please install it."
exit 1
fi
tmpfile=`mktemp /tmp/chromiumargs.XXXXXX` || { echo "Cannot create temporary file" >&2; exit 1; }
trap " [ -f \"$tmpfile\" ] && /bin/rm -f -- \"$tmpfile\"" 0 1 2 3 13 15
echo "set args $CHROMIUM_FLAGS ${1+"$@"}" > $tmpfile
echo "# Env:"
echo "# LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
echo "# PATH=$PATH"
echo "# GTK_PATH=$GTK_PATH"
echo "# CHROMIUM_USER_FLAGS=$CHROMIUM_USER_FLAGS"
echo "# CHROMIUM_FLAGS=$CHROMIUM_FLAGS"
echo "$GDB $LIBDIR/$APPNAME -x $tmpfile"
$GDB "$LIBDIR/$APPNAME" -x $tmpfile
if [ $want_temp_profile -eq 1 ] ; then
rm -rf $TEMP_PROFILE
fi
exit $?
else
if [ $want_temp_profile -eq 0 ] ; then
exec $LIBDIR/$APPNAME $CHROMIUM_FLAGS "$@"
else
# we can't exec here as we need to clean-up the temporary profile
$LIBDIR/$APPNAME $CHROMIUM_FLAGS "$@"
rm -rf $TEMP_PROFILE
fi
fi
"""

def download(link):
url = link

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break

file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,

f.close()


url = "".join( urllib.urlopen("http://commondatastorage.googleapis.com/chromium-browser-snapshots/Linux_x64/LAST_CHANGE") )

userpath = pwd.getpwuid(os.getuid()).pw_dir

fulluserpath = os.path.join(userpath,".config/chromium-check")

current = "".join(open(fulluserpath))




def get_chromium():
print "New version available"
print "Downloading"
download("http://commondatastorage.googleapis.com/chromium-browser-snapshots/Linux_x64/"+ url + "/chrome-linux.zip")
chromium_path = os.path.join(userpath,".chromium-browser/")
chromium_file = os.path.join(userpath,"chrome-linux.zip")
chromium_move = os.path.join(chromium_path + "chrome-linux/")
chromium_exec = os.path.join(chromium_path,"chrome")
shutil.rmtree(chromium_path)
os.makedirs(chromium_path)

file_zip = zipfile.ZipFile(chromium_file, 'r')
file_zip.extractall(chromium_path)
file_zip.close()

files = os.listdir(chromium_move)

for i in files:
src = chromium_move + i
dst = chromium_path
shutil.move(src, dst)

os.chmod(chromium_exec, 0755)


if int(url) > int(current):
get_chromium()
cc = open(fulluserpath,"w")
cc.write(url)
cc.close()

else:
print "You're already using the lastest revision"

if not os.path.isfile("/usr/bin/chromium-browser"):
print chromium_browser
print "Copy/Paste the output above into /usr/bin/chromium-browser and make it chmod executable +x"

if not os.path.isfile(fulluserpath):
get_chromium()
cc = open(fulluserpath,"w")
cc.write(url)
cc.close()


Agistech.com.br

quinta-feira, 24 de maio de 2012

ffmpeg - convertendo vídeos para webm

ffmpeg -i videofinal.mkv -codec:v libvpx -quality good -cpu-used 0 -b:v 1200k -threads 4 videofinal.webm

Agistech.com.br

ffmpeg - screencast

ffmpeg -f alsa -ac 2 -i pulse -f x11grab -s hd1080 -r 60 -i :0.0 -vcodec libx264 -preset ultrafast -an -y video.mkv -acodec pcm_s16le -b:a 48000k -loglevel quiet -vn -y audio.mkv
Agistech.com.br

sábado, 3 de março de 2012

Sobre o Problema Da Soma De Sub-Ítens Do noskleta

Referente ao post do nosklo http://pythonlog.wordpress.com/2010/01/19/problema-da-soma-de-sub-itens/ O código a seguir consegue executar todos os testes de dados_teste.txt em menos de 2 segundos em um processador x4 955 overclock 4ghz
from itertools import chain, combinations
       
itens = range(-2000, 1, 1) + range(1,10, 3)
a = sorted([i for i in itens if i > 0], reverse=True)
b =  sorted([i for i in itens if i < 0], reverse=True)
found = False
totalB = abs(sum(b))
 
if sum(a) < totalB:
    a, b = b, a
    totalB = abs(sum(b))            
   
       
if b != [] or a != []:
  
    if len(a) < 30:
 
        for i in chain.from_iterable(combinations(a, n+1)
                           for n in xrange(len(b),0,-1)):
        
            if abs(sum(i)) - totalB == 0:
                currentList = a+b
                sublist =  list(i)+b
                absoluteValue= (abs(sum(i)) + totalB)
                print  "com %s retornou %s Cujo o Valor absoluto é: %s  " \
                                  % (currentList,  sublist,  absoluteValue)
                found = True
                break
         
    else:
 
        loop = True
        size = len(a)
         
        while loop and size >= 2:       
   
            for i in chain.from_iterable(combinations(a, n+1)
                                 for n in xrange(size,0,-1)):
   
                if sum(abs(j) for j in i) >=  totalB:
                    size-=1
                    break
                else:
                    loop = False
                break
             
        for i in chain.from_iterable(combinations(a, n+1)
                                  for n in xrange(size,0,-1)):
        
            if abs(sum(i)) - totalB == 0:
                currentList = a+b
                sublist =  list(i)+b
                absoluteValue= (abs(sum(i)) + totalB)
                print  "com %s retornou %s Cujo o Valor absoluto é: %s  " \
                          % (currentList,  sublist,  absoluteValue)
                found = True
                break

    if not found:
        for i in chain.from_iterable(combinations(itens, n+1)
                         for n in xrange(len(itens), 0, -1)):
            if abs(sum(i)) == 0:
                currentList = itens
                sublist =  list(i)
                absoluteValue= sum( abs(j) for j in i )
                print  "com %s retornou %s Cujo o Valor absoluto é: %s  " \
                                  % (currentList,  sublist,  absoluteValue)
                found = True
                break
        
   
    if not found:     
        print "%s Nenhuma sublista" % itens
Agistech.com.br

quinta-feira, 6 de outubro de 2011

smtplib - Enviando E-mails com anexo

def email():
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import formatdate
    from email import Encoders
    import os
    user = "user@email.com" 
    password = "password" 
    subject = "email teste" 
    fromaddr = 'from@email.com' 
    toaddrs = 'to@email.com' 
    msg = MIMEMultipart()
    msg['Date'] = formatdate( localtime = True )
    
    msg['Subject'] = 'subject'

    msg.attach( MIMEText( 'oi' ) )
    part = MIMEBase( 'application', "octet-stream" )
    open( 'teste.txt', 'w' ).write( 'teste')
    part.set_payload( open( 'teste.txt', "rb" ).read() )
    Encoders.encode_base64( part )
    part.add_header( 'Content-Disposition', 'attachment; filename="teste.txt"' )
    msg.attach( part )
        
    servidor = smtplib.SMTP( 'smtp.domain:port' )
    servidor.ehlo()  
    servidor.starttls()  
    servidor.ehlo()  
    servidor.login( user, password )  
    servidor.sendmail( fromaddr, toaddrs, msg.as_string() )
Agistech.com.br

quarta-feira, 5 de outubro de 2011

Pyramid - convertendo html para pdf

import cStringIO as StringIO
import ho.pisa as pisa
from pyramid.renderers import render


def pdf( request ):
    
    request.response.content_type = 'application/pdf'

    request.response.headerlist.append( ( 'Content-Disposition', 'attachment; filename=test.pdf' ) )
    
    value = {}
    
    html = render( 'nameoftheproject:templates/foobar.jinja2', value, request )
    
    result = StringIO.StringIO()
    
    pisa.pisaDocument( StringIO.StringIO( html.encode( "UTF-8" ) ), result )
    
    request.response.write( result.getvalue() )

    return request.response
Agistech.com.br