<commit_before>#!/usr/bin/python

import bitvector

import random

generated = bitvector.BitVector()
count = 0
total = 1000000

while (count < total):
	num = random.randint(0,total)
	if not generated.get(num):
		print num
		generated.set(num)
		count += 1
<commit_msg>Refactored to allow passing lower_bound, upper_bound, and total as CLI arguments. Added comments and explanations. Added validation of CLI arguments<commit_after>#!/usr/bin/python

import bitvector
import sys
import random

def echo_unique_random_ints(lower_bound, upper_bound, total):
	"""Generates a list of unique integers in a random order.
	Will generate <total> numbers in the list, between <lower_bound> and <upper_bound>.

	Uses a bitvector to keep track of the numbers we've already generated to ensure uniqueness.
	Can get slower as it progresses if total is close to (upper_bound - lower_bound).
	This is because it is increasingly likely to generate ints that are already in the bitvector
	and have to try again. Need to figure out a different approach that doesn't have this issue.

	"""
	generated = bitvector.BitVector()
	count = 0

	while (count < total):
		num = random.randint(lower_bound,upper_bound)
		if not generated.get(num):
			print num
			generated.set(num)
			count += 1

if __name__ == "__main__":
	if len(sys.argv) != 4:
		print "Please call with the following structure:"
		print "generate_random_ints.py <lower_bound> <upper_bound> <total>"
		exit()

	lower_bound = int(sys.argv[1])
	upper_bound = int(sys.argv[2])
	total = int(sys.argv[3])

	# validation
	if lower_bound >= upper_bound:
		print "lower_bound must be less than upper_bound"
		exit()
	if (upper_bound - lower_bound) < total:
		print "total must be a number less than or equal to upper_bound minus lower_bound"
		exit()

	echo_unique_random_ints(lower_bound, upper_bound, total)<|endoftext|>


<commit_before>import os
import subprocess
import re
import glob
import numpy as np
from astropy.io import fits
from astropy.time import Time
from astropy.table import Table
import desiutil.log
import desisurvey.config
import desisurvey.plan
import desisurvey.tiles
from desisurvey.utils import yesno

logger = desiutil.log.get_logger()

def make_tileid_list(fadir):
    fafiles = glob.glob(os.path.join(fadir, '**/*.fits*'), recursive=True)
    rgx = re.compile(r'.*fiberassign-(\d+)\.fits(\.gz)?')
    existing_tileids = []
    existing_fafiles = []
    for fn in fafiles:
        match = rgx.match(fn)
        if match:
            existing_tileids.append(int(match.group(1)))
            existing_fafiles.append(fn)
    return np.array(existing_tileids), np.array(existing_fafiles)

def tileid_to_clean(faholddir, fadir, mtldone):
    """Identify invalidated fiberassign files for deletion.

    Scans faholddir for fiberassign files.  Compares the MTLTIMES with the times in
    the mtldone file.  If a fiberassign file was designed before an overlapping
    tile which later had MTL updates, that fiberassign file is "invalid" and
    should be deleted.

    Parameters
    ----------
    faholddir : str
        directory name of fiberassign holding pen
    fadir : str
        directory name of svn-controlled fiber assign directory.
    mtldone : array
        numpy array of finished tile MTL updates.  Must contain at least
        TIMESTAMP and TILEID fields.
    """
    import dateutil.parser
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    existing = tiles.tileID[plan.tile_status != 'unobs']
    m = (plan.tile_status == 'unobs') & (plan.tile_priority <= 0)
    existing_tileids, existing_fafiles = make_tileid_list(faholddir)
    intiles = np.isin(existing_tileids, tiles.tileID)
    existing_tileids = existing_tileids[intiles]
    existing_fafiles = existing_fafiles[intiles]
    existing = existing[np.isin(existing, existing_tileids)]
    logger.info('Reading in MTLTIME header from %d fiberassign files...' %
                len(existing_fafiles))
    mtltime = [fits.getheader(fn).get('MTLTIME', 'None')
               for fn in existing_fafiles]
    m = np.array([mtltime0 is not None for mtltime0 in mtltime])
    if np.any(~m):
        logger.warning('MTLTIME not found for tiles {}!'.format(
            ' '.join([x for x in existing_fafiles[~m]])))
    existing_tileids = existing_tileids[m]
    existing_fafiles = existing_fafiles[m]
    mtltime = np.array(mtltime)[m]
    mtltime = Time([dateutil.parser.parse(mtltime0)
                    for mtltime0 in mtltime]).mjd
    # we have the mtl times for all existing fa files.
    # we want the largest MTL time of any overlapping tile which has
    # status != 'unobs'
    tilemtltime = np.zeros(tiles.ntiles, dtype='f8') - 1
    index, mask = tiles.index(existing_tileids, return_mask=True)
    if np.sum(~mask) > 0:
        logger.info('Ignoring {} TILEID not in the tile file'.format(
            np.sum(~mask)))
    index = index[mask]
    existing_tileids = existing_tileids[mask]
    mtltime = mtltime[mask]
    tilemtltime[index] = mtltime
    # this has the MTL design time of all of the tiles.
    # we also need the MTL done time of all the tiles.
    index, mask = tiles.index(mtldone['TILEID'], return_mask=True)
    mtldonetime = [dateutil.parser.parse(mtltime0)
                   for mtltime0 in mtldone['TIMESTAMP']]
    mtldonetime = Time(mtldonetime).mjd
    tilemtldonetime = np.zeros(tiles.ntiles, dtype='f8')
    tilemtldonetime[index[mask]] = mtldonetime[mask]
    maxoverlappingtilemtldonetime = np.zeros(tiles.ntiles, dtype='f8')
    for i, neighbors in enumerate(tiles.overlapping):
        if len(neighbors) == 0:
            continue
        maxoverlappingtilemtldonetime[i] = np.max(tilemtldonetime[neighbors])
    expired = ((maxoverlappingtilemtldonetime > tilemtltime)
               & (plan.tile_status == 'unobs') & (tilemtltime > -1))
    for tileid in existing:
        tileidpadstr = '%06d' % tileid
        fafn = os.path.join(fadir, tileidpadstr[:3],
                            'fiberassign-%s.fits.gz' % tileidpadstr)
        if not os.path.exists(fafn):
            logger.error('Tile {} is not unobs, '.format(fafn) +
                         'but does not exist in SVN?!')
    return tiles.tileID[expired]

def remove_tiles_from_dir(dirname, tileid):
    for tileid0 in tileid:
        for ext in ['fits.gz', 'png', 'log']:
            expidstr= '{:06d}'.format(tileid0)
            os.remove(os.path.join(
                dirname, expidstr[:3],
                'fiberassign-{}.{}'.format(expidstr, ext)))

def missing_tileid(fadir, faholddir):
    """Return missing TILEID and superfluous TILEID.

    The fiberassign holding pen should include all TILEID
    for available, unobserved tiles.  It should include no TILEID
    for unavailable or observed tiles.  This function computes the list
    of TILEID that should exist, but do not, as well as the list of TILEID
    that should not exist, but do.

    Parameters
    ----------
    fadir : str
        directory name of fiberassign directory
    faholddir : str
        directory name of fiberassign holding pen

    Returns
    -------
    missingtiles, extratiles
    missingtiles : array
        array of TILEID for tiles that do not exist, but should.
        These need to be designed and added to the holding pen.
    extratiles : array
        array of TILEID for tiles that exist, but should not.
        These need to be deleted from the holding pen.
    """
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    tileid, fafn = make_tileid_list(faholddir)
    shouldexist = tiles.tileID[(plan.tile_status == 'unobs') &
                               (plan.tile_priority > 0)]
    missingtiles = set(shouldexist) - set(tileid)
    shouldnotexist = tiles.tileID[(plan.tile_status != 'unobs') |
                                  (plan.tile_priority <= 0)]
    doesexist = np.isin(tileid, shouldnotexist)
    count = 0
    for tileid0 in tileid[doesexist]:
        expidstr = '{:06d}'.format(tileid0)
        if not os.path.exists(os.path.join(
                fadir, expidstr[:3],
                'fiberassign-{}.fits.gz'.format(expidstr))):
            logger.error('TILEID %d should be checked into and is not!' %
                         tileid0)
        else:
            count += 1
    if count > 0:
        logger.info('Confirmed %d files in SVN also in holding pen.' %
                    count)
        logger.info('TILEID: ' + ' '.join(
            [str(x) for x in np.sort(tileid[doesexist])]))
    return (np.sort(np.array([x for x in missingtiles])),
            np.sort(tileid[doesexist]))

def maintain_svn(svn, untrackedonly=True, verbose=False):
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    fnames = []
    if untrackedonly:
        res = subprocess.run(['svn', 'status', svn], capture_output=True)
        output = res.stdout.decode('utf8')
        for line in output.split('\n'):
            if len(line) == 0:
                continue
            modtype = line[0]
            if modtype != '?':
                print('unrecognized line: "{}", ignoring.'.format(line))
                continue
            # new file.  We need to check it in or delete it.
            fname = line[8:]
            fnames.append(fname)
    else:
        import glob
        fnames = glob.glob(os.path.join(svn, '**/*'), recursive=True)
    rgx = re.compile(svn + '/' +
                     r'\d\d\d/fiberassign-(\d+)\.(fits|fits\.gz|png|log)')
    todelete = []
    tocommit = []
    mintileid = np.min(tiles.tileID)
    maxtileid = np.max(tiles.tileID)
    for fname in fnames:
        match = rgx.match(fname)
        if not match:
            if verbose:
                logger.warn('unrecognized filename: "{}", ignoring.'.format(fname))
            continue
        tileid = int(match.group(1))
        idx, mask = tiles.index(tileid, return_mask=True)
        if not mask:
            if verbose and (tileid >= mintileid) and (tileid <= maxtileid):
                logger.warn('unrecognized TILEID {}, ignoring.'.format(tileid))
            continue
        if plan.tile_status[idx] == 'unobs':
            todelete.append(fname)
        else:
            tocommit.append(fname)
    if not untrackedonly:
        tocommit = []
    return todelete, tocommit

def execute_svn_maintenance(todelete, tocommit, echo=False, svnrm=False):
    if echo:
        cmd = ['echo', 'svn']
    else:
        cmd = ['svn']
    for fname in todelete:
        if svnrm:
            subprocess.run(cmd + ['rm', fname])
        else:
            if not echo:
                os.remove(fname)
            else:
                print('removing ', fname)
    for fname in tocommit:
        subprocess.run(cmd + ['add', fname])

def maintain_holding_pen_and_svn(fbadir, faholddir, mtldonefn):
    todelete, tocommit = maintain_svn(fbadir)
    if len(todelete) + len(tocommit) > 0:
        logger.info(('To delete from %s: ' % fbadir) +
                    ' '.join([os.path.basename(x) for x in todelete]))
        logger.info(('To commit to %s: ' % fbadir) +
                    ' '.join([os.path.basename(x) for x in tocommit]))
        qstr = ('Preparing to perform svn fiberassign maintenance, '
                'deleting {} and committing {} files.  Continue?'.format(
                    len(todelete), len(tocommit)))
        okay = yesno(qstr)
        if okay:
            execute_svn_maintenance(todelete, tocommit, echo=True)
            okay = yesno('The following commands will be executed.  '
                         'Still okay?')
            if okay:
                execute_svn_maintenance(todelete, tocommit)
    if mtldonefn is not None:
        invalid = tileid_to_clean(faholddir, fbadir, Table.read(mtldonefn))
    if len(invalid) > 0:
        okay = yesno(('Deleting %d out-of-date fiberassign files from holding '
                      'pen .  Continue?').format(len(toclean)))
        if okay:
            remove_tiles_from_dir(faholddir, toclean)
    missing, extra = missing_tileid(fbadir, faholddir)
    if len(extra) > 0:
        okay = yesno(('Deleting %d fiberassign files in SVN from the '
                      'holding pen.  Continue?') % len(extra))
        if okay:
            remove_tiles_from_dir(faholddir, extra)
    if len(missing) < 100:
        logger.info('Need to design the following tiles here! ' +
                    ' '.join([str(x) for x in missing]))
    else:
        logger.info('Need to design many (%d) tiles here!' % len(missing))
<commit_msg>Fix typos in holding pen maintenance.<commit_after>import os
import subprocess
import re
import glob
import numpy as np
from astropy.io import fits
from astropy.time import Time
from astropy.table import Table
import desiutil.log
import desisurvey.config
import desisurvey.plan
import desisurvey.tiles
from desisurvey.utils import yesno

logger = desiutil.log.get_logger()

def make_tileid_list(fadir):
    fafiles = glob.glob(os.path.join(fadir, '**/*.fits*'), recursive=True)
    rgx = re.compile(r'.*fiberassign-(\d+)\.fits(\.gz)?')
    existing_tileids = []
    existing_fafiles = []
    for fn in fafiles:
        match = rgx.match(fn)
        if match:
            existing_tileids.append(int(match.group(1)))
            existing_fafiles.append(fn)
    return np.array(existing_tileids), np.array(existing_fafiles)

def tileid_to_clean(faholddir, fadir, mtldone):
    """Identify invalidated fiberassign files for deletion.

    Scans faholddir for fiberassign files.  Compares the MTLTIMES with the times in
    the mtldone file.  If a fiberassign file was designed before an overlapping
    tile which later had MTL updates, that fiberassign file is "invalid" and
    should be deleted.

    Parameters
    ----------
    faholddir : str
        directory name of fiberassign holding pen
    fadir : str
        directory name of svn-controlled fiber assign directory.
    mtldone : array
        numpy array of finished tile MTL updates.  Must contain at least
        TIMESTAMP and TILEID fields.
    """
    import dateutil.parser
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    existing = tiles.tileID[plan.tile_status != 'unobs']
    m = (plan.tile_status == 'unobs') & (plan.tile_priority <= 0)
    existing_tileids, existing_fafiles = make_tileid_list(faholddir)
    intiles = np.isin(existing_tileids, tiles.tileID)
    existing_tileids = existing_tileids[intiles]
    existing_fafiles = existing_fafiles[intiles]
    existing = existing[np.isin(existing, existing_tileids)]
    logger.info('Reading in MTLTIME header from %d fiberassign files...' %
                len(existing_fafiles))
    mtltime = [fits.getheader(fn).get('MTLTIME', 'None')
               for fn in existing_fafiles]
    m = np.array([mtltime0 is not None for mtltime0 in mtltime])
    if np.any(~m):
        logger.warning('MTLTIME not found for tiles {}!'.format(
            ' '.join([x for x in existing_fafiles[~m]])))
    existing_tileids = existing_tileids[m]
    existing_fafiles = existing_fafiles[m]
    mtltime = np.array(mtltime)[m]
    mtltime = Time([dateutil.parser.parse(mtltime0)
                    for mtltime0 in mtltime]).mjd
    # we have the mtl times for all existing fa files.
    # we want the largest MTL time of any overlapping tile which has
    # status != 'unobs'
    tilemtltime = np.zeros(tiles.ntiles, dtype='f8') - 1
    index, mask = tiles.index(existing_tileids, return_mask=True)
    if np.sum(~mask) > 0:
        logger.info('Ignoring {} TILEID not in the tile file'.format(
            np.sum(~mask)))
    index = index[mask]
    existing_tileids = existing_tileids[mask]
    mtltime = mtltime[mask]
    tilemtltime[index] = mtltime
    # this has the MTL design time of all of the tiles.
    # we also need the MTL done time of all the tiles.
    index, mask = tiles.index(mtldone['TILEID'], return_mask=True)
    mtldonetime = [dateutil.parser.parse(mtltime0)
                   for mtltime0 in mtldone['TIMESTAMP']]
    mtldonetime = Time(mtldonetime).mjd
    tilemtldonetime = np.zeros(tiles.ntiles, dtype='f8')
    tilemtldonetime[index[mask]] = mtldonetime[mask]
    maxoverlappingtilemtldonetime = np.zeros(tiles.ntiles, dtype='f8')
    for i, neighbors in enumerate(tiles.overlapping):
        if len(neighbors) == 0:
            continue
        maxoverlappingtilemtldonetime[i] = np.max(tilemtldonetime[neighbors])
    expired = ((maxoverlappingtilemtldonetime > tilemtltime)
               & (plan.tile_status == 'unobs') & (tilemtltime > -1))
    for tileid in existing:
        tileidpadstr = '%06d' % tileid
        fafn = os.path.join(fadir, tileidpadstr[:3],
                            'fiberassign-%s.fits.gz' % tileidpadstr)
        if not os.path.exists(fafn):
            logger.error('Tile {} is not unobs, '.format(fafn) +
                         'but does not exist in SVN?!')
    return tiles.tileID[expired]

def remove_tiles_from_dir(dirname, tileid):
    for tileid0 in tileid:
        for ext in ['fits.gz', 'png', 'log']:
            expidstr= '{:06d}'.format(tileid0)
            os.remove(os.path.join(
                dirname, expidstr[:3],
                'fiberassign-{}.{}'.format(expidstr, ext)))

def missing_tileid(fadir, faholddir):
    """Return missing TILEID and superfluous TILEID.

    The fiberassign holding pen should include all TILEID
    for available, unobserved tiles.  It should include no TILEID
    for unavailable or observed tiles.  This function computes the list
    of TILEID that should exist, but do not, as well as the list of TILEID
    that should not exist, but do.

    Parameters
    ----------
    fadir : str
        directory name of fiberassign directory
    faholddir : str
        directory name of fiberassign holding pen

    Returns
    -------
    missingtiles, extratiles
    missingtiles : array
        array of TILEID for tiles that do not exist, but should.
        These need to be designed and added to the holding pen.
    extratiles : array
        array of TILEID for tiles that exist, but should not.
        These need to be deleted from the holding pen.
    """
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    tileid, fafn = make_tileid_list(faholddir)
    shouldexist = tiles.tileID[(plan.tile_status == 'unobs') &
                               (plan.tile_priority > 0)]
    missingtiles = set(shouldexist) - set(tileid)
    shouldnotexist = tiles.tileID[(plan.tile_status != 'unobs') |
                                  (plan.tile_priority <= 0)]
    doesexist = np.isin(tileid, shouldnotexist)
    count = 0
    for tileid0 in tileid[doesexist]:
        expidstr = '{:06d}'.format(tileid0)
        if not os.path.exists(os.path.join(
                fadir, expidstr[:3],
                'fiberassign-{}.fits.gz'.format(expidstr))):
            logger.error('TILEID %d should be checked into and is not!' %
                         tileid0)
        else:
            count += 1
    if count > 0:
        logger.info('Confirmed %d files in SVN also in holding pen.' %
                    count)
        logger.info('TILEID: ' + ' '.join(
            [str(x) for x in np.sort(tileid[doesexist])]))
    return (np.sort(np.array([x for x in missingtiles])),
            np.sort(tileid[doesexist]))

def maintain_svn(svn, untrackedonly=True, verbose=False):
    cfg = desisurvey.config.Configuration()
    tiles = desisurvey.tiles.get_tiles()
    plan = desisurvey.plan.Planner(restore=cfg.tiles_file())
    fnames = []
    if untrackedonly:
        res = subprocess.run(['svn', 'status', svn], capture_output=True)
        output = res.stdout.decode('utf8')
        for line in output.split('\n'):
            if len(line) == 0:
                continue
            modtype = line[0]
            if modtype != '?':
                print('unrecognized line: "{}", ignoring.'.format(line))
                continue
            # new file.  We need to check it in or delete it.
            fname = line[8:]
            fnames.append(fname)
    else:
        import glob
        fnames = glob.glob(os.path.join(svn, '**/*'), recursive=True)
    rgx = re.compile(svn + '/' +
                     r'\d\d\d/fiberassign-(\d+)\.(fits|fits\.gz|png|log)')
    todelete = []
    tocommit = []
    mintileid = np.min(tiles.tileID)
    maxtileid = np.max(tiles.tileID)
    for fname in fnames:
        match = rgx.match(fname)
        if not match:
            if verbose:
                logger.warn('unrecognized filename: "{}", ignoring.'.format(fname))
            continue
        tileid = int(match.group(1))
        idx, mask = tiles.index(tileid, return_mask=True)
        if not mask:
            if verbose and (tileid >= mintileid) and (tileid <= maxtileid):
                logger.warn('unrecognized TILEID {}, ignoring.'.format(tileid))
            continue
        if plan.tile_status[idx] == 'unobs':
            todelete.append(fname)
        else:
            tocommit.append(fname)
    if not untrackedonly:
        tocommit = []
    return todelete, tocommit

def execute_svn_maintenance(todelete, tocommit, echo=False, svnrm=False):
    if echo:
        cmd = ['echo', 'svn']
    else:
        cmd = ['svn']
    for fname in todelete:
        if svnrm:
            subprocess.run(cmd + ['rm', fname])
        else:
            if not echo:
                os.remove(fname)
            else:
                print('removing ', fname)
    for fname in tocommit:
        subprocess.run(cmd + ['add', fname])

def maintain_holding_pen_and_svn(fbadir, faholddir, mtldonefn):
    todelete, tocommit = maintain_svn(fbadir)
    if len(todelete) + len(tocommit) > 0:
        logger.info(('To delete from %s: ' % fbadir) +
                    ' '.join([os.path.basename(x) for x in todelete]))
        logger.info(('To commit to %s: ' % fbadir) +
                    ' '.join([os.path.basename(x) for x in tocommit]))
        qstr = ('Preparing to perform svn fiberassign maintenance, '
                'deleting {} and committing {} files.  Continue?'.format(
                    len(todelete), len(tocommit)))
        okay = yesno(qstr)
        if okay:
            execute_svn_maintenance(todelete, tocommit, echo=True)
            okay = yesno('The following commands will be executed.  '
                         'Still okay?')
            if okay:
                execute_svn_maintenance(todelete, tocommit)
            okay = yesno('Commit to svn?')
            if okay:
                subprocess.run('svn', 'ci', fbadir,
                               '-m "Adding newly observed tiles."')
    if mtldonefn is not None:
        invalid = tileid_to_clean(faholddir, fbadir, Table.read(mtldonefn))
    if len(invalid) > 0:
        okay = yesno(('Deleting %d out-of-date fiberassign files from ' +
                      'holding pen .  Continue?').format(len(invalid)))
        if okay:
            remove_tiles_from_dir(faholddir, invalid)
    missing, extra = missing_tileid(fbadir, faholddir)
    if len(extra) > 0:
        okay = yesno(('Deleting %d fiberassign files in SVN from the '
                      'holding pen.  Continue?') % len(extra))
        if okay:
            remove_tiles_from_dir(faholddir, extra)
    if len(missing) < 100:
        logger.info('Need to design the following tiles here! ' +
                    ' '.join([str(x) for x in missing]))
    else:
        logger.info('Need to design many (%d) tiles here!' % len(missing))
<|endoftext|>


<commit_before>from TestStack.White.UIItems.MenuItems import Menu
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword

class MenuKeywords(LibraryComponent):
    @keyword
    def verify_menu(self, locator, expected):
        """Verifies the text of a menu item.

        ``locator`` is the locator of the menu item.

        ``expected`` is the expected text of the menu item.
        """
        menu = self.state._get_typed_item_by_locator(Menu, locator)
        self.state._verify_value(expected, menu.Name)

    @keyword
    def click_menu_button(self, locator):
        """Clicks a menu button.

        ``locator`` is the locator of the menu button.
        """
        menu_button = self.state._get_typed_item_by_locator(Menu, locator)
        menu_button.Click()

    @keyword
    def click_popup_menu_item(self, *text_path):
        """Clicks an item in the currently open popup/context menu.

        ``text_path`` is the path to the item to click.

        Examples:
        | Click Popup Menu Item | Paste | | # click an item in the root level |
        | Click Popup Menu Item | Refactor | Rename | # click a sub item |
        """
        popup_menu = self.state.window.Popup
        popup_menu.Item(list(text_path)).Click()
<commit_msg>Rename popup menu keyword<commit_after>from TestStack.White.UIItems.MenuItems import Menu
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword

class MenuKeywords(LibraryComponent):
    @keyword
    def verify_menu(self, locator, expected):
        """Verifies the text of a menu item.

        ``locator`` is the locator of the menu item.

        ``expected`` is the expected text of the menu item.
        """
        menu = self.state._get_typed_item_by_locator(Menu, locator)
        self.state._verify_value(expected, menu.Name)

    @keyword
    def click_menu_button(self, locator):
        """Clicks a menu button.

        ``locator`` is the locator of the menu button.
        """
        menu_button = self.state._get_typed_item_by_locator(Menu, locator)
        menu_button.Click()

    @keyword
    def click_item_in_popup_menu(self, *text_path):
        """Clicks an item in the currently open popup/context menu.

        ``text_path`` is the path to the item to click.

        Examples:
        | Click Popup Menu Item | Paste | | # click an item in the root level |
        | Click Popup Menu Item | Refactor | Rename | # click a sub item |
        """
        popup_menu = self.state.window.Popup
        popup_menu.Item(list(text_path)).Click()
<|endoftext|>


<commit_before>from django.db import models
from datetime import datetime
from markdownx.models import MarkdownxField
from django.utils import timezone

# Track model
class Track(models.Model):
    title = models.CharField(max_length=50)
    icon = models.CharField(max_length=100)
    short_description = models.TextField()
    subtitle = models.TextField()
    hero_image= models.CharField(max_length=200)
    long_description = MarkdownxField()

# Region model
class Region(models.Model):
    name = models.CharField(max_length=30)
    thumbnail_image = models.CharField(max_length=200)
    hero_image = models.CharField(max_length=200)
    motto = models.TextField()
    description = models.TextField()

    def __str__(self):
        return self.name

# Member model
class Member(models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30)
    photo = models.CharField(max_length=200)
    personal_page = models.CharField(max_length=200)
    region = models.ForeignKey(Region)

    def __str__(self):
        return self.name +' '+ self.surname

# Event model
class Event(models.Model):
	title = models.CharField(max_length=50)
	short_description = models.TextField()
	start_date = models.DateTimeField()
	end_date = models.DateTimeField(null =True, blank=True)
	thumbnail_image = models.CharField(max_length=200)
	hero_image = models.CharField(max_length=200)
	aplly_form = models.CharField(max_length=200)
	long_description = MarkdownxField()
	application_start_date = models.DateTimeField(null=True, blank=True)
	application_end_date = models.DateTimeField(null=True, blank=True)
	region = models.ForeignKey(Region, null=True, blank=True)

# Story model
class Story(models.Model):
    title = models.CharField(max_length=100)
    short_description = models.TextField()
    create_date = models.DateTimeField(default=timezone.now)
    thumbnail_image = models.CharField(max_length=200)
    subtitle = models.CharField(max_length=200)
    long_description = MarkdownxField()
    region = models.ForeignKey(Region, blank=True, null=True)
<commit_msg>add a difinition str<commit_after>from django.db import models
from datetime import datetime
from markdownx.models import MarkdownxField
from django.utils import timezone

# Track model
class Track(models.Model):
    title = models.CharField(max_length=50)
    icon = models.CharField(max_length=100)
    short_description = models.TextField()
    subtitle = models.TextField()
    hero_image= models.CharField(max_length=200)
    long_description = MarkdownxField()

    def __str__(self):
        return self.title

# Region model
class Region(models.Model):
    name = models.CharField(max_length=30)
    thumbnail_image = models.CharField(max_length=200)
    hero_image = models.CharField(max_length=200)
    motto = models.TextField()
    description = models.TextField()

    def __str__(self):
        return self.name

# Member model
class Member(models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30)
    photo = models.CharField(max_length=200)
    personal_page = models.CharField(max_length=200)
    region = models.ForeignKey(Region)

    def __str__(self):
        return self.name +' '+ self.surname

# Event model
class Event(models.Model):
	title = models.CharField(max_length=50)
	short_description = models.TextField()
	start_date = models.DateTimeField()
	end_date = models.DateTimeField(null =True, blank=True)
	thumbnail_image = models.CharField(max_length=200)
	hero_image = models.CharField(max_length=200)
	aplly_form = models.CharField(max_length=200)
	long_description = MarkdownxField()
	application_start_date = models.DateTimeField(null=True, blank=True)
	application_end_date = models.DateTimeField(null=True, blank=True)
	region = models.ForeignKey(Region, null=True, blank=True)

# Story model
class Story(models.Model):
    title = models.CharField(max_length=100)
    short_description = models.TextField()
    create_date = models.DateTimeField(default=timezone.now)
    thumbnail_image = models.CharField(max_length=200)
    subtitle = models.CharField(max_length=200)
    long_description = MarkdownxField()
    region = models.ForeignKey(Region, blank=True, null=True)
<|endoftext|>


<commit_before>import mdtraj
import numpy as np
import pandas as pd
import cStringIO
import simtk.openmm.app.element
import simtk.unit as unit
import itertools

import logging
logger = logging.getLogger(__name__)

gaff_elements = {'br': 'Br',
 'c': 'C',
 'c1': 'C',
 'c2': 'C',
 'c3': 'C',
 'ca': 'C',
 'cc': 'C',
 'cd': 'C',
 'ce': 'C',
 'cf': 'C',
 'cg': 'C',
 'ch': 'C',
 'cl': 'Cl',
 'cp': 'C',
 'cq': 'C',
 'cu': 'C',
 'cv': 'C',
 'cx': 'C',
 'cy': 'C',
 'cz': 'C',
 'f': 'F',
 'h1': 'H',
 'h2': 'H',
 'h3': 'H',
 'h4': 'H',
 'h5': 'H',
 'ha': 'H',
 'hc': 'H',
 'hn': 'H',
 'ho': 'H',
 'hp': 'H',
 'hs': 'H',
 'hw': 'H',
 'hx': 'H',
 'i': 'I',
 'n': 'N',
 'n1': 'N',
 'n2': 'N',
 'n3': 'N',
 'n4': 'N',
 'na': 'N',
 'nb': 'N',
 'nc': 'N',
 'nd': 'N',
 'ne': 'N',
 'nf': 'N',
 'nh': 'N',
 'no': 'N',
 'o': 'O',
 'oh': 'O',
 'os': 'O',
 'ow': 'O',
 'p2': 'P',
 'p3': 'P',
 'p4': 'P',
 'p5': 'P',
 'pb': 'P',
 'px': 'P',
 'py': 'P',
 's': 'S',
 's2': 'S',
 's4': 'S',
 's6': 'S',
 'sh': 'S',
 'ss': 'S',
 'sx': 'S',
 'sy': 'S'}

def parse_mol2_sections(x):
    if x.startswith('@<TRIPOS>'):
        parse_mol2_sections.key = x
    return parse_mol2_sections.key

def mol2_to_dataframes(filename):
    """Convert a GAFF mol2 file to a pair of pandas dataframes."""
    with open(filename) as f:
        data = dict((key, list(grp)) for key, grp in itertools.groupby(f, parse_mol2_sections))

    csv = cStringIO.StringIO()
    csv.writelines(data["@<TRIPOS>BOND\n"][1:])
    csv.reset()
    bonds_frame = pd.read_table(csv, delim_whitespace=True, names=["bond_id", "id0","id1", "bond_type"], index_col=0, header=None, sep="\s*",)

    csv = cStringIO.StringIO()
    csv.writelines(data["@<TRIPOS>ATOM\n"][1:])
    csv.reset()
    atoms_frame = pd.read_csv(csv, delim_whitespace=True, names=["serial", "name", "x", "y" ,"z", "atype", "code", "resName", "charge"], header=None, usecols=range(1, 10))

    return atoms_frame, bonds_frame

class Mol2Parser(object):
    def __init__(self, filename):
        self.atoms, self.bonds = mol2_to_dataframes(filename)

    def to_mdtraj(self):
        atoms, bonds = self.atoms, self.bonds
        atoms_mdtraj = atoms[["name", "resName"]]
        atoms_mdtraj["serial"] = atoms.index
        atoms_mdtraj["element"] = atoms.atype.map(gaff_elements)
        atoms_mdtraj["resSeq"] = np.ones(len(atoms))
        atoms_mdtraj["chainID"] = np.ones(len(atoms))

        bonds_mdtraj = bonds[["id0", "id1"]].values
        offset = bonds_mdtraj.min()
        bonds_mdtraj -= offset

        top = mdtraj.Topology.from_dataframe(atoms_mdtraj, bonds_mdtraj)
        xyzlist = np.array([atoms[["x","y","z"]].values])
        xyzlist /= 10.0  # Convert from angstrom to nanometer
        traj = mdtraj.Trajectory(xyzlist, top)
        return traj

    def to_openmm(self):
        traj = self.to_mdtraj()
        top_mm = traj.top.to_openmm()
        xyz_mm = traj.xyz[0].tolist()

        return top_mm, xyz_mm

<commit_msg>pyflakes, pep8, and docstrings for gafftools.py<commit_after>import mdtraj
import numpy as np
import pandas as pd
import cStringIO
import itertools

import logging
logger = logging.getLogger(__name__)

gaff_elements = {
    'br': 'Br',
    'c': 'C',
    'c1': 'C',
    'c2': 'C',
    'c3': 'C',
    'ca': 'C',
    'cc': 'C',
    'cd': 'C',
    'ce': 'C',
    'cf': 'C',
    'cg': 'C',
    'ch': 'C',
    'cl': 'Cl',
    'cp': 'C',
    'cq': 'C',
    'cu': 'C',
    'cv': 'C',
    'cx': 'C',
    'cy': 'C',
    'cz': 'C',
    'f': 'F',
    'h1': 'H',
    'h2': 'H',
    'h3': 'H',
    'h4': 'H',
    'h5': 'H',
    'ha': 'H',
    'hc': 'H',
    'hn': 'H',
    'ho': 'H',
    'hp': 'H',
    'hs': 'H',
    'hw': 'H',
    'hx': 'H',
    'i': 'I',
    'n': 'N',
    'n1': 'N',
    'n2': 'N',
    'n3': 'N',
    'n4': 'N',
    'na': 'N',
    'nb': 'N',
    'nc': 'N',
    'nd': 'N',
    'ne': 'N',
    'nf': 'N',
    'nh': 'N',
    'no': 'N',
    'o': 'O',
    'oh': 'O',
    'os': 'O',
    'ow': 'O',
    'p2': 'P',
    'p3': 'P',
    'p4': 'P',
    'p5': 'P',
    'pb': 'P',
    'px': 'P',
    'py': 'P',
    's': 'S',
    's2': 'S',
    's4': 'S',
    's6': 'S',
    'sh': 'S',
    'ss': 'S',
    'sx': 'S',
    'sy': 'S'}

def parse_mol2_sections(x):
    """Helper function for parsing a section in a MOL2 file."""
    if x.startswith('@<TRIPOS>'):
        parse_mol2_sections.key = x
    return parse_mol2_sections.key

def mol2_to_dataframes(filename):
    """Convert a GAFF mol2 file to a pair of pandas dataframes.

    Parameters
    ----------
    filename : str
        Name of mol2 filename

    Returns
    -------
    atoms_frame : pd.DataFrame
        DataFrame containing atom information
    bonds_frame : pd.DataFrame
        DataFrame containing bond information
    """
    with open(filename) as f:
        data = dict((key, list(grp)) for key, grp in itertools.groupby(f, parse_mol2_sections))

    csv = cStringIO.StringIO()
    csv.writelines(data["@<TRIPOS>BOND\n"][1:])
    csv.reset()
    bonds_frame = pd.read_table(csv, delim_whitespace=True, names=["bond_id", "id0", "id1", "bond_type"], index_col=0, header=None, sep="\s*")

    csv = cStringIO.StringIO()
    csv.writelines(data["@<TRIPOS>ATOM\n"][1:])
    csv.reset()
    atoms_frame = pd.read_csv(csv, delim_whitespace=True, names=["serial", "name", "x", "y", "z", "atype", "code", "resName", "charge"], header=None, usecols=range(1, 10))

    return atoms_frame, bonds_frame

class Mol2Parser(object):
    def __init__(self, filename):
        """Create Mol2Parser object containing parsed Mol2 data.

        Parameters
        ----------
        filename : str
            Name of mol2 filename

        """
        self.atoms, self.bonds = mol2_to_dataframes(filename)

    def to_mdtraj(self):
        """Return parsed Mol2 as a MDTraj trajectory

        Returns
        -------
        traj : MDTraj.Trajectory
            Trajectory containing Mol2 data in first frame
        """
        atoms, bonds = self.atoms, self.bonds
        atoms_mdtraj = atoms[["name", "resName"]]
        atoms_mdtraj["serial"] = atoms.index
        atoms_mdtraj["element"] = atoms.atype.map(gaff_elements)
        atoms_mdtraj["resSeq"] = np.ones(len(atoms))
        atoms_mdtraj["chainID"] = np.ones(len(atoms))

        bonds_mdtraj = bonds[["id0", "id1"]].values
        offset = bonds_mdtraj.min()
        bonds_mdtraj -= offset

        top = mdtraj.Topology.from_dataframe(atoms_mdtraj, bonds_mdtraj)
        xyzlist = np.array([atoms[["x", "y", "z"]].values])
        xyzlist /= 10.0  # Convert from angstrom to nanometer
        traj = mdtraj.Trajectory(xyzlist, top)
        return traj

    def to_openmm(self):
        """Return parsed Mol2 in OpenMM format

        Returns
        -------
        top_mm : simtk.openmm.app.Topology
            Topology representing Mol2 object
        xyz_mm : list
            List of xyz coordinates of atoms [nanometers]
        """
        traj = self.to_mdtraj()
        top_mm = traj.top.to_openmm()
        xyz_mm = traj.xyz[0].tolist()

        return top_mm, xyz_mm
<|endoftext|>


<commit_before>from django.contrib import admin
from gallery.models import Gallery, Picture

class GalleryAdmin(admin.ModelAdmin):
	list_display = ('name', 'slug', 'order', 'picture_count', 'parent_gallery',
        'date_created', 'date_modified', 'published')
	list_filter = ('date_created', 'date_modified')
	search_fields = ('name', 'slug', 'parent_gallery')
	prepopulated_fields = {'slug': ('name',)}

class PictureAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'gallery', 'order',
        'date_created', 'date_modified')
    search_fields = ('name', 'original', 'gallery')
    list_filter = ('gallery', 'date_created', 'date_modified')
    fields = ('name', 'slug', 'description', 'original', 'gallery', 'order')
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Gallery, GalleryAdmin)
admin.site.register(Picture, PictureAdmin)
<commit_msg>Fixes error searching in admin for pictures or galleries.<commit_after>from django.contrib import admin
from gallery.models import Gallery, Picture

class GalleryAdmin(admin.ModelAdmin):
	list_display = ('name', 'slug', 'order', 'picture_count', 'parent_gallery',
        'date_created', 'date_modified', 'published')
	list_filter = ('date_created', 'date_modified')
	search_fields = ('name', 'slug', 'parent_gallery__name')
	prepopulated_fields = {'slug': ('name',)}

class PictureAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'gallery', 'order',
        'date_created', 'date_modified')
    search_fields = ('name', 'original', 'gallery__name')
    list_filter = ('gallery', 'date_created', 'date_modified')
    fields = ('name', 'slug', 'description', 'original', 'gallery', 'order')
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Gallery, GalleryAdmin)
admin.site.register(Picture, PictureAdmin)
<|endoftext|>


<commit_before>"""Test suite for phlurl_watcher."""
# =============================================================================
#                                   TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
# cover those concerns.
#
# Concerns:
# [ A] can dump and load again from empty watcher
# [ A] can dump and load again from watcher with one element
# -----------------------------------------------------------------------------
# Tests:
# [ A] test_A_Breathing
# =============================================================================

from __future__ import absolute_import

import random
import unittest

import phlsys_fs

import phlurl_watcher

class Test(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_A_Breathing(self):

        def request_func(url):
            return str(random.randint(0, 8 * 8 * 8 * 8)) + url

        watcher = phlurl_watcher.Watcher(request_func)

        with phlsys_fs.chtmpdir_context():

            with open('data', 'w') as f:
                watcher.dump(f)
            with open('data') as f:
                watcher.load(f)

            url = 'http://z.com'

            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

            with open('data', 'w') as f:
                watcher.dump(f)
            with open('data') as f:
                watcher.load(f)

            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ------------------------------ END-OF-FILE ----------------------------------
<commit_msg>Arcyd: fix phlurl_watcher__t flakiness<commit_after>"""Test suite for phlurl_watcher."""
# =============================================================================
#                                   TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
# cover those concerns.
#
# Concerns:
# [ A] can dump and load again from empty watcher
# [ A] can dump and load again from watcher with one element
# -----------------------------------------------------------------------------
# Tests:
# [ A] test_A_Breathing
# =============================================================================

from __future__ import absolute_import

import unittest

import phlsys_fs

import phlurl_watcher

class Test(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_A_Breathing(self):

        # N.B. We have to assign to an array as we're in a nested func
        #      and otherwise we won't be referring to the same data.
        #      In Python 3 we can do better with 'nonlocal'
        request_count = [0]

        def request_func(url):
            # make sure the result is different each time
            request_count[0] += 1
            return str(request_count[0]) + url

        watcher = phlurl_watcher.Watcher(request_func)

        with phlsys_fs.chtmpdir_context():

            with open('data', 'w') as f:
                watcher.dump(f)
            with open('data') as f:
                watcher.load(f)

            url = 'http://z.com'

            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

            with open('data', 'w') as f:
                watcher.dump(f)
            with open('data') as f:
                watcher.load(f)

            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ------------------------------ END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>"""
general functions for handling common pipeline steps
"""

from bcbio.utils import safe_makedir, file_exists
from bipy.log import logger
import datetime
import os
import yaml
import abc

def setup_pipeline(config):
    """
    creates output directories
    and performs some minor validation on the configuration file
    """
    # make initial directories
    if "dir" not in config:
        logger.error("'dir' must be in config file, see example "
                     " configurations.")
        exit(-1)
    config = _setup_config(config)
    map(safe_makedir, config["dir"].values())

    _write_config(config)

    return config

def _write_config(config):
    """
    output a yaml file of the configuration for this run in the results
    directory
    """
    yaml_file = os.path.join(config["dir"].get("results", "results"),
                             "config.yaml")
    with open(yaml_file, "w") as out_handle:
        out_handle.write(yaml.dump(config))

def _setup_config(config):
    """
    configuration file setup
    """
    if "pipeline" in config:
        # add timestamp for the run
        if config["pipeline"].get("timestamp", None):
            time_fmt = '%Y-%m-%d-%H-%M-%S'
            now = datetime.datetime.now().strftime(time_fmt)
            stamped_dir = os.path.join(config["dir"]["results"], now)
            config["dir"]["results"] = stamped_dir

    return config

def AbstractRunner(object):

    @abc.abstractmethod
    def run(self):
        """Runs the command"""
        return

    @abc.abstractmethod
    def output(self):
        """Returns summary output of running the command in a dictionary"""
        return

    @abc.abstractmethod
    def command(self):
        """Returns the actual command line for running the command as a string"""
        return

    @abc.abstractmethod
    def accepts(self):
        """Returns a list of extensions the command accepts for input files"""
        return

    @abc.abstractmethod
    def next(self):
        """Returns the files that would be used post this stage of processing"""
        return
<commit_msg>Added some skeleton code for later use.<commit_after>"""
general functions for handling common pipeline steps
"""

from bcbio.utils import safe_makedir, file_exists
from bipy.log import logger
import datetime
import os
import yaml
import abc

def setup_pipeline(config):
    """
    creates output directories
    and performs some minor validation on the configuration file
    """
    # make initial directories
    if "dir" not in config:
        logger.error("'dir' must be in config file, see example "
                     " configurations.")
        exit(-1)
    config = _setup_config(config)
    map(safe_makedir, config["dir"].values())

    _write_config(config)

    return config

def _write_config(config):
    """
    output a yaml file of the configuration for this run in the results
    directory
    """
    yaml_file = os.path.join(config["dir"].get("results", "results"),
                             "config.yaml")
    with open(yaml_file, "w") as out_handle:
        out_handle.write(yaml.dump(config))

def _setup_config(config):
    """
    configuration file setup
    """
    if "pipeline" in config:
        # add timestamp for the run
        if config["pipeline"].get("timestamp", None):
            time_fmt = '%Y-%m-%d-%H-%M-%S'
            now = datetime.datetime.now().strftime(time_fmt)
            stamped_dir = os.path.join(config["dir"]["results"], now)
            config["dir"]["results"] = stamped_dir

    return config

class AbstractRunner(object):

    @abc.abstractmethod
    def run(self):
        """Runs the command"""
        return

    @abc.abstractmethod
    def output(self):
        """Returns summary output of running the command in a dictionary"""
        return

    @abc.abstractmethod
    def command(self):
        """Returns the actual command line for running the command as a string"""
        return

    @abc.abstractmethod
    def accepts(self):
        """Returns a list of extensions the command accepts for input files"""
        return

    @abc.abstractmethod
    def next(self):
        """Returns the files that would be used post this stage of processing"""
        return

class AbstractStage(object):

    def __init__(self, config):
        self.config = config
        self._validate_config()

    def _validate_config(self):
        if "stage" not in self.config:
            raise ValueError('Could not find "stage" in the config file.')

    @property
    def stages(self):
        return self.config["stage"]

    def run_start_message(self, in_file):
        print "Starting lol. %s" % (self.stage)
        #logger.info("Starting %s on %s" % (self.stage, in_file))
<|endoftext|>


<commit_before>from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard

class UQAMDashboard(Dashboard):
    def __init__(self, **kwargs):
        Dashboard.__init__(self, **kwargs)

        self.children.append(modules.AppList(
            title=_('Catalogue'),
            column=1,
            collapsible=False,
            models=('cat.models.MuseumObject', 'parties.*',
                'loans.models.LoanAgreement', 'condition.*',
                'subcollections.*'),
            exclude=('django.contrib.*', 'djcelery.*', 'reports.*',  'location.*'),
        ))

        self.children.append(modules.LinkList(
            title=_('Geo-location'),
            column=1,
            children=(
                ['Geo-locations', '/admin/location/globalregion/jstree'],
            )
        ))

        self.children.append(modules.ModelList(
            title=_('Geo-location'),
            column=1,
            models=('location.models.GlobalRegion', 'location.models.Country',
                'location.models.StateProvince', 'location.models.RegionDistrict',
                'location.models.Locality', 'location.models.Place', 'location.models.Region'),
        ))

        self.children.append(modules.AppList(
            title='Data dictionary',
            column=1,
            models=('cat.models.*', 'loans.models.LoanPurpose'),
            exclude=('cat.models.MuseumObject',)
        ))

        # append an app list module for "Administration"
        self.children.append(modules.AppList(
            title=_('Administration'),
            column=1,
            collapsible=True,
            models=('django.contrib.*', 'djcelergy.*', 'reports.*',
                'dataimport.*', 'mediaman.*'),
        ))

        # append a recent actions module
        self.children.append(modules.RecentActions(
            title=_('Recent Actions'),
            column=2,
            collapsible=False,
            limit=5,
        ))

        self.children.append(modules.LinkList(
            layout='inline',
            title=_('Admin tools'),
            column=2,
            children=(
                ['Upload media', '/mediaman/bulk_upload/'],
                ['Filter/query items', '/admin/cat/museumobject/search'],
            )
        ))
<commit_msg>remove excess geolocs from admin dashboard<commit_after>from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard

class UQAMDashboard(Dashboard):
    def __init__(self, **kwargs):
        Dashboard.__init__(self, **kwargs)

        self.children.append(modules.AppList(
            title=_('Catalogue'),
            column=1,
            collapsible=False,
            models=('cat.models.MuseumObject', 'parties.*',
                'loans.models.LoanAgreement', 'condition.*',
                'subcollections.*'),
            exclude=('django.contrib.*', 'djcelery.*', 'reports.*',  'location.*'),
        ))

        self.children.append(modules.LinkList(
            title=_('Geo-location'),
            column=1,
            children=(
                ['Geo-locations', '/admin/location/globalregion/jstree'],
            )
        ))

#        self.children.append(modules.ModelList(
#            title=_('Geo-location'),
#            column=1,
#            models=('location.models.GlobalRegion', 'location.models.Country',
#                'location.models.StateProvince', 'location.models.RegionDistrict',
#                'location.models.Locality', 'location.models.Place', 'location.models.Region'),
#        ))

        self.children.append(modules.AppList(
            title='Data dictionary',
            column=1,
            models=('cat.models.*', 'loans.models.LoanPurpose'),
            exclude=('cat.models.MuseumObject',)
        ))

        # append an app list module for "Administration"
        self.children.append(modules.AppList(
            title=_('Administration'),
            column=1,
            collapsible=True,
            models=('django.contrib.*', 'djcelergy.*', 'reports.*',
                'dataimport.*', 'mediaman.*'),
        ))

        # append a recent actions module
        self.children.append(modules.RecentActions(
            title=_('Recent Actions'),
            column=2,
            collapsible=False,
            limit=5,
        ))

        self.children.append(modules.LinkList(
            layout='inline',
            title=_('Admin tools'),
            column=2,
            children=(
                ['Upload media', '/mediaman/bulk_upload/'],
                ['Filter/query items', '/admin/cat/museumobject/search'],
            )
        ))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Quattor'
copyright = u'2014, Quattor Collaboration'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '10.2-SNAPSHOT'
# The full version, including alpha/beta/rc tags.
release = '10.2-SNAPSHOT'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'QuattorPandoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'Pan.tex', u'Pan Language Compiler Documentation',
   u'Quattor Collaboration', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pan', u'Pan Language Compiler Documentation',
     [u'Quattor Collaboration'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'Pan', u'Pan Language Compiler Documentation',
   u'Quattor Collaboration', 'Quattor', 'Pan language compiler for Quattor toolkit.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = u'Pan'
epub_author = u'Quattor Collaboration'
epub_publisher = u'Quattor Collaboration'
epub_copyright = u'2014, Quattor Collaboration'

# The basename for the epub file. It defaults to the project name.
# epub_basename = u'Pan'

# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
# epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or en if the language is not set.
# epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
# epub_identifier = ''

# A unique identification for the text.
# epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
# epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
# epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_pre_files = []

# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
# epub_tocdepth = 3

# Allow duplicate toc entries.
# epub_tocdup = True

# Choose between 'default' and 'includehidden'.
# epub_tocscope = 'default'

# Fix unsupported image types using the PIL.
# epub_fix_images = False

# Scale large images.
# epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# epub_show_urls = 'inline'

# If false, no index is generated.
# epub_use_index = True
<commit_msg>Fix indentation of hanging blocks to meet pep8<commit_after># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Quattor'
copyright = u'2014, Quattor Collaboration'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '10.2-SNAPSHOT'
# The full version, including alpha/beta/rc tags.
release = '10.2-SNAPSHOT'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'QuattorPandoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    # 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    ('index', 'Pan.tex', u'Pan Language Compiler Documentation',
     u'Quattor Collaboration', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pan', u'Pan Language Compiler Documentation',
     [u'Quattor Collaboration'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'Pan', u'Pan Language Compiler Documentation',
     u'Quattor Collaboration', 'Quattor', 'Pan language compiler for Quattor toolkit.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = u'Pan'
epub_author = u'Quattor Collaboration'
epub_publisher = u'Quattor Collaboration'
epub_copyright = u'2014, Quattor Collaboration'

# The basename for the epub file. It defaults to the project name.
# epub_basename = u'Pan'

# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
# epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or en if the language is not set.
# epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
# epub_identifier = ''

# A unique identification for the text.
# epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
# epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
# epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_pre_files = []

# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
# epub_tocdepth = 3

# Allow duplicate toc entries.
# epub_tocdup = True

# Choose between 'default' and 'includehidden'.
# epub_tocscope = 'default'

# Fix unsupported image types using the PIL.
# epub_fix_images = False

# Scale large images.
# epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# epub_show_urls = 'inline'

# If false, no index is generated.
# epub_use_index = True
<|endoftext|>


<commit_before>"""PyFixedFlatFile"""
__version__ = '0.9'
from pyFixedFlatFile.pyFixedFlatFile import PyFixedFlatFile
<commit_msg>Atualiza versão para 1.0<commit_after>"""PyFixedFlatFile"""
__version__ = '1.0'
from pyFixedFlatFile.pyFixedFlatFile import PyFixedFlatFile
<|endoftext|>


<commit_before>"""Constructs linear elasticity problems for first-order elements in 2D and 3D

References
----------

    "Matlab implementation of the finite element method in elasticity"
    Computing, Volume 69,  Issue 3  (November 2002) Pages: 239 - 263
    J. Alberty, C. Carstensen, S. A. Funken, and R. KloseDOI
    http://www.math.hu-berlin.de/~cc/

"""

__docformat__ = "restructuredtext en"

__all__ = [ 'linear_elasticity' ]

from scipy import array, matrix, ones, zeros, arange, empty, \
        hstack, vstack, tile, ravel, mgrid, concatenate, \
        cumsum, dot, eye, asarray
from scipy.linalg import inv, det
from scipy.sparse import coo_matrix, bsr_matrix

def linear_elasticity(grid, spacing=None, E=1e5, nu=0.3, format=None):
    if len(grid) == 2:
        return q12d(grid, spacing=spacing, E=E, nu=nu, format=format)
    else:
        raise NotImplemented('no support for grid=%s' % str(grid))

def q12d(grid, spacing=None, E=1e5, nu=0.3, dirichlet_boundary=True, format=None):
    """Q1 elements in 2 dimensions"""
    X,Y = tuple(grid)

    if X < 1 or Y < 1:
        raise ValueError('invalid grid shape')

    if dirichlet_boundary:
        X += 1
        Y += 1

    pts = mgrid[0:X+1,0:Y+1]
    pts = hstack((pts[0].T.reshape(-1,1) - X/2.0, pts[1].T.reshape(-1,1) - Y/2.0))

    if spacing is None:
        DX,DY = 1,1
    else:
        DX,DY = tuple(spacing)
        pts = [DX,DY]

    #compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter
    mu   = E / (2 + 2*nu)                   # shear modulus

    vertices = array([[0,0],[DX,0],[DX,DY],[0,DY]])
    K = q12d_local(vertices, lame, mu )

    nodes = arange( (X+1)*(Y+1) ).reshape(X+1,Y+1)
    LL = nodes[:-1,:-1]
    I  = (2*LL).repeat( K.size ).reshape(-1,8,8)
    J  = I.copy()
    I += tile( [0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) )
    J += tile( [0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) ).T
    V  = tile( K, (X*Y,1) )

    I = ravel(I)
    J = ravel(J)
    V = ravel(V)

    A = coo_matrix( (V,(I,J)), shape=(pts.size,pts.size) ).tocsr() #sum duplicates
    A = A.tobsr(blocksize=(2,2))

    del I,J,V,LL,nodes

    B = zeros(( 2 * (X+1)*(Y+1), 3))
    B[0::2,0] = 1
    B[1::2,1] = 1
    B[0::2,2] = -pts[:,1]
    B[1::2,2] =  pts[:,0]

    if dirichlet_boundary:
        mask = zeros((X+1, Y+1),dtype='bool')
        mask[1:-1,1:-1] = True
        mask = ravel(mask)
        data = zeros( ((X-1)*(Y-1),2,2) )
        data[:,0,0] = 1
        data[:,1,1] = 1
        indices = arange( (X-1)*(Y-1) )
        indptr = concatenate((array([0]),cumsum(mask)))
        P = bsr_matrix((data,indices,indptr),shape=(2*(X+1)*(Y+1),2*(X-1)*(Y-1)))
        Pt = P.T
        A = P.T * A * P

        B = Pt * B

    return A.asformat(format),B

def q12d_local(vertices, lame, mu):
    """local stiffness matrix for two dimensional elasticity on a square element

    Parameters
    ----------
    lame : Float
        Lame's first parameter
    mu   : Float
        shear modulus

    Notes
    -----
    Vertices should be listed in counter-clockwise order::

        [3]----[2]
         |      |
         |      |
        [0]----[1]

    Degrees of freedom are enumerated as follows::

        [x=6,y=7]----[x=4,y=5]
            |            |
            |            |
        [x=0,y=1]----[x=2,y=3]

    """

    M    = lame + 2*mu # P-wave modulus

    R_11 = matrix([[  2, -2, -1,  1],
                   [ -2,  2,  1, -1],
                   [ -1,  1,  2, -2],
                   [  1, -1, -2,  2]]) / 6.0

    R_12 = matrix([[  1,  1, -1, -1],
                   [ -1, -1,  1,  1],
                   [ -1, -1,  1,  1],
                   [  1,  1, -1, -1]]) / 4.0

    R_22 = matrix([[  2,  1, -1, -2],
                   [  1,  2, -2, -1],
                   [ -1, -2,  2,  1],
                   [ -2, -1,  1,  2]]) / 6.0

    F = inv( vstack( (vertices[1] - vertices[0], vertices[3] - vertices[0]) ) )

    K = zeros((8,8)) # stiffness matrix

    E = F.T * matrix([[M, 0],[0, mu]]) * F
    K[0::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    E = F.T * matrix([[mu, 0],[0, M]]) * F
    K[1::2,1::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    E = F.T * matrix([[0, mu],[lame, 0]]) * F;
    K[1::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    K[0::2,1::2] = K[1::2,0::2].T

    K /= det(F)

    return K

def linear_elasticity_p1(vertices, elements, E=1e5, nu=0.3, format=None):
    """P1 elements in 2 or 3 dimensions"""

    #compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter
    mu   = E / (2 + 2*nu)                   # shear modulus

    vertices = asarray(vertices)
    elements = asarray(elements)

    D   = vertices.shape[1]    # spatial dimension
    DoF = D*vertices.shape[0]  # number of degrees of freedom
    NE  = elements.shape[0]    # number of elements

    if elements.shape[1] != D + 1:
        raise ValueError('dimension mismatch')

    if D == 2:
        local_K = p12d_local
    elif D == 3:
        local_K = p13d_local
    else:
        raise NotImplementedError('only dimension 2 and 3 are supported')

    row = elements.repeat(D).reshape(-1,D)
    row *= D
    row += arange(D)
    row = row.reshape(-1,D*(D+1)).repeat(D*(D+1), axis=0)
    row = row.reshape(-1,D*(D+1),D*(D+1))
    col = row.swapaxes(1,2)

    data = empty( (NE, D*(D+1), D*(D+1)), dtype=float)

    for i in xrange(NE):
        element_indices  = elements[i,:]
        element_vertices = vertices[element_indices,:]

        data[i] = local_K(element_vertices, lame, mu)

    row  = row.ravel()
    col  = col.ravel()
    data = data.ravel()

    A = coo_matrix( (data,(row,col)), shape=(DoF,DoF)).tocsr()  #sum duplicates
    A = A.tobsr(blocksize=(D,D))

    # compute rigid body modes
    if D == 2:
        B = zeros( (DoF,3) )
        B[0::2,0] = 1              # vector field in x direction
        B[1::2,1] = 1              # vector field in y direction

        B[0::2,2] = -vertices[:,1] # rotation vector field (-y,x)
        B[1::2,2] =  vertices[:,0]
    else:
        B = zeros( (DoF,6) )
        B[0::3,0] = 1              # vector field in x direction
        B[1::3,1] = 1              # vector field in y direction
        B[2::3,2] = 1              # vector field in z direction

        B[0::3,3] = -vertices[:,1] # rotation vector field (-y,x,0)
        B[1::3,3] =  vertices[:,0]
        B[0::3,4] = -vertices[:,2] # rotation vector field (-z,0,x)
        B[2::3,4] =  vertices[:,0]
        B[1::3,5] = -vertices[:,2] # rotation vector field (0,-z,y)
        B[2::3,5] =  vertices[:,1]

    return A.asformat(format),B

def p12d_local(vertices, lame, mu):
    """local stiffness matrix for P1 elements in 2d"""
    assert(vertices.shape == (3,2))

    A = vstack( (ones((1,3)),vertices.T) )
    PhiGrad = inv(A)[:,1:] #gradients of basis functions
    R = zeros((3,6))
    R[ [[0],[2]], [0,2,4] ] = PhiGrad.T
    R[ [[2],[1]], [1,3,5] ] = PhiGrad.T
    C = mu*array([[2,0,0],[0,2,0],[0,0,1]]) + lame*array([[1,1,0],[1,1,0],[0,0,0]])
    K = det(A)/2.0*dot(dot(R.T,C),R)
    return K

def p13d_local(vertices, lame, mu):
    """local stiffness matrix for P1 elements in 3d"""
    assert(vertices.shape == (4,3))

    A = vstack( (ones((1,4)),vertices.T) )
    PhiGrad = inv(A)[:,1:] #gradients of basis functions

    R = zeros((6,12))
    R[[0,3,4], 0::3] = PhiGrad.T
    R[[3,1,5], 1::3] = PhiGrad.T
    R[[4,5,2], 2::3] = PhiGrad.T

    C = zeros((6,6))
    C[0:3,0:3] = lame + 2*mu*eye(3)
    C[3:6,3:6] = mu*eye(3)

    K = det(A)/6*dot(dot(R.T,C),R)
    return K

<commit_msg>updated elastic docstrings<commit_after>"""Constructs linear elasticity problems for first-order elements in 2D and 3D

    References
    ----------
    "Matlab implementation of the finite element method in elasticity"
    Computing, Volume 69,  Issue 3  (November 2002) Pages: 239 - 263
    J. Alberty, C. Carstensen, S. A. Funken, and R. KloseDOI
    http://www.math.hu-berlin.de/~cc/

"""

__docformat__ = "restructuredtext en"

__all__ = [ 'linear_elasticity', 'linear_elasticity_p1' ]

from scipy import array, matrix, ones, zeros, arange, empty, \
        hstack, vstack, tile, ravel, mgrid, concatenate, \
        cumsum, dot, eye, asarray
from scipy.linalg import inv, det
from scipy.sparse import coo_matrix, bsr_matrix

def linear_elasticity(grid, spacing=None, E=1e5, nu=0.3, format=None):
    """
    Q1 FEM on a regular recatangular grid for linear elasticity

    Parameters
    ----------
    grid : tuple
        length 2 tuple of grid sizes, e.g. (10,10)
    spacing : tuple
        length 2 tuple of grid spacings, e.g. (1.0,0.1)
    E : float
        Young's modulus
    nu : float
        Poisson's ratio
    format : string
        'csr', 'csc', 'coo', 'bsr'

    Returns
    -------
    A : {csr_matrix}
        FE Q1 stiffness matrix

    Notes
    -----
        - only 2d for now

    Examples
    --------
    >>> from pyamg.gallery import linear_elasticity
    >>> A,B = linear_elasticity((4,4))

    See Also
    --------
    linear_elasticity_p1
    """
    if len(grid) == 2:
        return q12d(grid, spacing=spacing, E=E, nu=nu, format=format)
    else:
        raise NotImplemented('no support for grid=%s' % str(grid))

def q12d(grid, spacing=None, E=1e5, nu=0.3, dirichlet_boundary=True, format=None):
    """Q1 elements in 2 dimensions

    See Also
    --------
    linear_elasticity
    """
    X,Y = tuple(grid)

    if X < 1 or Y < 1:
        raise ValueError('invalid grid shape')

    if dirichlet_boundary:
        X += 1
        Y += 1

    pts = mgrid[0:X+1,0:Y+1]
    pts = hstack((pts[0].T.reshape(-1,1) - X/2.0, pts[1].T.reshape(-1,1) - Y/2.0))

    if spacing is None:
        DX,DY = 1,1
    else:
        DX,DY = tuple(spacing)
        pts = [DX,DY]

    #compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter
    mu   = E / (2 + 2*nu)                   # shear modulus

    vertices = array([[0,0],[DX,0],[DX,DY],[0,DY]])
    K = q12d_local(vertices, lame, mu )

    nodes = arange( (X+1)*(Y+1) ).reshape(X+1,Y+1)
    LL = nodes[:-1,:-1]
    I  = (2*LL).repeat( K.size ).reshape(-1,8,8)
    J  = I.copy()
    I += tile( [0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) )
    J += tile( [0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8,1) ).T
    V  = tile( K, (X*Y,1) )

    I = ravel(I)
    J = ravel(J)
    V = ravel(V)

    A = coo_matrix( (V,(I,J)), shape=(pts.size,pts.size) ).tocsr() #sum duplicates
    A = A.tobsr(blocksize=(2,2))

    del I,J,V,LL,nodes

    B = zeros(( 2 * (X+1)*(Y+1), 3))
    B[0::2,0] = 1
    B[1::2,1] = 1
    B[0::2,2] = -pts[:,1]
    B[1::2,2] =  pts[:,0]

    if dirichlet_boundary:
        mask = zeros((X+1, Y+1),dtype='bool')
        mask[1:-1,1:-1] = True
        mask = ravel(mask)
        data = zeros( ((X-1)*(Y-1),2,2) )
        data[:,0,0] = 1
        data[:,1,1] = 1
        indices = arange( (X-1)*(Y-1) )
        indptr = concatenate((array([0]),cumsum(mask)))
        P = bsr_matrix((data,indices,indptr),shape=(2*(X+1)*(Y+1),2*(X-1)*(Y-1)))
        Pt = P.T
        A = P.T * A * P

        B = Pt * B

    return A.asformat(format),B

def q12d_local(vertices, lame, mu):
    """local stiffness matrix for two dimensional elasticity on a square element

    Parameters
    ----------
    lame : Float
        Lame's first parameter
    mu : Float
        shear modulus

    Notes
    -----
    Vertices should be listed in counter-clockwise order::

        [3]----[2]
         |      |
         |      |
        [0]----[1]

    Degrees of freedom are enumerated as follows::

        [x=6,y=7]----[x=4,y=5]
            |            |
            |            |
        [x=0,y=1]----[x=2,y=3]

    """

    M    = lame + 2*mu # P-wave modulus

    R_11 = matrix([[  2, -2, -1,  1],
                   [ -2,  2,  1, -1],
                   [ -1,  1,  2, -2],
                   [  1, -1, -2,  2]]) / 6.0

    R_12 = matrix([[  1,  1, -1, -1],
                   [ -1, -1,  1,  1],
                   [ -1, -1,  1,  1],
                   [  1,  1, -1, -1]]) / 4.0

    R_22 = matrix([[  2,  1, -1, -2],
                   [  1,  2, -2, -1],
                   [ -1, -2,  2,  1],
                   [ -2, -1,  1,  2]]) / 6.0

    F = inv( vstack( (vertices[1] - vertices[0], vertices[3] - vertices[0]) ) )

    K = zeros((8,8)) # stiffness matrix

    E = F.T * matrix([[M, 0],[0, mu]]) * F
    K[0::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    E = F.T * matrix([[mu, 0],[0, M]]) * F
    K[1::2,1::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    E = F.T * matrix([[0, mu],[lame, 0]]) * F;
    K[1::2,0::2] = E[0,0] * R_11 + E[0,1] * R_12 + E[1,0] * R_12.T + E[1,1] * R_22

    K[0::2,1::2] = K[1::2,0::2].T

    K /= det(F)

    return K

def linear_elasticity_p1(vertices, elements, E=1e5, nu=0.3, format=None):
    """P1 elements in 2 or 3 dimensions

    Parameters
    ----------
    verticies : array_like
        array of vertices of a triangle or tets
    elements : array_like
        array of vertex indices for tri or tet elements
    E : float
        Young's modulus
    nu : float
        Poisson's ratio
    format : string
        'csr', 'csc', 'coo', 'bsr'

    Returns
    -------
    A : {csr_matrix}
        FE Q1 stiffness matrix

    Notes
    -----
        - works in both 2d and in 3d

    Examples
    --------
    >>> from pyamg.gallery import linear_elasticity_p1
    >>> E = array([[0,1,2],[1,3,2]])
    >>> V = array([[0.0,0.0],[1.0,0.0],[0.0,1.0],[1.0,1.0]])
    >>> A,B = linear_elasticity_p1(V,E)

    See Also
    --------
    linear_elasticity
    """

    #compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu)) # Lame's first parameter
    mu   = E / (2 + 2*nu)                   # shear modulus

    vertices = asarray(vertices)
    elements = asarray(elements)

    D   = vertices.shape[1]    # spatial dimension
    DoF = D*vertices.shape[0]  # number of degrees of freedom
    NE  = elements.shape[0]    # number of elements

    if elements.shape[1] != D + 1:
        raise ValueError('dimension mismatch')

    if D == 2:
        local_K = p12d_local
    elif D == 3:
        local_K = p13d_local
    else:
        raise NotImplementedError('only dimension 2 and 3 are supported')

    row = elements.repeat(D).reshape(-1,D)
    row *= D
    row += arange(D)
    row = row.reshape(-1,D*(D+1)).repeat(D*(D+1), axis=0)
    row = row.reshape(-1,D*(D+1),D*(D+1))
    col = row.swapaxes(1,2)

    data = empty( (NE, D*(D+1), D*(D+1)), dtype=float)

    for i in xrange(NE):
        element_indices  = elements[i,:]
        element_vertices = vertices[element_indices,:]

        data[i] = local_K(element_vertices, lame, mu)

    row  = row.ravel()
    col  = col.ravel()
    data = data.ravel()

    A = coo_matrix( (data,(row,col)), shape=(DoF,DoF)).tocsr()  #sum duplicates
    A = A.tobsr(blocksize=(D,D))

    # compute rigid body modes
    if D == 2:
        B = zeros( (DoF,3) )
        B[0::2,0] = 1              # vector field in x direction
        B[1::2,1] = 1              # vector field in y direction

        B[0::2,2] = -vertices[:,1] # rotation vector field (-y,x)
        B[1::2,2] =  vertices[:,0]
    else:
        B = zeros( (DoF,6) )
        B[0::3,0] = 1              # vector field in x direction
        B[1::3,1] = 1              # vector field in y direction
        B[2::3,2] = 1              # vector field in z direction

        B[0::3,3] = -vertices[:,1] # rotation vector field (-y,x,0)
        B[1::3,3] =  vertices[:,0]
        B[0::3,4] = -vertices[:,2] # rotation vector field (-z,0,x)
        B[2::3,4] =  vertices[:,0]
        B[1::3,5] = -vertices[:,2] # rotation vector field (0,-z,y)
        B[2::3,5] =  vertices[:,1]

    return A.asformat(format),B

def p12d_local(vertices, lame, mu):
    """local stiffness matrix for P1 elements in 2d"""
    assert(vertices.shape == (3,2))

    A = vstack( (ones((1,3)),vertices.T) )
    PhiGrad = inv(A)[:,1:] #gradients of basis functions
    R = zeros((3,6))
    R[ [[0],[2]], [0,2,4] ] = PhiGrad.T
    R[ [[2],[1]], [1,3,5] ] = PhiGrad.T
    C = mu*array([[2,0,0],[0,2,0],[0,0,1]]) + lame*array([[1,1,0],[1,1,0],[0,0,0]])
    K = det(A)/2.0*dot(dot(R.T,C),R)
    return K

def p13d_local(vertices, lame, mu):
    """local stiffness matrix for P1 elements in 3d"""
    assert(vertices.shape == (4,3))

    A = vstack( (ones((1,4)),vertices.T) )
    PhiGrad = inv(A)[:,1:] #gradients of basis functions

    R = zeros((6,12))
    R[[0,3,4], 0::3] = PhiGrad.T
    R[[3,1,5], 1::3] = PhiGrad.T
    R[[4,5,2], 2::3] = PhiGrad.T

    C = zeros((6,6))
    C[0:3,0:3] = lame + 2*mu*eye(3)
    C[3:6,3:6] = mu*eye(3)

    K = det(A)/6*dot(dot(R.T,C),R)
    return K
<|endoftext|>


<commit_before>import uuid

from pantsmud.driver import auxiliary

class Mobile(object):
    """
    A representation of a mobile entity in the game world.

    Instances of this class could represent mobs in a traditional MUD world, ships in an EVE-like game or monsters in a
    roguelike.
    """
    def __init__(self):
        self.uuid = uuid.uuid4()
        self.world = None
        self.brain_uuid = None
        self.node_uuid = None
        self.aux = auxiliary.new_data(auxiliary.AUX_TYPE_MOBILE)

    @property
    def brain(self):
        """
        Get the Brain attached to this Mobile.
        """
        if self.brain_uuid:
            return self.world.brains[self.brain_uuid]
        else:
            return self.brain_uuid

    @brain.setter
    def brain(self, brain):
        """
        Attach a Brain to this Mobile.
        """
        if brain:
            self.brain_uuid = brain.uuid
        else:
            self.brain_uuid = None

    @property
    def node(self):
        """
        Get the container Node for this Mobile.
        """
        if self.node_uuid:
            return self.world.nodes[self.node_uuid]
        else:
            return self.node_uuid

    @node.setter
    def node(self, node):
        """
        Set the container Node for this Mobile.
        """
        if node:
            self.node_uuid = node.uuid
        else:
            self.node_uuid = None
<commit_msg>Added attach_brain and detach_brain methods to Mobile. Added message method to mobile.<commit_after>import uuid

from pantsmud.driver import auxiliary

class Mobile(object):
    """
    A representation of a mobile entity in the game world.

    Instances of this class could represent mobs in a traditional MUD world, ships in an EVE-like game or monsters in a
    roguelike.
    """
    def __init__(self):
        self.uuid = uuid.uuid4()
        self.world = None
        self.brain_uuid = None
        self.node_uuid = None
        self.aux = auxiliary.new_data(auxiliary.AUX_TYPE_MOBILE)

    @property
    def brain(self):
        """
        Get the Mobile's Brain, if it has one.
        """
        if self.brain_uuid:
            return self.world.brains[self.brain_uuid]
        else:
            return self.brain_uuid

    @brain.setter
    def brain(self, brain):
        """
        Set the Mobile's Brain.
        """
        if brain:
            self.brain_uuid = brain.uuid
        else:
            self.brain_uuid = None

    @property
    def node(self):
        """
        Get the container Node for this Mobile.
        """
        if self.node_uuid:
            return self.world.nodes[self.node_uuid]
        else:
            return self.node_uuid

    @node.setter
    def node(self, node):
        """
        Set the container Node for this Mobile.
        """
        if node:
            self.node_uuid = node.uuid
        else:
            self.node_uuid = None

    def attach_brain(self, brain):
        """
        Attach a Brain to this Mobile.
        """
        self.brain = brain
        brain.mobile = self

    def detach_brain(self):
        """
        Detach a Brain from this Mobile.
        """
        self.brain.mobile = None
        self.brain = None

    def message(self, name, data=None):
        """
        Send a message to the Mobile's Brain, if it has one.
        """
        if self.brain:
            self.brain.message(name, data)
<|endoftext|>