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 13 total  RSS 

Groovy - Plain Text Word Wrap method

// Groovy Method to perform word-wrap to a specified length.
// Returns a List of strings representing the wrapped text

// Quick and Dirty method for plain text word-wrap to a specified width
static class TextUtils {
	
	static String[] wrapntab(input, linewidth = 70, indent = 0) throws IllegalArgumentException {
		if(input == null)
			throw new IllegalArgumentException("Input String must be non-null")
		if(linewidth <= 1)
			throw new IllegalArgumentException("Line Width must be greater than 1")
		if(indent <= 0)
			throw new IllegalArgumentException("Indent must be greater than 0")
		
		def olines = []
		def oline = " " * indent
		
		input.split(" ").each() { wrd ->
			if( (oline.size() + wrd.size()) <= linewidth ) {
				oline <<= wrd <<= " "
			}else{
				olines += oline
				oline = " " * indent
			}
		}
		olines += oline
		return olines
	}
}

// TEST
// the input String
input = "Note From SUPPLIER: Booking confirmed by fax.  4 standard rooms - 3 twin shared, 1 single room, please advise if guests require meals.. "

// call static wrapntab method to break the input string into 70 char wide lines with a 4 char initial indent
olines = TextUtils.wrapntab(input,70,4)

// print the output
olines.each() {
	println it
}

Find & Replace in Word Document with Ruby

I use this to open a "template" (really just a plain Word document with [text to replace] inside), do the substitutions, and save as a new filename.

require 'win32ole'

word = WIN32OLE.new('Word.Application')
#word.Visible = true # uncomment if you want to see it happen
doc = word.Documents.Open('c:\file_to_open.doc')
{
  'name' => 'Tim Morgan',
  'date' => Date.today.strftime('%B %d, %Y'),
  ...
}.each do |key, value|
  word.Selection.HomeKey(unit=6) # start at beginning
  find = word.Selection.Find
  find.Text = "[#{key}]" # text must be in square brackets
  while word.Selection.Find.Execute
    word.Selection.TypeText(text=value)
  end
end
doc.SaveAs('c:\output_file.doc')
doc.Close

Elegant way of shorten a text string

this method shortens a plain text string down to complete words contained in given scope (count)

def shorten (string, count = 30)
	if string.length >= count 
		shortened = string[0, count]
		splitted = shortened.split(/\s/)
		words = splitted.length
		splitted[0, words-1].join(" ") + ' ...'
	else 
		string
	end
end

Ruby dictionary username generation

Generate a new random name from dictionary words.

DICT_PATH = '/usr/share/dict/words'
DICT_SIZE = 234936

def self.generated_name words = 2, length = 23
  name = 'a'*(length+1)
  while name.length > length
    name = (1..words).map{%x[sed -n '#{rand(DICT_SIZE)} {p;q;}' '#{DICT_PATH}'].chomp.capitalize}.join
  end
end

Javascript: convert integer to word (e.g. 18 -> "eighteen")

// Convert a positive integer less than 1000 to its word representation.

var units = new Array ("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
var tens = new Array ("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");

function num(it) {
	var theword = "";
	var started;
	if (it>999) return "Lots";
	if (it==0) return units[0];
	for (var i = 9; i >= 1; i--){
		if (it>=i*100) {
			theword += units[i];
			started = 1;
			theword += " hundred";
			if (it!=i*100) theword += " and ";
			it -= i*100;
			i=0;
		}
	};
	
	for (var i = 9; i >= 2; i--){
		if (it>=i*10) {
			theword += (started?tens[i-2].toLowerCase():tens[i-2]);
			started = 1;
			if (it!=i*10) theword += "-";
			it -= i*10;
			i=0
		}
	};
	
	for (var i=1; i < 20; i++) {
		if (it==i) {
			theword += (started?units[i].toLowerCase():units[i]);
		}
	};
	return theword;
}

VBA DDE WORD EXCEL

// This is just sample code of some dde commands

Sub RUNEXCELMACRO()
'RUN MACRO
aChan = DDEInitiate(App:="Excel", Topic:="System")
DDEExecute Channel:=aChan, Command:="[Run(" & Chr(34) & _
    "Personal.xls!Macro1" & Chr(34) & ")]"
DDETerminate Channel:=aChan
'POKE
Chan = DDEInitiate(App:="Excel", Topic:="System")
DDEExecute Channel:=Chan, Command:="[OPEN(" & Chr(34) _
    & "C:\Sales.xls" & Chr(34) & ")]"
DDETerminate Channel:=Chan
Chan = DDEInitiate(App:="Excel", Topic:="Sales.xls")
DDEPoke Channel:=Chan, Item:="R1C1", Data:="1996 Sales"
DDETerminate Channel:=Chan
'This example opens the Microsoft Excel workbook Book1.xls and retrieves the contents of cell R1C1.
Chan = DDEInitiate(App:="Excel", Topic:="System")
DDEExecute Channel:=Chan, Command:="[OPEN(" & Chr(34) _
    & "C:\My Documents\Book1.xls" & Chr(34) & ")]"
DDETerminate Channel:=Chan
Chan = DDEInitiate(App:="Excel", Topic:="C:\DATA\SBS.xls")
msg = DDERequest(Channel:=Chan, Item:="R2C1")
msg = msg & " " & DDERequest(Channel:=Chan, Item:="R2C2")
MsgBox msg
DDETerminateAll
'This example opens a channel to the System topic in Microsoft Excel and then uses the Topics item to return a list of available topics. The example inserts the topic list, which includes all open workbooks, after the selection.
aChan = DDEInitiate(App:="Excel", Topic:="System")
TOPICLIST = DDERequest(Channel:=aChan, Item:="Topics")
Selection.InsertAfter TOPICLIST
DDETerminate Channel:=aChan

End Sub

ALL-WORDS? - returns true if all values in a block are word! values.

all-words?: func [
	"Returns true if all values in a block are word! values."
	block [block!]
] [
	parse block [some word!]
]

words-like - Returns a block of words in the object that match the given pattern.

words-like: func [
    "Returns a block of words in the object that match the given pattern."
    object  [object!]
    pattern [word! any-string!]
    ;??? Add an /unbound refinement
][
    pattern: join form pattern "*"
    collect w [
        foreach word next first object [
            if find/match/any form word pattern [w: bind word in object 'self]
        ]
    ]
]

Script Word from Python

A quick and dirty class for working with Word via COM in Python. By far, not all of the power of Word is available here, but it's a good start for simple tasks.

from win32com.client import constants, Dispatch

import pythoncom

wdStory = 6

class WordDocument(object):
  """
  Some convenience methods for Word documents accessed
  through COM.
  """
  
  def __init__(self, visible=False):
    self.app = Dispatch("Word.Application")
    self.app.Visible = visible
  
  def new(self, filename=None):
    """
    Create a new Word document. If 'filename' specified,
    use the file as a template.
    """
    self.app.Documents.Add(filename)
  
  def open(self, filename):
    """
    Open an existing Word document for editing.
    """
    self.app.Documents.Open(filename)
  
  def save(self, filename=None):
    """
    Save the active document. If 'filename' is given,
    do a Save As.
    """
    if filename:
      self.app.ActiveDocument.SaveAs(filename)
    else:
      self.app.ActiveDocument.Save()
  
  def save_as(self, filename):
    return self.save(filename)
  
  def print_out(self):
    """
    Print the active document.
    """
    self.app.Application.PrintOut()
  
  def close(self):
    """
    Close the active document.
    """
    self.app.ActiveDocument.Close()
  
  def quit(self):
    """
    Quit Word.
    """
    return self.app.Quit()
  
  def find_and_replace(self, find_str, replace_str):
    """
    Find all occurances of 'find_str' and replace with 'replace_str'
    in the active document.
    """
    self.app.Selection.HomeKey(Unit=wdStory)
    find = self.app.Selection.Find
    find.Text = find_str
    while self.app.Selection.Find.Execute():
      self.app.Selection.TypeText(Text=replace_str)

Find datatype words

datatypes: has [types attrs value word] [
	word: 'datatype!
	types: copy []
	attrs: second system/words
	foreach item first system/words [
		if all [
			not unset? first attrs
			any [
				all [string? :word find value word]
				all [
					not string? :word
					datatype? get :word
					(get :word) = type? first attrs
				]
			]
		] [
			append types item
		]
		attrs: next attrs
	]
	sort types
]
print mold datatypes
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS