Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - Freak

Pages: [1]
1
Beginner's Corner / [Perl] Sentences generator.
« on: December 02, 2015, 08:39:54 am »
Hello,

I'm working on a little project, and I decided to share my code from the initial concept. (When I finish the final awesome version, I'll share that too).

Basically I saw /r/subredditsimulator which is a subreddit comprised entirely of bots meant to simulate a real subreddit by using Markov chains to create realistic sounding text. It caught my attention and I absolutely love stuff like this. I decided to make something similar, and started by just writing a program to create realistic-ish sentences.

This program takes in a file with sample text, chooses a random word, then chooses every next word by making a list of words that follow that word in the sample (including repeats) and picking one of those at random until it reaches the set sentence length.

This is a very rough program, it doesn't do capitalization or filter punctuation or anything, but it's a start.

Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
my(@sample, $name, @sentence, $num, $lastWord, @nextWords);
print "Enter the name of the file: ";
chomp($name = <stdin>);

open FILE, "<$name" or die "Error: $!\n";
while(<FILE>){
push(@sample, split(" ", lc($_)));
}
close FILE;

for(;;){
@sentence = ();
print "Enter the number of words for the sentence (Enter nothing to quit): ";
chomp($num = <stdin>);
if($num eq ""){
last;
}else{
push(@sentence, $sample[int(rand(scalar(@sample)))]." ");
for(my $i = 1;$i<$num;++$i){
$lastWord = $sentence[$i-1];
$lastWord =~ s/ //g;
@nextWords = ();
for(my $e = 0; $e<scalar(@sample); ++$e){
if($sample[$e] eq $lastWord){
push(@nextWords, $sample[$e+1]);
}
}
push(@sentence, $nextWords[int(rand(scalar(@nextWords)))]." ");
}
print @sentence;
print "\n\n";
}
}

I took a screenshot of me running it 5 times so you can see the result.



Enjoy!

2
Found it on the Webs / Free online textbooks through charity site.
« on: September 04, 2015, 05:17:49 am »
Hello.   

I saw someone post about this on Facebook today and I thought y'all might be interested. It's a site that's funded by a bunch of charities so that they can provide free textbooks to students. They'd probably be supplementary to whatever book is required for your course though. They're not buying textbooks and shipping them to you for free, they're making their own versions of textbooks that are peer reviewed and giving you free ebooks or they'll send you a physical copy that costs as much as the materials to make it. I think the hope is also that professors start using these textbooks for their courses, so that'd be nice.


https://openstaxcollege.org/

3
For problem 3 I went iterative because I've always heard that recursion is generally slower because of the repeated calls to the stack. That's really interesting that it might be faster for this particular problem though. I'll look into that some more.

For problem 4 that doesn't work by itself. You still need to look at the numbers after the first one. For example:
Code: [Select]
{56, 5} --> 56 5
{54, 5} --> 5 54
If the second digit is higher or lower than the first it changes the order that they should go in.

Tell me what you come up with for number 5, and thanks for the response :)

4
Found it on the Webs / Realistic mobile hacking/coding game
« on: June 10, 2015, 04:34:40 am »
Hello,

Today I was browsing the Google play store and recommended for me was a game called "Hacked". I clicked on it out of curiosity and it turns out that it is actually good. I haven't gotten too far yet, and I don't know if you could really call it a "hacking" game from what I've seen, but it gives you puzzles where you write actual code.

It does stuff like say say "Your friend brought you his phone to jailbreak" and then give you a puzzle to write a program that returns the largest value out of an inputted list. I would say that it'd be a good way to learn programming, but it's probably not for complete beginners.

http://www.hackedapp.com/

5
Hello.

A month ago I saw this on reddit claiming that all "real" programmers should be able to solve these 5 problems in less than an hour total. I, and many of the commenters thought that was bullshit because 4 can be tricky and 5 is kinda tough (funnily enough, the blogger got number 4 wrong the first time). Regardless, I left it bookmarked a long time and finally decided to try them all anyway and so I'm posting my solutions!

Problem 1:
"Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion."

Very straight forward...
My solution:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
my @givenList = (1,2,3,4,5,6,7,8,9,0);

sub forList{
   my $runningTotal = 0;
   for(my $i = 0;$i<scalar(@givenList);++$i){
      $runningTotal += $givenList[$i];
   }
   return $runningTotal;
}
sub whileList{
   my $i = 0;
   my $runningTotal = 0;
   while($i<scalar(@givenList)){
      $runningTotal += $givenList[$i];
      ++$i;
   }
   return $runningTotal;
}
sub recursiveList{
   my @thisList = @_;
   if(scalar(@thisList) == 1){
      return $thisList[0];
   }else{
      return pop(@thisList)+recursiveList(@thisList);
   }
}

print forList."\n";
print whileList."\n";
print recursiveList(@givenList)."\n";

Problem 2:
"Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3]."

Also very straight forward...
My solution:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
my(@listOne, @listTwo, @listThree, $i);
@listOne = ('a','b','c');
@listTwo = (1,2,3);
@listThree = ();

#I assume they are equal size. Otherwise this'd need:
   #Some conditionals to avoid null pointers.
   #The conditional in the for loop to be (;$i<scalar(@listOne) and $i<scalar(@listTwo)
for($i = 0;$i<scalar(@listOne);++$i){
   push(@listThree, $listOne[$i]);
   push(@listThree, $listTwo[$i]);
}

print join(", ", @listThree);

Problem 3:
"Write a function that computes the list of the first 100 Fibonacci numbers."

If you don't know, the Fibonacci sequence is a sequence of numbers where each number is the sum of the previous two and the first two numbers are 0 1. So it goes 0 1 1 2 3 5 8 13 21...

My solution:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
my($one, $two, $i, $temp);
$one = 0;
$two = 1;
print "$one\n$two\n";
for($i = 0;$i<100;++$i){
   $temp = $two;
   $two = $one + $two;
   $one = $temp;
   print "$two\n";
}

Problem 4:
"Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021."

So this one is the first one that's a bit tricky and requires you to think of a way to solve it rather than just implementing what it told you. My way was to bruteforce each combination of the numbers as a string, then typecast it to an integer and compare it to the previous largest number. My program only works for lists of 4 numbers which is kind of stupid. There's probably a good recursive way to do this or something, and I should probably redo it to be honest, but whatever.

My solution:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
my(@nums, @nums2, @nums3, @nums4, $largest, $current, $i, $j, $k, $l);
@nums = (50, 2, 1, 9);
$largest = 0;

for($i = 0;$i<scalar(@nums);++$i){
   @nums2 = ();
   for($j = 0;$j<scalar(@nums);++$j){ #construct @nums2
      if($j == $i){
         next;
      }else{
         push(@nums2, $nums[$j]);
      }
   }
   for($j = 0;$j<scalar(@nums2);++$j){
      @nums3 = ();
      for($k = 0;$k<scalar(@nums2);++$k){ #construct @nums3
         if($k == $j){
            next;
         }else{
            push(@nums3, $nums2[$k]);
         }
      }
      for($k = 0;$k<scalar(@nums3);++$k){
         @nums4 = ();
         for($l = 0;$l<scalar(@nums3);++$l){ #construct @nums4
            if($l == $k){
               next;
            }else{
               push(@nums4, $nums3[$l]);
            }
         }
         for($l = 0;$l<scalar(@nums4);++$l){
            $current = $nums[$i].$nums2[$j].$nums3[$k].$nums4[$l]; #concatenated numbers typecasted to a number
            if( $current > $largest ){
               $largest = $current;
            }
         }
      }
   }   
}
print $largest;

Problem 5:
"Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100."

This one is actually a bit harder. My solution was to first create an array of every unique concatenation of the numbers 1-9 (1 2 3 4 5 6 7 8 9, 1 2 3 4 5 6 7 89, 1 2 3 4 5 6 78 9, etc...) by counting upward in binary from 00000000 to 11111111 where each number represents a spot between two numbers and 1s are concatenations and 0s are a space. After that I looped through each entry and did basically the same thing again but where 1s were + and 0s were - and then I'd check each one to see if it equaled 100.

My solution:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;

my($runningTotal, $ones, $goodString);
my @concats = &allCombinations;      #All different concatenations of 1-9
my @binaryList;                  #The binary array representing + and -
my @thisConcat;                  #Array containing all the different numbers in the current concatenation
my @finalCombos;               #Array containing all configurations that add to 100
for(my $i = 0; $i<scalar(@concats); ++$i){ #for each unique concatenation of 0-9.
   $ones = "";
   @binaryList = ();
   @thisConcat = split(' ', $concats[$i]);
   for(my $e = 0; $e<scalar(@thisConcat)-1; ++$e){   #Fill @binaryList with 0s
      push(@binaryList, 0);
      $ones .= 1;
   }

   while(join('', @binaryList)<$ones){ #Try all combinations of + and - between concatenations.
      for(my $e = scalar(@binaryList)-1; $e>=0; --$e){ #count upwards in binary
         if($binaryList[$e] == 0){
            $binaryList[$e] = 1;   #1 means +
            last;
         }elsif($binaryList[$e] == 1){
            $binaryList[$e] = 0;   #0 means -
         }
      }

      $runningTotal = $thisConcat[0];
      for(my $e = 1; $e<=scalar(@binaryList); ++$e){ #edit $runningTotal.
         if($binaryList[$e-1] == 1){
            $runningTotal += $thisConcat[$e];
         }else{
            $runningTotal -= $thisConcat[$e];
         }
      }
      if($runningTotal == 100){
         $goodString = "";
         for(my $e = 0; $e<scalar(@binaryList); ++$e){
            $goodString .= $thisConcat[$e];
            if($binaryList[$e] == 1){
               $goodString .= "+";
            }else{
               $goodString .= "-";
            }
         }
         $goodString .= $thisConcat[scalar(@thisConcat)-1];
         push(@finalCombos, $goodString);
      }
   }
}
for(my $i = 0; $i<scalar(@finalCombos); ++$i){
   print $finalCombos[$i]."\n";
}

sub allCombinations{
   my($check, $one1, $two1, $thisString);
   my @numbers = (1,2,3,4,5,6,7,8,9);
   my @concats = (); #list of lists that are unique combinations of the above numbers.
   my @binaryList = (0,0,0,0,0,0,0,0); #a number for each space between entries in @numbers. 1 means concat.

   while(join('', @binaryList)<11111110){ #count upwards in binary
      for(my $i = 7; $i>=0; --$i){
         if($binaryList[$i] == 0){
            $binaryList[$i] = 1;
            last;
         }elsif($binaryList[$i] == 1){
            $binaryList[$i] = 0;
         }
      }
      $thisString = $numbers[0];
      my $i = 0;
      for(my $i = 0; $i<scalar(@binaryList); ++$i){
         if($binaryList[$i] == 0){
            $thisString .= " ";
         }
         $thisString .= $numbers[$i+1];
      }
      push(@concats, $thisString);
   }
   return @concats;
}

So there ya go! Tell me what you think of my implementations/algorithms and what your first thought was for each one if it was different than mine!

6
General discussion / Re: Mental illness?
« on: May 10, 2015, 11:29:41 pm »
I have these to issues freak:
http://en.wikipedia.org/wiki/Schizophrenia
http://en.wikipedia.org/wiki/Fetal_alcohol_spectrum_disorder


just an fyi, not an easy life for me lol

My position isn't meant to downplay the difficulties for people who have been told they're mentally ill. Like I said, I've been diagnosed with stuff myself. Battling thoughts of suicide is a daily struggle, and my anxiety can get so bad that I'm afraid to leave my room to get water if my roommates have company.

I won't deny the reality of fetal alcohol disorders. From what I understand, these are neurological disorders and issues with fetal development. That's different from just looking at certain people and saying "Your emotions are wrong! You must be ill." or any related statement.

As for schizophrenia, I don't think that's an illness. This is despite the fact that I've had relatives and close friends with the diagnosis. I don't think there's anything wrong with hearing voices, but if they're scary or disturbing then that's a problem. What's actually really interesting about this is that people with "schizophrenia" in Asian and African countries rarely have bad voices. It's strangely unique to America and Europe to have mean or scary ones. With delusions, I think it'd be hypocritical for anyone to say claim that your perceptions of reality are wrong while assuming that theirs are right.

You're free to disagree with me, I just want to make sure it's understood that even if I don't think there are mental "illnesses" I think it's equally shitty to live with this stuff.

7
General discussion / Re: Mental illness?
« on: May 09, 2015, 09:21:06 am »
I'm definitely one of the crazies. I've been diagnosed with depression and social anxiety, which can be pretty tough. I also used to hear voices for a while in high school and they were horribly mean and terrifying, but I've been so depressed lately that I kind of want them back so that everything isn't so flat and pointless. I'd rather be terrified than numb and emotionless.

I actually don't believe that mental illness is a real thing. Obviously I know that people can hear voices, have anxiety, depression, or whatever else that's out of their control, but I don't think that "ill" is a good description of that. I don't think it's a bad thing to hear voices, but I think it's a bad thing if they scare the shit out of you like mine did. There was a psychiatrist named Thomas Szasz who wrote a lot on this topic, and I like his position. He called this stuff "problems with living" instead of mental illness. Being depressed or having extra anxiety or anything like that doesn't make you ill, but it can be a problem with living that you experience.

I am currently on medications, but I want to get off of them. I don't think they do anything and I'm sick of paying for them. I also was never told that they drastically increase my risk of getting seizures, so that's pretty fucked up. I wonder what else they didn't tell me.

I've never been to a psych ward, and I'd probably do whatever I can not to go to one. I don't like that they can call me a danger to myself and effectively imprison me against my will. There was actually recently a woman who was imprisoned in a psych ward and sedated against her will for a week because she told her doctor "Obama follows me on Twitter" and he actually did, but nobody believed her.

8
Scripting Languages / [Perl] robots.txt webcrawler
« on: April 24, 2015, 08:40:07 am »
Hello,

This is a program takes in a URL in the format "www.example.com" and crawls to every new domain that it finds copying their robots.txt file. Note that it doesn't dig very deep because it only looks at the source for the front page of a website for new domains. If it was looking at https://evilzone.org, for example, it would not look in https://evilzone.org/scripting-languages/

Theoretically, a robots.txt file tells webcrawlers what portions of their website they can and can't index, etc... There's nothing that actually enforces this, but it's supposed to be convention. This is useful because web administrators put things in there that they don't want to show up on a Google search which can mean that information held within is sensitive.

I tested my program on "www.google.com" which yielded:



And if you look in one of these you'll see something like:



Finally, here is the code:
Code: (perl) [Select]
#!/usr/bin/perl -w
use strict;
use LWP::Simple;
use utf8;
my(@domains, $pageContent, $i, $e, $new, $robotsContent);

print "Enter domain to start with: (Ex. \"www.google.com\")\n";
chomp($domains[0] = <stdin>);
for($i = 0;$i<scalar(@domains);$i++){
   $pageContent = lc(get("http://".$domains[$i]));
   while($pageContent =~ /href=\"(.*?)\"/g){
      if($1 =~ /http:\/\/(.*?)\// or $1 =~ /https:\/\/(.*?)\//){
         $new = 1;
         for($e = 0;$e<scalar(@domains);$e++){
            if($domains[$e] eq $1){
               $new = 0;
            }
         }
         if($new){
            push(@domains, $1);
         }
      }
   }
   $robotsContent = get("http://".$domains[$i]."/robots.txt");
   if($robotsContent){
      $robotsContent = lc($robotsContent);
      open FILE, ">$domains[$i] robots.txt" or die "Error: $!\n";
      binmode(FILE, ":utf8");
      print FILE $robotsContent;
      close FILE;
   }
}

Enjoy :)

EDIT:
I found two little bugs today, but I changed the code in this post to get rid of them. If you run the code that used to be here it will still work perfectly, it'll just spew some warnings at you sometimes, but if you ignore them it'll still do it's job. Like I said though, the code that's on here now works perfectly.

I also am attaching a zip of 6,001 robots.txt files that I found while testing it today. I just started on en.wikipedia.org and let it run for a while.

9
Beginner's Corner / Re: [C] Optimal prime generators experiment
« on: April 15, 2015, 07:17:55 am »
Oh, I just forgot to comment out the print statements  for my post, but when I tested it for speed it was without printing. It takes like 8 seconds with printing haha.
Computer speed is probably it then. Thanks :)

10
Beginner's Corner / Re: [C] Optimal prime generators experiment
« on: April 15, 2015, 03:35:00 am »
Thanks, HTH, for telling me about that! I went ahead and wrote my own implementation:
Code: (c) [Select]
#include <stdio.h>
#define upper 2000000
int nums[upper] = {0}; //0 means prime

int main(int argc, char *argv[]){
    unsigned long i, e;
    for(i = 3;;i+=2){
        if(!(nums[i])){
            printf("%d\t", i);
            if((i*i)>upper){
                i+=2;
                break; //After (i*i)>upper there are no composites that weren't covered by the earlier primes
            }else{
                for(e = 2*i;e<upper;e+=i){ //Set multiples to composite
                    nums[e] = 1; //1 means composite
                }
            }
        }
    }
    for(;i<upper;i+=2){ //Same as before but without eliminating composites
        if(!(nums[i])){
            printf("%d\t", i);
        }
    }
    return 0;
}

Which takes about .095 to calculate up to 2 million. That's not quite as much as an increase as yours showed though. Any of you see something I might have done poorly? Like I said, I'm pretty new to C.

Should I go ahead and post this to challenge 17 too?

Kenjoe41, I bookmarked the wiki page for the Sieve of Atkin so thanks for that! That page also talks about a sieve that Euler made, so I'll probably give both of those a go and post them here when I finish them.

11
Beginner's Corner / [C] Optimal prime generators experiment
« on: April 14, 2015, 08:17:49 am »
A while ago I remembered a time about 5 years ago in high school when some friends and I were writing prime number generators in C++ and seeing who could make theirs the fastest. Since I've been picking up some C in my spare time I thought I'd try that again!

My first version involved checking only odd numbers, and dividing them by all of the odd numbers up to their square roots. It also just checks up to 2 million. It's just an arbitrary upper limit that I set at the time.
Code: (c) [Select]
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]){
    int i = 1;
    int e;
    outer_loop:
        while(i<2000000){
            i+=2;
            for(e = 3;e<sqrt(i);e+=2){
                if(!(i%e)){
                    goto outer_loop;
                }
            }
            //printf("%d\t", i);
        }
    return 0;
}

Now before you yell at me for using goto let me explain myself! I changed it to this while I was optimizing it. Originally it was nested loops, but I didn't have an easy way to do a "continue" for the outer loop. I was using break in the inner loop and needed to use a variable as a check if a number was prime or not. The whole idea of this was to try to make it as fast as I could. This goto statement makes it act exactly how it did before, except I didn't need a checking variable that would slow down the program (albeit by an almost immeasurable amount).

This program generally runs in about 5 seconds.

Now the problem with this program is that it is a shitty algorithm. It's definitely better than what we did in high school when we divided every number--including even numbers--by every number before its half. The reason that this algorithm is still slow is because lets say I'm checking 41 or something.
41%3 != 0
41%5 != 0
41%6 != 0
There is NO number that is divisible by 6 and isn't divisible by 3. This program checks multiples of prime numbers, which is pointless. Rather, it should only check for even division by prime numbers because every non-prime is divisible by at least 1 prime beneath it.

I realized this after a while, and that's when I got discouraged for a while. C doesn't have dynamically expanding arrays, so I can't just add every newly discovered prime to an array. I thought about implementing a linked list or something, but I don't know C well enough to do that yet.

Just recently I realized a solution that isn't ideal but would work. I would initialize the array to be large enough for 148993 elements. That's the number of prime numbers between 2 and 2 million.
Code: (c) [Select]
#include <stdio.h>

int main(int argc, char *argv[]){
    int i = 3;
    int e;
    int count = 1;
    int primes[148932] = {3}; //set the array size to the number of primes before the upper limit.
    outer_loop:
        while(i<2000000){
            i+=2;
            for(e = 0;(primes[e]*primes[e])<=i;++e){
                if(!(i%primes[e])){
                    goto outer_loop;
                }
            }
            //printf("%d\t", i);
            primes[count] = i;
            ++count;
        }
    return 0;
}

This one isn't ideal because I can't just change the upper limit whenever to see how fast it is for a different number of primes. It requires you to know ahead of time how many primes there are in your interval (meaning you already ran a prime number generator).

This one ran in about 3.2 seconds until my friend suggested I change
Code: (c) [Select]
primes[e]<=sqrt(i)
to
Code: (c) [Select]
(primes[e]*primes[e])<=i
after which it runs in about .2 seconds.

It turns out that determining square roots is very slow because the algorithm used requires doing a bunch of loops until they approximate it.

I wrote a final version that takes a command line argument for how many primes you want to generate. So instead of finding them all in an interval it finds a specific number of them. This sort of avoids the issue with the last one where you can't experiment with different intervals, but not completely because it abandons the interval model.
Code: (c) [Select]
#include <stdio.h>

int main(int argc, char *argv[]){
    int num = atoi(argv[1]);
    int i = 3;
    int e;
    int count = 2;
    int primes[num];
    primes[0] = 2;
    primes[1] = 3;
    outer_loop:
        while(count<num){
            i+=2;
            for(e = 1;(primes[e]*primes[e])<=i;++e){ //e=1 because primes[0]==2 and i will never be even.
                if(!(i%primes[e])){
                    goto outer_loop;
                }
            }
            primes[count] = i;
            ++count;
        }
    /*for(i = 0;i<num;++i){
        printf("%d\t", primes[i]);
    }*/
    return 0;
}

This one generally runs at the same time as the last one if you run "prime3.exe 148993" because there weren't any real changes to the algorithm itself.


I still might try a linked list implementation so that I can compare that, but I'd assume that it's slower than my second version.

If you have any optimization suggestions, I'd LOVE to hear them! This is pretty fun for me because it reminds me of the fun I had in that class goofing around with my friends.

12
General discussion / Re: Artificial Womb a blessing! or?
« on: April 06, 2015, 06:14:52 am »
I think that ecotogenesis/artificial wombs are a wonderful thing that can't come quickly enough for so many different reasons.

Regardless of the legality of it, many employers still ask women during interviews about their plans to have children or things along those lines. It makes it much more difficult for women to have children and a career at the same time. This is especially true because women are often pressured their entire lives to have children. They are told from childhood that one day they're going to have children. On top of that, giving birth is a painful and traumatic experience for many women, and many women still die from it.

A surrogate would also no longer be required for gay men who want children or women who are infertile due to issues with their uterus.

It's even good for the children themselves. We constantly hear of new things that you're not supposed to do while your pregnant because of effects that it may have on the baby. For all we know there are a host of things right now that we should not be doing, but with this technology it wouldn't matter.

I'm generally a supporter for transhumanist projects and technology though. I don't understand why people would claim that we're "playing God" or that this is "unnatural" or even why those are necessarily bad things.

13
Beginner's Corner / [Perl] Obfuscated code reformatting
« on: March 21, 2015, 03:16:02 am »
Hello,

Sometimes you'll open the source code to a website and try to understand how things were done only to find some garbled mass of garbage like this from Google's home page:
http://pastebin.com/cFuPtgiv

This program will help with that a bit by reformatting the code into something a little more readable like this:
http://pastebin.com/t7e8XVUx
On that page it still might look a little bad in some places but that's because the lines are longer than the width of the paste box. Also, a lot of places obfuscate their code on purpose to keep people from understanding it, so even though this is now formatted nicely it's still very confusing.

This'll only work on "curly bracket" languages that use semicolons (Java, C/++, Javascript, etc...) though, and it also messes up things that would usually be 1 line even though they have curly brackets. An example in Java is:
Code: [Select]
int[] array = {1,2,3};
Which would be turned into:
Code: [Select]
int[] array = {
   1,2,3
}
;

Code: [Select]
#!/usr/bin/perl -w
use strict;
my($fname);
my $code = "";
my $tabs = -1;

print "File name: ";
chomp($fname = <STDIN>);
open UNFORM, "<$fname";
foreach(<UNFORM>){
   $code .= $_;
}
close UNFORM;

$code =~ s/\n//g;   #Remove all formating.
$code =~ s/\t//g;   #That way I don't have to check for it to make sure I don't fuck it up.
my @arr = split('', $code);
push(@arr, "\n");   #Avoid index out of bounds in the following loop.
for(my $i = 0; $i<scalar(@arr); ++$i){
   if($arr[$i] eq '{'){
      ++$tabs;
      $arr[$i] = "{\n";
      for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
   }elsif($arr[$i] eq '}'){
      --$tabs;
      $arr[$i] = "}\n";
      for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
   }elsif($arr[$i] eq ';'){
      $arr[$i] = ";\n";
      if($arr[$i+1] eq '}'){
         for(my $e = 0;$e<$tabs;++$e){$arr[$i] .= "\t"}
      }else{
         for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
      }
   }
}
$fname =~ s/\./2\./;
open FORM, ">$fname";
print FORM join('', @arr);
close FORM;

14
Scripting Languages / [Perl] FTP Search Engine
« on: March 20, 2015, 03:24:25 am »
Hello,

This program takes in a file containing addresses for FTP servers and, for each address, crawls through every available directory recursively printing filenames and pathnames containing either all or any of a set of user inputted keywords to a file kinda like a search engine.

At each iteration through the list of addresses the user is prompted for the username and password of the FTP server (You can just leave them blank for anonymous FTP).

Here's a screenshot of an example output for ftp://ftp.kernel.org/ with the keyword "rpm":


If you un-comment line 36 it will print out each directory that it crawls to as it crawls to them. I like to run it that way because then you can actually tell that it's making progress instead of just staring and waiting at a blank terminal. The reason I commented it out here though is because technically it's faster if it doesn't print them.

Code: [Select]
#!/usr/bin/perl -w
use strict;
use Net::FTP;
my($fname, @keys, $mode, @ips, $ftp, $check, $user, $pass);
print "Filename:\n> ";
chomp($fname = <STDIN>);
print "Keyword(s):\n> ";
chomp(@keys = split(' ', lc(<STDIN>)));
print "Select mode:\n1 - Contains all keywords.\n2 - Contains any keyword.\n> ";
chomp($mode = <STDIN>);
if($mode != 1 and $mode != 2){
   print "Invalid mode.\n";
   exit(1);
}

open IP, "<$fname" or die "Error: $!\n";
open SEARCH, ">search.txt" or die "Error: $!\n";
@ips = <IP>;
close IP;
foreach(@ips){
   chomp($_);
   $ftp = Net::FTP->new($_, Timeout => 5) or do{print "Error: $!\n"; next;};
   print "Username for $_\n> ";
   chomp($user = <STDIN>);
   print "Password for $_\n> ";
   chomp($user = <STDIN>);
   $ftp->login($user, $pass) or do{print "Error: $!\n"; next;};
   &navigate($_);
   $ftp->quit();
}
close SEARCH;

sub navigate{
   foreach($ftp->ls()){
      $ftp->cwd($_) or do{&test($ftp->pwd()."/".$_, $_[0]); next;};
      #print $ftp->pwd()."\n";
      &navigate($_[0]);
      $ftp->cdup();
   }
}
sub test{
   foreach(@keys){
      if($mode == 1){
         if(!(lc($_[0]) =~ /$_/)){
            $check = 0;
            last;
         }else{
            $check = 1;
         }
      }else{
         if(lc($_[0]) =~ /$_/){
            $check = 1;
            last;
         }else{
            $check = 0;
         }
      }
   }
   if($check){
      print SEARCH "ftp://".$_[1].$_[0]."\n";
   }
}

15
Beginner's Corner / [Perl] Anonymous FTP scanner
« on: March 16, 2015, 09:04:34 pm »
It's my spring break so I've been programming a bit, and yesterday I whipped this up.

You enter 2 IPv4 addresses (a start and an end) and it will try to connect to anonymous FTP on every address between those two addresses, then it will write all of the addresses that it worked on to a file called "list.txt"

I just made it really quick so I didn't really bother to make it user-proof. If you give it something other than an IPv4 address it will probably crash. If your end IP comes before your start IP it will scan everything between the start address and 255.255.255.255

I also set the timeout to only 5 seconds, so if you're on a slow network or something you could get false negatives, but this way it won't take 1000 years to finish.

Code: [Select]
#!/usr/bin/perl -w
use strict;
use Net::FTP;
my(@ipArr, $end, $ftp);
print "Enter the start IP:\n>  ";
chomp(@ipArr = split(/\./, <STDIN>));
print "Enter the end IP:\n>  ";
chomp($end = <STDIN>);
open FILE, ">list.txt" or die "Error: $!\n";
for(; $ipArr[0]<=255; ++$ipArr[0]){
   for(; $ipArr[1]<=255; ++$ipArr[1]){
      for(; $ipArr[2]<=255; ++$ipArr[2]){
         for(; $ipArr[3]<=255; ++$ipArr[3]){
            if($end eq $ipArr[0]."\.".$ipArr[1]."\.".$ipArr[2]."\.".($ipArr[3]-1)){
               print "Done.\n";
               close FILE;
               exit(1);
            }
            $ftp = Net::FTP->new($ipArr[0]."\.".$ipArr[1]."\.".$ipArr[2]."\.".$ipArr[3], Timeout => 5) or next;
            $ftp->login() or do{$ftp->quit(); next;};
            $ftp->quit;
            print FILE $ipArr[0]."\.".$ipArr[1]."\.".$ipArr[2]."\.".$ipArr[3]."\n";
         }
         $ipArr[3] = 0;
      }
      $ipArr[2] = 0;
   }
   $ipArr[1] = 0;
}
print "Something unexpected happened.\n";
close FILE;


Enjoy :)

Pages: [1]