code
stringlengths
1
18.2k
def reassign_comment_to_book(self, comment_id, from_book_id, to_book_id): """Moves a ``Credit`` from one ``Book`` to another. Mappings to other ``Books`` are unaffected. arg: comment_id (osid.id.Id): the ``Id`` of the ``Comment`` arg: from_book_id (osid.id.Id): the ``Id`` of the current ``Book`` arg: to_book_id (osid.i...
def can_create_book_with_record_types(self, book_record_types): """Tests if this user can create a single ``Book`` using the desired record types. While ``CommentingManager.getBookRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required for creating a specific `...
None: return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=book_record_types) return True
def update_book(self, book_form): """Updates an existing book. arg: book_form (osid.commenting.BookForm): the form containing the elements to be updated raise: IllegalState - ``book_form`` already used in an update transaction raise: InvalidArgument - the form contains an invalid value raise: NullArgument - ``book_form...
except KeyError: raise errors.Unsupported('book_form did not originate from this session') if not book_form.is_valid(): raise errors.InvalidArgument('one or more of the form elements is invalid') collection.save(book_form._my_map) # save is deprecated - change to replace_one self._forms[book_form.get_id().get_identifie...
def alias_book(self, book_id, alias_id): """Adds an ``Id`` to a ``Book`` for the purpose of creating compatibility. The primary ``Id`` of the ``Book`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another book, it is reassigned to the given book `...
def get_root_books(self): """Gets the root books in the book hierarchy. A node with no parents is an orphan. While all book ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. return: (osid.commenting.BookList) - the root books ...
def has_parent_books(self, book_id): """Tests if the ``Book`` has any parents. arg: book_id (osid.id.Id): a book ``Id`` return: (boolean) - ``true`` if the book has parents, f ``alse`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to c...
def is_parent_of_book(self, id_, book_id): """Tests if an ``Id`` is a direct parent of book. arg: id (osid.id.Id): an ``Id`` arg: book_id (osid.id.Id): the ``Id`` of a book return: (boolean) - ``true`` if this ``id`` is a parent of ``book_id,`` f ``alse`` otherwise raise: NotFound - ``book_id`` is not found raise: Null...
def get_parent_book_ids(self, book_id): """Gets the parent ``Ids`` of the given book. arg: book_id (osid.id.Id): a book ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the book raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete re...
def get_parent_books(self, book_id): """Gets the parent books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the parent books of the ``id`` raise: NotFound - a ``Book`` identified by ``Id is`` not found raise: NullArgument - ``book_id`` is ``null...
def is_ancestor_of_book(self, id_, book_id): """Tests if an ``Id`` is an ancestor of a book. arg: id (osid.id.Id): an ``Id`` arg: book_id (osid.id.Id): the ``Id`` of a book return: (boolean) - ``tru`` e if this ``id`` is an ancestor of ``book_id,`` ``false`` otherwise raise: NotFound - ``book_id`` is not found raise: N...
def has_child_books(self, book_id): """Tests if a book has any children. arg: book_id (osid.id.Id): a book ``Id`` return: (boolean) - ``true`` if the ``book_id`` has children, ``false`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to ...
def is_child_of_book(self, id_, book_id): """Tests if a book is a direct child of another. arg: id (osid.id.Id): an ``Id`` arg: book_id (osid.id.Id): the ``Id`` of a book return: (boolean) - ``true`` if the ``id`` is a child of ``book_id,`` ``false`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgum...
def get_child_book_ids(self, book_id): """Gets the child ``Ids`` of the given book. arg: book_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the book raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete requ...
def get_child_books(self, book_id): """Gets the child books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the child books of the ``id`` raise: NotFound - a ``Book`` identified by ``Id is`` not found raise: NullArgument - ``book_id`` is ``null`` ...
def is_descendant_of_book(self, id_, book_id): """Tests if an ``Id`` is a descendant of a book. arg: id (osid.id.Id): an ``Id`` arg: book_id (osid.id.Id): the ``Id`` of a book return: (boolean) - ``true`` if the ``id`` is a descendant of the ``book_id,`` ``false`` otherwise raise: NotFound - ``book_id`` is not found ra...
def get_book_nodes(self, book_id, ancestor_levels, descendant_levels, include_siblings): """Gets a portion of the hierarchy for the given book. arg: book_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to include. A value of 0 returns no parents in the node. a...
osid.resource.BinHierarchySession.get_bin_nodes return objects.BookNode(self.get_book_node_ids( book_id=book_id, ancestor_levels=ancestor_levels, descendant_levels=descendant_levels, include_siblings=include_siblings)._my_map, runtime=self._runtime, proxy=self._proxy)
def add_root_book(self, book_id): """Adds a root book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: AlreadyExists - ``book_id`` is already in hierarchy raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: Permission...
def remove_root_book(self, book_id): """Removes a root book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: NotFound - ``book_id`` is not a root raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandator...
def add_child_book(self, book_id, child_id): """Adds a child to a book. arg: book_id (osid.id.Id): the ``Id`` of a book arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``book_id`` is already a parent of ``child_id`` raise: NotFound - ``book_id`` or ``child_id`` not found raise: NullArgume...
def remove_child_book(self, book_id, child_id): """Removes a child from a book. arg: book_id (osid.id.Id): the ``Id`` of a book arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``book_id`` not a parent of ``child_id`` raise: NullArgument - ``book_id`` or ``child_id`` is ``null`` raise: Operatio...
def remove_child_books(self, book_id): """Removes all children from a book. arg: book_id (osid.id.Id): the ``Id`` of a book raise: NotFound - ``book_id`` not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *complianc...
def get_value_by_parameter(self, parameter_id=None): """Gets a ``Value`` for the given parameter ``Id``. If more than one value exists for the given parameter, the most preferred value is returned. This method can be used as a convenience when only one value is expected. ``get_values_by_parameters()`` should be used fo...
parameter_id.get_identifier() parameter_map = self._catalog._config_map['parameters'][parameter_key] except KeyError: raise NotFound(str(parameter_id)) if len(parameter_map['values']) == 0: raise NotFound() lowest_priority_value_map = None for value_map in parameter_map['values']: if lowest_priority_value_map is None o...
def parse_config(): """Parse the configuration and create required services. Note: Either takes the configuration from the environment (a variable named ``FLASH_CONFIG``) or a file at the module root (named ``config.json``). Either way, it will attempt to parse it as JSON, expecting the following format:: { "name": <Pr...
def _parse_file(): """Parse the config from a file. Note: Assumes any value that ``"$LOOKS_LIKE_THIS"`` in a service definition refers to an environment variable, and attempts to get it accordingly. """ file_name = path.join( path.abspath(path.dirname(path.dirname(__file__))), 'config.json' ) logger.info('loading confi...
def _read_file(file_name): """Read the file content and load it as JSON. Arguments: file_name (:py:class:`str`): The filename. Returns: :py:class:`dict`: The loaded JSON data. Raises: :py:class:`FileNotFoundError`: If the file is not found. """ with open(file_name) as config_file: data = json.load(config_file) return d...
def build_message(self, checker): """Builds the checker's error message to report""" solution = ' (%s)' % checker.solution if self.with_solutions else '' return '{} {}{}'.format(checker.code, checker.msg, solution)
def run(self): """Primary entry point to the plugin, runs once per file.""" paths = [x for x in practices.__dict__.values() if hasattr(x, 'code')] for node in ast.walk(self.tree): try: lineno, col_offset = node.lineno, node.col_offset except AttributeError: # Not all nodes have coordinates, e.g.: ast.Module continue fo...
def all_experiments(self): """ Retrieve every available experiment. Returns a list of ``cleaver.experiment.Experiment``s """ try: return [ self.experiment_factory(e) for e in model.Experiment.query.all() ] finally: self.Session.close()
def get_experiment(self, name, variants): """ Retrieve an experiment by its name and variants (assuming it exists). :param name a unique string name for the experiment :param variants a list of strings, each with a unique variant name Returns a ``cleaver.experiment.Experiment`` or ``None`` """ try: return self.experime...
def save_experiment(self, name, variants): """ Persist an experiment and its variants (unless they already exist). :param name a unique string name for the experiment :param variants a list of strings, each with a unique variant name """ try: model.Experiment( name=name, started_on=datetime.utcnow(), variants=[ model.V...
def get_variant(self, identity, experiment_name): """ Retrieve the variant for a specific user and experiment (if it exists). :param identity a unique user identifier :param experiment_name the string name of the experiment Returns a ``String`` or `None` """ try: match = model.Participant.query.join( model.Experiment )...
def set_variant(self, identity, experiment_name, variant_name): """ Set the variant for a specific user. :param identity a unique user identifier :param experiment_name the string name of the experiment :param variant_name the string name of the variant """ try: experiment = model.Experiment.get_by(name=experiment_name...
def _parametersAsIndex( self, ps ): """Private method to turn a parameter dict into a string suitable for keying a dict. ps: the parameters as a hash returns: a string key""" k = "" for p in sorted(ps.keys()): # normalise the parameters v = ps[p] k = k + "{p}=[[{v}]];".format(p = p, v = v) return k
def addResult( self, result, jobids = None ): """Add a result. This should be :term:`results dict` as returned from an instance of :class:`Experiment`, that contains metadata, parameters, and result. Results cannot be overridden, as notebooks are immutable: adding more results simply adds another result set. The result...
lists need not be the same length, to allow for experiments that return lists of result dicts.) :param result: a results dict :param jobids: the pending result job id(s) (defaults to no jobs) """ # deal with the dufferent ways of presenting results to be added if isinstance(result, list): # a list, recursively add for ...
deal with results like this: {r}".format(r = result)) # if there is are job ids provided, cancel the corresponding pending jobs if jobids is not None: if not isinstance(jobids, list): jobids = [ jobids ] for jobid in jobids: if jobid in self._pending.keys(): # grab the results list for which this is a pending job k = s...
def addPendingResult( self, ps, jobid ): """Add a "pending" result that we expect to get results for. :param ps: the parameters for the result :param jobid: an identifier for the pending result""" k = self._parametersAsIndex(ps) # retrieve or create the result list if k in self._results.keys(): rs = self._results[k] el...
def cancelPendingResult( self, jobid ): """Cancel a particular pending result. Note that this only affects the notebook's record, not any job running in a lab. :param jobid: job id for pending result""" if jobid in self._pending.keys(): k = self._pending[jobid] del self._pending[jobid] if k in self._results.keys(): rs ...
def pendingResultsFor( self, ps ): """Retrieve a list of all pending results associated with the given parameters. :param ps: the parameters :returns: a list of pending result job ids, which may be empty""" k = self._parametersAsIndex(ps) if k in self._results.keys(): # filter out pending job ids, which can be anything...
def cancelPendingResultsFor( self, ps ): """Cancel all pending results for the given parameters. Note that this only affects the notebook's record, not any job running in a lab. :param ps: the parameters""" k = self._parametersAsIndex(ps) if k in self._results.keys(): # remove from results rs = self._results[k] js = [ ...
def cancelAllPendingResults( self ): """Cancel all pending results. Note that this only affects the notebook's record, not any job running in a lab.""" for k in self._results.keys(): rs = self._results[k] self._results[k] = [ j for j in rs if isinstance(j, dict) ] self._pending = dict()
def resultsFor( self, ps ): """Retrieve a list of all results associated with the given parameters. :param ps: the parameters :returns: a list of results, which may be empty""" k = self._parametersAsIndex(ps) if k in self._results.keys(): # filter out pending job ids, which can be anything except dicts return [ res for...
def results( self ): """Return a list of all the results currently available. This excludes pending results. Results are returned as a single flat list, so any repetition structure is lost. :returns: a list of results""" rs = [] for k in self._results.keys(): # filter out pending job ids, which can be anything except d...
def dataframe( self, only_successful = True ): """Return the results as a pandas DataFrame. Note that there is a danger of duplicate labels here, for example if the results contain a value with the same name as one of the parameters. To resolve this, parameter names take precedence over metadata values, and result name...
= r[Experiment.METADATA].copy() rd.update(r[Experiment.PARAMETERS]) rd.update(r[Experiment.RESULTS]) else: # experiment returned an exception if not only_successful: # ...but we want it anyway rd = r[Experiment.METADATA].copy() rd.update(r[Experiment.PARAMETERS]) # ...and there are no results to add else: rd = None ret...
def distutils_autosemver_case( metadata, with_release_notes=False, with_authors=True, with_changelog=True, bugtracker_url=None, ): """ :param metadata: distutils metadata object. :param with_release_notes: if true, will create the release notes. :type with_release_notes: bool :param with_authors: if true, will create t...
def distutils_old_autosemver_case(metadata, attr, value): """DEPRECATED""" metadata = distutils_default_case(metadata, attr, value) create_changelog(bugtracker_url=getattr(metadata, 'bugtracker_url', '')) return metadata
def parse(self, stream): """ Parse the given stream """ lines = re.sub("[\r\n]+", "\n", stream.read()).split("\n") for line in lines: self.parseline(line)
async def stream_as_text(stream): """ Given a stream of bytes or text, if any of the items in the stream are bytes convert them to text. This function can be removed once we return text streams instead of byte streams. """ async for data in stream: if not isinstance(data, six.text_type): data = data.decode('utf-8', 're...
def pylint_jenkins(): """Run PyLint on the code and produce a report suitable for the Jenkins plugin 'violations'. Note that there is a bug in the Violations plugin which means that absolute paths to source (produced by PyLint) are not read. The sed command removes the workspace part of the path making everything good ...
def configure_google_analytics(): """An optional task; if run, this will switch on Google Analystics, reporting documentation usage to Aviser. This is meant to be run only by Aviser when producing HTML for the main web site. """ f = open(os.path.join("doc", "_templates", "google-analytics.html"), "w") f.write("""<scrip...
def publish(): """Publishes Formic to PyPi (don't run unless you are the maintainer)""" print("To be ready for release, remember:") print(" 1) Update the version number (and associated test)") print(" 2) Update the ChangeLog.rst (and other documentation)") print( " ChangeLog should have an line (title) consisting of th...
published_version) print("Current version: ", our_version) if our_version == published_version: raise Exception( "You are attempting to republish version " + our_version) # sanity: check ChangeLog starts with our version changelog = open("CHANGELOG.rst", "r") found = False for line in changelog.readlines(): if line.str...
looking_for) status = subprocess.check_output(["hg", "status"]) for line in status.split("\n"): if len(line) > 0: raise Exception("Uncommitted changes present") try: v = os.environ["RELEASE"] if v != "formic": raise KeyError() except KeyError: print("$RELEASE environment variable is not set") raise subprocess.check_cal...
def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True): '''launch module.main functions in another process''' processes = [] if kill_before_launch: for module_name, name in modules_with_names: kill_module(name) for module_name, name in modules_with_names: m = importlib.import_module(...
def list(self, **kwds): """ Endpoint: /albums/list.json Returns a list of Album objects. """ albums = self._client.get("/albums/list.json", **kwds)["result"] albums = self._result_to_list(albums) return [Album(self._client, album) for album in albums]
def cover_update(self, album, photo, **kwds): """ Endpoint: /album/<album_id>/cover/<photo_id>/update.json Update the cover photo of an album. Returns the updated album object. """ result = self._client.post("/album/%s/cover/%s/update.json" % (self._extract_id(album), self._extract_id(photo)), **kwds)["result"] # API c...
def create(self, name, **kwds): """ Endpoint: /album/create.json Creates a new album and returns it. """ result = self._client.post("/album/create.json", name=name, **kwds)["result"] return Album(self._client, result)
def delete(self, album, **kwds): """ Endpoint: /album/<id>/delete.json Deletes an album. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/album/%s/delete.json" % self._extract_id(album), **kwds)["result"]
def add(self, album, objects, object_type=None, **kwds): """ Endpoint: /album/<id>/<type>/add.json Add objects (eg. Photos) to an album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. Returns the updated album object. """ return self._a...
def remove(self, album, objects, object_type=None, **kwds): """ Endpoint: /album/<id>/<type>/remove.json Remove objects (eg. Photos) to an album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. Returns the updated album object. """ retur...
def _add_remove(self, action, album, objects, object_type=None, **kwds): """Common code for the add and remove endpoints.""" # Ensure we have an iterable of objects if not isinstance(objects, collections.Iterable): objects = [objects] # Extract the type of the objects if object_type is None: object_type = objects[0].ge...
def update(self, album, **kwds): """ Endpoint: /album/<id>/update.json Updates an album with the specified parameters. Returns the updated album object. """ result = self._client.post("/album/%s/update.json" % self._extract_id(album), **kwds)["result"] # APIv1 doesn't return the updated album (frontend issue #937) if i...
def view(self, album, **kwds): """ Endpoint: /album/<id>/view.json Requests all properties of an album. Returns the requested album object. """ result = self._client.get("/album/%s/view.json" % self._extract_id(album), **kwds)["result"] return Album(self._client, result)
def clone(self, folder, git_repository): """Ensures theme destination folder and clone git specified repo in it. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder """ os.makedirs(folder) git.Git().clone(git_repository, folder)
def update_git_repository(self, folder, git_repository): """Updates git remote for the managed theme folder if has changed. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder """ # load repo object from path repo = git.Repo(folder) # keep local_head_name for to reset ...
def update(self, folder, git_repository): """Creates or updates theme folder according given git repository. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder """ # git clone try: self.clone(folder, git_repository) # git update if folder already exist except OSError:...
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. If there are ``summarized_intensities`` provided, reads the files (:py:func:`read_summarized_intensities`) and skips to step 7. 3. Reads the ``bim`` file to g...
sex_problems = read_sex_problems(args.sex_problems) # Reading the intensity file data = read_intensities(args.intensities, marker_names_chr, sample_names_gender, sex_problems) else: data = read_summarized_intensities(args.summarized_intensities) # Plot the gender plot_gender(data, args)
def read_sex_problems(file_name): """Reads the sex problem file. :param file_name: the name of the file containing sex problems. :type file_name: str :returns: a :py:class:`frozenset` containing samples with sex problem. If there is no ``file_name`` (*i.e.* is ``None``), then an empty :py:class:`frozenset` is returned....
def encode_chr(chromosome): """Encodes chromosomes. :param chromosome: the chromosome to encode. :type chromosome: str :returns: the encoded chromosome as :py:class:`int`. It changes ``X``, ``Y``, ``XY`` and ``MT`` to ``23``, ``24``, ``25`` and ``26``, respectively. It changes everything else as :py:class:`int`. If :py...
[23, 24, 25, 26] >>> encode_chr("27") Traceback (most recent call last): ... ProgramError: 27: invalid chromosome >>> encode_chr("XX") Traceback (most recent call last): ... ProgramError: XX: invalid chromosome """ if chromosome == "X": return 23 if chromosome == "Y": return 24 if chromosome == "XY": return 25 if chrom...
def read_bim(file_name): """Reads the BIM file to gather marker names. :param file_name: the name of the ``bim`` file. :type file_name: str :returns: a :py:class:`dict` containing the chromosomal location of each marker on the sexual chromosomes. It uses the :py:func:`encode_chr` to encode the chromosomes from ``X`` an...
def read_fam(file_name): """Reads the FAM file to gather sample names. :param file_name: the ``fam`` file to read. :type file_name: str :returns: a :py:class:`dict` containing the gender of each samples. It uses the :py:func:`encode_gender` to encode the gender from ``1``and ``2`` to ``Male`` and ``Female``, respective...
def plot_gender(data, options): """Plots the gender. :param data: the data to plot. :param options: the options. :type data: numpy.recarray :type options: argparse.Namespace Plots the summarized intensities of the markers on the Y chromosomes in function of the markers on the X chromosomes, with problematic samples wit...
ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) # Setting the title ax.set_xlabel(options.xlabel) ax.set_ylabel(options.ylabel) # For the legend plot_object = [] labels = [] # Plotting the OK males males = np.logical_and(data["gender"] == "Male", data["status"] == "OK") tmp, = ax.plot(data["ch...
"^", ms=6, mec="#000000", mfc="#669900") plot_object.append(tmp) labels.append("Problematic Males (n={})".format(sum(males))) if options.summarized_intensities is None: print_data_to_file(data[males], "{}.problematic_males.txt".format(options.out)) # Plotting the Problem females females = np.logical_and(data["gender"] ...
write file".format(file_name) raise ProgramError(msg)
def print_data_to_file(data, file_name): """Prints data to file. :param data: the data to print. :param file_name: the name of the output file. :type data: numpy.recarray :type file_name: str """ try: with open(file_name, 'w') as output_file: print >>output_file, "\t".join(data.dtype.names) for row in data: print >>out...
def read_summarized_intensities(prefix): """Reads the summarized intensities from 6 files. :param prefix: the prefix of the six files. :type prefix: str :returns: a :py:class`numpy.recarray` containing the following columns (for each of the samples): ``sampleID``, ``chr23``, ``chr24``, ``gender`` and ``status``. Instea...
and ``status``. The final data set contains the following information for each sample: * ``sampleID``: the sample ID. * ``chr23``: the summarized intensities for chromosome 23. * ``chr24``: the summarized intensities for chromosome 24. * ``gender``: the gender of the sample (``Male`` or ``Female``). * ``status``: the s...
for i, col_name in enumerate(row) ]) for col_name in {"sampleID", "chr23", "chr24", "gender", "status"}: if col_name not in header_index: msg = "{}: no column named {}".format( prefix+suffix, col_name, ) raise ProgramError(msg) else: sampleID = row[header_index["sampleID"]] chr23 = row[header_index["chr23"]] chr24 = ro...
def read_intensities(file_name, needed_markers_chr, needed_samples_gender, sex_problems): """Reads the intensities from a file. :param file_name: the name of the input file. :param needed_markers_chr: the markers that are needed. :param needed_samples_gender: the gender of all the samples. :param sex_problems: the samp...
the sample ID. * ``chr23``: the summarized intensities for chromosome 23. * ``chr24``: the summarized intensities for chromosome 24. * ``gender``: the gender of the sample (``Male`` or ``Female``). * ``status``: the status of the sample (``OK`` or ``Problem``). The summarized intensities for a chromosome (:math:`S_{chr...
{"SNP Name", "Sample ID", "X", "Y", "Chr"}: if col_name not in header_index: msg = "{}: no column named {}".format(file_name, col_name) raise ProgramError(msg) else: # This is the data # Check if we want this sample and this marker sampleID = row[header_index["Sample ID"]] markerID = row[header_index["SNP Name"]] chrom...
float(allele_b) except ValueError: msg = "{}: {} and {}: wrong intensities".format(file_name, allele_a, allele_b) raise ProgramError(msg) if chromosome == 23: # Chromosome 23 intensities[sampleID][0] += allele_a + allele_b intensities[sampleID][1] += 1 else: # Chromosome 24 intensities[sampleID][2] += allele_a + allele...
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t...
such file".format(args.intensities) raise ProgramError(msg) else: if args.bfile is not None or args.intensities is not None: msg = ("need to specify either '--bfile' and '--intensities', or " "'--summarized-intensities'") raise ProgramError(msg) for suffix in {".ok_females.txt", ".ok_males.txt", ".ok_unknowns.txt", ".p...
def safe_main(): """A safe version of the main function (that catches ProgramError).""" try: main() except KeyboardInterrupt: logger.info("Cancelled by user") sys.exit(0) except ProgramError as e: logger.error(e.message) parser.error(e.message)
def filter(self, *args, **kwargs): """If id or pk was specified as a kwargs, return even if it's deleteted.""" if 'pk' in kwargs or 'id' in kwargs: return self.all_with_deleted().filter(*args, **kwargs) return self.get_query_set().filter(*args, **kwargs)
def preprocess(self, data): """ Processes popcorn JSON and builds a sane data model out of it @param data : The popcorn editor project json blob """ print 'Beginning pre-process...' for url, video in data['media'][0]['clipData'].iteritems(): print 'Downloading {0} from {1}.'.format(video['title'], url) # Removes all wh...
item.options['y_px'] = percent_to_px( item.options['top'], self.size[1] ) self.track_items.append(item) if event['type'] == 'sequencer': video = TrackVideo( event['type'], event['popcornOptions']['source'][0], event['popcornOptions'] ) self.track_videos.append(video) self.parse_duration() cfilter = r'color=c={0}:s={1}x...
def parse_duration(self): """ Corrects for any offsets that may have been created by loop and skip events """ for edit in self.track_edits: if edit.edit_type == 'loopPlugin': self.duration += ( (edit.options['end'] - edit.options['start']) * float(edit.options['loop']) )
def wrap_lines(content, length=80): """Wraps long lines to a maximum length of 80. :param content: the content to wrap. :param legnth: the maximum length to wrap the content. :type content: str :type length: int :returns: a string containing the wrapped content. :rtype: str """ return "\n".join(textwrap.wrap(content, l...
def format_numbers(number, prefix=""): """Formats number in the scientific notation for LaTeX. :param number: the number to format. :param prefix: a prefix to add before the number (e.g. "p < "). :type number: str :type prefix: str :returns: a string containing the scientific notation of the number. :rtype: str """ # M...
def sanitize_fig_name(name): """Sanitizes the name of a file (for including graphics in LaTeX). :param name: the name of the file to sanitize. :type name: str :returns: the sanitized name. For example, if the name of the graphic file is ``test.1.png``, the sanitized version of it for LaTeX is ``{test.1}.png``. """ name...