20120704




package adventure;

import java.awt.*;

import com.jme3.scene.Spatial;
import com.jme3.light.DirectionalLight;
import com.jme3.font.BitmapText;
import java.awt.event.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.applet.*;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeCanvasContext;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

public class Dungeon3D extends SimpleApplication implements Playable {
private JPanel buttons;
private PlaceView placeview;
private Commands commands;
private TextArea textarea;

class MyWindowAdapter extends WindowAdapter {

public void windowClosing(WindowEvent e) {
System.exit(0);
}
}

// Load an image from the net, making sure it has already been
// loaded when the method returns
public Image loadPicture(String imageName) {
Image im = null;

// Load the image from the net
try {
URL imageSource = new URL(
"http://www.student.nada.kth.se/~d99-nro/" + imageName);

} catch (MalformedURLException e) {
}

return im;
}

// Load and play a sound from /usr/local/hacks/sounds/

public void playSound(String name) {
URL u = null;

try {
u = new URL("file:" + "/usr/local/hacks/sounds/" + name + ".au");
} catch (MalformedURLException e) {
}

AudioClip a = Applet.newAudioClip(u);
a.play();
}

public static void main(String[] args) {

java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AppSettings settings = new AppSettings(true);
settings.setWidth(850);
settings.setHeight(440);

Dungeon3D canvasApplication = new Dungeon3D();
canvasApplication.setSettings(settings);
canvasApplication.createCanvas(); // create canvas!
JmeCanvasContext ctx = (JmeCanvasContext) canvasApplication
.getContext();
ctx.setSystemListener(canvasApplication);
Dimension dim = new Dimension(640, 480);
ctx.getCanvas().setPreferredSize(dim);

JFrame window = new JFrame("Swing Application");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// JPanel panel = new JPanel(new FlowLayout()); // a panel
JPanel panel = new JPanel(new BorderLayout()); // a panel
World world = new DungeonWorld(canvasApplication);
Person me = new Person(world, "You", null);
PlaceView placeview = new PlaceView(me);
Commands commands = new Commands(me);
TextArea textarea = new TextArea("", 10, 60,
TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.append("You are in a dungeon. The horrible shrieks of the undead chill your bones.\n");
textarea.setEditable(false);
panel.add("West", ctx.getCanvas());
panel.add("East", commands);
panel.add("South", textarea);

// add all your Swing components ...
// panel.add(new JButton("Some Swing Component"));

// add the JME canvas
// panel.add(ctx.getCanvas());
window.add(panel);
window.pack();
window.setVisible(true);
canvasApplication.startCanvas();

}
});

}

@Override
public void simpleInitApp() {

// activate windowed input behaviour
flyCam.setDragToRotate(true);
// Set up inputs and load your scene as usual

Spatial teapot = assetManager.loadModel("Models/Teapot/Teapot.obj");
Material mat_default = new Material(assetManager,
"Common/MatDefs/Misc/ShowNormals.j3md");
teapot.setMaterial(mat_default);
rootNode.attachChild(teapot);

// Create a wall with a simple texture from test_data
Box box = new Box(Vector3f.ZERO, 2.5f, 2.5f, 1.0f);
Spatial wall = new Geometry("Box", box);
Material mat_brick = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md");
mat_brick.setTexture("ColorMap", assetManager
.loadTexture("Textures/Terrain/BrickWall/BrickWall.jpg"));
wall.setMaterial(mat_brick);
wall.setLocalTranslation(2.0f, -2.5f, 0.0f);
rootNode.attachChild(wall);

// Display a line of text with a default font
guiNode.detachAllChildren();
guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
BitmapText helloText = new BitmapText(guiFont, false);
helloText.setSize(guiFont.getCharSet().getRenderedSize());
helloText.setText("Hello World");
helloText.setLocalTranslation(300, helloText.getLineHeight(), 0);
guiNode.attachChild(helloText);

// Load a model from test_data (OgreXML + material + texture)
Spatial ninja = assetManager.loadModel("Models/Ninja/Ninja.mesh.xml");
ninja.scale(0.05f, 0.05f, 0.05f);
ninja.rotate(0.0f, -3.0f, 0.0f);
ninja.setLocalTranslation(0.0f, -5.0f, -2.0f);
rootNode.attachChild(ninja);
// You must add a light to make the model visible
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
rootNode.addLight(sun);

}

}

20111205

Software for iPhone, iPad, iOS


Hello
My friend Urban (ui.beam) has done the graphics for a Christmas application for Apple for kids I propose we take a look at
http://itunes.apple.com/nz/app/ackemos-christmas-tree/id482039230?l=sv&ls=1&mt=8
If you have iPad och iPhone I think you should try it, especially if you have kids who like christmas. I think the graphics are very good. What do you think? I don't think I can run it since I don't have an Apple computer but maybe you do? I note that there are many people who can do graphics while not many know how to implement a design / layout with a programmed layoutmanager or CSS as in the web case. I'm still learning how to align graphic component with no tables and CSS instead. It's actually quite practical and I think CSS is much better than Javascript since CSS responds much quicker and can be interactive while Javascript can give you a flash of unstyled content that needs fixing with CSS.

I believe for Apple the implementation language is Objective-C which to me is an Apple lock-in ie to port it you have to rewrite all software to another environment such as MS XNA or likewise and that is something that should be done at the same time for all platforms. I mean if you're going to make both a Windows version and an Apple version then you should develop for multiple platforms at the same time. Do you agree? Apple is basically a BSD and the scenario appears to be that Apple owns Objective-C, Microsoft owns C#, Google owns python, Oracle owns Java and they all want to lock you to their platforms and in Aplpe's case they're selling you...hardware.

Cheers \n

20111104

Ted Valentin: Some nuggets from 24HBC

Ted Valentin: Some nuggets from 24HBC: 24 Hour Business Camp is over for this time. If you missed the pitch presentations you can see them here . Each team got one minute to pre...

Neogregious: Migrating an App to High-Replication Datastore on ...

Neogregious: Migrating an App to High-Replication Datastore on ...: Google's Appengine now gives you the choice between the original master-slave datastore, and the new high-replication datastore. In a nutshe...

20111101

GAE python 2.7 + jinja2 + i18n + WTForms

Moving from 2.6 to 2.7 may not sound like a big deal. Current system is python 2.6 + django and I propose python 2.7 + jinja2 + WTForms.

Even though we change the template editor, we can use old django translations that we worked on in I way I just tested and luckily this appeared to work subclassing the jinja environment and loading the django translation so we can have the best of both worlds - django's extensive translations and the 10-20 faster rendering of jinja2:

from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
class DjangoTranslator(object):

    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext
        self.ugettext = ugettext
        self.ungettext = ungettext

from jinja2 import Environment, FileSystemLoader
class DjangoEnvironment(jinja2.Environment):

    def get_translator(self, context):
        return DjangoTranslator()

jinja_environment = DjangoEnvironment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)

class I18NHandler(webapp2.RequestHandler):

    def initialize(self, request, response):
        webapp2.RequestHandler.initialize(self, request, response)
        self.request.COOKIES = Cookies(self)
        self.request.META = os.environ
        self.reset_language()

    def reset_language(self):

        # Decide the language from Cookies/Headers
        language = translation.get_language_from_request(self.request)
        translation.activate(language)
        self.request.LANGUAGE_CODE = translation.get_language()

        # Set headers in response
        self.response.headers['Content-Language'] = str(translation.get_language())

If you want you can inspect the working copy at http://jinja2wtforms.montaoproject.appspot.com
It listens to parameter hl eg  http://jinja2wtforms.montaoproject.appspot.com/?hl=pt will load the Portuguese translations and likewise.

Regards,
Niklas

20111022

GAE page editor

I'm making some proposals, my page editor just with appengine_admin that enables the area /admin and I can edit a variable and even though it's just HTML I suppose I could add an HTML editor.

I could also deploy a working version with CoderBuddy.com but then I must go to CoderBuddy to edit my site and my client wants to forget about who is hosting so a builtin admin ui is kind of required

The option to import RSS from a blog is very interesting, I didn't think of it and it's a good solution but maybe it is going to be slow if I don't cache it. Also saving HTML files to the blobstore seems very nice but could be overkill for the simple legacy site that I'm migrating to appspot since something small and self-contained might be the best solution.

So my solution with appengine_admin is something like this and it actually enables editing HTML given a page ID:

class Page(db.Model):
  body = db.TextProperty(required=True)

class AdminPage(appengine_admin.
ModelAdmin):

    model = Page
    listFields = (
        'body',
        )
    editFields = (
        'body',
        )

    ('/page/([0-9]+)', PageHandler),

class PageHandler(BaseHandler):
  def get(self, file_id):
    page = Page.get_by_id(long(file_id))
    if not page:
      self.error(404)
      return
    self.render_template(file_id+'.html', {
        'body': page.body,
    })

1.html:

test
{{body}}

20110719

Cloud computing benchmark

Traditional Setup
100ms from End user to infrastructure.
180ms to pass the load balancer
150ms for Apache/Php/Java to start working on the request (out put hello world)
150ms for SQL to start working on a request
200ms to get the SQL request
100ms to write and send to user.

Total time 880ms to server text out of a database as HTML

GAE
100ms from End user to infrastructure.
35ms to start working
75ms to retrieve via GQL
100 MS to send to user

Total time 305MS

20110702

Progress

The incident described here happened to our project too:
http://code.google.com/p/googleappengine/issues/detail?id=4384
So there seems to be 2 ways to go and both will work. If you want to follow the project we just updated and refreshed instanced complying towards django 1.2 and google app engine 1.5.1. The way I get a fresh copy of the project is using mercurial like this

ubuntu@ubuntu:~$ cd /media/Lexar/
ubuntu@ubuntu:/media/Lexar$ hg clone https://niklasro@montao.googlecode.com/hg/ montao
warning: montao.googlecode.com certificate with fingerprint a9:be:c0:4a:da:1c:eb:4c:31:9d:78:27:48:99:f4:9c:9a:e8:53:c8 not verified (check hostfingerprints or web.cacerts config setting)
efterfrågar alla ändringar
lägger till ändringar
lägger till manifest
lägger till filändringar
lade till 207 ändringar med 2837 modifikationer i 2070 filer (+3 huvuden)
uppdaterar till grenen default
1542 filer uppdaterade, 0 filer sammanfogade, 0 filer raderade, 0 filer olösta
ubuntu@ubuntu:/media/Lexar$

This way I can keep development on a USB stick. There is a rather new feature we can buy that's called "Always On" - do you know what it does and if it's worth it? This week I posted a question on software here: http://stackoverflow.com/questions/6545853/class-methods-vs-instance-methodsThere was some technical problem that now seems resolved around updating to django 1.2 with google app engine as we sandby for more challenges having good growth this year compared to last year, growth that is good in relative terms that can affect a project valuation. Naturally we could use a "makeover" escpecially for the Brazilian parts of the app where usage dimished. What's very good with the newer deployments is that large object get saved to the app engine in an overseeable way (not too complicated code like we had with the Java deployment that had too many special cases and too low abstraction level). There is an option called Always on that we can discuss whether we want or need:
Always On $0.30 per day ($9.00 per month) Learn more

Ideas and challenges - just let us know! One resource to look at is montao.googlecode.com where we link to other projects.

20101205

GAE forms

To validate a form one could validate with javascript clientside. I too want form validation, preview, blobstore, i18n and edit items preferably with no thirdparty libraries so trying to learn how with a Form class with BlobStore blobs I got this in the upload handler ie a BlobstoreUploadHandler that uploads a blobstore blob using a form class ...
blob_info = self.get_uploads()[0] 
data = AForm(data=self.request.POST) 
entity = data.save(commit=False) 
entity.put() 
im = Image(reference=entity) 
im.primary_image = blob_info.key() 
im.put() entity.put()
... Dispatching to upload handling is a view class that renders self.render_template("upload.html", { 'form': form, 'form_url': blobstore.create_upload_url('/fileupload'),
Then I enabled the form page to also able to edit an item
if self.request.get('id'): 
a = A.get_by_id(long(self.request.get('id'))) 
form = AForm(instance = a) 
else: form = AForm() 
After that I too have issues with validation and preview where BlobStore seems doable to fit in a form.
My form class is
class AForm(djangoforms.ModelForm): 
text = forms.CharField(widget=forms.Textarea(attrs={'rows':'11','cols':'70','class':'foo'}),label=_("content").capitalize()) 
class Meta: 
model = A 
fields = ['category','currency','price','title','phonenumber','postaladress','name','text','email'] #change the order
I now hope we can recommend or comment how to enable validation and preview the "official" way. Since django.contrib.formtools.preview appears built in GAE it could be good to first try what the SDK provides to minimize thirdparty library dependency. I didn't look at formish yet and will do so onwards.

20100918

CSS, tables or images?

Advantages using css instead of table and files * CSS is for information and tables for data (fuzzy which is which) * CSS you can enlarge infinitely since it's code * CSS you can make multilingual easily just input the text * Also simple to change colors Do you agree or propose otherwise?

20100905

Solar Energy

The cleanest form of energy for our planet also renews itself daily. Historically the challenge has been its efficiency rate, i.e. the energy output compared to the solar energy input, which has been uncommercially low. This is now changing as new materials yield substantial improvements. As a consequence the interest quickly grows for solar energy as a serious alternative source of energy and manufacturers of solar energy panels, such as REC, are consequently experiencing steep increases in demand for their products. Commercial applications are now appearing also in relatively sun-poor countries like Germany and Norway. Presumably the sunshine in the Sahara deserts could be used to build large solar cell facilities that can produce great quantities of energy, free from pollution. If only 4 % of the world's deserts could be covered with solar cells, theoretically the whole global energy consumption could be satisfied. The problem is the cost. Solar cell facilities are expensive and most users live far away from deserts. It's expensive to lay wire or build high voltage lines. Unstable political relations are further reasons why the sahara still has no solar cell facilities, but they probably will come. The International Energy Agency, IEA, has formed a group to analyze solar cell plants in the saharan desert. The first attempts at large solar cell areas in the desert are now being tested. A 644 MW-facility in the Nevada desert in the USA was opened in June 2007 and in the United Arab Emirates a plant is built to provide 10 000 homes with power. These solar energy plants are facilities using solar energy to generate electricity with turbine-driven generators (thermal solar plants) or with solar cells. In thermal solar plants sunlight is used to generate current with conventional steam turbine technology. To reach high temperatures sun-following large mirrors are used on statives (heliostater). The mirrors reflect and concentrate the direct sunshine to an absorber on top of a solar tower. There water is heated to high temperatur and generates steam. Alternatively a so-called parabolic collector with steam pipes can produce the steam. The steam is then led to a turbine connected to a generator where electronic current is finally generated. So far the largest thermal solar plants were built in California where 2.7 billion square meters of parabolic collectors are gathering 430 MW (megawatt) electronic current. Production of current for the electronic power grid from thermal solar plants or solar cell based plants that lead to profitability is still far despite the large growth in the solar cell market. In the beginning of the 21st century the solar cell market grew about 25 % every year on average and in 2005 the production capacity rose above 1000 MW corresponding to 10 million square meters a year. The largest market is in Germany which through legislation created incentives to invest in new facilities where anybody can become producer of electronic power. 60 % of the solar cells were installed in Europe and 30 % in Asia. Currently solar electricity from solar cells is about five times costlier than conventional electricity from the net, but the gap is decreasing due to increasing electricity prices and decreasing production costs for solar cells.

20100831

Online sources

Online mainly 2 income sources are doable 1) Advertising 2) Direct payments we didn't yet enable So here's some nr 1 data we can manipulate (eg stretch/squeeze "time" to reach 2 %) for our Montao and Kool Business projects, hoping you all stay well with me starting this an open less technically detailed more usabilityfocused discussion if/how languages, functions, modules or components prioritize. Does UML define priorities other than sequence diagrams? Should we reference UML at all? Alternatives? Is the observation general that that php and .net are more successful ? Does it depend on using a large or small projects etc. Online version is Language: en ar bn ca cs cy da de el es es_AR fi fr gl hu he is it ja kn lv mk nl no pl pt pt-br ro ru sk sl sr sv ta te tr uk zh-cn zh-tw Draft wiki page very general "view ad" ViewAd User views ad Introduction¶ Initiator:user Details¶ * Precondition * Postcondition Vill vi att montao eller koolbusiness.com ska kunna byta språk? Hur? Till vilka? Dokumentation underlättar. Koolbusiness.com och Montao.com.br har inte samma språkfunktion Montao.com.br avsiktligt inte har.

20100813

Exact Physics

Far better exactly answering the right question than an approximate answer to the wrong question.

20100625

Live life scheme

(defun run-life-on (filename)
 (with-current-buffer (get-buffer-create filename)
 (life)
 (write-file filename)
(setq quit-flag 1)))

20100224

Solve "BUFFER OVERFLOW"

2. IRQ 3. Define working environment

PHYSICS


Energi: E= mv2 / 2(rörelseenergi)E =hf =  hc  / λ,p= hf  / c (fotoner, p=rörelsemängd), E=mc2, 1eV=J
Δλ= h / mc(1 - cos Φ(comptonskift för våglängd, m=massa hos målpartikel), λ = h/ p (deBroglie, materievågor)
d2Ψ /dx2 +2m / h2[E-U(x)]Ψ = 0 (Schrödinger, U(x)=pot. energi från omgivning, E=partikels tot. energi, Ψ=vågfkt.)
Fri partikel:d2Ψ /dx2 +( /λ)2Ψ = 0 (U(x)=0, λ=deBroglie). Allm. lösn: Ψ(x) = Aeikx + Be-ikx , |Ψ|2 dx= 1
Δx ·Δpx ≥η,ΔE·Δt≥η , En =(h2  /8mL2)n2  Ψn(x)= (2/L)½sin(   /Lx) (elektron i pot. brunn, L=bredd, n=kv.tillst.),

hopp: ΔE =[hf ]=Ehög-Elåg, Väte: P(r)=r2e-2r/a4/a(elektr. rad. sannolikhet, a)


Atomer: n (huvudkv.tal),1 (0..n-1), ml (magn. -1..1), ms (spinn, -½, ½), 1:0=s, 1=p, 2=d, 3=f... (n=2, l=3 ⇒ 2f)
Laser: Stimulerad utsändning av fotoner. Strålning hf = Ex - E0 stimulerar atom att gå från högre energi till lägre,
och stimulerande + utsänd atom = laser. Det måste finnas fler atomer i över energ.tillst. än i det lägre.

n-dopning, 1+ elektronen vandrar, p-dopning, 1-, hålet vandrar.
R = R0e-λt (radioaktiv sönderfallstakt, -dN/dt, λ=sönderfallskonstant, T½ = ln2/λ), r = r0A1/3 (atomens medelradie)
α-sönderfall: 4He sänds ut, β-sönderfall: n → p+e- + νe (N=N-1)
Bindningsenergi/nukleon:E=ΔEbind / A, där ΔEbind = Σ (mc2)- Mc2  (nukleonernas massa är större än atomens)

Fission: Q= bindningsenergi slut - bindningsenergi start, neutroner krockar och knuffar atomer upp
till instabila isotoper som sönderfaller. Vid kedjereaktion frigörs fler neutroner än som tas upp.

Fusion: 2
1H2H+e+e (e+ +e- →2γ), 2H+1H3H + γ, 23H→4H+21H (proton-proton, Q)

Partiklar: Fermion=halvtaligt spinn, Boson=heltaligt spinn. Hadron=stark kraft, Lepton=svag kraft. Ferm:1/kv.tal
Hadron&Boson=Meson, Hadron&Fermion=Baryon
Leptoner: Leptontalet för varje familj ( e--,τ- ) bevaras i varje reaktion, så också för baryontal och särhet.

Family
Ferm/Bos
Hadr/Lept
Charge
Strange
Lepton number
Baryon number
Anti
e--,τ-
F
L
-1

1
0
e+++
p
F
H
+1
0
0
1
p-
n
F
H
0
0
0
1

Σ +,0, -
F
H
1,0,-1
-1
0
1

Ξ 0, -
F
H
0,-1
-2
0
1

π +,0, -
B
H
1,0,-1
0
0
0


Quark
Charge
Strange
Baryon number all +
Spin all ½
up
+
0


down
-
0


charm
+
0


strange
-
-1


top
+
0


bottom
-
0



Varje baryon är en komb. av 3 kvarkar, varje meson är ett kvark-antikvark-par. Elektromagnetisk kraft: Utbytande av virtuella fotoner. Svag kraft: Bärare - W och L (tunga!), W är + eller -. Stark kraft: Bärare - Gluoner. I propose ternary even 25:75,25:25:50=50:50 1 known,seen or heard(difference)(1),2 models angular and/or blank,empty or static 8,t²/(1-v/c)², 1=cosh2x-sinh2x, generating function, carrier, magnetindependent, timeindependent (why=always), substance=no, blank, 0 or minimal numbers=automatic ⊗:A,B=0,75,tensor(1/75) split/fuse, ⋘1 Hubble: v = Hr (r=avstånd). Bakgrundsstrålning: Strålning från när universum blev 1eV=1.6*10⁻¹⁹ J, Q=12.86 MeV, a=5.29*10⁻¹¹ m, En=-13.6 eV/n² ?critical mass relative out 75 % bindande verkan non-relative (142%>)109 % de facto > same 10 over & over



20100219

✈dfly live

getting 109 % capacity. What's 75 %

system   Size   Fused  Avail Capacity  Mount

0        16M     16M  -1.2M  109% 
Yellow meeting room Alin Drimus, …

mekatronik


(Not otherwise) specified Dear whomever, if knowlegable how to enable Novatel HSDPA (3G) or lose the beep when tabbing eg /sbin/dhclient, then kindly inform how. Here's df -h, pciconf -lf and a link to this dragonflybsd/niklas with thanks to all BSD R&D
Filesystem Size Used Avail Capacity Mounted on
cd0c 1.2G 1.2G 0B 100% /
/dev/mfs70 16M 4.7M 9.8M 32% /root
/dev/mfs72 124M 17M 97M 15% /var
/dev/mfs74 7.8M 8.0K 7.2M 0% /tmp
/dev/mfs76 12M 9.7M 1.1M 89% /etc
/dev/mfs78 3.0M 90K 2.6M 3% /dev
/dev/mfs80 3.9M 6.0K 3.6M 0% /usr/local/etc
/dev/mfs82 3.9M 4.0K 3.6M 0% /var/db/xkb
procfs 4.0K 4.0K 0B 100% /proc
Copyright (c) 2003-2009 The DragonFly Project.
Copyright (c) 1992-2003 The FreeBSD Project.
Copyright (c) 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994
The Regents of the University of California. All rights reserved.
DragonFly 2.2.0-RELEASE #0: Sun Feb 15 17:55:25 PST 2009
root@pkgbox.dragonflybsd.org:/build/usr.obj/usr/src/sys/DFLYLIVE
TSC clock: 2394009240 Hz, i8254 clock: 1193186 Hz
CPU: Intel(R) Core(TM)2 Duo CPU T7700 @ 2.40GHz (2394.02-MHz 686-class CPU)
Origin = "GenuineIntel" Id = 0x6fb Stepping = 11
Features=0xbfebfbff
Features2=0xe3bd
Hyperthreading: 2 logical CPUs
real memory = 3756367872 (3668328K bytes)
avail memory = 3637329920 (3552080K bytes)
Preloaded elf kernel "/boot/kernel" at 0xc0809000.
Preloaded elf module "/boot/modules/acpi.ko" at 0xc08092ec.
Pentium Pro MTRR support enabled
md0: Malloc disk
pcibios: BIOS version 2.10
Using $PIR table, 13 entries at 0xc00fa570
ACPI: RSDP @ 0x0xfbb10/0x0024 (v 2 DELL )
ACPI: XSDT @ 0x0xdfe5d200/0x0064 (v 1 DELL M08 0x27D80C0B ASL 0x00000061)
ACPI: FACP @ 0x0xdfe5d09c/0x00F4 (v 4 DELL M08 0x27D80C0B ASL 0x00000061)
ACPI: DSDT @ 0x0xdfe5d800/0x63B2 (v 2 INT430 SYSFexxx 0x00001001 INTL 0x20050624)
ACPI: FACS @ 0x0xdfe6c000/0x0040
ACPI: HPET @ 0x0xdfe5d300/0x0038 (v 1 DELL M08 0x00000001 ASL 0x00000061)
ACPI: APIC @ 0x0xdfe5d400/0x0068 (v 1 DELL M08 0x27D80C0B ASL 0x00000047)
ACPI: ASF! @ 0x0xdfe5d000/0x007E (v 32 DELL M08 0x27D80C0B ASL 0x00000061)
ACPI: MCFG @ 0x0xdfe5d3c0/0x003E (v 16 DELL M08 0x27D80C0B ASL 0x00000061)
ACPI: TCPA @ 0x0xdfe5d700/0x0032 (v 1 0x00000000 ASL 0x00000000)
ACPI: SLIC @ 0x0xdfe5d49c/0x0176 (v 1 DELL M08 0x27D80C0B ASL 0x00000061)
ACPI: SSDT @ 0x0xdfe5b97e/0x04CC (v 1 PmRef CpuPm 0x00003000 INTL 0x20050624)
npx0:  on motherboard
npx0: INT 16 interface
Using XMM optimized bcopy/copyin/copyout
acpi0:  on motherboard
ACPI: SSDT @ 0x0xdfe6c080/0x0043 (v 1 LMPWR DELLLOM 0x00001001 INTL 0x20050624)
Warning: ACPI is disabling APM's device. You can't run both
acpi_timer0: <24-bit timer at 3.579545MHz> port 0x1008-0x100b on acpi0
cpu0:  on acpi0
ACPI: SSDT @ 0x0xdfe5be4a/0x05E5 (v 1 PmRef Cpu0Cst 0x00003001 INTL 0x20050624)
ACPI: SSDT @ 0x0xdfe5c4b4/0x02C8 (v 1 PmRef Cpu0Ist 0x00003000 INTL 0x20050624)
acpi_tz0:  on acpi0
acpi_lid0:  on acpi0
acpi_button0:  on acpi0
acpi_button1:  on acpi0
acpi_acad0:  on acpi0
battery0:  on acpi0
battery1:  on acpi0
atkbdc0:  port 0x66,0x62,0x64,0x60 irq 1 on acpi0
atkbd0:  flags 0x1 irq 1 on atkbdc0
kbd0 at atkbd0
psm0:  irq 12 on atkbdc0
psm0: model GlidePoint, device ID 0
sio0 port 0x3f8-0x3ff irq 4 on acpi0
sio0: type 16550A
legacypci0 on motherboard
pcib0:  on legacypci0
pci0:  on pcib0
pcib1:  at device 1.0 on pci0
pci1:  on pcib1
pci1:  at 0.0 irq 5
uhci0:  port 0x6f20-0x6f3f irq 11 at device 26.0 on pci0
usb0:  on uhci0
usb0: USB revision 1.0
uhub0:  on usb0
uhub0: 2 ports with 2 removable, self powered
uhci1:  port 0x6f00-0x6f1f irq 10 at device 26.1 on pci0
usb1:  on uhci1
usb1: USB revision 1.0
uhub1:  on usb1
uhub1: 2 ports with 2 removable, self powered
pci0:  at 26.7 irq 9
pci0:  (vendor=0x8086, dev=0x284b) at 27.0 irq 10
pcib2:  at device 28.0 on pci0
pcib2: Disable PCI Express hot-plug interrupts(0x0008)
pci11:  on pcib2
pcib3:  at device 28.1 on pci0
pcib3: Disable PCI Express hot-plug interrupts(0x0008)
pci12:  on pcib3
pci12:  (vendor=0x14e4, dev=0x4328) at 0.0 irq 3
pcib4:  at device 28.3 on pci0
pcib4: Disable PCI Express hot-plug interrupts(0x0008)
pci13:  on pcib4
pcib5:  at device 28.5 on pci0
pcib5: Disable PCI Express hot-plug interrupts(0x0008)
pci9:  on pcib5
bge0:  mem 0xf1bf0000-0xf1bfffff irq 3 at device 0.0 on pci9
bge0: CHIP ID 0xa0020000; ASIC REV 0x0a; CHIP REV 0xa0; PCI-E
miibus0:  on bge0
brgphy0:  on miibus0
brgphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, 1000baseT, 1000baseT-FDX, auto
bge0: MAC address: 00:1d:09:ac:e2:3e
uhci2:  port 0x6f80-0x6f9f irq 11 at device 29.0 on pci0
usb2:  on uhci2
usb2: USB revision 1.0
uhub2:  on usb2
uhub2: 2 ports with 2 removable, self powered
uhci3:  port 0x6f60-0x6f7f irq 10 at device 29.1 on pci0
usb3:  on uhci3
usb3: USB revision 1.0
uhub3:  on usb3
uhub3: 2 ports with 2 removable, self powered
uhci4:  port 0x6f40-0x6f5f irq 9 at device 29.2 on pci0
usb4:  on uhci4
usb4: USB revision 1.0
uhub4:  on usb4
uhub4: 2 ports with 2 removable, self powered
pci0:  at 29.7 irq 11
pcib6:  at device 30.0 on pci0
pci3:  on pcib6
cbb0:  at device 1.0 on pci3
cardbus0:  on cbb0
pccard0: <16-bit PCCard bus> on cbb0
pcib6: routed slot 1 INTA to irq 255
cbb: Unable to map IRQ...
device_probe_and_attach: cbb0 attach returned 12
fwohci0: vendor=1217, dev=f7
fwohci0: <1394 Open Host Controller Interface> mem 0xf1afe800-0xf1afefff,0xf1aff000-0xf1afffff irq 9 at device 1.4 on pci3
fwohci0: OHCI version 1.10 (ROM=0)
fwohci0: No. of Isochronous channel is 8.
fwohci0: EUI64 47:4f:c0:00:02:6a:ac:70
fwohci0: Phy 1394a available S400, 1 ports.
fwohci0: Link S400, max_rec 2048 bytes.
firewire0:  on fwohci0
fwe0:  on firewire0
fwe0: MAC address: 46:4f:c0:6a:ac:70
sbp0:  on firewire0
fwohci0: Initiate bus reset
fwohci0: node_id=0xc800ffc0, gen=1, CYCLEMASTER mode
firewire0: 1 nodes, maxhop <= 0, cable IRM = 0 (me)
firewire0: bus manager 0 (me)
isab0:  at device 31.0 on pci0
isa0:  on isab0
atapci0:  port 0x6fa0-0x6faf,0x376,0x170-0x177,0x3f6,0x1f0-0x1f7 irq 5 at device 31.1 on pci0
ata0:  on atapci0
uhub5:  on uhub4
uhub5: 4 ports with 3 removable, self powered
acd0: DVDR  at ata0-master UDMA33
ata1:  on atapci0
atapci1:  port 0xeff0-0xefff,0x6ee0-0x6eef,0x6ec8-0x6ecb,0x6ec0-0x6ec7,0x6eb8-0x6ebb,0x6eb0-0x6eb7 irq 10 at device 31.2 on pci0
ata2:  on atapci1
ata3:  on atapci1
pci0:  (vendor=0x8086, dev=0x283e) at 31.3 irq 3
eisa0:  on motherboard
mainboard0:  on eisa0 slot 0
pmtimer0 on isa0
fdc0: ready for input in output
fdc0: cmd 3 failed at out byte 1 of 3
vga0:  at port 0x3c0-0x3df iomem 0xa0000-0xbffff on isa0
sc0:  at flags 0x100 on isa0
sc0: VGA <16 virtual consoles, flags=0x300>
sio2: can't drain, serial port might not exist, disabling
ppc0: parallel port not found.
ugen0:  on uhub0
ugen1:  on uhub1
ugen2:  on uhub5
Mounting root from cd9660:cd0c
cd0 at ata0 bus 0 target 0 lun 0
cd0:  Removable CD-ROM SCSI-0 device
cd0: 33.000MB/s transfers
cd0: cd present [619632 x 2048 byte records]

hostb0@pci0:0:0: class=0x060000 card=0x01fe1028 chip=0x2a008086 rev=0x0c hdr=0x00
vendor = 'Intel Corporation'
device = 'Mobile PM965/GM965/GL960 Express Processor to DRAM Controller'
class = bridge
subclass = HOST-PCI
pcib1@pci0:1:0: class=0x060400 card=0x00000088 chip=0x2a018086 rev=0x0c hdr=0x01
vendor = 'Intel Corporation'
device = 'Mobile PM965/GM965/GL960 Express PCIe Root Port'
class = bridge
subclass = PCI-PCI
uhci0@pci0:26:0: class=0x0c0300 card=0x01fe1028 chip=0x28348086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB UHCI #4'
class = serial bus
subclass = USB
uhci1@pci0:26:1: class=0x0c0300 card=0x01fe1028 chip=0x28358086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB UHCI #5'
class = serial bus
subclass = USB
none0@pci0:26:7: class=0x0c0320 card=0x01fe1028 chip=0x283a8086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '81EC1043 (?) ICH8 Enhanced USB2 Enhanced Host Controller'
class = serial bus
subclass = USB
none1@pci0:27:0: class=0x040300 card=0x01fe1028 chip=0x284b8086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H Intel audio controller embedded with the 82801H chipset ( ICH8 chipset )'
class = multimedia
pcib2@pci0:28:0: class=0x060400 card=0x00000040 chip=0x283f8086 rev=0x02 hdr=0x01
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) PCIe Port 1'
class = bridge
subclass = PCI-PCI
pcib3@pci0:28:1: class=0x060400 card=0x00000040 chip=0x28418086 rev=0x02 hdr=0x01
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) PCIe Port 2'
class = bridge
subclass = PCI-PCI
pcib4@pci0:28:3: class=0x060400 card=0x00000040 chip=0x28458086 rev=0x02 hdr=0x01
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) PCIe Port 4'
class = bridge
subclass = PCI-PCI
pcib5@pci0:28:5: class=0x060400 card=0x00000040 chip=0x28498086 rev=0x02 hdr=0x01
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) PCIe Port 6'
class = bridge
subclass = PCI-PCI
uhci2@pci0:29:0: class=0x0c0300 card=0x01fe1028 chip=0x28308086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB UHCI #1'
class = serial bus
subclass = USB
uhci3@pci0:29:1: class=0x0c0300 card=0x01fe1028 chip=0x28318086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB UHCI #2'
class = serial bus
subclass = USB
uhci4@pci0:29:2: class=0x0c0300 card=0x01fe1028 chip=0x28328086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB UHCI #3'
class = serial bus
subclass = USB
none2@pci0:29:7: class=0x0c0320 card=0x01fe1028 chip=0x28368086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) USB2 EHCI #1'
class = serial bus
subclass = USB
pcib6@pci0:30:0: class=0x060401 card=0x00000050 chip=0x24488086 rev=0xf2 hdr=0x01
vendor = 'Intel Corporation'
device = '82801 Family (ICH2/3/4/5/6/7/8/9-M) Hub Interface to PCI Bridge'
class = bridge
subclass = PCI-PCI
isab0@pci0:31:0: class=0x060100 card=0x01fe1028 chip=0x28158086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801HEM (ICH8M-E) LPC Interface Controller'
class = bridge
subclass = PCI-ISA
atapci0@pci0:31:1: class=0x01018a card=0x01fe1028 chip=0x28508086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) Ultra ATA Storage Controllers'
class = mass storage
subclass = ATA
atapci1@pci0:31:2: class=0x01018f card=0x01fe1028 chip=0x28288086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801 (ICH8M) 3 port SATA Controller'
class = mass storage
subclass = ATA
none3@pci0:31:3: class=0x0c0500 card=0x01fe1028 chip=0x283e8086 rev=0x02 hdr=0x00
vendor = 'Intel Corporation'
device = '82801H (ICH8 Family) SMBus Controller'
class = serial bus
subclass = SMBus
none4@pci1:0:0: class=0x030000 card=0x01fe1028 chip=0x042910de rev=0xa1 hdr=0x00
vendor = 'Nvidia Corp'
device = 'Unknown nVidia Quadro FX 570M'
class = display
subclass = VGA
none5@pci12:0:0: class=0x028000 card=0x000a1028 chip=0x432814e4 rev=0x03 hdr=0x00
vendor = 'Broadcom Corporation'
device = 'BCM94321KFBG Broadcom 4321AGN 802.11a/b/g/draft-n Wi-Fi Solution'
class = network
bge0@pci9:0:0: class=0x020000 card=0x01fe1028 chip=0x167314e4 rev=0x02 hdr=0x00
vendor = 'Broadcom Corporation'
device = 'NetXtreme BCM5755M Gigabit Ethernet PCIe'
class = network
subclass = ethernet
cbb0@pci3:1:0: class=0x060700 card=0x01fe1028 chip=0x71351217 rev=0x21 hdr=0x02
vendor = 'O2 Micro Inc'
device = 'OZ711EZ1 MemoryCardBus Controller'
class = bridge
subclass = PCI-CardBus
fwohci0@pci3:1:4: class=0x0c0010 card=0x01fe1028 chip=0x00f71217 rev=0x02 hdr=0x00
vendor = 'O2 Micro Inc'
device = '0x00f71217 1394 Open Host Controller Interface'
class = serial bus
subclass = FireWire

20100207

LSL

Solution is whether listener or observer is self (de se) or central (de re).

20091229

20091114

DragonFly BSD

mainly all good results.
             
agp0@pci0:0:0:0:        class=0x060000 card=0x00000000 chip=0x71908086 rev=0x03           
hdr=0x00
    vendor     = 'Intel Corporation'
    device     = '82443BX/ZX 440BX/ZX CPU to PCI Bridge (AGP Implemented)'
    class      = bridge
    subclass   = HOST-PCI
pcib1@pci0:0:1:0:       class=0x060400 card=0x00000000 chip=0x71918086 rev=0x03           
hdr=0x01
    vendor     = 'Intel Corporation'
    device     = '82443BX/ZX 440BX/ZX AGPset PCI-to-PCI bridge'
    class      = bridge
    subclass   = PCI-PCI
cbb0@pci0:0:3:0:        class=0x060700 card=0x00bb1028 chip=0xac1c104c rev=0x01           
hdr=0x02
    vendor     = 'Texas Instruments (TI)'
    device     = 'PCI1225 PC Card CardBus Controller'
    class      = bridge
    subclass   = PCI-CardBus
cbb1@pci0:0:3:1:        class=0x060700 card=0x00bb1028 chip=0xac1c104c rev=0x01           
hdr=0x02
    vendor     = 'Texas Instruments (TI)'
    device     = 'PCI1225 PC Card CardBus Controller'
    class      = bridge
    subclass   = PCI-CardBus
isab0@pci0:0:7:0:       class=0x068000 card=0x00000000 chip=0x71108086 rev=0x02           
hdr=0x00
    vendor     = 'Intel Corporation'
    device     = '82371AB/EB/MB PIIX4/4E/4M ISBridgeA'
    class      = bridge
atapci0@pci0:0:7:1:     class=0x010180 card=0x00000000 chip=0x71118086 rev=0x01           
hdr=0x00
    vendor     = 'Intel Corporation'
    device     = '82371AB/EB/MB PIIX4/4E/4M IDE Controller'
    class      = mass storage
    subclass   = ATA
uhci0@pci0:0:7:2:       class=0x0c0300 card=0x00000000 chip=0x71128086 rev=0x01           
hdr=0x00
    vendor     = 'Intel Corporation'
    device     = '82371AB/EB/MB PIIX4/4E/4M USB Interface'
    class      = serial bus
    subclass   = USB
none0@pci0:0:7:3:       class=0x068000 card=0x00000000 chip=0x71138086 rev=0x03           
hdr=0x00
    vendor     = 'Intel Corporation'
    device     = '82371AB/EB/MB PIIX4/4E/4M Power Management Controller'
    class      = bridge
none1@pci0:0:8:0:       class=0x040100 card=0x00bb1028 chip=0x1998125d rev=0x10           
hdr=0x00
    vendor     = 'ESS Technology'
ethernet, graphics and fluxbox chosen which work, python perfectly succeeded accordingly test or benchmark 2 browsers with zooming eg firefox, opera to test and windowmanagement, multimedia, diskless, physical limit, tougher appliances, loadbalancing, fw, physical experiments, localisation and internationalisation, some exotic symbols that need all functions, windowmanager, networking, very fast despite old hardware, responds impressively beating even expectation where 8 awaited zeroes insignificantly appear related to tty, no real error, blunder between logical 0 and physical 1. gnome build error, manual path updates needed.

20091112

physical proximity

[Valid KML 2.2]
             
 
proximity_fetch(News.all().filter("modified >",datetime.now()-timedelta(days=self.request.get('days'))).filter("published =",True).filter("modified <=",datetime.strptime(str(datetime.now())[:-7], "%Y-%m-%d %H:%M:%S")).order("-modified"),db.GeoPt(self.request.get('lat'),self.request.get('lon')),max_results=self.request.get('m'),max_distance=self.request.get('r'))
  

20091011

kml

[Valid KML 2.2]
             
        from django.template import defaultfilters              
        url = os.environ['HTTP_HOST'] if os.environ.get('HTTP_HOST') else os.environ['SERVER_NAME']               
        news= New.gql("where published = True and modified >:1 order by modified desc",datetime.datetime.now()-timedelta(days=days))                
        self.response.out.write('')
        for new in news:          
            if new.geopt:           
                if new.matched_images.get():
                    imageid=new.matched_images.get().key().id()  
                    kml = ('< ![CDATA[ %s ]]> %d,%d'
           ) %(url,new.matched_images.get().key().id(),new.matched_images.get().full_ext,''+new.title+'
'+defaultfilters.urlize(defaultfilters.truncatewords(new.text,20) ),new.geopt.lon,new.geopt.lat) else: kml = (' %d,%d' ) %(''+new.title+'
'+defaultfilters.urlize(defaultfilters.truncatewords( defaultfilters.striptags(new.text),20)),new.geopt.lon,new.geopt.lat) self.response.out.write(kml) self.response.out.write('
'

20090830

2 system development models

When all you know is wrong:
3:Do it wrong
2:Fix your wrong
1:Goto 3
When all you know is just:
2:Adjust to just
1:Goto 2

20090816

Layerwork

Easified 4 are emittables,moves,mods and views where middle 2 are logics.
3 parts to keep aside are logic (app layer and runnables), transport (formats and interfaces) and presentation (layouts). Linebreak convention easifies debugging (where 15 instructions or tags are good) while otherwise all on one row makes more professional depedency, if you want less choice.

20090812

Forward compliance and/or -patibility

// should mean "current protocol" for standard-independence. This way is more independent than tied to protocol.

20090810

sitemap generator

Old one "sitemap_gen.py" digs presentation (our projector and cabling) and logs (junk) where this goes straight storage to gz. Premise: /[id]/[title]
Comment: Premise rests on R&D opinion yet to standardize since viceversa (/[title]/[id]) is easier to remember but conflicts different items with same titles which can't keep uniqums

    url = os.environ['HTTP_HOST'] if os.environ.get('HTTP_HOST') else os.environ['SERVER_NAME']   
output = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" >'
for ad in Ad.gql("where published = True and modified >:1 order by modified desc", datetime.now() - timedelta (days = days)):
output = '%s<url><loc>http://%s/%d/%s</loc><lastmod>%s</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>' %( output, url,ad.key().id(),defaultfilters.slugify(ad.title),ad.modified.date())
output = '%s</urlset>' %output
self.response.headers['Content-Type'] = 'gzip'
self.response.headers['Content-Length'] = str(len(output))
self.response.out.write(compressBuf(output))

20090715

42 dialects languages got

SinسShinشKAFكFehفKhaFقLAMلMiMمNOONنAinعGhmغBبTتTheثGجHAحKhaخDALدZALذReرZenزTAHضZAHTodo: add .po custom xtras, korean, klingon, latin...
Fork
{% get_current_language as LANGUAGE_CODE %}{{ LANGUAGE_CODE }}{% get_available_languages as LANGUAGES %}{% for LANGUAGE in LANGUAGES %}{% ifnotequal LANGUAGE_CODE LANGUAGE.0 %}{{ LANGUAGE.0 }}{% endifnotequal %}{% endfor %}

_____________________
Left:Translate "Language"

20090601

Linearization or anything towards O(1/n)

Example usage: loadbalancing
Thesis: G(O(f(n)))=O(1)
Example: Switch models and at once O(n) is O(1)
Hence all computable calculations already can prepare O(1)
Trace physical spinmodel O(N)xO(m)

20090513

Convention

always arguments, always return a value, always ternary, always all reversible=invertible, avoid floats fancy Integers or LIFO buffer instead, avoid vector fancy lists and (dynamic) arrays instead, avoid interfaces (they were no function, just names) fancy inheritance instead, avoid switch/if/else and fancy : instead ie else, avoid checkbox / boolean even to return (keep ternaries where default=basecase) to facilitate typeconversions between {},None,'None',0,'0' , avoid concatenate fancy buffer instead, avoid the void, avoid threads or sync (200 Hz=sleep(5)) then:

action.do(data)
not:
action.new(data).do(moredata)
and predefine both local and global

20090508

research

Given f0,g1,g2,g3...find f so that f*g=...

20080529

Google analytics filter

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package filters;

import java.util.ResourceBundle;
import java.io.IOException;
import javax.servlet.*;

/**
*
* @author Niklas
*/
public class GAnalyticsFilter implements Filter {

public void destroy() {
}

public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setAttribute("analytics_id", ResourceBundle.getBundle("Application").getString("analytics_id"));
chain.doFilter(request, response);
}

public void init(FilterConfig filterConfig)
throws ServletException {
}
}

20080320

getareacodesbyadminarea or locality

//TODO iso standard compliance
public class AreaCodeBean extends ActionForm {
private Collection beanCollection = null;
private ArrayList categories = null;
private Collection acCollection = null;
private ArrayList aclist = null;
public ArrayList getAreacodes() {
Connection conn = null;
if (aclist == null) {
ArrayList entries = new ArrayList(40);
try {
conn = DBSettings.getConnection();
PreparedStatement ps = conn.prepareStatement("select ac from areacodes");
ResultSet rs = ps.executeQuery();
int i = 0;
while (rs.next()) {
entries.add(new LabelValueBean(rs.getString("ac"), rs.getString("ac")));
}
rs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
aclist = entries;
}
return aclist;
}

20080205

Make hyperlinks

             
import java.io.*;
import java.util.regex.*;
import org.apache.log4j.Logger;
public class RegexpMakeHyperlinks {
Logger log = Logger.getLogger(this.getClass());
/**
* Loads a file into a StringBuffer
* @param f File to read
* @return StringBuffer with contents of text file.
* @throws IOException
*/
public StringBuffer loadFile(File f) throws IOException {
log.debug("Reading file " + f.getAbsolutePath());
BufferedReader in = new BufferedReader(new FileReader(f));
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(new BufferedWriter(sw));
String line = null;
while ((line = in.readLine()) != null) {
pw.println(line);
}
pw.flush();
in.close();
return sw.getBuffer();
}
/**
* Writes the contents of a StringBuffer to file
* @param f File to write to
* @param sb Text to write to file
* @throws IOException
*/
public void writeToFile(File f, StringBuffer sb) throws IOException {
log.debug("Outputting to " + f.getAbsolutePath());
BufferedReader in = new BufferedReader(new StringReader(sb.toString()));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
String line = null;
while ((line = in.readLine()) != null) {
out.println(line);
}
out.flush();
in.close();
}
/**
* Converts all urls like "www.google.com" into hyperlinks in the text.
*
* @param initialText The text to convert
* @return Converted text.
*/
public StringBuffer convertText(StringBuffer initialText) {
StringBuffer result = new StringBuffer(initialText.length());
Pattern p = Pattern.compile("(@)?(href=')?(HREF=')?(HREF=\")?(href=\")?(http://)?[a-zA-Z_0-9\\-]+(\\.\\w[a-zA-Z_0-9\\-]+)+(/[#;@&\\n\\-=?\\+\\%/\\.\\w]+)?");
Matcher m = p.matcher(initialText);
while (m.find()) {
String href = m.group();
//log.debug("href:"+href);
if (href.startsWith("@")) {
continue;
}
// ignore links that are already hyperlinks
if (href.startsWith("href")) {
continue;
}
//TO DO: add more top domains
if (href.indexOf(".br") != -1 || href.indexOf(".com") != -1 || href.indexOf(".COM") != -1 || href.indexOf(".net") != -1 || href.indexOf(".org") != -1 || href.indexOf(".se") != -1 || href.indexOf(".pt") != -1 || href.indexOf(".es") != -1) {
if (!href.startsWith("http://") && !href.startsWith("HTTP://")) {
// add on the http:// if necessary
m.appendReplacement(result, "" + href + "");
} else {
m.appendReplacement(result, "" + href + "");
}
}
}
m.appendTail(result);
return result;
}
/**
* Testing method for experimenting with the patternmatching
* @param text
*/
public void matchLink(String text) {
Pattern p = Pattern.compile("(http://)?www\\..*?.com\\b");
Matcher m = p.matcher(text);
while (m.find()) {
log.debug("Found: " + m.group());
}
}
}