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-19 of 19 total

Finding line number when matching text

I use python to do some text analysis.
I load all the text file into a string and match it with
a regexp. Now I want to know the line number of a match.
I can use the line number to lookup inside the text.
(in this case using EditPlus)
src = open('2.htm').read()
pattern = '<P>([^<]+)<SUP>'  # or anything else
for m in re.finditer(pattern, src):
	start = m.start()
	lineno = src.count('\n', 0, start) + 1
	offset = start - src.rfind('\n', 0, start)
	word = m.group(1)
	print "2.htm(%s,%s): %s" % (lineno, offset, word)

Editplus allow me to double click at the output printed
and jump to the exact position using the given lineno, offset.

Commify numbers

This is just the Ruby version of a known regular expression
to get comma-formatted numbers.


numbers = "10000000 1.345 -91245555.45 +6788876.224334 -2321232" 

numbers.reverse!
numbers.gsub!(/(\d\d\d)(?=\d)(?!\d*\.)/, '\1,')
puts numbers.reverse!


MIDI Note number and frequency

Summary of MIDI Note Numbers
MIDI Note to Frequency

I can use them with my midi snippet.
# from http://logic-users.org/forums/L-OT/295
# Each note's frequency is 2^(1/12) times of the previous note.

freq = 440 * 2^((n-69)/12)
n = 69 + 12*log(freq/440)/log(2)

# Doe, ray, me, fa, sol, la, tee, doe
>>> play([(i, 100) for i in [60, 62, 64,65, 67, 69, 71,72]])

Adjust Page Number when Page Length Changes

In a web page you are display a certain page worth of results. If you allow the user to change the page length, you'll need to find the new page number that contains the first item on the current page. This is VB.Net code.

intOldPageLength = GetPageLengthValue()

' if there is a new page length value
If intOldPageLength <> m_intPageLength Then

   ' adjust the page number to compensate
   intItemCount = ((m_intPage - 1) * intOldPageLength) + 1
   m_intPage = intItemCount \ m_intPageLength
   If intItemCount - (m_intPage * m_intPageLength) > 0 Then
      m_intPage = m_intPage + 1
   End If

End If


The index of the first item on the current page happens to be a count of the items up to that point. So assume we are paging that amount and use the last page as our new current page. We apply standard paging logic of items integer divided by page length to determine the number of pages and add one if there is a remainder.

There are a couple formulas at work here worth noting.
Index of Last Item on page:
page number * page length
Index of First Item on page:
(index of last item of previous page) + 1
((page number - 1) * page length) + 1
Page Count based on page length:
number of items [integer divide] page length
if there is a remainder to the above then add 1

add thousands separators to numbers

I've finally figured out how to add thousands separators.

If there's a built in for this (like a `sprintf` parameters) I don't want to hear it. I just don't, ok?

def ts( st )
  st = st.reverse
  r = ""
  max = if st[-1].chr == '-'
    st.size - 1
  else
    st.size
  end
  if st.to_i == st.to_f
    1.upto(st.size) {|i| r << st[i-1].chr ; r << ',' if i%3 == 0 and i < max}
  else
    start = nil
    1.upto(st.size) {|i|
      r << st[i-1].chr
      start = 0 if r[-1].chr == '.' and not start
      if start
        r << ',' if start % 3 == 0 and start != 0  and i < max
        start += 1
      end
    }
  end
  r.reverse
end


That's it.

puts ts('100')
puts ts('1')
puts ts('1000')
puts ts('1000000.01')
puts ts('100046546510000.022435451')
puts ts('-100')
puts ts('-1')
puts ts('-1000')
puts ts('-1000000.01')
puts ts('-100046546510000.022435451')


outputs:

100
1
1,000
1,000,000.01
100,046,546,510,000.022435451
-100
-1
-1,000
-1,000,000.01
-100,046,546,510,000.022435451


It's ugly, yeah, but it works.

Number to Engineering format

Engineering format lists the exponent in powers of three

def number_to_engineering(value, precision=3)
  expof10 = ((Math.log10(value)/3.0).floor)*3
  value *= 10**(-expof10)
  case 
    when value>=1000.0 : 
      value /= 1000.0
      expof10 +=3 
    when value>=100.0 :  precision -= 2 
    when value>=10.0 :  precision -= 1 
  end
  "%.*fe%d" % [precision-1, value, expof10]
end

number_to_engineering(15000) => "15e3"


Helper to format numbers using scientific notation

For those of us who can't remember the formatting codes

def number_to_scientific(num,precision=3)
	"%.#{precision}e" % num
end

number_to_scientific(10000) => 1.000e004

in some cases it might be better to use the 'g' code instead of the 'e' code.

Helper to print numbers as ordinals (1st, 2nd, 3rd...)

def number_to_ordinal(num)
  num = num.to_i
  if (10...20)===num
    "#{num}th"
  else
    g = %w{ th st nd rd th th th th th th }
    a = num.to_s
    c=a[-1..-1].to_i
    a + g[c]
  end
end

number_to_ordinal(12) => "12th"
number_to_ordinal(7) => "7th"


Note that floats will be converted to ints (without rounding) before processing.

baseX converter

you can use this function to convert an integer into any number system upto base36 (e.g. for TinyURL generation coupled with a global ID counter)

function int2baseX($val,$base=16) {
  if (0==$val) return 0;
  $symbols='0123456789abcdefgihjklmnopqrstuvwxyz';
  $result='';
  $exp=$oldpow=1;
  while($val>0 && $exp<10) {
    $pow=pow($base,$exp++);
    $mod=($val % $pow);
    $result=substr($symbols,$mod/$oldpow,1).$result;
    $val-=$mod;
    $oldpow=$pow;
  }
  return $result;
}
« Newer Snippets
Older Snippets »
Showing 11-19 of 19 total