rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
tmp = ['0' if s[(4 * x)] == 0 else '1' for x in range((len(s) / 4))] n[row + orow][ocol:ocol + 128] = tmp row += 1
tmp = [1 if s[(x*4)]==s[(x*4)+1]==s[(x*4)+2]==s[(x*4)+3] else 0 for x in range(int(len(s)/4))] n[row+orow][ocol:ocol+128] = tmp row+=1
def post(self): delList = [] key = self.request.params.get('k', None) now = time.time() seed = self.request.params.get('seed', int(now / 15)) tile = Tile.get(db.Key.from_path('Tiles', key)) if tile: #if it does exist, turn it into a binary 256x256 matrix n = [] row = 0 for s in png.Reader(bytes=tile.band).asRGBA()[2]: ...
palette = [(0x00, 0x00, 0x00, 0xff), (0xff, 0xff, 0xff, 0x00)] w = png.Writer(256, 256, palette=palette, bitdepth=1) w.write(f, n)
palette=[(0,0,0,255),(255,255,255,255)] w = png.Writer(256,256, interlace=0, palette=palette, bitdepth=1, greyscale=False) w.write(f, n)
def post(self): delList = [] key = self.request.params.get('k', None) now = time.time() seed = self.request.params.get('seed', int(now / 15)) tile = Tile.get(db.Key.from_path('Tiles', key)) if tile: #if it does exist, turn it into a binary 256x256 matrix n = [] row = 0 for s in png.Reader(bytes=tile.band).asRGBA()[2]: ...
('/cron/interpolate/tiles', InterpolateTile)],
('/cron/see', SeeImage), ('/cron/interpolate/tiles', InterpolateTile), ('/cron/bytes', Bytes)],
def post(self): delList = [] key = self.request.params.get('k', None) now = time.time() seed = self.request.params.get('seed', int(now / 15)) tile = Tile.get(db.Key.from_path('Tiles', key)) if tile: #if it does exist, turn it into a binary 256x256 matrix n = [] row = 0 for s in png.Reader(bytes=tile.band).asRGBA()[2]: ...
of = self.request.params.get('offset', None)
of = self.request.params.get('offset', 0)
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) results = [] of = self.request.params.get('offset', None) #items = "{'items':[" start = time.time() if k: key = db.Key.fro...
if of is not None: d = q.fetch(10,offset=int(of)) else: of = 0 d = q.fetch(10)
d = q.fetch(n,offset=int(of))
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) results = [] of = self.request.params.get('offset', None) #items = "{'items':[" start = time.time() if k: key = db.Key.fro...
if ct==10: of = int(of)+10
la = int(of) - n if ct==n: of = int(of)+n
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) results = [] of = self.request.params.get('offset', None) #items = "{'items':[" start = time.time() if k: key = db.Key.fro...
out = {"time":t,"items":results,"next":of}
out = {"time":t,"items":results,"next":of,"last":la}
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) results = [] of = self.request.params.get('offset', None) #items = "{'items':[" start = time.time() if k: key = db.Key.fro...
n[oct+int(((math.floor(row/2)+oct)*256) + math.floor(ct/2))] = c n[oct+int(((math.floor(row/2)+oct+1)*256) + math.floor(ct/2))] = c n[oct+int(((math.floor(row/2)+oct)*256) + math.floor(ct/2) + 1)] = c n[oct+int(((math.floor(row/2)+oct+1)*256) + math.floor(ct/2) + 1)] = c
n[oct+int(((math.floor(row/2)+orow)*256) + math.floor(ct/2))] = c n[oct+int(((math.floor(row/2)+orow+1)*256) + math.floor(ct/2))] = c n[oct+int(((math.floor(row/2)+orow)*256) + math.floor(ct/2) + 1)] = c n[oct+int(((math.floor(row/2)+orow+1)*256) + math.floor(ct/2) + 1)] = c
def get(self): #from now on, assume the key sent was k="01" key = self.request.params.get('k', None) bands = [] #we just want a list with a '0' pixel place holder for every pixel in a 256x256 PNG n = "0" * 65536 n = list(n) #the way that quadtree logic works, is that every tile of 256x256, is quartered #into 4 equa...
n = self.request.params.get('n', 10)
n = int(self.request.params.get('n', 10))
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) n = self.request.params.get('n', 10) results = [] of = self.request.params.get('offset', 0) #items = "{'items':[" start = ...
of = self.request.params.get('offset', 0)
of = int(self.request.params.get('offset', 0))
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) n = self.request.params.get('n', 10) results = [] of = self.request.params.get('offset', 0) #items = "{'items':[" start = ...
d = q.fetch(n,offset=int(of))
d = q.fetch(n,offset=of)
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) n = self.request.params.get('n', 10) results = [] of = self.request.params.get('offset', 0) #items = "{'items':[" start = ...
la = int(of) - n
la = int(of) - n if int(of) - n > -1 else None
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) n = self.request.params.get('n', 10) results = [] of = self.request.params.get('offset', 0) #items = "{'items':[" start = ...
self.response.out.write(simplejson.dumps(out, indent=4))
self.response.out.write(simplejson.dumps(out))
def post(self): cb = self.request.params.get('callback', None) if cb is not None: self.response.out.write("%s(" % cb) k = self.request.params.get('key', None) s = self.request.params.get('s', None) n = self.request.params.get('n', 10) results = [] of = self.request.params.get('offset', 0) #items = "{'items':[" start = ...
sw.FixReorder(); return sw.Wire();
sw.ClosedWireMode = True; sw.FixReorderMode = 1; sw.FixConnectedMode = 1; sw.FixLackingMode = 1; sw.FixGaps3dMode = 1; sw.FixConnectedMode = 1; sw.FixDegeneratedMode = 1; sw.Perform(); return sw.WireAPIMake();
def fixWire(wire): sw = ShapeFix_Wire(); sw.Load(wire); sw.FixReorder(); return sw.Wire();
image= fields.Many2One('nereid.static.file', 'Image',) author= fields.Many2One('res.users', 'Author',)
author= fields.Many2One('res.user', 'Author',)
def defaults_active(self, cursor, user, context=None ): 'Return True' return True
_order = ('sequence', 'ASC')
def on_change_with_unique_identifier(self, cursor, user, vals, context=None): if vals.get('name'): if not vals.get('unique_identifier'): vals['unique_identifier'] = slugify(vals['name']) return vals['unique_identifier']
menu_item_object, menu_item_id, menu, context)
menu_item_object, menu_item_id[0], menu, context)
def _menu_for(self, cursor, user, identifier, ident_field_value, context=None): """ Returns a dictionary of menu tree
request.tryton_user,
request.tryton_user.id,
def wrapper(identifier, ident_field_value): return self._menu_for( local.transaction.cursor, request.tryton_user, identifier, ident_field_value, request.tryton_context )
menu_item_object, menu_item_id, menu, context): """ :param menu_item_object: object from pool :param menu_item_id: ID of the remote item :param menu: Browse Record of the menu item
menu, menu_item, context): """ :param menu: BrowseRecord of the Menu :param menu_item: BrowseRecord of the root menu_item
def _generate_menu_tree(self, cursor, user, menu_item_object, menu_item_id, menu, context): """ :param menu_item_object: object from pool :param menu_item_id: ID of the remote item :param menu: Browse Record of the menu item :param context: Tryton Context """ result = {} menu_item = menu_item_object.browse( cursor, us...
menu_item = menu_item_object.browse( cursor, user, menu_item_id, context) result['parent'] = self._menu_item_to_dict( cursor, user, menu_item, menu)
result.update( self._menu_item_to_dict( cursor, user, menu_item, menu ) )
def _generate_menu_tree(self, cursor, user, menu_item_object, menu_item_id, menu, context): """ :param menu_item_object: object from pool :param menu_item_id: ID of the remote item :param menu: Browse Record of the menu item :param context: Tryton Context """ result = {} menu_item = menu_item_object.browse( cursor, us...
self._menu_item_to_dict(cursor, user, child, menu) \
self._generate_menu_tree( cursor, user, menu, child, context) \
def _generate_menu_tree(self, cursor, user, menu_item_object, menu_item_id, menu, context): """ :param menu_item_object: object from pool :param menu_item_id: ID of the remote item :param menu: Browse Record of the menu item :param context: Tryton Context """ result = {} menu_item = menu_item_object.browse( cursor, us...
return self._generate_menu_tree(cursor, user, menu_item_object, menu_item_id[0], menu, context)
root_menu_item = menu_item_object.browse( cursor, user, menu_item_id[0], context ) return self._generate_menu_tree( cursor, user, menu, root_menu_item, context )
def _menu_for(self, cursor, user, identifier, ident_field_value, context=None): """ Returns a dictionary of menu tree
cursor.execute('select distinct parent from cms_menuitems where \ id in (' + ','.join(
cursor.execute('select distinct parent from nereid_cms_menuitems \ where id in (' + ','.join(
def check_recursion(self, cursor, user, ids): """ Check the recursion beyond a certain limit. :param cursor: Database Cursor :param user: ID of User :param ids: ID of Current Record
local.transaction.cursor, user, ids, request.tryton_context
local.transaction.cursor, request.tryton_user.id, ids, request.tryton_context
def wrapper(domain, offset=0, limit=10, order=None): """ :param domain: a list of tuples or lists lists are constructed like this: ``['operator', args, args, ...]`` operator can be 'AND' or 'OR', if it is missing the default value will be 'AND' tuples are constructed like this: ``('field name', 'operator', value)`` fie...
unique_name = fields.Char('Unique Name', size=100, required=True,)
unique_name = fields.Char( 'Unique Name', required=True, on_change_with=['title', 'unique_name'], )
def on_change_with_unique_name(self, cursor, user, vals, context=None): if vals.get('title'): if not vals.get('unique_name'): vals['unique_name'] = slugify(vals['title']) return vals['unique_name']
def defaults_active(self, cursor, user, context=None ):
def default_active(self, cursor, user, context=None ):
def defaults_active(self, cursor, user, context=None ): 'Return True' return True
published_on = fields.DateTime('Published On')
published_on = fields.Date('Published On')
def render(self, uri, page=1): """ Renders the category """ article_obj = self.pool.get('nereid.cms.article') category_ids = self.search([('uri', '=', uri)]) if not category_ids: return NotFound()
'name' : getattr(menu_item, menu.identifier_field), 'uri' : getattr(menu_item, menu.uri_field),
'name' : getattr(menu_item, menu.identifier_field.name), 'uri' : getattr(menu_item, menu.uri_field.name),
def _menu_item_to_dict(self, cursor, user, menu_item, menu): """ :param menu_item: BR of the menu item :param menu: BR of the menu set """ return { 'name' : getattr(menu_item, menu.identifier_field), 'uri' : getattr(menu_item, menu.uri_field), }
user = user_obj.browse(cursor, user_id, user_id, context=context)
user = user_obj.browse(cursor, user, user, context=context)
def default_author(self, cursor, user, context=None ): user_obj = self.pool.get('res.user') employee_obj = self.pool.get('company.employee')
def menu_for(self, *args):
def menu_for(self, request):
def menu_for(self, *args): """ Template context processor method
'name' : menu_item.name,
'name' : getattr(menu_item, menu.identifier_field),
def _menu_item_to_dict(self, cursor, user, menu_item, menu): """ :param menu_item: BR of the menu item :param menu: BR of the menu set """ return { 'name' : menu_item.name, 'uri' : getattr(menu_item, menu.uri_field), }
_order = 'sequence' title= fields.Char('Title', size=100, required=True,) unique_name= fields.Char(
_order = ('sequence', 'ASC') title = fields.Char('Title', size=100, required=True,) unique_name = fields.Char(
def on_change_with_unique_identifier(self, cursor, user, vals, context=None): if vals.get('name'): if not vals.get('unique_identifier'): vals['unique_identifier'] = slugify(vals['name']) return vals['unique_identifier']
def _menu_item_to_dict(self, cursor, user, menu_item, menu): """ :param menu_item: BR of the menu item :param menu: BR of the menu set """ return { 'name' : menu_item.name, 'uri' : getattr(menu_item, menu.uri_field), } def _generate_menu_tree(self, cursor, user, menu_item_object, menu_item_id, menu, context): """ :par...
def __init__(self): super(CMSMenus, self).__init__() self._sql_constraints += [ ('unique_identifier', 'UNIQUE(unique_identifier, website)', 'The Unique Identifier of the Menu must be unique.'), ]
return time.strftime("%Y-%m-%d %H:%M:%S")
date_obj = self.pool.get('ir.date') return date_obj.today(cursor, user, context=context)
def default_create_date(self, cursor, user, context=None ): return time.strftime("%Y-%m-%d %H:%M:%S")
return time.strftime("%Y-%m-%d %H:%M:%S")
date_obj = self.pool.get('ir.date') return date_obj.today(cursor, user, context=context)
def default_published_on(self, cursor, user, context=None ): return time.strftime("%Y-%m-%d %H:%M:%S")
return wrapper
return {'menu_for': wrapper}
def wrapper(identifier, ident_field_value): return self._menu_for( local.transaction.cursor, request.tryton_user, identifier, ident_field_value, request.tryton_context )
for i in range(1,KEY_LEN):
for i in range(0,KEY_LEN):
def rand_key(): key=str() for i in range(1,KEY_LEN): key += "%02x"%( random.randint( 0, 255) ) return key
for i in range(1,NUM_KEYS):
for i in range(0,NUM_KEYS):
def rand_key(): key=str() for i in range(1,KEY_LEN): key += "%02x"%( random.randint( 0, 255) ) return key
out_file.write(bytes(out_data[:filesize - out_file.tell()]))
out_file.write(self.fix_bytes(out_data[:filesize - out_file.tell()]))
def decrypt_file(self, in_file_path, out_file_path, password = None): with open(in_file_path, 'rb') as in_file: #If a password is provided, generate key and iv using salt from file. if password is not None: self._salt = in_file.read (32) self.create_key_from_password (password) #Key and iv have not been generated or ...
out_file.write(bytes(out_data))
out_file.write(self.fix_bytes(out_data))
def decrypt_file(self, in_file_path, out_file_path, password = None): with open(in_file_path, 'rb') as in_file: #If a password is provided, generate key and iv using salt from file. if password is not None: self._salt = in_file.read (32) self.create_key_from_password (password) #Key and iv have not been generated or ...
out_file.write(bytes(out_data))
out_file.write(self.fix_bytes(out_data))
def encrypt_file(self, in_file_path, out_file_path, password = None): #If a password is provided, generate new salt and create key and iv if password is not None: self.new_salt() self.create_key_from_password(password) else: self._salt = None #If key and iv are not provided are established above, bail out. if self._ke...
if fname in knownProblemFiles:
if os.path.basename(fname) in knownProblemFiles:
def importModel(modelName, srcPath, dstPath = None, clobber=False): "importing model into the database" if dstPath == None: dstPath = initialize.atmosStoragePath(modelName) # Check to see if the destination path exists if not os.path.exists(dstPath): os.makedirs(dstPath) modeldb.initModelTable(modelName) conn...
conn.close()
def getInterpModels(dimensions, whereSQLStatement, gridData): conn = modeldb.getModelDBConnection() positions = conn.execute('select %s whereSQLStatement' % (dimensions,)).fetchall() binaryDecks = conn.execute('select deck whereSQLStatement') conn.close() modelGrid = [] for binDeck in binaryDecks: deck = pickle.loa...
connection.close()
def getNearestNeighbours(model, Teff, logg, FeH, k=2.0, alpha=0.0, level=1): """ Finds the nearest neighbours to a point in a multi-dimensional grid. Parameters: =========== FeH : float The metallicity ([Fe/H]) of the star you plan to interpolate for. Teff : float The effective temperature (Teff in Kelvin)...
alpha_available = [point[4] for point in grid if point[1] in FeH_neighbours and point[0] in Teff_neighbours and point[1] in logg_neighbours and point[3] in k_neighbours]
def getNearestNeighbours(model, Teff, logg, FeH, k=2.0, alpha=0.0, level=1): """ Finds the nearest neighbours to a point in a multi-dimensional grid. Parameters: =========== FeH : float The metallicity ([Fe/H]) of the star you plan to interpolate for. Teff : float The effective temperature (Teff in Kelvin)...
availableDimenstions = {
availableDimensions = {
def getNearestNeighbours(model, Teff, logg, FeH, k=2.0, alpha=0.0, level=1): """ Finds the nearest neighbours to a point in a multi-dimensional grid. Parameters: =========== FeH : float The metallicity ([Fe/H]) of the star you plan to interpolate for. Teff : float The effective temperature (Teff in Kelvin)...
whereSql = ' from %s where ' % modelName + ' between ? and ? '.join(dimensions) + ' between ? and ?'
whereSql = ' from %s where ' % model + ' between ? and ? '.join(dimensions) + ' between ? and ?'
def getNearestNeighbours(model, Teff, logg, FeH, k=2.0, alpha=0.0, level=1): """ Finds the nearest neighbours to a point in a multi-dimensional grid. Parameters: =========== FeH : float The metallicity ([Fe/H]) of the star you plan to interpolate for. Teff : float The effective temperature (Teff in Kelvin)...
raise atmosphyOutOfBoundsError('the given data point (%2.4f)' ' is outside the bounds of the grid' % point)
raise atmosphyOutOfBoundsError('the given data point (%2.4f) is outside the bounds of the grid' % point)
def get1Dneighbours(data, point, level=1): """ Returns closest neighbours on either side of the point provided. Parameters: =========== data : array The data points used to find neighbours from. point : float The point used to look for neighbours. level : integer, optional The number of neighbours to find o...
if model == '\n': continue
if model == '\n' or model == '': continue
def importModel(modelName, srcPath, dstPath = None, clobber=False): "importing model into the database" if dstPath == None: dstPath = initialize.atmosStoragePath(modelName) # Check to see if the destination path exists if not os.path.exists(dstPath): os.makedirs(dstPath) modeldb.initModelTable(modelName) conn...
return True
def importModel(modelName, srcPath, dstPath = None, overwrite=False, verbose=False): if dstPath == None: dstPath = initialize.atmosStoragePath(modelName) # Check to see if the destination path exists if not os.path.exists(dstPath): os.makedirs(dstPath) modelData = splitModel(srcPath,dstPath) dbPath = initialize.atmosS...
mixLengthMatch = re.search('L/H[ =]?(\d+\.\d+)',model)
mixLengthMatch = re.search('ONVECTION (OFF|ON)\s+(\d+\.\d+)',model)
def splitModel(srcPath, dstPath, overwrite=False, verbose=False): """Imports the standard CasKur Modelgrid from srcPath and writes single files to dstPath""" srcPath = os.path.abspath(srcPath) dstPath = os.path.abspath(dstPath) modelData = [] for fname in glob(os.path.join(srcPath,'*.dat')): modelSrc = file(fname).read...
raise casKurImportException("Current\ Model does not contain effective\ temperature:\n\n--------\n\n%s"%model)
raise casKurImportException( "Current Model does not contain effective temperature:" "\n\n--------\n\n%s" % (model,))
def splitModel(srcPath, dstPath, overwrite=False, verbose=False): """Imports the standard CasKur Modelgrid from srcPath and writes single files to dstPath""" srcPath = os.path.abspath(srcPath) dstPath = os.path.abspath(dstPath) modelData = [] for fname in glob(os.path.join(srcPath,'*.dat')): modelSrc = file(fname).read...
raise casKurImportException("Current\ Model does not contain metallicity \ information:\n\n--------\n\n%s"%model)
raise casKurImportException( "Current Model does not contain metallicity information:" "\n\n--------\n\n%s" % (model,)) if mixLengthMatch == None: raise casKurImportException( "Current Model does not contain mixing length information:" "\n\n--------\n\n%s" % (model,))
def splitModel(srcPath, dstPath, overwrite=False, verbose=False): """Imports the standard CasKur Modelgrid from srcPath and writes single files to dstPath""" srcPath = os.path.abspath(srcPath) dstPath = os.path.abspath(dstPath) modelData = [] for fname in glob(os.path.join(srcPath,'*.dat')): modelSrc = file(fname).read...
alpha = float(metalAlphaMatch.groups()[0]) mixing = convertAlpha[metalAlphaMatch.groups()[0]]
alpha = convertAlpha[metalAlphaMatch.groups()[1]] mixing = float(mixLengthMatch.groups()[1])
def splitModel(srcPath, dstPath, overwrite=False, verbose=False): """Imports the standard CasKur Modelgrid from srcPath and writes single files to dstPath""" srcPath = os.path.abspath(srcPath) dstPath = os.path.abspath(dstPath) modelData = [] for fname in glob(os.path.join(srcPath,'*.dat')): modelSrc = file(fname).read...
self.assertAlmostEqual(15.2509232731,pred.sigma,places=10) self.assertAlmostEqual(13.5855936402,pred.mu,places=10)
self.assertAlmostEqual(16.0393816869,pred.sigma,places=5) self.assertAlmostEqual(15.6772857277,pred.mu,places=5)
def bran(x): y = (x[1]-(5.1/(4.*pi**2.))*x[0]**2.+5.*x[0]/pi-6.)**2.+10.*(1.-1./(8.*pi))*cos(x[0])+10. return y
if default_value.shape != shape:
def __init__(self, default_value=None, dtype = None, shape = None, iotype=None, desc=None, units=None, **metadata): # Determine default_value if unspecified if default_value is None: if shape is None or len(shape) == 1: default_value = array([]) elif len(shape) == 2: default_value = array([[]]) elif len(shape) == 3: d...
def easy_test(self, text, outcome, variables):
def easy(self, text, outcome, variables):
def easy_test(self, text, outcome, variables): t = self.go_single(text, variables) self.assertTrue(t == outcome)
self.easy_test(s, s, {})
self.easy(s, s, {})
def test_no_changes(self): s = "hello, i'm andrew" self.easy_test(s, s, {})
self.easy_test(s, t, {"h" : "HEIGHT"})
self.easy(s, t, {"h" : "HEIGHT"})
def test_normal_replace(self): s = "my height: %h" t = "my heighHEIGHT " self.easy_test(s, t, {"h" : "HEIGHT"})
self.easy_test(s, t, {"h" : "andrew"})
self.easy(s, t, {"h" : "andrew"})
def test_normal_replace_beginning(self): s = "%h blahhREAL DATA" t = "andrew REAL DATA" self.easy_test(s, t, {"h" : "andrew"})
self.easy_test(s, t, {"*n" : 103})
self.easy(s, t, {"*n" : 103})
def test_overwrite_variable(self): s = "METHOD %*n" t = "METHOD 103" self.easy_test(s, t, {"*n" : 103})
self.easy_test(s, t, {"*n" : 103})
self.easy(s, t, {"*n" : 103})
def test_overwrite_variable_2(self): s = "METHOD %*n DONT REMOVE" t = "METHOD 103 DONT REMOVE" self.easy_test(s, t, {"*n" : 103})
self.easy_test(s, t, {"*method": 103})
self.easy(s, t, {"*method": 103})
def test_overwrite_long_var(self): s = "METHOD %*method" t = "METHOD 103 " self.easy_test(s, t, {"*method": 103})
bounds = (genome.getParam("rangemin",0), genome.getParam("rangemax",100)) dim = len(genome)
bounds = (gMom.getParam("rangemin",0), gMom.getParam("rangemax",100)) dim = len(gMom)
def G1DListCrossOverRealHypersphere(genome, **args): """ A genome reproduction algorithm, developed by Tristan Hearn at the NASA Glenn Research Center, which uses a hypersphere defined by a pair of parents to find the space of possible children. Children are then picked at random from that space. """ gMom = args['mom'...
if self.parent: self.parent.child_invalidated(self.name)
if self.parent: self.parent.child_invalidated(self.name, outs)
def _pre_execute (self, force=False): """Prepares for execution by calling *tree_rooted()* and *check_config()* if their "dirty" flags are set, and by requesting that the parent Assembly update this Component's invalid inputs. Overrides of this function must call this version. """ if self._call_tree_rooted: self.tree_...
self.invalidate_deps() if self.parent is None:
outs = self.invalidate_deps() if (outs is None) or outs: if self.parent: self.parent.child_invalidated(self.name, outs) if self.parent is None: self._call_execute = True valids = self._valid_dict for name in self.list_inputs(): valids[name] = True else: valids = self._valid_dict invalid_ins = [inp for inp in self.lis...
def _pre_execute (self, force=False): """Prepares for execution by calling *tree_rooted()* and *check_config()* if their "dirty" flags are set, and by requesting that the parent Assembly update this Component's invalid inputs. Overrides of this function must call this version. """ if self._call_tree_rooted: self.tree_...
valids = self._valid_dict for name in self.list_inputs():
self.parent.update_inputs(self.name, invalid_ins) for name in invalid_ins:
def _pre_execute (self, force=False): """Prepares for execution by calling *tree_rooted()* and *check_config()* if their "dirty" flags are set, and by requesting that the parent Assembly update this Component's invalid inputs. Overrides of this function must call this version. """ if self._call_tree_rooted: self.tree_...
else: valids = self._valid_dict invalid_ins = [inp for inp in self.list_inputs(connected=True) if valids.get(inp) is False] if invalid_ins: self._call_execute = True self.parent.update_inputs(self.name, invalid_ins) for name in invalid_ins: valids[name] = True elif self._call_execute == False and len(self.list_outputs(...
elif self._call_execute == False and len(self.list_outputs(valid=False)): self._call_execute = True
def _pre_execute (self, force=False): """Prepares for execution by calling *tree_rooted()* and *check_config()* if their "dirty" flags are set, and by requesting that the parent Assembly update this Component's invalid inputs. Overrides of this function must call this version. """ if self._call_tree_rooted: self.tree_...
Returns None, indicating that all outputs are invalidated.
Returns None, indicating that all outputs are newly invalidated, or [], indicating that no outputs are newly invalidated.
def invalidate_deps(self, varnames=None, force=False): """Invalidate all of our outputs if they're not invalid already. For a typical Component, this will always be all or nothing, meaning there will never be partial validation of outputs. NOTE: Components supporting partial output validation must override this functi...
print 'listdirs = ', os.listdir()
print 'listdirs = ', os.listdir('.')
def _build_sdist(projdir, destdir, version): """Build an sdist out of a develop egg.""" startdir = os.getcwd() try: os.chdir(projdir) # clean up any old builds if os.path.exists('build'): shutil.rmtree('build') _build_dist('sdist', destdir) if sys.platform == 'win32': # turn .zip file into .tar.gz file so setuptools wi...
check_call(['bzr', 'tag', options.version])
def main(): """Create an OpenMDAO release, placing the following files in the specified destination directory: - a tar file of the repository - source distribs of all of the openmdao subpackages - an openmdao empty top level distrib that does nothing but depend on all of the openmdao subpackages (so someone can 'openm...
local = ResourceAllocationManager.get_allocator(0) n_servers = local.max_servers({'python_version':sys.version[:3]})
n_servers = self.local.max_servers({'python_version':sys.version[:3]})
def test_max_servers(self): logging.debug('') logging.debug('test_max_servers')
self.assertEqual(n_servers, local.max_load * n_cpus)
self.assertEqual(n_servers, self.local.max_load * n_cpus)
def test_max_servers(self): logging.debug('') logging.debug('test_max_servers')
n_servers = local.max_servers({'python_version':'bad-version'})
n_servers = self.local.max_servers({'python_version':'bad-version'})
def test_max_servers(self): logging.debug('') logging.debug('test_max_servers')
local = ResourceAllocationManager.get_allocator(0) local.max_load = 10 self.assertEqual(local.name, 'LocalHost')
def test_hostnames(self): logging.debug('') logging.debug('test_hostnames')
local = ResourceAllocationManager.get_allocator(0) local.max_load = 10
def test_resources(self): logging.debug('') logging.debug('test_resources')
base = os.path.join(destdir,os.path.basename(projdir)) zipname = base+'-%s.zip' % version tarname = base+'-%s.tar.gz' % version
base = os.path.join(destdir, os.path.basename(projdir)+'-%s' % version) zipname = base+'.zip' tarname = base+'.tar.gz'
def _build_sdist(projdir, destdir, version): """Build an sdist out of a develop egg.""" startdir = os.getcwd() try: os.chdir(projdir) # clean up any old builds if os.path.exists('build'): shutil.rmtree('build') _build_dist('sdist', destdir) if sys.platform == 'win32': # turn .zip file into .tar.gz file so setuptools wi...
def build_docs(version=None):
def build_docs(argv=None):
def build_docs(version=None): """A script (openmdao_build_docs) points to this. It generates the Sphinx documentation for openmdao. """ branchdir, docdir, bindir =_get_dirnames() startdir = os.getcwd() if not os.path.isdir(docdir): raise RuntimeError('doc directory '+docdir+' not found') _write_src_docs(branchdir, d...
if version: shtitle = 'OpenMDAO Documentation v%s' % version else: version = 'rev %s' % get_revision() shtitle = 'OpenMDAO Documentation (%s)' % version
def build_docs(version=None): """A script (openmdao_build_docs) points to this. It generates the Sphinx documentation for openmdao. """ branchdir, docdir, bindir =_get_dirnames() startdir = os.getcwd() if not os.path.isdir(docdir): raise RuntimeError('doc directory '+docdir+' not found') _write_src_docs(branchdir, d...
parser = OptionParser() parser.add_option("-v", "--version", action="store", type="string", dest="version", help="version string applied to docs") (options, args) = parser.parse_args(sys.argv[1:]) build_docs(options.version)
build_docs()
def _compare_traits_path(x, y): if os.path.basename(x) > os.path.basename(y): return 1 elif os.path.basename(x) < os.path.basename(y): return -1 else: return 0
check_call([sys.executable, installer, '-d', destdir, '-f', 'http://openmdao.org/dists'])
check_call([sys.executable, installer, '-d', destdir])
def main(): """Create an OpenMDAO release, placing the following files in the specified destination directory: - a tar file of the repository - source distribs of all of the openmdao subpackages - an openmdao empty top level distrib that does nothing but depend on all of the openmdao subpackages (so someone can 'openm...
url = self.buildout['buildout']['index']
try: url = self.buildout['buildout']['index'] except KeyError: url = 'http://pypi.python.org/pypi' try: search_path = [self.buildout['buildout']['find-links']] except KeyError: search_path = [] self.logger.info('using URL %s', url) self.logger.info(' and search path %s', search_path)
def install(self): startdir = os.getcwd() if os.path.exists(self.bundledir): self.logger.debug('removing old bundle directory %s' % self.bundledir) shutil.rmtree(self.bundledir) if os.path.exists(self.bundle_cache): shutil.rmtree(self.bundle_cache) os.makedirs(os.path.join(self.bundledir, 'buildout', 'eggs')) os.make...
raise zc.buildout.UserError("Can't contact egg server at '%s': %s" % (url, exc)) index = PackageIndex(url, search_path=[])
msg = "Can't contact egg server at '%s': %s" % (url, exc) raise zc.buildout.UserError(msg) index = PackageIndex(url, search_path=search_path)
def install(self): startdir = os.getcwd() if os.path.exists(self.bundledir): self.logger.debug('removing old bundle directory %s' % self.bundledir) shutil.rmtree(self.bundledir) if os.path.exists(self.bundle_cache): shutil.rmtree(self.bundle_cache) os.makedirs(os.path.join(self.bundledir, 'buildout', 'eggs')) os.make...
url = %(url)s
url = '%(url)s'
def after_install(options, home_dir): global logger reqs = %(reqs)s cmds = %(cmds)s url = %(url)s found = [c for c in cmds if url in c] if not found: cmds.extend(['-f',url]) etc = join(home_dir, 'etc') ## TODO: this should all come from distutils ## like distutils.sysconfig.get_python_inc() if sys.platform == 'win32': ...
if not self.is_valid() or self._num_input_caseiters > 0:
if not self.is_valid():
def _pre_execute (self): """Prepares for execution by calling *tree_rooted()* and *check_config()* if their "dirty" flags are set, and by requesting that the parent Assembly update this Component's invalid inputs. Overrides of this function must call this version. """ if self._call_tree_rooted: self.tree_rooted() if ...
if self.get_pathname() != 'branin_meta_model': print 'execute %s' % self.get_pathname() else: sys.stdout.write('.')
def run (self, force=False): """Run this object. This should include fetching input variables, executing, and updating output variables. Do not override this function. """ if self.directory: self.push_dir()
else: print 'skipping %s' % self.get_pathname()
def run (self, force=False): """Run this object. This should include fetching input variables, executing, and updating output variables. Do not override this function. """ if self.directory: self.push_dir()
if not path or not path.startswith('/OpenMDAO'):
if sys.platform != 'win32' and not path.startswith('/OpenMDAO'): path = '' if not path:
def find_repository(repository, user): """ Return repository's root directory path, or None. """ user_base = os.path.join(os.sep, 'OpenMDAO', 'dev', user) shared_base = os.path.join(os.sep, 'OpenMDAO', 'dev', 'shared') if not repository: path = find_bzr() if not path or not path.startswith('/OpenMDAO'): # Use default ...
print 'find_bzr', path
def find_bzr(path=None): """ Return bzr root directory path, or None. """ if not path: path = os.getcwd() if not os.path.exists(path): return None while path: print 'find_bzr', path if os.path.exists(os.path.join(path, '.bzr')) or \ os.path.exists(os.path.join(path, '.bzrignore')): return os.path.abspath(path) else: pt...
'-H', 'None', '-maqNxd',
'-maqNxd',
def _pre_install(self, distloc): self.logger.info("pre-installing %s" % os.path.basename(distloc)) if distloc.endswith('.egg'): self.logger.debug("unpacking archive %s to %s" % (os.path.join(self.bundle_cache, distloc), os.path.join(self.bundledir,'buildout','eggs', distloc))) setuptools.archive_util.unpack_archive(dis...
os.remove("error.out")
try: os.remove("error.out") except WindowsError: pass
def tearDown(self): for directory in ('a', 'b'): if os.path.exists(directory): shutil.rmtree(directory) if os.path.exists("error.out"): os.remove("error.out") SimulationRoot.chroot(ORIG_DIR)
trait = self.traits().get(name) if not trait: trait = self._instance_traits().get(name)
if self._cached_traits_ is None: self._cached_traits_ = self.traits() self._cached_traits_.update(self._instance_traits()) trait = self._cached_traits_.get(name)
def get_trait ( self, name, copy = False ): """Returns the trait indicated by name, or None if not found. No recursive search is performed if name contains dots. This is a replacement for the trait() method on HasTraits objects, because that method can return traits that shouldn't exist. """ trait = self.traits().get...
result.add_trait(name, copy.copy(trait.trait_type))
result.add_trait(name, _clone_trait(trait))
def __deepcopy__ ( self, memo ): """ Overrides deepcopy for HasTraits because otherwise we lose instance traits when we copy. :( """ id_self = id( self ) if id_self in memo: return memo[ id_self ] result = super(Container, self).__deepcopy__(memo) olditraits = self._instance_traits() newtraits = result._instance_traits...
shutil.rmtree('build')
shutil.rmtree('build', ignore_errors=True)
def _build_sdist(projdir, destdir, version): """Build an sdist out of a develop egg.""" startdir = os.getcwd() try: os.chdir(projdir) # clean up any old builds if os.path.exists('build'): shutil.rmtree('build') _build_dist('sdist', destdir) if os.path.exists('build'): shutil.rmtree('build') if sys.platform == 'win32': ...
self.cnmn1.obj = numarray.array(self.objective.evaluate())
self.cnmn1.obj = self.objective.evaluate()
def execute(self): """Perform the optimization.""" # set conmin array sizes and such self._config_conmin() self.cnmn1.igoto = 0 self.iter_count = 0 # perform an initial run for self-consistency self.run_iteration()
metadata['low'] = low metadata['high'] = high
def __init__(self, default_value=None, iotype=None, desc=None, \ low=None, high=None, exclude_low=False, exclude_high=False, \ units=None, **metadata): # Determine defalt_value if unspecified if default_value is None: if low is None and high is None: default_value = 0.0 elif low is None: default_value = high else: def...
counts = self.parent.exec_counts()
counts = self.parent.exec_counts(srccomps)
def is_valid(self): """Return False if any of our public variables is invalid.""" if self._call_execute: return False if False in self._valid_dict.values(): return False if self.parent is not None: srccomps = [n for n,v in self.get_expr_sources()] if len(srccomps): counts = self.parent.exec_counts() for count,tup in zi...
reqs = ['numpy', 'scipy', 'docutils==0.6', 'Pyevolve==0.6', 'coverage==3.3.1', 'Pygments==1.3.1', 'pycrypto==2.0.1', 'ordereddict==1.1', 'Traits==3.3.0', 'PyYAML==3.09', 'Sphinx==1.0.1', 'Jinja2==2.4', 'virtualenv==1.4.6', 'Fabric==0.9.0', 'decorator==3.2.0', 'networkx==1.0.1', 'pyparsing==1.5.2', 'conmin==1.0.1', 'nos...
reqs = ['numpy', 'scipy', 'docutils==0.6', 'Pyevolve==0.6', 'Pygments==1.3.1', 'pycrypto==2.0.1', 'ordereddict==1.1', 'Traits==3.3.0', 'PyYAML==3.09', 'Jinja2==2.4', 'Sphinx==1.0.4', 'virtualenv==1.4.6', 'Fabric==0.9.0', 'decorator==3.2.0', 'networkx==1.0.1', 'pyparsing==1.5.2', 'conmin==1.0.1', 'nose==0.11.3']
def after_install(options, home_dir): global logger reqs = ['numpy', 'scipy', 'docutils==0.6', 'Pyevolve==0.6', 'coverage==3.3.1', 'Pygments==1.3.1', 'pycrypto==2.0.1', 'ordereddict==1.1', 'Traits==3.3.0', 'PyYAML==3.09', 'Sphinx==1.0.1', 'Jinja2==2.4', 'virtualenv==1.4.6', 'Fabric==0.9.0', 'decorator==3.2.0', 'network...
self.hobj.arr1 = [3.1415926] self.hobj.arr2 = [42.]
self.hobj.arr1 = [1.0, 2.0, 3.0] self.hobj.arr2 = [[1.,2.],[3.,4.]]
def setUp(self): """this setup function will be called before each test in this class""" self.hobj = Component() self.hobj.add_trait('arr1',Array(array([98.9]), iotype='in', units='ft')) self.hobj.add_trait('arr2', Array(array([13.2]), iotype='out', units='inch')) self.hobj.add_trait('arr3', Array(iotype='in', units='k...
self.assertEqual(3.1415926, self.hobj.arr1[0])
def test_set_to_default(self): self.assertEqual(3.1415926, self.hobj.arr1[0]) self.hobj.add_trait('arr4', Array(iotype='in', units='kg')) self.assertTrue(all(array([]) == self.hobj.arr4)) self.hobj.arr4 = [6.5] self.assertEqual(6.5, self.hobj.arr4[0]) self.hobj.revert_to_defaults() self.assertEqual([98.9], self.hobj....