Snipplr Snippets – WordPress Plugin


Published in: Plugins, Site NewsPosted by Travis on 07/05/10


Snipplr Snippet WordPress Plugin

The Snipplr Snippets WordPress plugin was recently updated and now works with WordPress 3.0.

If you’re not familiar with the plugin, it allows you to embed snippets directly into your Wordpress posts using the snippet ID.

Features include:

  • Code highlighting using GeSHi.
  • Sidebar widget to show your latest code snippets.
  • Easily embed snippets into the page using [snippet id=##]
  • Customisable layout using CSS. Can disable default plug-in CSS from the admin settings
  • Uninstall option in the plugin settings page.

Pick up the plugin now or head over to the author’s website for more information.


Snippets App – With Built in Snipplr Love


Published in: Site NewsPosted by Travis on 06/24/10


Snippets App

We just received an email from developer Vadim Shpakovski who informed us of Snippets, a Mac App that stores your valuable pieces of code so you can reuse them in different projects over and over.

That all sounds very tasty, but here’s the best part – it has built in Snipplr submission functionality. So you got to love that!

Head over to the Snippets website, or check out the page we just put together in our developers section and let us know what you think about it.


Lightweight IPv4


Published in: Development, Language, PHPPosted by Jdub7 on 08/03/09


Introduction

For a midsize project I wanted to store IP ranges in the database with the option to to also store CIDR blocks. CIDR blocks, though powerful are somewhat difficult for a typical user. Additional using them is not as precise for all ip ranges. There are a plethora of tools available on the internet that will do what I would like. However, incorporating these tools would not be practical. What I want is to mimic the functionality of these tools so that it can be easily imported into any of my projects. The most coveted tool for me would be to convert an IP range to a precise range of CIDR blocks. This required specific functionality not naturally provided in PHP.

  • Check for Valid Netmask
  • Check whether an IP address is within a CIDR block.
  • Take user input and a Netmask and make it into a valid CIDR block.
  • CIDR number into Netmask
  • Netmask to CIDR
  • Take an IP range and fit it into an exact range of CIDR blocks.

This presents some difficulty in that PHP’s network functions are not thorough enough. The revelation came when I realized that an IP address is merely a number. In fact the whole protocol is rooted in binary using very specific patterns. With that in mind I thought we could develop very light weight methods to solve our problem.

The Code

It is important to note that the methods provided are meant for IPv4 addresses only are only tested on a 32bit system. Also, I did not care to do much in the way of error checking, but doing so, like testing whether the CIDR number is unsigned and less than or equal to 32, should be trivial.

Though the solution I sought after would require PHP I didn’t limit myself to that language only. In fact the PHP code I found seemed inefficient. Most involved a number conversions or parsing the address using sprintf using loops and nested if statements. Indeed the most efficient code, which shouldn’t surprise most was in ANSI C. Bit Twiddling Hacks resource proved very useful.

About Binary

I am not attempting to teach binary math. Since the code does not “read like prose” a small amount of knowledge is required in order to understand the code. Some excellent resources are Wikipedia’s article on CIDR and PHP binary operators.


Joy Of Groovy


Published in: Development, Groovy, LanguagePosted by yighu on 07/29/09


In my work and my volunteer, I need to do a lot of scripting for all kinds of things such as system administration, data migration etc. I have used shell script, perl and many other tools on and off for a long time before. Scripting with Groovy brings me much joy and fun.

Groovy brings the full Java language and its own flavors to your finger tips while you are typing and thinking your tasks and you can do a lot of things very easily and much simpler than other scripting. Here I will put up a few examples that demonstrate a few tricks that can simplify a lot of daily scripting work:

  1. File Manipulation
  2. Configuration
  3. Database Access
  4. Logging

Suppose you want to create a file and put stuff in it. This is how you do it:

def file=new File(“test.txt”)

do this: file.append(“line 1\n”) file.append(“line 2\n”)

Now the file has 2 lines.

Later some where, you want to do something with the data in the file, for example email the data to some one, this is how you get the content for the file: def content=file.txt()

Suppose you want to write a method, for example log(String text). The log method basically append what ever text into a log file.

binding['writer']=new File(“log.txt”)

def log(String text){ writer.append(text+”\n”) }

Now suppose, instead of putting the log into a log file, I want to put the log into a database table for easy to search or may be for data warehousing purpose, you can easily change the above log method without touching the rest of your code.

def log(String text){ sql.execute(“insert into usertrace(id,description) value(?,?)”,[nextid(),text]) }

where nextid() is simply a method that return you the next id of table usertrace.

Now what is sql here? Before I talk sql, I need to touch the groovy configuration a bit.

The ConfigSlurper is a cool thing.

You might have been used to manipulate the java Property class which you need to load the property file and then use getter method to fetch the string property you want. The groovy way is much simpler.

In this code, MyConfig.groovy is a groovy class which contains name/value pairs, one of them is called sql like this:

sql=groovy.sql.Sql.newInstance(“jdbc:postgresql://localhost:5432/helloworld”,”username”,”password”,”org.postgresql.Driver”)

This is how you get the property sql.

binding['cfg']=new ConfigSlurper().parse(new File(‘MyConfig.groovy’).toURL()) binding['sql']=cfg.sql

Notice that the new variable sql is an object, not just a String as in Java Property file. Then you can execute the method of the object sql, like we did in the above log method.

Have fun so far! As you explore Groovy, you will discover them more.


Custom Error Constructors in JavaScript


Published in: JavaScript, UncategorizedPosted by Elijah Grey on


[Note to person reviewing this: You should make a JavaScript post category.]

Most of the time, the standard six native error constructors and the one generic error constructor are not specific enough for an error. What if you want your library to throw a custom SecurityError if it detects an XSS vector on a website? I made a function to create such constructors that behave the exact same way the native error constructors, like SyntaxError by using methods like Error.prototype.toString and the standard error object format. This code makes throwing a custom fake error constructor made with ErrorConstructor("SyntaxError") have the same output as a native SyntaxError in a JavaScript shell. I’ve tested the code in Firefox 3/3.5 and Opera 9.6 and it seems to work fine. Comment and say if it works in your browser too.

function ErrorConstructor(constructorName) {
  var errorConstructor = function(message, fileName, lineNumber) {
  // don't directly name this function, .name is used by Error.prototype.toString
    if (this == window) return new arguments.callee(message, fileName, lineNumber);
    this.name = errorConstructor.name;
    this.message = message||"";
    this.fileName = fileName||location.href;
    if (!isNaN(+lineNumber)) this.lineNumber = +lineNumber;
    else this.lineNumber = 1;
  }
  errorConstructor.name = constructorName||Error.prototype.name;
  errorConstructor.prototype.toString = Error.prototype.toString;

  return errorConstructor;
}

Usage: ErrorConstructor([constructorName])

Note: If no constructorName is specified, the default of Error.prototype.name is used

Usage for generated error constructor: errorConstructor([message[, location[, lineNumber]])

Examples:

var SecurityError = ErrorConstructor("Security Error"),
MarkupError = ErrorConstructor("(X)HTML Markup Error");
//these will both throw a SecurityError starting with "Security Error on line 83:"
var xss_error = "Possible XSS Vector\n\
 JSON XHR response parsed with eval()\n\
 Recommended fix: Parse JSON with JSON.parse";
throw new SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
throw SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
//these will both throw the following MarkupError:
//"(X)HTML Markup Error on line 1: Invalid DOCTYPE"
throw new MarkupError("Invalid DOCTYPE");
throw MarkupError("Invalid DOCTYPE");

AS2 / AS3 Game Score Formatter


Published in: ActionScript, ActionScript 3Posted by Jeremy on 09/11/08


Often when developing games I have the need to add zeros in front of my score depending on how many digits are to be shown. For instance, even though I may have a score of 5, I still need to display 00005 on the screen.

To do this I wrote this useful little function for just that purpose.

trace(formatScore(555, 6)); // 000555 trace(formatScore(-555, 6)); // -000555

function formatScore( value:Number, digits):String {

var scoreStr:String = ''; var tempScore:String = '';

var scoreLen:Number = value.toString().length; var indexOfNeg:Number = value.toString().indexOf('-');

if (value.toString().charAt(0) == '-') {

tempScore = String(value.toString().substring(indexOfNeg+1, scoreLen)); scoreLen--; } for (var i:Number = 0; i<(digits-scoreLen); i++) {

scoreStr += '0'; } var posAnswer:String = String(scoreStr+value.toString()); var negAnswer:String = '-'+String(scoreStr+tempScore.toString()); var answer:String = (indexOfNeg == -1) ? posAnswer : negAnswer;

return answer; }

Jeremy Sykes is a Flash Game Programmer & Developer


CSS Rounded Corner Roundup


Published in: CSSPosted by Jon Henshaw on 07/27/08


The past several years have introduced many different solutions for creating rounded corners using CSS. Some of the solutions use images, while others don’t – while others require assistance from JavaScript. The great thing about Snipplr is that we capture all of these rounded corner techniques on one page. Below is a highlight of some of the best rounded corner techniques.

100% CSS ROUNDED CORNERS !! No IE sorry!

As is common with techniques that use Web standards, when implemented, they don’t work with Internet Explorer (IE). This is one simple technique that uses very simple CSS that adjusts the border radius, but alas, croaks in IE.

Rounded Corners Without Images Or JavaScript

We move onto the next solution that theoretically does work in IE and also doesn’t require images or JavaScript (JS). Unfortunately, it does utilize a lot of CSS code.

Rounded Corners With Images

Failing to be impressed with a lack of images, one can opt for images with this technique. The CSS gets a little shorter and slightly more elegant — now we’re getting somewhere reasonable.

Anti-Aliased Curvy Corners

But if you like to live on the edge and you crave more code that you can shake a stick at, then Curvy Corners is for you. It’s all JS, all the time. It will create on-the-fly rounded corners for any HTML DIV element, that (supposedly) looks as good as any graphically created corners.

If none of the above solutions peak your interest, then feel free to peruse the full list of rounded corner solutions.


Snipplr Ruby Gem, Bringing Snipplr Into the Command Line


Published in: Bash, RubyPosted by narkisr on 07/16/08


Command Line Interface (CLI) has long been my favorite interface when handling code, it makes it easy to edit, search and traverse your code base with tools like vim, find and grep.

Common CLI usage includes the copy and pasting of code snippets. However, keeping track of all those snippets isn’t easy , Snipplr makes the storage and retrieval of snippets easy as pie but requires a Web browser. The Snipplr Ruby Gem is intended to bridge the gap with a simple unified interface. Let’s take for example a scenario on which we would want to get a specific snippet that contains Spring in its title and add it to a file:

Read the rest of this entry »


When a Snippet isn’t a Snippet


Published in: New Features, NewsPosted by Jon Henshaw on 04/09/08


We’ve been getting a lot of snippet entries that are really just spam. Thanks to users like Frank B., we’ve been able to react to it as quickly as possible. However, a better solution for handling this spam is to give our users the ability to flag these snippets themselves.

We’ve implemented a new “Report this Snippet” link that’s located beneath each code snippet box. Clicking on this link will notify us if you think the snippet is spam. There’s also a built in threshold to take the snippet offline if enough unique users click the link.

We’ll see how this system works and will adjust it accordingly. As always, thank you for using Snipplr!


What’s New With Snipplr


Published in: Design, Development, NewsPosted by Jason Tan on 01/17/08


I wanted to write a quick post to update you all on what’s been going on with Snipplr.

First, thank you for your feedback on the new design, both positive and negative. It’s hard to be all things to all people, but we’re going to give it our best shot. Trey is busy working on an alternate style that is more minimalistic, smaller, and has more room to view code. We’d love to give you more control over your preferred interface. In the meantime, I’ve made some small changes to the interface – like making the code editing block more suitable for code on both the new and edit snippet pages.

Aside from the design, I’ve been working to make some system changes:

  • Search. Searching now works more like how you would expect. I’ve also added an advanced search, which allows you to search source code and filter by language.
  • Languages. I added some new languages that were requested and also upgraded GeSHI (for syntax highlighting) to the latest version.
  • Spam. I replaced the math captcha for new user registration with reCAPTCHA and haven’t seen any spam bots try to create an account since.
  • Details. There are lots more minor changes and fixes around the site on both the front and back end. As always, please contact us with any bugs or suggestions you have.

We have lots of more ideas and things in the works, so keep checking back here for the latest news.