Friday, June 29, 2012

Binary Tree Search (Haskell)

As of recently I've been looking into Haskell for a chance to better understand functional programming. I'm finding the logic set used for such a style really helps in breaking down a task into smaller tasks, as apposed to always viewing things as a whole and breaking them down into steps. Hard to understand, but it makes sense to me. Anyway, I wanted to challenge myself to see if I was really learning, and decided why not make a searching algorithm. I've never made one before, so I picked one with a concept I understood and already knew the logic of. So the task really was applying these steps in a functional way.

So the basics of a binary tree is you check the middle of an ordered list, if it matches, it's true, if it's greater than that, you check the middle of the first half, if it's less than that, check the middle of the trailing half, rinse and repeat until either all options are exhausted or you find the value. Anyway, here's my code for it.
bt :: (Ord a) => a -> [a] -> Bool
bt _ [] = False
bt x xs
    | x < item = bt x $ take itemNum xs
    | x > item = bt x $ drop (itemNum + 1) xs
    | otherwise = True
        itemNum = (length xs) `div` 2
        item    = xs !! itemNum

On a comment to Haskell, I'm not finding that the language is elegant but instead that functional programming itself it elegant and solid in build compared to all the tracking involved in imperative programming. Haskell itself is a bit cryptic and seems to lean far away from syntaxes I'm used to, but I am slowly getting accustomed to. Hopefully in the future I can have some decent searching and sorting algorithms, maybe even ones for solving puzzles or path finding. Should be fun.

Thursday, June 28, 2012

MyBB Registered-only view BBCode

Decided to make another quick MyBB addon, this adds some BBCode. You can use [paranoid][/paranoid] tags to prevent non-registered and banned members from viewing stuff selectively. I am using it to cover up various resource links. If you are logged in, it will appear like nothing is changed, you can only tell what's covered up by logging out or being banned.

[Download v1.0]


Friday, June 22, 2012

Firebug Quick Info (remove)

One of the things that has been annoying me on firebug, is the quick info popup. It's always in the way. So I looked up how to disable it because I didn't have a clue where the options where. In my version of firefox, under Tools > Web Development > Firebug > Options and clicked to uncheck the "Quick Info" option. I think on older versions it was just under the Tools menu. Either way, if you didn't know how to do that, now you know.

Friday, June 15, 2012

Python Lambda Intro (with simple example)

While really a simple thing to do, I wanted to post an example of a very simple program using something a little less common. Instead of the more common way of making a function, I will instead use lambda. In Python, lambda is used for passing an anonymous functions to a method or can be used to have a function generate simple functions. For the latter, decorators can be used for a more complex function generation, however I have yet to fully grasp using it, so I'll save explaining that for when I know how to practically use it.

Now anonymous functions are cool because you can either pass them to a function without creating some permanent function that will only be used in that one particular instance or you can pass it to a variable reference. Passing to variable reference is as simple as defining any variable. The difference in this particular instance is that lambda is limited to very simple functions, and returning variables is not as clear as a return statement. Let's view a quick example.

import sys

ftoc = lambda(f): (f-32.0)*(5.0/9.0)
ctof = lambda(c): (9.0/5.0)*c+32.0

        print """Pick a conversion (EOF to end ctrl+z win/ctrl+c *nix)
1 - Fahrenheit to Celsius
2 - Celsius to Fahrenheit
3 - Exit

        choice = raw_input()

        if choice == 3:
            print "What is the tempurature?",
            temp = raw_input()
            if choice == "1":
                print str(ftoc(float(temp)))+" Celsius"
            elif choice == "2":
                print str(ctof(float(temp)))+" Fahrenheit"
                print "Unknown option"

    except KeyboardInterrupt:

    except Exception as e:
        print "An error occured: "+str(e)
print "Goodbye."

The main point to focus on is the 2 lines following the import statements. To break it down, ftoc = lambda(f): (f-32.0)*(5.0/9.0) is actually very simple. It starts out with a normal variable declaration, variable name being ctof. We then assign it to the value of the lambda statement. The word lambda in Python means an anonymous function, then the (x) is the arguments the function accepts. This does not need to be in parenthesis can could just as easily be lambda x:. I use the parentheses to more clearly show that it's not the function name, but arguments being passed to it, I find it to be more clear for myself reading it. The next part is just a formula for converting the temperature. The question may arise, where is the return value? Quite simply, it's whatever the code in the lambda statement evaluates to at the very end.

Now some caveats. Lambda functions cannot span multiple lines, it's only a 1 liner function (with the exception being if a docstring is used). It also supports nested scope, so if it is within a scope where it uses a variable name, it will use that variable, however if the variable is the name of an argument variable, that value will be used instead. Finally, semicolons are ending delimiters and cannot be used to include multiple lines of code, it is only a single statement.

One more little catch I ran into, while I doubt anyone has a need for it, trying to define a list of lambda functions through list comprehension will not work to make different functions. Using something like y = [lambda (x): x+z for z in range(10)] will result in all 10 list items having z as 9 because it will use z as a reference to z and not replace the value, therefore the last value of z is the one that is used. However, if you replace the lambda function with a function that returns lambda functions, it works, and looks like this.

def a(x):
    return lambda(y): x+y

y = [a(z) for z in range(10)]

I was also informed of an alternative way to do this through default values, which looks a little uglier, but can condense things if you really want to. You can do something like y = [(lambda x, z=z: x+z) for z in range(10)], which will place the value of z as the default argument. Note however, that since it is a default argument, it can then be changed, which does not seem like a clean solution.

Wednesday, June 13, 2012

Javascript "use strict";

I came across this in some generated Javascript and got curious as to what it meant exactly, so I looked it up. I've also spent some time reading the notes on it over at MDN, and I'm going to try and summarize it from what I could understand a bit shorter.

Now first thing, this is a new standard for ECMAScript5 (what Javascript is based on, as well as other stuff like Actionscript). It should look familiar to Perl programmers, as Perl has a use strict; which both have similar goals. Now the thing with how it was implemented in the ES5 standard is that if what runs it does not support strict mode, it won't throw an error or warning because it does not add any new syntax. So if your browser doesn't support strict mode, it won't interfere with anything. This could also lead to my own theorized problems in the future, but I'll get to that later.

First, how to use strict mode. You can either make a function in strict mode by placing "use strict"; in the function or make everything strict by placing that at the top of your script.

So what does strict mode do? Makes Javascript throw more errors. Sounds bad, but this is good for those that like clean code without useless crap left behind that could lead to bugs. What do I mean? Well, things that would normally go by silently and either do some unexpected behavior or nothing at all, will throw an error. The best example I see from this is when using a variable. Normally if you do something like

function a() {
    something = 0;

Then something will be a global variable because it was referenced before being declared. Now you need to declare a variable before using it with var. This can prevent problems of not paying attention to scope and accidentally overwriting something or if you typo and accidentally make a new variable.

Now there are some variables you cannot overwrite, most for obvious reasons. Trying to overwrite them will throw an error rather than just doing well... nothing. Same goes for deleting certain things that aren't deletable. There are also more reserved words added that you cannot use and trying to redefine something like NaN, eval and arguments. Always a good idea to avoid using reserved and builtin objects as a variable or something like that.

While on the topic of eval, a variable declared in an eval statement will only be within that scope. It will not create a global variable. I personally never use functions like that and if I want a similar effect will use the closest thing to a macro in lisp, but that's all preference. You can also use the "use strict"; statement inside an eval, this making the code in it strict. Also, if "use strict"; has something like eval(...) in its scope, that code is strict. However if it's used like in a passed argument
function a(f, code) {
    "use strict";
a(eval, "var x"); // Not strict
a(eval, "'use strict';var x;"); // Strict

Which seems weird to me, but there's probably some reason for it I couldn't even guess. I'd have to guess it has something to do with scope, though.

Anywho, there's also stuff about arguments only containing the original arguments passed to a function. Makes sense. Also, arguments.callee is no longer used, so name your functions.

There was stuff on this, however I did not understand the wording, I'll edit this and explain it should I ever figure it out or should someone explain it to me better.

Now for the security it adds. function.caller and function.arguments is no longer global. This means you cannot access it globaly closing some security holes, I would hope obscure ones. Then there is the list of reserved words that are implements, interface, let, package, private, public, static, and yield. They did that because they will be for future versions or something like that. Quick side-note, ES5 unconditionally reserves the words class, enum, export, extends, import, and super, so avoid those as well as not all browsers may reserve them.

Now, do not rely on these "security" features in strict mode. Not all browsers support it, so those holes can still exist even if you use strict mode. Now problems I see arising even when it's widely supported is that some companies, one of which I've worked for, use old software for very long periods of time. My current job still has stuff using Windows 98 and I also worked for a place that still used IE5 when IE8 had been out for a while. Bottom line to me it seems, is never use Javascript for security, even for the user's security. It's running code that's arbitrarily downloaded.

Anyway, check out the link of MDN for a more detailed explanation made by people far smarter than I am on this subject if you want to know more, I just wanted to try and explain it myself as well.

Sunday, June 10, 2012

Refused to set unsafe header

*** If interested in CORS, try this.

This is an annoying little error that I've seen some people mention and even ran into with JavaScript. Moreover, it appears only in Webkit based browsers. So what's the problem? Basically a browser like Google Chrome will not change certain http headers in an XMLHttpRequest using setRequestHeader(). This is not a problem in Firefox or Opera from my testing so far. According to W3, it is actually the behavior they have as "standard" in their working draft. Headers they don't want you to overwrite are
  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Date
  • DNT
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via
Or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-)."[1]
Now as to where this could be a problem, for me at least, is when I am trying to spoof some headers and want to do so in a browser as apposed to writing a script or getting an addon to do so for me. However, there is a security risk it could open up called HTTP Request Smuggling. As to how one would pull it off, I think an XSS vulnerability would need to be there as well for this in JavaScript to do anything. Bottom line for the security of it on the design end, make sure you check your sources before you use things like external scripts. As for user-end security, just be careful what sites you go to and use some common sense when you can.

Now as for ways around this, you would need either an addon to modify this for you or use related command line arguments. For example, to change the User-Agent header, you launch Chrome from your terminal with the option --user-agent="Some new UA string". As for an addon to do this, I do not know of any or if it is even possible, but if I find something I will update that here.

*[1] -

Tag Cloud

.NET (1) A+ (2) addon (6) Android (4) anonymous functions (5) application (10) arduino (1) artificial intelligence (2) bash (4) c (7) camera (1) certifications (4) cobol (1) comptia (4) computing (2) css (2) customize (16) encryption (2) error (19) exploit (17) ftp (3) funny (2) gadget (3) games (2) Gtk (1) GUI (5) hardware (7) haskell (15) help (8) HTML (6) irc (2) java (5) javascript (21) Linux (20) Mac (5) malware (2) math (8) network (9) objects (2) OCaml (1) perl (4) php (9) plugin (7) programming (42) python (24) radio (1) regex (3) security (25) sound (1) speakers (1) ssh (3) story (1) Techs from the Crypt (2) telnet (2) tools (15) troubleshooting (5) Ubuntu (4) Unix (4) virtualization (1) web design (14) Windows (8) wx (2)