[codebase] post hier je zinnige code!

Pagina: 1 2 Laatste
Acties:
  • 5.671 views sinds 30-01-2008

Acties:
  • 0 Henk 'm!

  • wasigh
  • Registratie: Januari 2001
  • Niet online

wasigh

wasigh.blogspot.com

Topicstarter
Om een goed plan weer in ere te herstellen de codebase!
de vorige is helaas na [bc3] verdwenen en het wordt wel weer eens tijd voor een nieuwe.

Wat is de bedoeling?

Heb je een handig stukje code geschreven en denk je dat het voor meerdere mensen handig/nuttig kan zijn dan kun je het in deze thread posten!

Met daarbij de taal waarin je het gemaakt hebt en het doel van de code.
Later als deze thread aardig vol is maken we er een mooi faq-topic van en bieden zo een snelle manier om dingen op te zoeken. Dus leef je uit!

Acties:
  • 0 Henk 'm!

  • Nielsz
  • Registratie: Maart 2001
  • Niet online
taal = PHP
doel = tijd berekenen die erover gedaan wordt om de pagina te parsen
code =
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function timing($command)
{
      global $starttime, $endtime; 
       if($command == 'start') //starten
        {
            $mtime1 = microtime(); 
            $mtime1 = explode(" ",$mtime1);
            $mtime1 = $mtime1[1] + $mtime1[0]; 
            $starttime = $mtime1;
        }
      else if($command == 'end')  
      {
            $mtime2 = microtime();
            $mtime2 = explode(" ",$mtime2);
            $mtime2 = $mtime2[1] + $mtime2[0];
            $endtime = $mtime2;
            $totaltime = ($endtime - $starttime);
            $totaltime = round($totaltime,6);
            return $totaltime;
      }
}
?>

Toepassing =
code:
1
2
3
timing('start');
jecommandos();
echo timing('end');

Thanx, Eamelink voor de nasty typo ;)

Acties:
  • 0 Henk 'm!

  • MPEG
  • Registratie: Oktober 2000
  • Laatst online: 21-10-2020
code:
1
2
3
4
function A()
{
   printf "hello world!";
}

Elke programmeertaal :P

AMD 64 X2 4800+ @2,41Ghz,
2048MB DDRRAM,
ATI X800GTO,
2x Samsung 930BF 19" TFT


Acties:
  • 0 Henk 'm!

Verwijderd

php, htmlspecialchars() terugzetten.
PHP:
1
2
3
4
5
6
<?
function htmlkickchars($text){
$text = str_replace(array("&amp;gt;", "&amp;lt;","&amp;quot;", "&amp;amp;"), array(">","<", "\"", "&amp;"), $text);
return $text;
}
?>

een klein voorbeeld... misschien niet het meest zinvolle
werking:
PHP:
1
2
3
4
5
6
<?
$string = htmlspecialchars($string);
echo "$string";
$string = htmlkickchars($string);
mail ($to,$subject,$string);
?>

Acties:
  • 0 Henk 'm!

Verwijderd

taal = Delphi
doel = het berekenen van a^b mod n
code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function PowerMod(a, b, n: int64): int64;
var c: int64;
begin
  c := 1;
  while b > 1 do
  begin
    if (b mod 2) = 1 then
    begin
    c := (a * c) mod n;
    b := b - 1;
    end;
    a := (a * a) mod n;
    b := b div 2;
  end;

  result := (a * c) mod n;
end;

toepassing = deze berekening wordt veel gebruikt in encryptie algoritmes. Natuurlijk is int64 veel te klein om een leuke waarde voor encryptie in te stoppen, maar het skelet van de code blijft gelijk als je hier je eigen bignumber-class voor gebruikt. Je hebt dan wel een algoritme nodig dat efficient de mod van een getal van je eigen bignumber type uitrekend, en om dat te doen staat hieronder een bignumber-mod algoritme. (De div kun je vervangen door een gewone deling, omdat het per constructie een deling zonder rest zal zijn, alleen begrijpt de Delphi compiler dat niet)

taal = Delphi
doel = helpt bij het maken van een mod functie voor je eigen bignumber-classe
code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function BigNumberMod(a, n: <je eigen bignumber type>): <je eigen bignumber type>;
var a2, n2, n3: <je eigen bignumber type>;
begin
  a2 := a;
  n2 := n;
  n3 := 2 * n2;
  while n3 <= a2 do 
  begin
    n2 := n3;
    n3 := 2 * n2;
  end;
  while n2 <= a2 do
  begin
    a2 := a2 - n2;
    while (n2 > a2) and (n2 > n) do n2 := n2 / 2;
  end;

  result := a2;
end;

Nu rest je niets anders dan het defineren van de gangbare rekenkundige operaties op je eigen bignumber classe. De deling in het algoritme is altijd een deling zonder rest, dus daar hoef je niet bang voor te zijn

Acties:
  • 0 Henk 'm!

  • [ti]
  • Registratie: Februari 2000
  • Niet online
Taal = PHP
Doel = Image Resizen (voor Thumbnails bv.)
PHP:
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
<?
set_time_limit(0); // we don't want to timeout.

if ((isset($image)) &amp;&amp; (is_uploaded_file($image)))
{ // resize the image

    if ($HTTP_POST_FILES['image']['type'] != "image/pjpeg")
        die($HTTP_POST_FILES['image']['type'] . " is not a supported file type");

    $inputImg = ImageCreateFromJPEG($image);
    
    $srcX = imagesx($inputImg);
    $srcY = imagesy($inputImg);
    
    $dstY = 72; // fixed Y for the image. always the same
    $maxX = 96; // max X for image, if image is smaller it will be centered
    
    $ratio = ($srcY / $dstY);
    $dstX  = ($srcX / $ratio);
    
    $outputImg = ImageCreateTrueColor($maxX, $dstY);
    imagefill($outputImg, 0, 0, ImageColorAllocate($outputImg, 255, 255, 255));
    
    imagecopyresampled($outputImg, $inputImg,
                       (($maxX - $dstX) / 2),0,0,0,
                       $dstX, $dstY,
                       $srcX, $srcY);

    header("content-type: image/png");
    imagepng($outputImg);
}
else // print the form
{
    printf("<form enctype=\"multipart/form-data\" action=\"\" method=\"post\">");
    printf("Resize image: <input name=\"image\" type=\"file\">");
    printf("<input type=\"submit\" value=\"Submit Image\">");
    printf("</form>");
}
?>

Acties:
  • 0 Henk 'm!

  • wasigh
  • Registratie: Januari 2001
  • Niet online

wasigh

wasigh.blogspot.com

Topicstarter
O ja, was ik even vergeten:
graag je code commenten als je dat nodig vind. :)

Acties:
  • 0 Henk 'm!

Verwijderd

taal : PHP
doel : je browser laten crashen
PHP:
1
2
3
4
5
6
7
<?
    $variabele=0;
    while ($variabele==0)
    {
         echo "ik ga zo crashen<p>";
    }
?>

Acties:
  • 0 Henk 'm!

Verwijderd

Uitleg staat al in de file (directe copy n paste)
maargoed:

dit scripje list gewoon alle plaatjes vanuit een opgegeven directory
dus in plaats van steeds van die img tag's te tiepen kan het dus zo :)
PHP:
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
<?
/** Door: Mark van der Velden.
  *
  *     dynom@dynom.ath.cx
  *
  *
  * Uitleg:
  * Deze code is ervoor bedoelt om plaatjes vanuit een bepaalde
  * directory op een pagina weer te geven. deze code is met uitleg.
  * de versie zonder overbodige info is: img-dirlist2.php
  * deze code werkt overigens _ALLEEN_ op linux/unix systemen.
  *
  **/


// Variable declareren,
$title="Titelding";    // Titel van de pagina.
$path="../lol/Gummbah";    // pad naar de files. _GEEN_ "/" aan het einde.

// opzetten van page.
echo "<html>
 <head>
  <title>${title} - listing files from: ${path}</title>
 </head>
 <body>";

// een array volstoppen met bestanden in de $path dir.
$data=explode("\n",`/bin/ls ${path}`);

// berekenen van het aantal gebruikte slots in een array.
$aantal=count($data);

// loopje voor de output
for ($i=0; $aantal > ($i + 1); $i++) {

  if (!is_dir(${path} . "/" . $data[$i])) {

    // Bestandsnaam boven een plaatje
    echo "\n  <br><br>\n  Bestandsnaam: $data[$i]<br>\n";

    // Vervangen van %20 (met %20 als deel van een bestandsnaam geeft errors.)
    $data[$i]=eregi_replace("%20","%2520", $data[$i]);

    echo "  [img]\"${path}/$data[$i]\"><br[/img]";
  }
}

// eindigen van de page.
echo "
 </body>
</html>";
?>

Ik weet onder de mysql shell geen optie om alle tables te laten zien, en om overal phpMyAdmin te gaan installen schiet ook niet echt op als ik alleen deze functie mis, dus heb ik een scripje gemaakt wat alle tables uit een database laat zien. met een optionele DROP functie.
PHP:
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
<?
/** Door: Mark van der Velden.
  *
  *     dynom@dynom.ath.cx
  *
  *
  * Uitleg:
  * Deze code is ervoor bedoelt om tables uit een database te vissen
  * Een optie die ik miste in de standaard mysql shell. dus heb ik er
  * een scripje voor geschreven met een drop functie.
  * phpMyAdmin is een andere oplossing. maar als je alleen maar even
  * een db leeg moet gooien is dit sneller
  *
  * er zit een optie op om DROP TABLE uit of aan te zetten standaard staat het uit.
  * zie regel 27.
  **/

// Login info.
$mysql_login_name="";
$mysql_login_pass="";
$mysql_login_host="";

// Geef de naam van de database die we gaan gebruiken
$database_name="";

// mag de table gewist worden ?
$allow_drop="false";    // true of false (false betekend dat er NIET! gewist mag worden)

@mysql_connect($mysql_login_host,$mysql_login_name,$mysql_login_pass) or die("Connectie was niet mogelijk, is alles goed gedefineerd ?");

if ($drop) {
  @mysql_query("DROP TABLE $database_name.$drop") or die("Het was niet mogelijk om $drop te wissen...<br>\n" .mysql_error());
  unset($drop);
}

$tables=mysql_list_tables($database_name);

echo "listing tables from database: <b>$database_name</b><br>\n<hr>\n";

$i=0;

while (list($data)=mysql_fetch_array($tables)) {

  echo " &amp;amp;nbsp; &amp;amp;nbsp; &amp;amp;nbsp; o <b>" . $data . "</b>";

  if ($allow_drop=="true") {
    echo "<a href=\"?drop=$data\">DROP-TABLE</a>";
  }

  echo "<Br>\n";
  $i++;
}

echo "\n<hr>\nHere are $i tables listed<br>\n";
?>

Nuttig is deze niet maar wel eens grappig. zoals sommige ongetwijfeld zullen weten heb je long ip's. (een standaard ip: 213.84.170.157 de long ip versie hiervan: 3579095709)

kan je testen met:
ping 213.84.170.157
die zal gelijkwaardig zijn aan:
ping 3579095709

naja goed hier de code:
PHP:
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
<?
/** Door: Mark van der Velden.
  *
  *     dynom@dynom.ath.cx
  *
  *
  * Uitleg:
  * convert een standaard ip naar een "long-ip"
  * ik heb de formule en uitleg hieronder in het engels staan.
  *
  **/

/**
  * This script calculates the long ip version of a given ip:
  * maybe this makes sence:
  *
  * 127.0.0.1 == 01111111.00000000.00000000.00000001
  *
  * Now the formula goes like this:
  *
  * 256*256*256*<first part of a ip> + 256*256*<second part of ip> + 256*<third part of ip> + 1*<fourth part of ip> = <longip>
  *
  * in this case:
  *
  * 256*256*256*127 + 256*256*0 + 256*0 + 1*1 == 2130706433
  *
  **/

if ($check_ip) {

    if ($ip_to_check!="") {
        $ip=explode(".", $ip_to_check);
        $long_ip=((16777216 * $ip[0]) + (65536 * $ip[1]) + (256 * $ip[2]) + $ip[3]);
        $message="long ip for $ip_to_check == $long_ip";
    } else {
        $message="Ehrm.. try filling something in... like: 127.0.0.1";
    }

    unset($check_ip);

} else {

    $message="example: 127.0.0.1";
}

?>

<html>
 <body>
  <pre>
  <? echo "$message<br>\n" ?>
  <form method=post>
  <input type=text name=ip_to_check>
  <input type=submit value=calculate name=check_ip>
  </form>
  </pre>
 </body>
</html>
?>

Acties:
  • 0 Henk 'm!

  • RdeTuinman
  • Registratie: Mei 2001
  • Laatst online: 25-09 09:25
Taal = PHP
Doel = Site binnenhalen van achter een proxy (Zowel GET als POST)
PHP:
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
<?
function get_site($site,$body="",$method="GET")
    {
        $fp = fsockopen ("xxx.xxx.xxx.xxx", $httppoort, $errno, $errstr, 30); // vul hier je proxy-adres in en http-poort van proxy
        if (!$fp) 
        {
                //echo "$errstr ($errno)<br>\n";
                return false;
        }
        else
        {
            
            //echo "connection through proxy<br>";
            $req  = "$method ".$site." HTTP/1.1\n";    
            $req .= "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*\n";    
            $req .= "Referer: none\n";
            $req .= "Accept-Language: en-us\n";    
            $req .= "Accept-Encoding: gzip, deflate\n";    
            $req .= "User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)\n";    
            $req .= "Host: ".$host."\n";    $req .= "Connection: Keep-Alive\n";
            if ($method == "POST")
            {
                $req .= "Content-type: application/x-www-form-urlencoded\n";        
                $req .= "Content-length: ".strlen($body)."\n";
            }
            $req .= "\n";
            
            
            //echo nl2br($req)."<hr>";
            
            fwrite($fp, $req.$body,strlen($req.$body)) || die("error");
            $contents = "";
                while (!feof($fp))
                {
                    $contents .= fgets ($fp,128);
                }
                fclose ($fp);                
                return $contents;
            }
        }
?>

Gebruik:

met GET:
PHP:
1
2
3
<?
$inhoudVanWebsite = get_site("www.domein.nl?variabele=waarde&amp;variabele2=anderewaarde");
?>

met POST:
PHP:
1
2
3
4
<?
$variabelen = "variabele=waarde&amp;variabele2=anderewaarde";
$inhoudVanWebsite = get_site("www.domein.nl",$variabelen,"POST");
?>

PS. Deze code komt van GoT, is alleen aangepast naar mijn wens ;)

Acties:
  • 0 Henk 'm!

Verwijderd

Taal = ASP (vbs)
Doel = Inlogprocedure koppelen aan bestaand WinNTdomein

winntloginForm.asp
code:
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
<%@ Language=VBScript %>
<%option explicit%>
<html>
  <head><title></title></head>
  <body>
    <form method="post" action="winntlogin.asp">
    <table>
      <tr>
        <td>Username</td>
        <td><input type="text" name="username"></td>
      </tr>
      <tr>
        <td>Password</td>
        <td><input type="password" name="password"></td>
      </tr>
      <tr>
        <td>Domain</td>
        <td><select name="domain">
<%
dim cont, obj, domainName
set cont = getObject("WinNT:")

for each obj in cont
    if(obj.class = "Domain") then
        domainName = obj.name
        response.write("<option value=""" & domainName & """>" & domainName & "</option>")
        selected = ""
    end if
next
%>
</select</td>
      </tr>
      <tr>
        <td colspan="2" align="center"><input type="submit" name="submit" value="Login"></td>
      </tr>
    </table>
    </form>
  </body>
</html>

winntlogin.asp
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ Language=VBScript %>
<%
dim username, password, winNTAuthDomain, myNTUser, domain

username = request.form("username")
password = request.form("password")
domain = request.form("domain")

on error resume next

set winNTAuthDomain = getObject("WinNT:")

set myNTUser = winNTAuthDomain.OpenDSObject("WinNT://" & domain & "/" & username, username, password, ADS_SECURE_AUTHENTICATION)
if(err.number = 0) then
    response.write("You are logged in " & myNTUser.FullName)
else
    response.write("Invalid username/password combination")
end if
%>

Acties:
  • 0 Henk 'm!

  • Pelle
  • Registratie: Januari 2001
  • Laatst online: 14:09

Pelle

🚴‍♂️

taal = PHP
doel = Date (2001-10-08) weergeven als 8 oktober 2001
PHP:
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
<?
function convertDate($brakkeDatum) {
        $mooieDatum = split("-", $brakkeDatum);

        //eventuele 0 voor de dag wegslopen
        if (substr($mooieDatum[2], 0, 1) == "0") {
                $dag = substr($mooieDatum[2], 1, 1);
        } else {
                $dag = $mooieDatum[2];
        }

        //eventuele 0 voor de maand wegslopen
        if (substr($mooieDatum[1], 0, 1) == "0") {
                $maand = substr($mooieDatum[1], 1, 1);
        } else {
                $maand = $mooieDatum[1];
        }

        $maanden = array ("whoops","januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","nov
ember","december");
        $maand   = $maanden[$maand];

        //jaar bepalen
        $jaar = $mooieDatum[0];

        //mooie datum samenstellen en returnen
        $datumString = "$dag $maand $jaar";
        return $datumString;
}
?>

Aan te roepen met:
PHP:
1
2
3
4
5
<?
// bijvoorbeeld datum van vandaag laten zien
$vandaag = date("Y-m-d");
print convertDate($vandaag);
?>

Acties:
  • 0 Henk 'm!

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06 13:31

drm

f0pc0dert


• Taal: PHP
• Datastructures Queue en Stack in objectvorm
• spreken voor zich, dus commenten vond ik niet nodig ;)

PHP:
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
<?
class Stack
{
   var      $data;
   
   function Stack ()
   {
      $this->data = array ();
   }
   
   function push ( $item )
   {
      array_push ( $this->data, $item );
      return $item;
   }
   
   function pop ()
   {
      return array_pop ( $this->data );
   }

   function peek ()
   {
      return $this->push ( $this->pop () );
   }
   
   function rollBack ( $entry )
   {
      return ( in_array ( $entry, $this->data ) );
   }
}

class Queue
{
   var      $data;
   
   function Queue ()
   {
      $this->data = array ();
   }
   
   function deque ()
   {
      return array_shift ( $this->data );
   }
   
   function enque ( $item )
   {
      array_unshift ( $this->data, $item );
      return $item;
   }
   
   function peek ()
   {
      return $this->unshift ( $this->shift () );
   }
}
?>


• Taal: PHP
• Session wrapper class
• comment ook niet echt nodig.

PHP:
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
<?
class Session
{
   function Session ()
   {
      session_start ();
   }
   
   function reg ( $str )
   {
      session_register ( $str );
   }
   
   function unreg ( $str )
   {
      session_unregister ( $str );
   }
   
   function killvar ( $str )
   {
      global $GLOBALS;
      unset ( $GLOBALS [ $str ] );
      session_unregister ( $str );
   }
   
   function kill ()
   {
      global $HTTP_SESSION_VARS;
      
      foreach ( $HTTP_SESSION_VARS as $key => $val )
         $this->killvar ( $key );
      session_destroy ();
   }
   
   function renew ()
   {
      $this->kill ();
      session_start ();
   }
}
?>


• Taal: PHP
• 2 validation functies voor email en URL dmv regex
• zijn niet echt toereikend maar voor de gemiddelde formuliertjes enzo wel handig

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?
function validateEmail ( $email )
{
   return ( preg_match ( "/^[a-zA-Z0-9_.-]+\@[a-zA-Z0-9-.]+\.[a-zA-Z]{2,}$/", $email ) != 0 );
}

function validateURL ( $url )
{
   if ( preg_match ( "/^(www\.)?[a-zA-Z0-9-.]+\.[a-zA-Z]{2,}$/", $url ) != 0 )
      return "http://" . $url;
   elseif ( preg_match ( "/^(http:\/\/)?(www\.)?[a-zA-Z0-9-.]+\.[a-zA-Z]{2,}/", $url ) != 0 )
      return $url;
   else
      return false;
}
?>


• Taal: PHP
• Recursief str-replacen van objecten en arrays

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?
function r_replace ( $needle, $str, $haystack )
{
   if ( is_string ( $haystack ) )
      $haystack = str_replace ( $needle, $str, $haystack );
   elseif ( is_array ( $haystack ) )
      while ( list ( $a, $value ) = each ( $haystack ) )
         $haystack [ $a ] = r_replace ( $needle, $str, $value );
   elseif ( is_object ( $haystack ) )
   {
      $v = get_object_vars ( $haystack );
      while ( list ( $prop, $value ) = each ( $v ) )
         $haystack->$prop = r_replace ( $needle, $str, $value );
   }

   return $haystack;
}
?>


• Taal:PHP
• Recursief html-entities op objecten en arrays

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?
function r_entities ( $var )
{
   if ( is_string ( $var ) )
      $var = htmlentities ( $var );
   elseif ( is_array ( $var ) )
      while ( list ( $a, $value ) = each ( $var ) )
         $var [ $a ] = r_entities ( $value );
   elseif ( is_object ( $var ) )
   {
      $v = get_object_vars ( $var );
      while ( list ( $a, $value ) = each ( $haystack ) )
         $var->$a = r_entities ( $value );
   }
   return $var;
}
?>


• Taal: PHP
• Recursief ' en $ escapen en unescapen op objecten en arrays. vooral handig voor MySQL toepassingen.
Maakt gebruik van bovenstaande r_replace

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
<?
function slash ( $var )
{
   $str = r_replace ( "'", "''", $var );
   return r_replace ( '$', '\$', $str );
}

function unslash ( $var )
{
   $str = r_replace ( "''", "'", $var );
   return r_replace ( '\$', '$', $str );
}
?>


Taal: PHP
MySQL wrapper class
Wederom als je de code leest vast wel te snappen

PHP:
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
<?
define ( "MYSQL_ASSOC",             1 );
define ( "MYSQL_OBJECT",            2 );
define ( "MYSQL_ARRAY",             3 );

class query {
   var $result;

   function query ( $query, $db = false )
   {
      if ( $db != false )
         mysql_select_db ( $db );
      $this->result = mysql_query ( $query );
      if ( mysql_errno () &amp;amp;&amp;amp; LOGGER_INCLUDED )
      {
         errorLog ( __FILE__, __LINE__, mysql_error () );
         return false;
      }
   }
   
   function noResult ()
   {
      return ( mysql_num_rows ( $this->result ) == 0 );
   }
   
   function getNextRow ( $type = MYSQL_ASSOC )
   {
      switch ( $type )
      {
         case MYSQL_ASSOC:
            $row = mysql_fetch_array ( $this->result );
            break;
         case MYSQL_OBJECT:
            $row = mysql_fetch_object ( $this->result );
            break;
         case MYSQL_ARRAY:
            $row = mysql_fetch_row ( $this->result );
            break;
         default:
            $row = false;
            break;
      }
      if ( mysql_errno () &amp;amp;&amp;amp; LOGGER_INCLUDED )
      {
         errorLog ( __FILE__, __LINE__, mysql_error () );
         return false;
      }

      if ( $row )
         return $row;
      else
      {
         mysql_free_result ( $this->result );
         $this->result = false;
         return false;
      }
      
   }

   function free ()
   {
      if ( $this->result )
         mysql_free_result ( $this->result );
   }
}

class MySQL {
   var         $db;
   
   function MySQL ( $db, $link = false )
   {
      $this->db = $db;
      if ( $link != false )
         $res = mysql_select_db ( $db, $link );
      else
         $res = mysql_select_db ( $db );
      
      if ( !$res )
      {
         errorLog ( __LINE__, __FILE__, "Wrong database: $db" );
         $this->db = false;
         return false;
      }
   }

   function getRow ( $query, $type = MYSQL_ASSOC )
   {
      $sql = new query ( $query, $this->db );
      $row = $sql->getNextRow ( $type );
      $sql->free ();
      return $row;
   }
   
   function getSet ( $query, $type = MYSQL_ASSOC )
   {
      $ret = array ();
      $sql = new query ( $query, $this->db );
      while ( $row = $sql->getNextRow ( $type ) )
         $ret[] = $row;
      $sql->free ();
      return $ret;
   
   }
   
   function plainQuery ( $query )
   {
      mysql_query ( $query );
      if ( mysql_errno () &amp;amp;&amp;amp; defined ( LOGGER_INCLUDED ) )
      {
         errorLog ( __FILE__, __LINE__, mysql_error () );
         return false;
      }
      return mysql_affected_rows ();
   }
}
?>

pf... nou is voorlopig wel genoeg, toch?

Voor vragen opmerkingen etc. zijn m'n mailadres en icq # te vinden in mijn profile. Heb nog veel meer van die rotzooi liggen, maar dit zijn wel zo ongeveer de handigste voor de gemiddelde php-er hier.

edit:

• Taal: PHP
• errorLog functie, logt errors
• MySQL wrapper hierboven maakt hier ook gebruik van, vandaar edit ;)

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?
define ( "LOGGER_INCLUDED", 1 );

if ( !isset ( $ERROR_LOG_FILE ) || empty ( $ERROR_LOG_FILE ) )
   $ERROR_LOG_FILE = "./log/error.log";

function errorLog ( $file, $line, $msg )
{
   global $ERROR_LOG_FILE;
   $fd = fopen ( $ERROR_LOG_FILE, "a+" );
   fwrite ( $fd, sprintf ( "%s\t%s at line %s:\t%s\n", date ( "g:h:i d-m-Y" ), $file, $line, $msg ) );
   fclose ( $fd );
}
?>

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


Acties:
  • 0 Henk 'm!

Verwijderd

Taal : C/C++
Doel : Een switch() op strings
Omschrijving: Visual Basic en C# ondersteunen beide switchen op strings. In C moet je hiervoor strcmp gebruiken. Dit leid al snel tot onduidelijke, geneste if /else if's. Volgende macro's doen in principe hetzelfde, maar zorgen er wel voor dat je code een stuk netter wordt.
code:
code:
1
2
3
4
#define sswitch(a) {char* _p = a; if (0)
#define scase(x) } else if ( !stricmp(_p, x) ) {
#define sdefault } else {
#define sendswitch }

Gebruik:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char *psz = ...;

sswitch( psz )
{
  scase( "geval1" )
    //  code voor geval 1

  scase( "geval2" )
    //  code voor geval 2

  // etc

  sdefault
    //  default code 
}
sendswitch

Acties:
  • 0 Henk 'm!

  • xychix
  • Registratie: September 2000
  • Laatst online: 16-09 07:50

xychix

FreeBSD Rules !

een handige upload.php file
plaatsen,

een map files aanmaken en chmodden naar 777
en uploaden maar.

ook word er een lijst met bestanden uit ./files weergegeven, dit zijn tevens linkjes naar het bestand.
code:
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
<?PHP
if ($submit)
{
 if (is_uploaded_file($bestand))
 {
  if($pass != "send")
  {
   echo "Nu nog met het JUISTE password!<br><hr><br>";
  }
  else
  {
  copy($bestand, "./files/$bestand_name");
  echo "Bestand '$bestand_name' met de grootte: $bestand_size bytes is succesvol geupload!<br><hr><br>";
  }
 }
 else
 {
  echo "Er is een fout bij het uploaden van bestand: '$bestand'!<br><hr><br>";
 }
}
else
{
 echo "Selecteer een bestand om te uploaden! LET OP overschrijven gaat ZONDER waarschuwing!<br><hr><br>";
}
echo "<form method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"bestand\"><br>
<input type=\"password\" name=\"pass\"> Password<br>
<input type=\"submit\" value=\"Uploaden maar!\" name=\"submit\">
</form><hr>";
$filecounter = "1";
$directory = dir("./files");
while($entry=$directory->read())
{
  echo "file $filecounter:";    echo "<a href=\"./files/$entry\" target=\"_blank\">$entry</a><br>";    $filecounter++;
}
echo "<p> $filecounter files found";
$directory->close();
?>

Every failure offers you a new opportunity! | Lokatie database|GoT - Notepad


Acties:
  • 0 Henk 'm!

Verwijderd

Taal : C/C++
Omgeving: Windows
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool IsWin2K()
{
    OSVERSIONINFO osvi;
    osvi.dwOSVersionInfoSize = sizeof (osvi);
    GetVersionEx(&osvi);
    return ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) && (osvi.dwMajorVersion >= 5);
 
}
bool IsWin98OrBetter()
{
    OSVERSIONINFO osvi;
    osvi.dwOSVersionInfoSize = sizeof (osvi);
    GetVersionEx(&osvi);
    return((osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) && ( (osvi.dwMajorVersion > 4) || 
( (osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion > 0) ) )||
( ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) &&(osvi.dwMajorVersion > 4) ));
}

.edit
Paar keer een enter tussengevoegd, want layout was beetje heel veel verneukt :o

Acties:
  • 0 Henk 'm!

Verwijderd

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
bool drag;
int oldx,oldy;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Image1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
drag=true;
oldx=X;
oldy=Y;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Image1MouseMove(TObject *Sender, TShiftState Shift,
int X, int Y)
{
if(drag&&CheckBox1->Checked){
TImage* img = dynamic_cast<TImage*>(Sender);
img->Left=img->Left+(X-oldx);
img->Top=img->Top+(Y-oldy);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Image1MouseUp(TObject *Sender, TMouseButton Button,
TShiftState Shift, int X, int Y)
{
drag=false;
}
//---------------------------------------------------------------------------
Taal : C++
Doel : om plaatjes (of iets anders) te verschuiven over een form d.m.v. klikken op het plaatje. Door deze code te gebruiken kun je meerdere plaatjes met dezelfde functie laten
schuiven.

Acties:
  • 0 Henk 'm!

Verwijderd

taal = php
doel = berekenen van taal
stond er al in maar code is kleiner
PHP:
1
2
3
4
5
6
7
8
9
10
11
<?
  
$sStart = microtime();  
// 
// hier je script
// 
$sEnd = microtime();
$aA = explode(' ',$sStart.' '.$sEnd);
printf('%03.8f Seconds<br>',($aA[2]+$aA[3])-($aA[0]+$aA[1]));  
exit;  
?>

Acties:
  • 0 Henk 'm!

Verwijderd

Fancy Windows Logon Script
code:
1
verwijderd

Ik post um wel weer als ie qua layout beter is :)

Acties:
  • 0 Henk 'm!

  • chris
  • Registratie: September 2001
  • Laatst online: 11-03-2022
Niet van mezelf, stond wel ergens op m'n harddisk :)

Functie: Text to UBB
PHP:
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
<?
function UBB($string)
{ 
//HTML escapen
$string = htmlspecialchars($string);
$string = nl2br ($string);

//UBB code
$tags = array("b","u","i","B","U","I");
for ($i = 0; $i < sizeof($tags); $i++)
{
$t = $tags[$i];
$open1 = quotemeta("[$t]"); $close1 = quotemeta("[/$t]");
$open2 = "<$t>"; $close2 = "</$t>";
$expression = "!$open1(.*)$close1!Ui";
$replacement = "$open2\\1$close2";
$string = preg_replace($expression, $replacement, $string);
}

//ubb link
$string = eregi_replace("(^|[ \n\r\t])((http(s?)://)(www\.)?([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)","\\1[url=\\2\]\\2[/url]",$string); 
$string = eregi_replace("(^|[ \n\r\t])(www\.([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)","\\1[url=http://\\2\]\\2[/url]",$string); 
$string = eregi_replace("(^|[ \n\r\t])((ftp://)(www\.)?([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)","\\1[url=\\2\]\\2[/url]",$string); 
$string = eregi_replace("(^|[ \n\r\t])(ftp\.([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)","\\1[url=ftp://\\2\]\\2[/url]",$string); 

//ubb email
$string = preg_replace ("/(([a-z]|[A-Z]|[0-9]|[_\-.])*@([a-z]|[A-Z]|[0-9]|[_\-.])*\.\w{2,3})(\W|$|\ )/", "[url=\"mailto:\\1\">\\1</a>\\4", $string);

//ubb <a href="http:// en [url=]
$string = preg_replace ("/\[url=\"(.*?)\"](.*?)\\[\/url\]/i","/\[url=\\1]\\2\\[\/url\]/i", $string);
$string = preg_replace ("/\[url=(.*?)\](.*?)\\[\/url\]/i", "<a href=\"\\1\" target=\"_blank\">\\2</a>", $string);
$string = preg_replace ("/\[url=(.*?)\](.*?)\\[\/url\]/i", "<a href=\"\\1\]\\2[/url]",$string);
$string = preg_replace ("/\\[url\](.*?)\\[\/url\]/i", "[url=\"\\1\]\\1</a>",$string);

$string=str_replace(":)","[img]\"img/ubb/smile.gif\"[/img]", $string);
$string=str_replace(">:)", "[img]\"img/ubb/devil.gif\"[/img]", $string);
$string=str_replace(":(","[img]\"img/ubb/frown.gif\"[/img]", $string);
$string=str_replace(":'(","[img]\"img/ubb/cry.gif\"[/img]", $string);
$string=str_replace(":+","[img]\"img/ubb/clown.gif\"[/img]", $string);
$string=str_replace(":D","[img]\"img/ubb/biggrin.gif\"[/img]", $string);
$string=str_replace(":O","[img]\"img/ubb/redface.gif\"[/img]", $string);
$string=str_replace(":P","[img]\"img/ubb/puh2.gif\"[/img]", $string);
$string=str_replace("*D","[img]\"img/ubb/shiny.gif\"[/img]", $string);

//Enters toe voegen
//$string = ($string);
$string=str_replace("\n\n","\n",$string);
$string=str_replace("\n\n","\n",$string);
$string=str_replace("\r","",$string);
$string=str_replace("\n","",$string);

return $string;
}
?>

Acties:
  • 0 Henk 'm!

  • Apache
  • Registratie: Juli 2000
  • Laatst online: 26-09 19:17

Apache

amateur software devver

Directory structuur vanaf de dir waarin het script staat
PHP:
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
<?
$level = -1;
// eerste deel van de string afkappen zodat we de maps relatief tot vanaf deze file
$start =  strlen(getcwd());

function newdir($file)
{
    global $level;

    $tmphandle = opendir($file);
    chdir($file);
    $level++;

    while (false !== ($file = readdir($tmphandle)))
        file_or_dir($file);

    $level--;
    chdir("..");
    closedir($tmphandle);
}

function file_or_dir($file)
{
    global $start;

    if ($file != "." &amp;&amp; $file != "..")
    {

        $dir = getcwd();
        $dir = substr("$dir", $start);

        if (is_dir($file))
        {
            echo "Dir: <b>$dir/$file</b><br>\n";
            newdir($file);
        }
        else
            echo "File: $dir/<i>$file</i><br>\n";
    }
}

/*function printSpaces()
{
    global $level;

    for ($i = 0; $i < $level; $i++)
        echo "----";

}*/

newdir(".");
?>

If it ain't broken it doesn't have enough features


Acties:
  • 0 Henk 'm!

Verwijderd

leuk topic :)

taal: php
doel: eerste letter hoofdletter
code:
1
2
3
4
5
function MakeUpper($input) {
        $l = substr($input,0,1);
        $old_string = substr($input,1,strlen($input));
        $new_string = strtoupper($l).$old_string;
        return $new_string;}

bijv. MakeUpper("apeldoorn") -> "Apeldoorn"

taal: php
doel: mail versturen
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    function n_mail( $from, $to , $subject,$core_msg, $add_header) 
    { 
        $cmd_line=sprintf("/usr/sbin/sendmail -r %s -t",$from); 
        $fp=popen($cmd_line,"w"); 
        $temp=sprintf("To: %s\n",$to); 
        $len=strlen($temp); 
        $ret_p=fputs($fp,$temp,$len); 
        $temp=sprintf("Subject: %s\n",$subject); 
        $len=strlen($temp); 
        $ret_p=fputs($fp,$temp,$len); 
        if ($add_header != "") 
        { 
            $temp=sprintf("%s\n",$add_header); 
            $len=strlen($temp); 
            $ret_p=fputs($fp,$temp,$len); 
        } 
        $temp=sprintf("\n%s\n",$core_msg); 
        $len=strlen($temp); 
        $ret_p=fputs($fp,$temp,$len); 
        pclose($fp); 
    }

bijv. n_mail("from@email.nl","to@email.nl","subject","hoi blabla","Content-Type: Text/HTML;");


taal: php
doel: van string (bepaalde syntax) naar array
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    function SPLIT_INTO_ARRAY($input,$ltag,$rtag) { 
        $description = $input;
        $description_array = explode($ltag,$input);
        $desc_tag_nr_ = "";
        $description_ = "";
        for ($i=0;$i<count($description_array)-1;$i++) {
            $desc_tag_len = strpos($description,$rtag)-1;
            $desc_tag_nr = substr($description,1,$desc_tag_len);
            $desc_tag_nr_ .= $desc_tag_nr.",";
            $description = str_replace($ltag.$desc_tag_nr.$rtag,"",$description);
            if (strpos($description,$ltag) == FALSE) {
                $description_ = $description_.$description;
            } else {
                $description_ .= substr($description,0,strpos($description,$ltag))."||";
                $description = substr($description,strpos($description,$ltag),strlen($description));
            }
        }
        $desc_tag_nr_ = substr($desc_tag_nr_,0,strlen($desc_tag_nr_)-1);
        $desc_tag_nr = explode(",",$desc_tag_nr_);
        $description_ = substr($description_,0,strlen($description_));
        $description = explode("||",$description_);
        return array($description,$desc_tag_nr); // returns an 2-dimensional array[x][y]
    }

bijv. $var = "[1]item1[2]item2[3]blabla[5]iets"
$var_ = SPLIT_INTO_ARRAY($var,"[","]");

item1 1
item2 2
blabla 3
iets 5

taal: php
doel: inhoud van array weergeven
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    function ListArray($var, $title='ListArray') {
        if($title){ $string = ''; }
        $string .= '<table border="0" cellpadding="2" cellspacing="1" bgcolor="CCCCCC" style="font-size:10px;">'; 
        if($title){ $string .= '<tr bgcolor="003346" style="color: whitesmoke;"><td><b>Key</b></td><td><b>Value</b></td></tr>';}
        while(list($key, $val) = each($var)):
            $string .= '<tr bgcolor="whitesmoke">' ; 
            $string .= "<td valign=\"top\"><b>$key</b></td><td valign=\"top\">";
            if(is_array($val)) {
                $string .= ListArray($val, '');
            } else { $string .= "$val" ; }
            $string .= '</td></tr>'; 
        endwhile;
        $string .= "</table>"; 
        if($title){ $string .= ''; } 
        return $string; 
    }

met dank aan php.net voor die laatste:P
bijv. echo ListArray(SPLIT_INTO_ARRAY($var,"[","]"));

Acties:
  • 0 Henk 'm!

Verwijderd

taal = perl
doel = 'woordenboekje'
beschrijving = een woordenboek dinges dat www.vandale.nl (mis)bruikt voor een shell-woordenboekje
platform = linux

code =
code:
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
#!/usr/bin/perl

open(PIPE, "lynx --source \"http://www.vandale.nl/cgi-bin/gx.cgi/AppLogic+FTCont
entServer?pagename=VanDale/ZoekResultaat&zoekwoord=$ARGV[0]\" | ");

%html = ( 126 => "~",
        180 => "'",
        183 => ".",
        );

print "\n";

while(<PIPE>) { 
    chomp; 
    $cnt++; 
    if (/U hebt gezocht op\:/gi) { 
      $start="here" 
      } 
    if ( $start ) { 
      if (/<DD>|<BIG>/gi) { 
        $print = stripHtml($_);
        $print =~ s/\&\#([0-9]{3})\;/$html{$1}/gi;
        print $print,"\n";
      }
    } 
    if ( /<\/DL>/gi ) { $last = $cnt; } 
    if ( $last && ($cnt - $last) > 10 ) { last; } 
}

close(PIPE);

sub stripHtml {
    $_ = shift;
    s/<\/DL>/\n+++++++++++++++++\n/gi;
    s/<\/DD>/\n /gi;
    s/<I>(.*)<\/I>/$1/gi;
    s/\"</\"></gi;
    s/<\s>/<>/gi;
    s/<\S>/<>/gi;
    s/<\w>/<>/gi;
    s/<\W>/<>/gi;
    s/<(.{1,5})>/<>/gi;
    s/<>//gi;
    s/<font (.*)\">//gi;
    return $_;
}

have phun

Acties:
  • 0 Henk 'm!

  • CyBeR
  • Registratie: September 2001
  • Niet online

CyBeR

💩

Taal: perl
Doel: ip adressen omzetten naar 32bit ints
Usage: neemt er zo veel als je wilt op de cmdline, als een naam meerdere ips heeft (round-robin dns) worden ze allemaal geprint.

Code:
code:
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
#!/usr/bin/perl -w

########################
## Author: Marco Wessel
## Licence: GPL
## 

use strict;

if(!$ARGV[0]){
      print "Need argument!\n";
      exit(1);
}
my $sargs;
foreach $sargs (@ARGV){
      print "$sargs: " .  convert($sargs) . "\n";
}

sub convert{
my ($args) = @_;
my ($name, $aliases, $addrtype, $length, @addresses) = gethostbyname($args);
if (defined($name)){
      my $addy;
      my @longs;
      my $ret;
      foreach $addy (@addresses){
            my @addrs = unpack('C4', $addy);
            my $res = ($addrs[0]<<24) + ($addrs[1]<<16) + ($addrs[2]<<8) + $addrs[3];
            $longs[$#longs + 1] = $res;
      }
      $ret = join(", ", @longs);
return $ret;
} else {
return "Couldn't resolve host";
}
}

All my posts are provided as-is. They come with NO WARRANTY at all.


Acties:
  • 0 Henk 'm!

  • JayTaph
  • Registratie: Oktober 1999
  • Laatst online: 30-09-2023

JayTaph

Portability is for canoes.

Platform: unix/linux (volgens mijn POSIX compliant)
Taal: C
Doel: shared libraries

DLTEST.C
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <dlfcn.h>

int (*func)(int);

int main (void) {
    void *dl_handle;

    dl_handle = dlopen ("libsharedlib.so", RTLD_LAZY);
    if (!dl_handle) {
        printf ("dlopen(): %s\n", dlerror());
        exit (1);
    }

    func = dlsym (dl_handle, "shared_function");
    printf ("func() returned: %d\n", func (2));

    if (dlclose (dl_handle)) {
        printf ("dlclose(): %s\n", dlerror());
        exit (3);
    }
}

SHAREDLIB.C
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

void _init (void) {
    printf ("The shared library is opened!\n");
}

void _fini (void) {
    printf ("The shared library is closed! :(\n");
}

int shared_function (int i) {
    printf ("Welkom in shared_function! Het nummertje is %d.\n", i);
    return i - 1;
}

MAKEFILE
code:
1
2
3
4
all:
    cc -c -o sharedlib.o sharedlib.c
    ld -shared -o libsharedlib.so sharedlib.o
    cc -o dltest dltest.c -ldl

Even zorgen dat de sharedlib begint met LIB en eindigd op .SO en dat deze in de LD_LIBRARY_PATH of /etc/ld.so.conf staat (en eventjes ldconfig draaien).

Yo dawg, I heard you like posts so I posted below your post so you can post again.


Acties:
  • 0 Henk 'm!

Verwijderd

taal: javascript
doel: array stack functies, voor netscape en ms-js engine ouder dan 5.5
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if([].top==null) Array.prototype.top=Array_top;
if([].push==null) Array.prototype.push=Array_push;
if([].pop==null) Array.prototype.pop=Array_pop;
function Array_top() {
  return this[this.length-1];
}
function Array_push(o) {
  this[this.length]=o;
}
function Array_pop() {
  var o=this[this.length-1];
  this.length--;
  return o;
}

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: PHP
Doel: Pagina gzippen (om bandbreedte te sparen)
Werkt alleen als zlib is meegecompileerd met PHP.

Zorg dat het volgende aan het begin van de code staat/geinclude wordt.
PHP:
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
<?
/**
 * Checks if user accepts gzipped output, and if zo compresses the output
 * @param $text text to compress
 * @param $level compression level (1 is recommended)
 */
function gzip($text, $level=1)
{
  global $TS, $DB;
  global $HTTP_ACCEPT_ENCODING;

  // Check if zlib is installed
  if(function_exists("crc32") &amp;&amp; function_exists("gzcompress"))
  {
    // if so check what kind of gzipping can be used
    if(strpos(" ".$HTTP_ACCEPT_ENCODING, "x-gzip"))
       $encoding = "x-gzip";
    elseif(strpos(" ".$HTTP_ACCEPT_ENCODING,"gzip"))
       $encoding = "gzip";

    if ($encoding) // ok, encoding is accepted
    {
       header("Content-Encoding: $encoding");

       $size = strlen($text);
       $crc = crc32($text);

       $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
       $output .= substr(gzcompress($text, $level), 0, -4);
       $output .= pack("V", $crc);
       $output .= pack("V", $size);
    }
    else
       $output = $text;
  }
  else
    $output = $text;

  echo $output;
}
?>

Aan het begin van je script voeg je het volgende toe:
PHP:
1
2
3
<?
ob_start();
?>

en aan het einde:
PHP:
1
2
3
4
5
<?
$html = ob_get_contents();
ob_end_clean();
gzip($html, 1);
?>

Acties:
  • 0 Henk 'm!

  • CyBeR
  • Registratie: September 2001
  • Niet online

CyBeR

💩

Taal: Perl
Doel: uitpluizen welke http server een host draait
Usage: neemt een host op de cmdline (met :poort indien nodig)
code:
code:
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
#!/usr/bin/perl -w

###################
## HTTP Server identifier
## By Marco Wessel
## Licence: GPL
####

use strict;
use IO::Socket;

my $host; my $port;
if (!$ARGV[0]){
      print "Need argument!\n";
      exit(1);
}
if ($ARGV[0] =~ /([^:]+):([0-9]+)/){
      $host = $1; $port = $2;
} else {
      $host = $ARGV[0]; $port = 80;
}
my $sock = IO::Socket::INET->new("$host:$port");
if ($sock){
      print $sock "HEAD / HTTP/1.0\n\n";
      while (my $line = <$sock>){
            chomp $line;
            if ($line =~ /Server: (.*)/){
                print "Server: $1\n";
                print "Host: $host at port $port\n";
            }
      }
      close ($sock);
} else {
      print "Couldn't connect to host $host\n";
      print "$!\n";
}

voorbeeld:
code:
1
2
3
[marco@phoenix marco]$ ./serverident.pl localhost
Server: Apache/1.3.22 (Unix) mod_perl/1.26 PHP/4.0.6 mod_gzip/1.3.19.1a mod_ssl/2.8.5 OpenSSL/0.9.6b
Host: localhost at port 80

werkt niet op bepaalde servers (yahoo.com bijvoorbeeld) :(

All my posts are provided as-is. They come with NO WARRANTY at all.


Acties:
  • 0 Henk 'm!

  • wasigh
  • Registratie: Januari 2001
  • Niet online

wasigh

wasigh.blogspot.com

Topicstarter
schopje?

Acties:
  • 0 Henk 'm!

  • Lurge
  • Registratie: Maart 2000
  • Niet online

Lurge

ActueleWind

taal = php
doel = string afkappen met ... erachter
code =
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?
function string_afkappen($string,$aantal_tekens){
    // De var $aantal_tekens geeft aan hoe lang de tekst mag worden.
    // De functieglobal $string;
    if(strlen($string) > $aantal_tekens){
       $row = explode(" ", $string);
        if(strlen($row[0]) < $aantal_tekens){
        for($i = 0; $i < count($row); $i++) {
          if(strlen($de_string_op_lengte." ".$row[$i]) < $aantal_tekens){
              if($i == 0){
                $de_string_op_lengte = $row[$i];
              }else{
                $de_string_op_lengte = $de_string_op_lengte." ".$row[$i];
              }
          }
        }
        }else{
          $de_string_op_lengte = substr($string, 0, $aantal_tekens);
        }
   $string = "$de_string_op_lengte"."...";}
   return $string;
}
?>

PS. dit is niet mijn code maar ik vond het wel nuttig om hier te posten...

ActueleWind


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: Delphi
Doel: Een unit met een aantal functies en/of procedures die ik heb gemaakt met betrekking tot kleurtjes en plaatjes, geen idee of het zo op zichzelf werkt, heb namelijk Images in uses staan.
code:
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
unit Colors;

interface

uses
  Windows, Graphics, SysUtils, Status, Dialogs, Classes;

const
  MaxPixelCount = 32768;

type
  TAdjustType = (
    atBrightness,     // Prm1 = IncBy
    atGrey,      //
    atNegative,  //
    atColorizeHSV,    // Prm1 = H, Prm2 = S, Prm3 = V
    atColorizeRGB,    // Prm1 = R, Prm2 = G, Prm3 = B
    atBlackOrWhite);  // Prm1 = WhiteAt

  THSVTriple = record
    H, S, V: Integer;
  end;

  TRGBTriple = record
    R, G, B: Integer;
  end;

type
  TRGBTripleArray = array[0..MaxPixelCount-1] of tagRGBTriple;
  PRGBTripleArray = ^TRGBTripleArray;

function ColorToRGBTriple(Col: TColor): tagRGBTriple;
function RGBTripleToColor(tagRGBTriple: tagRGBTriple): TColor;
function HtmlToDelphi(HtmlColor: String): TColor;
function DelphiToHtml(DelphiColor: TColor): String;
function TestCol(Val: Integer): Integer;
function HSVtoRGB(H, S, V: Integer): TColor;
function AdjustBlackOrWhite(Col: TColor; WhiteAt: Integer): TColor;
function AdjustBrightness(Col: TColor; IncBy: Integer): TColor;
function AdjustIntelBrightness(Col: TColor; DecOnWhite: Integer): TColor;
function AdjustGrey(Col: TColor): TColor;
function AdjustNegative(Col: TColor): TColor;
function AdjustColorizeRGB(Col: TColor; iR, iG, iB: Integer): TColor;
function AdjustBitmap(AdjType: TAdjustType; P1, P2, P3: Integer; Bmp: TBitmap; ShowStatus: Boolean): Boolean;
procedure CreateColorSpectrum(Bitmap: TBitmap; W, H: Integer);

const
  clBtnBack = $00FFEEDD;
var
  AdjustExecuting: Boolean;

implementation

uses
  Images;

function ColorToRGBTriple(Col: TColor): tagRGBTriple;
begin
  with Result do begin
    rgbtRed := GetRValue(Col);
    rgbtGreen := GetGValue(Col);
    rgbtBlue := GetBValue(Col);
  end;
end;

function RGBTripleToColor(tagRGBTriple: tagRGBTriple): TColor;
begin
  Result := RGB(
    tagRGBTriple.rgbtRed,
    tagRGBtriple.rgbtGreen,
    tagRGBTriple.rgbtBlue);
end;

function TestCol(Val: Integer): Integer;
begin
  if Val < 0 then Result := 0
  else if Val > 255 then Result := 255
  else Result := Val;
end;

function HSVtoRGB(H,S,V: Integer): TColor;
var
  F, HTmp: Integer;
  P, Q, T, R, G, B, VS: Integer;
begin
  if S = 0 then Result := RGB(V, V, V)
  else begin
    if H = 360 then HTmp := 0
    else HTmp := H;
    F := HTmp mod 60;
    HTmp := HTmp div 60;
    S := TestCol(S);
    if S = 0 then S := 1;
    VS := V * S;
    P := V - (VS div 255);
    Q := V - ((VS * F) div (255*60));
    T := V - ((VS * (60 - F)) div (255*60));
    case HTmp of
    0:  begin R := V;  G := T;  B := P  end;
    1:  begin R := Q;  G := V;  B := P  end;
    2:  begin R := p;  G := V;  B := T  end;
    3:  begin R := p;  G := Q;  B := V  end;
    4:  begin R := T;  G := P;  B := V  end;
    5:  begin R := V;  G := P;  B := Q  end
    else
    begin R := 0;  G := 0;  B := 0; end;
    end;
    Result := RGB(R, G, B);
  end
end;

function AdjustBlackOrWhite(Col: TColor; WhiteAt: Integer): TColor;
var
  T: Integer;
begin
  T := ColorToRGB(Col);
  if ((GetRValue(T)+GetGValue(T)+GetBValue(T)) div 3) >= WhiteAt then Result := clWhite
  else Result := clBlack;
end;

function AdjustBrightness(Col: TColor; IncBy: Integer): TColor;
var
  T: Integer;
begin
  T := ColorToRGB(Col);
  Result := RGB(
    TestCol(GetRValue(T)+IncBy),
    TestCol(GetGValue(T)+IncBy),
    TestCol(GetBValue(T)+IncBy));
end;

function AdjustIntelBrightness(Col: TColor; DecOnWhite: Integer): TColor;
begin
  if AdjustBlackOrWhite(Col,130) = $00FFFFFF then Result := AdjustBrightness(Col,-DecOnWhite)
  else Result := AdjustBrightness(Col,DecOnWhite)
end;

function AdjustGrey(Col: TColor): TColor;
var
  T: Integer;
begin
  T := ColorToRGB(Col);
  T := (GetRValue(T)+GetGValue(T)+GetBValue(T)) div 3;
  Result := RGB(T,T,T);
end;

function AdjustNegative(Col: TColor): TColor;
begin
  Result := $00FFFFFF - Col;
end;

function AdjustColorizeRGB(Col: TColor; iR, iG, iB: Integer): TColor;
var
  T: Integer;
begin
  T := ColorToRGB(Col);
  T := (GetRValue(T)+GetGValue(T)+GetBValue(T)) div 3;
  Result := RGB(
    TestCol(T - (255 - iR)),
    TestCol(T - (255 - iG)),
    TestCol(T - (255 - iB)));
end;

function AdjustBitmap(AdjType: TAdjustType; P1, P2, P3: Integer; Bmp: TBitmap; ShowStatus: Boolean): Boolean;
var
  X, Y: Integer;
  T: TColor;
  R, G, B: Integer;
  ScanLn: PRGBTripleArray;
begin
  Result := TRUE;
  Bmp.PixelFormat := pf24bit;
  if not AdjustExecuting then begin
    try
    AdjustExecuting := TRUE;
    R := 255;
    G := 255;
    B := 255;
    if AdjType = atColorizeHSV then begin
      T := HSVtoRGB(P1, P2, P3);
      R := GetRValue(T);
      G := GetGValue(T);
      B := GetBValue(T);
    end;
    for Y := 0 to Bmp.Height-1 do begin
      ScanLn := Bmp.ScanLine[Y];
      for X := 0 to Bmp.Width-1 do begin
        case AdjType of
        atBrightness:
          ScanLn[X] := ColorToRGBTriple(AdjustBrightness(RGBTripleToColor(ScanLn[X]), P1));
        atGrey:
          ScanLn[X] := ColorToRGBTriple(AdjustGrey(RGBTripleToColor(ScanLn[X])));
        atNegative:
          ScanLn[X] := ColorToRGBTriple(AdjustNegative(RGBTripleToColor(ScanLn[X])));
        atColorizeHSV:
          ScanLn[X] := ColorToRGBTriple(AdjustColorizeRGB(RGBTripleToColor(ScanLn[X]), R, G, B));
        atColorizeRGB:
          ScanLn[X] := ColorToRGBTriple(AdjustColorizeRGB(RGBTripleToColor(ScanLn[X]), P1, P2, P3));
        atBlackOrWhite:
          ScanLn[X] := ColorToRGBTriple(AdjustBlackOrWhite(RGBTripleToColor(ScanLn[X]), P1));
        end;
      end;
    end;
    AdjustExecuting := FALSE;
    except
    AdjustExecuting := FALSE;
    Result := FALSE;
    end;
  end
  else Result := FALSE;
end;

function HtmlToDelphi(HtmlColor: String): TColor;
var
  S: String;
begin
  S := Copy(HtmlColor,6,2)+Copy(HtmlColor,4,2)+Copy(HtmlColor,2,2);
  if Length(HtmlColor) = 7 then Result := StringToColor('$00'+S)
  else Result := clBlack;
end;

function DelphiToHtml(DelphiColor: TColor): String;
var
  C: String;
begin
  C := IntToHex(ColorToRGB(DelphiColor),6);
  Result :=
    '#'+
    Copy(C,5,2)+
    Copy(C,3,2)+
    Copy(C,1,2);
end;

procedure CreateColorSpectrum(Bitmap: TBitmap; W, H: Integer);
var
  X, Y, C: Integer;
  Ln: PRGBTripleArray;
  Tmp: TBitmap;
begin
  Tmp := TBitmap.Create;
  try
    Tmp.Width := 360;
    Tmp.Height := 510;
    Tmp.PixelFormat := pf24bit;
    for Y := 0 to 254 do begin
    Ln := Tmp.ScanLine[Y];
    for X := 0 to 359 do begin
      C := HSVToRGB(X,255,Y);
      with Ln[X] do begin
        rgbtRed := GetRValue(C);
        rgbtGreen := GetGValue(C);
        rgbtBlue := GetBValue(C);
      end;
    end;
    end;
    for Y := 509 downto 255 do begin
    Ln := Tmp.ScanLine[Y];
    for X := 0 to 359 do begin
      C := HSVToRGB(X,255-(Y-255),255);
      with Ln[X] do begin
        rgbtRed := GetRValue(C);
        rgbtGreen := GetGValue(C);
        rgbtBlue := GetBValue(C);
      end;
    end;
    end;
  finally
    Bitmap.Width := W;
    Bitmap.Height := H;
    Bitmap.Canvas.StretchDraw(Rect(0,0,W,H),Tmp);
    Tmp.Free;
  end;
end;

end.

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: Delphi
Doel: Hier de Images unit, een aantal handige functies voor het aanpassen van plaatjes, vooral Aplpha Blending en Fade Text.
code:
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
unit Images;

interface

uses
  Windows, SysUtils, Graphics, Classes, Colors;

const
  MaxPixelCount = 32768;

type
  TRGBTripleArray = array[0..MaxPixelCount-1] of tagRGBTriple;
  pRGBTripleArray = ^TRGBTripleArray;

procedure RotateBitmap(Bitmap: TBitmap; AngleOfRotation: Double);
procedure DissolveBitmap(Bitmap: TBitmap; DissolvePixels: Integer);
procedure AlphaBlendBitmaps(Bitmap: TBitmap; Bmp1, Bmp2: TBitmap; R: TRect; Opacity: Integer);
procedure FadeText(Bitmap: TBitmap; S1, S2: String; FromCanvas: TCanvas; Opacity: Integer);

implementation

procedure RotateBitmap(Bitmap: TBitmap; AngleOfRotation: Double);
var
  Theta, CosTheta, SinTheta: Extended;
  I, IOriginal, IPrime, IPrimeRotated, IRotationAxis,
  J, JOriginal, JPrime, JPrimeRotated, JRotationAxis,
  oW, oH, nW, nH: Integer;
  RowOriginal: pRGBTripleArray;
  RowRotated: pRGBTRipleArray;
  Tmp: TBitmap;
begin
  Tmp := TBitmap.Create;
  nW := 0;
  nH := 0;
  try
    Theta := -AngleOfRotation * (Pi / 180);
    CosTheta := Cos(Theta);
    SinTheta := Sin(Theta);
    oW := Bitmap.Width;
    oH := Bitmap.Height;
    nW := Abs(Round(oW * SinTheta)) + Abs(Round(oW * CosTheta));
    nH := Abs(Round(oH * SinTheta)) + Abs(Round(oH * CosTheta));
    Tmp := TBitmap.Create;
    Tmp.Width := nW;
    Tmp.Height := nH;
    Tmp.PixelFormat := pf24bit;
    IRotationAxis := oW div 2;
    JRotationAxis := oH div 2;
    for j := nW-1 downto 0 do begin
    RowRotated  := Tmp.Scanline[J];
    JPrime := 2 * (J - (nW - oW) div 2 - JRotationAxis) + 1;
    for i := nH-1 downto 0 do begin
      IPrime := 2 * (I - (nH - oH) div 2 - IRotationAxis) + 1;
      IPrimeRotated := Round(iPrime * CosTheta - jPrime * sinTheta);
      JPrimeRotated := Round(iPrime * sinTheta + jPrime * cosTheta);
      IOriginal := (IPrimeRotated - 1) div 2 + IRotationAxis;
      JOriginal := (JPrimeRotated - 1) div 2 + JRotationAxis;
      if (IOriginal >= 0) and (IOriginal <= Bitmap.Width-1) and (JOriginal >= 0) and (JOriginal <= Bitmap.Height-1) then begin
        RowOriginal := Bitmap.Scanline[JOriginal];
        RowRotated[I] := RowOriginal[IOriginal]
      end
      else begin
        with RowRotated[I] do begin
        rgbtBlue := 255;
        rgbtGreen := 0;
        rgbtRed := 0;
        end;
      end;
    end;
    end;
  finally
    Bitmap.Width := nW;
    Bitmap.Height := nH;
    Bitmap.Canvas.Draw(0,0,Tmp);
    Tmp.Free;
  end;
end;

procedure DissolveBitmap(Bitmap: TBitmap; DissolvePixels: Integer);
var
  C: Integer;
  T: tagRGBTriple;
  W, H: Integer;

  procedure DissolvePixel(X, Y: Integer);

    procedure SetRow(Row: Integer);

    function Check(Max, Int: Integer): Integer;
    begin
      if Int < 0 then Result := Max-(-Int)-1
      else if Int > Max-1 then Result := Int-Max
      else Result := Int;
    end;

    procedure SetCol(Col: Integer);
    begin
      with Bitmap do TRGBTripleArray(Scanline[(Check(H,(Y-Random(5))+Random(2)+Col))]^)[(Check(W,(X-Random(5))+Random(2)))+Row] := T;
    end;

    begin
    SetCol(0);
    SetCol(1);
    SetCol(2);
    SetCol(3);
    end;

  begin
    T := TRGBTripleArray(Bitmap.Scanline[Y]^)[X];
    SetRow(0);
    SetRow(1);
    SetRow(2);
    SetRow(3);
  end;

var
  X, Y: Integer;
begin
  C := 0;
  if DissolvePixels > 0 then begin
    repeat
    Inc(C);
    W := Bitmap.Width;
    H := Bitmap.Height;
    X := Random(W);
    Y := Random(H);
    if X = 0 then X := 1
    else if X = W then X := W-1;
    if Y = 0 then Y := 1
    else if Y = H then Y := H-1;
    DissolvePixel(X,Y);
    until C = DissolvePixels;
  end;
end;

procedure AlphaBlendBitmaps(Bitmap: TBitmap; Bmp1, Bmp2: TBitmap; R: TRect; Opacity: Integer);
var
  X, Y: Integer;
  ScanLn1, ScanLn2: PRGBTripleArray;
  Tmp: TBitmap;
begin
  Tmp := TBitmap.Create;
  try
    Bitmap.Width := R.Right - R.Left;
    Bitmap.Height := R.Bottom - R.Top;
    Bitmap.PixelFormat := pf24Bit;
    Tmp.Width := Bitmap.Width;
    Tmp.Height := Bitmap.Height;
    Tmp.PixelFormat := pf24Bit;
    Bitmap.Canvas.CopyRect(Rect(0,0,Bitmap.Width,Bitmap.Height),Bmp1.Canvas,R);
    Tmp.Canvas.CopyRect(Rect(0,0,Bitmap.Width,Bitmap.Height),Bmp2.Canvas,R);
    for Y := 0 to Bitmap.Height-1 do begin
    ScanLn1 := Bitmap.Scanline[Y];
    ScanLn2 := Tmp.Scanline[Y];
    for X := 0 to Bitmap.Width-1 do begin
      with ScanLn1[X] do begin
        rgbtBlue := ((255 - Opacity) * (rgbtBlue - ScanLn2[X].rgbtBlue)) div 255 + ScanLn2[X].rgbtBlue;
        rgbtGreen := ((255 - Opacity) * (rgbtGreen - ScanLn2[X].rgbtGreen)) div 255 + ScanLn2[X].rgbtGreen;
        rgbtRed := ((255 - Opacity) * (rgbtRed - ScanLn2[X].rgbtRed)) div 255 + ScanLn2[X].rgbtRed;
      end;
    end;
    end;
  finally
    Tmp.Free;
  end;
end;

procedure FadeText(Bitmap: TBitmap; S1, S2: String; FromCanvas: TCanvas; Opacity: Integer);
var
  Bmp1: TBitmap;
  Bmp2: TBitmap;
  T1, T2, H: Integer;
begin
  Bmp1 := TBitmap.Create;
  Bmp2 := TBitmap.Create;
  try
    with Bmp1.Canvas do begin
    Font.Assign(FromCanvas.Font);
    Brush.Color := FromCanvas.Brush.Color;
    Pen.Color := FromCanvas.Pen.Color;
    end;
    with Bmp2.Canvas do begin
    Font.Assign(FromCanvas.Font);
    Brush.Color := FromCanvas.Brush.Color;
    Pen.Color := FromCanvas.Pen.Color;
    end;
    T1 := Bmp1.Canvas.TextWidth(S1);
    T2 := Bmp2.Canvas.TextWidth(S2);
    H := Bmp1.Canvas.TextHeight(S1);
    Bmp1.Height := H;
    Bmp2.Height := H;
    if T1 > T2 then begin
    Bmp1.Width := T1;
    Bmp2.Width := T1;
    end
    else begin
    Bmp1.Width := T2;
    Bmp2.Width := T2;
    end;
    Bmp1.Canvas.FillRect(Rect(0,0,Bmp1.Width,Bmp1.Height));
    Bmp2.Canvas.FillRect(Rect(0,0,Bmp2.Width,Bmp2.Height));
    Bmp1.Canvas.TextOut(0,0,S1);
    Bmp2.Canvas.TextOut(0,0,S2);
    AlphaBlendBitmaps(Bitmap, Bmp1, Bmp2, Rect(0,0,Bmp1.Width,Bmp1.Height), Opacity);
  finally
    Bmp1.Free;
    Bmp2.Free;
  end;
end;

Acties:
  • 0 Henk 'm!

Verwijderd

jezus, wel veel code, mag dat zomaar????

Acties:
  • 0 Henk 'm!

  • RdeTuinman
  • Registratie: Mei 2001
  • Laatst online: 25-09 09:25
AUB opmerking hier: [topic=342482/1/25]

Acties:
  • 0 Henk 'm!

Verwijderd

Op donderdag 06 december 2001 13:02 schreef CyrusTheVirus het volgende:
code:
1
2
3
4
function A()
{
   printf "hello world!";
}

Elke programmeertaal :P
lukt niet in ASM :P

Acties:
  • 0 Henk 'm!

  • basjuh
  • Registratie: Januari 2001
  • Laatst online: 13:37
Taal: VB
Doel: Snel rekenen met Euro's voor de luie mensen.
Code = NIET geoptimaliseerd !

Altijd leuk om te prutsen :)

Private Sub Command1_Click()
Dim mystr
mystr = Format(Text1 / 2.20371, "0.00")
Text2.Text = mystr
End Sub

Private Sub Command2_Click()
Dim mystr
mystr = Format(Text3 * 2.20371, "0.00")
Text4.Text = mystr
End Sub

Weet t soms wel beter


Acties:
  • 0 Henk 'm!

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06 13:31

drm

f0pc0dert

Op maandag 10 december 2001 16:56 schreef spock13 het volgende:

[..]

lukt niet in ASM :P
en in C, C++, Java, JavaScript, Visual Basic, blablabla etc. ook niet, hoor :)

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C++
Functie: l33t
Naam: dick.cpp

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

void make_dick_long()
{
    int x;
    for(x=0;x<50;x++)
    {
        printf("my dick is now %d cm long\n", x);
    }
}

int main()
{
    make_dick_long();
    return 0;
}

:P

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Bepaal of een integer een macht van 2 is.

code:
1
2
3
4
unsigned int v; // Is v een macht van 2?
bool f;    // Resultaat 

f = (v & (v - 1)) == 0;

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Swappen van 2 integer waarden

code:
1
#define SWAP(a, b) ((a ^= b), (b ^= a), (a ^= b))

Acties:
  • 0 Henk 'm!

  • CyBeR
  • Registratie: September 2001
  • Niet online

CyBeR

💩

Taal: Perl
Doel: simpele perl -e irc bot, oneliner dus ;)


perl -MIO::Socket -e '$sock=IO::Socket::INET->new("phoenix.uzaynet.nl:6667")||die "error"; print $sock "USER cyber cyber cyber :cyber\r\n"; print $sock "NICK Oneliner\r\n"; while ($line = <$sock>){ chomp $line; $line =~ s/\r$//; print "$line\n"; if ($line =~ /^PING (:.*)/){ print $sock "PONG $1\r\n"; } elsif ($line =~ /:.* PRIVMSG ([^\s]+) :ol: say (.*)/){ print $sock "PRIVMSG $1 :$2\r\n"; } elsif ($line =~ /:.* PRIVMSG ([^\s]+) :ol: me (.*)/){ &action($2, $1); } elsif ($line =~ /:.* 004 .*/){ &join("#botfu"); } } sub action{ my ($action, $chan) = @_; printf $sock ("PRIVMSG $chan :\x01ACTION $action\x01\r\n"); } sub join{ my ($channel) = @_; print $sock "JOIN $channel\r\n"; }'

[edit]
code tags maar weg gehaald
layout ging helemaal b0rk >:)

All my posts are provided as-is. They come with NO WARRANTY at all.


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Tja .. had het nodig om een byte op een databus te zetten.

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
char Mask;
char Buffer = 0x1A;

for ( Mask = 0x80; Mask != 0; Mask >>= 1)
{
   if ( Mask & Buffer)
   {
    // bit = 1
   }
   else
   {
    // bit = 0
   }
}

Acties:
  • 0 Henk 'm!

  • Mart!
  • Registratie: Februari 2000
  • Laatst online: 28-09 08:51
Taal: Visual Basic (ook te gebruiken in ASP na een paar aanpassingen)
Doel: connect met Unreal Tournament Server via Webadmin poort om een level te restarten (GET actie) of Deck16][ te starten (POST actie), gebruik makende van automatische authenticatie (hier u/p Admin/Admin)
Opmerkingen:
- Maakt gebruik van WinHTTP5.0 component, deze dus toevoegen aan je references
- code opslaan als filenaam.frm en vervolgens dubbelklikken om het als nieuw project te openen
- Om te bouwen om content van websites af te rippen >:)
- command2 -> restart current level
command3 -> load Deck16][
text1 -> bevat teruggekregen HTML
text2 -> bevat teruggekregen status
UTServerIP -> Constante met IP en poort van UT webadmin
- Als je dit gebruikt voor een UT Admin tool, laat het me dan ff weten, kunnen we er misschien samen aan werken
code:
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
VERSION 5.00
Begin VB.Form frmMain 
   Caption     =   "Form1"
   ClientHeight    =   7725
   ClientLeft   =   60
   ClientTop     =   345
   ClientWidth     =   8835
   LinkTopic     =   "Form1"
   ScaleHeight     =   7725
   ScaleWidth   =   8835
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton Command3 
    Caption    =   "LoadLevel"
    Height      =   375
    Left        =   4080
    TabIndex      =   3
    Top      =   7320
    Width        =   1695
   End
   Begin VB.CommandButton Command2 
    Caption    =   "Restart"
    Height      =   375
    Left        =   2400
    TabIndex      =   2
    Top      =   7320
    Width        =   1575
   End
   Begin VB.TextBox Text2 
    Height      =   495
    Left        =   0
    TabIndex      =   1
    Top      =   6480
    Width        =   8775
   End
   Begin VB.TextBox Text1 
    Height      =   6375
    Left        =   0
    MultiLine    =   -1  'True
    TabIndex      =   0
    Top      =   0
    Width        =   8775
   End
End
Attribute VB_Name = "frmMain"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Const UTServerIP = "10.1.1.10:8080"

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1

Private Sub Form_Load()
    'Create an instance of the WinHttpRequest object.
    Set WinHttpReq = New WinHttpRequest
End Sub

Private Sub Command2_Click()
    WinHttpReq.Open "GET", _
    "http://" & UTServerIP & "/ServerAdmin/current_restart", False
    WinHttpReq.SetCredentials "Admin", "Admin", _
    HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    WinHttpReq.Send
    Text2.Text = WinHttpReq.Status & " " & _
    WinHttpReq.StatusText
    Text1.Text = WinHttpReq.GetAllResponseHeaders & "  " & _
    WinHttpReq.ResponseText
End Sub

Private Sub Command3_Click()
    WinHttpReq.Open "POST", "http://" & _
    UTServerIP & "/ServerAdmin/current_game", False
    WinHttpReq.SetCredentials "Admin", "Admin", 
    HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    WinHttpReq.SetRequestHeader "content-length", ""
    WinHttpReq.SetRequestHeader "content-type", _ 
    "application/x-www-form-urlencoded"
    WinHttpReq.Send "GameTypeSelect=BotPack.DeathMatchPlus" & _
    "&MapSelect=DM-Deck16][.unr&SwitchGameTypeAndMap=Switch"
    Text2.Text = WinHttpReq.Status & " " & _
    WinHttpReq.StatusText
    Text1.Text = WinHttpReq.GetAllResponseHeaders & "  " & _
    WinHttpReq.ResponseText
End Sub

Acties:
  • 0 Henk 'm!

Verwijderd

Op donderdag 06 december 2001 13:21 schreef dynom het volgende:
Ik weet onder de mysql shell geen optie om alle tables te laten zien, en om overal phpMyAdmin te gaan installen schiet ook niet echt op als ik alleen deze functie mis, dus heb ik een scripje gemaakt wat alle tables uit een database laat zien. met een optionele DROP functie.
Gewoon "show tables".
Lekker simpel he?

Acties:
  • 0 Henk 'm!

  • D2k
  • Registratie: Januari 2001
  • Laatst online: 22-09 14:35

D2k

Op dinsdag 11 december 2001 14:35 schreef cruesli het volgende:
Gewoon "show tables".
Lekker simpel he?
pssssssssssst
Op maandag 10 december 2001 16:55 schreef RdeTuinman het volgende:
AUB opmerking hier: [topic=342482/1/25]
:)

Doet iets met Cloud (MS/IBM)


Acties:
  • 0 Henk 'm!

  • mauriceb
  • Registratie: Maart 2001
  • Laatst online: 07-09 21:54
Taal: VBA
Doel: Mijn leven gemakkelijker maken.

Ik ben eens ooit tegen een internetsite gesurft.

Acties:
  • 0 Henk 'm!

  • BierPul
  • Registratie: Juni 2001
  • Laatst online: 19-09 21:49

BierPul

2 koffie graag

maak 1 db met 2 velden

id || thumb_path || full_path

trap die helemaal vol met paden naar plaatjes

verander de var in dit script ff layout modden en banzai >:)

Taal: PHP
Doel: Gallery script in samen werking met het thumbnail script van hierboven "deadly combination" :)
PHP:
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
<?
MySQL_CONNECT($hostname,$username,$password) or DIE("#55 de database is slapies aan het doen zzzzzzzz");
mysql_select_db($dbName) or DIE("#50 Sorry jongens er gaat iets fout");

$tabel = "de tabel naam met de plaatjes";

echo "<table align=\"center\" width=\"100%\"><tr>";
    if (empty($perpage)) $perpage = 15; //Hoeveel max op een pagina
    if (empty($pperpage)) $pperpage = 5;    
    if (empty($sort)) $sort = "desc";
    if (empty($offset)) $offset = 0;
    if (empty($poffset)) $poffset = 0;
    $amount = mysql_query("SELECT count(*) FROM $tabel");
    $amount_array = mysql_fetch_array($amount);
    $pages = ceil($amount_array["0"] / $perpage);
    $actpage = ($offset+$perpage)/$perpage;
    $maxoffset = ($pages-1)*$perpage;
    $maxpoffset = $pages-$pperpage;
    $middlepage=($pperpage-1)/2;
    if ($maxpoffset<0) {$maxpoffset=0;}
    echo "<td>\n<center>";
    if ($pages) {  // alleen wanneer $pages>0

        echo "$ad_pages\n";
    if ($offset) {
            $noffset=$offset-$perpage;
            $npoffset = $noffset/$perpage-$middlepage;
        if ($npoffset<0) {$npoffset=0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        echo "<a href=\"$PHP_SELF?offset=0&amp;poffset=0\"><<</a> ";
        echo "<a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\"><</a> ";
        }
        for($i = $poffset; $i< $poffset+$pperpage &amp;&amp; $i < $pages; $i++) {
        $noffset = $i * $perpage;
            $npoffset = $noffset/$perpage-$middlepage;
            if ($npoffset<0) {$npoffset = 0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        $actual = $i + 1;
            if ($actual==$actpage) {
         echo "| <b>$actual</b> | ";
            } else {
         echo "| <a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\">$actual</a> | ";
        }
    }
    if ($offset+$perpage<$amount_array["0"]) {
            $noffset=$offset+$perpage;
            $npoffset = $noffset/$perpage-$middlepage;
            if ($npoffset<0) {$npoffset=0;}
            if ($npoffset>$maxpoffset) {$npoffset = $maxpoffset;}
        echo "<a href=\"$PHP_SELF?offset=$noffset&amp;poffset=$npoffset\">></a> ";
        echo "<a href=\"$PHP_SELF?offset=$maxoffset&amp;poffset=$maxpoffset\">>></a> ";
        }
    }
    echo "</center></td></tr>\n";
    echo "</table>\n";


$thumbnail_query = mysql_query("SELECT id, thumb_path FROM $table ORDER BY id DESC LIMIT $offset,$perpage") or die (mysql_error());

$i = 1;
echo "<table border=0 cellpadding=5 cellspacing=4><tr>"; 
while ($thumb = mysql_fetch_array($thumbnail_query)) {
    
    echo "<td align='center'><a href='popimage.php?pic_id=$thumb[id]' target='_blank'>[img]'$thumb[thumb_path]'[/img]</a></td>\n";
if ($i%4 == 0)//aantal rijen {              
  echo "</tr>\n<tr>\n";          
}            
    $i++;
  }
echo "</tr></table>";
?>

Ja man


Acties:
  • 0 Henk 'm!

  • 4of9
  • Registratie: Maart 2000
  • Laatst online: 13-12-2024
Taal: VBscript (serverside)
Doel: Parse Time van een pagina
code:
1
2
3
4
5
6
7
8
9
10
11
bovenaan de pagina:
<%
Dim parseTime
parseTime = TIMER
%>
onderaan de pagina:
<%
If parseTime <> "" then
Response.Write "Parsed in:" & (TIMER - parseTime) & "seconds" 
End If
%>

Aspirant Got Pappa Lid | De toekomst is niet meer wat het geweest is...


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: ASP
Doel: Niet echt schokkend, wel veel gebruikt; soort uitgebreide Server.HTMLEncode:
code:
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
' Encode alphanumeric characters from ISO set with HTML codes - 3-7-2001 Mark Volmer
Function ISO2HTML(strSomeString)
    Dim i

    'Create & Fill Dictionary with ISO characters as keys and their codes as values
    Set charDict = CreateObject("Scripting.Dictionary")


    charDict.Add "!", "!"
    charDict.Add """", """
    charDict.Add "#", "#"
    charDict.Add "$", "$"
    charDict.Add "%", "%"
    charDict.Add "&", "&"
    charDict.Add "'", "'"
    charDict.Add "(", "("
    charDict.Add ")", ")"
    charDict.Add "*", "*"
    charDict.Add "+", "+"
    charDict.Add ",", ","
    charDict.Add "-", "-"
    charDict.Add ".", "."
    charDict.Add "/", "/"
    charDict.Add ":", ":"
    charDict.Add ";", ";"
    charDict.Add "<", "<"
    charDict.Add "=", "="
    charDict.Add ">", ">"
    charDict.Add "?", "?"
    charDict.Add "@", "@"
    charDict.Add "[", "["
    charDict.Add "\", "\"
    charDict.Add "]", "]"
    charDict.Add "^", "^"
    charDict.Add "_", "_"
    charDict.Add "`", "`"
    charDict.Add "{", "{"
    charDict.Add "|", "|"
    charDict.Add "}", "}"

    'Loop through Dictionary
    strcharDictKey = charDict.Keys
    For i = 0 To charDict.Count - 1
        key = strcharDictKey(i) 
        value = charDict.Item(strcharDictKey(i)) 
        strSomeString = Replace(strSomeString, key, value)
    Next
    ISO2HTML = strSomeString
End Function

Acties:
  • 0 Henk 'm!

Verwijderd

Ok dan zal ik hier ook maar eens wat leuks posten

xSimple Login Script v1.01 by Xtentic(*ChandlerFOK*)

... were one of a kind ...

// filename --> login.include.php
PHP:
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
<?
 

/* 

+-+-------------------------------------+-+ 
|#| xEasy Login System v1.01 by Xtentic |#| 
|#|       http://www.xtentic.com        |#| 
|#+-------------------------------------+#| 
|#| Hi, welcome to my xEasyLogin script |#| 
|#|  this script uses only cookies but  |#| 
|#| but can easyly be converted to the  |#| 
|#| use of sessions (maby i do that in  |#| 
|#|         the Future or so)..         |#| 
|#|                ----                 |#| 
|#|CheckThizOUt!.                       |#| 
|#|                ----                 |#| 
|#|  You can change the name of your    |#| 
|#| cookie! it's now 'xAdmin' but pls   |#| 
|#| change this to your own, cauze it   |#| 
|#|  may else use a cookie of someone   |#| 
|#|            else or so!.             |#| 
|#|                ----                 |#| 
|#| Enjoy and don't forget to credit ME |#| 
|#|        X-T-E-N-T-I-C.C-O-M          |#| 
+-+-------------------------------------+-+ 

Enjoy and don't forget to credit ME! 

*/ 

function checkCookie() { 
    global $prog, $xEasyAdmin; 
    global $HTTP_SERVER_VARS; 

    if ($xEasyAdmin == $prog[validate]) {                     // cookie is set! 
        return true; 
    }else{ 
        return; 
    } 
} 

function makeCookie($days) { 
    global $prog, $xEasyAdmin; 
    setcookie("xEasyAdmin", $prog[validate], time() + (3600 * $days)); 
} 

function removeCookie() { 
    global $prog, $xEasyAdmin; 
    setcookie("xEasyAdmin", "0", time() - 3600); 
} 

function showLoginDenied() { 
    // echo "Sorry your login was unsuccessfull please try again...<br>\r\n";"; 
    // echo "<a href=\"login.php\">Login here</a>\r\n"; 
    header("location: login.php"); 
} 


function showLogin() { 
    global $prog; 

    echo "<h1>" . $prog[title] . "</h1>\r\n"; 
    echo "<form action=\"$prog[program]\" method=\"post\"><table width=\"500\" bgcolor=\"#ccccff\">\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td>Username</td><td><input type=\"text\" size=\"25\" name=\"xAdminName\"></td></tr>\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td>Password</td><td><input type=\"password\" size=\"25\" name=\"xAdminPass\"></td></tr>\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td><input type=\"submit\" name=\"xAdminSubmit\" value=\"Submit\"></td></tr>\r\n"; 
    echo "</table></form>\r\n"; 
} 

function showLogout() { 
    global $prog; 

    echo "<h1>" . $prog[title] . "</h1>\r\n"; 
    echo "<form action=\"$prog[program]\" method=\"post\"><table width=\"500\" bgcolor=\"#ccccff\">\r\n"; 
    echo "<tr bgcolor=\"#ffffff\"><td><input type=\"submit\" name=\"xAdminSubmit\" value=\"Logout\"></td></tr>\r\n"; 
    echo "</table></form>\r\n"; 
} 

function checkLogin() { 
    global $prog, $xAdminName, $xAdminPass; 

    if ($prog[username] == $xAdminName &amp;&amp; $prog[password] == $xAdminPass) { 
        return true;                      // login successfull 
    } 
} 


$prog[username] = "admin"; 
$prog[password] = "qwerty"; 
$prog[title] = "xEasyLogin v1.0 by ChandlerFOK"; 
$prog[validate] = "xEasyLoginCookie"; 

?> 
?>

// filename --> login.php
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?
 

include("login.include.php"); 

if (checkcookie()) { 
   echo "<strong>Yes</strong> you have logged in!..\r\n<a href=\"main.php\">main</a>"; 
   showLogout(); 
}elseif ($xAdminSubmit == "Submit") { 
   if (checkLogin()) { 
       makeCookie(1); 
       header("location: main.php"); 
   }else{ 
       header("location: main.php"); 
   } 
}else{ 
   showLogin(); 
} 


?> 
?>

// filename --> main.php :+
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?
 

include("login.include.php"); 

if ($xAdminSubmit == "Logout") { 
   removeCookie(); 
   header("location: login.php"); 
}elseif (checkcookie()) { 
   echo "<strong>Yes</strong> you have logged in!..\r\n"; 
   showLogout(); 
}else{ 
   showLoginDenied(); 
} 

?> 
?>

[wasigh style]
schopje?
[/wasigh style]

Acties:
  • 0 Henk 'm!

  • johnwoo
  • Registratie: Oktober 1999
  • Laatst online: 10:35

johnwoo

3S-GTE

Taal: VB
Doel: eigen Replace() functie, handig in VB5 en eerder
Code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Public Function MyReplace(ByVal Haystack As String, _
                  ByVal Needle As String, _
                  ByVal ReplaceWith As String) As String
    ' Replaces all occurences of Needle in Haystack with ReplaceWith.
    Dim Pos As Integer, _
      Start As Integer, _
      NeedleLen As Integer, _
      ReplaceLen As Integer
    
    NeedleLen = Len(Needle)
    ReplaceLen = Len(ReplaceWith)
    Pos = InStr(Haystack, Needle)
    While Pos
      Haystack = Left$(Haystack, Pos - 1) _
        & ReplaceWith _
        & Mid$(Haystack, Pos + NeedleLen)
      Pos = InStr(Pos + ReplaceLen, Haystack, Needle)
    Wend
    MyReplace = Haystack
End Function

4200Wp ZO + 840Wp ZW + 1680Wp NW | 14xIQ7+ + 1xDS3-L | MTVenusE | HWP1


Acties:
  • 0 Henk 'm!

  • drZymo
  • Registratie: Augustus 2000
  • Laatst online: 15-09 08:44
Simpel maar effectief. Het zou je computer moeten afsluiten, maar om een of andere reden reboot ie alleen. :P
code:
1
2
3
4
5
6
7
8
9
10
11
12
[bits 16]
[org 0x100]

;shuts down ATX power :P
mov dx, 0x0CF9

mov al, 0xFE
out dx, al
mov al, 0xFF
out dx, al

ret

Ooh ja taal = NASM

"There are three stages in scientific discovery: first, people deny that it is true; then they deny that it is important; finally they credit the wrong person."


  • KoeKk
  • Registratie: September 2000
  • Laatst online: 18-09 18:41
taal = ASP
doel = tijd berekenen die erover gedaan wordt om de pagina te parsen

Starten van de timer aan het begin v/d pagina, functie, whatever
code:
1
2
  'A time counter
  TimeStart = Timer

Het berekenen van de genomen tijd...
code:
1
2
3
4
strTimer = "<span class=""small"">" &_ 
         Round((Timestart- Timer) * -1, 3) &_
         " seconden naar gezocht</span>"
Response.Write strTimer

Round werkt simpel, als je meer als 3 getallen achter de comma wilt vervang je de 3 door iets anders ;)
Deze timer plaats ik meestal in development versies van een website in de header & footer...

Acties:
  • 0 Henk 'm!

  • klokop
  • Registratie: Juli 2001
  • Laatst online: 22-09 10:26

klokop

swiekie swoeng

taal: php
doel: eerste letter hoofdletter
code:
1
2
3
4
5
function MakeUpper($input) {
        $l = substr($input,0,1);
        $old_string = substr($input,1,strlen($input));
        $new_string = strtoupper($l).$old_string;
        return $new_string;}

bijv. MakeUpper("apeldoorn") -> "Apeldoorn"
Hadden we daar ucfirst() niet voor? (en ucwords())

"Passing silhouettes of strange illuminated mannequins"


Acties:
  • 0 Henk 'm!

  • Clay
  • Registratie: Oktober 1999
  • Laatst online: 20-08 09:22

Clay

cookie erbij?

  • javascript form hulpje
  • alternatieve "anders namelijk" voor dropdowns.
  • geen input ernaast meer nodig
code:
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
function addAnders(obj) {   
   if(obj.selectedIndex != obj.length-1) return;    
   anders = prompt('geef wat anders op dan: ','');
   if(!anders) {
    // prompt cancel gedrukt
    obj.selectedIndex = 0;
    return;
   }
    
   // nieuwe options
   obj[obj.length-1] = new Option(anders, anders);
   obj[obj.length] = new Option('anders namelijk ...');
    
   // nieuwe selecten
   obj.selectedIndex = obj.length -2
}


met:

<select name="ikwil" onchange="addAnders(this)">
   <option value="drank"> drank
   <option value="eten"> eten
   <option value="peuken"> peuken
   <option value="eene"> anders namelijk ...
</select>

Instagram | Flickr | "Let my music become battle cries" - Frédéric Chopin


Acties:
  • 0 Henk 'm!

  • pim
  • Registratie: Juli 2001
  • Laatst online: 28-09 15:33

pim

Misschien dat jullie hier iets aan hebben, of is dit te simpel? Ik gebruik het zelf regelmatig. wat stukjes code die ik heb opgeslagen in een tekstbestandje..

-----------------------------------------------------------
Taal: PERL
Doel: Een formulier wat met method=get verstuurd is opvangen

#Method=GET opvangen
print "Content-type: text/html\n\n";
$buffer = $ENV{'QUERY_STRING'};
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name,$value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s/~!/ ~!/g;
$in{$name} = $value;
}
$voorbeeld = $in{'voorbeeld'};
-----------------------------------------------------------
Taal: PERL
Doel: Een formulier wat met method=post verstuurd is opvangen

#Method=POST opvangen

print "Content-type: text/html\n\n";
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$voorbeeld=$FORM{'voorbeeld'};
-----------------------------------------------------------
Taal: PERL
Doel: Formuliertje versturen via Perl met method=POST

print "Content-type: text/html\n\n";
use HTTP::Request::Common qw/POST/;
use LWP::UserAgent;
$ua = LWP::UserAgent->new();
my $req = POST 'http://www.homepage.com/cgi-bin/bla/bla.pl',
[ onderwerp => "testonderwerp",
value2name => "value2",
value3name => "value3" ];
$results = $ua->request($req)->as_string;
-----------------------------------------------------------
Taal: PERL
Doel: HTML mailtje versturen via je je SENDMAIL

$mailp="/usr/sbin/sendmail";
open(MAIL,"|$mailp -t");
print MAIL "To: $aanemail\n";
print MAIL "From: $afzenderemail\n";
print MAIL "Subject: $onderwerp\n";
print MAIL "MIME-Version: 1.0\n";
print MAIL "Content-Transfer-Encoding: 7bit\n";
print MAIL "Content-Disposition: inline;\n";
print MAIL "Content-Type: text/html; charset=us-ascii\n\n";
print MAIL "<font face=arial size=2>$berichtje</font>\n";
print MAIL "\<br\>\n";
close (MAIL);
-----------------------------------------------------------
Taal: PERL
Doel: content rippen

#!/usr/bin/perl
print "Content-type: text/html\n\n";
#het bestand waaruit gegrabbed word.
use LWP::Simple;
$file=get("http://www.google.com");
#tekens tellen in gegrabde bestand t/m <form
$tekens_tot_begin=index($file, "<form", $tekens_tot_begin);
#tekens tellen in gegrabde bestand t/m </form>> vanaf <form
$tekens_tot_eind=index($file, "</form>", $tekens_tot_begin);
#Hoeveel tekens van <form> t/m </form>
$lengte=$tekens_tot_eind - $tekens_tot_begin;
#Vanaf start het verschil in tekens gaan grabben + 7 tekens om </form> er nog bij te krijgen.
$grab=substr($file, $tekens_tot_begin, $lengte + 7);
# gegrabte stuk weergeven:
print $grab;
-----------------------------------------------------------
Taal: PERL
Doel: Een random getal afronden

$getal = rand(100);
$getal++;
$getal = int($getal);
print $getal;
-----------------------------------------------------------
Taal: PERL
Doel: checken of een string een woord bevat.

$_ = "het is weer laat";
if (/laat/){
print "de string bevat het woord \"laat\"";
}else{
print "de string bevat NIET het woord \"laat\"";
}

Acties:
  • 0 Henk 'm!

  • crisp
  • Registratie: Februari 2000
  • Laatst online: 14:28

crisp

Devver

Pixelated

Taal: PHP
Doel: Visitor counter
Code:
PHP:
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
<?
#############################################
#                             #
#       Crisp's first PHP counter       #
#                             #
#  www.crisp.demon.nl  tino@crisp.demon.nl  #
#                             #
#############################################

###############################################################################################
#
# Since I couldn't find a counter that suited all my needs, and since I knew nothing about PHP
# I just took the best parts of all counters I could find and made my own.
#
###############################################################################################
#
#  version 1.0  December 24, 2001
#
###############################################################################################

###############################################################################################
# Set all the variables here
###############################################################################################

$path = "../pictures/";             # Path to the image file
$image = "digits.jpg";      # Destination of the file in $path
$maxlength = 5;           # Maximum number of digits
$leading_zeros = true;      # include leading zero's up to the maximum length, or surpress

###############################################################################################
# Don't change below this line unless you don't know what you're doing either ;-)
###############################################################################################

# start a new session or restore original session
session_start();

# Get contents of counter file
$thefile = file("count.txt");
$count = implode("", $thefile);

# Check if we have a registered var called "id"; if we have it this is
# a continuation of a previous session, so we don't add to the count
# else we register the var to prevent adding to the count next time.
if (!session_is_registered("id")) {

  $id = 1;
  session_register ("id");

# add 1 to the count and store it
  $count++;
  $myfile = fopen("count.txt","w");
  fputs($myfile,$count);
  fclose($myfile);

}

# determine the number of digits
$length = strlen($count); 

if ($digits < 1) { 
    $digits = $length;
}
if ($digits > $maxlength) {
    $digits = $maxlength;
}

$count = sprintf("%0".$digits."s",$count);
$count = substr("$count", -$digits);

# get the sample file
if (file_exists("$path/$pix.jpg")) {
      $image="$pix.jpg"; 
}

# create the new image
$output_image = ImageCreateFromJPEG("$path/$image");
$output_imag_x = ImageSX($output_image);
$output_imag_y = ImageSY($output_image);
$cutter = $output_imag_x/10;
if ($leading_zeros) $output_x = $cutter*$maxlength;
else $output_x = $cutter*$digits;
$output = ImageCreate($output_x, $output_imag_y);

$offset = 0;

# leading zero's?
if ($leading_zeros) {

  $counter = $maxlength;

  while ($counter > $digits) {
    $c = "0";
    $x = $offset*$cutter;
    $y = $c*$cutter;
    ImageCopyResized($output, $output_image, $x, 0, $y, 0, $cutter, $output_imag_y, $cutter, $output_imag_y); 
    $offset++;
    $counter--;
  }

}

$counter = 0;

while ($counter < $digits) {
    $c = substr("$count", $counter, 1);
    $x = $offset*$cutter;
    $y = $c*$cutter;
    ImageCopyResized($output, $output_image, $x, 0, $y, 0, $cutter, $output_imag_y, $cutter, $output_imag_y); 
    $offset++;
    $counter++;
}

Header("Content-type: image/jpeg");
ImageJPEG($output);
ImageDestroy($output);
?>

Ik gebruik dit plaatje voor de digits, maar dat kan een willekeurig ander plaatje zijn:

Afbeeldingslocatie: http://www.toonwildeboer.com/pictures/digits.jpg

Includen in je HTML:
code:
1
[img]"counter.php"[/img]

Intentionally left blank


Acties:
  • 0 Henk 'm!

  • 845
  • Registratie: September 2001
  • Laatst online: 06:54

845

Ik heb vorig jaar voor school een keer een imagionair rekenmachine geschreven, zeker voor elektro is ie heel makkelijk

Taal: C
platform: Dos (waarschijnlijk doet ie het ook op de rest, maar dat is C :))
code:
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
/*Bas Breijer 24-09-2001  Imagionaire Rekenmachine t.b.v. Elektrotechniek*/

#include <stdio.h>
#include <conio.h>
#include <math.h>

struct compl
{
    float a,b,arg,mod;
};


struct compl invoer (int*);
struct compl optel (struct compl, struct compl);
struct compl verm (struct compl, struct compl);
struct compl delen (struct compl, struct compl);
struct compl aftrekken (struct compl,struct compl);
void rnp (struct compl *);
void pnr (struct compl *);
void hoek (struct compl *);

main ()
{
    int menu=0, inv=0, opt=0, ver=0, dele=0, aftr=0, aantal;
   struct compl cget1,cget2,som,prod,quot,versch;

   do
   {
    clrscr();
       printf("\n\n\tComplexe Rekenmachine\n");
    printf("\n\t\t\t1. Invoer\n");
    if (inv!=0)
    {
        printf("\t\t\t-Getal 1(cartesiaans):\t\t%.2f + %.2f.j\n", cget1.a,cget1.b);
       printf("\t\t\t-Getal 1(polair):     \t\t%.2f / %.2f\n",cget1.mod,cget1.arg);
       printf("\t\t\t-Getal 2(cartesiaans):\t\t%.2f + %.2f.j\n", cget2.a,cget2.b);
       printf("\t\t\t-Getal 2(polair):     \t\t%.2f / %.2f\n",cget2.mod,cget2.arg);
    };
    printf("\t\t\t2. Optellen\n");
    if (opt!=0)
    {
        printf("\t\t\t-Getal 1 + Getal 2(cartesiaans):%.2f + %.2f.j\n", som.a,som.b);
       printf("\t\t\t-Getal 1 + Getal 2(polair):     %.2f / %.2f\n",som.mod,som.arg);
    };
    printf("\t\t\t3. Vermenigvuldigen\n");
    if (ver!=0)
    {
        printf("\t\t\t-Getal 1 * Getal 2(cartesiaans):%.2f + %.2f.j\n", prod.a,prod.b);
       printf("\t\t\t-Getal 1 * Getal 2(polair):     %.2f / %.2f\n",prod.mod,prod.arg);
    };
    printf("\t\t\t4. Delen\n");
    if (dele==1)
    {
        printf("\t\t\t-Getal 1 / Getal 2(cartesiaans):%.2f + %.2f.j\n", quot.a,quot.b);
       printf("\t\t\t-Getal 1 / Getal 2(polair):     %.2f / %.2f\n",quot.mod,quot.arg);
    }else if (dele==2)
    {
        printf("\t\t\t-Het MOD gedeelte van Getal 2 is 0, delen gaat dus niet\n");
    };
    printf("\t\t\t5. Aftrekken\n");
    if (aftr!=0)
    {
        printf("\t\t\t-Getal 1 - Getal 2(cartesiaans):%.2f + %.2f.j\n", versch.a,versch.b);
       printf("\t\t\t-Getal 1 - Getal 2(polair):     %.2f / %.2f\n",versch.mod,versch.arg);
    }
    printf("\t\t\t6. Stoppen\n");
    scanf("%d", &menu);
    switch (menu)
    {
        case 1:
            aantal=1;
                   cget1=invoer(&aantal);
            if (aantal==3)
            {
               inv=0;
                break;
            }
            aantal=2;
            cget2=invoer(&aantal);
            if (aantal==3)
            {
               inv=0;
                break;
            }
            inv=1;
            opt=0;
            ver=0;
            dele=0;
            aftr=0;
            break;
       case 2:
                   som=optel(cget1,cget2);
            opt=1;
            break;
       case 3:
                   prod=verm(cget1,cget2);
            ver=1;
            break;
       case 4:
            if (cget2.mod!=0)
            {
                   quot=delen(cget1,cget2);
            dele=1;
            }else
            {
            dele=2;
            };
                   break;
       case 5:
                   versch=aftrekken(cget1,cget2);
            aftr=1;
            break;
    };
   }while (menu!=6);
   return 0;
}

struct compl invoer (int *aant)
{
    struct compl temp;
   int menu=0;

   clrscr();
   printf("Getal %d", *aant);
      printf("\n\n\t\t\tWilt U een getal invoeren invoer in:");
   printf("\n\t\t\t\t1. Cartesiaanse notatie (A+B.j).");
   printf("\n\t\t\t\t2. Polaire notatie (mod / arg).");
   printf("\n\t\t\t\t3. Terug naar het hoofdmenu.\n");
   do
   {
   scanf("%d", &menu);
   }while (menu<1 && menu>3);
     switch (menu)
      {
       case 1:
                      printf("\nGeef het A gedeelte van het getal.\n");
                     scanf("%f", &temp.a);
                     printf("\nGeef het B gedeelte van het getal.\n");
                     scanf("%f", &temp.b);
                rnp (&temp);
           break;
          case 2:
                     printf("\nGeef het MOD gedeelte van het getal.\n");
                scanf("%f", &temp.mod);
                printf("\nGeef het ARG gedeelte van het getal in graden.\n");
                scanf("%f", &temp.arg);
                pnr (&temp);
           break;
    case 3:
                    *aant=3;
           break;
   }
   return temp;
}

void rnp (struct compl *pntemp)
{
    if (pntemp->a==0)
    {
        if (pntemp->b>0)
       {
           pntemp->arg=90;
       };
       if (pntemp->b<0)
       {
           pntemp->arg=270;
       };
    }else
    {
        pntemp->arg=(180/M_PI)*atan2(pntemp->b, pntemp->a);
    }
    pntemp->mod=sqrt(pow(pntemp->a,2)+pow(pntemp->b,2));
   hoek (pntemp);
    return;
}

void pnr (struct compl *pntemp)
{
    if (pntemp->mod==0)
   {
         pntemp->a=0;
         pntemp->b=0;
    pntemp->arg=0;
   }else
   {
    pntemp->a=pntemp->mod*cos(pntemp->arg*M_PI/180);
    pntemp->b=pntemp->mod*sin(pntemp->arg*M_PI/180);
   };
   hoek (pntemp);
   return;
}

void hoek (struct compl *pntemp2)
{
    while (pntemp2->arg>=360)
   {
    pntemp2->arg=pntemp2->arg-360;
   }
   while (pntemp2->arg<0)
   {
         pntemp2->arg=360+pntemp2->arg;
   }
   return;
}

struct compl optel (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.a=tempcget1.a+tempcget2.a;
   temp.b=tempcget1.b+tempcget2.b;
   rnp (&temp);
   return temp;
}

struct compl verm (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.mod=tempcget1.mod*tempcget2.mod;
   temp.arg=tempcget1.arg+tempcget2.arg;
   pnr (&temp);
   return temp;
}

struct compl delen (struct compl tempcget1, struct compl tempcget2)
{
    struct compl temp;

   temp.mod=tempcget1.mod/tempcget2.mod;
   temp.arg=tempcget1.arg-tempcget2.arg;
   pnr (&temp);
   return temp;
}

struct compl aftrekken (struct compl tempcget1,struct compl tempcget2)
{
    struct compl temp;

   temp.a=tempcget1.a-tempcget2.a;
   temp.b=tempcget1.b-tempcget2.b;
   rnp (&temp);
   return temp;
}

Acties:
  • 0 Henk 'm!

  • D2k
  • Registratie: Januari 2001
  • Laatst online: 22-09 14:35

D2k

ach ik ben in een goede bui
uit de reeks icon topics een ip lock script
PHP:
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
<?
// je hebt een tabel log met daarin tijd en ip (kan je varchars van maken)
// connect gedoe
$server="localhost";
$user="";
$pass="";
$db="";
mysql_connect ($server, $user, $pass);
mysql_select_db($db);
// selecteer tijd horende bij ip
$result = mysql_query("SELECT tijd FROM log WHERE ip='$REMOTE_ADDR'");
// tijd in s op dit moment vanaf epoc
$nu = date("U");

if (mysql_num_rows($result)) 
{    
 
    $row = mysql_fetch_array ($result);       

    if (($nu + 600) > $row[tijd])  //tijd naar behoeven in te stellen
        {     
        echo "toegang";
        mysql_query("UPDATE log SET tijd='$nu' WHERE ip='$REMOTE_ADDR'");    
    }
else
{
     echo("geen toegang");
}        

}

else 
{    
mysql_query ("INSERT INTO log (tijd, ip) VALUES ('$nu', '$REMOTE_ADDR')");
echo "toegang";
}
?>

Doet iets met Cloud (MS/IBM)


Acties:
  • 0 Henk 'm!

  • rambo-2001
  • Registratie: November 2000
  • Laatst online: 02-01-2024

rambo-2001

be anonymous

taal=VBscript clientside
doel=weergave van alle mogelijke pincodes.
code:
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
<HTML>
<HEAD><TITLE>pincode</TITLE></HEAD>
<BODY>
<CENTER>
<SCRIPT LANGUAGE="VBSCRIPT">
dim counter1
dim counter2
dim counter3
dim counter4
counter1=0
counter2=0
counter3=0
counter4=0
do while counter4<=10 and counter3<=10 and counter2<=10 and counter1<=9
document.write counter1 & counter2 & counter3 & counter4 & "<BR>"
counter4=counter4+1
if counter4=10 then
counter3=counter3+1
counter4=0
end if
if counter3=10 then
counter2=counter2+1
counter3=0
end if
if counter2=10 then
counter1=counter1+1
counter2=0
end if
loop
</SCRIPT>
</CENTER>
</BODY>
</HTML>

cs skill - making a desert eagle out of tooth picks


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: JavaScript
Doel: (IE Only) sim-pel Form Highlight scriptje.
Geeft bij mouseover, of bij selectie van een form element (input, password, textarea) deze een andere kleur. Bij mouseout verandert de kleur weer terug. Makkelijk te aan te passen om ook bijv. button mee te pakken.
te bewonderen o.a. hier

in je <head>
code:
1
<script language="JavaScript" src="formhighlight.js" type="text/javascript"></script>

in je <body>
code:
1
<body onload="InitFormHighlight();">

formhighlight.js:
code:
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
// universal form element highligting system. written by Jelle Ursem, for NVLF

var focused = '';


function getfocus()
{
    if (this.disabled == false)
    {
         if (focused) 
          {
             var i = 0;
               var j = 0;
                while (j < document.forms.length)
                {
               while (i < document.forms[j].length)
                {
                if (document.forms[j].elements[i].name == focused) 
                {
                 document.forms[j].elements[i].style.backgroundColor='#FFFFFF';
                     document.forms[j].elements[i].style.scrollbarTrackColor='#FFFFFF';
                    }
                    i++;
                 }
                 j++;
              }
          }
    this.style.backgroundColor="EEF7FF";
    this.style.scrollbarTrackColor='#EEF7FF'
    focused = this.name;
    }
 return true;
}


function highlight()
{
 if (this.disabled == false)
 {
  this.style.backgroundColor="EEF7FF";
  this.style.scrollbarTrackColor='#EEF7FF';
 }
 return true;
}

function lightsoff()
{
         if (focused) 
          {
             var i = 0;
               var j = 0;
                while (j < document.forms.length)
                {
               while (i < document.forms[j].length)
                {
                if ((document.forms[j].elements[i].name != focused) && (document.forms[j].elements[i].disabled == false) && ((document.forms[j].elements[i].type == "password") || (document.forms[j].elements[i].type == "text") || (document.forms[j].elements[i].type == "textarea")) )
                {
                    document.forms[j].elements[i].style.backgroundColor='#FFFFFF';
                    document.forms[j].elements[i].style.scrollbarTrackColor='#FFFFFF'; 
                    }
                    i++;
                 }
                 j++;
              }
          }
          else if (this.disabled == false)
          {
          this.style.backgroundColor='#FFFFFF';
          this.style.scrollbarTrackColor='#FFFFFF';
          }
 return true;
}

function InitFormHighlight()
{
    if (navigator.appName == "Microsoft Internet Explorer")
        { 
            var i = 0;
            var j = 0;
                while (j < document.forms.length)
                {
                 while (i < document.forms[j].elements.length)
                {   
                    if ((document.forms[j].elements[i].type == "text") || (document.forms[j].elements[i].type == "password") || (document.forms[j].elements[i].type == "textarea") )
                     {
                        document.forms[j].elements[i].onfocus = getfocus;
                        document.forms[j].elements[i].onmouseover = highlight; 
                        document.forms[j].elements[i].onmouseout = lightsoff;
                        document.forms[j].elements[i].onmousedown = getfocus;  
                     }
                    i++;
                  }
                 j++;
                }
        }
 return true;

}

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Doel: 403 Error Handler
Warning!: Script gaat er van uit dat je zelf je apache 403 configuratie aangepast hebt naar 403.php!
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?
function writetxt($filename, $str) // simpele text schrijf functie
{  
    $fp = fopen($filename, 'a+'); // open bestand
    fwrite($fp, "$str\n"); // stringetje erbij met een linebreak
    fclose($fp); // bestand sluiten

}
    
    if ($REQUEST_URI != '/403.php') // zitten we in verboden gebied?
    {
        writetxt('/home/abso/lute/path/403.txt', "Referer: $REQUEST_URI - IP: $REMOTE_ADDR - Reverse DNS: ". gethostbyaddr($REMOTE_ADDR)." - Time: ".date("j-n-Y G:i:s")); // schrijf dan referer, ip, reverse dns en tijd &amp; datum naar 403.txt
        header('location: http://www.domein.nl/403.php'); // doorsturen naar root voor nette errorhandling (anders zijn je plaatjes vern*%@kt)
    }

    else
    {
    // include hier je templates en geef een nette error weer
    $maintext = 'Er is een fout opgetreden. <br>U bent niet gemachtigd om deze URL op te vragen.<br><br> De webmaster is om veiligheidsredenen op de hoogte gesteld, en zal indien nodig maatregelen nemen.';
    include('include/template.inc.php');
    }
?>

Output:
Referer: /razor/ - IP: 195.***.63.4 - Reverse DNS: 195.***.63.4 - Time: 7-1-2002 15:50:44
Referer: /razor/ - IP: 62.***.19.131 - Reverse DNS: asd-tel-***-***-131.dial.freesurf.nl - Time: 8-1-2002 13:06:16

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Functie: Titel uit variabele halen
Code:
PHP:
1
2
3
4
5
6
7
8
9
<?
function gettitle($var)
{
   if (eregi("<title>(.*)</title>", $text, $out))
    {
      $result = $out[1];
    }
}
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: PHP
Doel: Word Document, of ander bestand als downoad aanbieden ipv openen.
Gebruiken als: download.php?filename=documentnaam
Waarschuwing!: Gebruiker moet zelf extentie aan bestand geven
PHP:
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
<?
if (file_exists($filename.".doc")) // bestaat het bestand?
  {
    $filename = $filename.".doc"; // doc erachter, om geklooi met slimme variabelen te voorkomen
    if (strstr($HTTP_USER_AGENT, "MSIE")) // internet explorer?
      {
        $attachment = ""; // attachment var leeglaten
      }
    else
      {
        $attachment = " attachment;"; // attachment var vullen
      }

    $size = filesize("$filename"); // bestandsgrootte
    $fh = fopen("$filename", "r"); // bestand openen
    // correcte headers sturen
    header("Content-Type: application/octetstream");
    header("Content-Length: $size");
    header("Pragma: no-cache");
    header("Expires: 0");
    header("Content-Disposition:$attachment filename=$doc");
    header("Content-Transfer-Encoding: binary");

    fpassthru($fh); // bestand doorsturen
    exit; // script stoppen
  }
else // bestand bestaat niet
  {
        // Error Handling
    $mailto= "webmaster@domein.nl"; // e-mail adres
    $subject= "Fout bij downloaden bestand vanaf domein"; // subject
    $from= "php@domein.nl"; // afzender
    $message= "Er is een fout opgetreden bij het proberen te downloaden van het volgende bestand:\n
    $filename\n
    De bezoeker kwam van pagina: $HTTP_REFERER\n
    De tijd is nu: ".date("j-n-Y G:i:s")."\n
    Ip nummer van de bezoeker: $REMOTE_ADDR\n
    "; // info mailtje
    mail( "$mailto", "$subject", "$message", "From: $from"); // mailen
        // nette foutmelding aan gebruiker
    $maintext = 'Er is een fout opgetreden.<br><br>Het bestand is niet gevonden, of er was een andere fout tijdens het aanbieden van de download.<br><br>Er is inmiddels een e-mail gestuurd naar de webmaster, die het probleem hoogstwaarschijnlijk binnen 24 uur zal oplossen.<br><br>Onze excuses voor dit ongemak.'));
    include('template.inc.php'); // template includen
  }
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Upper/Lower Case.

code:
1
2
#define UP_CASE(ch)  ((ch) & 223)   
#define LOW_CASE(ch) ((ch) | 32)

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Beschrijving: Runtime Endianness bepalen.


Returned 1 als systeem Little Endian is, 0 als het Big Endian is.
code:
1
2
3
4
5
int little_endian(void)
{
    int iValue = 1;
    return (iValue == *((char*)&iValue));
}

Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

Taal: HTML/JS
Doel: Simpele routeplanner naar jouw adres
Waarschuwing!: Zelf even jouwstraat, jouwhuisnummer en jouw plaats invullen
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Route bepalen naar het me huis:&nbsp; <table border='0' ><tr><td width='100%'><form action='OpenWindow();'><b>Uw postcode:</b></td><td align='right'><input type='text' class='form' name='ZIPCODE'></td>
</tr>
<tr>
<td align='right' colspan='2'>
<hr style='width:100%;'>
<input class='button' type='button' value='bepaal route' onclick='OpenWindow();'></td></tr></table>

</form><script language='javascript'>
function OpenWindow()
{

RouteWindow = window.open('http://www.routenet.nl?main=asp/euroroute/euroadres.asp?viapunten=off&searchtype=1&STREET=&CITY=&ZIPCODE='+document.forms[0].ZIPCODE.value+'&COUNTRY=NL&STREET=jouwstraat+jouwhuisnummer&CITY=jouwstada&ZIPCODE=&COUNTRY=NL','Windowname'); 

}
</script><a href='http://www.routenet.nl'>[img]'http://www.routenet.nl/images/logo_routenet.gif'[/img]
<br><br>
Routeplanner door <a href='http://www.routenet.nl'>Routenet.nl</a>. Alle rechten voorbehouden.

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Visual Basic
Platform: Windows NT/2000/XP
Doel: CPU usage uitvragen

In de General-Declarations sectie van je form:
(als je het in een module zet kun "Private" weglaten)
code:
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
  Const SystemBasicInformation = 0
  Const SystemPerformanceInformation = 2
  Const SystemTimeInformation = 3
 
  Private Type LARGE_INTEGER
    LowPart As Long
    HighPart As Long
  End Type
 
  Private Type SYSTEM_BASIC_INFORMATION
    dwUnknown1 As Long
    uKeMaximumIncrement As Long
    uPageSize As Long
    uMmNumberOfPhysicalPages As Long
    uMmLowestPhysicalPage As Long
    uMmHighestPhysicalPage As Long
    uAllocationGranularity As Long
    pLowestUserAddress As Long
    pMmHighestUserAddress As Long
    uKeActiveProcessors As Long
    bKeNumberProcessors As Byte
    bUnknown2 As Byte
    wUnknown3 As Integer
  End Type
 
  Private Type SYSTEM_PERFORMANCE_INFORMATION
    liIdleTime As LARGE_INTEGER
    dwSpare(76) As Long
  End Type
 
  Private Type SYSTEM_TIME_INFORMATION
    liKeBootTime As LARGE_INTEGER
    liKeSystemTime As LARGE_INTEGER
    liExpTimeZoneBias As LARGE_INTEGER
    uCurrentTimeZoneId As Long
    dwReserved As Long
  End Type
 
  Private Declare Function NtQuerySystemInformation Lib "NTDLL" (ByVal SystemInformationClass As Long, SystemInformation As Any, ByVal SystemInformationLength As Long, ReturnLength As Long) As Long

De functies zelf:
code:
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
Private Function Li2Double(x As LARGE_INTEGER) As Double
  Li2Double = (x.HighPart * (2 ^ 32)) + x.LowPart
End Function
 
Private Function GetCPUusageNT() As Long
  Dim SysPerfInfo As SYSTEM_PERFORMANCE_INFORMATION
  Dim SysTimeInfo As SYSTEM_TIME_INFORMATION
  Dim SysBaseInfo As SYSTEM_BASIC_INFORMATION
  Dim dbIdleTime As Double
  Dim dbSystemTime As Double
  Dim Status As Long
 
  On Error Resume Next
 
  Status = NtQuerySystemInformation(SystemBasicInformation, SysBaseInfo, Len(SysBaseInfo), vbNull)
  If Status <> 0 Then Exit Function
 
  Status = NtQuerySystemInformation(SystemTimeInformation, SysTimeInfo, Len(SysTimeInfo), 0)
  If Status <> 0 Then Exit Function
 
  Status = NtQuerySystemInformation(SystemPerformanceInformation, SysPerfInfo, Len(SysPerfInfo), vbNull)
  If Status <> 0 Then Exit Function
 
  If Li2Double(liOldIdleTime) <> 0 Then
    dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime)
    dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime)
 
    dbIdleTime = dbIdleTime / dbSystemTime
 
    dbIdleTime = 100 - ((dbIdleTime * 100) / SysBaseInfo.bKeNumberProcessors)
 
    GetCPUusageNT = Int(dbIdleTime + 0.5)
  End If
 
  liOldIdleTime = SysPerfInfo.liIdleTime
  liOldSystemTime = SysTimeInfo.liKeSystemTime
End Function

Routines om de CPU usage onder Win9x/ME kun je overal op internet vinden (staat gewoon in de registry).

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Visual Basic
Doel: Kijken of een file bestaat
code:
1
2
3
4
5
6
7
8
9
10
11
Function FileExists(FileName As String) As Boolean
  Dim I As Integer

  On Error Resume Next
  I = Len(Dir(FileName, vbReadOnly + vbHidden + vbSystem))
  If Err Or (I = 0) Or (Trim$(FileName) = "") Then
    FileExists = False
  Else
    FileExists = True
  End If
End Function

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • Mr. B.
  • Registratie: Mei 2000
  • Niet online
Taal: Turbo Pascal/Assembly
Doel: Omzetten van een string in hoofd- of kleine letters (TP biedt standaard alleen functies om Chars te upper/lowercasen)
code:
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
function HoofdLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'a'
    JB @GEEN_KLEINE_LETTER
    CMP AL,'z'
    JA @GEEN_KLEINE_LETTER
    SUB AL, 20h
    @GEEN_KLEINE_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

function KleineLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'A'
    JB @GEEN_HOOFD_LETTER
    CMP AL,'Z'
    JA @GEEN_HOOFD_LETTER
    SUB AL, -20h
    @GEEN_HOOFD_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

StatBar.nl - @GoT

Het verschil tussen theorie en praktijk is in de praktijk altijd veel groter dan in theorie.


Acties:
  • 0 Henk 'm!

  • jelmervos
  • Registratie: Oktober 2000
  • Niet online

jelmervos

Simple user

Taal: Javascript
Doel: 'Autoaanvullen' voor een combobox via een editbox.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script language="JavaScript">
//<!--
function SearchSelectBox(in_sFormName, in_sInputName, in_sSelectName)
{
  sSearchString = document.forms[in_sFormName].elements[in_sInputName].value.toUpperCase();
  iSearchTextLength = sSearchString.length;
  for (x = 0; x < document.forms[in_sFormName].elements[in_sSelectName].options.length; x++)
  {
    sOptionText = document.forms[in_sFormName].elements[in_sSelectName].options[x].text;
    sOptionComp = sOptionText.substr(0, iSearchTextLength).toUpperCase();
    if(sSearchString == sOptionComp)
    {
    document.forms[in_sFormName].elements[in_sSelectName].selectedIndex = x;
    break;
    }
  }
}
//-->
</script>

"The shell stopped unexpectedly and Explorer.exe was restarted."


Acties:
  • 0 Henk 'm!

Verwijderd

Taal: PHP
Doel: Een pagina navigatie systeem genereren in de vorm
[ « < 2 3 4 5 6 > » ]

Code:
PHP:
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
<?
/**
 * @param $curpage De pagina waar men op dit moment is
 * @param $totalpage Het totaal aantal pagina's
 * @param $parseurl De url waar de pagina nummers naar moeten verwijzen, in de vorm "page.php?p=%%" waar %%
 *                  automatisch door het pagina nummer vervangen zal worden
 * @param $width (optioneel) maximum aantal pagina's voor er geschrapt gaat worden aan beide zijden (als in voorbeeld)
 */
function generatepages($curpage, $totalpages, $parseurl, $width=4)
{
   $thereiscurpage = ($curpage == -1) ? 0 : 1;
   if(!$thereiscurpage)
      $curpage = 0;
   
   $returnvalue = "";
   
   $pp = $curpage+1;
   
   if($pp > 1)
   {
      $url[boardpage] = str_replace('%%', 0, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;#171;</a> ";
      $url[boardpage] = str_replace('%%', $curpage-1, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;lt;</a> ";
   }
   $from = ($pp==1) ? 1 : $pp-$width;
   $to = $pp+$width;
   for($i=$from;$i<=$to;++$i)
   {
      if($i<=$totalpages &amp;&amp; $i>0)
      {
         $var[page] = $i;
         if($i == $pp &amp;&amp; $thereiscurpage)
            $returnvalue .= "<b>$var[page]</b> ";
         else
         {
            $url[boardpage] = str_replace('%%', $i-1, $parseurl);
            $returnvalue .= "<a href=\"$url[boardpage]\">$var[page]</a> ";
         }
      }
   }
   if($pp < $totalpages)
   {
      if($thereiscurpage)
      {
         $url[boardpage] = str_replace('%%', $curpage+1, $parseurl);
         $returnvalue .= "<a href=\"$url[boardpage]\">&amp;gt;</a> ";
      }
      $url[boardpage] = str_replace('%%', $totalpages-1, $parseurl);
      $returnvalue .= "<a href=\"$url[boardpage]\">&amp;#187;</a> ";
   }
   if($totalpages==1)
      return "";
   else
      return $returnvalue;
}
?>

Acties:
  • 0 Henk 'm!

Verwijderd

Taal = Visual Basic 6
Doel = Check of een ADO recordset leeg is
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Public Function RecordSetEmpty(rs As ADODB.Recordset) As Boolean
    
On Error GoTo ErrorHandler
    
    'is the recordset empty?
    RSEmpty = (rs.EOF And rs.BOF)
    
    Exit Function
ErrorHandler:

    Screen.MousePointer = vbDefault
    MsgBox "Error" & vbCrLf & Err.Description, vbCritical, App.ProductName

End Function

Acties:
  • 0 Henk 'm!

  • Woudloper
  • Registratie: November 2001
  • Niet online

Woudloper

« - _ - »

Taal: Visual Basic
Doel: Een String/Num teruggeven uit een tab delimited bestand. Stel:
strTest = "4 [tab] Tweakers zijn samen [tab] 4"

dan kan je met de GetNum(strTest) het getal 4 terugkrijgen en wordt strTest verkleint naar:

strTest = "Tweakers zijn samen [tab] 4"

Met GetStr(strTest) krijg je dan de string 'Tweakers zijn samen' terug.
code:
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
Private Function GetNum(ByRef line As String) As Double
' Description:  return a number, or error if a string is found or line is over
'          the component and the trailing tab is removed from the "line".

Dim s        As String
Dim i        As Long

    i = InStr(line, vbTab)
    
    If i > 0 Then            'there is a tab
      s = Left(line, i - 1)
      line = Mid(line, i + 1)
    Else                    'last component
      s = line
      line = ""
    End If

    If InStr(1, s, ".") > 0 Then    'There is a dot (.)
      s = Replace(s, ".", ",")
    End If

    'Verify it is a number
    If s <> "" Then          's contains come string
      If Not IsNumeric(s) Then    'throw an error
        Err.Raise 10001, "", "Argument not a number"
        GetNum = 0
        Exit Function
      End If
    End If
    
    If s = "" Then
      s = "0"
    End If

    GetNum = CDbl(s)            'Return value of the function.


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
End Function

Private Function GetStr(ByRef line As String) As String
' Description:  This function returns a String. This component and it's trailing TAB are
'          removed from the line and the line is given back as a ByRef variable.

Dim s        As String
Dim i        As Long

    i = InStr(line, vbTab)

    If i > 0 Then          ' there is a tab, because the value is higher than 0
      s = Left(line, i - 1)
      line = Mid(line, i + 1)
    Else                ' last component
      s = line
      line = ""
    End If

    GetStr = s

End Function

Acties:
  • 0 Henk 'm!

Verwijderd

Naam: html highlight script
Taal: PHP
Version: 0.1
Beschrijving:
Highlight de html code i.p.v. php
code:
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
<?php
    function keepIndent($value) {
      $value = preg_replace("/\t/", "&nbsp;&nbsp;&nbsp;&nbsp;", $value);
      return $value;
    }
    function addColor($value, $color) {
      return '<font color="' . $color . '">' . htmlentities(stripslashes($value)) . '</font>';
    }

    function doColor() {
      $args = func_get_args();
      $replace = addColor($args[0] . $args[1], "green");
      $replace .= addColor($args[2] . $args[3], "purple");
      $replace .= addColor($args[4], "red");
      $replace .= addColor($args[5], "green");


      return $replace;
    }
    $regexps =
      "/(<\/?)([a-z][a-z0-9]*)((\s[a-z\:]+)(\s?\=\s?)((\"|\')[a-z\s\#@0-9\_\-\.\/\?\,]*(\"|\')))*(>)/Ue"
    ;
    $replaces =
      "doColor('\\1', '\\2', '\\4', '\\5', '\\6', '\\9');"
    ;
    // gebruik (stel $html bevat wat html code)
    $html = preg_replace($regexps, $replaces, $html);
    print keepIndent(nl2br($html));
?>

Acties:
  • 0 Henk 'm!

  • SchizoDuckie
  • Registratie: April 2001
  • Laatst online: 18-02 23:12

SchizoDuckie

Kwaak

*swing*

Taal: PHP
Doel: word document (.doc) in lezen en omzetten naar schone html
Waarschuwing! je moet wel wvware geinstalleerd hebben.

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?
 $text = `/usr/local/bin/wvWare -x '/usr/local/share/wv/wvHtml.xml' -d '/tmp/' 'path/naar/document.doc'`; 
  
 while (strpos($text, '<b></b>') !== false) {$text = str_replace('<b></b>', '', $text);} 
 while (strpos($text, "\n</p>") !== false) {$text = str_replace("\n</p>", "</p>", $text);} 
 while (strpos($text, "\">\n") !== false) {$text = str_replace("\">\n", "\">", $text);} 
 while (strpos($text, '"></p>') !== false)  
      {  
           $close = strpos($text, '"></p>'); 
           $pos = strrpos(substr($text,0,$close),"<p"); 
           $length = ($close - $pos) + 6; 
           $text = str_replace( substr($text, $pos, $length) , '', $text); 
      } 
 while (strpos($text, "\n\n") !== false) {$text = str_replace("\n\n", "\n", $text);} 
  
 echo($text);
 
?>

Stop uploading passwords to Github!


Acties:
  • 0 Henk 'm!

  • JaQ
  • Registratie: Juni 2001
  • Laatst online: 12:14

JaQ

Taal: PL/SQL
Doel: Converteren van een kolom in een tabel naar EURO (in dit geval vanaf BEF)
Usage: exec pck_convert(<<tabelnaam>>,<<kolomnaam>>,<<sleutel1>>,<<optional: sleutel2>>,<<optional: sleutel 3>>);


rem Title:pck_log.sql
rem Version: 1.0
rem Last update date: 04-DEC-01
rem Purpose: This package is used as a logging package for the euro conversion.
rem It contains a procedure for cleaning the log.
rem The procedure log exists more than once. This is a technique called
rem overloading. Oracle will decide automatically which procedure fits
rem by checking the parameters.
rem Dependencies: The eur_log table has to be created
rem Parameters: 1. username
rem 2. password
rem 3. database
rem
rem History:
rem 04-DEC-01 JLCreation of this script
rem

prompt define parameters as follows
prompt [1] user [2] password [3] database

define p_username = '&1'
define p_password = '&2'
define p_database = '&3'

connect &p_username/&p_password@&p_database

create or replace package pck_log
is
procedure clear_log
(p_scriptname eur_log.scriptname%type);
--
procedure log
( p_scriptname eur_log.scriptname%type
, p_notes eur_log.notes%type);
--
procedure log
( p_scriptname eur_log.scriptname%type
, p_tablename eur_log.table_name%type
, p_columnname eur_log.column_name%type
, p_type eur_log.type%type
, p_notes eur_log.notes%type);
--
end pck_log;
/

show errors

create or replace package body pck_log
is
--
procedure clear_log
(p_scriptname eur_log.scriptname%type)
is
begin
--
delete from eur_log
where scriptname = p_scriptname;
--
exception
when others then
log (p_scriptname,'Cleaning log failed : ' || substr (sqlerrm, 1, 100));
end;
--
procedure log
(p_scriptname eur_log.scriptname%type
,p_notes eur_log.notes%type)
is
begin
insert
into eur_log
( timestamp
, scriptname
, table_name
, column_name
, type
, notes)
values
( sysdate
, p_scriptname
, 'NONE'
, 'NONE'
, 'FAIL'
, p_notes);

end;

procedure log
(p_scriptname eur_log.scriptname%type
,p_tablename eur_log.table_name%type
,p_columnname eur_log.column_name%type
,p_type eur_log.type%type
,p_notes eur_log.notes%type)
is

begin
--
insert
into eur_log
( timestamp
, scriptname
, table_name
, column_name
, type
, notes)
values
( sysdate
, p_scriptname
, p_tablename
, p_columnname
, p_type
, p_notes);
--
end log;
--
end pck_log;
/


rem Title: pck_convert.sql
rem Version: 1.4
rem Last Update Date: 12-DEC-01
rem Author: Jacco Landlust
rem Purpose: This package is used for converting data to euro.
rem The package works as follows:
rem 1. clear log
rem 2. build pl/sql block dynamicly according to the input
rem parameters
rem 3. execute code
rem ad1. clearing the log is done by the log-handling package
rem called pck_log.
rem ad2. the pl/sql block is build by different functions.
rem for each part of the pl/sql block a seperate function
rem exists. This way small changes on this block are easier
rem to implement.
rem ad3. executing the code is done through native pl/sql, using
rem the execute immediate function. (EXECUTE IMMEDIATE <<CODE>>)
rem this is only possible in Oracle 8.0 databases or newer.
rem If this package is needed in older Oracle databases,
rem a exec_sql function should be build, using
rem the dbms_sql.exec_sql function to execute the code.
rem
rem = Short description of the dynamicly build PL/SQL block =
rem The "header" of the sql-block is the variable definition
rem also a exception and a pragma exeception init get defined
rem this exception will handle the oracle error "snapshot too old"
rem This error is a well know error that occurs while using cursors
rem with a lot of rows that get updated.
rem Cursor definition depends on the keys that are given into
rem the procedure.
rem The body part of the pl/sql block is the part where all the
rem "action" is going on. Values get divided by the euro constant
rem that is defined in the package. Also logging of the rounding
rem differences and the update of the data happenes here. The
rem global constant gc_test defines whether data actually gets
rem updated, or if the outcome is written to the logtable (test
rem conversion). The only tricky part in the body is the snapshot
rem too old handling. If the cursor breaks and comes back with the
rem snapshot too old message, the pl/sql block rolls back to the last
rem savepoint. The cursor is getting rebuild from the point where it
rem broke, and it will continue automaticly.
rem The footer is the logging and exception handling part of the code.
rem
rem Paramaters: 1. username
rem 2. password
rem 3. database
rem
rem History:
rem 04-DEC-01 JL Creation of this document
rem 05-DEC-01 JL Added the pk's as parameters. The primary keys help the script
rem to identify the record.
rem 05-DEC-01 JL Replaced the exec_sql procedure (uses dbms_sql package) with
rem execute immediate (native). Also split up the build_code
rem function into different functions, to make additions easier.
rem 06-DEC-01 JL Added changes for changed logging
rem 12-DEC-01 JL Introduced gc_test constant, to be able to run this package on a
rem production environment. The outcome will be inserted into a log
rem table, instead of updating the "to be converted" table.
rem

prompt define parameters as follows
prompt [1] username [2] password [3] database

define p_usr = '&1'
define p_psw = '&2'
define p_db = '&3'

set verify off

whenever sqlerror exit failure

connect &p_usr/&p_psw@&p_db


create or replace package pck_convert is

procedure to_euro
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null);

function build_code
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2;

end pck_convert;
/
show errors

create or replace package body pck_convert
is

--
-- Global variable definition
--
gv_script varchar2(30) := 'pck_convert';
gv_eur_value number := 40.3399;
gc_test boolean := false;

function build_header
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: this function will build the first part of the pl/sql block
-- that is used for conversion to euro.
--
-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := 'declare ' ||
' gv_euro_value number; ' ||
' lv_script eur_log.scriptname%type; ' ||
' lv_new_value number; ' ||
' lv_pk1 ' || p_tablename || '.' || p_pk1 || '%type; ';

-- if there is only 1 primary key, the other key variable usages are not need

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 ' || p_tablename || '.' || p_pk2 || '%type; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk3 ' || p_tablename || '.' || p_pk3 || '%type; ';
end if;

lv_statement := lv_statement ||
' lv_rounding_difference number; ' ||
' lv_rows_processed pls_integer; ' ||
' lv_wrong pls_integer; ' ||
' lv_valid_snapshot boolean; ' ||
' snapshot_too_old exception; ' ||
' pragma exception_init (snapshot_too_old, -1555); ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_header',p_tablename, p_columnname, 'Fail: ', substr (sqlerrm, 1, 100));
end build_header;

function build_cursor
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: This function is used for building the cursor that is used in
-- the pl/sql block that is used for the conversion to euro.

-- local variable definitions
--
lv_statement varchar2(20000);

begin

lv_statement := ' cursor c_values ' ||
' ( cp_pk1 ' || p_tablename || '.' || p_pk1 || '%type default null ';

-- use statements for primary keys only is needed.

if p_pk2 is not null then
lv_statement := lv_statement || ' , cp_pk2 ' || p_tablename || '.' || p_pk2 || '%type default null ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , cp_pk3 ' || p_tablename || '.' || p_pk3 || '%type default null ';
end if;

lv_statement := lv_statement || ') ' ||
' is ' ||
' select ' || p_columnname || ' cn ' ||
' , ' || p_pk1 || ' pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' , ' || p_pk2 || ' pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , ' || p_pk3 || ' pk3 ';
end if;

lv_statement := lv_statement ||
' from ' || p_tablename ||
' where ' || p_pk1 || ' >= nvl (cp_pk1, ' || p_pk1 || ') ';

if p_pk2 is not null then
lv_statement := lv_statement || ' and ' || p_pk2 || ' >= nvl (cp_pk2, ' || p_pk2 || ') ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' and ' || p_pk3 || ' >= nvl (cp_pk3, ' || p_pk3 || ') ';
end if;

lv_statement := lv_statement ||
' order by ' || p_pk1;

if p_pk2 is not null then
lv_statement := lv_statement || ', ' || p_pk2;
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ', ' || p_pk3;
end if;

lv_statement := lv_statement || '; ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_cursor', p_tablename, p_columnname, 'Fail: ', substr (sqlerrm, 1, 100));
end build_cursor;

function build_body
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is
-- Purpose: This function will create the body text of the pl/sql block
-- that is used for conversion to euro. All "main" converting
-- will occurr in this part.

-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := 'begin ' ||
' lv_script := ' || '''' || 'pck_convert.build_code' || '''' || '; ' ||
' pck_log.clear_log (lv_script); ' ||
' commit; ' ||
' lv_rows_processed := 0; ' ||
' lv_wrong := 0; ' ||
' lv_pk1 := null; ';

-- only use key variables if needed

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 := null; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk3 := null; ';
end if;

lv_statement := lv_statement ||
' lv_valid_snapshot := false; ' ||
' gv_euro_value := 40.3399; ' ||
' while lv_valid_snapshot = false loop ' ||
' lv_valid_snapshot := true; ' ||
' begin ' ||
' for r_values in c_values ' ||
' (lv_pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' , lv_pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' , lv_pk3 ';
end if;

lv_statement := lv_statement || ') ' ||
' loop ' ||
' begin ' ||
' savepoint euro_conv; ' ||
' lv_rounding_difference := 0; ' ||
' lv_new_value := r_values.cn / gv_euro_value; ' ||
' lv_pk1 := r_values.pk1; ';

if p_pk2 is not null then
lv_statement := lv_statement || ' lv_pk2 := r_values.pk2; ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' lv_pk2 := r_values.pk3; ';
end if;

lv_statement := lv_statement ||
' lv_rounding_difference := round (lv_new_value, 2) - lv_new_value; ' ||
' lv_new_value := round (lv_new_value, 2); ';

-- updating depends on the constant gc_test which indicates if it is a testconversion or a
-- definitive conversion.
if gc_test = true then

lv_statement := lv_statement ||
'pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ', ' || '''' || p_columnname || '''' || ', ' ||
'''' || 'TEST' || '''' || ', ' || '''' || p_pk1 || ' = ' || '''' || '||' || ' lv_pk1' || '||';

if p_pk2 is not null then

lv_statement := lv_statement ||
'''' || p_pk2 || ' = ' || '''' || '||' || ' lv_pk2 ' || '|| ' ;

end if;
if p_pk3 is not null then

lv_statement := lv_statement ||
'''' || p_pk3 || ' = ' || '||' || 'lv_pk3 ' || '|| ' ;

end if;

lv_statement := lv_statement ||
'''' || ' old_value = ' || '''' || '||' || 'r_values.cn' || '||' || '''' ||
' new_value = ' || '''' || '||' || 'lv_new_value)';

else

lv_statement := lv_statement ||
' update ' || p_tablename ||
' set ' || p_columnname || ' = lv_new_value ' ||
' where ' || p_pk1 || ' = r_values.pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' and ' || p_pk2 || ' = ' || 'r_values.pk2 ';
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' and ' || p_pk3 || ' = ' || 'r_values.pk3 ';
end if;
end if;

lv_statement := lv_statement || '; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' ||',' || '''' || p_columnname || '''' || ',' || '''' || 'ROUND' || '''' || ',' || ' lv_rounding_difference ); ' ||
' lv_rows_processed := lv_rows_processed + 1; ' ||
' commit; ' ||
' exception ' ||
' when snapshot_too_old then ' ||
' raise snapshot_too_old; ' ||
' when others then ' ||
' rollback to euro_conv; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'FAIL' || '''' || ',' || '''' || p_pk1 || ' = ' || '''' || '||' || 'lv_pk1 ';

if p_pk2 is not null then
lv_statement := lv_statement || ' || ' || '''' || p_pk2 || ' = ' || '''' || '||' || ' lv_pk2 ' ;
end if;
if p_pk3 is not null then
lv_statement := lv_statement || ' || ' || '''' || p_pk3 || ' = ' || '''' || '||' || ' lv_pk3 ' ;
end if;

lv_statement := lv_statement || '||' || '''' || ' ' || '''' || '||' || 'substr(sqlerrm, 1, 100)); ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_body' , p_tablename, p_columnname, 'FAIL' , substr (sqlerrm, 1, 100));
end build_body;

function build_footer
(p_tablename all_tab_columns.table_name%type
,p_columnname all_tab_columns.column_name%type)
return varchar2
is

-- Purpose: This function will build the error handling and logging part of the pl/sql block
-- that is used for converting to euro.

--
-- local variable definitions
--
lv_statement varchar2(10000);

begin

lv_statement := ' commit; ' ||
' lv_wrong := lv_wrong + 1; ' ||
' end; ' ||
' end loop; ' ||
' exception ' ||
' when snapshot_too_old then ' ||
' rollback; ' ||
' lv_valid_snapshot := false; ' ||
' end; ' ||
' end loop; ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'RP' || '''' || ',' || 'lv_rows_processed); ' ||
' pck_log.log (lv_script, ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'RF' || '''' || ',' || 'lv_wrong); '||
' commit; ' ||
'exception ' ||
' when others then ' ||
' pck_log.log (lv_script '|| ', ' || '''' || p_tablename || '''' || ',' || '''' || p_columnname || '''' || ',' || '''' || 'FAIL' || '''' || ',' || ' substr (sqlerrm, 1, 100)); ' ||
'end; ';

return (lv_statement);

exception
when others then
pck_log.log (gv_script || '.build_footer', p_tablename, p_columnname ,'FAIL' , substr (sqlerrm, 1, 100));
end build_footer;

function build_code
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
return varchar2
is

-- local variable definitions
--
lv_statement varchar2(30000);

begin

-- reset variables

lv_statement := null;

-- build code

lv_statement :=
build_header (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_cursor (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_body (p_tablename, p_columnname, p_pk1, p_pk2, p_pk3) ||
build_footer (p_tablename, p_columnname);

return (lv_statement);

end build_code;

procedure to_euro
( p_tablename all_tab_columns.table_name%type
, p_columnname all_tab_columns.column_name%type
, p_pk1 all_tab_columns.column_name%type
, p_pk2 varchar2 default null
, p_pk3 varchar2 default null)
is

lv_statement varchar2(30000);
begin

-- clear log
pck_log.clear_log (gv_script);

-- build code
lv_statement := build_code(p_tablename, p_columnname, p_pk1, p_pk2, p_pk3);

-- execute code
execute immediate lv_statement;

commit;

exception
when others then
pck_log.log(gv_script || '.to_euro', p_tablename, p_columnname, 'FAIL' , substr (sqlerrm, 1, 100));
commit;
end to_euro;

end pck_convert;
/


show errors

Extra toelichting

De logging package is nodig, omdat het teruggeven van foutmeldingen vanuit Native niet mogelijk is...

Egoist: A person of low taste, more interested in themselves than in me


Acties:
  • 0 Henk 'm!

Verwijderd

Offtopic: WAT zijn jullie in vredensnaam aan het doen dan?, ik bedoel, ik heb het geprobeerd te begrijpen, maar lukt dus niet echt. Ik zie alleen maar rare tekentjes hmmm

Acties:
  • 0 Henk 'm!

  • Mior
  • Registratie: Maart 2000
  • Laatst online: 13:22
Op woensdag 06 februari 2002 04:06 schreef Pjoeloe het volgende:
Offtopic: WAT zijn jullie in vredensnaam aan het doen dan?, ik bedoel, ik heb het geprobeerd te begrijpen, maar lukt dus niet echt. Ik zie alleen maar rare tekentjes hmmm
|:(

Dat noemen ze nou 'programmeren'.

Acties:
  • 0 Henk 'm!

Verwijderd

OK, das dus niet voor mij weggelegd!

Acties:
  • 0 Henk 'm!

Verwijderd

Op woensdag 06 februari 2002 22:53 schreef Pjoeloe het volgende:
OK, das dus niet voor mij weggelegd!
:D

Acties:
  • 0 Henk 'm!

  • LuCarD
  • Registratie: Januari 2000
  • Niet online

LuCarD

Certified BUFH

Op woensdag 06 februari 2002 22:53 schreef Pjoeloe het volgende:
OK, das dus niet voor mij weggelegd!
In ieder geval....

Welcome :)

Tip: lees de faq daar staan een aantal leuke tutorials als je toch besluit te beginnen ;)

Programmer - an organism that turns coffee into software.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: Alle environmental variablelen displayen (werkt ook via webserver / browser (CGI))
code:
1
2
3
4
5
6
7
8
#!perl -Tw
 
use strict;
 
print "Content-type: text/plain\n\n";
foreach (keys %ENV)
{ print "$_ = $ENV{$_}\n";
}

Intructie: Sla dit op als env.pl, chmod het naar 755 (chmod 755 env.pl) en run het op de command line of via je webserver (cgi-bin dir enzo...)

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: checken of een integer een prime (priemgetal) is.
Usage: Sla deze text op als prime.pl, chmod het naar 755 en run het met een getal als argument (bv 'prime.pl 101')
Humor: het algoritme is slechts 1 regel code.
code:
1
2
3
4
5
6
7
8
9
10
#!perl -Tw

use strict;

if ((1 x $ARGV[0]) !~ m/^(11+)\1+$/)
{ print "$ARGV[0] is a prime!\n";
}
else
{ print "Sorry but $ARGV[0] ain't a prime number.\n";
}

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 13:27
Op donderdag 07 maart 2002 11:20 schreef Jaaap het volgende:
code:
1
if ((1 x $ARGV[0]) !~ m/^(11+)\1+$/)
Wat een ontzettend ranzige methode =) Wel leuk gevonden trouwens.
Een andere leuke methode om een ONEINDIGE reeks priemgetallen te genereren, is de volgende. (Voor een functionele programmeertaal als Clean, Miranda of Haskell):
code:
1
Start = s [2..] where s [p:r] = [p:s [i \\ i <- r | i mod p <> 0]]

Acties:
  • 0 Henk 'm!

  • Ronald_stage
  • Registratie: Januari 2002
  • Laatst online: 28-09 13:06

Ronald_stage

wat kan je hier nog zeggen

TAAL: vb
Function: Disable X
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Option Explicit
Private Declare Function GetSystemMenu Lib "user32" _
    (ByVal hwnd As Long, ByVal bRevert As Long) As Long

Private Declare Function RemoveMenu Lib "user32" _
    (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
    Private Const MF_BYPOS = &H400&
=========================================================

Private Sub Form_Load()
 DisableCloseButton Me.hwnd
End Sub

=========================================================

Public Sub DisableCloseButton(hwnd As Long)
    Dim hSysMenu As Long
    hSysMenu = GetSystemMenu(hwnd, 0)
    Call RemoveMenu(hSysMenu, 6, MF_BYPOS)
    Call RemoveMenu(hSysMenu, 5, MF_BYPOS)
End Sub

Acties:
  • 0 Henk 'm!

  • Juup
  • Registratie: Februari 2000
  • Niet online
Taal: Perl
Doel: het maken van een index file in een dir waar allemaal plaatjes instaan en z'n subdirs (recursief). In de index.html file zijn dan alle plaatjes te zien.
code:
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
#!perl -Tw
 
use strict;
my @dirs;
$dirs[0] = "/web/htdocs/images";   #change this to your dir
 
foreach my $dir (@dirs)
{ opendir (DIR, $dir) || die $!;
  my @localdirs;
  my @localfiles;
  while (defined (my $filename = readdir(DIR)))
  { if ((-d "$dir/$filename") && ($filename !~ /^\./))
    { push @dirs, "$dir/$filename";
    push @localdirs, "<a href=\"$filename/\">$filename</a><br>\n";
    }
    if (( -f "$dir/$filename" ) && ($filename =~ /\.(gif|jpg|png)$/))
    { push @localfiles, "<a href=\"$filename\">[img]\"$filename\"[/img]<br>$filename</a><br><br><br>\n";
    }
  }
  closedir (DIR);
  open (FH, ">$dir/index.html") || die $!;
  print FH "<html>\n<head>\n<title>image index for $dir</title>";
  print FH "</head>\n<body>\n<center>\n<h1>Image Index for $dir</h1><br>\n";
  foreach (sort(@localdirs))
  { print FH $_;
  }
  print FH "<br>\n<br>\n";
  foreach (sort(@localfiles))
  { print FH $_;
  }
  print FH "</center>\n</body>\n</html>\n";
  close (FH);
}

Een wappie is iemand die gevallen is voor de (jarenlange) Russische desinformatiecampagnes.
Wantrouwen en confirmation bias doen de rest.


Acties:
  • 0 Henk 'm!

Verwijderd

Op donderdag 07 maart 2002 11:20 schreef Jaaap het volgende:
Doel: checken of een integer een prime (priemgetal) is.
[..]
Op donderdag 07 maart 2002 12:10 schreef Soultaker het volgende:

[..]

Een andere leuke methode om een ONEINDIGE reeks priemgetallen te genereren, is de volgende.
LEES! (sorry voor het schreeuwe)
enne regexp's zijn nou enmaal ranzig

Acties:
  • 0 Henk 'm!

  • Grum
  • Registratie: Juni 2001
  • Niet online
Op donderdag 07 maart 2002 15:21 schreef Foxboy het volgende:
LEES! (sorry voor het schreeuwe)
enne regexp's zijn nou enmaal ranzig
'andere' doelt niet altijd op een vorige post hoor :) maar ok

btw je vind perl kontschoppen en regexps ranzig ? .. dan mis je et sterkste staaltje uit de taal man :)

Acties:
  • 0 Henk 'm!

  • Dope-E
  • Registratie: Januari 2001
  • Laatst online: 30-05 12:05

Dope-E

The one and only Dope

Taal: VB(script) (vast wel naar andere taal om te bouwen ;))
Doel: Bijvoorbeeld pw's encrypted in db opslaan of in cookies...

als iemand inlogd eerst hash maken dan vergelijken met db...
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'encryptie algorithme... oneway --> hash
Function Hash(ByVal text)
    dim a
    dim i

    a=1
    For i = 1 to len(text)
        a=sqr(a*i*asc(mid(text,i,1))) 'Numeric Hash
    Next
    
    Rnd(-1)
    Randomize a

    For i = 1 to 16
        Hash = Hash & Chr(int(rnd*256)) 'Char Hash
    Next
End function

Voorbeeld: "test" wordt "ÕÎ0ûñÄg\íêÖ"

edit:

Zou misschien wel leuk zijn om te kijken of iemand dit kan omdraaien... dus de hash als invoer en de tekst als uitvoer, misschien een }:O bij nodig :?
:+

twitter.com/curly_sanders


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 13:27
Op donderdag 07 maart 2002 15:21 schreef Foxboy het volgende:
LEES! (sorry voor het schreeuwe)
Ik erger me er toch aan. Ik wist heus wel wat jou code en de mijne deed hoor. Omdat jij een compact en nogal obfuscated stukje code gaf voor het controleren van priemgetallen, gaf ik een ANDER stukje code over priemgetallen, dat OOK compact en enigszins obfuscated was en de leuke eigenschap had 't een oneindige reeks oplevert.
enne regexp's zijn nou enmaal ranzig
Hier wel, maar dat maakt de code snippet juist zo leuk (hoewel niet echt prakisch). Meestal kunnen regexps wel zinnig worden gebruikt.

Acties:
  • 0 Henk 'm!

  • Janoz
  • Registratie: Oktober 2000
  • Laatst online: 07:50

Janoz

Moderator Devschuur®

!litemod

En nu ophouden met dat gelul ;) en code posten. Daar is dit topic voor bedoeld :)..

Ken Thompson's famous line from V6 UNIX is equaly applicable to this post:
'You are not expected to understand this'


Acties:
  • 0 Henk 'm!

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 13:27
Vooruit dan maar, een stukje Clean code (hoewel 't waarschijnlijk ook wel in andere functionele programmeertalen aan de praat te krijgen is) voor het berekenen van 'n CRC32 checksum (volgens de ISO 3309 standaard). Wordt veel gebruikt in archiefbestandsformaten e.d.
code:
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
/* The CRC type: a 32-bit integer (considered unsigned) */
:: CRC   :== Int

/* Generate CRC table in a constant application form */
crcTable :: {#CRC}
crcTable
=: { iterate step n !! 8 \\ n <- [0..255] }
where
    /* apply a CRC iteration step on an integer */
    step i
    | i bitand 1 == 1 = 0xEDB88320 bitxor (i >>! 1)
    | otherwise  = i >>! 1
    
/* Returns the CRC32 value of a given string. */
crc :: (!{#Char} -> CRC)
crc = crcUpdate 0

/* Updates a given CRC32 value with a certain string.
This function can be used to calculate the CRC32 value in portions, instead
of loading all input data into memory and processing it at once. The following
expressions are equivalent: (crcUpdate (crc a) b) <==> (crc (a++b)) */
crcUpdate :: !CRC !{#Char} -> CRC
crcUpdate crc str
= bitnot (update (bitnot crc) 0)
where
    length = size str
    
    update :: !CRC !Int -> CRC
    update crc i
    | i == length = crc
    | otherwise   = update crc` (i+1)
    where
      chr  = toInt str.[i]
      crc` = (crcTable.[(crc bitxor chr) bitand 0xFF]) bitxor (crc >>! 8)

Omdat Clean eigenlijk niet aan unsigned integers doet, heb ik >>! gedefinieerd als unsigned right shift operator:
code:
1
2
3
4
5
6
7
8
/* Unsigned right shift operation on (signed) integers */
(>>!) infix 7 :: !Int !Int -> Int
(>>!) i n
| n >= 0  = result
where
    result
    | i >= 0 = i >> n
    | i < 0  = ((i bitand 0x7FFFFFFF) >> n) bitor (1 << (31-n))

Acties:
  • 0 Henk 'm!

  • chaozz
  • Registratie: Juni 2000
  • Laatst online: 29-08 01:01

chaozz

Retrofiel

Op dinsdag 08 januari 2002 22:40 schreef Mr. B. het volgende:
Taal: Turbo Pascal/Assembly
Doel: Omzetten van een string in hoofd- of kleine letters (TP biedt standaard alleen functies om Chars te upper/lowercasen)
code:
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
function HoofdLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'a'
    JB @GEEN_KLEINE_LETTER
    CMP AL,'z'
    JA @GEEN_KLEINE_LETTER
    SUB AL, 20h
    @GEEN_KLEINE_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;

function KleineLetters(S: string): string;
begin
  asm
    CLD
    LEA SI,S
    LES DI,@Result
    SEGSS LODSB
    STOSB
    XOR AH,AH
    XCHG AX,CX
    JCXZ @EINDE
    @BEGIN_LUS:
    SEGSS LODSB
    CMP AL,'A'
    JB @GEEN_HOOFD_LETTER
    CMP AL,'Z'
    JA @GEEN_HOOFD_LETTER
    SUB AL, -20h
    @GEEN_HOOFD_LETTER:
    STOSB
    LOOP @BEGIN_LUS
    @EINDE:
  end;
end;
dat kan toch veel simpeler?
code:
1
2
3
4
5
6
7
8
9
function MaakUpcase(strOud: string) : string;
var strNieuw, Waarde;

begin
 for Waarde := 1 to Length(strOud)
  strNieuw : = StrNieuw + Upcase(strOud[Waarde]);

 MaakUpcase := strNieuw;
end;

kan me vergissen, tis alweer een tijdje geleden. >:)

chaozz.nl | RetroGameCouch


Acties:
  • 0 Henk 'm!

  • rvrbtcpt
  • Registratie: November 2000
  • Laatst online: 28-09 09:14
Taal: Java
Doel: Controle of een ingevoerde datum geldig is
Code:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try {
  System.out.println("SimpleDateFormatter check op de datum -> "+begindatum );
  // Format the current time.
  SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
  Date testDatum = formatter.parse(begindatum);
  String checkDatum = formatter.format(testDatum);
  if( checkDatum.equals(begindatum) ) {
    // Goed!
  } else {
    // Fout!
    System.out.println("Ongeldige datum. Goede datum : "+checkDatum+" ?? ");
  }
  System.out.println("SimpleDateFormatter check op de datum -> OK  ("+testDatum+")" );
} catch( java.text.ParseException fout ) {
    System.out.println("Ongeldige datum.");
}

Uitleg:
De standaard Java datum class wordt gebruikt om te controleren of een String (begindatum) correct is ingevoerd.
Het leuke van de Java date class is dat een ongeldige datum wordt omgezet in een correcte datum.
Dus 32-01-2002 wordt 01-02-2002. Deze datum staat in de variabele: checkDatum.
Deze heb ik gebruikt om user input te valideren en vervolgens de misschien correcte datum als output bij de error mee te geven.

Acties:
  • 0 Henk 'm!

  • Limhes
  • Registratie: Oktober 2001
  • Laatst online: 28-09 17:41
Voor degenen die een MSN progsel in C# willen maken en anderen:

Taal: C#
Platform: alles waar .NET op draait
Doel: op een simpele manier een md5 hash genereren
code:
1
2
3
4
5
6
7
8
9
10
using System.Web.Security;

class Test
{
  static void Main()
  {
    string sToMD5 = "ditmoetgehashedworden";
    string sFromMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(sToMD5, "md5");
  }
}

Acties:
  • 0 Henk 'm!

Verwijderd

Taal: C/C++
Doel: het berekenen van face en vertex normals uit vertexdata. Gebruikt facenormals voor het bepalen van een smoothing angle tussen faces zodat de vertexnormals van gesharede vertices wel/niet worden bepaald uit het middelen van de facenormal van de aangrenzende faces (still with me? :))
code:
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
// Purpose: calculates the face and vertexnormals for all the faces and vertices in the model.
void
CalculateNormals(SModel *pTheModel, float fSmoothingAngle)
{
    int         iFaceCnt, iFaceCnt2, iVertexCnt, iCurrentVertexIndx;
    SFace       *pCurrentFace;
    SVect3      vA, vB, vNormal, vTmpResult;
    int         *arrpiAmFacesPerVertex, *arrpiFPVIndices, **arrpiFacesPerVertex;
    double      dAngle;

    // Free up the eventually allocated VertexNormals array, we don't use it anymore.
    if(pTheModel->m_pVertexNormals)
    {
        // remove the memory, we don't know if it's large enough
        free(pTheModel->m_pVertexNormals);
    }

    // Allocate memory for the counterarray per vertex for the amount of faces the vertices are in.
    arrpiAmFacesPerVertex=(int *)malloc(sizeof(int) * pTheModel->m_iAmVertices);
    memset(arrpiAmFacesPerVertex, 0, sizeof(int) * pTheModel->m_iAmVertices);
    // allocate memory for the indices array per vertex, for the indices in the arrays per vertex in arrpiFacesPerVertex[][]
    arrpiFPVIndices=(int *)malloc(sizeof(int) * pTheModel->m_iAmVertices);
    memset(arrpiFPVIndices, 0, sizeof(int) * pTheModel->m_iAmVertices);
    // allocate the pointerarray for the arrays per vertex where the faceindices are stored.
    arrpiFacesPerVertex=(int **)malloc(sizeof(int *) * pTheModel->m_iAmVertices);
    memset(arrpiFacesPerVertex, 0, sizeof(int *) * pTheModel->m_iAmVertices);

    // first, calculate all facenormals for each face in the model.
    for(iFaceCnt = 0;iFaceCnt < pTheModel->m_iAmFaces;iFaceCnt++)
    {
        pCurrentFace=&pTheModel->m_pFaces[iFaceCnt];
        // calculate the vectors that make up the face plane, using the 3 vertices of this face
        vA[0]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][0] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][0];
        vA[1]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][1] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][1];
        vA[2]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[0]][2] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][2];
        vB[0]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][0] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][0];
        vB[1]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][1] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][1];
        vB[2]=pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[2]][2] - 
                    pTheModel->m_pVertices[pCurrentFace->m_iVertexIndices[1]][2];

        // Crossproduct to get the normal. (B x A, otherwise we end up with normals facing to the inside of the model)
        CrossProductVect3(vB, vA, vNormal);
        // Normalize vNormal
        Vector3Normalize(vNormal);
        // store face normal
        pCurrentFace->m_vFaceNormal[0]=vNormal[0];
        pCurrentFace->m_vFaceNormal[1]=vNormal[1];
        pCurrentFace->m_vFaceNormal[2]=vNormal[2];
        // reset vertexnormals
        pCurrentFace->m_vVertexNormals[0][0]=0.0f;
        pCurrentFace->m_vVertexNormals[0][1]=0.0f;
        pCurrentFace->m_vVertexNormals[0][2]=0.0f;
        pCurrentFace->m_vVertexNormals[1][0]=0.0f;
        pCurrentFace->m_vVertexNormals[1][1]=0.0f;
        pCurrentFace->m_vVertexNormals[1][2]=0.0f;
        pCurrentFace->m_vVertexNormals[2][0]=0.0f;
        pCurrentFace->m_vVertexNormals[2][1]=0.0f;
        pCurrentFace->m_vVertexNormals[2][2]=0.0f;

        // add the amount faces per vertex counters for the vertices in the current face.
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[0]]++;
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[1]]++;
        arrpiAmFacesPerVertex[pCurrentFace->m_iVertexIndices[2]]++;
    }

    // now per vertex, allocate an array of face indices where we'll store per face the vertex is in, the index
    // of that face. 
    for(iVertexCnt = 0; iVertexCnt < pTheModel->m_iAmVertices;iVertexCnt++)
    {
        if(arrpiAmFacesPerVertex[iVertexCnt] > 0)
        {
            arrpiFacesPerVertex[iVertexCnt]=(int *)malloc(sizeof(int) * arrpiAmFacesPerVertex[iVertexCnt]);
            memset(arrpiFacesPerVertex[iVertexCnt], 0 , sizeof(int) * arrpiAmFacesPerVertex[iVertexCnt]);
        }
    }

    // walk all the faces, store each face's index in the current free slot in the faceindex array of the particular
    // vertex. 
    for(iFaceCnt=0;iFaceCnt<pTheModel->m_iAmFaces;iFaceCnt++)
    {
        for(iVertexCnt = 0;iVertexCnt < 3;iVertexCnt++)
        {
            iCurrentVertexIndx=pTheModel->m_pFaces[iFaceCnt].m_iVertexIndices[iVertexCnt];
            arrpiFacesPerVertex[iCurrentVertexIndx][arrpiFPVIndices[iCurrentVertexIndx]++]=iFaceCnt;
        }
    }

    // Now, walk all vertices. Per vertex, we'll calculate for each face this vertex is in, the vertexnormal,
    // by averaging the facenormals of all the faces that are in the same smoothgroup. faces are in the same
    // smoothgroup when the angle between the normals of these faces is < ANGLE_SMOOTH. We determine the angle
    // with the dotproduct (which results in the cos(angle) * length A * length B. Since length of the normals
    // is 1.0, we leave these out of it).
    for(iVertexCnt=0;iVertexCnt<pTheModel->m_iAmVertices;iVertexCnt++)
    {
        
        for(iFaceCnt=0;iFaceCnt<arrpiAmFacesPerVertex[iVertexCnt];iFaceCnt++)
        {
            // Store face normal as startvalue in the vTmpResult vector which will contain the
            // calculation result for this vertex-face combination
            vTmpResult[0]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[0];
            vTmpResult[1]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[1];
            vTmpResult[2]=pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal[2];

            // Walk the complete facelist of this vertex again, and check whether the facenormal of
            // each face should be averaged with the vTmpResult. This will only be done when the angle
            // between the normal of the face iFaceCnt and the face iFaceCnt2 < ANGLE_SMOOTH, AND iFaceCnt != iFaceCnt2
            for(iFaceCnt2=0;iFaceCnt2<arrpiAmFacesPerVertex[iVertexCnt];iFaceCnt2++)
            {
                if(iFaceCnt==iFaceCnt2)
                {
                    // the same, skip
                    continue;
                }
                // Test if the angle between the facenormals is < ANGLE_SMOOTH
                dAngle=DotProductVect3(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vFaceNormal,
                            pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt2]].m_vFaceNormal);
                dAngle=(acos(dAngle)/ PI) * 180.0;
                // now test if this angle is smaller than fSmoothingAngle. more than 1 angle can result in the same
                // cosine value, but this doesn't matter since 2 normals who opposite eachother have the maximum angle, 180
                // degrees, and in that range, no double cosine values occure for the same angle.
                if(dAngle < fSmoothingAngle)
                {
                    // this face (iFaceCnt2) is part of a smooth surface together with face (iFaceCnt).
                    Vector3Add(vTmpResult, pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt2]].m_vFaceNormal,
                                    vTmpResult);
                }
            }
            // make the vector again of length 1
            Vector3Normalize(vTmpResult);
            // store vTmpResult in the right VertexNormal slot for the vertex iVertexCnt. only 3 slots available, so
            // we do a dirty if then else thingy. If stored, move on with the next face!
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[0]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[0][2]=vTmpResult[2];
                // continue with next face
                continue;
            }
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[1]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[1][2]=vTmpResult[2];
                // continue with next face
                continue;
            }
            if(pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_iVertexIndices[2]==iVertexCnt)
            {
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][0]=vTmpResult[0];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][1]=vTmpResult[1];
                pTheModel->m_pFaces[arrpiFacesPerVertex[iVertexCnt][iFaceCnt]].m_vVertexNormals[2][2]=vTmpResult[2];
            }
        }
    }
    // done!
    // free up all the memory we've allocated
    for(iVertexCnt = 0; iVertexCnt < pTheModel->m_iAmVertices;iVertexCnt++)
    {
        free(arrpiFacesPerVertex[iVertexCnt]);
    }
    free(arrpiFacesPerVertex);
    free(arrpiAmFacesPerVertex);
    free(arrpiFPVIndices);
}

Hulp routines
code:
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
// Purpose: adds 2 vectors vSrc1 and vSrc2 and puts result in vDst
inline void
Vector3Add(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0]=vSrc1[0]+vSrc2[0];
    vDst[1]=vSrc1[1]+vSrc2[1];
    vDst[2]=vSrc1[2]+vSrc2[2];
}

// Purpose: calculates the average of 2 given 3pos vectors vSrc1 and vSrc2 and puts the result in vDst
inline void
Vector3Average(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0]=(vSrc1[0]+vSrc2[0]) * 0.5f;
    vDst[1]=(vSrc1[1]+vSrc2[1]) * 0.5f;
    vDst[2]=(vSrc1[2]+vSrc2[2]) * 0.5f;
}

// Purpose: calculates the cross product of 2 given vectors vSrc1 and vSrc2 and returns the result
// vector vDst
inline void 
CrossProductVect3(SVect3 vSrc1, SVect3 vSrc2, SVect3 vDst)
{
    vDst[0] = vSrc1[1] * vSrc2[2] - vSrc1[2] * vSrc2[1];
    vDst[1] = vSrc1[2] * vSrc2[0] - vSrc1[0] * vSrc2[2];
    vDst[2] = vSrc1[0] * vSrc2[1] - vSrc1[1] * vSrc2[0];
}

// Purpose: normalizes the given vector to a length of 1.0f. Used for normals
// Returns true if succeeded, false otherwise
inline bool 
Vector3Normalize (SVect3 vSrc)
{
    int     i;
    double  dLength;
    
    dLength=Vector3Length(vSrc);
    if(dLength<=0.0)
    {
        return false;
    }
        
    for (i=0 ; i < 3 ; i++)
    {
        vSrc[i] = (float)((double)vSrc[i] / dLength);   
    }
    return true;
}

// Purpose: calcs the dotproduct between 2 vectors vSrc1 and vSrc2 and returns the product as a float.
// Dot product calculates ||vSrc1|| * ||vSrc2|| * cos Alpha. Alpha is angle between vSrc1 and vSrc2.
inline float
DotProductVect3(SVect3 vSrc1, SVect3 vSrc2)
{
    return ((vSrc1[0]*vSrc2[0]) + (vSrc1[1]*vSrc2[1]) + (vSrc1[2]*vSrc2[2]));
}

Acties:
  • 0 Henk 'm!

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06 13:31

drm

f0pc0dert

PHP: Random pass generator
Textinterface
Spelling van het wachtwoord in telefonisch alfabet (engels)
Genereert enkel op basis van aangegeven characters in array "chars".
  • Wanneer je nieuwe toevoegd moet je ook hun "spelling-counterpart" erbij zetten, bijv: [php]<? "/" => "forwardslash", "~" => "tilde"?>[/php]
_____________________________________________________________________________________________
Code
code:
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
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());


$chars = array (
   "a" => "alpha",
   "b" => "bravo",
   "c" => "charlie",
   "d" => "delta",
   "e" => "echo",
   "f" => "foxtrot",
   "g" => "golf",
   "h" => "hotel",
   "i" => "india",
   "j" => "julia",
   "k" => "kilo",
   "l" => "lima",
   "m" => "mike",
   "n" => "november",
   "o" => "oscar",
   "p" => "papa",
   "q" => "quebec",
   "r" => "romeo",
   "s" => "sierra",
   "t" => "tango",
   "u" => "uniform",
   "v" => "victor",
   "w" => "whiskey",
   "x" => "x-ray",
   "y" => "yankee",
   "z" => "zulu",
   1 => "one",
   2 => "two",
   3 => "three",
   4 => "four",
   5 => "five",
   6 => "six",
   7 => "seven",
   8 => "eight",
   9 => "nine",
   0 => "zero"
);

foreach ( $chars as $k => $v )
   if ( is_string ( $k ) )
    $chars [ strtoupper ( $k ) ] = strtoupper ( $v );

foreach ( array_keys ( $chars ) as $k )
   $str .= $k;

$pass = "";
for ( $a = 0; $a < 8; $a ++ )
   $pass .= $str [ rand ( 0, strlen ( $str ) ) ];

for ( $a = 0; $a < strlen ( $pass ); $a ++ )
   $arr [] = $chars [ $pass [ $a ] ];

echo $pass, "  (", implode  ( " - ", $arr ), ")";

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


Acties:
  • 0 Henk 'm!

Verwijderd

PHP:
1
<?function even($num) {    if ($num % 2) { // ...Number is odd...        return;        } else {         // number is even....                return true;        }}?>

functie om te controlleren of een getal even of oneven is :)

Acties:
  • 0 Henk 'm!

  • pistole
  • Registratie: Juli 2000
  • Nu online

pistole

Frutter

vbscript. Erg simpel maar wel handig. Voor o.a. strings naar MSSQL te duwen. Als je apostrophes hebt in die strings kan dat problemen opleveren. Oplossing: apostrophe verdubbelen.
code:
1
2
3
function qfix(str)
  qfix=replace(str, "'", "'')
end function

Controleren of een datum correct is. Zeer eenvoudig toe te passen voor int, string, etc
code:
1
2
3
4
5
6
7
8
9
10
11
function isDate(str)
  dim tmp
  tmp=""
  isDate=false

  on error resume next
    tmp=formatdatetime(str)
  on error goto 0

  if tmp<>"" then isDate=true
end function

Ik frut, dus ik epibreer

Pagina: 1 2 Laatste

Dit topic is gesloten.