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 1-10 of 10 total  RSS 

Zoom into SVG

This code is a complete SVG document which can be copied and pasted into a file saved as an SVG document (eg. makeZoom.svg) and run locally within your SVG compliant web browser. When the user clicks on the yellow rectangle the shape will increase in size giving the appearance that the document has just been zoomed in.

   1  
   2  <svg	xmlns="http://www.w3.org/2000/svg" width="100%"
   3  		xmlns:xlink="http://www.w3.org/1999/xlink" id="cont" viewBox="0 0 300 100">
   4    <g>	
   5      <g id="sketch" class="sketch">
   6        <rect x="130"
   7    y="6" width="20px" height="10px" fill="yellow" onclick="zoomIn()" />
   8      </g>
   9    </g>
  10  
  11    <script>
  12    <![CDATA[
  13    function zoomIn(){
  14  
  15      document.getElementById('sketch').parentNode.setAttribute('transform','translate(-70  ,-6)')
  16      document.getElementById('sketch').setAttribute('transform','scale(1.5)')
  17    }
  18    ]]>
  19    </script>
  20  </svg>
  21  


I started off experimenting with viewBox however for simplicity, transform seems better suited for zoom, and panning.

Reference:
Coordinate Systems, Transformations and Units - SVG 1.1 - 20030114 [w3.org]
Example for viewbox control [carto.net]

Using XSLT to convert a value to upper or lowercase

This code was copied from XSLT Case Conversion Solution [topxml.com]

Firstly lets place all the letters of the alphabet, lower case and upper case in variables.
   1  <xsl:variable name="lcletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
   2  <xsl:variable name="ucletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>

To then convert our data to upper case we use the translate method, which replaces all the lower case characters with upper case.
   1  <xsl:value-of select="translate($toconvert,$lcletters,$ucletters)"/>

Lower Case Transformation

The lower case transformation is basically the same:
   1  <xsl:value-of select="translate($toconvert,$ucletters,$lcletters)"/>

Translates Morse code from a mobile phone style keypad into plain English

// Translates Morse code specially input from a Nokia 3510i or Nokia 6600 to plain English. I primarily used the button 1 for a dot, 2 for a dash and 5 for the terminator. I later extended the flexibility of the inputs by allowing 4 to be a dot, 7 a dash and 9 as the terminator. eg. ghi = dots pqrs = dashes wxyz = terminators and spaces.

   1  
   2  #!/usr/bin/ruby
   3  #filename: morsecode.rb
   4  
   5  require 'net/http'
   6  require 'rexml/document'
   7  
   8  include REXML
   9  
  10  class Morsecode
  11    def initialize
  12      @doc_mlookup = load_lookup('http://jamesrobertson.eu/p/xml/', 'morsecode.xml')
  13      @doc_charmcode = load_lookup('http://jamesrobertson.eu/p/xml/', 'charmcode.xml')
  14    end
  15  
  16    def load_lookup(url, filename)
  17      xml_data = Net::HTTP.get_response(URI.parse(url + filename)).body
  18      Document.new(xml_data)
  19    end
  20  
  21    def decode_string(doc, a_buffer)
  22      pstring = ''
  23      a_buffer.each do |word|
  24        pstring += doc.root.elements["code[@encode='" + word + "']"].text
  25      end
  26      pstring
  27    end
  28  
  29    def decode_kstring(buffer)
  30      decode_string(@doc_charmcode, buffer.scan(/./))
  31    end
  32  
  33    def decode_mstring(buffer)
  34      decode_string(@doc_mlookup, buffer.split('4'))
  35    end
  36  
  37    def decode(buffer)
  38      decode_mstring(decode_kstring(buffer)) if buffer.length > 0
  39    end
  40  end
  41  
  42  #test
  43  a = Morsecode.new
  44  puts a.decode('gwpwrwgw')
  45  
  46  

Babelfish translate

Ok, so maybe some of you might think that Babelfish's the best translator out there. I don't know about that , but I do know where my towel is ;)
So, boys and girls, here's the bookmarklet that allows to translate your current web-page using the babelfish translation engine.

   1  
   2  javascript:location.href='http://babelfish.altavista.com/babelfish/tr?trurl='+encodeURIComponent(location.href)+'&lp=%s&btnTrUrl=Translate'


To make it useful, save it as a bookmark in FF (or as a new search engine in Opera) and give it a keyword/shortcut by editing the bookmark's properties in FF (or the search properties in Opera). Let's call him, say 'bf', that should do it.

Here are some examples:
   1  
   2  bf en_fr
   3  bf fr_en
   4  bf en_ja


Enjoy!
G.R.

Google translate bookmarklet

Here's perhaps the most powerful bookmarklet I've ever created ...
This one translates the current web page from your current browser session into another language!

Syntax from the address bar in your FF or Opera browser:
   1  
   2   tr <FROM>|<TO>


Examples:
   1  
   2   tr en|de
   3   tr en|fr
   4   tr en|pt
   5   tr de|en


Here's the bookmarklet code
   1  
   2  javascript:location.href='http://translate.google.com/translate?u='+encodeURIComponent(location.href)+'&langpair=%s&hl=EN&ie=UTF-8&oe=UTF-8&prev=%2Flanguage_tools'


FF instructions:
Copy/paste the code in a new bookmark. Then, in the new bookmark properties, edit the keyword/shortcut field and insert 'tr'. That's it!

Opera instructions:
Copy the bookmarklet code. Then, in tools-->preferences-->search-->add-->details, paste the code in the address field, fill in a name for in the name field, and write 'tr' in the keyword field. Then save all. That's it!

PyS60 - BabelFish

// Translate from language A to language B
// code not complete but it works

   1  
   2  import urllib
   3  
   4  ####################################################################################### <BabelFish>
   5  class BabelFish(object):
   6      
   7      def translate(self, lang, message):
   8          
   9          try:
  10              url = urllib.URLopener()
  11          
  12              query = urllib.urlencode({
  13                                        'doit':'done',
  14                                        'intl':'1',
  15                                        'lp':lang,
  16                                        'tt':'urltext',
  17                                        'urltext':message
  18                                        })
  19          
  20              responde = url.open('http://babelfish.altavista.com/tr', query).read()
  21          
  22              start = responde.find('<div style=padding:10px;>') + 25
  23              stop = responde.find('</div>', start)
  24          
  25              return responde[start:stop]
  26          
  27          except Exception, error:
  28              return '-' + str(error)
  29  ####################################################################################### </BabelFish>
  30  
  31  ####################################################################################### <BabelFishUI>
  32  from graphics import *
  33  
  34  import appuifw
  35  import e32
  36  
  37  class BabelFishUI(object):
  38      
  39      def __init__(self):
  40          
  41          self.__lock = e32.Ao_lock()
  42          self.__img = Image.new((176, 144))
  43          self.__language = 'it_en'
  44          self.__textUI = None
  45          
  46          appuifw.app.exit_key_handler = lambda:self.__lock.signal()
  47          
  48          appuifw.app.title = u'BabelFish v1.0'
  49          appuifw.app.body = self.__canvas = appuifw.Canvas(redraw_callback=self.updateScreen)
  50          
  51          appuifw.app.menu = [(u'Translate', lambda:self.__translateUI()), (u'About', lambda:appuifw.note(u'BabelFish: v1.0", "Created by\nWhite Tiger\n<Z-TEAM@Libero.it>', 'info')), (u'Exit', lambda:self.__lock.signal)]
  52          
  53          self.updateScreen(None)
  54          
  55          self.__menuMain = appuifw.app.menu
  56          self.__bgMain = appuifw.app.body
  57          
  58          self.__lock.wait()
  59      
  60      def updateScreen(self, rect):
  61          
  62          self.__canvas.blit(self.__img)
  63      
  64      def __back(self):
  65          
  66          appuifw.app.menu = self.__menuMain
  67          appuifw.app.body = self.__bgMain
  68          
  69          appuifw.app.set_tabs([u'Back'], lambda x:None)
  70      
  71      def __translateUI(self):
  72          
  73          self.__textUI = appuifw.Text()
  74                  
  75          appuifw.app.menu = [(u'Translate', lambda:self.__translate()), (u'Language', lambda:self.__setLanguage()), (u'Clear', lambda:self.__textUI.clear()), (u'Back', lambda:self.__back())]
  76                     
  77          appuifw.app.body = self.__textUI
  78                  
  79      def __setLanguage(self):
  80          
  81          resp = appuifw.selection_list([u'italiano-inglese', u'inglese-italiano', u'inglese-francese', u'francese-inglese', u'inglese-tedesco', u'tedesco-inglese',
  82                                         u'francese-italiano', u'italiano-francese'], 1)
  83          
  84          if resp == 0:
  85              self.__language = 'it_en'
  86          elif resp == 1:
  87              self.__language = 'en_it'
  88          elif resp == 2:
  89              self.__language = 'en_fr'
  90          elif resp == 3:
  91              self.__language = 'fr_en'
  92          elif resp == 4:
  93              self.__language = 'en_de'
  94          elif resp == 5:
  95              self.__language = 'de_en'
  96          elif resp == 6:
  97              self.__language = 'fr_it'
  98          elif resp == 7:
  99              self.__language = 'it_fr'
 100              
 101      def __translate(self):
 102          
 103          babel = BabelFish()
 104          
 105          resp = babel.translate(self.__language, self.__textUI.get())
 106          
 107          if resp[0] == '-':
 108              self.__textUI.set(unicode(resp[1:]))
 109          else:
 110              self.__textUI.set(unicode(': ' +self.__textUI.get() + '\n: ' + resp))
 111                  
 112          appuifw.note(u'Translate', 'conf')
 113  ####################################################################################### </BabelFishUI>
 114  
 115  if __name__ == '__main__':
 116      
 117      BabelFishUI()

Python - Query BabelFish

//Example di POST HTTP

   1  
   2  #!/usr/bin/python
   3  
   4  import urllib
   5  
   6  def translate(lang='it_en', text='ciao'):
   7  	
   8  	'''Converte delle frasi da una lingua sorgente ad una lingua destinazione'''
   9  
  10  	url = urllib.URLopener()
  11  	
  12  	query = urllib.urlencode({'doit':'done', 'intl':'1', 'lp':lang, 'tt':'urltext', 'urltext':text})
  13  	
  14  	responde = url.open('http://babelfish.altavista.com/tr', query).read()
  15  
  16  	start = responde.find('<div style=padding:10px;>') + 25
  17  	stop = responde.find('</div>', start)
  18  
  19  	print responde[start:stop]

Latex2wiki

Translate a subset of LaTeX into MoinMoin wiki syntax.


   1  
   2  #!/usr/bin/env python
   3  
   4  #    Copyright (C) 2003, Maxime Biais <maxime@biais.org>
   5  #
   6  #    This program is free software; you can redistribute it and/or modify
   7  #    it under the terms of the GNU General Public License as published by
   8  #    the Free Software Foundation; either version 2 of the License, or
   9  #    (at your option) any later version.
  10  #
  11  #    This program is distributed in the hope that it will be useful,
  12  #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  13  #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14  #    GNU General Public License for more details.
  15  #
  16  #    You should have received a copy of the GNU General Public License
  17  #    along with this program; if not, write to the Free Software
  18  #    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  19  #
  20  # $Id: latex2wiki.py,v 1.1.1.1 2004/03/14 18:31:50 max Exp $
  21  
  22  import sys, re
  23  
  24  def dummy(d):
  25      pass
  26  
  27  NONE = "__@NONE@__"
  28  
  29  tr_list = [
  30      (r"\\includegraphics.*{(.*)\.eps}", "attachment::%s.png", dummy),
  31      (r"\\caption{.*}", "", dummy),
  32      (r"\\label{.*}", "", dummy),
  33      (r"(.*)\\emph{(.*)}(.*)", """%s'''%s'''%s""", dummy),
  34      (r"\\item (.*)", " * %s", dummy),
  35      (r"\\begin{.*}", "", dummy),
  36      (r"\\end{.*}", "", dummy),
  37      (r"(.*)``(.*)''(.*)", "%s\"%s\"%s", dummy),
  38      (r"\\chapter{(.*)}", NONE, dummy),
  39      (r"\\paragraph{(.*)}", "==== %s ====", dummy),
  40      (r"\\subsubsection{(.*)}", "==== %s ====", dummy),
  41      (r"\\subsection{(.*)}", "=== %s ===", dummy),
  42      (r"\\section{(.*)}", "== %s ==", dummy),
  43      (r"(.*)\\fig{.*}(.*)", "%s suivant %s", dummy)
  44      ]
  45  
  46  in_stream  = open(sys.argv[1], "r")
  47  if len(sys.argv) < 3:
  48      out_stream = sys.stdout
  49  else:
  50      out_stream = open(sys.argv[2], "w")
  51  
  52  
  53  for i in in_stream.readlines():
  54      cur_write = 0
  55      for reg in tr_list:
  56          m = re.search(reg[0], i)
  57          if m:
  58              reg[2](i)
  59              cur_write = 1
  60              if reg[1] == NONE:
  61                  break
  62              print >> out_stream, reg[1] % m.groups()
  63              break
  64      if not cur_write:
  65          out_stream.write(i)

translit string (americanize)

   1  
   2  require 'iconv'
   3  
   4  class String
   5    def translit
   6      self.gsub(/[^\x20-\x7f]/){ Iconv.iconv('us-ascii//IGNORE//TRANSLIT', 'utf-8',$&)[0].sub(/^[\^`'"~](?=[a-z])/i, '')}
   7    end
   8  end

converting some french chars with python

because translate and maketrans don't love utf-8 ;-(
   1  
   2      import string
   3      french=u"15 résultats trouvés".encode("utf_16")
   4      
   5      sfrom = u"àâäéèêëïîôöûùüç".encode("utf_16")
   6      sto   = u"aaaeeeeiioouuuc".encode("utf_16")
   7      print french.translate( string.maketrans(sfrom,sto) )
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS