Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
Code Snippets: Store, sort and share source code, with tag goodness
[go: Go Back, main page]

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 (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

Top Tags Alphabetically

REBOL (110)
apache (13)
array (23)
bash (20)
canvas (11)
cli (13)
csharp (15)
css (27)
database (11)
date (17)
expressionengine (19)
file (31)
files (11)
find (12)
form (11)
google (11)
html (63)
http (11)
image (20)
java (41)
javascript (140)
lighttpd (16)
linux (26)
list (11)
mac (18)
math (28)
mysql (24)
osx (22)
perl (32)
php (79)
prototype (11)
python (172)
rails (98)
regex (12)
ruby (146)
rubyonrails (33)
series (21)
series60 (58)
servers (17)
shell (40)
sql (40)
ssh (26)
string (20)
text (12)
time (13)
unix (24)
web (19)
windows (15)
xml (26)
xslt (12)

« Newer Snippets
Older Snippets »
1128 total  XML / RSS feed 

gnuplot sinus example (produce .eps file for inclusion in latex)

This is a very simple gnuplot script to plot a sinus curve and save it to "sinus.eps"

If you saved the code to a file sinus.gnuplot, you can run it with the command:
gnuplot < sinus.gnuplot

The file can then be viewed by ghostview, or converted to pdf via the command "epstopdf"

I found *lots* of help on gnuplot on this website:
http://t16web.lanl.gov/Kawano/gnuplot/index-e.html

set term postscript eps color blacktext "Helvetica" 24
set output 'sinus.eps'
set ylabel 'sin(x)'
set xlabel 'x'
plot sin(x)
set output
quit

generate .eps figure with python by using gnuplot

this is a sample python script to generate a bode plot (nothing fancy).

Mathematical data is computed using scipy (=scientific python) and numpy (=powerful multidimensional array to use with scipy).

Data is handled to gnuplot by the package gnuplot-py (http://gnuplot-py.sourceforge.net). Tu use gnuplot-py with the new scipy/numpy packages you have to replace "Numeric" by "numpy" in all source files of gnuplot-py before installing. Examples provided by the package won't work, but you can use it without problem

if you want to *automatically* use that in latex see my Makefile code snippets

#!/usr/bin/python
# -*- coding: utf-8 -*-

import scipy, numpy, Gnuplot

N = 1000
x = numpy.randn(N)
y = numpy.randn(N)
X = numpy.dft.fft(x)[1:N/2+1]
Y = numpy.dft.fft(y)[1:N/2+1]
S = X * Y.conj()
S_abs = abs(S)
S_phase = numpy.arctan(S.imag / S.real)

# 100 Hz
fsamp = 100.
freq = numpy.arange(1,N/2+1) * fsamp / N

plot = Gnuplot.Gnuplot()
data_abs = Gnuplot.Data(freq, S_abs, with='lines')
data_phase = Gnuplot.Data(freq, S_phase, with='lines')
plot('set term postscript eps color blacktext "Helvetica" 24')
plot("set output 'bode.eps'")
plot('set multiplot')
plot('set size 1.0,0.5')
plot('set origin 0.0,0.5')
plot("set ylabel 'amplitude'")
plot('set logscale y')
plot.plot(data_abs)
plot('set origin 0.0,0.0')
plot("set ylabel 'phase'")
plot("set xlabel 'Frequency (Hz)'")
plot('set nologscale y')
plot.plot(data_phase)
plot('set nomultiplot')
plot('set output')
plot('quit')

Makefile for latex

this is a sample makefile to build a latex report with pdflatex. all images are build from a makefile in the subdirectory images/ (see my other Makefile)

I found those websites useful when building the makefile

http://www.wlug.org.nz/MakefileHowto
http://www.gnu.org/software/make/manual/html_chapter/make.html

TEXFILE=report

all: $(TEXFILE).pdf

# .PHONY tells make that these rules don't create any file
# --> if there is a file called all it will still run
.PHONY: all clean images

%.pdf: %.tex images
	pdflatex $<
	pdflatex $<

# for subdirectories use the variable $(MAKE)
# -C path/to/directory to tell in which directory to run
#
#  --> note: use environment variables like this $(VARIABLE)
images:
	$(MAKE) -C images 

clean:
	$(MAKE) clean -C images
	rm -f *.aux *.log

Makefile for images in latex

This is a Makefile to build images for use by pdflatex from .gnuplot command files and .py python scripts. It is supposed that the gnuplot/python files produce .eps images when launched

all: sinus.pdf sincos.pdf sine.pdf sine2.pdf sincos2.pdf bode.pdf

.PHONY: all clean

# we want all .gnuplot files to be 'made' into .eps files
# the % replaces any name
# in the rule: 	$< replaces the source
# 				$@ replaces the target
# example: convert $< $@
# 
%.eps: %.gnuplot
	gnuplot < $<

%.eps: %.py
	python $<

%.pdf: %.eps
	epstopdf $<
	
clean:
	rm -f *.eps *.pdf

One-click connect from cygwin to full-screen Linux (X stuff required)

Optional: execute the following once (see http://hacks.oreilly.com/pub/h/66 for
details), to avoid typing in the password.

set LINUX_HOST=mylinuxhost
ssh-keygen -t rsa
ssh %USERNAME%@%LINUX_HOST% "mkdir .ssh; chmod 0700 .ssh"
bash -c 'scp ~/.ssh/id_rsa.pub %LINUX_HOST%:.ssh/authorized_keys2'


Now, if you save the following as a BATCH file, you can just click it
to connect to fullscreen Linux:

set LINUX_HOST=mylinuxhost
start /min xinit 
xhost +%LINUX_HOST%
ssh %LINUX_HOST% "declare -x DISPLAY=%COMPUTERNAME%:0; echo $DISPLAY;gnome-session"'


NOTES:
1.
Sometimes xhost + does not execute in time. O well. Just close
all windows that got opened and try again.

2.
If you didn't do the step one (ssh keys), you will be prompted
to enter the linux password; this increases the chances of the above
error.

3.
The single terminal window appearing in the Linux desktop is in fact
a window from your PC.

[Multiplatform] Thumbnails of all (gif, jpeg, and png) images in a directory

Thanks Dorrin for your Thumbnailer!
I hope you don't mind, but I did some minor fixes and made your script more portable. Now, you can use it on Windows too.
By the way, as I revealed there is no dependency of "from mod_python import apache", so I removed it.

import os
import re
from PIL import Image

header = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Directory Listing</title></head>
<body>'''
images_per_row = 5
max_width,max_height = 150,150

path = os.path.dirname(__file__)
  
def thumbnail(filename):
  thumbsdir = os.path.join(path, ".thumbnails")
  thumbfile = os.path.join(thumbsdir, filename)
  if os.path.exists(thumbfile):
    return

  if not os.path.exists(thumbsdir):
    os.mkdir(thumbsdir);
    
  filepath = os.path.join(path, filename)
  image = Image.open(filepath)
  image.thumbnail((max_width, max_height), Image.ANTIALIAS)
  image.save(thumbfile)

def index(req):
  return_value = header

  dir_list = os.listdir(path)
  image_list = []

  search = re.compile("(.*\.[Jj][Pp][Ee]?[Gg]$)|(.*\.[Pp][Nn][Gg]$)|(.*\.[Gg][Ii][Ff]$)")

  image_count = 0
  for file in dir_list:
    if search.match(file):
      image_count += 1
      image_list.append(file)

  if image_count > 0:
    image_list.sort()
    num_rows = image_count / images_per_row

    image_num = 0
    return_value += '<table width="100%" border="0"><tr>\n'

    for image in image_list:
      thumbnail(image)
      image_num += 1
      return_value += '<td><a href="' + image + '"><img src=".thumbnails/' + image + '" alt="' + image + '"></a>'

      if image_num % images_per_row:
        return_value += '</td>\n'

      else:
        return_value += '</td></tr><tr>\n'

  return_value += "</table></body></html>"
  return return_value


Here is small test script.
It generates thumbnails with Dorrin's script, then grabs HTML output and writes it to index.html file, so you get nice index page.

import thumbnail
import os

html = thumbnail.index(0)

htmlfile = os.path.join(os.getcwd(), "index.html")
f = open(htmlfile, "w")
f.write(html);
f.close()

Thumbnails of all (gif, jpeg, and png) images in a directory

I've gone with just gif, jpeg, and png for now, but it should be easy enough to add any others that PIL supports - just update the regex.

This code generates a basic page with thumbnails of all images in the directory it is run from. It caches thumbnails in the .thumbnails directory. It requires mod_python and PIL to run, though mod_python can be removed trivially.

from mod_python import apache
import os
import re
from PIL import Image

header = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Directory Listing</title></head>
<body>'''
images_per_row = 5
max_width,max_height = 150,150

path = os.path.dirname(__file__)
  
def thumbnail(filename):
  if os.path.exists(path + "/.thumbnails/" + filename):
    return

  image = Image.open(path + "/" + filename)
  image.thumbnail((max_width, max_height), Image.ANTIALIAS)
  image.save(path + "/.thumbnails/" + filename)

def index(req):
  return_value = header

  dir_list = os.listdir(path)
  image_list = []

  search = re.compile("(.*\.[Jj][Pp][Ee]?[Gg]$)|(.*\.[Pp][Nn][Gg]$)|(.*\.[Gg][Ii][Ff]$)")

  image_count = 0
  for file in dir_list:
    if search.match(file):
      image_count += 1
      image_list.append(file)

  if image_count > 0:
    image_list.sort()
    num_rows = image_count / images_per_row

    image_num = 0
    return_value += '<table width="100%" border="0"><tr>\n'

    for image in image_list:
      thumbnail(image)
      image_num += 1
      return_value += '<td><a href="' + image + '"><img src=".thumbnails/' + image + '" alt="' + image + '"></a>'

      if image_num % images_per_row:
        return_value += '</td>\n'

      else:
        return_value += '</td></tr><tr>\n'

  return_value += "</table></body></html>"
  return return_value

HTTP 301 - Moved Permanently

<script runat="server">
private void Page_Load(object sender, System.EventArgs e) {
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", "http://www.new-url.com");
}
</script>

http://www.webconfs.com/how-to-redirect-a-webpage.php

Creating a Multiple Row Form

// Jamis Buck's reply to a mailing list question: http://www.ruby-forum.com/topic/52514#26231

The View
<% 10.times do |n| %>
  <%= text_field_tag "milestones[#{n}][title]" %><br />
<% end %>

The Controller
def create
  10.times do |n|
    next if params[:milestones][n.to_s][:title].blank?
    Milestone.create(params[:milestones][n.to_s])
  end
end

escape-control-chars

    escape-control-chars: func [
        "Convert all control chars in string to \uxxxx format"
        s [any-string!] /local ctrl-ch c
    ][
        ctrl-ch: charset [#"^@" - #"^_"]
        parse/all s [
            any [
                mark: copy c ctrl-ch (
                    change/part mark encode-control-char to char! c 1
                ) 5 skip
                | skip
            ]
        ]
        s
    ]
« Newer Snippets
Older Snippets »
1128 total  XML / RSS feed