SP/web2py/gluon/contrib/populate.py

275 lines
1.4 MiB
Python
Raw Permalink Normal View History

2018-10-25 15:33:07 +00:00
from __future__ import print_function
from gluon._compat import pickle, unicodeT
from gluon.fileutils import open_file
import re
import random
import datetime
IUP = {'shoebill':{'a':1,'187':1},'trout-like':{'parr':1},'fig.':{'19':1},'mcintosh.':{'the':1,'illustration':1},'chiasmodon':{'niger':2},'yellow':{'and':4,'giant':1,'green':2,'red':1,'spots':1},'four':{'brightly':1,'hundred':1,'haunts':1,'feet':1,'solutions':2,'hours.':1,'things':1,'long':1,'.':2,'legs':1,'inches':4,'thousand':1,'million':1,'pairs':2,'hours':1,'satellites':1,'tufts':1,'great':1,'main':1,'of':1,'months':1,'days':1,'times':4,'volumes':1,'inches.':1,'frilled':2,'or':3},'snapping-blades':{'the':1},'aegir':{'on':4},'hanging':{'down':1,'on':2},'bird--evidences':{'of':1},'canes':{'venatici':1},'inheritance.':{'looking':1},'electricity':{'and':5,'belong':1,'is':4,'rotating':2,'held':1,'as':1,'sec':1,'in':1,'yet':1,'predominates':1,'from':1,'there':1,'.':9,'to':1,'which':4,';':4,'has':1,'we':1,'that':1,'here':1,'i.e':1,'like':1,'repel':1,'the':2,'or':1,'attracting':1},'similarity':{'of':3,'between':1},'sunlit':{'side':1},'superficially':{'indistinguishable':1,'like':1},'out-breeding':{'among':1,'when':1,'exogamy':1},'lord':{'popular':1,'kelvin':5,'avebury':1},'non-intelligent':{'experiments':1},'flicking':{'out':1},'meadows':{'and':2,'an':1},'sinking':{'down':2,'according':1,'in':1},'digit':{'of':1,'well':1},'co-operation':{'of':2},'oceans':{'lie':1,'of':1,'there':1,'are':1,'goes':1,'must':1},'pigment':{'and':1,'is':2,'.':1,'as':1,'which':1,';':1},'figs':{'.':1},'fingers.':{'but':1},'experimentally':{'on':1},'bringing':{'of':1,'about':1,'the':2},'elevations':{'and':1,'of':1},'meadow.':{'in':1},'internally':{'hot':1},'whitman':{'says':1,'took':1},'colour--the':{'result':2},'stars.':{'yet':1},'persisted':{'as':1,'until':1},'chameleons':{'the':1,'.':1},'intensification':{'of':1},'succession':{'giving':1,'of':5,'the':1,'has':1,'.':1},'tube--the':{'walls':1},'ultra-violet':{'and':1,'light':1,'waves--which':1,'or':1,'waves':1},'straight':{'ahead':1,'drop':1,'lines':1,'down':1,'through':1,'in':1,'path':2,'line':1,'legs':1,'along':1},'spiders':{'about':1,'were':1,'it':1,'.':1,'scorpions':1,'are':1,'have':1,'in':1},'specially':{'protected':1,'adapted':1},'symmetry.':{'illustration':1},'stiffens':{'.':1},'270':{'a':1,'silk':1,'reproduced':1},'271':{'electrical':1,'from':1},'second':{'and':5,'layer':1,'when':1,'year':1,'extinction':1,'yet':1,'any':1,'group':1,'would':3,'there':1,'question':2,'.':10,'to':1,'millennium':1,'which':1,';':1,'then':1,'we':1,'advantage':1,'that':1,'class':1,'screen.':1,'interglacial':1,'every':1,'longest':1,'not':1,'cousin':1,'copy':1,'opportunity':1,'by':1,'a':1,'great':1,'these':1,'of':1,'or':1,'preparation':1,'printing':1,'error':1,'position':1,'the':2,'chapter':1,'photograph':2},'attended':{'the':1,'by':2},'274':{'photo':1},'275':{'from':1},'278':{'hours':1,'photo':1},'279':{'rotating':1,'the':2},'inanimate':{'world':1},'dormancy':{'.':1},'errors':{'a':1,'in':1},'semicircular':{'canals':1},'phalangers':{'and':1,'flying':1},'thunder':{'and':1,'means':1},'nature.':{'the':1,'typical':1,'what':1,'illustration':1,'one':1},'contributed':{'every':1},'fingers':{'and':6,'to':1,';':1,'2':1,'knocking':1},'lowliness':{'.':1},'fossil':{'horses':1,'remains':2,'series':1,'forms':2,'scorpions':1,'of':2,'species':1},'increasing':{'control--a':1,'temperature':1,'facility':1,'intelligence':1,'complexity':2,'fullness':1,'the':1,'with':1,'day':1},'inducement':{'many':1},'surface--the':{'photosphere--is':1},'chins':{'and':1},'error':{'a':1,'we':1,'is':1,'here':1,'method':2,'to':1,';':1,'or':1,'must':1},'here':{'and':5,'says':1,'is':5,'within':1,'some':1,'it':1,'anticipating':1,'go':1,'seen':1,'again':4,'for':1,'also':1,'rather':1,'concerned':1,'since':1,'.':1,'to':3,'only':2,'cockchafers':1,'you':1,'was':2,'refer':1,'we':2,'let':1,'with':1,'nor':1,'a':1,'of':1,'spontaneously':1,'the':2,'stimulating':1,'are':1},'atoms':{'and':10,'being':1,'is':1,'an':1,'270':1,'whilst':1,'exist':1,'are':4,'have':1,'in':3,'seem':1,'seek':1,'containing':1,'indivisible':1,'from':1,'appear':1,'would':1,'with':1,'had':1,'.':5,'which':2,'got':1,';':2,'has':1,'was':1,'into':1,'do':2,'form':1,'were':4,'but':1,'atoms':2,'break':1,'most':1,
FIRST_NAMES = "James,John,Robert,Michael,William,David,Richard,Charles,Joseph,Thomas,Christopher,Daniel,Paul,Mark,Donald,George,Kenneth,Steven,Edward,Brian,Ronald,Anthony,Kevin,Jason,Matthew,Gary,Timothy,Jose,Larry,Jeffrey,Frank,Scott,Eric,Stephen,Andrew,Raymond,Gregory,Joshua,Jerry,Dennis,Walter,Patrick,Peter,Harold,Douglas,Henry,Carl,Arthur,Ryan,Roger,Joe,Juan,Jack,Albert,Jonathan,Justin,Terry,Gerald,Keith,Samuel,Willie,Ralph,Lawrence,Nicholas,Roy,Benjamin,Bruce,Brandon,Adam,Harry,Fred,Wayne,Billy,Steve,Louis,Jeremy,Aaron,Randy,Howard,Eugene,Carlos,Russell,Bobby,Victor,Martin,Ernest,Phillip,Todd,Jesse,Craig,Alan,Shawn,Clarence,Sean,Philip,Chris,Johnny,Earl,Jimmy,Antonio,Danny,Bryan,Tony,Luis,Mike,Stanley,Leonard,Nathan,Dale,Manuel,Rodney,Curtis,Norman,Allen,Marvin,Vincent,Glenn,Jeffery,Travis,Jeff,Chad,Jacob,Lee,Melvin,Alfred,Kyle,Francis,Bradley,Jesus,Herbert,Frederick,Ray,Joel,Edwin,Don,Eddie,Ricky,Troy,Randall,Barry,Alexander,Bernard,Mario,Leroy,Francisco,Marcus,Micheal,Theodore,Clifford,Miguel,Oscar,Jay,Jim,Tom,Calvin,Alex,Jon,Ronnie,Bill,Lloyd,Tommy,Leon,Derek,Warren,Darrell,Jerome,Floyd,Leo,Alvin,Tim,Wesley,Gordon,Dean,Greg,Jorge,Dustin,Pedro,Derrick,Dan,Lewis,Zachary,Corey,Herman,Maurice,Vernon,Roberto,Clyde,Glen,Hector,Shane,Ricardo,Sam,Rick,Lester,Brent,Ramon,Charlie,Tyler,Gilbert,Gene,Marc,Reginald,Ruben,Brett,Angel,Nathaniel,Rafael,Leslie,Edgar,Milton,Raul,Ben,Chester,Cecil,Duane,Franklin,Andre,Elmer,Brad,Gabriel,Ron,Mitchell,Roland,Arnold,Harvey,Jared,Adrian,Karl,Cory,Claude,Erik,Darryl,Jamie,Neil,Jessie,Christian,Javier,Fernando,Clinton,Ted,Mathew,Tyrone,Darren,Lonnie,Lance,Cody,Julio,Kelly,Kurt,Allan,Nelson,Guy,Clayton,Hugh,Max,Dwayne,Dwight,Armando,Felix,Jimmie,Everett,Jordan,Ian,Wallace,Ken,Bob,Jaime,Casey,Alfredo,Alberto,Dave,Ivan,Johnnie,Sidney,Byron,Julian,Isaac,Morris,Clifton,Willard,Daryl,Ross,Virgil,Andy,Marshall,Salvador,Perry,Kirk,Sergio,Marion,Tracy,Seth,Kent,Terrance,Rene,Eduardo,Terrence,Enrique,Freddie,Wade,Austin,Stuart,Fredrick,Arturo,Alejandro,Jackie,Joey,Nick,Luther,Wendell,Jeremiah,Evan,Julius,Dana,Donnie,Otis,Shannon,Trevor,Oliver,Luke,Homer,Gerard,Doug,Kenny,Hubert,Angelo,Shaun,Lyle,Matt,Lynn,Alfonso,Orlando,Rex,Carlton,Ernesto,Cameron,Neal,Pablo,Lorenzo,Omar,Wilbur,Blake,Grant,Horace,Roderick,Kerry,Abraham,Willis,Rickey,Jean,Ira,Andres,Cesar,Johnathan,Malcolm,Rudolph,Damon,Kelvin,Rudy,Preston,Alton,Archie,Marco,Wm,Pete,Randolph,Garry,Geoffrey,Jonathon,Felipe,Bennie,Gerardo,Ed,Dominic,Robin,Loren,Delbert,Colin,Guillermo,Earnest,Lucas,Benny,Noel,Spencer,Rodolfo,Myron,Edmund,Garrett,Salvatore,Cedric,Lowell,Gregg,Sherman,Wilson,Devin,Sylvester,Kim,Roosevelt,Israel,Jermaine,Forrest,Wilbert,Leland,Simon,Guadalupe,Clark,Irving,Carroll,Bryant,Owen,Rufus,Woodrow,Sammy,Kristopher,Mack,Levi,Marcos,Gustavo,Jake,Lionel,Marty,Taylor,Ellis,Dallas,Gilberto,Clint,Nicolas,Laurence,Ismael,Orville,Drew,Jody,Ervin,Dewey,Al,Wilfred,Josh,Hugo,Ignacio,Caleb,Tomas,Sheldon,Erick,Frankie,Stewart,Doyle,Darrel,Rogelio,Terence,Santiago,Alonzo,Elias,Bert,Elbert,Ramiro,Conrad,Pat,Noah,Grady,Phil,Cornelius,Lamar,Rolando,Clay,Percy,Dexter,Bradford,Merle,Darin,Amos,Terrell,Moses,Irvin,Saul,Roman,Darnell,Randal,Tommie,Timmy,Darrin,Winston,Brendan,Toby,Van,Abel,Dominick,Boyd,Courtney,Jan,Emilio,Elijah,Cary,Domingo,Santos,Aubrey,Emmett,Marlon,Emanuel,Jerald,Edmond,Emil,Dewayne,Will,Otto,Teddy,Reynaldo,Bret,Morgan,Jess,Trent,Humberto,Emmanuel,Stephan,Louie,Vicente,Lamont,Stacy,Garland,Miles,Micah,Efrain,Billie,Logan,Heath,Rodger,Harley,Demetrius,Ethan,Eldon,Rocky,Pierre,Junior,Freddy,Eli,Bryce,Antoine,Robbie,Kendall,Royce,Sterling,Mickey,Chase,Grover,Elton,Cleveland,Dylan,Chuck,Damian,Reuben,Stan,August,Leonardo,Jasper,Russel,Erwin,Benito,Hans,Monte,Blaine,Ernie,Curt,Quentin,Agustin,Murray,Jamal,Devon,Adolfo,Harrison,Tyson,Burton,Brady,Elliott,Wilfredo,Bart,Jarrod,Vance,Denis,Damien,Joaquin,Harlan,Desmond,Elliot,Darwin,Ashley,Gregorio,Buddy,Xavier,Kermit,Roscoe,Esteban,Anton,Solomon,Scotty,Norbert,Elvin,Williams,Nolan,Carey,Rod,Quinton,Hal,Brain,Rob,Elwood,Kendrick,Darius,Moises,Son,Marlin,Fidel,Thaddeus,Cliff,Marcel,Ali
LAST_NAMES="Smith,Johnson,Williams,Jones,Brown,Davis,Miller,Wilson,Moore,Taylor,Anderson,Thomas,Jackson,White,Harris,Martin,Thompson,Garcia,Martinez,Robinson,Clark,Rodriguez,Lewis,Lee,Walker,Hall,Allen,Young,Hernandez,King,Wright,Lopez,Hill,Scott,Green,Adams,Baker,Gonzalez,Nelson,Carter,Mitchell,Perez,Roberts,Turner,Phillips,Campbell,Parker,Evans,Edwards,Collins,Stewart,Sanchez,Morris,Rogers,Reed,Cook,Morgan,Bell,Murphy,Bailey,Rivera,Cooper,Richardson,Cox,Howard,Ward,Torres,Peterson,Gray,Ramirez,James,Watson,Brooks,Kelly,Sanders,Price,Bennett,Wood,Barnes,Ross,Henderson,Coleman,Jenkins,Perry,Powell,Long,Patterson,Hughes,Flores,Washington,Butler,Simmons,Foster,Gonzales,Bryant,Alexander,Russell,Griffin,Diaz,Hayes,Myers,Ford,Hamilton,Graham,Sullivan,Wallace,Woods,Cole,West,Jordan,Owens,Reynolds,Fisher,Ellis,Harrison,Gibson,Mcdonald,Cruz,Marshall,Ortiz,Gomez,Murray,Freeman,Wells,Webb,Simpson,Stevens,Tucker,Porter,Hunter,Hicks,Crawford,Henry,Boyd,Mason,Morales,Kennedy,Warren,Dixon,Ramos,Reyes,Burns,Gordon,Shaw,Holmes,Rice,Robertson,Hunt,Black,Daniels,Palmer,Mills,Nichols,Grant,Knight,Ferguson,Rose,Stone,Hawkins,Dunn,Perkins,Hudson,Spencer,Gardner,Stephens,Payne,Pierce,Berry,Matthews,Arnold,Wagner,Willis,Ray,Watkins,Olson,Carroll,Duncan,Snyder,Hart,Cunningham,Bradley,Lane,Andrews,Ruiz,Harper,Fox,Riley,Armstrong,Carpenter,Weaver,Greene,Lawrence,Elliott,Chavez,Sims,Austin,Peters,Kelley,Franklin,Lawson,Fields,Gutierrez,Ryan,Schmidt,Carr,Vasquez,Castillo,Wheeler,Chapman,Oliver,Montgomery,Richards,Williamson,Johnston,Banks,Meyer,Bishop,Mccoy,Howell,Alvarez,Morrison,Hansen,Fernandez,Garza,Harvey,Little,Burton,Stanley,Nguyen,George,Jacobs,Reid,Kim,Fuller,Lynch,Dean,Gilbert,Garrett,Romero,Welch,Larson,Frazier,Burke,Hanson,Day,Mendoza,Moreno,Bowman,Medina,Fowler,Brewer,Hoffman,Carlson,Silva,Pearson,Holland,Douglas,Fleming,Jensen,Vargas,Byrd,Davidson,Hopkins,May,Terry,Herrera,Wade,Soto,Walters,Curtis,Neal,Caldwell,Lowe,Jennings,Barnett,Graves,Jimenez,Horton,Shelton,Barrett,Obrien,Castro,Sutton,Gregory,Mckinney,Lucas,Miles,Craig,Rodriquez,Chambers,Holt,Lambert,Fletcher,Watts,Bates,Hale,Rhodes,Pena,Beck,Newman,Haynes,Mcdaniel,Mendez,Bush,Vaughn,Parks,Dawson,Santiago,Norris,Hardy,Love,Steele,Curry,Powers,Schultz,Barker,Guzman,Page,Munoz,Ball,Keller,Chandler,Weber,Leonard,Walsh,Lyons,Ramsey,Wolfe,Schneider,Mullins,Benson,Sharp,Bowen,Daniel,Barber,Cummings,Hines,Baldwin,Griffith,Valdez,Hubbard,Salazar,Reeves,Warner,Stevenson,Burgess,Santos,Tate,Cross,Garner,Mann,Mack,Moss,Thornton,Dennis,Mcgee,Farmer,Delgado,Aguilar,Vega,Glover,Manning,Cohen,Harmon,Rodgers,Robbins,Newton,Todd,Blair,Higgins,Ingram,Reese,Cannon,Strickland,Townsend,Potter,Goodwin,Walton,Rowe,Hampton,Ortega,Patton,Swanson,Joseph,Francis,Goodman,Maldonado,Yates,Becker,Erickson,Hodges,Rios,Conner,Adkins,Webster,Norman,Malone,Hammond,Flowers,Cobb,Moody,Quinn,Blake,Maxwell,Pope,Floyd,Osborne,Paul,Mccarthy,Guerrero,Lindsey,Estrada,Sandoval,Gibbs,Tyler,Gross,Fitzgerald,Stokes,Doyle,Sherman,Saunders,Wise,Colon,Gill,Alvarado,Greer,Padilla,Simon,Waters,Nunez,Ballard,Schwartz,Mcbride,Houston,Christensen,Klein,Pratt,Briggs,Parsons,Mclaughlin,Zimmerman,French,Buchanan,Moran,Copeland,Roy,Pittman,Brady,Mccormick,Holloway,Brock,Poole,Frank,Logan,Owen,Bass,Marsh,Drake,Wong,Jefferson,Park,Morton,Abbott,Sparks,Patrick,Norton,Huff,Clayton,Massey,Lloyd,Figueroa,Carson,Bowers,Roberson,Barton,Tran,Lamb,Harrington,Casey,Boone,Cortez,Clarke,Mathis,Singleton,Wilkins,Cain,Bryan,Underwood,Hogan,Mckenzie,Collier,Luna,Phelps,Mcguire,Allison,Bridges,Wilkerson,Nash,Summers,Atkins,Wilcox,Pitts,Conley,Marquez,Burnett,Richard,Cochran,Chase,Davenport,Hood,Gates,Clay,Ayala,Sawyer,Roman,Vazquez,Dickerson,Hodge,Acosta,Flynn,Espinoza,Nicholson,Monroe,Wolf,Morrow,Kirk,Randall,Anthony,Whitaker,Oconnor,Skinner,Ware,Molina,Kirby,Huffman,Bradford,Charles,Gilmore,Dominguez,Oneal,Bruce,Lang,Combs,Kramer,Heath,Hancock,Gallagher,Gaines,Shaffer,Short,Wiggins,Mathews,Mcclain,Fischer,Wall,Small,Melton,Hensley,Bond,Dyer,Cameron,Grimes,Contreras,Christian,Wyatt,Baxter,Snow,Mosley,Shepherd,Larsen,Hoover,Beasley,Glenn,Petersen,White
class Learner:
def __init__(self):
self.db = {}
def learn(self, text):
replacements1 = {'[^a-zA-Z0-9\.;:\-]': ' ',
'\s+': ' ', ', ': ' , ', '\. ': ' . ',
': ': ' : ', '; ': ' ; '}
for key, value in replacements1.items():
text = re.sub(key, value, text)
items = [item.lower() for item in text.split(' ')]
for i in range(len(items) - 1):
item = items[i]
nextitem = items[i + 1]
if item not in self.db:
self.db[item] = {}
if nextitem not in self.db[item]:
self.db[item][nextitem] = 1
else:
self.db[item][nextitem] += 1
def save(self, filename):
pickle.dump(self.db, open_file(filename, 'wb'))
def load(self, filename):
self.loadd(pickle.load(open_file(filename, 'rb')))
def loadd(self, db):
self.db = db
def generate(self, length=10000, prefix=False):
replacements2 = {' ,': ',', ' \.': '.\n', ' :': ':', ' ;':
';', '\n\s+': '\n'}
keys = list(self.db.keys())
key = keys[random.randint(0, len(keys) - 1)]
words = key
words = words.capitalize()
regex = re.compile('[a-z]+')
for i in range(length):
okey = key
if not key in self.db:
break # should not happen
db = self.db[key]
s = sum(db.values())
i = random.randint(0, s - 1)
for key, value in db.items():
if i < value:
break
else:
i -= value
if okey == '.':
key1 = key.capitalize()
else:
key1 = key
if prefix and regex.findall(key1) and \
random.random() < 0.01:
key1 = '<a href="%s%s">%s</a>' % (prefix, key1, key1)
words += ' ' + key1
text = words
for key, value in replacements2.items():
text = re.sub(key, value, text)
return text + '.\n'
def da_du_ma(n=4):
return ''.join([['da', 'du', 'ma', 'mo', 'ce', 'co',
'pa', 'po', 'sa', 'so', 'ta', 'to']
[random.randint(0, 11)] for i in range(n)])
def populate(table, n=None, default=True, compute=False, contents={}):
"""Populate table with n records.
if n is None, it does not populate the database but returns a generator
if default=True use default values to fields.
if compute=False doesn't load values into computed fields.
if contents has data, use these values to populate related fields.
can be used in two ways:
>>> populate(db.tablename, n=100)
or
>>> for k,row in enumerate(populate(db.tablename)): print row
"""
generator = populate_generator(table, default=default,
compute=compute, contents=contents)
if n is not None:
for k,record in enumerate(generator):
if k>=n: break
table.insert(**record)
table._db.commit()
return generator
def populate_generator(table, default=True, compute=False, contents={}):
"""Populate table with n records.
if default=True use default values to fields.
if compute=False doesn't load values into computed fields.
if contents has data, use these values to populate related fields.
"""
ell = Learner()
#ell.learn(open('20417.txt','r').read())
#ell.save('frequencies.pickle')
#ell.load('frequencies.pickle')
ell.loadd(IUP)
ids = {}
while True:
record = contents.copy() # load user supplied contents.
for fieldname in table.fields:
if fieldname in record:
continue # if user supplied it, let it be.
field = table[fieldname]
if not isinstance(field.type, (str, unicodeT)):
continue
elif field.type == 'id':
continue
elif field.type == 'upload':
continue
elif field.compute is not None:
continue
elif default and not field.default in (None, ''):
record[fieldname] = field.default
elif compute and field.compute:
continue
elif field.type == 'boolean':
record[fieldname] = random.random() > 0.5
elif field.type == 'date':
record[fieldname] = \
datetime.date(2009, 1, 1) - \
datetime.timedelta(days=random.randint(0, 365))
elif field.type == 'datetime':
record[fieldname] = \
datetime.datetime(2009, 1, 1) - \
datetime.timedelta(days=random.randint(0, 365))
elif field.type == 'time':
h = random.randint(0, 23)
m = 15 * random.randint(0, 3)
record[fieldname] = datetime.time(h, m, 0)
elif field.type == 'password':
record[fieldname] = ''
elif field.type == 'integer' and \
hasattr(field.requires, 'options'):
options = field.requires.options(zero=False)
if len(options) > 0:
record[fieldname] = options[
random.randint(0, len(options) - 1)][0]
else:
record[fieldname] = None
elif field.type == 'list:integer' and hasattr(field.requires, 'options'):
options = field.requires.options(zero=False)
if len(options) > 0:
record[fieldname] = [item[0] for item in random.sample(
options, random.randint(0, len(options) - 1) / 2)]
elif field.type == 'integer':
try:
record[fieldname] = random.randint(
field.requires.minimum, field.requires.maximum - 1)
except:
if 'day' in fieldname:
record[fieldname] = random.randint(1,28)
elif 'month' in fieldname:
record[fieldname] =random.randint(1,12)
elif 'year' in fieldname:
record[fieldname] =random.randint(2000,2013)
else:
record[fieldname] = random.randint(0, 1000)
elif field.type == 'double' \
or str(field.type).startswith('decimal'):
if hasattr(field.requires, 'minimum'):
rand = random.random()
if str(field.type).startswith('decimal'):
import decimal
rand = decimal.Decimal(rand)
record[fieldname] = field.requires.minimum + \
rand * (field.requires.maximum -
field.requires.minimum)
else:
record[fieldname] = random.random() * 1000
elif field.type[:10] == 'reference ':
tablename = field.type[10:]
if not tablename in ids:
if table._db._dbname == 'gql':
ids[tablename] = [x.id for x in table._db(
table._db[field.type[10:]].id > 0).select()]
else:
ids[tablename] = [x.id for x in table._db(
table._db[field.type[10:]].id > 0).select()]
n = len(ids[tablename])
if n:
record[fieldname] = \
ids[tablename][random.randint(0, n - 1)]
else:
record[fieldname] = 0
elif field.type[:15] == 'list:reference ':
tablename = field.type[15:]
if not tablename in ids:
if table._db._dbname == 'gql':
ids[tablename] = [x.id for x in table._db(
table._db[field.type[15:]].id > 0).select()]
else:
ids[tablename] = [x.id for x in table._db(
table._db[field.type[15:]].id > 0).select()]
n = len(ids[tablename])
if n:
record[fieldname] = [item for item in random.sample(
ids[tablename], random.randint(0, n - 1) / 2)]
else:
record[fieldname] = 0
elif field.type == 'list:string' \
and hasattr(field.requires, 'options'):
options = field.requires.options(zero=False)
if len(options) > 0:
record[fieldname] = [item[0] for item in random.sample(
options, random.randint(0, len(options) - 1) / 2)]
elif field.type == 'string':
if hasattr(field.requires, 'options'):
options = field.requires.options(zero=False)
record[fieldname] = \
options[random.randint(0, len(options) - 1)][0]
elif fieldname.find('url') >= 0:
record[fieldname] = 'http://%s.example.com' % \
da_du_ma(4)
elif fieldname.find('email') >= 0:
record[fieldname] = '%s@example.com' % da_du_ma(4)
elif fieldname.find('name')>=0:
if fieldname.find('first')>=0:
record[fieldname] = random.choice(FIRST_NAMES)
elif fieldname.find('last')>=0:
record[fieldname] = random.choice(LAST_NAMES)
elif fieldname.find('username')>=0:
record[fieldname] = random.choice(FIRST_NAMES).lower()+str(random.randint(1000,9999))
else:
record[fieldname] = random.choice(FIRST_NAMES)+' '+random.choice(LAST_NAMES)
elif fieldname.find('phone')>=0:
record[fieldname] = '(%s%s%s) %s%s%s-%s%s%s%s' % (
random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'),random.choice('1234567890'))
elif fieldname.find('address') >=0:
record[fieldname] = '%s %s %s Street' % (random.randint(1000,9000),random.choice(FIRST_NAMES),random.choice(LAST_NAMES))
else:
z = ell.generate(10, prefix=False)
record[fieldname] = z[:min(60,field.length)].replace('\n', ' ')
elif field.type == 'text':
if fieldname.find('address')>=0:
record[fieldname] = '%s %s %s Street\nChicago, IL\nUSA' % (random.randint(1000,9000),random.choice(FIRST_NAMES),random.choice(LAST_NAMES))
else:
record[fieldname] = ell.generate(
random.randint(10, 100), prefix=None)
yield record
if __name__ == '__main__':
ell = Learner()
ell.loadd(IUP)
print(ell.generate(1000, prefix=None))