Tag Archive for unique

Unique array in JavaScript

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

source

Postgresql find duplicate columns

select event_id,user_id, count(*) from event_attend
group by event_id,user_id
HAVING count(*) > 1

source

Base62 Encode / Decode

function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    // can't handle numbers larger than 2^31-1 = 2147483647
    $str = '';
    do {
        $i = $val % $base;
        $str = $chars[$i] . $str;
        $val = ($val - $i) / $base;
    } while($val > 0);
    return $str;
}

function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    $len = strlen($str);
    $val = 0;
    $arr = array_flip(str_split($chars));
    for($i = 0; $i < $len; ++$i) {
        $val += $arr[$str[$i]] * pow($base, $len-$i-1);
    }
    return $val;
}

echo encode(2147483647); // outputs 2lkCB1

source

Insert or update if unique key already exist

INSERT INTO `tableName`
VALUES (?,?,?,'-1',?,'0')
ON DUPLICATE KEY
UPDATE `id` = ?, `foo` = ?, `bar` = ?

source

MD5 String Hash

#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>

@interface Util : NSObject {}
//	generates a unique id from a string
+ (NSString *)uniqueIDFromString:(NSString *)source;
@end

@implementation Util
//	generates a unique id from a string
+ (NSString *)uniqueIDFromString:(NSString *)source
{
const char *src = [[source lowercaseString] UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(src, strlen(src), result);

NSString *ret = [[[NSString alloc] initWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] autorelease];

return ret;
}
@end

source

PHP isUnique

// FUNCTION isUnique
//
// $table -> table to check
// $field -> column to check
// $value -> value to check
// $except -> a clause to add to the mix.
//
// ex if( ! isUnique( "users" , "user_login" , "user1" );
// ex if( ! isUnique( "users" , "user_login" , "user1" , "user_id != XX" );

function isUnique( $table , $field , $value , $except = null )
{


// build the query
// value is escape cause maybe that comes from the user form
// the rest should be coming from the programmer.

$q = "SELECT COUNT( ".$field." ) as total FROM ".$table." WHERE ".$field." = '".mysql_escape_string( $value )."'";


// ok exception clause so lets just add it to the where
// this probably gets used when a user does an update to their
// user name...
if( $except != null )
{
$q .= "' AND ".$except;
}


$qr = dbquery( $q );
$total = $qr->fields['total'];

return $total == 0;
}

source

Create Unique Code Replacing Lookalike Characters

function create_key(&$cnnDB){
$letters = range('A','Z');
$numbers = range(0,9);
$all = array_merge($numbers,$letters);
$foundkey = false;
while(!$foundkey){
for($i=0;$i<5;$i++){
$num = rand(0,count($all)-1);
$key .= $all[$num];
$total += $num;
}

//Replace Oh with Zero, I with one
$key = str_replace(
array('O','I'),
array('0','1'),
$key
);

//make checksum
$key .= $all[($total % count($all))];

$key = str_replace(
array('O','I'),
array('0','1'),
$key
);

$SQL = 'select C_Key from customers where C_Key = "'.$key.'"';
$result = $cnnDB->GetRow($SQL);
if(count($result) == 0){
$foundkey = true;
}
}

return $key;
}

source

Unique ID sequence class

class UniqueIdGenerator(object):
"""A dictionary-like class that can be used to assign unique integer IDs to
names.

Usage:

>>> gen = UniqueIdGenerator()
>>> gen["A"]
0
>>> gen["B"]
1
>>> gen["C"]
2
>>> gen["A"]      # Retrieving already existing ID
0
>>> len(gen)      # Number of already used IDs
3
"""

def __init__(self, id_generator=None):
"""Creates a new unique ID generator. `id_generator` specifies how do we
assign new IDs to elements that do not have an ID yet. If it is `None`,
elements will be assigned integer identifiers starting from 0. If it is
an integer, elements will be assigned identifiers starting from the given
integer. If it is an iterator or generator, its `next` method will be
called every time a new ID is needed."""
if id_generator is None: id_generator = 0
if isinstance(id_generator, int):
import itertools
self._generator = itertools.count(id_generator)
else:
self._generator = id_generator
self._ids = {}

def __getitem__(self, item):
"""Retrieves the ID corresponding to `item`. Generates a new ID for `item`
if it is the first time we request an ID for it."""
try:
return self._ids[item]
except KeyError:
self._ids[item] = self._generator.next()
return self._ids[item]

def __len__(self):
"""Retrieves the number of added elements in this UniqueIDGenerator"""
return len(self._ids)

def reverse_dict(self):
"""Returns the reversed mapping, i.e., the one that maps generated IDs to their
corresponding items"""
return dict((v, k) for k, v in self._ids.iteritems())

def values(self):
"""Returns the list of items added so far. Items are ordered according to
the standard sorting order of their keys, so the values will be exactly
in the same order they were added if the ID generator generates IDs in
ascending order. This hold, for instance, to numeric ID generators that
assign integers starting from a given number."""
return sorted(self._ids.keys(), key = self._ids.__getitem__)

source

Unique

Array.prototype._unique = function() {
/*
*  Kills duplicates in an array
*/

var obj={}, i=this.length, arr=[],t;
while(i--)
t=this[i],obj[t]=t;

for(i in obj)
arr.push(obj[i]);

return arr;
};// End Function

source

simple UUID

function uuid($length=32) {
mt_srand((double)microtime()*1000000);
$r = strtoupper(md5(time().$_SERVER["REMOTE_ADDR"].$_SERVER["UNIQUE_ID"].mt_rand(0,9999)));
if ($length<32){ $r=substr($r,0,$length-1); }
return $r;
}

source