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

« Newer Snippets
Older Snippets »
Showing 11-20 of 25 total

Flac to mp3

Converts all *.flac files in the current dir to mp3.

#!/bin/bash

for file in *.flac
do
	echo Converting $file
	flac123 -q --wav=- "$file" | lame - "$file".mp3
done

PHP : Exportar CSV a mySQL / Export CSV to mySQL

Cóodigo fuente / Source code :

function exportarCSV_a_mySQL($fileCSV)
{
	$registros=0;

	$ruta=$fileCSV['tmp_name'];

	if(!file_exists($ruta))
	{return false;}

	$tabla=quitar_extension($fileCSV['name']);
	
	$borra_tabla="DROP TABLE `".$tabla."`";
	mysql_query($borra_tabla);
	$f=fopen($ruta,"r");
	if($f)
	{
		echo "<b>Guardando CSV en la BDD :</b><br />";
		$contenido=fread($f,filesize($ruta));
		fclose($f);
		$contenido=ereg_replace("\r\n", "\n" , $contenido); // convertimos windows a unix
		$lineas=explode("\n",$contenido);
		$titulo=explode(";",$lineas[0]);
		$NUM_CAMPOS=count($titulo);
		$sql_generado_para_eliminar="";
		$crear_tabla_campos="";
		for($i=0;$i<$NUM_CAMPOS;$i++)
		{
		$titulo[$i]=ereg_replace("\"", "" , $titulo[$i]); // kitamos comillas
		$sql_generado_para_eliminar.=" AND `".$titulo[$i]."` =''";
		$crear_tabla_campos.="`".$titulo[$i]."` varchar(60) NOT NULL";
			if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
			{
			$crear_tabla_campos.=",";
			}
		}
		$crear_tabla="CREATE TABLE `".$tabla."` (".$crear_tabla_campos.") ENGINE=MyISAM DEFAULT CHARSET=latin1;";
		mysql_query($crear_tabla);
		$linea=1;
		do
		{
			$insertar_titulos="";
			$insertar_campos="";
			$campo=explode(";",$lineas[$linea]);
			for($i=0;$i<$NUM_CAMPOS;$i++)
			{
			$campo[$i]=ereg_replace("\"", "" , $campo[$i]);
			$insertar_titulos.=" `".$titulo[$i]."` ";
			$insertar_campos.=" '".$campo[$i]."' ";
				if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
				{
				$insertar_titulos.=",";
				$insertar_campos.=",";
				}
			}
			$sql="INSERT INTO `".$tabla."` ( ".$insertar_titulos." ) VALUES ( ".$insertar_campos." );";
			if(mysql_query($sql))
			{
			echo ". ";
			$registros++;
			}
			else
			{echo "X ";return false;}
		$linea++;
		}while(next($lineas));

	$sql="DELETE FROM `".$tabla."` WHERE 1".$sql_generado_para_eliminar;mysql_query($sql);
	echo "<br />";
	return $tabla;
	}
	else
	{
	return false;
	}
}

function quitar_extension($archivo)
{
	$extension = strrchr($archivo,".");
	$pos=strpos($archivo,$extension);
	return substr($archivo,0,$pos);
}


Código ejemplo de llamada / Code exmple call :

$tabla = exportarCSV_a_mySQL($_FILES['archivo_csv']);
if($tabla)
{
echo "Export OK in mysql table : ".$tabla;
}
else
{
echo "Error in export ...";
}

Convert extensions of files to lowercase using perl

1. Searches for files having uppercase extensions (can be mixed with numbers and can be multipart eg: TAR.BZ2 ).
It does not detect files whose extensions contain both upper and lower cases. This is intentional, as if you have part of extension lowercase, you probably intentionally left the other part upper case. Changing this behaviour is trivial. Replace that complex (?:[A-Z]*[0-9]*\.*) with a . (a dot).

2. It then converts them to lowercase.

#!/usr/bin/perl
$files=`ls`;
@files=split(/\n/,$files);
foreach (@files) {
    if(/(.*)\.((?:[A-Z]*[0-9]*\.*)+)$/) {
        $name=$1."."."\L$2\E";
        system("mv $_ $name")
    }
}

Looks quite ugly, but this is what I could do with the Perl I know, and more importantly, it works (at least in my case)!

Ruby CSV to XML Converter

This code will take an input CSV file and output XML. IT was easy to write, but I haven't found anything out there to do this. The first line of the CSV file should contain the element names.

#!/usr/bin/ruby

require 'csv'

print "CSV file to read: "
input_file = gets.chomp

print "File to write XML to: "
output_file = gets.chomp

print "What to call each record: "
record_name = gets.chomp

csv = CSV::parse(File.open(input_file) {|f| f.read} )
fields = csv.shift

puts "Writing XML..."

File.open(output_file, 'w') do |f|
  f.puts '<?xml version="1.0"?>'
  f.puts '<records>'
  csv.each do |record|
    f.puts " <#{record_name}>"
    for i in 0..(fields.length - 1)
      f.puts "  <#{fields[i]}>#{record[i]}</#{fields[i]}>"
    end
    f.puts " </#{record_name}>"
  end
  f.puts '</records>'
end # End file block - close file

puts "Contents of #{input_file} written as XML to #{output_file}."

bindec.scm

// Convert list of 1s and 0s back to base ten number.

; Andrew Pennebaker
; 5 Feb 2007
; License: GPL
; URL: http://snippets.dzone.com/posts/show/3479

(define bin->dec
	(lambda (b)
		(cond
			((integer? b) b)
			((= (length b) 0) 0)
			(else
				(+
					(* (expt 2 (- (length b) 1)) (car b))
					(bin->dec (cdr b)))))))

decbin.scm

// Converts a base ten integer to a list of 1s and 0s

; Andrew Pennebaker
; 3 Feb 2007
; License: GPL
; URL: http://snippets.dzone.com/posts/show/3478

(define dec->bin
	(lambda (d)
		(cond
			((< d 1) (list 0))
			((= d 1) (list 1))
			((> d 1) (append
				(dec->bin (floor (/ d 2)))
				(list (if (= (modulo d 2) 0) 0 1)))))))

Convert Array to Hash

Probably nothing new in this but here is one way of converting an Array to a Hash:

require "enumerator"

class Array
  def to_h
    Hash[*enum_with_index.to_a.flatten]
  end
end

%w{a b c d}.to_h  # =>  {"a"=>0, "b"=>1, "c"=>2, "d"=>3}


html2txt.py

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="10 Dec 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__credits__="Based on http://mail.python.org/pipermail/python-list/2004-November/291562.html"
__URL__="http://snippets.dzone.com/posts/show/3127"

import htmllib
from sgmllib import SGMLParser

import sys

class html2txt(SGMLParser):
	"""html2txt()"""

	def reset(self):
		SGMLParser.reset(self)
		self.pieces=[]

	def handle_data(self, text):
		self.pieces.append(text)

	def unknown_starttag(self, tag, attributes):
		pass

	def unknown_endtag(self, tag):
		pass

	def handle_entityref(self, ref):
		try:
			self.pieces.append(htmllib.HTMLParser.entitydefs[ref])
		except KeyError, e:
			self.pieces.append("&"+ref)

	def output(self):
		return "".join(self.pieces)

if __name__=="__main__":
	html="".join(sys.stdin.readlines())

	parser = html2txt()
	parser.feed(html)
	parser.close()

	print parser.output()

Bash - avi2mpg

ffmpeg -i video.avi -target vcd video.mpg

Convert single object to List

Works with varargs in Java 1.6

List<String> list = java.util.Arrays.asList("foo");
« Newer Snippets
Older Snippets »
Showing 11-20 of 25 total