mediawiki user language recognition

March 3rd, 2010 thomas No comments

so i had the problem, that there was a multilingual mediawiki installation with lot of translations. So far so good, the user could select the appropriate language if he visited the Base English page. So i was wondering if there was a tool that tries to detect the users browser language and act upon that. To my surprise there was none that could be used easily in the way i needed it to be :-\

So i added some parts to the Polyglot extension so it redirects the user to the correct page. What i changes is really trivial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        $accept = @$_SERVER["HTTP_ACCEPT_LANGUAGE"];
        $redir=false;
        if(!empty($accept))
        {
                $accept = explode( ',', $accept );
                foreach($accept as $ulang)
                {
                        $ulanga = explode( '-', $ulang );
                        $tu = Title::makeTitle( $ns, $n . '/' . $ulanga[0] );
                        if($tu->exists())
                        {
                                $t = $tu;
                                $redir=true;
                                break;
                        }

                }
        }

not really difficult ;)

example pages (works if your first browser language is not English …):
http://wiki.rigsofrods.com/pages/Portal
or:
http://wiki.rigsofrods.com/pages/Truck_Description_File

the whole file for your usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php
/**
 * Polyglot extension - automatic redirects based on user language
 *
 * Features:
 *  * Magic redirects to localized page version
 *  * Interlanguage links in the sidebar point to localized local pages
 *
 * This can be combined with LanguageSelector and MultiLang to provide more internationalization support.
 *
 * See the README file for more information
 *
 * @package MediaWiki
 * @subpackage Extensions
 * @author Daniel Kinzler, brightbyte.de
 * @copyright © 2007 Daniel Kinzler
 * @licence GNU General Public Licence 2.0 or later
 */


if( !defined( 'MEDIAWIKI' ) ) {
        echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
        die( 1 );
}

$wgExtensionCredits['other'][] = array(
        'path' => __FILE__,
        'name' => 'Polyglot',
        'author' => 'Daniel Kinzler',
        'url' => 'http://mediawiki.org/wiki/Extension:Polyglot',
        'description' => 'Support for content in multiple languages in a single MediaWiki',
);

/**
* Set languages with polyglot support; applies to negotiation of interface language,
* and to lookups for loclaized pages.
* Set this to a small set of languages that are likely to be used on your site to
* improve performance. Leave NULL to allow all languages known to MediaWiki via
* $wgLanguageNames.
* If the LanguageSelector extension is installed, $wgLanguageSelectorLanguages is used
* as a fallback.
*/

$wgPolyglotLanguages = null;

/**
* Namespaces to excempt from polyglot support, with respect to automatic redirects.
* All "magic" namespaces are excempt per default. There should be no reason to change this.
* Note: internationalizing templates is best done on-page, using the MultiLang extension.
*/

$wfPolyglotExcemptNamespaces = array(NS_CATEGORY, NS_TEMPLATE, NS_IMAGE, NS_MEDIA, NS_SPECIAL, NS_MEDIAWIKI);

/**
* Wether talk pages should be excempt from automatic polyglot support, with respect to
* automatic redirects. True per default.
*/

$wfPolyglotExcemptTalkPages = true;

/**
* Set to true if polyglot should resolve redirects that are encountered when applying an
* automatic redirect to a localized page. This requires additional database access every
* time a locaized page is accessed.
*/

$wfPolyglotFollowRedirects = true;
///// hook it up /////////////////////////////////////////////////////
$wgHooks['ArticleFromTitle'][] = 'wfPolyglotArticleFromTitle';
$wgHooks['LinkBegin'][] = 'wfPolyglotLinkBegin';
$wgHooks['ParserAfterTidy'][] = 'wfPolyglotParserAfterTidy';
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = 'wfPolyglotSkinTemplateOutputPageBeforeExec';

$wgExtensionFunctions[] = "wfPolyglotExtension";

function wfPolyglotExtension() {
        global $wgPolyglotLanguages;

        if ( $wgPolyglotLanguages === null ) {
                $wgPolyglotLanguages = @$GLOBALS['wgLanguageSelectorLanguages'];
        }

        if ( $wgPolyglotLanguages === null ) {
                $wgPolyglotLanguages = array_keys( $GLOBALS['wgLanguageNames'] );
        }
}

function wfPolyglotArticleFromTitle( &$title, &$article ) {
        global $wfPolyglotExcemptNamespaces, $wfPolyglotExcemptTalkPages, $wfPolyglotFollowRedirects;
        global $wgLang, $wgContLang, $wgRequest;

        if ($wgRequest->getVal( 'redirect' ) == 'no') {
                return true;
        }

        $ns = $title->getNamespace();

        if ( $ns < 0
                || in_array($ns,  $wfPolyglotExcemptNamespaces)
                || ($wfPolyglotExcemptTalkPages && MWNamespace::isTalk($ns)) ) {
                return true;
        }

        $n = $title->getDBkey();
        $nofollow = false;
        $force = false;

        //TODO: when user-defined language links start working (see below),
        //      we need to look at the langlinks table here.
        if ( !$title->exists() && strlen( $n ) > 1 ) {
                $escContLang = preg_quote( $wgContLang->getCode(),  '!' );
                if ( preg_match( '!/$!', $n ) ) {
                        $force = true;
                        $remove = 1;
                } elseif ( preg_match( "!/{$escContLang}$!", $n ) ) {
                        $force = true;
                        $remove = strlen( $wgContLang->getCode() ) + 1;
                }
        }

        $accept = @$_SERVER["HTTP_ACCEPT_LANGUAGE"];
        $redir=false;
        if(!empty($accept))
        {
                $accept = explode( ',', $accept );
                foreach($accept as $ulang)
                {
                        $ulanga = explode( '-', $ulang );
                        $tu = Title::makeTitle( $ns, $n . '/' . $ulanga[0] );
                        if($tu->exists())
                        {
                                $t = $tu;
                                $redir=true;
                                break;
                        }

                }
        }

        if(!$redir)
        {
                if ( $force ) {
                        $t = Title::makeTitle( $ns, substr( $n, 0, strlen( $n ) - $remove ) );
                        $nofollow = true;
                } else {
                        $lang = $wgLang->getCode();
                        $t = Title::makeTitle( $ns, $n . '/' . $lang );
                }

                if (!$t->exists()) {
                        return true;
                }
        }

        if ($wfPolyglotFollowRedirects && !$nofollow) {
                $a = new Article($t);
                $a->loadPageData();

                if ($a->mIsRedirect) {
                        $rt = $a->followRedirect();
                        if ($rt && $rt->exists()) {
                                //TODO: make "redirected from" show $source, not $title, if we followed a redirect internally.
                                //     there seems to be no clean way to do that, though.
                                //$source = $t;
                                $t = $rt;
                        }
                }
        }

        if (!class_exists('PolyglotRedirect')) {
                class PolyglotRedirect extends Article {
                        var $mTarget;

                        function __construct( $source, $target ) {
                                Article::__construct($source);
                                $this->mTarget = $target;
                                $this->mIsRedirect = true;
                        }

                        function followRedirect() {
                                return $this->mTarget;
                        }

                        function loadPageData( $data = 'fromdb' ) {
                                Article::loadPageData( $data );
                                $this->mIsRedirect = true;
                        }
                }
        }

        //print $t->getFullText();

        $article = new PolyglotRedirect( $title, $t ); //trigger redirect to lovcalized page

        return true;
}

function wfPolyglotLinkBegin( $linker, $target, &$text, &$customAttribs, &$query, &$options, &$ret ) {
        global $wfPolyglotExcemptNamespaces, $wfPolyglotExcemptTalkPages, $wgContLang;

        $ns = $target->getNamespace();

        if ( $ns < 0
                || in_array( $ns, $wfPolyglotExcemptNamespaces )
                || ( $wfPolyglotExcemptTalkPages && MWNamespace::isTalk( $ns ) ) ) {
                return true;
        }

        $dbKey = $target->getDBkey();

        if ( !$target->exists() && strlen( $dbKey ) > 1 ) {
                $escContLang = preg_quote( $wgContLang->getCode(),  '!' );
                if ( preg_match( '!/$!', $dbKey ) ) {
                        $remove = 1;
                } elseif ( preg_match( "!/{$escContLang}$!", $dbKey ) ) {
                        $remove = strlen( $wgContLang->getCode() ) + 1;
                } else {
                        return true;
                }
        } else {
                return true;
        }

        $t = Title::makeTitle( $ns, substr( $dbKey, 0, strlen( $dbKey ) - $remove ) );

        if ( $t->exists() ) {
                $options = array_diff( $options, array( 'broken' ) );
                $options []= 'known';
        }

        return true;
}

function wfPolyglotGetLanguages( $title ) {
        global $wgPolyglotLanguages;
        if (!$wgPolyglotLanguages) return null;

        $n = $title->getDBkey();
        $ns = $title->getNamespace();

        $links = array();

        foreach ($wgPolyglotLanguages as $lang) {
                $t = Title::makeTitle($ns, $n . '/' . $lang);
                if ($t->exists()) $links[$lang] = $t->getFullText();
                //$links[$lang] = $t->getFullText();
        }

        return $links;
}

function wfPolyglotParserAfterTidy( &$parser, &$text ) {
        global $wgPolyglotLanguages, $wfPolyglotExcemptNamespaces, $wfPolyglotExcemptTalkPages;
        global $wgContLang;

        if ( !$wgPolyglotLanguages ) return true;
        if ( !$parser->mOptions->getInterwikiMagic() ) return true;

        $n = $parser->mTitle->getDBkey();
        $ns = $parser->mTitle->getNamespace();
        $contln = $wgContLang->getCode();

        $userlinks = $parser->mOutput->getLanguageLinks();

        $links = array();
        $pagelang = null;

        //TODO: if we followed a redirect, analyze the redirect's title too.
        //      at least if wgPolyglotFollowRedirects is true

        if ( $ns >= 0 && !in_array($ns,  $wfPolyglotExcemptNamespaces)
                && (!$wfPolyglotExcemptTalkPages || !MWNamespace::isTalk($ns)) ) {
                $ll = wfPolyglotGetLanguages($parser->mTitle);
                if ($ll) $links = array_merge($links, $ll);

                if (preg_match('!(.+)/(\w[-\w]*\w)$!', $n, $m)) {
                        $pagelang = $m[2];
                        $t = Title::makeTitle($ns, $m[1]);
                        if (!isset($links[$contln]) && $t->exists()) $links[$contln] = $t->getFullText() . '/';

                        $ll = wfPolyglotGetLanguages($t);
                        if ($ll) {
                                unset($ll[$pagelang]);
                                $links = array_merge($links, $ll);
                        }
                }
        }

        //TODO: would be nice to handle "normal" interwiki-links here.
        //      but we would have to hack into Title::getInterwikiLink, otherwise
        //      the links are not recognized.
        /*
        foreach ($userlinks as $link) {
                $m = explode(':', $link, 2);
                if (sizeof($m)<2) continue;

                $links[$m[0]] = $m[1];
        }
        */


        if ($pagelang) unset($links[$pagelang]);

        //print_r($links);

        $fakelinks = array();
        foreach ($links as $lang => $t) {
                $fakelinks[] = $lang . ':' . $t;
        }

        $parser->mOutput->setLanguageLinks($fakelinks);
        return true;
}

function wfPolyglotSkinTemplateOutputPageBeforeExec($skin, $tpl) {
        global $wgOut, $wgContLang;

        $language_urls = array();
        foreach( $wgOut->getLanguageLinks() as $l ) {
                if (preg_match('!^(\w[-\w]*\w):(.+)$!', $l, $m)) {
                        $lang = $m[1];
                        $l = $m[2];
                }
                else {
                        continue; //NOTE: shouldn't happen
                }

                $nt = Title::newFromText( $l );
                $language_urls[] = array(
                        'href' => $nt->getFullURL(),
                        'text' => $wgContLang->getLanguageName( $lang ),
                        'class' => 'interwiki-' . $lang,
                );
        }

        if(count($language_urls)) {
                $tpl->setRef( 'language_urls', $language_urls);
        } else {
                $tpl->set('language_urls', false);
        }
        return true;
}
?>
Categories: coding, php Tags:

if you use open source software …

February 27th, 2010 thomas No comments
Categories: OSS Tags:

decent identicons with php

February 24th, 2010 thomas No comments

so there is a project that implements identicons in php: problem is that they are hardcoded, low res and not good looking.

i wanted it more the gravatar style:

so i found this nice wordpress plugin: http://scott.sherrillmix.com/blog/blogger/wp_identicon/

which i (hackish) converted to pure php, so you can use it anywhere outside of wordpress:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<?php
/*
Plugin Name: WP_Identicon
Version: 1.02
Plugin URI: http://scott.sherrillmix.com/blog/blogger/wp_identicon/
Description: This plugin generates persistent specific geometric icons for each user based on the ideas of <a href="http://www.docuverse.com/blog/donpark/2007/01/18/visual-security-9-block-ip-identification">Don Park</a>.
Author: Scott Sherrill-Mix
Author URI: http://scott.sherrillmix.com/blog/
Author non WP port: thomas{AT}thomasfischer{DOT}biz
*/

function identicon_get_options(){
    //Set Default Values Here
    //$default_array=array('size'=>35,'backr'=>array(255,255),'backg'=>array(255,255),'backb'=>array(255,255), 'forer'=>array(1,255),'foreg'=>array(1,255),'foreb'=>array(1,255),'squares'=>4,'autoadd'=>1,'gravatar'=>0,'grey'=>0);
    $default_array=array(
    'size'=>300,
    'backr'=>array(225,255),
    'backg'=>array(225,255),
    'backb'=>array(225,255),
    'forer'=>array(1,205),
    'foreg'=>array(1,205),
    'foreb'=>array(1,205),
    'squares'=>5,
    'autoadd'=>0,
    'gravatar'=>0,
    'grey'=>0);
    return($default_array);
}

class identicon {
    var $identicon_options;
    var $blocks;
    var $shapes;
    var $rotatable;
    var $square;
    var $im;
    var $colors;
    var $size;
    var $blocksize;
    var $quarter;
    var $half;
    var $diagonal;
    var $halfdiag;
    var $transparent=false;
    var $centers;
    var $shapes_mat;
    var $symmetric_num;
    var $rot_mat;
    var $invert_mat;
    var $rotations;

    //constructor
    function identicon($blocks='') {
        $this->identicon_options=identicon_get_options();
        if ($blocks) $this->blocks=$blocks;
        else $this->blocks=$this->identicon_options['squares'];
        $this->blocksize=80;
        $this->size=$this->blocks*$this->blocksize;
        $this->quarter=$this->blocksize/4;
        $this->half=$this->blocksize/2;
        $this->diagonal=sqrt($this->half*$this->half+$this->half*$this->half);
        $this->halfdiag=$this->diagonal/2;
        $this->shapes=array(
            array(array(array(90,$this->half),array(135,$this->diagonal),array(225,$this->diagonal),array(270,$this->half))),//0 rectangular half block
            array(array(array(45,$this->diagonal),array(135,$this->diagonal),array(225,$this->diagonal),array(315,$this->diagonal))),//1 full block
            array(array(array(45,$this->diagonal),array(135,$this->diagonal),array(225,$this->diagonal))),//2 diagonal half block
            array(array(array(90,$this->half),array(225,$this->diagonal),array(315,$this->diagonal))),//3 triangle
            array(array(array(0,$this->half),array(90,$this->half),array(180,$this->half),array(270,$this->half))),//4 diamond
            array(array(array(0,$this->half),array(135,$this->diagonal),array(270,$this->half),array(315,$this->diagonal))),//5 stretched diamond
            array(array(array(0,$this->quarter),array(90,$this->half),array(180,$this->quarter)), array(array(0,$this->quarter),array(315,$this->diagonal),array(270,$this->half)), array(array(270,$this->half),array(180,$this->quarter),array(225,$this->diagonal))),// 6 triple triangle
            array(array(array(0,$this->half),array(135,$this->diagonal),array(270,$this->half))),//7 pointer
            array(array(array(45,$this->halfdiag),array(135,$this->halfdiag),array(225,$this->halfdiag),array(315,$this->halfdiag))),//9 center square
            array(array(array(180,$this->half),array(225,$this->diagonal),array(0,0)), array(array(45,$this->diagonal),array(90,$this->half),array(0,0))),//9 double triangle diagonal
            array(array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half),array(0,0))),//10 diagonal square
            array(array(array(0,$this->half),array(180,$this->half),array(270,$this->half))),//11 quarter triangle out
            array(array(array(315,$this->diagonal),array(225,$this->diagonal),array(0,0))),//12quarter triangle in
            array(array(array(90,$this->half),array(180,$this->half),array(0,0))),//13 eighth triangle in
            array(array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half))),//14 eighth triangle out
            array(array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half),array(0,0)), array(array(0,$this->half),array(315,$this->diagonal),array(270,$this->half),array(0,0))),//15 double corner square
            array(array(array(315,$this->diagonal),array(225,$this->diagonal),array(0,0)), array(array(45,$this->diagonal),array(135,$this->diagonal),array(0,0))),//16 double quarter triangle in
            array(array(array(90,$this->half),array(135,$this->diagonal),array(225,$this->diagonal))),//17 tall quarter triangle
            array(array(array(90,$this->half),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(45,$this->diagonal),array(90,$this->half),array(270,$this->half))),//18 double tall quarter triangle
            array(array(array(90,$this->half),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(45,$this->diagonal),array(90,$this->half),array(0,0))),//19 tall quarter + eighth triangles
            array(array(array(135,$this->diagonal),array(270,$this->half),array(315,$this->diagonal))),//20 tipped over tall triangle
            array(array(array(180,$this->half),array(225,$this->diagonal),array(0,0)), array(array(45,$this->diagonal),array(90,$this->half),array(0,0)), array(array(0,$this->half),array(0,0),array(270,$this->half))),//21 triple triangle diagonal
            array(array(array(0,$this->quarter),array(315,$this->diagonal),array(270,$this->half)), array(array(270,$this->half),array(180,$this->quarter),array(225,$this->diagonal))),//22 double triangle flat
            array(array(array(0,$this->quarter),array(45,$this->diagonal),array(315,$this->diagonal)), array(array(180,$this->quarter),array(135,$this->diagonal),array(225,$this->diagonal))),//23 opposite 8th triangles
            array(array(array(0,$this->quarter),array(45,$this->diagonal),array(315,$this->diagonal)), array(array(180,$this->quarter),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(180,$this->quarter),array(90,$this->half),array(0,$this->quarter),array(270,$this->half))),//24 opposite 8th triangles + diamond
            array(array(array(0,$this->quarter),array(90,$this->quarter),array(180,$this->quarter),array(270,$this->quarter))),//25 small diamond
            array(array(array(0,$this->quarter),array(45,$this->diagonal),array(315,$this->diagonal)), array(array(180,$this->quarter),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(270,$this->quarter),array(225,$this->diagonal),array(315,$this->diagonal)),array(array(90,$this->quarter),array(135,$this->diagonal),array(45,$this->diagonal))),//26 4 opposite 8th triangles
            array(array(array(315,$this->diagonal),array(225,$this->diagonal),array(0,0)), array(array(0,$this->half),array(90,$this->half),array(180,$this->half))),//27 double quarter triangle parallel
            array(array(array(135,$this->diagonal),array(270,$this->half),array(315,$this->diagonal)), array(array(225,$this->diagonal),array(90,$this->half),array(45,$this->diagonal))),//28 double overlapping tipped over tall triangle
            array(array(array(90,$this->half),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(315,$this->diagonal),array(45,$this->diagonal),array(270,$this->half))),//29 opposite double tall quarter triangle
            array(array(array(0,$this->quarter),array(45,$this->diagonal),array(315,$this->diagonal)), array(array(180,$this->quarter),array(135,$this->diagonal),array(225,$this->diagonal)), array(array(270,$this->quarter),array(225,$this->diagonal),array(315,$this->diagonal)),array(array(90,$this->quarter),array(135,$this->diagonal),array(45,$this->diagonal)),array(array(0,$this->quarter),array(90,$this->quarter),array(180,$this->quarter),array(270,$this->quarter))),//30 4 opposite 8th triangles+tiny diamond
            array(array(array(0,$this->half),array(90,$this->half),array(180,$this->half),array(270,$this->half), array(270,$this->quarter),array(180,$this->quarter),array(90,$this->quarter),array(0,$this->quarter))),//31 diamond C
            array(array(array(0,$this->quarter),array(90,$this->half),array(180,$this->quarter),array(270,$this->half))),//32 narrow diamond
            array(array(array(180,$this->half),array(225,$this->diagonal),array(0,0)), array(array(45,$this->diagonal),array(90,$this->half),array(0,0)), array(array(0,$this->half),array(0,0),array(270,$this->half)), array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half))),//33 quadruple triangle diagonal
            array(array(array(0,$this->half),array(90,$this->half),array(180,$this->half),array(270,$this->half),array(0,$this->half), array(0,$this->quarter),array(270,$this->quarter),array(180,$this->quarter),array(90,$this->quarter),array(0,$this->quarter))),//34 diamond donut
            array(array(array(90,$this->half),array(45,$this->diagonal),array(0,$this->quarter)), array(array(0,$this->half),array(315,$this->diagonal),array(270,$this->quarter)), array(array(270,$this->half),array(225,$this->diagonal),array(180,$this->quarter))),//35 triple turning triangle
            array(array(array(90,$this->half),array(45,$this->diagonal),array(0,$this->quarter)), array(array(0,$this->half),array(315,$this->diagonal),array(270,$this->quarter))),//36 double turning triangle
            array(array(array(90,$this->half),array(45,$this->diagonal),array(0,$this->quarter)), array(array(270,$this->half),array(225,$this->diagonal),array(180,$this->quarter))),//37 diagonal opposite inward double triangle
            array(array(array(90,$this->half),array(225,$this->diagonal),array(0,0),array(315,$this->diagonal))),//38 star fleet
            array(array(array(90,$this->half),array(225,$this->diagonal),array(0,0),array(315,$this->halfdiag),array(225,$this->halfdiag), array(225,$this->diagonal),array(315,$this->diagonal))),//39 hollow half triangle
            array(array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half)), array(array(270,$this->half),array(315,$this->diagonal),array(0,$this->half))),//40 double eighth triangle out
            array(array(array(90,$this->half),array(135,$this->diagonal),array(180,$this->half),array(180,$this->quarter)), array(array(270,$this->half),array(315,$this->diagonal),array(0,$this->half),array(0,$this->quarter))),//42 double slanted square
            array(array(array(0,$this->half),array(45,$this->halfdiag), array(0,0),array(315,$this->halfdiag)), array(array(180,$this->half),array(135,$this->halfdiag), array(0,0),array(225,$this->halfdiag))),//43 double diamond
            array(array(array(0,$this->half),array(45,$this->diagonal), array(0,0),array(315,$this->halfdiag)), array(array(180,$this->half),array(135,$this->halfdiag), array(0,0),array(225,$this->diagonal))),//44 double pointer
        );
        $this->rotatable=array(1,4,8,25,26,30,34);
        $this->square=$this->shapes[1][0];
        $this->symmetric_num=ceil($this->blocks*$this->blocks/4);
        for ($i=0;$i<$this->blocks;$i++){
            for ($j=0;$j<$this->blocks;$j++){
                $this->centers[$i][$j]=array($this->half+$this->blocksize*$j,$this->half+$this->blocksize*$i);
                $this->shapes_mat[$this->xy2symmetric($i,$j)]=1;
                $this->rot_mat[$this->xy2symmetric($i,$j)]=0;
                $this->invert_mat[$this->xy2symmetric($i,$j)]=0;
                if (floor(($this->blocks-1)/2-$i)>=0&floor(($this->blocks-1)/2-$j)>=0&($j>=$i|$this->blocks%2==0)){
                    $inversei=$this->blocks-1-$i;
                    $inversej=$this->blocks-1-$j;
                    $symmetrics=array(array($i,$j),array($inversej,$i),array($inversei,$inversej),array($j,$inversei));
                    $fill=array(0,270,180,90);
                    for ($k=0;$k<count($symmetrics);$k++){
                        $this->rotations[$symmetrics[$k][0]][$symmetrics[$k][1]]=$fill[$k];
                    }
                }
            }
        }
    }

    function xy2symmetric($x,$y){
        $index=array(floor(abs(($this->blocks-1)/2-$x)),floor(abs(($this->blocks-1)/2-$y)));
        sort($index);
        $index[1]*=ceil($this->blocks/2);
        $index=array_sum($index);
        return $index;
    }



    //convert array(array(heading1,distance1),array(heading1,distance1)) to array(x1,y1,x2,y2)
    function identicon_calc_x_y($array,$centers,$rotation=0){
        $output=array();
        $centerx=$centers[0];
        $centery=$centers[1];
        while($thispoint=array_pop($array)){
            $y=round($centery+sin(deg2rad($thispoint[0]+$rotation))*$thispoint[1]);
            $x=round($centerx+cos(deg2rad($thispoint[0]+$rotation))*$thispoint[1]);
            array_push($output,$x,$y);
        }
        return $output;
    }

    //draw filled polygon based on an array of (x1,y1,x2,y2,..)
    function identicon_draw_shape($x,$y){
        $index=$this->xy2symmetric($x,$y);
        $shape=$this->shapes[$this->shapes_mat[$index]];
        $invert=$this->invert_mat[$index];
        $rotation=$this->rot_mat[$index];
        $centers=$this->centers[$x][$y];
        $invert2=abs($invert-1);
        $points=$this->identicon_calc_x_y($this->square,$centers,0);
        $num = count($points) / 2;
        imagefilledpolygon($this->im, $points, $num, $this->colors[$invert2]);
        foreach($shape as $subshape){
            $points=$this->identicon_calc_x_y($subshape,$centers,$rotation+$this->rotations[$x][$y]);
            $num = count($points) / 2;
            imagefilledpolygon($this->im, $points, $num,$this->colors[$invert]);
        }
    }

    //use a seed value to determine shape, rotation, and color
    function identicon_set_randomness($seed=""){
        //set seed
        $twister=new identicon_mersenne_twister(hexdec($seed));
        foreach ($this->rot_mat as $key => $value){
            $this->rot_mat[$key]=$twister->rand(0,3)*90;
            $this->invert_mat[$key]=$twister->rand(0,1);
            #&$this->blocks%2
            if ($key==0) $this->shapes_mat[$key]=$this->rotatable[$twister->array_rand($this->rotatable)];
            else $this->shapes_mat[$key]=$twister->array_rand($this->shapes);
        }
        $forecolors=array($twister->rand($this->identicon_options['forer'][0],$this->identicon_options['forer'][1]), $twister->rand($this->identicon_options['foreg'][0],$this->identicon_options['foreg'][1]), $twister->rand($this->identicon_options['foreb'][0],$this->identicon_options['foreb'][1]));
        $this->colors[1]=imagecolorallocate($this->im, $forecolors[0],$forecolors[1],$forecolors[2]);
        if (array_sum($this->identicon_options['backr']) + array_sum($this->identicon_options['backg']) + array_sum($this->identicon_options['backb'])==0) {
            $this->colors[0]=imagecolorallocatealpha($this->im,0,0,0,127);
            $this->transparent=true;
            imagealphablending ($this->im,false);
            imagesavealpha($this->im,true);
        } else {
            $backcolors=array($twister->rand($this->identicon_options['backr'][0],$this->identicon_options['backr'][1]), $twister->rand($this->identicon_options['backg'][0],$this->identicon_options['backg'][1]), $twister->rand($this->identicon_options['backb'][0],$this->identicon_options['backb'][1]));
            $this->colors[0]=imagecolorallocate($this->im, $backcolors[0],$backcolors[1],$backcolors[2]);
        }
        if($this->identicon_options['grey']){
            $this->colors[1]=imagecolorallocate($this->im, $forecolors[0],$forecolors[0],$forecolors[0]);
            if(!$this->transparent) $this->colors[0]=imagecolorallocate($this->im, $backcolors[0],$backcolors[0],$backcolors[0]);
        }
        return true;
    }

    function identicon_build($seed='',$altImgText='',$img=true,$outsize='',$write=true,$random=true,$displaysize='',$gravataron=true){
        $filepath = '/var/www/your/path/ident/';
        //make an identicon and return the filepath or if write=false return picture directly
        if (function_exists("gd_info")){
            // init random seed
            //$id=$seed;
            $id=substr(sha1($seed),0,12);
            $fn=$id.'.png';
            $filename=$filepath.$fn;
            if ($outsize=='') $outsize=$this->identicon_options['size'];
            if($displaysize=='') $displaysize=$outsize;
            //if (!file_exists($filename))
            {
                $this->im = imagecreatetruecolor($this->size,$this->size);
                $this->colors = array(imagecolorallocate($this->im, 255,255,255));
                if ($random) $this->identicon_set_randomness($id);
                else {$this->colors = array(imagecolorallocate($this->im, 255,255,255),imagecolorallocate($this->im, 0,0,0));$this->transparent=false;};
                imagefill($this->im,0,0,$this->colors[0]);
                for ($i=0;$i<$this->blocks;$i++){
                    for ($j=0;$j<$this->blocks;$j++){
                    $this->identicon_draw_shape($i,$j);
                    }
                }

                $out = @imagecreatetruecolor($outsize,$outsize);
                imagesavealpha($out,true);
                imagealphablending($out,false);
                imagecopyresampled($out,$this->im,0,0,0,0,$outsize,$outsize,$this->size,$this->size);
                imagedestroy($this->im);
                if ($write){
                        $wrote=imagepng($out,$filename);
                        if(!$wrote) return false; //something went wrong but don't want to mess up blog layout
                }else{
                    header ("Content-type: image/png");
                    imagepng($out);
                }
                imagedestroy($out);
            }
            $filename=$filename;
            if($this->identicon_options['gravatar']&&$gravataron)
                    $filename = "http://www.gravatar.com/avatar.php?gravatar_id=".md5($seed)."&amp;size=$outsize&amp;default=$filename";
            if ($img){
                $filename='<img class="identicon" src="'.$fn.'" alt="'.str_replace('"',"'",$altImgText).' Identicon Icon" height="'.$displaysize.'" width="'.$displaysize.'" />';
            }
            return $filename;
        } else { //php GD image manipulation is required
            return false; //php GD image isn't installed but don't want to mess up blog layout
        }
    }

    function identicon_display_parts(){
        $this->identicon(1);
        for ($i=0;$i<count($this->shapes);$i++){
            $this->shapes_mat=array($i);
            $this->invert_mat=array(1);
            $output.=$this->identicon_build($seed='example'.$i,$altImgText='',$img=true,$outsize=30,$write=true,$random=false);
            $counter++;
        }
        $this->identicon();
    return $output;
    }
}

//create identicon for later use
global $identicon;
$identicon = new identicon;



class identicon_mersenne_twister{
//Copied from wikipedia pseudocode
//Don't call over 600 times (without recalling the constructor)
// Create a length 624 array to store the state of the generator
 var $MT;
 var $i;
 // Initialise the generator from a seed
 function identicon_mersenne_twister ($seed=123456) {
     $this->MT[0] = $seed;
         $this->i=1;
     for ($i=1;$i<624;$i++) { // loop over each other element
         $this->MT[$i] = $this->mysql_math('(1812433253 * ('.$this->MT[$i-1].' ^ ('.$this->MT[$i-1]." >> 30)) + $i) & 0xffffffff");
     }
         $this->generateNumbers();
 }

    //(some) PHP integers don't have enough bits for Mersenne Twister so use mysql
    function mysql_math($equation){
        $equation='select '.$equation;
        //echo $equation;
        $dblink=mysql_connect("localhost","username","password") or die (mysql_error());
        $res = mysql_query($equation,$dblink) or die (mysql_error());
            $arr=mysql_fetch_array($res);

        mysql_close($dblink) or die (mysql_error());

        //global $wpdb;
        //$query="SELECT ".$equation;
        //$answer=$wpdb->get_var($query);
        //echo $equation;
        //echo $arr[0].'<br/>';

        return $arr[0];//$answer;
    }

 // Generate an array of 624 untempered numbers
 function generateNumbers() {
     for ($i=0;$i<624;$i++) {
         $y = $this->mysql_math('('.$this->MT[$i].' & 0x7fffffff) + ('.$this->MT[($i+1)%624].' & 0xfffffffe)');
                 $even=$this->mysql_math($y.' ^ 0x00000001');
         if ($even) {
             $this->MT[$i] = $this->mysql_math($this->MT[($i + 397) % 624]." ^ ($y >> 1)");
         } else {
             $this->MT[$i] = $this->mysql_math($this->MT[($i + 397) % 624]." ^ ($y >>1) ^ (2567483615)"); // 0x9908b0df
         }
     }
 }

 // Extract a tempered pseudorandom number based on the i-th value
 // generateNumbers() will have to be called again once the array of 624 numbers is exhausted
 function extractNumber() {
     $y = $this->MT[$this->i];
     $y = $this->mysql_math("$y ^ ($y >>11) ^ (($y << 7) & 2636928640) ^ (($y << 15) & 4022730752) ^ ($y >>18)");
         $this->i++;
     return $y/0xffffffff;
 }

    function rand($low,$high){
        $pick=floor($low+($high-$low+1)*$this->extractNumber());
        return ($pick);
    }
    function array_rand($array){
        return($this->rand(0,count($array)-1));
    }
}

echo $identicon->identicon_build($_GET['hash'], '', true, '', true, true);
echo '<br/>';
echo '<br/>';
echo $identicon->identicon_build($_GET['hash'].'1', '', true, '', true, true);
echo '<br/>';
echo '<br/>';
echo $identicon->identicon_build($_GET['hash'].'2', '', true, '', true, true);
echo '<br/>';
echo '<br/>';
?>

the images above were produced by this code.
have fun using it :)

Categories: coding, php, website Tags:

windows: finding GUID of self

January 22nd, 2010 thomas No comments

so in the previous post i created a utility to get some exe’s and .pdb’s file GUID’s. However i need to get this information for the process that is currently executed (self). So what do we do? We apply they same technique as before and just preset the filename with the current executable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include "exeguid.h"
void  printGuid(GUID &g)
{
    char buf[120];
    sprintf(buf,"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", g.Data1,g.Data2,g.Data3,UINT(g.Data4[0]),UINT(g.Data4[1]),UINT(g.Data4[2]),UINT(g.Data4[3]),UINT(g.Data4[4]),UINT(g.Data4[5]),UINT(g.Data4[6]),UINT(g.Data4[7]));
    printf("%s\n", buf);
}

int _tmain(int argc, _TCHAR* argv[])
{
   
    GUID g;
    if(!getmyGUID(g))
        printGuid(g);
    else
        printf("error getting my GUID\n");
   
    return 0;
}

sounds easy, eh? :)

so to proof its working:

>SelfGUID.exe
8b73f207-5509-4b7d-82c9-a4979208416f

executed the same binary again: GUID stays the same:

>SelfGUID.exe
8b73f207-5509-4b7d-82c9-a4979208416f

rebuild the binary two times and executed it after building:

>SelfGUID.exe
68ce44c6-5ca8-431d-a29b-5480cf7e53ac
>SelfGUID.exe
b91fae19-e200-4207-8468-a4ca54581949

EDIT: removed unused dependency from the project (zip updated)
Source code and executable: selfGUID.zip

Categories: coding, windows Tags:

windows GUID’s and debug builds

January 22nd, 2010 thomas No comments

So i was experimenting with windows and the debug functions and needed a fast utility that will give me the GUID’s for executables and .pdb files. This GUID is used to compare if the executable and the .pdb file fit together. (note: only in most recent [VS2008] versions, before a timestamp was used)

So with this little handy utility you can get the executable GUID:

>GUIDTool.exe exe RoR.exe
f8d102be-40e0-4409-8d94-c97e0bb4fce0

and its fitting .pdb file:

>GUIDTool.exe pdb ror.pdb
f8d102be-40e0-4409-8d94-c97e0bb4fce0

Please note that 99% of the code was copy-pasted together – origins are still in the source files.

Source code and executable: GUIDTool.zip

Categories: coding, windows Tags:

benchmarking std::vector

January 12th, 2010 thomas No comments

so i always wondered whats the fastest way is to iterate over a vector. So with this little snippet you can find out for yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// some simple std::vector benchmark tool
// Jan 2010, thomas{AT}thomasfischer{DOT}biz
// also see http://stackoverflow.com/questions/776624/whats-faster-iterating-an-stl-vector-with-vectoriterator-or-with-at
#include <stdio.h>
#include <vector>
#include "Timer.h"

#define VECSIZE 500000


typedef struct foo_t {
    char tmp[2];
} foo_t;

int main(int argc, char **argv)
{
    int amount = VECSIZE;
    int tests = 10;
    printf("testing with %d elements a %d bytes (%0.2f MB) and %d runs per test\n", amount, sizeof(foo_t), (amount*sizeof(foo_t))/1024.0f/1024.0f, tests);
   
    double time = 0.0f;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        vec.reserve(amount);
        foo_t f; // with random data in it
        Timer *t = new Timer();
        for(int i=0;i<amount;i++)
            vec.push_back(f);
        time += t->elapsed();
    }
    printf("add time (resized before): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        foo_t f; // with random data in it
        Timer *t = new Timer();
        for(int i=0;i<amount;i++)
            vec.push_back(f);
        time += t->elapsed();
    }
    printf("add time (dynamic resize): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        foo_t f; // with random data in it
        for(int i=0;i<amount;i++)
            vec.push_back(f);

        Timer *t = new Timer();
        for(std::vector<foo_t>::iterator it=vec.begin(); it!=vec.end(); it++)
        {
            // some example usage
            it->tmp[1] = 0;
        }
        time += t->elapsed();
    }
    printf("iterate time (version #1): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        foo_t f; // with random data in it
        for(int i=0;i<amount;i++)
            vec.push_back(f);

        Timer *t = new Timer();
        std::vector<foo_t>::iterator vecEnd = vec.end();
        for(std::vector<foo_t>::iterator it=vec.begin(); it!=vecEnd; ++it)
        {
            // some example usage
            it->tmp[1] = 0;
        }
        time += t->elapsed();
    }
    printf("iterate time (version #2): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        foo_t f; // with random data in it
        for(int i=0;i<amount;i++)
            vec.push_back(f);

        Timer *t = new Timer();
        for(int i=0; i<amount; i++)
        {
            // some example usage
            vec[i].tmp[1] = 0;
        }
        time += t->elapsed();
    }
    printf("iterate time (version #3): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        std::vector<foo_t> vec;
        foo_t f; // with random data in it
        for(int i=0;i<amount;i++)
            vec.push_back(f);

        Timer *t = new Timer();
        for(unsigned int i=0; i<vec.size(); ++i)
        {
            // some example usage
            vec.at(i).tmp[1] = 0;
        }
        time += t->elapsed();
    }
    printf("iterate time (version #4): %f\n", time/tests);


    time=0;
    for(int i=0;i<tests;i++)
    {
        foo_t vec[VECSIZE];
       
        Timer *t = new Timer();
        for(int i=0; i<amount; ++i)
        {
            // some example usage
            vec[i].tmp[1] = 0;
        }
        time += t->elapsed();
    }
    printf("iterate over array (version #1): %f\n", time/tests);

    time=0;
    for(int i=0;i<tests;i++)
    {
        foo_t *vec = (foo_t *)malloc(sizeof(foo_t) * amount);
       
        Timer *t = new Timer();
        for(int i=0; i<amount; ++i)
        {
            // some example usage
            vec[i].tmp[1] = 0;
        }
        time += t->elapsed();
        free(vec);
    }
    printf("iterate over array (version #2): %f\n", time/tests);

    return 0;
}

to compile, add the Timer.h from my previous post :)

which results in the following output on my windows machine (/Oi /O2)

testing with 500000 elements a 2 bytes (0.95 MB) and 10 runs per test
add time (resized before): 0.005281
add time (dynamic resize): 0.007693
iterate time (version #1): 0.004180
iterate time (version #2): 0.004107
iterate time (version #3): 0.000903
iterate time (version #4): 0.004891
iterate over array (version #1): 0.000277
iterate over array (version #2): 0.000773

what are your results?

Categories: coding, cpp, funstuff Tags:

cross platform timer class

January 12th, 2010 thomas No comments

So, as it seems there is no usable class in boost which can measure time down to milliseconds, so i rolled my own. (in fact i was a bit shocked that the timer class that ships with Boost only measures used CPU time) I tested it under linux and windows, and its working well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// simple Timer class, Jan 2010, thomas{AT}thomasfischer{DOT}biz
// tested under windows and linux
// license: do whatever you want to do with it ;)
#ifndef TIMER_H__
#define TIMER_H__

// boost timer is awful, measures cpu time on linux only...
// thus we have to hack together some cross platform timer :(

#ifndef WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif

class Timer
{
protected:
#ifdef WIN32
    LARGE_INTEGER start;
#else
    struct timeval start;
#endif

public:
    Timer()
    {
        restart();
    }

    double elapsed()
    {
#ifdef WIN32
        LARGE_INTEGER tick, ticksPerSecond;
        QueryPerformanceFrequency(&ticksPerSecond);
        QueryPerformanceCounter(&tick);
        return ((double)tick.QuadPart - (double)start.QuadPart) / (double)ticksPerSecond.QuadPart;
#else
        struct timeval now;
        gettimeofday(&now, NULL);
        return (now.tv_sec - start.tv_sec) + (now.tv_usec - start.tv_usec)/1000000.0;
#endif
    }

    void restart()
    {
#ifdef WIN32
        QueryPerformanceCounter(&start);       
#else
        gettimeofday(&start, NULL);
#endif
    }
};

#endif //TIMER_H__

how you use it:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include "Timer.h"

int main(int argc, char **argv)
{
    Timer *t = new Timer();
    Sleep(1000);
    printf("time gone: %f\n", t->elapsed());
    return 0;
}

which results in my windows machine into this output:

time gone: 0.999699
Categories: coding, cpp, tutorials Tags:

IP WHOIS query via python

January 7th, 2010 thomas No comments

this is a simple example (based on some 2006 rwhois code) how to get further information about an IP address:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os, sys, string, time, getopt, socket, select, re, errno, copy, signal

def queryWhois(query, server='whois.ripe.net'):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while 1:
        try:
            s.connect((server, 43))
        except socket.error, (ecode, reason):
            if ecode==errno.EINPROGRESS:
                continue
            elif ecode==errno.EALREADY:
                continue
            else:
                raise socket.error, (ecode, reason)
            pass
        break

    ret = select.select ([s], [s], [], 30)

    if len(ret[1])== 0 and len(ret[0]) == 0:
        s.close()
        raise TimedOut, "on data"

    s.setblocking(1)

    s.send("%s\n" % query)
    page = ""
    while 1:
        data = s.recv(8196)
        if not data: break
        page = page + data
        pass

    s.close()
   
    if string.find(page, "IANA-BLK") != -1:
        raise 'no match'
       
    if string.find(page, "Not allocated by APNIC") != -1:
        raise 'no match'
   
    return page
   
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "usage: %s <IP address>" % sys.argv[0]
        sys.exit(1)
    ip = sys.argv[1]
   
    for server in ['whois.arin.net', 'whois.ripe.net', 'whois.apnic.net', 'whois.lacnic.net', 'whois.afrinic.net']:
        try:
            res = queryWhois(ip, server)
            print '======', server
            print res
            break # we only need the info once
        except:
            pass

just run it with the IP as argument

Categories: coding, python Tags:

useful c++ assert macro snippets

December 31st, 2009 thomas No comments

i just coded on this little bit, and i thought it might be worth to share the information as an example of how to roll your own assert, how to jump into the debugger and how to add log messages with proper calling information:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// this is the master swith to debug the stream locking/unlocking
#define DEBUGSTREAMFACTORIES

#define OGREFUNCTIONSTRING  String(__FUNCTION__)+" @ "+String(__FILE__)+":"+StringConverter::toString(__LINE__)

#ifdef DEBUGSTREAMFACTORIES
# define LOCKSTREAMS()       do { LogManager::getSingleton().logMessage("***LOCK:   "+OGREFUNCTIONSTRING); lockStreams();   } while(0)
# define UNLOCKSTREAMS()     do { LogManager::getSingleton().logMessage("***UNLOCK: "+OGREFUNCTIONSTRING); unlockStreams(); } while(0)
# ifdef WIN32
// __debugbreak will break into the debugger in visual studio
#  define MYASSERT(x)       do { if(!x) { LogManager::getSingleton().logMessage("***ASSERT FAILED: "+OGREFUNCTIONSTRING); __debugbreak(); }; } while(0)
# else //!WIN32
#  define MYASSERT(x)       assert(x)
# endif //WIN32
#else //!DEBUGSTREAMFACTORIES
# define LOCKSTREAMS()       ((void)0)
# define UNLOCKSTREAMS()     ((void)0)
# define MYASSERT(x)         ((void)0)
#endif //DEBUGSTREAMFACTORIES

also, you might enjoy this very well written tips and tricks for asserts: http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/

btw, happy new year ;)

Categories: coding Tags:

debugging crashing applications on customer’s windows

September 13th, 2009 thomas No comments

this snipped using the windows debugger (shipped with win 2k and after) was very helpful in tracking a problem:

set _NT_DEBUG_LOG_FILE_OPEN=debug-log.txt
ntsd -v -c "kb;q" .exe

also, you might want to read this awesome article:
http://blogs.msdn.com/pfedev/archive/2008/09/26/all-the-ways-to-capture-a-dump.aspx

and generally:
http://blogs.msdn.com/pfedev/

have fun debugging :)

Categories: coding, windows Tags: