code
stringlengths
1
18.2k
def run_once_per_node(func): """ Decorator preventing wrapped function from running more than once per host (not just interpreter session). Using env.patch = True will allow the wrapped function to be run if it has been previously executed, but not otherwise Stores the result of a function as server state """ @wraps(fu...
def _close(self, fd): """ Close the descriptor used for a path regardless of mode. """ if self._mode == WF_INOTIFYX: try: pynotifyx.rm_watch(self._inx_fd, fd) except: pass else: try: os.close(fd) except: pass
def _self_pipe(self): """ This sets up a self-pipe so we can hand back an fd to the caller allowing the object to manage event triggers. The ends of the pipe are set non-blocking so it doesn't really matter if a bunch of events fill the pipe buffer. """ import fcntl self._poll_fd, self._poll_send = os.pipe() for fd in ...
def _disappeared(self, fd, path, **params): """ Called when an open path is no longer acessible. This will either move the path to pending (if the 'missing' param is set for the file), or fire an exception. """ log = self._getparam('log', self._discard, **params) log.debug("Path %r removed or renamed, handling removal"...
def _poll_get_stat(self, fd, path): """ Check the status of an open path. Note that we have to use stat() rather than fstat() because we want to detect file removes and renames. """ try: st = os.stat(path) fstate = (st.st_mode, st.st_nlink, st.st_uid, st.st_gid, st.st_size, st.st_mtime) except Exception as e: log = sel...
def _poll_trigger(self): """ Trigger activity for the caller by writting a NUL to the self-pipe. """ try: os.write(self._poll_send, '\0'.encode('utf-8')) except Exception as e: log = self._getparam('log', self._discard) log.debug("Ignoring self-pipe write error -- %s", e)
def _trigger(self, fd, **params): """ We need events to fire on appearance because the code doesn't see the file until after it has been created. In WF_KQUEUE mode, this simulates triggering an event by firing a oneshot timer event to fire immediately (0 msecs). Because this uses the file descriptor as the timer identi...
file activity to wake up the caller. """ log = self._getparam('log', self._discard, **params) if self._mode == WF_KQUEUE: try: ev = select.kevent(fd, filter=select.KQ_FILTER_TIMER, flags=select.KQ_EV_ADD | select.KQ_EV_CLEAR | select.KQ_EV_ONESHOT, data=0) self._kq.control([ev], 0, 0) log.debug("Added timer event follo...
log.error("Pending file promotion of unknown wd %d failed", fd) elif self._mode == WF_POLLING: self._poll_stat[fd] = () self._poll_trigger()
def _add_file(self, path, **params): """ Attempt to add a file to the system monitoring mechanism. """ log = self._getparam('log', self._discard, **params) fd = None try: fd = os.open(path, os.O_RDONLY) except Exception as e: if not self.paths[path]: log.error("Open failed on watched path %r -- %s", path, e, exc_info=l...
except: pass raise e elif self._mode == WF_INOTIFYX: # inotify doesn't need the target paths open, so now it is known to be # accessible, close the actual fd and use the watch-descriptor as the fd. # # However, due to an apparent simfs bug where inotify does not fire either # IN_DELETE_SELF or IN_MOVE_SELF, we need to ...
failed on watched path %r -- %s", path, e) raise e elif self._mode == WF_POLLING: log.debug("path %s opened as fd %d", path, fd) fstate = self._poll_get_stat(fd, path) if fstate: self._poll_stat[fd] = fstate self.paths_open[path] = fd self.fds_open[fd] = path return True
def commit(self, **params): """ Rebuild kevent operations by removing open files that no longer need to be watched, and adding new files if they are not currently being watched. This is done by comparing self.paths to self.paths_open. """ log = self._getparam('log', self._discard, **params) # Find all the modules that ...
del self._inx_inode[path] elif self._mode == WF_POLLING: if fd in self._poll_stat: del self._poll_stat[fd] else: log.warning("fd watched path %r missing from _poll_stat map", path) try: os.close(fd) except Exception as e: log.warning("close failed on watched file %r -- %s", path, e) if fd in self.fds_open: del self.fds...
del self.paths_pending[path] self._trigger(self.paths_open[path], **params) added += 1 log.debug("Added watch for path %r with ident %d", path, self.paths_open[path]) if failed: self._clean_failed_fds(fdlist) raise Exception("Failed to set watch on %s -- %s" % (str(failed), str(last_exc))) log.debug("%d added, %d remov...
def get(self, **params): """ Return a list of watched paths that where affected by recent changes, following a successful poll() return for the controlling file descriptor. If param "timeout" is greater than 0, the event queue will be read multiple times and reads continue until a timeout occurs. With a timeout active,...
limit = self._getparam('limit', None, **params) if not limit or limit < 0: limit = None max_events = limit if limit else 10000 if self.unprocessed_event: log.debug("Will handle unprocessed event") if self._mode == WF_KQUEUE: evagg = {} while True: try: evlist = self._kq.control(None, max_events, timeout) except OSError...
except IOError as e: if e.errno == errno.EINTR: break raise e if not evlist: break log.debug("pynotifyx.get_events() returned %d event%s", len(evlist), ses(len(evlist))) for ev in evlist: if ev.wd in self.fds_open: path = self.fds_open[ev.wd] if path in evagg: evagg[path].mask |= ev.mask else: evagg[path] = ev elif ev....
log.info("'simfs' (used with containers) bug detected -- %r removed", path) if file_move_del: self._disappeared(ev.wd, path, **params) self.last_changes[path] = time.time() elif self._mode == WF_POLLING: # Consume any pending data from the self-pipe. Read # until EOF. The fd is already non-blocking so this # terminates...
fstate is None: self.last_changes[path] = now elif self._poll_stat[fd] != fstate: self._poll_stat[fd] = fstate self.last_changes[path] = now log.debug("Change on %r", path) else: raise Exception("Unsupported polling mode " + self.get_mode_name()) paths = list(self.last_changes) paths.sort() log.debug("Change was to %d ...
def add(self, paths, **params): """ Add a path (or list of paths) to the list of paths being watched. The 'missing' setting for a file can also be changed by re-adding the file. """ log = self._getparam('log', self._discard, **params) missing = self._getparam('missing', True, **params) commit = self._getparam('commit',...
def remove(self, paths, **params): """ Delete paths from the watched list. """ log = self._getparam('log', self._discard, **params) commit = self._getparam('commit', True, **params) if type(paths) is not list: paths = [paths] rebuild = False for path in paths: if path in self.paths_pending: del self.paths_pending[path]...
def scan(self, **params): """ This method should be called periodically if files were added with "missing=False". It will check for the appearance of missing files and ensure an event will be triggered for any that appear. It also needs to be called if the instance could be in WF_POLLING mode as file system changes wil...
that a pending path is now accessible, and then calling commit() to make the necessary adjustments. This will be efficient as long as the list of pending paths is small. At some point this should be optimized by watching the directory of a pending target (assuming it exists). If the directory changes to indicate the pe...
%s now accessible, triggering commit()", path) self.commit(**params) return if self._mode == WF_POLLING: log.debug("Checking %d open path%s", len(self._poll_stat), ses(len(self._poll_stat))) for fd in list(self._poll_stat): fstate = self._poll_get_stat(fd, self.fds_open[fd]) if fstate is None or self._poll_stat[fd] != ...
def replace_ext(filename, ext): """ Return new pathname formed by replacing extension in `filename` with `ext`. """ if ext.startswith('.'): ext = ext[1:] stem, _ = os.path.splitext(filename) return (stem + '.' + ext)
def check_imagemagick_supported_format(fmt): """ Return ``True`` if `convert` can be run and reports supporting image format `fmt`. """ try: convert_output = check_output(['convert', '--version']) # `subprocess` raises `OSError` if the executable is not found except (CalledProcessError, OSError) as err: logger.error( "...
['bzlib', 'djvu', ...] # supported = [] for line in convert_output.split('\n'): line = line.lower() if line.startswith('delegates'): supported += line.split(':', 1)[1].split() # allow fmt to be ``png``, ``JPEG``, ``.TIF`` etc. fmt = fmt.lower() if not fmt.startswith('.'): fmt = '.' + fmt try: delegate = SUPPORTED_IMAGE...
def get_experiments(self): '''Gets information for all experiments. Returns ------- List[Dict[str, str]] id, name and description for each experiment See also -------- :func:`tmserver.api.experiment.get_experiments` :class:`tmlib.models.experiment.Experiment` ''' logger.info('get experiments') url = self._build_api_url...
def create_experiment(self, workflow_type, microscope_type, plate_format, plate_acquisition_mode): '''Creates the experiment. Parameters ---------- workflow_type: str workflow type microscope_type: str microscope type plate_format: int well-plate format, i.e. total number of wells per plate plate_acquisition_mode: str ...
def rename_experiment(self, new_name): '''Renames the experiment. Parameters ---------- See also -------- :func:`tmserver.api.experiment.update_experiment` :class:`tmlib.models.experiment.ExperimentReference` ''' logger.info('rename experiment "%s"', self.experiment_name) content = {'name': new_name} url = self._build_...
def delete_experiment(self): '''Deletes the experiment. See also -------- :func:`tmserver.api.experiment.delete_experiment` :class:`tmlib.models.experiment.ExperimentReference` :class:`tmlib.models.experiment.Experiment` ''' logger.info('delete experiment "%s"', self.experiment_name) url = self._build_api_url( '/experi...
def delete_plate(self, name): '''Deletes a plate. Parameters ---------- name: str name of the plate that should be deleted See also -------- :func:`tmserver.api.plate.delete_plate` :class:`tmlib.models.plate.Plate` ''' logger.info( 'delete plate "%s" of experiment "%s"', name, self.experiment_name ) plate_id = self._ge...
def rename_plate(self, name, new_name): '''Renames a plate. Parameters ---------- name: str name of the plate that should be renamed new_name: str name that should be given to the plate See also -------- :func:`tmserver.api.plate.update_plate` :class:`tmlib.models.plate.Plate` ''' logger.info( 'rename plate "%s" of exp...
def rename_acquisition(self, plate_name, name, new_name): '''Renames an acquisition. Parameters ---------- plate_name: str name of the parent plate name: str name of the acquisition that should be renamed new_name: str name that should be given to the acquisition See also -------- :func:`tmserver.api.acquisition.update...
def delete_acquisition(self, plate_name, name): '''Deletes an acquisition. Parameters ---------- plate_name: str name of the parent plate name: str name of the acquisition that should be deleted See also -------- :func:`tmserver.api.acquisition.delete_acquisition` :class:`tmlib.models.acquisition.Acquisition` ''' logge...
def get_wells(self, plate_name=None): '''Gets information about wells. Parameters ---------- plate_name: str, optional name of the parent plate Returns ------- List[Dict[str, str]] id, name and description of each well See also -------- :func:`tmserver.api.well.get_wells` :class:`tmlib.models.well.Well` ''' logger.info...
def get_microscope_files(self, plate_name, acquisition_name): '''Gets status and name of files that have been registered for upload. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition Returns ------- List[Dict[str, str]] names and status of uploaded files...
def upload_microscope_files(self, plate_name, acquisition_name, path, parallel=1, retry=5, convert=None, delete_after_upload=False, _deprecated_directory_option=False): ''' Uploads microscope files contained in `path`. If `path` is a directory, upload all files contained in it. Parameters ---------- plate_name: str nam...
------- List[str] names of registered files See also -------- :func:`tmserver.api.acquisition.add_microscope_file` :class:`tmlib.models.file.MicroscopeImageFile` :class:`tmlib.models.file.MicroscopeMetadataFile` ''' if _deprecated_directory_option: logger.warn( "The `--directory` option is now superfluous." " You can r...
acquisition_name) path = os.path.expandvars(os.path.expanduser(path)) if os.path.isdir(path): filenames = [ f for f in os.listdir(path) if (not f.startswith('.') and not os.path.isdir(os.path.join(path, f))) ] paths = [ os.path.join(path, name) for name in filenames ] else: filenames = [ os.path.basename(path) ] paths ...
len(paths) retry += 1 # make usage here consistent with CLI usage while retry > 0: work = [ # function, *args ... (self._upload_file, upload_url, path, convert, delete_after_upload, convert_dir) for path in paths ] outcome = self._parallelize(work, parallel) # report on failures paths = [path for (ok, path) in outcome ...
def register_microscope_files(self, plate_name, acquisition_name, path): ''' Register microscope files contained in `path` (Server side). If `path` is a directory, upload all files contained in it. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition path: ...
def rename_channel(self, name, new_name): '''Renames a channel. Parameters ---------- name: str name of the channel that should be renamed new_name: str name that should be given to the channel See also -------- :func:`tmserver.api.channel.update_channel` :class:`tmlib.models.channel.Channel` ''' logger.info( 'rename c...
def get_cycles(self): '''Gets cycles. Returns ------- List[Dict[str, str]] information about each cycle See also -------- :func:`tmserver.api.cycle.get_cycles` :class:`tmlib.models.cycles.Cycle` ''' logger.info('get cycles of experiment "%s"', self.experiment_name) url = self._build_api_url( '/experiments/{experiment_i...
def download_channel_image(self, channel_name, plate_name, well_name, well_pos_y, well_pos_x, cycle_index=0, tpoint=0, zplane=0, correct=True, align =False): '''Downloads a channel image. Parameters ---------- channel_name: str name of the channel plate_name: str name of the plate well_name: str name of the well well_p...
well_pos_y, well_pos_x, cycle_index=cycle_index, tpoint=tpoint, zplane=zplane, correct=correct, align = align ) data = np.frombuffer(response.content, np.uint8) return cv2.imdecode(data, cv2.IMREAD_UNCHANGED)
def download_channel_image_file(self, channel_name, plate_name, well_name, well_pos_y, well_pos_x, cycle_index, tpoint, zplane, correct, align, directory): '''Downloads a channel image and writes it to a `PNG` file on disk. Parameters ---------- channel_name: str name of the channel plate_name: str name of the plate we...
between cycles. See also -------- :meth:`tmclient.api.TmClient.download_channel_image` ''' response = self._download_channel_image( channel_name, plate_name, well_name, well_pos_y, well_pos_x, cycle_index=cycle_index, tpoint=tpoint, zplane=zplane, correct=correct, align = align ) data = response.content filename = self...
def download_segmentation_image(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint=0, zplane=0, align = False): '''Downloads a segmentation image. Parameters ---------- plate_id: int ID of the parent experiment mapobject_type_name: str name of the segmented objects plate_name: str name of ...
return np.array(response, dtype=np.int32)
def download_segmentation_image_file(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, align, directory): '''Downloads a segmentation image and writes it to a *PNG* file on disk. Parameters ---------- mapobject_type_name: str name of the segmented objects plate_name: str name of ...
also -------- :meth:`tmclient.api.TmClient.download_segmentation_image` ''' response = self._download_segmentation_image( mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, align ) image = np.array(response, np.int32) if np.max(image) >= 2**16: raise ValueError( 'Cannot store segmentati...
def upload_segmentation_image(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, image): '''Uploads a segmentation image. Parameters ---------- mapobject_type_name: str name of the segmented objects plate_name: str name of the plate well_name: str name of the well in which the ima...
array.') if image.dtype != np.int32: raise ValueError('Image must have 32-bit integer data type.') self._upload_segmentation_image(mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, image )
def upload_segmentation_image_file(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zplane, filename): '''Uploads segmentations from a *PNG* image file. Parameters ---------- mapobject_type_name: str name of the segmented objects plate_name: str name of the plate well_name: str name of ...
filename.lower().endswith('png'): raise IOError('Filename must have "png" extension.') filename = os.path.expanduser(os.path.expandvars(filename)) image = cv2.imread(filename, cv2.IMREAD_UNCHANGED | cv2.IMREAD_ANYDEPTH) self._upload_segmentation_image( mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x,...
def rename_feature(self, mapobject_type_name, name, new_name): '''Renames a feature. Parameters ---------- mapobject_type_name: str name of the segmented objects type name: str name of the feature that should be renamed new_name: str name that should be given to the feature See also -------- :func:`tmserver.api.feature...
def delete_feature(self, mapobject_type_name, name): '''Deletes a feature. Parameters ---------- mapobject_type_name: str name of the segmented objects type name: str name of the feature that should be renamed See also -------- :func:`tmserver.api.feature.delete_feature` :class:`tmlib.models.feature.Feature` ''' logger...
def rename_mapobject_type(self, name, new_name): '''Renames a mapobject type. Parameters ---------- name: str name of the mapobject type that should be renamed new_name: str name that should be given to the mapobject type See also -------- :func:`tmserver.api.mapobject.update_mapobject_type` :class:`tmlib.models.mapobj...
def delete_mapobject_type(self, name): '''Deletes a mapobject type. Parameters ---------- name: str name of the mapobject type that should be renamed See also -------- :func:`tmserver.api.mapobject.delete_mapobject_type` :class:`tmlib.models.mapobject.MapobjectType` ''' logger.info( 'delete mapobject type "%s" of exper...
def get_features(self, mapobject_type_name): '''Gets features for a given object type. Parameters ---------- mapobject_type_name: str type of the segmented objects Returns ------- List[Dict[str, str]] information about each feature See also -------- :func:`tmserver.api.feature.get_features` :class:`tmlib.models.feature...
def upload_feature_value_file(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, filename, index_col): '''Uploads feature values for the given :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` at the specified :class:`Site <tmlib.models.site.Site>`. Parameters ---------- mapob...
def download_feature_values(self, mapobject_type_name, plate_name=None, well_name=None, well_pos_y=None, well_pos_x=None, tpoint=None): '''Downloads feature values for the given :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>`. Parameters ---------- mapobject_type_name: str type of the segmented objects pl...
pd.read_csv(file_obj) except EmptyDataError: return pd.DataFrame()
def download_feature_values_and_metadata_files(self, mapobject_type_name, directory, parallel=1): '''Downloads all feature values for the given object type and stores the data as *CSV* files on disk. Parameters ---------- mapobject_type_name: str type of the segmented objects directory: str absolute path to the directo...
= os.path.join(directory, os.path.basename(filename)) logger.info('write metadata to file: %s', filepath) with open(filepath, 'wb') as f: for c in res.iter_content(chunk_size=1000): f.write(c) work = [(download_per_well, well) for well in self.get_wells()] self._parallelize(work, parallel)
def download_object_metadata(self, mapobject_type_name, plate_name=None, well_name=None, well_pos_y=None, well_pos_x=None, tpoint=None): '''Downloads metadata for the given object type, which describes the position of each segmented object on the map. Parameters ---------- mapobject_type_name: str type of the segmented...
def download_workflow_description_file(self, filename): '''Downloads the workflow description and writes it to a *YAML* file. Parameters ---------- filename: str path to the file to which description should be written See also -------- :meth:`tmclient.api.TmClient.download_workflow_description` ''' description = self.d...
def upload_workflow_description_file(self, filename): '''Uploads workflow description from a *YAML* file. Parameters ---------- filename: str path to the file from which description should be read See also -------- :meth:`tmclient.api.TmClient.upload_workflow_description` ''' if ( not filename.lower().endswith('yml') a...
def resubmit_workflow(self, stage_name=None, description=None): '''Resubmits the workflow. Parameters ---------- stage_name: str, optional name of the stage at which workflow should be resubmitted (when omitted workflow will be restarted from the beginning) description: dict, optional workflow description See also ----...
def kill_workflow(self): '''Kills the workflow. See also -------- :func:`tmserver.api.workflow.kill_workflow` :class:`tmlib.workflow.workflow.Workflow` ''' logger.info('kill workflow of experiment "%s"', self.experiment_name) content = dict() url = self._build_api_url( '/experiments/{experiment_id}/workflow/kill'.forma...
def get_workflow_status(self, depth=2): '''Gets the workflow status. Parameters ---------- depth: int, optional query depth - in which detail status of subtasks will be queried Returns ------- dict status information about the workflow See also -------- :func:`tmserver.api.workflow.get_workflow_status` :func:`tmlib.wor...
def upload_jterator_project(self, pipeline, handles): '''Uploads a *jterator* project. Parameters ---------- pipeline: dict description of the jterator pipeline handles: dict, optional description of each module in the jterator pipeline See also -------- :func:`tmserver.api.workflow.update_jterator_project` :class:`tml...
def download_jterator_project_files(self, directory): '''Downloads the *jterator* project and stores it on disk in YAML format. The pipeline description will be stored in a ``pipeline.yaml`` file in `directory` and each handle description will be stored in a ``*handles.yaml`` file and placed into a ``handles`` subfolde...
in descriptions['handles'].items(): handles_filename = os.path.join( handles_subdirectory, '{name}.handles.yaml'.format(name=name) ) logger.debug( 'write handles description to file: %s', handles_filename ) with open(handles_filename, 'w') as f: content = yaml.safe_dump( description, explicit_start=True, default_flow_s...
def upload_jterator_project_files(self, directory): '''Uploads the *jterator* project description from files on disk in YAML format. It expects a ``pipeline.yaml`` file in `directory` and optionally ``*handles.yaml`` files in a ``handles`` subfolder of `directory`. Parameters ---------- directory: str path to the root ...
glob.glob(handles_filename_pattern): name = os.path.splitext(os.path.splitext( os.path.basename(handles_filename) )[0])[0] logger.debug('load handles file: %s', handles_filename) with open(handles_filename) as f: handles_descriptions[name] = yaml.safe_load(f.read()) self.upload_jterator_project( pipeline_description, h...
def get_tools_status(self, tool_name=None): '''Gets the status of tool jobs. Parameters ---------- tool_name: str, optional filter jobs by tool name Returns ------- dict status information about tool jobs See also -------- :func:`tmserver.api.tools.get_tools_status` :func:`tmlib.workflow.utils.get_task_status` :class:`...
def generate_csv(path, out): """\ Walks through the `path` and generates the CSV file `out` """ def is_berlin_cable(filename): return 'BERLIN' in filename writer = UnicodeWriter(open(out, 'wb'), delimiter=';') writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject')) for cable in cables_from_source(path, predic...
def serve_forever(self): """ Run the DAAP server. Start by advertising the server via Bonjour. Then serve requests until CTRL + C is received. """ # Verify that the provider has a server. if self.provider.server is None: raise ValueError( "Cannot start server because the provider has no server to " "publish.") # Verify...
def model_base(bind_label=None, info=None): """Create a base declarative class """ Model = type('Model', (BaseModel,), {'__odm_abstract__': True}) info = {} Model.__table_args__ = table_args(info=info) if bind_label: info['bind_label'] = bind_label return Model
def copy_models(module_from, module_to): """Copy models from one module to another :param module_from: :param module_to: :return: """ module_from = get_module(module_from) module_to = get_module(module_to) models = get_models(module_from) if models: models = models.copy() models.update(((t.key, t) for t in module_table...
def register(self, model, **attr): """Register a model or a table with this mapper :param model: a table or a :class:`.BaseModel` class :return: a Model class or a table """ metadata = self.metadata if not isinstance(model, Table): model_name = self._create_model(model, **attr) if not model_name: return model, name = m...
def create_table(self, name, *columns, **kwargs): """Create a new table with the same metadata and info """ targs = table_args(**kwargs) args, kwargs = targs[:-1], targs[-1] return Table(name, self.metadata, *columns, *args, **kwargs)
def database_create(self, database, **params): """Create databases for each engine and return a new :class:`.Mapper`. """ binds = {} dbname = database for key, engine in self.keys_engines(): if hasattr(database, '__call__'): dbname = database(engine) assert dbname, "Cannot create a database, no db name given" key = key...
def database_exist(self): """Create databases for each engine and return a new :class:`.Mapper`. """ binds = {} for key, engine in self.keys_engines(): key = key if key else 'default' binds[key] = self._database_exist(engine) return binds
def database_all(self): """Return a dictionary mapping engines with databases """ all = {} for engine in self.engines(): all[engine] = self._database_all(engine) return all
def table_create(self, remove_existing=False): """Creates all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Create all tables for %s', engine) try: self.metadata.create_all(engine, tables=tables) except Exception as exc: raise
def table_drop(self): """Drops all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Drop all tables for %s', engine) self.metadata.drop_all(engine, tables=tables)
def begin(self, close=True, expire_on_commit=False, session=None, commit=False, **options): """Provide a transactional scope around a series of operations. By default, ``expire_on_commit`` is set to False so that instances can be used outside the session. """ if not session: commit = True session = self.session(expire_...
def _database_create(self, engine, database): """Create a new database and return a new url representing a connection to the new database """ logger.info('Creating database "%s" in "%s"', database, engine) database_operation(engine, 'create', database) url = copy(engine.url) url.database = database return str(url)
def get_washing_regex(): """Return a washing regex list.""" global _washing_regex if len(_washing_regex): return _washing_regex washing_regex = [ # Replace non and anti with non- and anti-. This allows a better # detection of keywords such as nonabelian. (re.compile(r"(\snon)[- ](\w+)"), r"\1\2"), (re.compile(r"(\santi...
"Psi", "Rho", "Stor", "UA", "Xi", "Z") ] washing_regex += [(re.compile(r"(\W%s) ?\( ?([0-9]+) ?\)[A-Z]?" % name), r"\1(\2)") for name in ("CP", "E", "G", "O", "S", "SL", "SO", "Spin", "SU", "U", "W", "Z")] # Particles with ' washing_regex += [(re.compile(r"(\W%s) ('\W)" % name), r"\1\2") for name in ("Eta", "W", "Z")] ...
# Remove multiple spaces. (re.compile(r" +"), " "), # Remove multiple line breaks. (re.compile(r"\n+"), r"\n"), ] _washing_regex = washing_regex return _washing_regex
def normalize_fulltext(fulltext): """Return a 'cleaned' version of the output provided by pdftotext.""" # We recognize keywords by the spaces. We need these to match the # first and last words of the document. fulltext = " " + fulltext + " " # Replace some weird unicode characters. fulltext = replace_undesirable_charac...
def cut_references(text_lines): """Return the text lines with the references cut.""" ref_sect_start = find_reference_section(text_lines) if ref_sect_start is not None: start = ref_sect_start["start_line"] end = find_end_of_reference_section(text_lines, start, ref_sect_start["marker"], ref_sect_start["marker_pattern"]) ...
def _replace_greek_characters(line): """Replace greek characters in a string.""" for greek_char, replacement in iteritems(_GREEK_REPLACEMENTS): try: line = line.replace(greek_char, replacement) except UnicodeDecodeError: current_app.logger.exception("Unicode decoding error.") return "" return line
def fitNull(self, verbose=False, cache=False, out_dir='./cache', fname=None, rewrite=False, seed=None, n_times=10, factr=1e3, init_method=None): """ Fit null model """ if seed is not None: sp.random.seed(seed) read_from_file = False if cache: assert fname is not None, 'MultiTraitSetTest:: specify fname' if not os.path....
= self._gpNull.LML() if self._gpNull.mean.n_terms==1: RV['B'] = self._gpNull.mean.B[0] elif self._gpNull.mean.n_terms>1: warning.warn('generalize to more than 1 fixed effect term') if self.bgRE: RV['params0_g'] = self.Cg.getParams() else: RV['params0_g'] = sp.zeros_like(self.Cn.getParams()) RV['params0_n'] = self.Cn.ge...