id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
6,700
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.initialize_directories
def initialize_directories(self): """Automatically create local directories required by pip-accel.""" makedirs(self.config.source_index) makedirs(self.config.eggs_cache)
python
def initialize_directories(self): makedirs(self.config.source_index) makedirs(self.config.eggs_cache)
[ "def", "initialize_directories", "(", "self", ")", ":", "makedirs", "(", "self", ".", "config", ".", "source_index", ")", "makedirs", "(", "self", ".", "config", ".", "eggs_cache", ")" ]
Automatically create local directories required by pip-accel.
[ "Automatically", "create", "local", "directories", "required", "by", "pip", "-", "accel", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L146-L149
6,701
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.clean_source_index
def clean_source_index(self): """ Cleanup broken symbolic links in the local source distribution index. The purpose of this method requires some context to understand. Let me preface this by stating that I realize I'm probably overcomplicating things, but I like to preserve forward / backward compatibility when possible and I don't feel like dropping everyone's locally cached source distribution archives without a good reason to do so. With that out of the way: - Versions of pip-accel based on pip 1.4.x maintained a local source distribution index based on a directory containing symbolic links pointing directly into pip's download cache. When files were removed from pip's download cache, broken symbolic links remained in pip-accel's local source distribution index directory. This resulted in very confusing error messages. To avoid this :func:`clean_source_index()` cleaned up broken symbolic links whenever pip-accel was about to invoke pip. - More recent versions of pip (6.x) no longer support the same style of download cache that contains source distribution archives that can be re-used directly by pip-accel. To cope with the changes in pip 6.x new versions of pip-accel tell pip to download source distribution archives directly into the local source distribution index directory maintained by pip-accel. - It is very reasonable for users of pip-accel to have multiple versions of pip-accel installed on their system (imagine a dozen Python virtual environments that won't all be updated at the same time; this is the situation I always find myself in :-). These versions of pip-accel will be sharing the same local source distribution index directory. - All of this leads up to the local source distribution index directory containing a mixture of symbolic links and regular files with no obvious way to atomically and gracefully upgrade the local source distribution index directory while avoiding fights between old and new versions of pip-accel :-). - I could of course switch to storing the new local source distribution index in a differently named directory (avoiding potential conflicts between multiple versions of pip-accel) but then I would have to introduce a new configuration option, otherwise everyone who has configured pip-accel to store its source index in a non-default location could still be bitten by compatibility issues. For now I've decided to keep using the same directory for the local source distribution index and to keep cleaning up broken symbolic links. This enables cooperating between old and new versions of pip-accel and avoids trashing user's local source distribution indexes. The main disadvantage is that pip-accel is still required to clean up broken symbolic links... """ cleanup_timer = Timer() cleanup_counter = 0 for entry in os.listdir(self.config.source_index): pathname = os.path.join(self.config.source_index, entry) if os.path.islink(pathname) and not os.path.exists(pathname): logger.warn("Cleaning up broken symbolic link: %s", pathname) os.unlink(pathname) cleanup_counter += 1 logger.debug("Cleaned up %i broken symbolic links from source index in %s.", cleanup_counter, cleanup_timer)
python
def clean_source_index(self): cleanup_timer = Timer() cleanup_counter = 0 for entry in os.listdir(self.config.source_index): pathname = os.path.join(self.config.source_index, entry) if os.path.islink(pathname) and not os.path.exists(pathname): logger.warn("Cleaning up broken symbolic link: %s", pathname) os.unlink(pathname) cleanup_counter += 1 logger.debug("Cleaned up %i broken symbolic links from source index in %s.", cleanup_counter, cleanup_timer)
[ "def", "clean_source_index", "(", "self", ")", ":", "cleanup_timer", "=", "Timer", "(", ")", "cleanup_counter", "=", "0", "for", "entry", "in", "os", ".", "listdir", "(", "self", ".", "config", ".", "source_index", ")", ":", "pathname", "=", "os", ".", ...
Cleanup broken symbolic links in the local source distribution index. The purpose of this method requires some context to understand. Let me preface this by stating that I realize I'm probably overcomplicating things, but I like to preserve forward / backward compatibility when possible and I don't feel like dropping everyone's locally cached source distribution archives without a good reason to do so. With that out of the way: - Versions of pip-accel based on pip 1.4.x maintained a local source distribution index based on a directory containing symbolic links pointing directly into pip's download cache. When files were removed from pip's download cache, broken symbolic links remained in pip-accel's local source distribution index directory. This resulted in very confusing error messages. To avoid this :func:`clean_source_index()` cleaned up broken symbolic links whenever pip-accel was about to invoke pip. - More recent versions of pip (6.x) no longer support the same style of download cache that contains source distribution archives that can be re-used directly by pip-accel. To cope with the changes in pip 6.x new versions of pip-accel tell pip to download source distribution archives directly into the local source distribution index directory maintained by pip-accel. - It is very reasonable for users of pip-accel to have multiple versions of pip-accel installed on their system (imagine a dozen Python virtual environments that won't all be updated at the same time; this is the situation I always find myself in :-). These versions of pip-accel will be sharing the same local source distribution index directory. - All of this leads up to the local source distribution index directory containing a mixture of symbolic links and regular files with no obvious way to atomically and gracefully upgrade the local source distribution index directory while avoiding fights between old and new versions of pip-accel :-). - I could of course switch to storing the new local source distribution index in a differently named directory (avoiding potential conflicts between multiple versions of pip-accel) but then I would have to introduce a new configuration option, otherwise everyone who has configured pip-accel to store its source index in a non-default location could still be bitten by compatibility issues. For now I've decided to keep using the same directory for the local source distribution index and to keep cleaning up broken symbolic links. This enables cooperating between old and new versions of pip-accel and avoids trashing user's local source distribution indexes. The main disadvantage is that pip-accel is still required to clean up broken symbolic links...
[ "Cleanup", "broken", "symbolic", "links", "in", "the", "local", "source", "distribution", "index", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L151-L213
6,702
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.install_from_arguments
def install_from_arguments(self, arguments, **kw): """ Download, unpack, build and install the specified requirements. This function is a simple wrapper for :func:`get_requirements()`, :func:`install_requirements()` and :func:`cleanup_temporary_directories()` that implements the default behavior of the pip accelerator. If you're extending or embedding pip-accel you may want to call the underlying methods instead. If the requirement set includes wheels and ``setuptools >= 0.8`` is not yet installed, it will be added to the requirement set and installed together with the other requirement(s) in order to enable the usage of distributions installed from wheels (their metadata is different). :param arguments: The command line arguments to ``pip install ..`` (a list of strings). :param kw: Any keyword arguments are passed on to :func:`install_requirements()`. :returns: The result of :func:`install_requirements()`. """ try: requirements = self.get_requirements(arguments, use_wheels=self.arguments_allow_wheels(arguments)) have_wheels = any(req.is_wheel for req in requirements) if have_wheels and not self.setuptools_supports_wheels(): logger.info("Preparing to upgrade to setuptools >= 0.8 to enable wheel support ..") requirements.extend(self.get_requirements(['setuptools >= 0.8'])) if requirements: if '--user' in arguments: from site import USER_BASE kw.setdefault('prefix', USER_BASE) return self.install_requirements(requirements, **kw) else: logger.info("Nothing to do! (requirements already installed)") return 0 finally: self.cleanup_temporary_directories()
python
def install_from_arguments(self, arguments, **kw): try: requirements = self.get_requirements(arguments, use_wheels=self.arguments_allow_wheels(arguments)) have_wheels = any(req.is_wheel for req in requirements) if have_wheels and not self.setuptools_supports_wheels(): logger.info("Preparing to upgrade to setuptools >= 0.8 to enable wheel support ..") requirements.extend(self.get_requirements(['setuptools >= 0.8'])) if requirements: if '--user' in arguments: from site import USER_BASE kw.setdefault('prefix', USER_BASE) return self.install_requirements(requirements, **kw) else: logger.info("Nothing to do! (requirements already installed)") return 0 finally: self.cleanup_temporary_directories()
[ "def", "install_from_arguments", "(", "self", ",", "arguments", ",", "*", "*", "kw", ")", ":", "try", ":", "requirements", "=", "self", ".", "get_requirements", "(", "arguments", ",", "use_wheels", "=", "self", ".", "arguments_allow_wheels", "(", "arguments", ...
Download, unpack, build and install the specified requirements. This function is a simple wrapper for :func:`get_requirements()`, :func:`install_requirements()` and :func:`cleanup_temporary_directories()` that implements the default behavior of the pip accelerator. If you're extending or embedding pip-accel you may want to call the underlying methods instead. If the requirement set includes wheels and ``setuptools >= 0.8`` is not yet installed, it will be added to the requirement set and installed together with the other requirement(s) in order to enable the usage of distributions installed from wheels (their metadata is different). :param arguments: The command line arguments to ``pip install ..`` (a list of strings). :param kw: Any keyword arguments are passed on to :func:`install_requirements()`. :returns: The result of :func:`install_requirements()`.
[ "Download", "unpack", "build", "and", "install", "the", "specified", "requirements", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L215-L251
6,703
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.get_requirements
def get_requirements(self, arguments, max_retries=None, use_wheels=False): """ Use pip to download and unpack the requested source distribution archives. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param max_retries: The maximum number of times that pip will be asked to download distribution archives (this helps to deal with intermittent failures). If this is :data:`None` then :attr:`~.Config.max_retries` is used. :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). .. warning:: Requirements which are already installed are not included in the result. If this breaks your use case consider using pip's ``--ignore-installed`` option. """ arguments = self.decorate_arguments(arguments) # Demote hash sum mismatch log messages from CRITICAL to DEBUG (hiding # implementation details from users unless they want to see them). with DownloadLogFilter(): with SetupRequiresPatch(self.config, self.eggs_links): # Use a new build directory for each run of get_requirements(). self.create_build_directory() # Check whether -U or --upgrade was given. if any(match_option(a, '-U', '--upgrade') for a in arguments): logger.info("Checking index(es) for new version (-U or --upgrade was given) ..") else: # If -U or --upgrade wasn't given and all requirements can be # satisfied using the archives in pip-accel's local source # index we don't need pip to connect to PyPI looking for new # versions (that will just slow us down). try: return self.unpack_source_dists(arguments, use_wheels=use_wheels) except DistributionNotFound: logger.info("We don't have all distribution archives yet!") # Get the maximum number of retries from the configuration if the # caller didn't specify a preference. if max_retries is None: max_retries = self.config.max_retries # If not all requirements are available locally we use pip to # download the missing source distribution archives from PyPI (we # retry a couple of times in case pip reports recoverable # errors). for i in range(max_retries): try: return self.download_source_dists(arguments, use_wheels=use_wheels) except Exception as e: if i + 1 < max_retries: # On all but the last iteration we swallow exceptions # during downloading. logger.warning("pip raised exception while downloading distributions: %s", e) else: # On the last iteration we don't swallow exceptions # during downloading because the error reported by pip # is the most sensible error for us to report. raise logger.info("Retrying after pip failed (%i/%i) ..", i + 1, max_retries)
python
def get_requirements(self, arguments, max_retries=None, use_wheels=False): arguments = self.decorate_arguments(arguments) # Demote hash sum mismatch log messages from CRITICAL to DEBUG (hiding # implementation details from users unless they want to see them). with DownloadLogFilter(): with SetupRequiresPatch(self.config, self.eggs_links): # Use a new build directory for each run of get_requirements(). self.create_build_directory() # Check whether -U or --upgrade was given. if any(match_option(a, '-U', '--upgrade') for a in arguments): logger.info("Checking index(es) for new version (-U or --upgrade was given) ..") else: # If -U or --upgrade wasn't given and all requirements can be # satisfied using the archives in pip-accel's local source # index we don't need pip to connect to PyPI looking for new # versions (that will just slow us down). try: return self.unpack_source_dists(arguments, use_wheels=use_wheels) except DistributionNotFound: logger.info("We don't have all distribution archives yet!") # Get the maximum number of retries from the configuration if the # caller didn't specify a preference. if max_retries is None: max_retries = self.config.max_retries # If not all requirements are available locally we use pip to # download the missing source distribution archives from PyPI (we # retry a couple of times in case pip reports recoverable # errors). for i in range(max_retries): try: return self.download_source_dists(arguments, use_wheels=use_wheels) except Exception as e: if i + 1 < max_retries: # On all but the last iteration we swallow exceptions # during downloading. logger.warning("pip raised exception while downloading distributions: %s", e) else: # On the last iteration we don't swallow exceptions # during downloading because the error reported by pip # is the most sensible error for us to report. raise logger.info("Retrying after pip failed (%i/%i) ..", i + 1, max_retries)
[ "def", "get_requirements", "(", "self", ",", "arguments", ",", "max_retries", "=", "None", ",", "use_wheels", "=", "False", ")", ":", "arguments", "=", "self", ".", "decorate_arguments", "(", "arguments", ")", "# Demote hash sum mismatch log messages from CRITICAL to ...
Use pip to download and unpack the requested source distribution archives. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param max_retries: The maximum number of times that pip will be asked to download distribution archives (this helps to deal with intermittent failures). If this is :data:`None` then :attr:`~.Config.max_retries` is used. :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). .. warning:: Requirements which are already installed are not included in the result. If this breaks your use case consider using pip's ``--ignore-installed`` option.
[ "Use", "pip", "to", "download", "and", "unpack", "the", "requested", "source", "distribution", "archives", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L262-L321
6,704
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.unpack_source_dists
def unpack_source_dists(self, arguments, use_wheels=False): """ Find and unpack local source distributions and discover their metadata. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). :returns: A list of :class:`pip_accel.req.Requirement` objects. :raises: Any exceptions raised by pip, for example :exc:`pip.exceptions.DistributionNotFound` when not all requirements can be satisfied. This function checks whether there are local source distributions available for all requirements, unpacks the source distribution archives and finds the names and versions of the requirements. By using the ``pip install --download`` command we avoid reimplementing the following pip features: - Parsing of ``requirements.txt`` (including recursive parsing). - Resolution of possibly conflicting pinned requirements. - Unpacking source distributions in multiple formats. - Finding the name & version of a given source distribution. """ unpack_timer = Timer() logger.info("Unpacking distribution(s) ..") with PatchedAttribute(pip_install_module, 'PackageFinder', CustomPackageFinder): requirements = self.get_pip_requirement_set(arguments, use_remote_index=False, use_wheels=use_wheels) logger.info("Finished unpacking %s in %s.", pluralize(len(requirements), "distribution"), unpack_timer) return requirements
python
def unpack_source_dists(self, arguments, use_wheels=False): unpack_timer = Timer() logger.info("Unpacking distribution(s) ..") with PatchedAttribute(pip_install_module, 'PackageFinder', CustomPackageFinder): requirements = self.get_pip_requirement_set(arguments, use_remote_index=False, use_wheels=use_wheels) logger.info("Finished unpacking %s in %s.", pluralize(len(requirements), "distribution"), unpack_timer) return requirements
[ "def", "unpack_source_dists", "(", "self", ",", "arguments", ",", "use_wheels", "=", "False", ")", ":", "unpack_timer", "=", "Timer", "(", ")", "logger", ".", "info", "(", "\"Unpacking distribution(s) ..\"", ")", "with", "PatchedAttribute", "(", "pip_install_modul...
Find and unpack local source distributions and discover their metadata. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). :returns: A list of :class:`pip_accel.req.Requirement` objects. :raises: Any exceptions raised by pip, for example :exc:`pip.exceptions.DistributionNotFound` when not all requirements can be satisfied. This function checks whether there are local source distributions available for all requirements, unpacks the source distribution archives and finds the names and versions of the requirements. By using the ``pip install --download`` command we avoid reimplementing the following pip features: - Parsing of ``requirements.txt`` (including recursive parsing). - Resolution of possibly conflicting pinned requirements. - Unpacking source distributions in multiple formats. - Finding the name & version of a given source distribution.
[ "Find", "and", "unpack", "local", "source", "distributions", "and", "discover", "their", "metadata", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L365-L395
6,705
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.download_source_dists
def download_source_dists(self, arguments, use_wheels=False): """ Download missing source distributions. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). :raises: Any exceptions raised by pip. """ download_timer = Timer() logger.info("Downloading missing distribution(s) ..") requirements = self.get_pip_requirement_set(arguments, use_remote_index=True, use_wheels=use_wheels) logger.info("Finished downloading distribution(s) in %s.", download_timer) return requirements
python
def download_source_dists(self, arguments, use_wheels=False): download_timer = Timer() logger.info("Downloading missing distribution(s) ..") requirements = self.get_pip_requirement_set(arguments, use_remote_index=True, use_wheels=use_wheels) logger.info("Finished downloading distribution(s) in %s.", download_timer) return requirements
[ "def", "download_source_dists", "(", "self", ",", "arguments", ",", "use_wheels", "=", "False", ")", ":", "download_timer", "=", "Timer", "(", ")", "logger", ".", "info", "(", "\"Downloading missing distribution(s) ..\"", ")", "requirements", "=", "self", ".", "...
Download missing source distributions. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_wheels: Whether pip and pip-accel are allowed to use wheels_ (:data:`False` by default for backwards compatibility with callers that use pip-accel as a Python API). :raises: Any exceptions raised by pip.
[ "Download", "missing", "source", "distributions", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L397-L412
6,706
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.transform_pip_requirement_set
def transform_pip_requirement_set(self, requirement_set): """ Transform pip's requirement set into one that `pip-accel` can work with. :param requirement_set: The :class:`pip.req.RequirementSet` object reported by pip. :returns: A list of :class:`pip_accel.req.Requirement` objects. This function converts the :class:`pip.req.RequirementSet` object reported by pip into a list of :class:`pip_accel.req.Requirement` objects. """ filtered_requirements = [] for requirement in requirement_set.requirements.values(): # The `satisfied_by' property is set by pip when a requirement is # already satisfied (i.e. a version of the package that satisfies # the requirement is already installed) and -I, --ignore-installed # is not used. We filter out these requirements because pip never # unpacks distributions for these requirements, so pip-accel can't # do anything useful with such requirements. if requirement.satisfied_by: continue # The `constraint' property marks requirement objects that # constrain the acceptable version(s) of another requirement but # don't define a requirement themselves, so we filter them out. if requirement.constraint: continue # All other requirements are reported to callers. filtered_requirements.append(requirement) self.reported_requirements.append(requirement) return sorted([Requirement(self.config, r) for r in filtered_requirements], key=lambda r: r.name.lower())
python
def transform_pip_requirement_set(self, requirement_set): filtered_requirements = [] for requirement in requirement_set.requirements.values(): # The `satisfied_by' property is set by pip when a requirement is # already satisfied (i.e. a version of the package that satisfies # the requirement is already installed) and -I, --ignore-installed # is not used. We filter out these requirements because pip never # unpacks distributions for these requirements, so pip-accel can't # do anything useful with such requirements. if requirement.satisfied_by: continue # The `constraint' property marks requirement objects that # constrain the acceptable version(s) of another requirement but # don't define a requirement themselves, so we filter them out. if requirement.constraint: continue # All other requirements are reported to callers. filtered_requirements.append(requirement) self.reported_requirements.append(requirement) return sorted([Requirement(self.config, r) for r in filtered_requirements], key=lambda r: r.name.lower())
[ "def", "transform_pip_requirement_set", "(", "self", ",", "requirement_set", ")", ":", "filtered_requirements", "=", "[", "]", "for", "requirement", "in", "requirement_set", ".", "requirements", ".", "values", "(", ")", ":", "# The `satisfied_by' property is set by pip ...
Transform pip's requirement set into one that `pip-accel` can work with. :param requirement_set: The :class:`pip.req.RequirementSet` object reported by pip. :returns: A list of :class:`pip_accel.req.Requirement` objects. This function converts the :class:`pip.req.RequirementSet` object reported by pip into a list of :class:`pip_accel.req.Requirement` objects.
[ "Transform", "pip", "s", "requirement", "set", "into", "one", "that", "pip", "-", "accel", "can", "work", "with", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L508-L539
6,707
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.clear_build_directory
def clear_build_directory(self): """Clear the build directory where pip unpacks the source distribution archives.""" stat = os.stat(self.build_directory) shutil.rmtree(self.build_directory) os.makedirs(self.build_directory, stat.st_mode)
python
def clear_build_directory(self): stat = os.stat(self.build_directory) shutil.rmtree(self.build_directory) os.makedirs(self.build_directory, stat.st_mode)
[ "def", "clear_build_directory", "(", "self", ")", ":", "stat", "=", "os", ".", "stat", "(", "self", ".", "build_directory", ")", "shutil", ".", "rmtree", "(", "self", ".", "build_directory", ")", "os", ".", "makedirs", "(", "self", ".", "build_directory", ...
Clear the build directory where pip unpacks the source distribution archives.
[ "Clear", "the", "build", "directory", "where", "pip", "unpacks", "the", "source", "distribution", "archives", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L612-L616
6,708
paylogic/pip-accel
pip_accel/__init__.py
PipAccelerator.cleanup_temporary_directories
def cleanup_temporary_directories(self): """Delete the build directories and any temporary directories created by pip.""" while self.build_directories: shutil.rmtree(self.build_directories.pop()) for requirement in self.reported_requirements: requirement.remove_temporary_source() while self.eggs_links: symbolic_link = self.eggs_links.pop() if os.path.islink(symbolic_link): os.unlink(symbolic_link)
python
def cleanup_temporary_directories(self): while self.build_directories: shutil.rmtree(self.build_directories.pop()) for requirement in self.reported_requirements: requirement.remove_temporary_source() while self.eggs_links: symbolic_link = self.eggs_links.pop() if os.path.islink(symbolic_link): os.unlink(symbolic_link)
[ "def", "cleanup_temporary_directories", "(", "self", ")", ":", "while", "self", ".", "build_directories", ":", "shutil", ".", "rmtree", "(", "self", ".", "build_directories", ".", "pop", "(", ")", ")", "for", "requirement", "in", "self", ".", "reported_require...
Delete the build directories and any temporary directories created by pip.
[ "Delete", "the", "build", "directories", "and", "any", "temporary", "directories", "created", "by", "pip", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L618-L627
6,709
paylogic/pip-accel
pip_accel/__init__.py
DownloadLogFilter.filter
def filter(self, record): """Change the severity of selected log records.""" if isinstance(record.msg, basestring): message = record.msg.lower() if all(kw in message for kw in self.KEYWORDS): record.levelname = 'DEBUG' record.levelno = logging.DEBUG return 1
python
def filter(self, record): if isinstance(record.msg, basestring): message = record.msg.lower() if all(kw in message for kw in self.KEYWORDS): record.levelname = 'DEBUG' record.levelno = logging.DEBUG return 1
[ "def", "filter", "(", "self", ",", "record", ")", ":", "if", "isinstance", "(", "record", ".", "msg", ",", "basestring", ")", ":", "message", "=", "record", ".", "msg", ".", "lower", "(", ")", "if", "all", "(", "kw", "in", "message", "for", "kw", ...
Change the severity of selected log records.
[ "Change", "the", "severity", "of", "selected", "log", "records", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L662-L669
6,710
paylogic/pip-accel
pip_accel/cli.py
main
def main(): """The command line interface for the ``pip-accel`` program.""" arguments = sys.argv[1:] # If no arguments are given, the help text of pip-accel is printed. if not arguments: usage() sys.exit(0) # If no install subcommand is given we pass the command line straight # to pip without any changes and exit immediately afterwards. if 'install' not in arguments: # This will not return. os.execvp('pip', ['pip'] + arguments) else: arguments = [arg for arg in arguments if arg != 'install'] config = Config() # Initialize logging output. coloredlogs.install( fmt=config.log_format, level=config.log_verbosity, ) # Adjust verbosity based on -v, -q, --verbose, --quiet options. for argument in list(arguments): if match_option(argument, '-v', '--verbose'): coloredlogs.increase_verbosity() elif match_option(argument, '-q', '--quiet'): coloredlogs.decrease_verbosity() # Perform the requested action(s). try: accelerator = PipAccelerator(config) accelerator.install_from_arguments(arguments) except NothingToDoError as e: # Don't print a traceback for this (it's not very user friendly) and # exit with status zero to stay compatible with pip. For more details # please refer to https://github.com/paylogic/pip-accel/issues/47. logger.warning("%s", e) sys.exit(0) except Exception: logger.exception("Caught unhandled exception!") sys.exit(1)
python
def main(): arguments = sys.argv[1:] # If no arguments are given, the help text of pip-accel is printed. if not arguments: usage() sys.exit(0) # If no install subcommand is given we pass the command line straight # to pip without any changes and exit immediately afterwards. if 'install' not in arguments: # This will not return. os.execvp('pip', ['pip'] + arguments) else: arguments = [arg for arg in arguments if arg != 'install'] config = Config() # Initialize logging output. coloredlogs.install( fmt=config.log_format, level=config.log_verbosity, ) # Adjust verbosity based on -v, -q, --verbose, --quiet options. for argument in list(arguments): if match_option(argument, '-v', '--verbose'): coloredlogs.increase_verbosity() elif match_option(argument, '-q', '--quiet'): coloredlogs.decrease_verbosity() # Perform the requested action(s). try: accelerator = PipAccelerator(config) accelerator.install_from_arguments(arguments) except NothingToDoError as e: # Don't print a traceback for this (it's not very user friendly) and # exit with status zero to stay compatible with pip. For more details # please refer to https://github.com/paylogic/pip-accel/issues/47. logger.warning("%s", e) sys.exit(0) except Exception: logger.exception("Caught unhandled exception!") sys.exit(1)
[ "def", "main", "(", ")", ":", "arguments", "=", "sys", ".", "argv", "[", "1", ":", "]", "# If no arguments are given, the help text of pip-accel is printed.", "if", "not", "arguments", ":", "usage", "(", ")", "sys", ".", "exit", "(", "0", ")", "# If no install...
The command line interface for the ``pip-accel`` program.
[ "The", "command", "line", "interface", "for", "the", "pip", "-", "accel", "program", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/cli.py#L28-L66
6,711
paylogic/pip-accel
pip_accel/caches/local.py
LocalCacheBackend.get
def get(self, filename): """ Check if a distribution archive exists in the local cache. :param filename: The filename of the distribution archive (a string). :returns: The pathname of a distribution archive on the local file system or :data:`None`. """ pathname = os.path.join(self.config.binary_cache, filename) if os.path.isfile(pathname): logger.debug("Distribution archive exists in local cache (%s).", pathname) return pathname else: logger.debug("Distribution archive doesn't exist in local cache (%s).", pathname) return None
python
def get(self, filename): pathname = os.path.join(self.config.binary_cache, filename) if os.path.isfile(pathname): logger.debug("Distribution archive exists in local cache (%s).", pathname) return pathname else: logger.debug("Distribution archive doesn't exist in local cache (%s).", pathname) return None
[ "def", "get", "(", "self", ",", "filename", ")", ":", "pathname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "config", ".", "binary_cache", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "pathname", ")", ":", "logger...
Check if a distribution archive exists in the local cache. :param filename: The filename of the distribution archive (a string). :returns: The pathname of a distribution archive on the local file system or :data:`None`.
[ "Check", "if", "a", "distribution", "archive", "exists", "in", "the", "local", "cache", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/caches/local.py#L40-L54
6,712
paylogic/pip-accel
pip_accel/caches/local.py
LocalCacheBackend.put
def put(self, filename, handle): """ Store a distribution archive in the local cache. :param filename: The filename of the distribution archive (a string). :param handle: A file-like object that provides access to the distribution archive. """ file_in_cache = os.path.join(self.config.binary_cache, filename) logger.debug("Storing distribution archive in local cache: %s", file_in_cache) makedirs(os.path.dirname(file_in_cache)) # Stream the contents of the distribution archive to a temporary file # to avoid race conditions (e.g. partial reads) between multiple # processes that are using the local cache at the same time. with AtomicReplace(file_in_cache) as temporary_file: with open(temporary_file, 'wb') as temporary_file_handle: shutil.copyfileobj(handle, temporary_file_handle) logger.debug("Finished caching distribution archive in local cache.")
python
def put(self, filename, handle): file_in_cache = os.path.join(self.config.binary_cache, filename) logger.debug("Storing distribution archive in local cache: %s", file_in_cache) makedirs(os.path.dirname(file_in_cache)) # Stream the contents of the distribution archive to a temporary file # to avoid race conditions (e.g. partial reads) between multiple # processes that are using the local cache at the same time. with AtomicReplace(file_in_cache) as temporary_file: with open(temporary_file, 'wb') as temporary_file_handle: shutil.copyfileobj(handle, temporary_file_handle) logger.debug("Finished caching distribution archive in local cache.")
[ "def", "put", "(", "self", ",", "filename", ",", "handle", ")", ":", "file_in_cache", "=", "os", ".", "path", ".", "join", "(", "self", ".", "config", ".", "binary_cache", ",", "filename", ")", "logger", ".", "debug", "(", "\"Storing distribution archive i...
Store a distribution archive in the local cache. :param filename: The filename of the distribution archive (a string). :param handle: A file-like object that provides access to the distribution archive.
[ "Store", "a", "distribution", "archive", "in", "the", "local", "cache", "." ]
ccad1b784927a322d996db593403b1d2d2e22666
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/caches/local.py#L56-L73
6,713
fle/django-multi-email-field
multi_email_field/forms.py
MultiEmailField.to_python
def to_python(self, value): "Normalize data to a list of strings." # Return None if no input was given. if not value: return [] return [v.strip() for v in value.splitlines() if v != ""]
python
def to_python(self, value): "Normalize data to a list of strings." # Return None if no input was given. if not value: return [] return [v.strip() for v in value.splitlines() if v != ""]
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "# Return None if no input was given.", "if", "not", "value", ":", "return", "[", "]", "return", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ".", "splitlines", "(", ")", "if", "v...
Normalize data to a list of strings.
[ "Normalize", "data", "to", "a", "list", "of", "strings", "." ]
5488ab91053b8f7ed6c36a07c28d56efe85b1daf
https://github.com/fle/django-multi-email-field/blob/5488ab91053b8f7ed6c36a07c28d56efe85b1daf/multi_email_field/forms.py#L14-L19
6,714
fle/django-multi-email-field
multi_email_field/widgets.py
MultiEmailWidget.prep_value
def prep_value(self, value): """ Prepare value before effectively render widget """ if value in MULTI_EMAIL_FIELD_EMPTY_VALUES: return "" elif isinstance(value, six.string_types): return value elif isinstance(value, list): return "\n".join(value) raise ValidationError('Invalid format.')
python
def prep_value(self, value): if value in MULTI_EMAIL_FIELD_EMPTY_VALUES: return "" elif isinstance(value, six.string_types): return value elif isinstance(value, list): return "\n".join(value) raise ValidationError('Invalid format.')
[ "def", "prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "in", "MULTI_EMAIL_FIELD_EMPTY_VALUES", ":", "return", "\"\"", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "elif", "isinstance", "(...
Prepare value before effectively render widget
[ "Prepare", "value", "before", "effectively", "render", "widget" ]
5488ab91053b8f7ed6c36a07c28d56efe85b1daf
https://github.com/fle/django-multi-email-field/blob/5488ab91053b8f7ed6c36a07c28d56efe85b1daf/multi_email_field/widgets.py#L14-L22
6,715
ElementAI/greensim
greensim/__init__.py
tagged
def tagged(*tags: Tags) -> Callable: global GREENSIM_TAG_ATTRIBUTE """ Decorator for adding a label to the process. These labels are applied to any child Processes produced by event """ def hook(event: Callable): def wrapper(*args, **kwargs): event(*args, **kwargs) setattr(wrapper, GREENSIM_TAG_ATTRIBUTE, tags) return wrapper return hook
python
def tagged(*tags: Tags) -> Callable: global GREENSIM_TAG_ATTRIBUTE def hook(event: Callable): def wrapper(*args, **kwargs): event(*args, **kwargs) setattr(wrapper, GREENSIM_TAG_ATTRIBUTE, tags) return wrapper return hook
[ "def", "tagged", "(", "*", "tags", ":", "Tags", ")", "->", "Callable", ":", "global", "GREENSIM_TAG_ATTRIBUTE", "def", "hook", "(", "event", ":", "Callable", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "event", "(...
Decorator for adding a label to the process. These labels are applied to any child Processes produced by event
[ "Decorator", "for", "adding", "a", "label", "to", "the", "process", ".", "These", "labels", "are", "applied", "to", "any", "child", "Processes", "produced", "by", "event" ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L640-L651
6,716
ElementAI/greensim
greensim/__init__.py
select
def select(*signals: Signal, **kwargs) -> List[Signal]: """ Allows the current process to wait for multiple concurrent signals. Waits until one of the signals turns on, at which point this signal is returned. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and stops waiting on the set of :py:class:`Signal`s. In such a situation, a :py:class:`Timeout` exception is raised on the process. """ class CleanUp(Interrupt): pass timeout = kwargs.get("timeout", None) if not isinstance(timeout, (float, int, type(None))): raise ValueError("The timeout keyword parameter can be either None or a number.") def wait_one(signal: Signal, common: Signal) -> None: try: signal.wait() common.turn_on() except CleanUp: pass # We simply sets up multiple sub-processes respectively waiting for one of the signals. Once one of them has fired, # the others will all run no-op eventually, so no need for any explicit clean-up. common = Signal(name=local.name + "-selector").turn_off() if _logger is not None: _log(INFO, "select", "select", "select", signals=[sig.name for sig in signals]) procs = [] for signal in signals: procs.append(add(wait_one, signal, common)) try: common.wait(timeout) finally: for proc in procs: # Clean up the support processes. proc.interrupt(CleanUp()) return [signal for signal in signals if signal.is_on]
python
def select(*signals: Signal, **kwargs) -> List[Signal]: class CleanUp(Interrupt): pass timeout = kwargs.get("timeout", None) if not isinstance(timeout, (float, int, type(None))): raise ValueError("The timeout keyword parameter can be either None or a number.") def wait_one(signal: Signal, common: Signal) -> None: try: signal.wait() common.turn_on() except CleanUp: pass # We simply sets up multiple sub-processes respectively waiting for one of the signals. Once one of them has fired, # the others will all run no-op eventually, so no need for any explicit clean-up. common = Signal(name=local.name + "-selector").turn_off() if _logger is not None: _log(INFO, "select", "select", "select", signals=[sig.name for sig in signals]) procs = [] for signal in signals: procs.append(add(wait_one, signal, common)) try: common.wait(timeout) finally: for proc in procs: # Clean up the support processes. proc.interrupt(CleanUp()) return [signal for signal in signals if signal.is_on]
[ "def", "select", "(", "*", "signals", ":", "Signal", ",", "*", "*", "kwargs", ")", "->", "List", "[", "Signal", "]", ":", "class", "CleanUp", "(", "Interrupt", ")", ":", "pass", "timeout", "=", "kwargs", ".", "get", "(", "\"timeout\"", ",", "None", ...
Allows the current process to wait for multiple concurrent signals. Waits until one of the signals turns on, at which point this signal is returned. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and stops waiting on the set of :py:class:`Signal`s. In such a situation, a :py:class:`Timeout` exception is raised on the process.
[ "Allows", "the", "current", "process", "to", "wait", "for", "multiple", "concurrent", "signals", ".", "Waits", "until", "one", "of", "the", "signals", "turns", "on", "at", "which", "point", "this", "signal", "is", "returned", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L834-L873
6,717
ElementAI/greensim
greensim/__init__.py
Simulator.add_in
def add_in(self, delay: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': """ Adds a process to the simulation, which is made to start after the given delay in simulated time. See method add() for more details. """ process = Process(self, fn_process, self._gr) if _logger is not None: self._log(INFO, "add", __now=self.now(), fn=fn_process, args=args, kwargs=kwargs) self._schedule(delay, process.switch, *args, **kwargs) return process
python
def add_in(self, delay: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': process = Process(self, fn_process, self._gr) if _logger is not None: self._log(INFO, "add", __now=self.now(), fn=fn_process, args=args, kwargs=kwargs) self._schedule(delay, process.switch, *args, **kwargs) return process
[ "def", "add_in", "(", "self", ",", "delay", ":", "float", ",", "fn_process", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "'Process'", ":", "process", "=", "Process", "(", "self", ",", "fn_process", ...
Adds a process to the simulation, which is made to start after the given delay in simulated time. See method add() for more details.
[ "Adds", "a", "process", "to", "the", "simulation", "which", "is", "made", "to", "start", "after", "the", "given", "delay", "in", "simulated", "time", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L289-L299
6,718
ElementAI/greensim
greensim/__init__.py
Simulator.add_at
def add_at(self, moment: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': """ Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note that times in the past when compared to the current moment on the simulated clock are forbidden. See method add() for more details. """ delay = moment - self.now() if delay < 0.0: raise ValueError( f"The given moment to start the process ({moment:f}) is in the past (now is {self.now():f})." ) return self.add_in(delay, fn_process, *args, **kwargs)
python
def add_at(self, moment: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': delay = moment - self.now() if delay < 0.0: raise ValueError( f"The given moment to start the process ({moment:f}) is in the past (now is {self.now():f})." ) return self.add_in(delay, fn_process, *args, **kwargs)
[ "def", "add_at", "(", "self", ",", "moment", ":", "float", ",", "fn_process", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "'Process'", ":", "delay", "=", "moment", "-", "self", ".", "now", "(", "...
Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note that times in the past when compared to the current moment on the simulated clock are forbidden. See method add() for more details.
[ "Adds", "a", "process", "to", "the", "simulation", "which", "is", "made", "to", "start", "at", "the", "given", "exact", "time", "on", "the", "simulated", "clock", ".", "Note", "that", "times", "in", "the", "past", "when", "compared", "to", "the", "curren...
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L301-L313
6,719
ElementAI/greensim
greensim/__init__.py
Simulator.step
def step(self) -> None: """ Runs a single event of the simulation. """ event = heappop(self._events) self._ts_now = event.timestamp or self._ts_now event.execute(self)
python
def step(self) -> None: event = heappop(self._events) self._ts_now = event.timestamp or self._ts_now event.execute(self)
[ "def", "step", "(", "self", ")", "->", "None", ":", "event", "=", "heappop", "(", "self", ".", "_events", ")", "self", ".", "_ts_now", "=", "event", ".", "timestamp", "or", "self", ".", "_ts_now", "event", ".", "execute", "(", "self", ")" ]
Runs a single event of the simulation.
[ "Runs", "a", "single", "event", "of", "the", "simulation", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L348-L354
6,720
ElementAI/greensim
greensim/__init__.py
Simulator.stop
def stop(self) -> None: """ Stops the running simulation once the current event is done executing. """ if self.is_running: if _logger is not None: self._log(INFO, "stop", __now=self.now()) self._is_running = False
python
def stop(self) -> None: if self.is_running: if _logger is not None: self._log(INFO, "stop", __now=self.now()) self._is_running = False
[ "def", "stop", "(", "self", ")", "->", "None", ":", "if", "self", ".", "is_running", ":", "if", "_logger", "is", "not", "None", ":", "self", ".", "_log", "(", "INFO", ",", "\"stop\"", ",", "__now", "=", "self", ".", "now", "(", ")", ")", "self", ...
Stops the running simulation once the current event is done executing.
[ "Stops", "the", "running", "simulation", "once", "the", "current", "event", "is", "done", "executing", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L356-L363
6,721
ElementAI/greensim
greensim/__init__.py
Simulator._clear
def _clear(self) -> None: """ Resets the internal state of the simulator, and sets the simulated clock back to 0.0. This discards all outstanding events and tears down hanging process instances. """ for _, event, _, _ in self.events(): if hasattr(event, "__self__") and isinstance(event.__self__, Process): # type: ignore event.__self__.throw() # type: ignore self._events.clear() self._ts_now = 0.0
python
def _clear(self) -> None: for _, event, _, _ in self.events(): if hasattr(event, "__self__") and isinstance(event.__self__, Process): # type: ignore event.__self__.throw() # type: ignore self._events.clear() self._ts_now = 0.0
[ "def", "_clear", "(", "self", ")", "->", "None", ":", "for", "_", ",", "event", ",", "_", ",", "_", "in", "self", ".", "events", "(", ")", ":", "if", "hasattr", "(", "event", ",", "\"__self__\"", ")", "and", "isinstance", "(", "event", ".", "__se...
Resets the internal state of the simulator, and sets the simulated clock back to 0.0. This discards all outstanding events and tears down hanging process instances.
[ "Resets", "the", "internal", "state", "of", "the", "simulator", "and", "sets", "the", "simulated", "clock", "back", "to", "0", ".", "0", ".", "This", "discards", "all", "outstanding", "events", "and", "tears", "down", "hanging", "process", "instances", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L372-L381
6,722
ElementAI/greensim
greensim/__init__.py
Process.current
def current() -> 'Process': """ Returns the instance of the process that is executing at the current moment. """ curr = greenlet.getcurrent() if not isinstance(curr, Process): raise TypeError("Current greenlet does not correspond to a Process instance.") return cast(Process, greenlet.getcurrent())
python
def current() -> 'Process': curr = greenlet.getcurrent() if not isinstance(curr, Process): raise TypeError("Current greenlet does not correspond to a Process instance.") return cast(Process, greenlet.getcurrent())
[ "def", "current", "(", ")", "->", "'Process'", ":", "curr", "=", "greenlet", ".", "getcurrent", "(", ")", "if", "not", "isinstance", "(", "curr", ",", "Process", ")", ":", "raise", "TypeError", "(", "\"Current greenlet does not correspond to a Process instance.\""...
Returns the instance of the process that is executing at the current moment.
[ "Returns", "the", "instance", "of", "the", "process", "that", "is", "executing", "at", "the", "current", "moment", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L503-L510
6,723
ElementAI/greensim
greensim/__init__.py
Signal.turn_on
def turn_on(self) -> "Signal": """ Turns on the signal. If processes are waiting, they are all resumed. This may be invoked from any code. Remark that while processes are simultaneously resumed in simulated time, they are effectively resumed in the sequence corresponding to the queue discipline. Therefore, if one of the resumed processes turns the signal back off, remaining resumed processes join back the queue. If the queue discipline is not monotonic (for instance, if it bears a random component), then this toggling of the signal may reorder the processes. """ if _logger is not None: self._log(INFO, "turn-on") self._is_on = True while not self._queue.is_empty(): self._queue.pop() return self
python
def turn_on(self) -> "Signal": if _logger is not None: self._log(INFO, "turn-on") self._is_on = True while not self._queue.is_empty(): self._queue.pop() return self
[ "def", "turn_on", "(", "self", ")", "->", "\"Signal\"", ":", "if", "_logger", "is", "not", "None", ":", "self", ".", "_log", "(", "INFO", ",", "\"turn-on\"", ")", "self", ".", "_is_on", "=", "True", "while", "not", "self", ".", "_queue", ".", "is_emp...
Turns on the signal. If processes are waiting, they are all resumed. This may be invoked from any code. Remark that while processes are simultaneously resumed in simulated time, they are effectively resumed in the sequence corresponding to the queue discipline. Therefore, if one of the resumed processes turns the signal back off, remaining resumed processes join back the queue. If the queue discipline is not monotonic (for instance, if it bears a random component), then this toggling of the signal may reorder the processes.
[ "Turns", "on", "the", "signal", ".", "If", "processes", "are", "waiting", "they", "are", "all", "resumed", ".", "This", "may", "be", "invoked", "from", "any", "code", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L794-L808
6,724
ElementAI/greensim
greensim/__init__.py
Signal.turn_off
def turn_off(self) -> "Signal": """ Turns off the signal. This may be invoked from any code. """ if _logger is not None: self._log(INFO, "turn-off") self._is_on = False return self
python
def turn_off(self) -> "Signal": if _logger is not None: self._log(INFO, "turn-off") self._is_on = False return self
[ "def", "turn_off", "(", "self", ")", "->", "\"Signal\"", ":", "if", "_logger", "is", "not", "None", ":", "self", ".", "_log", "(", "INFO", ",", "\"turn-off\"", ")", "self", ".", "_is_on", "=", "False", "return", "self" ]
Turns off the signal. This may be invoked from any code.
[ "Turns", "off", "the", "signal", ".", "This", "may", "be", "invoked", "from", "any", "code", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L810-L817
6,725
ElementAI/greensim
greensim/__init__.py
Signal.wait
def wait(self, timeout: Optional[float] = None) -> None: """ Makes the current process wait for the signal. If it is closed, it will join the signal's queue. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and stops waiting for the :py:class:`Signal`. In such a situation, a :py:class:`Timeout` exception is raised on the process. """ if _logger is not None: self._log(INFO, "wait") while not self.is_on: self._queue.join(timeout)
python
def wait(self, timeout: Optional[float] = None) -> None: if _logger is not None: self._log(INFO, "wait") while not self.is_on: self._queue.join(timeout)
[ "def", "wait", "(", "self", ",", "timeout", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "None", ":", "if", "_logger", "is", "not", "None", ":", "self", ".", "_log", "(", "INFO", ",", "\"wait\"", ")", "while", "not", "self", ".", "...
Makes the current process wait for the signal. If it is closed, it will join the signal's queue. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and stops waiting for the :py:class:`Signal`. In such a situation, a :py:class:`Timeout` exception is raised on the process.
[ "Makes", "the", "current", "process", "wait", "for", "the", "signal", ".", "If", "it", "is", "closed", "it", "will", "join", "the", "signal", "s", "queue", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L819-L831
6,726
ElementAI/greensim
greensim/__init__.py
Resource.take
def take(self, num_instances: int = 1, timeout: Optional[float] = None) -> None: """ The current process reserves a certain number of instances. If there are not enough instances available, the process is made to join a queue. When this method returns, the process holds the instances it has requested to take. :param num_instances: Number of resource instances to take. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and leaves the queue forcibly. In such a situation, a :py:class:`Timeout` exception is raised on the process. """ if num_instances < 1: raise ValueError(f"Process must request at least 1 instance; here requested {num_instances}.") if num_instances > self.num_instances_total: raise ValueError( f"Process must request at most {self.num_instances_total} instances; here requested {num_instances}." ) if _logger is not None: self._log(INFO, "take", num_instances=num_instances, free=self.num_instances_free) proc = Process.current() if self._num_instances_free < num_instances: proc.local.__num_instances_required = num_instances try: self._waiting.join(timeout) finally: del proc.local.__num_instances_required self._num_instances_free -= num_instances if _logger is not None and proc in self._usage: self._log(WARNING, "take-again", already=self._usage[proc], more=num_instances) self._usage.setdefault(proc, 0) self._usage[proc] += num_instances
python
def take(self, num_instances: int = 1, timeout: Optional[float] = None) -> None: if num_instances < 1: raise ValueError(f"Process must request at least 1 instance; here requested {num_instances}.") if num_instances > self.num_instances_total: raise ValueError( f"Process must request at most {self.num_instances_total} instances; here requested {num_instances}." ) if _logger is not None: self._log(INFO, "take", num_instances=num_instances, free=self.num_instances_free) proc = Process.current() if self._num_instances_free < num_instances: proc.local.__num_instances_required = num_instances try: self._waiting.join(timeout) finally: del proc.local.__num_instances_required self._num_instances_free -= num_instances if _logger is not None and proc in self._usage: self._log(WARNING, "take-again", already=self._usage[proc], more=num_instances) self._usage.setdefault(proc, 0) self._usage[proc] += num_instances
[ "def", "take", "(", "self", ",", "num_instances", ":", "int", "=", "1", ",", "timeout", ":", "Optional", "[", "float", "]", "=", "None", ")", "->", "None", ":", "if", "num_instances", "<", "1", ":", "raise", "ValueError", "(", "f\"Process must request at...
The current process reserves a certain number of instances. If there are not enough instances available, the process is made to join a queue. When this method returns, the process holds the instances it has requested to take. :param num_instances: Number of resource instances to take. :param timeout: If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and leaves the queue forcibly. In such a situation, a :py:class:`Timeout` exception is raised on the process.
[ "The", "current", "process", "reserves", "a", "certain", "number", "of", "instances", ".", "If", "there", "are", "not", "enough", "instances", "available", "the", "process", "is", "made", "to", "join", "a", "queue", ".", "When", "this", "method", "returns", ...
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L912-L944
6,727
ElementAI/greensim
greensim/__init__.py
Resource.release
def release(self, num_instances: int = 1) -> None: """ The current process releases instances it has previously taken. It may thus release less than it has taken. These released instances become free. If the total number of free instances then satisfy the request of the top process of the waiting queue, it is popped off the queue and resumed. """ proc = Process.current() error_format = "Process %s holds %s instances, but requests to release more (%s)" if self._usage.get(proc, 0) > 0: if num_instances > self._usage[proc]: raise ValueError( error_format % (proc.local.name, self._usage[proc], num_instances) ) self._usage[proc] -= num_instances self._num_instances_free += num_instances if _logger is not None: self._log( INFO, "release", num_instances=num_instances, keeping=self._usage[proc], free=self.num_instances_free ) if self._usage[proc] <= 0: del self._usage[proc] if not self._waiting.is_empty(): num_instances_next = cast(int, self._waiting.peek().local.__num_instances_required) if num_instances_next <= self.num_instances_free: self._waiting.pop() elif _logger is not None: self._log(DEBUG, "release-nopop", next_requires=num_instances_next, free=self.num_instances_free) elif _logger is not None: self._log(DEBUG, "release-queueempty") else: raise RuntimeError( f"Process {proc.local.name} tries to release {num_instances} instances, but is holding none.)" )
python
def release(self, num_instances: int = 1) -> None: proc = Process.current() error_format = "Process %s holds %s instances, but requests to release more (%s)" if self._usage.get(proc, 0) > 0: if num_instances > self._usage[proc]: raise ValueError( error_format % (proc.local.name, self._usage[proc], num_instances) ) self._usage[proc] -= num_instances self._num_instances_free += num_instances if _logger is not None: self._log( INFO, "release", num_instances=num_instances, keeping=self._usage[proc], free=self.num_instances_free ) if self._usage[proc] <= 0: del self._usage[proc] if not self._waiting.is_empty(): num_instances_next = cast(int, self._waiting.peek().local.__num_instances_required) if num_instances_next <= self.num_instances_free: self._waiting.pop() elif _logger is not None: self._log(DEBUG, "release-nopop", next_requires=num_instances_next, free=self.num_instances_free) elif _logger is not None: self._log(DEBUG, "release-queueempty") else: raise RuntimeError( f"Process {proc.local.name} tries to release {num_instances} instances, but is holding none.)" )
[ "def", "release", "(", "self", ",", "num_instances", ":", "int", "=", "1", ")", "->", "None", ":", "proc", "=", "Process", ".", "current", "(", ")", "error_format", "=", "\"Process %s holds %s instances, but requests to release more (%s)\"", "if", "self", ".", "...
The current process releases instances it has previously taken. It may thus release less than it has taken. These released instances become free. If the total number of free instances then satisfy the request of the top process of the waiting queue, it is popped off the queue and resumed.
[ "The", "current", "process", "releases", "instances", "it", "has", "previously", "taken", ".", "It", "may", "thus", "release", "less", "than", "it", "has", "taken", ".", "These", "released", "instances", "become", "free", ".", "If", "the", "total", "number",...
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L946-L982
6,728
ElementAI/greensim
greensim/progress.py
capture_print
def capture_print(file_dest_maybe: Optional[IO] = None): """Progress capture that writes updated metrics to an interactive terminal.""" file_dest: IO = file_dest_maybe or sys.stderr def _print_progress(progress_min: float, rt_remaining: float, _mc: MeasureComparison) -> None: nonlocal file_dest percent_progress = progress_min * 100.0 time_remaining, unit = _display_time(rt_remaining) print( f"Progress: {percent_progress:.1f}% -- Time remaining: {time_remaining} {unit} ", end="\r", file=file_dest ) return _print_progress
python
def capture_print(file_dest_maybe: Optional[IO] = None): file_dest: IO = file_dest_maybe or sys.stderr def _print_progress(progress_min: float, rt_remaining: float, _mc: MeasureComparison) -> None: nonlocal file_dest percent_progress = progress_min * 100.0 time_remaining, unit = _display_time(rt_remaining) print( f"Progress: {percent_progress:.1f}% -- Time remaining: {time_remaining} {unit} ", end="\r", file=file_dest ) return _print_progress
[ "def", "capture_print", "(", "file_dest_maybe", ":", "Optional", "[", "IO", "]", "=", "None", ")", ":", "file_dest", ":", "IO", "=", "file_dest_maybe", "or", "sys", ".", "stderr", "def", "_print_progress", "(", "progress_min", ":", "float", ",", "rt_remainin...
Progress capture that writes updated metrics to an interactive terminal.
[ "Progress", "capture", "that", "writes", "updated", "metrics", "to", "an", "interactive", "terminal", "." ]
f160e8b57d69f6ef469f2e991cc07b7721e08a91
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/progress.py#L28-L42
6,729
libnano/primer3-py
primer3/wrappers.py
calcTm
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia'): ''' Return the tm of `seq` as a float. ''' tm_meth = _tm_methods.get(tm_method) if tm_meth is None: raise ValueError('{} is not a valid tm calculation method'.format( tm_method)) salt_meth = _salt_corrections_methods.get(salt_corrections_method) if salt_meth is None: raise ValueError('{} is not a valid salt correction method'.format( salt_corrections_method)) # For whatever reason mv_conc and dna_conc have to be ints args = [pjoin(PRIMER3_HOME, 'oligotm'), '-mv', str(mv_conc), '-dv', str(dv_conc), '-n', str(dntp_conc), '-d', str(dna_conc), '-tp', str(tm_meth), '-sc', str(salt_meth), seq] tm = subprocess.check_output(args, stderr=DEV_NULL, env=os.environ) return float(tm)
python
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia'): ''' Return the tm of `seq` as a float. ''' tm_meth = _tm_methods.get(tm_method) if tm_meth is None: raise ValueError('{} is not a valid tm calculation method'.format( tm_method)) salt_meth = _salt_corrections_methods.get(salt_corrections_method) if salt_meth is None: raise ValueError('{} is not a valid salt correction method'.format( salt_corrections_method)) # For whatever reason mv_conc and dna_conc have to be ints args = [pjoin(PRIMER3_HOME, 'oligotm'), '-mv', str(mv_conc), '-dv', str(dv_conc), '-n', str(dntp_conc), '-d', str(dna_conc), '-tp', str(tm_meth), '-sc', str(salt_meth), seq] tm = subprocess.check_output(args, stderr=DEV_NULL, env=os.environ) return float(tm)
[ "def", "calcTm", "(", "seq", ",", "mv_conc", "=", "50", ",", "dv_conc", "=", "0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50", ",", "max_nn_length", "=", "60", ",", "tm_method", "=", "'santalucia'", ",", "salt_corrections_method", "=", "'san...
Return the tm of `seq` as a float.
[ "Return", "the", "tm", "of", "seq", "as", "a", "float", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L70-L94
6,730
libnano/primer3-py
primer3/wrappers.py
_parse_ntthal
def _parse_ntthal(ntthal_output): ''' Helper method that uses regex to parse ntthal output. ''' parsed_vals = re.search(_ntthal_re, ntthal_output) return THERMORESULT( True, # Structure found float(parsed_vals.group(1)), # dS float(parsed_vals.group(2)), # dH float(parsed_vals.group(3)), # dG float(parsed_vals.group(4)) # tm ) if parsed_vals else NULLTHERMORESULT
python
def _parse_ntthal(ntthal_output): ''' Helper method that uses regex to parse ntthal output. ''' parsed_vals = re.search(_ntthal_re, ntthal_output) return THERMORESULT( True, # Structure found float(parsed_vals.group(1)), # dS float(parsed_vals.group(2)), # dH float(parsed_vals.group(3)), # dG float(parsed_vals.group(4)) # tm ) if parsed_vals else NULLTHERMORESULT
[ "def", "_parse_ntthal", "(", "ntthal_output", ")", ":", "parsed_vals", "=", "re", ".", "search", "(", "_ntthal_re", ",", "ntthal_output", ")", "return", "THERMORESULT", "(", "True", ",", "# Structure found", "float", "(", "parsed_vals", ".", "group", "(", "1",...
Helper method that uses regex to parse ntthal output.
[ "Helper", "method", "that", "uses", "regex", "to", "parse", "ntthal", "output", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L110-L119
6,731
libnano/primer3-py
primer3/wrappers.py
calcThermo
def calcThermo(seq1, seq2, calc_type='ANY', mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): """ Main subprocess wrapper for calls to the ntthal executable. Returns a named tuple with tm, ds, dh, and dg values or None if no structure / complex could be computed. """ args = [pjoin(PRIMER3_HOME, 'ntthal'), '-a', str(calc_type), '-mv', str(mv_conc), '-dv', str(dv_conc), '-n', str(dntp_conc), '-d', str(dna_conc), '-t', str(temp_c), '-maxloop', str(max_loop), '-path', THERMO_PATH, '-s1', seq1, '-s2', seq2] if temp_only: args += ['-r'] out = subprocess.check_output(args, stderr=DEV_NULL, env=os.environ) return _parse_ntthal(out)
python
def calcThermo(seq1, seq2, calc_type='ANY', mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): args = [pjoin(PRIMER3_HOME, 'ntthal'), '-a', str(calc_type), '-mv', str(mv_conc), '-dv', str(dv_conc), '-n', str(dntp_conc), '-d', str(dna_conc), '-t', str(temp_c), '-maxloop', str(max_loop), '-path', THERMO_PATH, '-s1', seq1, '-s2', seq2] if temp_only: args += ['-r'] out = subprocess.check_output(args, stderr=DEV_NULL, env=os.environ) return _parse_ntthal(out)
[ "def", "calcThermo", "(", "seq1", ",", "seq2", ",", "calc_type", "=", "'ANY'", ",", "mv_conc", "=", "50", ",", "dv_conc", "=", "0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ",",...
Main subprocess wrapper for calls to the ntthal executable. Returns a named tuple with tm, ds, dh, and dg values or None if no structure / complex could be computed.
[ "Main", "subprocess", "wrapper", "for", "calls", "to", "the", "ntthal", "executable", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L122-L145
6,732
libnano/primer3-py
primer3/wrappers.py
calcHairpin
def calcHairpin(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): ''' Return a namedtuple of the dS, dH, dG, and Tm of any hairpin struct present. ''' return calcThermo(seq, seq, 'HAIRPIN', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
python
def calcHairpin(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): ''' Return a namedtuple of the dS, dH, dG, and Tm of any hairpin struct present. ''' return calcThermo(seq, seq, 'HAIRPIN', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
[ "def", "calcHairpin", "(", "seq", ",", "mv_conc", "=", "50", ",", "dv_conc", "=", "0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ",", "temp_only", "=", "False", ")", ":", "return...
Return a namedtuple of the dS, dH, dG, and Tm of any hairpin struct present.
[ "Return", "a", "namedtuple", "of", "the", "dS", "dH", "dG", "and", "Tm", "of", "any", "hairpin", "struct", "present", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L148-L154
6,733
libnano/primer3-py
primer3/wrappers.py
calcHeterodimer
def calcHeterodimer(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): ''' Return a tuple of the dS, dH, dG, and Tm of any predicted heterodimer. ''' return calcThermo(seq1, seq2, 'ANY', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
python
def calcHeterodimer(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30, temp_only=False): ''' Return a tuple of the dS, dH, dG, and Tm of any predicted heterodimer. ''' return calcThermo(seq1, seq2, 'ANY', mv_conc, dv_conc, dntp_conc, dna_conc, temp_c, max_loop, temp_only)
[ "def", "calcHeterodimer", "(", "seq1", ",", "seq2", ",", "mv_conc", "=", "50", ",", "dv_conc", "=", "0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ",", "temp_only", "=", "False", ...
Return a tuple of the dS, dH, dG, and Tm of any predicted heterodimer.
[ "Return", "a", "tuple", "of", "the", "dS", "dH", "dG", "and", "Tm", "of", "any", "predicted", "heterodimer", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L157-L162
6,734
libnano/primer3-py
primer3/wrappers.py
designPrimers
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None): ''' Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file ''' sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) p3_args.setdefault('PRIMER_THERMODYNAMIC_PARAMETERS_PATH', pjoin(PRIMER3_HOME, 'primer3_config/')) in_str = _formatBoulderIO(p3_args) if input_log: input_log.write(in_str) input_log.flush() out_str, err_str = sp.communicate(input=in_str) if output_log: output_log.write(out_str) output_log.flush() if err_log and err_str is not None: err_log.write(err_str) err_log.flush() return _parseBoulderIO(out_str)
python
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None): ''' Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file ''' sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) p3_args.setdefault('PRIMER_THERMODYNAMIC_PARAMETERS_PATH', pjoin(PRIMER3_HOME, 'primer3_config/')) in_str = _formatBoulderIO(p3_args) if input_log: input_log.write(in_str) input_log.flush() out_str, err_str = sp.communicate(input=in_str) if output_log: output_log.write(out_str) output_log.flush() if err_log and err_str is not None: err_log.write(err_str) err_log.flush() return _parseBoulderIO(out_str)
[ "def", "designPrimers", "(", "p3_args", ",", "input_log", "=", "None", ",", "output_log", "=", "None", ",", "err_log", "=", "None", ")", ":", "sp", "=", "subprocess", ".", "Popen", "(", "[", "pjoin", "(", "PRIMER3_HOME", ",", "'primer3_core'", ")", "]", ...
Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file
[ "Return", "the", "raw", "primer3_core", "output", "for", "the", "provided", "primer3", "args", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/wrappers.py#L263-L284
6,735
libnano/primer3-py
setup.py
makeExecutable
def makeExecutable(fp): ''' Adds the executable bit to the file at filepath `fp` ''' mode = ((os.stat(fp).st_mode) | 0o555) & 0o7777 setup_log.info("Adding executable bit to %s (mode is now %o)", fp, mode) os.chmod(fp, mode)
python
def makeExecutable(fp): ''' Adds the executable bit to the file at filepath `fp` ''' mode = ((os.stat(fp).st_mode) | 0o555) & 0o7777 setup_log.info("Adding executable bit to %s (mode is now %o)", fp, mode) os.chmod(fp, mode)
[ "def", "makeExecutable", "(", "fp", ")", ":", "mode", "=", "(", "(", "os", ".", "stat", "(", "fp", ")", ".", "st_mode", ")", "|", "0o555", ")", "&", "0o7777", "setup_log", ".", "info", "(", "\"Adding executable bit to %s (mode is now %o)\"", ",", "fp", "...
Adds the executable bit to the file at filepath `fp`
[ "Adds", "the", "executable", "bit", "to", "the", "file", "at", "filepath", "fp" ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/setup.py#L111-L116
6,736
libnano/primer3-py
primer3/bindings.py
calcHairpin
def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0, temp_c=37, max_loop=30): ''' Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq (str): DNA sequence to analyze for hairpin formation mv_conc (float/int, optional): Monovalent cation conc. (mM) dv_conc (float/int, optional): Divalent cation conc. (mM) dntp_conc (float/int, optional): dNTP conc. (mM) dna_conc (float/int, optional): DNA conc. (nM) temp_c (int, optional): Simulation temperature for dG (Celsius) max_loop(int, optional): Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the hairpin formation. Raises: ``RuntimeError`` ''' _setThermoArgs(**locals()) return _THERMO_ANALYSIS.calcHairpin(seq).checkExc()
python
def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0, temp_c=37, max_loop=30): ''' Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq (str): DNA sequence to analyze for hairpin formation mv_conc (float/int, optional): Monovalent cation conc. (mM) dv_conc (float/int, optional): Divalent cation conc. (mM) dntp_conc (float/int, optional): dNTP conc. (mM) dna_conc (float/int, optional): DNA conc. (nM) temp_c (int, optional): Simulation temperature for dG (Celsius) max_loop(int, optional): Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the hairpin formation. Raises: ``RuntimeError`` ''' _setThermoArgs(**locals()) return _THERMO_ANALYSIS.calcHairpin(seq).checkExc()
[ "def", "calcHairpin", "(", "seq", ",", "mv_conc", "=", "50.0", ",", "dv_conc", "=", "0.0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50.0", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ")", ":", "_setThermoArgs", "(", "*", "*", ...
Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq (str): DNA sequence to analyze for hairpin formation mv_conc (float/int, optional): Monovalent cation conc. (mM) dv_conc (float/int, optional): Divalent cation conc. (mM) dntp_conc (float/int, optional): dNTP conc. (mM) dna_conc (float/int, optional): DNA conc. (nM) temp_c (int, optional): Simulation temperature for dG (Celsius) max_loop(int, optional): Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the hairpin formation. Raises: ``RuntimeError``
[ "Calculate", "the", "hairpin", "formation", "thermodynamics", "of", "a", "DNA", "sequence", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/bindings.py#L70-L97
6,737
libnano/primer3-py
primer3/bindings.py
calcEndStability
def calcEndStability(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30): ''' Calculate the 3' end stability of DNA sequence `seq1` against DNA sequence `seq2`. **Note that at least one of the two sequences must by <60 bp in length.** This is a cap imposed by Primer3 as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq1 (str) : DNA sequence to analyze for 3' end hybridization against the target sequence seq2 (str) : Target DNA sequence to analyze for seq1 3' end hybridization mv_conc (float/int, optional) : Monovalent cation conc. (mM) dv_conc (float/int, optional) : Divalent cation conc. (mM) dntp_conc (float/int, optional) : dNTP conc. (mM) dna_conc (float/int, optional) : DNA conc. (nM) temp_c (int, optional) : Simulation temperature for dG (C) max_loop(int, optional) : Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the 3' hybridization interaction. Raises: ``RuntimeError`` ''' _setThermoArgs(**locals()) return _THERMO_ANALYSIS.calcEndStability(seq1, seq2).checkExc()
python
def calcEndStability(seq1, seq2, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, temp_c=37, max_loop=30): ''' Calculate the 3' end stability of DNA sequence `seq1` against DNA sequence `seq2`. **Note that at least one of the two sequences must by <60 bp in length.** This is a cap imposed by Primer3 as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq1 (str) : DNA sequence to analyze for 3' end hybridization against the target sequence seq2 (str) : Target DNA sequence to analyze for seq1 3' end hybridization mv_conc (float/int, optional) : Monovalent cation conc. (mM) dv_conc (float/int, optional) : Divalent cation conc. (mM) dntp_conc (float/int, optional) : dNTP conc. (mM) dna_conc (float/int, optional) : DNA conc. (nM) temp_c (int, optional) : Simulation temperature for dG (C) max_loop(int, optional) : Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the 3' hybridization interaction. Raises: ``RuntimeError`` ''' _setThermoArgs(**locals()) return _THERMO_ANALYSIS.calcEndStability(seq1, seq2).checkExc()
[ "def", "calcEndStability", "(", "seq1", ",", "seq2", ",", "mv_conc", "=", "50", ",", "dv_conc", "=", "0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ")", ":", "_setThermoArgs", "(",...
Calculate the 3' end stability of DNA sequence `seq1` against DNA sequence `seq2`. **Note that at least one of the two sequences must by <60 bp in length.** This is a cap imposed by Primer3 as the longest reasonable sequence length for which a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50). Args: seq1 (str) : DNA sequence to analyze for 3' end hybridization against the target sequence seq2 (str) : Target DNA sequence to analyze for seq1 3' end hybridization mv_conc (float/int, optional) : Monovalent cation conc. (mM) dv_conc (float/int, optional) : Divalent cation conc. (mM) dntp_conc (float/int, optional) : dNTP conc. (mM) dna_conc (float/int, optional) : DNA conc. (nM) temp_c (int, optional) : Simulation temperature for dG (C) max_loop(int, optional) : Maximum size of loops in the structure Returns: A `ThermoResult` object with thermodynamic characteristics of the 3' hybridization interaction. Raises: ``RuntimeError``
[ "Calculate", "the", "3", "end", "stability", "of", "DNA", "sequence", "seq1", "against", "DNA", "sequence", "seq2", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/bindings.py#L167-L201
6,738
libnano/primer3-py
primer3/bindings.py
designPrimers
def designPrimers(seq_args, global_args=None, misprime_lib=None, mishyb_lib=None, debug=False): ''' Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/design args as per Primer3 docs global_args (dict, optional) : Primer3 global args as per Primer3 docs misprime_lib (dict, optional) : `Sequence name: sequence` dictionary for mispriming checks. mishyb_lib (dict, optional) : `Sequence name: sequence` dictionary for mishybridization checks. Returns: A dictionary of Primer3 results (should be identical to the expected BoulderIO output from primer3_main) ''' if global_args: primerdesign.setGlobals(global_args, misprime_lib, mishyb_lib) primerdesign.setSeqArgs(seq_args) return primerdesign.runDesign(debug)
python
def designPrimers(seq_args, global_args=None, misprime_lib=None, mishyb_lib=None, debug=False): ''' Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/design args as per Primer3 docs global_args (dict, optional) : Primer3 global args as per Primer3 docs misprime_lib (dict, optional) : `Sequence name: sequence` dictionary for mispriming checks. mishyb_lib (dict, optional) : `Sequence name: sequence` dictionary for mishybridization checks. Returns: A dictionary of Primer3 results (should be identical to the expected BoulderIO output from primer3_main) ''' if global_args: primerdesign.setGlobals(global_args, misprime_lib, mishyb_lib) primerdesign.setSeqArgs(seq_args) return primerdesign.runDesign(debug)
[ "def", "designPrimers", "(", "seq_args", ",", "global_args", "=", "None", ",", "misprime_lib", "=", "None", ",", "mishyb_lib", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "global_args", ":", "primerdesign", ".", "setGlobals", "(", "global_args",...
Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/design args as per Primer3 docs global_args (dict, optional) : Primer3 global args as per Primer3 docs misprime_lib (dict, optional) : `Sequence name: sequence` dictionary for mispriming checks. mishyb_lib (dict, optional) : `Sequence name: sequence` dictionary for mishybridization checks. Returns: A dictionary of Primer3 results (should be identical to the expected BoulderIO output from primer3_main)
[ "Run", "the", "Primer3", "design", "process", "." ]
0901c0ef3ac17afd69329d23db71136c00bcb635
https://github.com/libnano/primer3-py/blob/0901c0ef3ac17afd69329d23db71136c00bcb635/primer3/bindings.py#L246-L272
6,739
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.unravel_sections
def unravel_sections(section_data): """Unravels section type dictionary into flat list of sections with section type set as an attribute. Args: section_data(dict): Data return from py:method::get_sections Returns: list: Flat list of sections with ``sectionType`` set to type (i.e. recitation, lecture, etc) """ sections = [] for type, subsection_list in section_data.items(): for section in subsection_list: section['sectionType'] = type sections.append(section) return sections
python
def unravel_sections(section_data): sections = [] for type, subsection_list in section_data.items(): for section in subsection_list: section['sectionType'] = type sections.append(section) return sections
[ "def", "unravel_sections", "(", "section_data", ")", ":", "sections", "=", "[", "]", "for", "type", ",", "subsection_list", "in", "section_data", ".", "items", "(", ")", ":", "for", "section", "in", "subsection_list", ":", "section", "[", "'sectionType'", "]...
Unravels section type dictionary into flat list of sections with section type set as an attribute. Args: section_data(dict): Data return from py:method::get_sections Returns: list: Flat list of sections with ``sectionType`` set to type (i.e. recitation, lecture, etc)
[ "Unravels", "section", "type", "dictionary", "into", "flat", "list", "of", "sections", "with", "section", "type", "set", "as", "an", "attribute", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L64-L80
6,740
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.unravel_staff
def unravel_staff(staff_data): """Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to role type (i.e. course_admin, instructor, TA, etc) """ staff_list = [] for role, staff_members in staff_data['data'].items(): for member in staff_members: member['role'] = role staff_list.append(member) return staff_list
python
def unravel_staff(staff_data): staff_list = [] for role, staff_members in staff_data['data'].items(): for member in staff_members: member['role'] = role staff_list.append(member) return staff_list
[ "def", "unravel_staff", "(", "staff_data", ")", ":", "staff_list", "=", "[", "]", "for", "role", ",", "staff_members", "in", "staff_data", "[", "'data'", "]", ".", "items", "(", ")", ":", "for", "member", "in", "staff_members", ":", "member", "[", "'role...
Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to role type (i.e. course_admin, instructor, TA, etc)
[ "Unravels", "staff", "role", "dictionary", "into", "flat", "list", "of", "staff", "members", "with", "role", "set", "as", "an", "attribute", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L83-L99
6,741
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_gradebook_id
def get_gradebook_id(self, gbuuid): """Return gradebookid for a given gradebook uuid. Args: gbuuid (str): gradebook uuid, i.e. ``STELLAR:/project/gbngtest`` Raises: PyLmodUnexpectedData: No gradebook id returned requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: str: value of gradebook id """ gradebook = self.get('gradebook', params={'uuid': gbuuid}) if 'data' not in gradebook: failure_messsage = ('Error in get_gradebook_id ' 'for {0} - no data'.format( gradebook )) log.error(failure_messsage) raise PyLmodUnexpectedData(failure_messsage) return gradebook['data']['gradebookId']
python
def get_gradebook_id(self, gbuuid): gradebook = self.get('gradebook', params={'uuid': gbuuid}) if 'data' not in gradebook: failure_messsage = ('Error in get_gradebook_id ' 'for {0} - no data'.format( gradebook )) log.error(failure_messsage) raise PyLmodUnexpectedData(failure_messsage) return gradebook['data']['gradebookId']
[ "def", "get_gradebook_id", "(", "self", ",", "gbuuid", ")", ":", "gradebook", "=", "self", ".", "get", "(", "'gradebook'", ",", "params", "=", "{", "'uuid'", ":", "gbuuid", "}", ")", "if", "'data'", "not", "in", "gradebook", ":", "failure_messsage", "=",...
Return gradebookid for a given gradebook uuid. Args: gbuuid (str): gradebook uuid, i.e. ``STELLAR:/project/gbngtest`` Raises: PyLmodUnexpectedData: No gradebook id returned requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: str: value of gradebook id
[ "Return", "gradebookid", "for", "a", "given", "gradebook", "uuid", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L101-L123
6,742
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_options
def get_options(self, gradebook_id): """Get options for gradebook. Get options dictionary for a gradebook. Options include gradebook attributes. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Returns: An example return value is: .. code-block:: python { u'data': { u'accessLevel': u'class', u'archived': False, u'calc_on_approved_only': False, u'configured': None, u'courseName': u'', u'courseNumber': u'mitxdemosite', u'deriveOverallGrades': False, u'gradebookEwsEnabled': False, u'gradebookId': 1293808, u'gradebookName': u'Gradebook for mitxdemosite', u'gradebookReadOnly': False, u'gradebookVisibleToAdvisors': False, u'graders_change_approved': False, u'hideExcuseButtonInUI': False, u'homeworkBetaEnabled': False, u'membershipQualifier': u'/project/mitxdemosite', u'membershipSource': u'stellar', u'student_sees_actual_grades': True, u'student_sees_category_info': True, u'student_sees_comments': True, u'student_sees_cumulative_score': True, u'student_sees_histograms': True, u'student_sees_submissions': False, u'ta_approves': False, u'ta_change_approved': False, u'ta_configures': False, u'ta_edits': False, u'use_grade_weighting': False, u'usingAttendance': False, u'versionCompatible': 4, u'versionCompatibleString': u'General Availability' }, } """ end_point = 'gradebook/options/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id) options = self.get(end_point) return options['data']
python
def get_options(self, gradebook_id): end_point = 'gradebook/options/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id) options = self.get(end_point) return options['data']
[ "def", "get_options", "(", "self", ",", "gradebook_id", ")", ":", "end_point", "=", "'gradebook/options/{gradebookId}'", ".", "format", "(", "gradebookId", "=", "gradebook_id", "or", "self", ".", "gradebook_id", ")", "options", "=", "self", ".", "get", "(", "e...
Get options for gradebook. Get options dictionary for a gradebook. Options include gradebook attributes. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Returns: An example return value is: .. code-block:: python { u'data': { u'accessLevel': u'class', u'archived': False, u'calc_on_approved_only': False, u'configured': None, u'courseName': u'', u'courseNumber': u'mitxdemosite', u'deriveOverallGrades': False, u'gradebookEwsEnabled': False, u'gradebookId': 1293808, u'gradebookName': u'Gradebook for mitxdemosite', u'gradebookReadOnly': False, u'gradebookVisibleToAdvisors': False, u'graders_change_approved': False, u'hideExcuseButtonInUI': False, u'homeworkBetaEnabled': False, u'membershipQualifier': u'/project/mitxdemosite', u'membershipSource': u'stellar', u'student_sees_actual_grades': True, u'student_sees_category_info': True, u'student_sees_comments': True, u'student_sees_cumulative_score': True, u'student_sees_histograms': True, u'student_sees_submissions': False, u'ta_approves': False, u'ta_change_approved': False, u'ta_configures': False, u'ta_edits': False, u'use_grade_weighting': False, u'usingAttendance': False, u'versionCompatible': 4, u'versionCompatibleString': u'General Availability' }, }
[ "Get", "options", "for", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L125-L181
6,743
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_assignments
def get_assignments( self, gradebook_id='', simple=False, max_points=True, avg_stats=False, grading_stats=False ): """Get assignments for a gradebook. Return list of assignments for a given gradebook, specified by a py:attribute::gradebook_id. You can control if additional parameters are returned, but the response time with py:attribute::avg_stats and py:attribute::grading_stats enabled is significantly longer. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): return just assignment names, default= ``False`` max_points (bool): Max points is a property of the grading scheme for the assignment rather than a property of the assignment itself, default= ``True`` avg_stats (bool): return average grade, default= ``False`` grading_stats (bool): return grading statistics, i.e. number of approved grades, unapproved grades, etc., default= ``False`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of assignment dictionaries An example return value is: .. code-block:: python [ { u'assignmentId': 2431240, u'categoryId': 1293820, u'description': u'', u'dueDate': 1372392000000, u'dueDateString': u'06-28-2013', u'gradebookId': 1293808, u'graderVisible': True, u'gradingSchemeId': 2431243, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 10.0, u'name': u'Homework 1', u'shortName': u'HW1', u'userDeleted': False, u'weight': 1.0 }, { u'assignmentId': 16708850, u'categoryId': 1293820, u'description': u'', u'dueDate': 1383541200000, u'dueDateString': u'11-04-2013', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 16708851, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'midterm1', u'shortName': u'mid1', u'userDeleted': False, u'weight': 1.0 }, ] """ # These are parameters required for the remote API call, so # there aren't too many arguments # pylint: disable=too-many-arguments params = dict( includeMaxPoints=json.dumps(max_points), includeAvgStats=json.dumps(avg_stats), includeGradingStats=json.dumps(grading_stats) ) assignments = self.get( 'assignments/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=params, ) if simple: return [{'AssignmentName': x['name']} for x in assignments['data']] return assignments['data']
python
def get_assignments( self, gradebook_id='', simple=False, max_points=True, avg_stats=False, grading_stats=False ): # These are parameters required for the remote API call, so # there aren't too many arguments # pylint: disable=too-many-arguments params = dict( includeMaxPoints=json.dumps(max_points), includeAvgStats=json.dumps(avg_stats), includeGradingStats=json.dumps(grading_stats) ) assignments = self.get( 'assignments/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=params, ) if simple: return [{'AssignmentName': x['name']} for x in assignments['data']] return assignments['data']
[ "def", "get_assignments", "(", "self", ",", "gradebook_id", "=", "''", ",", "simple", "=", "False", ",", "max_points", "=", "True", ",", "avg_stats", "=", "False", ",", "grading_stats", "=", "False", ")", ":", "# These are parameters required for the remote API ca...
Get assignments for a gradebook. Return list of assignments for a given gradebook, specified by a py:attribute::gradebook_id. You can control if additional parameters are returned, but the response time with py:attribute::avg_stats and py:attribute::grading_stats enabled is significantly longer. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): return just assignment names, default= ``False`` max_points (bool): Max points is a property of the grading scheme for the assignment rather than a property of the assignment itself, default= ``True`` avg_stats (bool): return average grade, default= ``False`` grading_stats (bool): return grading statistics, i.e. number of approved grades, unapproved grades, etc., default= ``False`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of assignment dictionaries An example return value is: .. code-block:: python [ { u'assignmentId': 2431240, u'categoryId': 1293820, u'description': u'', u'dueDate': 1372392000000, u'dueDateString': u'06-28-2013', u'gradebookId': 1293808, u'graderVisible': True, u'gradingSchemeId': 2431243, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 10.0, u'name': u'Homework 1', u'shortName': u'HW1', u'userDeleted': False, u'weight': 1.0 }, { u'assignmentId': 16708850, u'categoryId': 1293820, u'description': u'', u'dueDate': 1383541200000, u'dueDateString': u'11-04-2013', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 16708851, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'midterm1', u'shortName': u'mid1', u'userDeleted': False, u'weight': 1.0 }, ]
[ "Get", "assignments", "for", "a", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L183-L280
6,744
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_assignment_by_name
def get_assignment_by_name(self, assignment_name, assignments=None): """Get assignment by name. Get an assignment by name. It works by retrieving all assignments and returning the first assignment with a matching name. If the optional parameter ``assignments`` is provided, it uses this collection rather than retrieving all assignments from the service. Args: assignment_name (str): name of assignment assignments (list): assignments to search, default: None When ``assignments`` is unspecified, all assignments are retrieved from the service. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of assignment id and assignment dictionary .. code-block:: python ( 16708850, { u'assignmentId': 16708850, u'categoryId': 1293820, u'description': u'', u'dueDate': 1383541200000, u'dueDateString': u'11-04-2013', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 16708851, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'midterm1', u'shortName': u'mid1', u'userDeleted': False, u'weight': 1.0 } ) """ if assignments is None: assignments = self.get_assignments() for assignment in assignments: if assignment['name'] == assignment_name: return assignment['assignmentId'], assignment return None, None
python
def get_assignment_by_name(self, assignment_name, assignments=None): if assignments is None: assignments = self.get_assignments() for assignment in assignments: if assignment['name'] == assignment_name: return assignment['assignmentId'], assignment return None, None
[ "def", "get_assignment_by_name", "(", "self", ",", "assignment_name", ",", "assignments", "=", "None", ")", ":", "if", "assignments", "is", "None", ":", "assignments", "=", "self", ".", "get_assignments", "(", ")", "for", "assignment", "in", "assignments", ":"...
Get assignment by name. Get an assignment by name. It works by retrieving all assignments and returning the first assignment with a matching name. If the optional parameter ``assignments`` is provided, it uses this collection rather than retrieving all assignments from the service. Args: assignment_name (str): name of assignment assignments (list): assignments to search, default: None When ``assignments`` is unspecified, all assignments are retrieved from the service. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of assignment id and assignment dictionary .. code-block:: python ( 16708850, { u'assignmentId': 16708850, u'categoryId': 1293820, u'description': u'', u'dueDate': 1383541200000, u'dueDateString': u'11-04-2013', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 16708851, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'midterm1', u'shortName': u'mid1', u'userDeleted': False, u'weight': 1.0 } )
[ "Get", "assignment", "by", "name", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L282-L333
6,745
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.create_assignment
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs ): """Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, one word of no more than 5 characters, i.e. ``SAnew`` weight (str): floating point value for weight, i.e. ``1.0`` max_points (str): floating point value for maximum point total, i.e. ``100.0`` due_date_str (str): due date as string in ``mm-dd-yyyy`` format, i.e. ``08-21-2011`` gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` kwargs (dict): dictionary containing additional parameters, i.e. ``graderVisible``, ``totalAverage``, and ``categoryId``. For example: .. code-block:: python { u'graderVisible': True, u'totalAverage': None u'categoryId': 1007964, } Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing ``data``, ``status`` and ``message`` for example: .. code-block:: python { u'data': { u'assignmentId': 18490492, u'categoryId': 1293820, u'description': u'', u'dueDate': 1312171200000, u'dueDateString': u'08-01-2011', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 18490493, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'new NUMERIC SIMPLE ASSIGNMENT', u'numStudentGradesToBeApproved': 0, u'numStudentsToBeGraded': 614, u'shortName': u'SAnew', u'userDeleted': False, u'weight': 1.0 }, u'message': u'assignment is created successfully', u'status': 1 } """ data = { 'name': name, 'shortName': short_name, 'weight': weight, 'graderVisible': False, 'gradingSchemeType': 'NUMERIC', 'gradebookId': gradebook_id or self.gradebook_id, 'maxPointsTotal': max_points, 'dueDateString': due_date_str } data.update(kwargs) log.info("Creating assignment %s", name) response = self.post('assignment', data) log.debug('Received response data: %s', response) return response
python
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs ): data = { 'name': name, 'shortName': short_name, 'weight': weight, 'graderVisible': False, 'gradingSchemeType': 'NUMERIC', 'gradebookId': gradebook_id or self.gradebook_id, 'maxPointsTotal': max_points, 'dueDateString': due_date_str } data.update(kwargs) log.info("Creating assignment %s", name) response = self.post('assignment', data) log.debug('Received response data: %s', response) return response
[ "def", "create_assignment", "(", "# pylint: disable=too-many-arguments", "self", ",", "name", ",", "short_name", ",", "weight", ",", "max_points", ",", "due_date_str", ",", "gradebook_id", "=", "''", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'name'...
Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, one word of no more than 5 characters, i.e. ``SAnew`` weight (str): floating point value for weight, i.e. ``1.0`` max_points (str): floating point value for maximum point total, i.e. ``100.0`` due_date_str (str): due date as string in ``mm-dd-yyyy`` format, i.e. ``08-21-2011`` gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` kwargs (dict): dictionary containing additional parameters, i.e. ``graderVisible``, ``totalAverage``, and ``categoryId``. For example: .. code-block:: python { u'graderVisible': True, u'totalAverage': None u'categoryId': 1007964, } Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing ``data``, ``status`` and ``message`` for example: .. code-block:: python { u'data': { u'assignmentId': 18490492, u'categoryId': 1293820, u'description': u'', u'dueDate': 1312171200000, u'dueDateString': u'08-01-2011', u'gradebookId': 1293808, u'graderVisible': False, u'gradingSchemeId': 18490493, u'gradingSchemeType': u'NUMERIC', u'isComposite': False, u'isHomework': False, u'maxPointsTotal': 100.0, u'name': u'new NUMERIC SIMPLE ASSIGNMENT', u'numStudentGradesToBeApproved': 0, u'numStudentsToBeGraded': 614, u'shortName': u'SAnew', u'userDeleted': False, u'weight': 1.0 }, u'message': u'assignment is created successfully', u'status': 1 }
[ "Create", "a", "new", "assignment", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L335-L425
6,746
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.set_grade
def set_grade( self, assignment_id, student_id, grade_value, gradebook_id='', **kwargs ): """Set numerical grade for student and assignment. Set a numerical grade for for a student and assignment. Additional options for grade ``mode`` are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2`` To set 'excused' as the grade, enter ``None`` for letter and numeric grade values, and pass ``x`` as the ``specialGradeValue``. ``ReturnAffectedValues`` flag determines whether or not to return student cumulative points and impacted assignment category grades (average and student grade). Args: assignment_id (str): numerical ID for assignment student_id (str): numerical ID for student grade_value (str): numerical grade value gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` kwargs (dict): dictionary of additional parameters .. code-block:: python { u'letterGradeValue':None, u'booleanGradeValue':None, u'specialGradeValue':None, u'mode':2, u'isGradeApproved':False, u'comment':None, u'returnAffectedValues': True, } Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing response ``status`` and ``message`` .. code-block:: python { u'message': u'grade saved successfully', u'status': 1 } """ # pylint: disable=too-many-arguments # numericGradeValue stringified because 'x' is a possible # value for excused grades. grade_info = { 'studentId': student_id, 'assignmentId': assignment_id, 'mode': 2, 'comment': 'from MITx {0}'.format(time.ctime(time.time())), 'numericGradeValue': str(grade_value), 'isGradeApproved': False } grade_info.update(kwargs) log.info( "student %s set_grade=%s for assignment %s", student_id, grade_value, assignment_id) return self.post( 'grades/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), data=grade_info, )
python
def set_grade( self, assignment_id, student_id, grade_value, gradebook_id='', **kwargs ): # pylint: disable=too-many-arguments # numericGradeValue stringified because 'x' is a possible # value for excused grades. grade_info = { 'studentId': student_id, 'assignmentId': assignment_id, 'mode': 2, 'comment': 'from MITx {0}'.format(time.ctime(time.time())), 'numericGradeValue': str(grade_value), 'isGradeApproved': False } grade_info.update(kwargs) log.info( "student %s set_grade=%s for assignment %s", student_id, grade_value, assignment_id) return self.post( 'grades/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), data=grade_info, )
[ "def", "set_grade", "(", "self", ",", "assignment_id", ",", "student_id", ",", "grade_value", ",", "gradebook_id", "=", "''", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-arguments", "# numericGradeValue stringified because 'x' is a possible", "# value f...
Set numerical grade for student and assignment. Set a numerical grade for for a student and assignment. Additional options for grade ``mode`` are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2`` To set 'excused' as the grade, enter ``None`` for letter and numeric grade values, and pass ``x`` as the ``specialGradeValue``. ``ReturnAffectedValues`` flag determines whether or not to return student cumulative points and impacted assignment category grades (average and student grade). Args: assignment_id (str): numerical ID for assignment student_id (str): numerical ID for student grade_value (str): numerical grade value gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` kwargs (dict): dictionary of additional parameters .. code-block:: python { u'letterGradeValue':None, u'booleanGradeValue':None, u'specialGradeValue':None, u'mode':2, u'isGradeApproved':False, u'comment':None, u'returnAffectedValues': True, } Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing response ``status`` and ``message`` .. code-block:: python { u'message': u'grade saved successfully', u'status': 1 }
[ "Set", "numerical", "grade", "for", "student", "and", "assignment", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L454-L531
6,747
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.multi_grade
def multi_grade(self, grade_array, gradebook_id=''): """Set multiple grades for students. Set multiple student grades for a gradebook. The grades are passed as a list of dictionaries. Each grade dictionary in ``grade_array`` must contain a ``studentId`` and a ``assignmentId``. Options for grade mode are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2`` To set 'excused' as the grade, enter ``None`` for ``letterGradeValue`` and ``numericGradeValue``, and pass ``x`` as the ``specialGradeValue``. The ``ReturnAffectedValues`` flag determines whether to return student cumulative points and impacted assignment category grades (average and student grade) .. code-block:: python [ { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': 4522, u'specialGradeValue': None, u'returnAffectedValues': True, u'letterGradeValue': None, u'mode': 2, u'numericGradeValue': 50, u'isGradeApproved': False }, { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': 4522, u'specialGradeValue': u'x', u'returnAffectedValues': True, u'letterGradeValue': None, u'mode': 2, u'numericGradeValue': None, u'isGradeApproved': False }, { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': None, u'specialGradeValue': None, u'returnAffectedValues': True, u'letterGradeValue': u'A', u'mode': 1, u'numericGradeValue': None, u'isGradeApproved': False } ] Args: grade_array (dict): an array of grades to save gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing response ``status`` and ``message`` """ log.info('Sending grades: %r', grade_array) return self.post( 'multiGrades/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), data=grade_array, )
python
def multi_grade(self, grade_array, gradebook_id=''): log.info('Sending grades: %r', grade_array) return self.post( 'multiGrades/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), data=grade_array, )
[ "def", "multi_grade", "(", "self", ",", "grade_array", ",", "gradebook_id", "=", "''", ")", ":", "log", ".", "info", "(", "'Sending grades: %r'", ",", "grade_array", ")", "return", "self", ".", "post", "(", "'multiGrades/{gradebookId}'", ".", "format", "(", ...
Set multiple grades for students. Set multiple student grades for a gradebook. The grades are passed as a list of dictionaries. Each grade dictionary in ``grade_array`` must contain a ``studentId`` and a ``assignmentId``. Options for grade mode are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2`` To set 'excused' as the grade, enter ``None`` for ``letterGradeValue`` and ``numericGradeValue``, and pass ``x`` as the ``specialGradeValue``. The ``ReturnAffectedValues`` flag determines whether to return student cumulative points and impacted assignment category grades (average and student grade) .. code-block:: python [ { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': 4522, u'specialGradeValue': None, u'returnAffectedValues': True, u'letterGradeValue': None, u'mode': 2, u'numericGradeValue': 50, u'isGradeApproved': False }, { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': 4522, u'specialGradeValue': u'x', u'returnAffectedValues': True, u'letterGradeValue': None, u'mode': 2, u'numericGradeValue': None, u'isGradeApproved': False }, { u'comment': None, u'booleanGradeValue': None, u'studentId': 1135, u'assignmentId': None, u'specialGradeValue': None, u'returnAffectedValues': True, u'letterGradeValue': u'A', u'mode': 1, u'numericGradeValue': None, u'isGradeApproved': False } ] Args: grade_array (dict): an array of grades to save gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: dictionary containing response ``status`` and ``message``
[ "Set", "multiple", "grades", "for", "students", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L533-L609
6,748
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_sections
def get_sections(self, gradebook_id='', simple=False): """Get the sections for a gradebook. Return a dictionary of types of sections containing a list of that type for a given gradebook. Specified by a gradebookid. If simple=True, a list of dictionaries is provided for each section regardless of type. The dictionary only contains one key ``SectionName``. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): return a list of section names only Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: Dictionary of section types where each type has a list of sections An example return value is: .. code-block:: python { u'recitation': [ { u'editable': False, u'groupId': 1293925, u'groupingScheme': u'Recitation', u'members': None, u'name': u'Unassigned', u'shortName': u'DefaultGroupNoCollisionPlease1234', u'staffs': None }, { u'editable': True, u'groupId': 1327565, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r01', u'shortName': u'r01', u'staffs': None}, {u'editable': True, u'groupId': 1327555, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r02', u'shortName': u'r02', u'staffs': None } ] } """ params = dict(includeMembers='false') section_data = self.get( 'sections/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=params ) if simple: sections = self.unravel_sections(section_data['data']) return [{'SectionName': x['name']} for x in sections] return section_data['data']
python
def get_sections(self, gradebook_id='', simple=False): params = dict(includeMembers='false') section_data = self.get( 'sections/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=params ) if simple: sections = self.unravel_sections(section_data['data']) return [{'SectionName': x['name']} for x in sections] return section_data['data']
[ "def", "get_sections", "(", "self", ",", "gradebook_id", "=", "''", ",", "simple", "=", "False", ")", ":", "params", "=", "dict", "(", "includeMembers", "=", "'false'", ")", "section_data", "=", "self", ".", "get", "(", "'sections/{gradebookId}'", ".", "fo...
Get the sections for a gradebook. Return a dictionary of types of sections containing a list of that type for a given gradebook. Specified by a gradebookid. If simple=True, a list of dictionaries is provided for each section regardless of type. The dictionary only contains one key ``SectionName``. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): return a list of section names only Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: dict: Dictionary of section types where each type has a list of sections An example return value is: .. code-block:: python { u'recitation': [ { u'editable': False, u'groupId': 1293925, u'groupingScheme': u'Recitation', u'members': None, u'name': u'Unassigned', u'shortName': u'DefaultGroupNoCollisionPlease1234', u'staffs': None }, { u'editable': True, u'groupId': 1327565, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r01', u'shortName': u'r01', u'staffs': None}, {u'editable': True, u'groupId': 1327555, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r02', u'shortName': u'r02', u'staffs': None } ] }
[ "Get", "the", "sections", "for", "a", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L611-L681
6,749
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_section_by_name
def get_section_by_name(self, section_name): """Get a section by its name. Get a list of sections for a given gradebook, specified by a gradebookid. Args: section_name (str): The section's name. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of group id, and section dictionary An example return value is: .. code-block:: python ( 1327565, { u'editable': True, u'groupId': 1327565, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r01', u'shortName': u'r01', u'staffs': None } ) """ sections = self.unravel_sections(self.get_sections()) for section in sections: if section['name'] == section_name: return section['groupId'], section return None, None
python
def get_section_by_name(self, section_name): sections = self.unravel_sections(self.get_sections()) for section in sections: if section['name'] == section_name: return section['groupId'], section return None, None
[ "def", "get_section_by_name", "(", "self", ",", "section_name", ")", ":", "sections", "=", "self", ".", "unravel_sections", "(", "self", ".", "get_sections", "(", ")", ")", "for", "section", "in", "sections", ":", "if", "section", "[", "'name'", "]", "==",...
Get a section by its name. Get a list of sections for a given gradebook, specified by a gradebookid. Args: section_name (str): The section's name. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of group id, and section dictionary An example return value is: .. code-block:: python ( 1327565, { u'editable': True, u'groupId': 1327565, u'groupingScheme': u'Recitation', u'members': None, u'name': u'r01', u'shortName': u'r01', u'staffs': None } )
[ "Get", "a", "section", "by", "its", "name", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L683-L721
6,750
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_students
def get_students( self, gradebook_id='', simple=False, section_name='', include_photo=False, include_grade_info=False, include_grade_history=False, include_makeup_grades=False ): """Get students for a gradebook. Get a list of students for a given gradebook, specified by a gradebook id. Does not include grade data. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): if ``True``, just return dictionary with keys ``email``, ``name``, ``section``, default = ``False`` section_name (str): section name include_photo (bool): include student photo, default= ``False`` include_grade_info (bool): include student's grade info, default= ``False`` include_grade_history (bool): include student's grade history, default= ``False`` include_makeup_grades (bool): include student's makeup grades, default= ``False`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of student dictionaries .. code-block:: python [{ u'accountEmail': u'stellar.test2@gmail.com', u'displayName': u'Molly Parker', u'photoUrl': None, u'middleName': None, u'section': u'Unassigned', u'sectionId': 1293925, u'editable': False, u'overallGradeInformation': None, u'studentId': 1145, u'studentAssignmentInfo': None, u'sortableName': u'Parker, Molly', u'surname': u'Parker', u'givenName': u'Molly', u'nickName': u'Molly', u'email': u'stellar.test2@gmail.com' },] """ # These are parameters required for the remote API call, so # there aren't too many arguments, or too many variables # pylint: disable=too-many-arguments,too-many-locals # Set params by arguments params = dict( includePhoto=json.dumps(include_photo), includeGradeInfo=json.dumps(include_grade_info), includeGradeHistory=json.dumps(include_grade_history), includeMakeupGrades=json.dumps(include_makeup_grades), ) url = 'students/{gradebookId}' if section_name: group_id, _ = self.get_section_by_name(section_name) if group_id is None: failure_message = ( 'in get_students -- Error: ' 'No such section %s' % section_name ) log.critical(failure_message) raise PyLmodNoSuchSection(failure_message) url += '/section/{0}'.format(group_id) student_data = self.get( url.format( gradebookId=gradebook_id or self.gradebook_id ), params=params, ) if simple: # just return dict with keys email, name, section student_map = dict( accountEmail='email', displayName='name', section='section' ) def remap(students): """Convert mit.edu domain to upper-case for student emails. The mit.edu domain for user email must be upper-case, i.e. MIT.EDU. Args: students (list): list of students Returns: dict: dictionary of updated student email domains """ newx = dict((student_map[k], students[k]) for k in student_map) # match certs newx['email'] = newx['email'].replace('@mit.edu', '@MIT.EDU') return newx return [remap(x) for x in student_data['data']] return student_data['data']
python
def get_students( self, gradebook_id='', simple=False, section_name='', include_photo=False, include_grade_info=False, include_grade_history=False, include_makeup_grades=False ): # These are parameters required for the remote API call, so # there aren't too many arguments, or too many variables # pylint: disable=too-many-arguments,too-many-locals # Set params by arguments params = dict( includePhoto=json.dumps(include_photo), includeGradeInfo=json.dumps(include_grade_info), includeGradeHistory=json.dumps(include_grade_history), includeMakeupGrades=json.dumps(include_makeup_grades), ) url = 'students/{gradebookId}' if section_name: group_id, _ = self.get_section_by_name(section_name) if group_id is None: failure_message = ( 'in get_students -- Error: ' 'No such section %s' % section_name ) log.critical(failure_message) raise PyLmodNoSuchSection(failure_message) url += '/section/{0}'.format(group_id) student_data = self.get( url.format( gradebookId=gradebook_id or self.gradebook_id ), params=params, ) if simple: # just return dict with keys email, name, section student_map = dict( accountEmail='email', displayName='name', section='section' ) def remap(students): """Convert mit.edu domain to upper-case for student emails. The mit.edu domain for user email must be upper-case, i.e. MIT.EDU. Args: students (list): list of students Returns: dict: dictionary of updated student email domains """ newx = dict((student_map[k], students[k]) for k in student_map) # match certs newx['email'] = newx['email'].replace('@mit.edu', '@MIT.EDU') return newx return [remap(x) for x in student_data['data']] return student_data['data']
[ "def", "get_students", "(", "self", ",", "gradebook_id", "=", "''", ",", "simple", "=", "False", ",", "section_name", "=", "''", ",", "include_photo", "=", "False", ",", "include_grade_info", "=", "False", ",", "include_grade_history", "=", "False", ",", "in...
Get students for a gradebook. Get a list of students for a given gradebook, specified by a gradebook id. Does not include grade data. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): if ``True``, just return dictionary with keys ``email``, ``name``, ``section``, default = ``False`` section_name (str): section name include_photo (bool): include student photo, default= ``False`` include_grade_info (bool): include student's grade info, default= ``False`` include_grade_history (bool): include student's grade history, default= ``False`` include_makeup_grades (bool): include student's makeup grades, default= ``False`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of student dictionaries .. code-block:: python [{ u'accountEmail': u'stellar.test2@gmail.com', u'displayName': u'Molly Parker', u'photoUrl': None, u'middleName': None, u'section': u'Unassigned', u'sectionId': 1293925, u'editable': False, u'overallGradeInformation': None, u'studentId': 1145, u'studentAssignmentInfo': None, u'sortableName': u'Parker, Molly', u'surname': u'Parker', u'givenName': u'Molly', u'nickName': u'Molly', u'email': u'stellar.test2@gmail.com' },]
[ "Get", "students", "for", "a", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L723-L838
6,751
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_student_by_email
def get_student_by_email(self, email, students=None): """Get a student based on an email address. Calls ``self.get_students()`` to get list of all students, if not passed as the ``students`` parameter. Args: email (str): student email students (list): dictionary of students to search, default: None When ``students`` is unspecified, all students in gradebook are retrieved. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of student id and student dictionary. """ if students is None: students = self.get_students() email = email.lower() for student in students: if student['accountEmail'].lower() == email: return student['studentId'], student return None, None
python
def get_student_by_email(self, email, students=None): if students is None: students = self.get_students() email = email.lower() for student in students: if student['accountEmail'].lower() == email: return student['studentId'], student return None, None
[ "def", "get_student_by_email", "(", "self", ",", "email", ",", "students", "=", "None", ")", ":", "if", "students", "is", "None", ":", "students", "=", "self", ".", "get_students", "(", ")", "email", "=", "email", ".", "lower", "(", ")", "for", "studen...
Get a student based on an email address. Calls ``self.get_students()`` to get list of all students, if not passed as the ``students`` parameter. Args: email (str): student email students (list): dictionary of students to search, default: None When ``students`` is unspecified, all students in gradebook are retrieved. Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of student id and student dictionary.
[ "Get", "a", "student", "based", "on", "an", "email", "address", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L840-L866
6,752
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.spreadsheet2gradebook
def spreadsheet2gradebook( self, csv_file, email_field=None, approve_grades=False, use_max_points_column=False, max_points_column=None, normalize_column=None ): """Upload grade spreadsheet to gradebook. Upload grades from CSV format spreadsheet file into the Learning Modules gradebook. The spreadsheet must have a column named ``External email`` which is used as the student's email address (for looking up and matching studentId). These columns are disregarded: ``ID``, ``Username``, ``Full Name``, ``edX email``, ``External email``, as well as the strings passed in ``max_points_column`` and ``normalize_column``, if any. All other columns are taken as assignments. If ``email_field`` is specified, then that field name is taken as the student's email. .. code-block:: none External email,AB Assignment 01,AB Assignment 02 jeannechiang@gmail.com,1.0,0.9 stellar.test2@gmail.com,0.2,0.4 stellar.test1@gmail.com,0.93,0.77 Args: csv_reader (str): filename of csv data, or readable file object email_field (str): student's email approve_grades (bool): Should grades be auto approved? use_max_points_column (bool): If ``True``, read the max points and normalize values from the CSV and use the max points value in place of the default if normalized is ``False``. max_points_column (str): The name of the max_pts column. All rows contain the same number, the max points for the assignment. normalize_column (str): The name of the normalize column which indicates whether to use the max points value. Raises: PyLmodFailedAssignmentCreation: Failed to create assignment requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of dictionary containing response ``status`` and ``message``, and duration of operation """ non_assignment_fields = [ 'ID', 'Username', 'Full Name', 'edX email', 'External email' ] if max_points_column is not None: non_assignment_fields.append(max_points_column) if normalize_column is not None: non_assignment_fields.append(normalize_column) if email_field is not None: non_assignment_fields.append(email_field) else: email_field = 'External email' if not hasattr(csv_file, 'read'): file_pointer = open(csv_file) else: file_pointer = csv_file csv_reader = csv.DictReader(file_pointer, dialect='excel') response = self._spreadsheet2gradebook_multi( csv_reader, email_field, non_assignment_fields, approve_grades=approve_grades, use_max_points_column=use_max_points_column, max_points_column=max_points_column, normalize_column=normalize_column ) return response
python
def spreadsheet2gradebook( self, csv_file, email_field=None, approve_grades=False, use_max_points_column=False, max_points_column=None, normalize_column=None ): non_assignment_fields = [ 'ID', 'Username', 'Full Name', 'edX email', 'External email' ] if max_points_column is not None: non_assignment_fields.append(max_points_column) if normalize_column is not None: non_assignment_fields.append(normalize_column) if email_field is not None: non_assignment_fields.append(email_field) else: email_field = 'External email' if not hasattr(csv_file, 'read'): file_pointer = open(csv_file) else: file_pointer = csv_file csv_reader = csv.DictReader(file_pointer, dialect='excel') response = self._spreadsheet2gradebook_multi( csv_reader, email_field, non_assignment_fields, approve_grades=approve_grades, use_max_points_column=use_max_points_column, max_points_column=max_points_column, normalize_column=normalize_column ) return response
[ "def", "spreadsheet2gradebook", "(", "self", ",", "csv_file", ",", "email_field", "=", "None", ",", "approve_grades", "=", "False", ",", "use_max_points_column", "=", "False", ",", "max_points_column", "=", "None", ",", "normalize_column", "=", "None", ")", ":",...
Upload grade spreadsheet to gradebook. Upload grades from CSV format spreadsheet file into the Learning Modules gradebook. The spreadsheet must have a column named ``External email`` which is used as the student's email address (for looking up and matching studentId). These columns are disregarded: ``ID``, ``Username``, ``Full Name``, ``edX email``, ``External email``, as well as the strings passed in ``max_points_column`` and ``normalize_column``, if any. All other columns are taken as assignments. If ``email_field`` is specified, then that field name is taken as the student's email. .. code-block:: none External email,AB Assignment 01,AB Assignment 02 jeannechiang@gmail.com,1.0,0.9 stellar.test2@gmail.com,0.2,0.4 stellar.test1@gmail.com,0.93,0.77 Args: csv_reader (str): filename of csv data, or readable file object email_field (str): student's email approve_grades (bool): Should grades be auto approved? use_max_points_column (bool): If ``True``, read the max points and normalize values from the CSV and use the max points value in place of the default if normalized is ``False``. max_points_column (str): The name of the max_pts column. All rows contain the same number, the max points for the assignment. normalize_column (str): The name of the normalize column which indicates whether to use the max points value. Raises: PyLmodFailedAssignmentCreation: Failed to create assignment requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: tuple: tuple of dictionary containing response ``status`` and ``message``, and duration of operation
[ "Upload", "grade", "spreadsheet", "to", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L1053-L1137
6,753
mitodl/PyLmod
pylmod/gradebook.py
GradeBook.get_staff
def get_staff(self, gradebook_id, simple=False): """Get staff list for gradebook. Get staff list for the gradebook specified. Optionally, return a less detailed list by specifying ``simple = True``. If simple=True, return a list of dictionaries, one dictionary for each member. The dictionary contains a member's ``email``, ``displayName``, and ``role``. Members with multiple roles will appear in the list once for each role. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): Return a staff list with less detail. Default is ``False``. Returns: An example return value is: .. code-block:: python { u'data': { u'COURSE_ADMIN': [ { u'accountEmail': u'benfranklin@mit.edu', u'displayName': u'Benjamin Franklin', u'editable': False, u'email': u'benfranklin@mit.edu', u'givenName': u'Benjamin', u'middleName': None, u'mitId': u'921344431', u'nickName': u'Benjamin', u'personId': 10710616, u'sortableName': u'Franklin, Benjamin', u'surname': u'Franklin', u'year': None }, ], u'COURSE_PROF': [ { u'accountEmail': u'dduck@mit.edu', u'displayName': u'Donald Duck', u'editable': False, u'email': u'dduck@mit.edu', u'givenName': u'Donald', u'middleName': None, u'mitId': u'916144889', u'nickName': u'Donald', u'personId': 8117160, u'sortableName': u'Duck, Donald', u'surname': u'Duck', u'year': None }, ], u'COURSE_TA': [ { u'accountEmail': u'hduck@mit.edu', u'displayName': u'Huey Duck', u'editable': False, u'email': u'hduck@mit.edu', u'givenName': u'Huey', u'middleName': None, u'mitId': u'920445024', u'nickName': u'Huey', u'personId': 1299059, u'sortableName': u'Duck, Huey', u'surname': u'Duck', u'year': None }, ] }, } """ staff_data = self.get( 'staff/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=None, ) if simple: simple_list = [] unraveled_list = self.unravel_staff(staff_data) for member in unraveled_list.__iter__(): simple_list.append({ 'accountEmail': member['accountEmail'], 'displayName': member['displayName'], 'role': member['role'], }) return simple_list return staff_data['data']
python
def get_staff(self, gradebook_id, simple=False): staff_data = self.get( 'staff/{gradebookId}'.format( gradebookId=gradebook_id or self.gradebook_id ), params=None, ) if simple: simple_list = [] unraveled_list = self.unravel_staff(staff_data) for member in unraveled_list.__iter__(): simple_list.append({ 'accountEmail': member['accountEmail'], 'displayName': member['displayName'], 'role': member['role'], }) return simple_list return staff_data['data']
[ "def", "get_staff", "(", "self", ",", "gradebook_id", ",", "simple", "=", "False", ")", ":", "staff_data", "=", "self", ".", "get", "(", "'staff/{gradebookId}'", ".", "format", "(", "gradebookId", "=", "gradebook_id", "or", "self", ".", "gradebook_id", ")", ...
Get staff list for gradebook. Get staff list for the gradebook specified. Optionally, return a less detailed list by specifying ``simple = True``. If simple=True, return a list of dictionaries, one dictionary for each member. The dictionary contains a member's ``email``, ``displayName``, and ``role``. Members with multiple roles will appear in the list once for each role. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` simple (bool): Return a staff list with less detail. Default is ``False``. Returns: An example return value is: .. code-block:: python { u'data': { u'COURSE_ADMIN': [ { u'accountEmail': u'benfranklin@mit.edu', u'displayName': u'Benjamin Franklin', u'editable': False, u'email': u'benfranklin@mit.edu', u'givenName': u'Benjamin', u'middleName': None, u'mitId': u'921344431', u'nickName': u'Benjamin', u'personId': 10710616, u'sortableName': u'Franklin, Benjamin', u'surname': u'Franklin', u'year': None }, ], u'COURSE_PROF': [ { u'accountEmail': u'dduck@mit.edu', u'displayName': u'Donald Duck', u'editable': False, u'email': u'dduck@mit.edu', u'givenName': u'Donald', u'middleName': None, u'mitId': u'916144889', u'nickName': u'Donald', u'personId': 8117160, u'sortableName': u'Duck, Donald', u'surname': u'Duck', u'year': None }, ], u'COURSE_TA': [ { u'accountEmail': u'hduck@mit.edu', u'displayName': u'Huey Duck', u'editable': False, u'email': u'hduck@mit.edu', u'givenName': u'Huey', u'middleName': None, u'mitId': u'920445024', u'nickName': u'Huey', u'personId': 1299059, u'sortableName': u'Duck, Huey', u'surname': u'Duck', u'year': None }, ] }, }
[ "Get", "staff", "list", "for", "gradebook", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L1139-L1232
6,754
mitodl/PyLmod
pylmod/membership.py
Membership.get_group
def get_group(self, uuid=None): """Get group data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: group json """ if uuid is None: uuid = self.uuid group_data = self.get('group', params={'uuid': uuid}) return group_data
python
def get_group(self, uuid=None): if uuid is None: uuid = self.uuid group_data = self.get('group', params={'uuid': uuid}) return group_data
[ "def", "get_group", "(", "self", ",", "uuid", "=", "None", ")", ":", "if", "uuid", "is", "None", ":", "uuid", "=", "self", ".", "uuid", "group_data", "=", "self", ".", "get", "(", "'group'", ",", "params", "=", "{", "'uuid'", ":", "uuid", "}", ")...
Get group data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: group json
[ "Get", "group", "data", "based", "on", "uuid", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L32-L49
6,755
mitodl/PyLmod
pylmod/membership.py
Membership.get_group_id
def get_group_id(self, uuid=None): """Get group id based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No group data was returned. requests.RequestException: Exception connection error Returns: int: numeric group id """ group_data = self.get_group(uuid) try: return group_data['response']['docs'][0]['id'] except (KeyError, IndexError): failure_message = ('Error in get_group response data - ' 'got {0}'.format(group_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message)
python
def get_group_id(self, uuid=None): group_data = self.get_group(uuid) try: return group_data['response']['docs'][0]['id'] except (KeyError, IndexError): failure_message = ('Error in get_group response data - ' 'got {0}'.format(group_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message)
[ "def", "get_group_id", "(", "self", ",", "uuid", "=", "None", ")", ":", "group_data", "=", "self", ".", "get_group", "(", "uuid", ")", "try", ":", "return", "group_data", "[", "'response'", "]", "[", "'docs'", "]", "[", "0", "]", "[", "'id'", "]", ...
Get group id based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No group data was returned. requests.RequestException: Exception connection error Returns: int: numeric group id
[ "Get", "group", "id", "based", "on", "uuid", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L51-L72
6,756
mitodl/PyLmod
pylmod/membership.py
Membership.get_membership
def get_membership(self, uuid=None): """Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: membership json """ group_id = self.get_group_id(uuid=uuid) uri = 'group/{group_id}/member' mbr_data = self.get(uri.format(group_id=group_id), params=None) return mbr_data
python
def get_membership(self, uuid=None): group_id = self.get_group_id(uuid=uuid) uri = 'group/{group_id}/member' mbr_data = self.get(uri.format(group_id=group_id), params=None) return mbr_data
[ "def", "get_membership", "(", "self", ",", "uuid", "=", "None", ")", ":", "group_id", "=", "self", ".", "get_group_id", "(", "uuid", "=", "uuid", ")", "uri", "=", "'group/{group_id}/member'", "mbr_data", "=", "self", ".", "get", "(", "uri", ".", "format"...
Get membership data based on uuid. Args: uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: No data was returned. requests.RequestException: Exception connection error Returns: dict: membership json
[ "Get", "membership", "data", "based", "on", "uuid", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L74-L91
6,757
mitodl/PyLmod
pylmod/membership.py
Membership.email_has_role
def email_has_role(self, email, role_name, uuid=None): """Determine if an email is associated with a role. Args: email (str): user email role_name (str): user role uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: Unexpected data was returned. requests.RequestException: Exception connection error Returns: bool: True or False if email has role_name """ mbr_data = self.get_membership(uuid=uuid) docs = [] try: docs = mbr_data['response']['docs'] except KeyError: failure_message = ('KeyError in membership data - ' 'got {0}'.format(mbr_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message) if len(docs) == 0: return False has_role = any( (x.get('email') == email and x.get('roleType') == role_name) for x in docs ) if has_role: return True return False
python
def email_has_role(self, email, role_name, uuid=None): mbr_data = self.get_membership(uuid=uuid) docs = [] try: docs = mbr_data['response']['docs'] except KeyError: failure_message = ('KeyError in membership data - ' 'got {0}'.format(mbr_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message) if len(docs) == 0: return False has_role = any( (x.get('email') == email and x.get('roleType') == role_name) for x in docs ) if has_role: return True return False
[ "def", "email_has_role", "(", "self", ",", "email", ",", "role_name", ",", "uuid", "=", "None", ")", ":", "mbr_data", "=", "self", ".", "get_membership", "(", "uuid", "=", "uuid", ")", "docs", "=", "[", "]", "try", ":", "docs", "=", "mbr_data", "[", ...
Determine if an email is associated with a role. Args: email (str): user email role_name (str): user role uuid (str): optional uuid. defaults to self.cuuid Raises: PyLmodUnexpectedData: Unexpected data was returned. requests.RequestException: Exception connection error Returns: bool: True or False if email has role_name
[ "Determine", "if", "an", "email", "is", "associated", "with", "a", "role", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L93-L126
6,758
mitodl/PyLmod
pylmod/membership.py
Membership.get_course_id
def get_course_id(self, course_uuid): """Get course id based on uuid. Args: uuid (str): course uuid, i.e. /project/mitxdemosite Raises: PyLmodUnexpectedData: No course data was returned. requests.RequestException: Exception connection error Returns: int: numeric course id """ course_data = self.get( 'courseguide/course?uuid={uuid}'.format( uuid=course_uuid or self.course_id ), params=None ) try: return course_data['response']['docs'][0]['id'] except KeyError: failure_message = ('KeyError in get_course_id - ' 'got {0}'.format(course_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message) except TypeError: failure_message = ('TypeError in get_course_id - ' 'got {0}'.format(course_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message)
python
def get_course_id(self, course_uuid): course_data = self.get( 'courseguide/course?uuid={uuid}'.format( uuid=course_uuid or self.course_id ), params=None ) try: return course_data['response']['docs'][0]['id'] except KeyError: failure_message = ('KeyError in get_course_id - ' 'got {0}'.format(course_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message) except TypeError: failure_message = ('TypeError in get_course_id - ' 'got {0}'.format(course_data)) log.exception(failure_message) raise PyLmodUnexpectedData(failure_message)
[ "def", "get_course_id", "(", "self", ",", "course_uuid", ")", ":", "course_data", "=", "self", ".", "get", "(", "'courseguide/course?uuid={uuid}'", ".", "format", "(", "uuid", "=", "course_uuid", "or", "self", ".", "course_id", ")", ",", "params", "=", "None...
Get course id based on uuid. Args: uuid (str): course uuid, i.e. /project/mitxdemosite Raises: PyLmodUnexpectedData: No course data was returned. requests.RequestException: Exception connection error Returns: int: numeric course id
[ "Get", "course", "id", "based", "on", "uuid", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L128-L159
6,759
mitodl/PyLmod
pylmod/membership.py
Membership.get_course_guide_staff
def get_course_guide_staff(self, course_id=''): """Get the staff roster for a course. Get a list of staff members for a given course, specified by a course id. Args: course_id (int): unique identifier for course, i.e. ``2314`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of dictionaries containing staff data An example return value is: .. code-block:: python [ { u'displayName': u'Huey Duck', u'role': u'TA', u'sortableDisplayName': u'Duck, Huey' }, { u'displayName': u'Louie Duck', u'role': u'CourseAdmin', u'sortableDisplayName': u'Duck, Louie' }, { u'displayName': u'Benjamin Franklin', u'role': u'CourseAdmin', u'sortableDisplayName': u'Franklin, Benjamin' }, { u'displayName': u'George Washington', u'role': u'Instructor', u'sortableDisplayName': u'Washington, George' }, ] """ staff_data = self.get( 'courseguide/course/{courseId}/staff'.format( courseId=course_id or self.course_id ), params=None ) return staff_data['response']['docs']
python
def get_course_guide_staff(self, course_id=''): staff_data = self.get( 'courseguide/course/{courseId}/staff'.format( courseId=course_id or self.course_id ), params=None ) return staff_data['response']['docs']
[ "def", "get_course_guide_staff", "(", "self", ",", "course_id", "=", "''", ")", ":", "staff_data", "=", "self", ".", "get", "(", "'courseguide/course/{courseId}/staff'", ".", "format", "(", "courseId", "=", "course_id", "or", "self", ".", "course_id", ")", ","...
Get the staff roster for a course. Get a list of staff members for a given course, specified by a course id. Args: course_id (int): unique identifier for course, i.e. ``2314`` Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: list of dictionaries containing staff data An example return value is: .. code-block:: python [ { u'displayName': u'Huey Duck', u'role': u'TA', u'sortableDisplayName': u'Duck, Huey' }, { u'displayName': u'Louie Duck', u'role': u'CourseAdmin', u'sortableDisplayName': u'Duck, Louie' }, { u'displayName': u'Benjamin Franklin', u'role': u'CourseAdmin', u'sortableDisplayName': u'Franklin, Benjamin' }, { u'displayName': u'George Washington', u'role': u'Instructor', u'sortableDisplayName': u'Washington, George' }, ]
[ "Get", "the", "staff", "roster", "for", "a", "course", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/membership.py#L161-L210
6,760
mitodl/PyLmod
pylmod/base.py
Base._data_to_json
def _data_to_json(data): """Convert to json if it isn't already a string. Args: data (str): data to convert to json """ if type(data) not in [str, unicode]: data = json.dumps(data) return data
python
def _data_to_json(data): if type(data) not in [str, unicode]: data = json.dumps(data) return data
[ "def", "_data_to_json", "(", "data", ")", ":", "if", "type", "(", "data", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "return", "data" ]
Convert to json if it isn't already a string. Args: data (str): data to convert to json
[ "Convert", "to", "json", "if", "it", "isn", "t", "already", "a", "string", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L69-L77
6,761
mitodl/PyLmod
pylmod/base.py
Base._url_format
def _url_format(self, service): """Generate URL from urlbase and service. Args: service (str): The endpoint service to use, i.e. gradebook Returns: str: URL to where the request should be made """ base_service_url = '{base}{service}'.format( base=self.urlbase, service=service ) return base_service_url
python
def _url_format(self, service): base_service_url = '{base}{service}'.format( base=self.urlbase, service=service ) return base_service_url
[ "def", "_url_format", "(", "self", ",", "service", ")", ":", "base_service_url", "=", "'{base}{service}'", ".", "format", "(", "base", "=", "self", ".", "urlbase", ",", "service", "=", "service", ")", "return", "base_service_url" ]
Generate URL from urlbase and service. Args: service (str): The endpoint service to use, i.e. gradebook Returns: str: URL to where the request should be made
[ "Generate", "URL", "from", "urlbase", "and", "service", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L79-L91
6,762
mitodl/PyLmod
pylmod/base.py
Base.rest_action
def rest_action(self, func, url, **kwargs): """Routine to do low-level REST operation, with retry. Args: func (callable): API function to call url (str): service URL endpoint kwargs (dict): addition parameters Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response """ try: response = func(url, timeout=self.TIMEOUT, **kwargs) except requests.RequestException, err: log.exception( "[PyLmod] Error - connection error in " "rest_action, err=%s", err ) raise err try: return response.json() except ValueError, err: log.exception('Unable to decode %s', response.content) raise err
python
def rest_action(self, func, url, **kwargs): try: response = func(url, timeout=self.TIMEOUT, **kwargs) except requests.RequestException, err: log.exception( "[PyLmod] Error - connection error in " "rest_action, err=%s", err ) raise err try: return response.json() except ValueError, err: log.exception('Unable to decode %s', response.content) raise err
[ "def", "rest_action", "(", "self", ",", "func", ",", "url", ",", "*", "*", "kwargs", ")", ":", "try", ":", "response", "=", "func", "(", "url", ",", "timeout", "=", "self", ".", "TIMEOUT", ",", "*", "*", "kwargs", ")", "except", "requests", ".", ...
Routine to do low-level REST operation, with retry. Args: func (callable): API function to call url (str): service URL endpoint kwargs (dict): addition parameters Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response
[ "Routine", "to", "do", "low", "-", "level", "REST", "operation", "with", "retry", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L93-L120
6,763
mitodl/PyLmod
pylmod/base.py
Base.get
def get(self, service, params=None): """Generic GET operation for retrieving data from Learning Modules API. .. code-block:: python gbk.get('students/{gradebookId}', params=params, gradebookId=gbid) Args: service (str): The endpoint service to use, i.e. gradebook params (dict): additional parameters to add to the call Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response """ url = self._url_format(service) if params is None: params = {} return self.rest_action(self._session.get, url, params=params)
python
def get(self, service, params=None): url = self._url_format(service) if params is None: params = {} return self.rest_action(self._session.get, url, params=params)
[ "def", "get", "(", "self", ",", "service", ",", "params", "=", "None", ")", ":", "url", "=", "self", ".", "_url_format", "(", "service", ")", "if", "params", "is", "None", ":", "params", "=", "{", "}", "return", "self", ".", "rest_action", "(", "se...
Generic GET operation for retrieving data from Learning Modules API. .. code-block:: python gbk.get('students/{gradebookId}', params=params, gradebookId=gbid) Args: service (str): The endpoint service to use, i.e. gradebook params (dict): additional parameters to add to the call Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response
[ "Generic", "GET", "operation", "for", "retrieving", "data", "from", "Learning", "Modules", "API", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L122-L143
6,764
mitodl/PyLmod
pylmod/base.py
Base.post
def post(self, service, data): """Generic POST operation for sending data to Learning Modules API. Data should be a JSON string or a dict. If it is not a string, it is turned into a JSON string for the POST body. Args: service (str): The endpoint service to use, i.e. gradebook data (json or dict): the data payload Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response """ url = self._url_format(service) data = Base._data_to_json(data) # Add content-type for body in POST. headers = {'content-type': 'application/json'} return self.rest_action(self._session.post, url, data=data, headers=headers)
python
def post(self, service, data): url = self._url_format(service) data = Base._data_to_json(data) # Add content-type for body in POST. headers = {'content-type': 'application/json'} return self.rest_action(self._session.post, url, data=data, headers=headers)
[ "def", "post", "(", "self", ",", "service", ",", "data", ")", ":", "url", "=", "self", ".", "_url_format", "(", "service", ")", "data", "=", "Base", ".", "_data_to_json", "(", "data", ")", "# Add content-type for body in POST.", "headers", "=", "{", "'cont...
Generic POST operation for sending data to Learning Modules API. Data should be a JSON string or a dict. If it is not a string, it is turned into a JSON string for the POST body. Args: service (str): The endpoint service to use, i.e. gradebook data (json or dict): the data payload Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response
[ "Generic", "POST", "operation", "for", "sending", "data", "to", "Learning", "Modules", "API", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L145-L167
6,765
mitodl/PyLmod
pylmod/base.py
Base.delete
def delete(self, service): """Generic DELETE operation for Learning Modules API. Args: service (str): The endpoint service to use, i.e. gradebook Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response """ url = self._url_format(service) return self.rest_action( self._session.delete, url )
python
def delete(self, service): url = self._url_format(service) return self.rest_action( self._session.delete, url )
[ "def", "delete", "(", "self", ",", "service", ")", ":", "url", "=", "self", ".", "_url_format", "(", "service", ")", "return", "self", ".", "rest_action", "(", "self", ".", "_session", ".", "delete", ",", "url", ")" ]
Generic DELETE operation for Learning Modules API. Args: service (str): The endpoint service to use, i.e. gradebook Raises: requests.RequestException: Exception connection error ValueError: Unable to decode response content Returns: list: the json-encoded content of the response
[ "Generic", "DELETE", "operation", "for", "Learning", "Modules", "API", "." ]
b798b86c33d1eb615e7cd4f3457b5c15da1d86e0
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/base.py#L169-L185
6,766
jmcarp/sqlalchemy-postgres-copy
postgres_copy/__init__.py
raw_connection_from
def raw_connection_from(engine_or_conn): """Extract a raw_connection and determine if it should be automatically closed. Only connections opened by this package will be closed automatically. """ if hasattr(engine_or_conn, 'cursor'): return engine_or_conn, False if hasattr(engine_or_conn, 'connection'): return engine_or_conn.connection, False return engine_or_conn.raw_connection(), True
python
def raw_connection_from(engine_or_conn): if hasattr(engine_or_conn, 'cursor'): return engine_or_conn, False if hasattr(engine_or_conn, 'connection'): return engine_or_conn.connection, False return engine_or_conn.raw_connection(), True
[ "def", "raw_connection_from", "(", "engine_or_conn", ")", ":", "if", "hasattr", "(", "engine_or_conn", ",", "'cursor'", ")", ":", "return", "engine_or_conn", ",", "False", "if", "hasattr", "(", "engine_or_conn", ",", "'connection'", ")", ":", "return", "engine_o...
Extract a raw_connection and determine if it should be automatically closed. Only connections opened by this package will be closed automatically.
[ "Extract", "a", "raw_connection", "and", "determine", "if", "it", "should", "be", "automatically", "closed", "." ]
01ef522e8e46a6961e227069d465b0cb93e42383
https://github.com/jmcarp/sqlalchemy-postgres-copy/blob/01ef522e8e46a6961e227069d465b0cb93e42383/postgres_copy/__init__.py#L83-L92
6,767
biocommons/biocommons.seqrepo
biocommons/seqrepo/py2compat/_makedirs.py
makedirs
def makedirs(name, mode=0o777, exist_ok=False): """cheapo replacement for py3 makedirs with support for exist_ok """ if os.path.exists(name): if not exist_ok: raise FileExistsError("File exists: " + name) else: os.makedirs(name, mode)
python
def makedirs(name, mode=0o777, exist_ok=False): if os.path.exists(name): if not exist_ok: raise FileExistsError("File exists: " + name) else: os.makedirs(name, mode)
[ "def", "makedirs", "(", "name", ",", "mode", "=", "0o777", ",", "exist_ok", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "name", ")", ":", "if", "not", "exist_ok", ":", "raise", "FileExistsError", "(", "\"File exists: \"", "+", ...
cheapo replacement for py3 makedirs with support for exist_ok
[ "cheapo", "replacement", "for", "py3", "makedirs", "with", "support", "for", "exist_ok" ]
fb6d88682cb73ee6971cfa47d4dcd90a9c649167
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/biocommons/seqrepo/py2compat/_makedirs.py#L10-L19
6,768
biocommons/biocommons.seqrepo
misc/threading-verification.py
fetch_in_thread
def fetch_in_thread(sr, nsa): """fetch a sequence in a thread """ def fetch_seq(q, nsa): pid, ppid = os.getpid(), os.getppid() q.put((pid, ppid, sr[nsa])) q = Queue() p = Process(target=fetch_seq, args=(q, nsa)) p.start() pid, ppid, seq = q.get() p.join() assert pid != ppid, "sequence was not fetched from thread" return pid, ppid, seq
python
def fetch_in_thread(sr, nsa): def fetch_seq(q, nsa): pid, ppid = os.getpid(), os.getppid() q.put((pid, ppid, sr[nsa])) q = Queue() p = Process(target=fetch_seq, args=(q, nsa)) p.start() pid, ppid, seq = q.get() p.join() assert pid != ppid, "sequence was not fetched from thread" return pid, ppid, seq
[ "def", "fetch_in_thread", "(", "sr", ",", "nsa", ")", ":", "def", "fetch_seq", "(", "q", ",", "nsa", ")", ":", "pid", ",", "ppid", "=", "os", ".", "getpid", "(", ")", ",", "os", ".", "getppid", "(", ")", "q", ".", "put", "(", "(", "pid", ",",...
fetch a sequence in a thread
[ "fetch", "a", "sequence", "in", "a", "thread" ]
fb6d88682cb73ee6971cfa47d4dcd90a9c649167
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/misc/threading-verification.py#L32-L48
6,769
junaruga/rpm-py-installer
install.py
Application.run
def run(self): """Run install process.""" try: self.linux.verify_system_status() except InstallSkipError: Log.info('Install skipped.') return work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer') Log.info("Created working directory '{0}'".format(work_dir)) with Cmd.pushd(work_dir): self.rpm_py.download_and_install() if not self.python.is_python_binding_installed(): message = ( 'RPM Python binding failed to install ' 'with unknown reason.' ) raise InstallError(message) # TODO: Print installed module name and version as INFO. if self.is_work_dir_removed: shutil.rmtree(work_dir) Log.info("Removed working directory '{0}'".format(work_dir)) else: Log.info("Saved working directory '{0}'".format(work_dir))
python
def run(self): try: self.linux.verify_system_status() except InstallSkipError: Log.info('Install skipped.') return work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer') Log.info("Created working directory '{0}'".format(work_dir)) with Cmd.pushd(work_dir): self.rpm_py.download_and_install() if not self.python.is_python_binding_installed(): message = ( 'RPM Python binding failed to install ' 'with unknown reason.' ) raise InstallError(message) # TODO: Print installed module name and version as INFO. if self.is_work_dir_removed: shutil.rmtree(work_dir) Log.info("Removed working directory '{0}'".format(work_dir)) else: Log.info("Saved working directory '{0}'".format(work_dir))
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "linux", ".", "verify_system_status", "(", ")", "except", "InstallSkipError", ":", "Log", ".", "info", "(", "'Install skipped.'", ")", "return", "work_dir", "=", "tempfile", ".", "mkdtemp", "(",...
Run install process.
[ "Run", "install", "process", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L28-L54
6,770
junaruga/rpm-py-installer
install.py
RpmPy.download_and_install
def download_and_install(self): """Download and install RPM Python binding.""" if self.is_installed_from_bin: try: self.installer.install_from_rpm_py_package() return except RpmPyPackageNotFoundError as e: Log.warn('RPM Py Package not found. reason: {0}'.format(e)) # Pass to try to install from the source. pass # Download and install from the source. top_dir_name = self.downloader.download_and_expand() rpm_py_dir = os.path.join(top_dir_name, 'python') setup_py_in_found = False with Cmd.pushd(rpm_py_dir): if self.installer.setup_py.exists_in_path(): setup_py_in_found = True self.installer.run() if not setup_py_in_found: self.installer.install_from_rpm_py_package()
python
def download_and_install(self): if self.is_installed_from_bin: try: self.installer.install_from_rpm_py_package() return except RpmPyPackageNotFoundError as e: Log.warn('RPM Py Package not found. reason: {0}'.format(e)) # Pass to try to install from the source. pass # Download and install from the source. top_dir_name = self.downloader.download_and_expand() rpm_py_dir = os.path.join(top_dir_name, 'python') setup_py_in_found = False with Cmd.pushd(rpm_py_dir): if self.installer.setup_py.exists_in_path(): setup_py_in_found = True self.installer.run() if not setup_py_in_found: self.installer.install_from_rpm_py_package()
[ "def", "download_and_install", "(", "self", ")", ":", "if", "self", ".", "is_installed_from_bin", ":", "try", ":", "self", ".", "installer", ".", "install_from_rpm_py_package", "(", ")", "return", "except", "RpmPyPackageNotFoundError", "as", "e", ":", "Log", "."...
Download and install RPM Python binding.
[ "Download", "and", "install", "RPM", "Python", "binding", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L161-L184
6,771
junaruga/rpm-py-installer
install.py
RpmPyVersion.git_branch
def git_branch(self): """Git branch name.""" info = self.info return 'rpm-{major}.{minor}.x'.format( major=info[0], minor=info[1])
python
def git_branch(self): info = self.info return 'rpm-{major}.{minor}.x'.format( major=info[0], minor=info[1])
[ "def", "git_branch", "(", "self", ")", ":", "info", "=", "self", ".", "info", "return", "'rpm-{major}.{minor}.x'", ".", "format", "(", "major", "=", "info", "[", "0", "]", ",", "minor", "=", "info", "[", "1", "]", ")" ]
Git branch name.
[ "Git", "branch", "name", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L215-L219
6,772
junaruga/rpm-py-installer
install.py
SetupPy.add_patchs_to_build_without_pkg_config
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir): """Add patches to remove pkg-config command and rpm.pc part. Replace with given library_path: lib_dir and include_path: include_dir without rpm.pc file. """ additional_patches = [ { 'src': r"pkgconfig\('--libs-only-L'\)", 'dest': "['{0}']".format(lib_dir), }, # Considering -libs-only-l and -libs-only-L # https://github.com/rpm-software-management/rpm/pull/327 { 'src': r"pkgconfig\('--libs(-only-l)?'\)", 'dest': "['rpm', 'rpmio']", 'required': True, }, { 'src': r"pkgconfig\('--cflags'\)", 'dest': "['{0}']".format(include_dir), 'required': True, }, ] self.patches.extend(additional_patches)
python
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir): additional_patches = [ { 'src': r"pkgconfig\('--libs-only-L'\)", 'dest': "['{0}']".format(lib_dir), }, # Considering -libs-only-l and -libs-only-L # https://github.com/rpm-software-management/rpm/pull/327 { 'src': r"pkgconfig\('--libs(-only-l)?'\)", 'dest': "['rpm', 'rpmio']", 'required': True, }, { 'src': r"pkgconfig\('--cflags'\)", 'dest': "['{0}']".format(include_dir), 'required': True, }, ] self.patches.extend(additional_patches)
[ "def", "add_patchs_to_build_without_pkg_config", "(", "self", ",", "lib_dir", ",", "include_dir", ")", ":", "additional_patches", "=", "[", "{", "'src'", ":", "r\"pkgconfig\\('--libs-only-L'\\)\"", ",", "'dest'", ":", "\"['{0}']\"", ".", "format", "(", "lib_dir", ")...
Add patches to remove pkg-config command and rpm.pc part. Replace with given library_path: lib_dir and include_path: include_dir without rpm.pc file.
[ "Add", "patches", "to", "remove", "pkg", "-", "config", "command", "and", "rpm", ".", "pc", "part", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L323-L347
6,773
junaruga/rpm-py-installer
install.py
SetupPy.apply_and_save
def apply_and_save(self): """Apply replaced words and patches, and save setup.py file.""" patches = self.patches content = None with open(self.IN_PATH) as f_in: # As setup.py.in file size is 2.4 KByte. # it's fine to read entire content. content = f_in.read() # Replace words. for key in self.replaced_word_dict: content = content.replace(key, self.replaced_word_dict[key]) # Apply patches. out_patches = [] for patch in patches: pattern = re.compile(patch['src'], re.MULTILINE) (content, subs_num) = re.subn(pattern, patch['dest'], content) if subs_num > 0: patch['applied'] = True out_patches.append(patch) for patch in out_patches: if patch.get('required') and not patch.get('applied'): Log.warn('Patch not applied {0}'.format(patch['src'])) with open(self.OUT_PATH, 'w') as f_out: f_out.write(content) self.pathces = out_patches # Release content data to make it released by GC quickly. content = None
python
def apply_and_save(self): patches = self.patches content = None with open(self.IN_PATH) as f_in: # As setup.py.in file size is 2.4 KByte. # it's fine to read entire content. content = f_in.read() # Replace words. for key in self.replaced_word_dict: content = content.replace(key, self.replaced_word_dict[key]) # Apply patches. out_patches = [] for patch in patches: pattern = re.compile(patch['src'], re.MULTILINE) (content, subs_num) = re.subn(pattern, patch['dest'], content) if subs_num > 0: patch['applied'] = True out_patches.append(patch) for patch in out_patches: if patch.get('required') and not patch.get('applied'): Log.warn('Patch not applied {0}'.format(patch['src'])) with open(self.OUT_PATH, 'w') as f_out: f_out.write(content) self.pathces = out_patches # Release content data to make it released by GC quickly. content = None
[ "def", "apply_and_save", "(", "self", ")", ":", "patches", "=", "self", ".", "patches", "content", "=", "None", "with", "open", "(", "self", ".", "IN_PATH", ")", "as", "f_in", ":", "# As setup.py.in file size is 2.4 KByte.", "# it's fine to read entire content.", ...
Apply replaced words and patches, and save setup.py file.
[ "Apply", "replaced", "words", "and", "patches", "and", "save", "setup", ".", "py", "file", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L349-L382
6,774
junaruga/rpm-py-installer
install.py
Downloader.download_and_expand
def download_and_expand(self): """Download and expand RPM Python binding.""" top_dir_name = None if self.git_branch: # Download a source by git clone. top_dir_name = self._download_and_expand_by_git() else: # Download a source from the arcihve URL. # Downloading the compressed archive is better than "git clone", # because it is faster. # If download failed due to URL not found, try "git clone". try: top_dir_name = self._download_and_expand_from_archive_url() except RemoteFileNotFoundError: Log.info('Try to download by git clone.') top_dir_name = self._download_and_expand_by_git() return top_dir_name
python
def download_and_expand(self): top_dir_name = None if self.git_branch: # Download a source by git clone. top_dir_name = self._download_and_expand_by_git() else: # Download a source from the arcihve URL. # Downloading the compressed archive is better than "git clone", # because it is faster. # If download failed due to URL not found, try "git clone". try: top_dir_name = self._download_and_expand_from_archive_url() except RemoteFileNotFoundError: Log.info('Try to download by git clone.') top_dir_name = self._download_and_expand_by_git() return top_dir_name
[ "def", "download_and_expand", "(", "self", ")", ":", "top_dir_name", "=", "None", "if", "self", ".", "git_branch", ":", "# Download a source by git clone.", "top_dir_name", "=", "self", ".", "_download_and_expand_by_git", "(", ")", "else", ":", "# Download a source fr...
Download and expand RPM Python binding.
[ "Download", "and", "expand", "RPM", "Python", "binding", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L412-L428
6,775
junaruga/rpm-py-installer
install.py
Installer._make_lib_file_symbolic_links
def _make_lib_file_symbolic_links(self): """Make symbolic links for lib files. Make symbolic links from system library files or downloaded lib files to downloaded source library files. For example, case: Fedora x86_64 Make symbolic links from a. /usr/lib64/librpmio.so* (one of them) b. /usr/lib64/librpm.so* (one of them) c. If rpm-build-libs package is installed, /usr/lib64/librpmbuild.so* (one of them) otherwise, downloaded and extracted rpm-build-libs. ./usr/lib64/librpmbuild.so* (one of them) c. If rpm-build-libs package is installed, /usr/lib64/librpmsign.so* (one of them) otherwise, downloaded and extracted rpm-build-libs. ./usr/lib64/librpmsign.so* (one of them) to a. rpm/rpmio/.libs/librpmio.so b. rpm/lib/.libs/librpm.so c. rpm/build/.libs/librpmbuild.so d. rpm/sign/.libs/librpmsign.so . This is a status after running "make" on actual rpm build process. """ so_file_dict = { 'rpmio': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'rpmio/.libs', 'require': True, }, 'rpm': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'lib/.libs', 'require': True, }, 'rpmbuild': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'build/.libs', 'require': True, }, 'rpmsign': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'sign/.libs', }, } self._update_sym_src_dirs_conditionally(so_file_dict) for name in so_file_dict: so_dict = so_file_dict[name] pattern = 'lib{0}.so*'.format(name) so_files = Cmd.find(so_dict['sym_src_dir'], pattern) if not so_files: is_required = so_dict.get('require', False) if not is_required: message_format = ( "Skip creating symbolic link of " "not existing so file '{0}'" ) Log.debug(message_format.format(name)) continue message = 'so file pattern {0} not found at {1}'.format( pattern, so_dict['sym_src_dir'] ) raise InstallError(message) sym_dst_dir = os.path.abspath('../{0}'.format( so_dict['sym_dst_dir'])) if not os.path.isdir(sym_dst_dir): Cmd.mkdir_p(sym_dst_dir) cmd = 'ln -sf {0} {1}/lib{2}.so'.format(so_files[0], sym_dst_dir, name) Cmd.sh_e(cmd)
python
def _make_lib_file_symbolic_links(self): so_file_dict = { 'rpmio': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'rpmio/.libs', 'require': True, }, 'rpm': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'lib/.libs', 'require': True, }, 'rpmbuild': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'build/.libs', 'require': True, }, 'rpmsign': { 'sym_src_dir': self.rpm.lib_dir, 'sym_dst_dir': 'sign/.libs', }, } self._update_sym_src_dirs_conditionally(so_file_dict) for name in so_file_dict: so_dict = so_file_dict[name] pattern = 'lib{0}.so*'.format(name) so_files = Cmd.find(so_dict['sym_src_dir'], pattern) if not so_files: is_required = so_dict.get('require', False) if not is_required: message_format = ( "Skip creating symbolic link of " "not existing so file '{0}'" ) Log.debug(message_format.format(name)) continue message = 'so file pattern {0} not found at {1}'.format( pattern, so_dict['sym_src_dir'] ) raise InstallError(message) sym_dst_dir = os.path.abspath('../{0}'.format( so_dict['sym_dst_dir'])) if not os.path.isdir(sym_dst_dir): Cmd.mkdir_p(sym_dst_dir) cmd = 'ln -sf {0} {1}/lib{2}.so'.format(so_files[0], sym_dst_dir, name) Cmd.sh_e(cmd)
[ "def", "_make_lib_file_symbolic_links", "(", "self", ")", ":", "so_file_dict", "=", "{", "'rpmio'", ":", "{", "'sym_src_dir'", ":", "self", ".", "rpm", ".", "lib_dir", ",", "'sym_dst_dir'", ":", "'rpmio/.libs'", ",", "'require'", ":", "True", ",", "}", ",", ...
Make symbolic links for lib files. Make symbolic links from system library files or downloaded lib files to downloaded source library files. For example, case: Fedora x86_64 Make symbolic links from a. /usr/lib64/librpmio.so* (one of them) b. /usr/lib64/librpm.so* (one of them) c. If rpm-build-libs package is installed, /usr/lib64/librpmbuild.so* (one of them) otherwise, downloaded and extracted rpm-build-libs. ./usr/lib64/librpmbuild.so* (one of them) c. If rpm-build-libs package is installed, /usr/lib64/librpmsign.so* (one of them) otherwise, downloaded and extracted rpm-build-libs. ./usr/lib64/librpmsign.so* (one of them) to a. rpm/rpmio/.libs/librpmio.so b. rpm/lib/.libs/librpm.so c. rpm/build/.libs/librpmbuild.so d. rpm/sign/.libs/librpmsign.so . This is a status after running "make" on actual rpm build process.
[ "Make", "symbolic", "links", "for", "lib", "files", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L629-L706
6,776
junaruga/rpm-py-installer
install.py
Installer._copy_each_include_files_to_include_dir
def _copy_each_include_files_to_include_dir(self): """Copy include header files for each directory to include directory. Copy include header files from rpm/ rpmio/*.h lib/*.h build/*.h sign/*.h to rpm/ include/ rpm/*.h . This is a status after running "make" on actual rpm build process. """ src_header_dirs = [ 'rpmio', 'lib', 'build', 'sign', ] with Cmd.pushd('..'): src_include_dir = os.path.abspath('./include') for header_dir in src_header_dirs: if not os.path.isdir(header_dir): message_format = "Skip not existing header directory '{0}'" Log.debug(message_format.format(header_dir)) continue header_files = Cmd.find(header_dir, '*.h') for header_file in header_files: pattern = '^{0}/'.format(header_dir) (dst_header_file, subs_num) = re.subn(pattern, '', header_file) if subs_num == 0: message = 'Failed to replace header_file: {0}'.format( header_file) raise ValueError(message) dst_header_file = os.path.abspath( os.path.join(src_include_dir, 'rpm', dst_header_file) ) dst_dir = os.path.dirname(dst_header_file) if not os.path.isdir(dst_dir): Cmd.mkdir_p(dst_dir) shutil.copyfile(header_file, dst_header_file)
python
def _copy_each_include_files_to_include_dir(self): src_header_dirs = [ 'rpmio', 'lib', 'build', 'sign', ] with Cmd.pushd('..'): src_include_dir = os.path.abspath('./include') for header_dir in src_header_dirs: if not os.path.isdir(header_dir): message_format = "Skip not existing header directory '{0}'" Log.debug(message_format.format(header_dir)) continue header_files = Cmd.find(header_dir, '*.h') for header_file in header_files: pattern = '^{0}/'.format(header_dir) (dst_header_file, subs_num) = re.subn(pattern, '', header_file) if subs_num == 0: message = 'Failed to replace header_file: {0}'.format( header_file) raise ValueError(message) dst_header_file = os.path.abspath( os.path.join(src_include_dir, 'rpm', dst_header_file) ) dst_dir = os.path.dirname(dst_header_file) if not os.path.isdir(dst_dir): Cmd.mkdir_p(dst_dir) shutil.copyfile(header_file, dst_header_file)
[ "def", "_copy_each_include_files_to_include_dir", "(", "self", ")", ":", "src_header_dirs", "=", "[", "'rpmio'", ",", "'lib'", ",", "'build'", ",", "'sign'", ",", "]", "with", "Cmd", ".", "pushd", "(", "'..'", ")", ":", "src_include_dir", "=", "os", ".", "...
Copy include header files for each directory to include directory. Copy include header files from rpm/ rpmio/*.h lib/*.h build/*.h sign/*.h to rpm/ include/ rpm/*.h . This is a status after running "make" on actual rpm build process.
[ "Copy", "include", "header", "files", "for", "each", "directory", "to", "include", "directory", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L711-L756
6,777
junaruga/rpm-py-installer
install.py
Installer._rpm_py_has_popt_devel_dep
def _rpm_py_has_popt_devel_dep(self): """Check if the RPM Python binding has a depndency to popt-devel. Search include header files in the source code to check it. """ found = False with open('../include/rpm/rpmlib.h') as f_in: for line in f_in: if re.match(r'^#include .*popt.h.*$', line): found = True break return found
python
def _rpm_py_has_popt_devel_dep(self): found = False with open('../include/rpm/rpmlib.h') as f_in: for line in f_in: if re.match(r'^#include .*popt.h.*$', line): found = True break return found
[ "def", "_rpm_py_has_popt_devel_dep", "(", "self", ")", ":", "found", "=", "False", "with", "open", "(", "'../include/rpm/rpmlib.h'", ")", "as", "f_in", ":", "for", "line", "in", "f_in", ":", "if", "re", ".", "match", "(", "r'^#include .*popt.h.*$'", ",", "li...
Check if the RPM Python binding has a depndency to popt-devel. Search include header files in the source code to check it.
[ "Check", "if", "the", "RPM", "Python", "binding", "has", "a", "depndency", "to", "popt", "-", "devel", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L833-L844
6,778
junaruga/rpm-py-installer
install.py
FedoraInstaller.install_from_rpm_py_package
def install_from_rpm_py_package(self): """Run install from RPM Python binding RPM package.""" self._download_and_extract_rpm_py_package() # Find ./usr/lib64/pythonN.N/site-packages/rpm directory. # A binary built by same version Python with used Python is target # for the safe installation. if self.rpm.has_set_up_py_in(): # If RPM has setup.py.in, this strict check is okay. # Because we can still install from the source. py_dir_name = 'python{0}.{1}'.format( sys.version_info[0], sys.version_info[1]) else: # If RPM does not have setup.py.in such as CentOS6, # Only way to install is by different Python's RPM package. py_dir_name = '*' python_lib_dir_pattern = os.path.join( 'usr', '*', py_dir_name, 'site-packages') rpm_dir_pattern = os.path.join(python_lib_dir_pattern, 'rpm') downloaded_rpm_dirs = glob.glob(rpm_dir_pattern) if not downloaded_rpm_dirs: message = 'Directory with a pattern: {0} not found.'.format( rpm_dir_pattern) raise RpmPyPackageNotFoundError(message) src_rpm_dir = downloaded_rpm_dirs[0] # Remove rpm directory for the possible installed directories. for rpm_dir in self.python.python_lib_rpm_dirs: if os.path.isdir(rpm_dir): Log.debug("Remove existing rpm directory {0}".format(rpm_dir)) shutil.rmtree(rpm_dir) dst_rpm_dir = self.python.python_lib_rpm_dir Log.debug("Copy directory from '{0}' to '{1}'".format( src_rpm_dir, dst_rpm_dir)) shutil.copytree(src_rpm_dir, dst_rpm_dir) file_name_pattern = 'rpm-*.egg-info' rpm_egg_info_pattern = os.path.join( python_lib_dir_pattern, file_name_pattern) downloaded_rpm_egg_infos = glob.glob(rpm_egg_info_pattern) if downloaded_rpm_egg_infos: existing_rpm_egg_info_pattern = os.path.join( self.python.python_lib_dir, file_name_pattern) existing_rpm_egg_infos = glob.glob(existing_rpm_egg_info_pattern) for existing_rpm_egg_info in existing_rpm_egg_infos: Log.debug("Remove existing rpm egg info file '{0}'".format( existing_rpm_egg_info)) os.remove(existing_rpm_egg_info) Log.debug("Copy file from '{0}' to '{1}'".format( downloaded_rpm_egg_infos[0], self.python.python_lib_dir)) shutil.copy2(downloaded_rpm_egg_infos[0], self.python.python_lib_dir)
python
def install_from_rpm_py_package(self): self._download_and_extract_rpm_py_package() # Find ./usr/lib64/pythonN.N/site-packages/rpm directory. # A binary built by same version Python with used Python is target # for the safe installation. if self.rpm.has_set_up_py_in(): # If RPM has setup.py.in, this strict check is okay. # Because we can still install from the source. py_dir_name = 'python{0}.{1}'.format( sys.version_info[0], sys.version_info[1]) else: # If RPM does not have setup.py.in such as CentOS6, # Only way to install is by different Python's RPM package. py_dir_name = '*' python_lib_dir_pattern = os.path.join( 'usr', '*', py_dir_name, 'site-packages') rpm_dir_pattern = os.path.join(python_lib_dir_pattern, 'rpm') downloaded_rpm_dirs = glob.glob(rpm_dir_pattern) if not downloaded_rpm_dirs: message = 'Directory with a pattern: {0} not found.'.format( rpm_dir_pattern) raise RpmPyPackageNotFoundError(message) src_rpm_dir = downloaded_rpm_dirs[0] # Remove rpm directory for the possible installed directories. for rpm_dir in self.python.python_lib_rpm_dirs: if os.path.isdir(rpm_dir): Log.debug("Remove existing rpm directory {0}".format(rpm_dir)) shutil.rmtree(rpm_dir) dst_rpm_dir = self.python.python_lib_rpm_dir Log.debug("Copy directory from '{0}' to '{1}'".format( src_rpm_dir, dst_rpm_dir)) shutil.copytree(src_rpm_dir, dst_rpm_dir) file_name_pattern = 'rpm-*.egg-info' rpm_egg_info_pattern = os.path.join( python_lib_dir_pattern, file_name_pattern) downloaded_rpm_egg_infos = glob.glob(rpm_egg_info_pattern) if downloaded_rpm_egg_infos: existing_rpm_egg_info_pattern = os.path.join( self.python.python_lib_dir, file_name_pattern) existing_rpm_egg_infos = glob.glob(existing_rpm_egg_info_pattern) for existing_rpm_egg_info in existing_rpm_egg_infos: Log.debug("Remove existing rpm egg info file '{0}'".format( existing_rpm_egg_info)) os.remove(existing_rpm_egg_info) Log.debug("Copy file from '{0}' to '{1}'".format( downloaded_rpm_egg_infos[0], self.python.python_lib_dir)) shutil.copy2(downloaded_rpm_egg_infos[0], self.python.python_lib_dir)
[ "def", "install_from_rpm_py_package", "(", "self", ")", ":", "self", ".", "_download_and_extract_rpm_py_package", "(", ")", "# Find ./usr/lib64/pythonN.N/site-packages/rpm directory.", "# A binary built by same version Python with used Python is target", "# for the safe installation.", "...
Run install from RPM Python binding RPM package.
[ "Run", "install", "from", "RPM", "Python", "binding", "RPM", "package", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L898-L953
6,779
junaruga/rpm-py-installer
install.py
Linux.get_instance
def get_instance(cls, python, rpm_path, **kwargs): """Get OS object.""" linux = None if Cmd.which('apt-get'): linux = DebianLinux(python, rpm_path, **kwargs) else: linux = FedoraLinux(python, rpm_path, **kwargs) return linux
python
def get_instance(cls, python, rpm_path, **kwargs): linux = None if Cmd.which('apt-get'): linux = DebianLinux(python, rpm_path, **kwargs) else: linux = FedoraLinux(python, rpm_path, **kwargs) return linux
[ "def", "get_instance", "(", "cls", ",", "python", ",", "rpm_path", ",", "*", "*", "kwargs", ")", ":", "linux", "=", "None", "if", "Cmd", ".", "which", "(", "'apt-get'", ")", ":", "linux", "=", "DebianLinux", "(", "python", ",", "rpm_path", ",", "*", ...
Get OS object.
[ "Get", "OS", "object", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1175-L1182
6,780
junaruga/rpm-py-installer
install.py
Python.python_lib_rpm_dirs
def python_lib_rpm_dirs(self): """Both arch and non-arch site-packages directories.""" libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir] def append_rpm(path): return os.path.join(path, 'rpm') return map(append_rpm, libs)
python
def python_lib_rpm_dirs(self): libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir] def append_rpm(path): return os.path.join(path, 'rpm') return map(append_rpm, libs)
[ "def", "python_lib_rpm_dirs", "(", "self", ")", ":", "libs", "=", "[", "self", ".", "python_lib_arch_dir", ",", "self", ".", "python_lib_non_arch_dir", "]", "def", "append_rpm", "(", "path", ")", ":", "return", "os", ".", "path", ".", "join", "(", "path", ...
Both arch and non-arch site-packages directories.
[ "Both", "arch", "and", "non", "-", "arch", "site", "-", "packages", "directories", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1325-L1332
6,781
junaruga/rpm-py-installer
install.py
Rpm.version
def version(self): """RPM vesion string.""" stdout = Cmd.sh_e_out('{0} --version'.format(self.rpm_path)) rpm_version = stdout.split()[2] return rpm_version
python
def version(self): stdout = Cmd.sh_e_out('{0} --version'.format(self.rpm_path)) rpm_version = stdout.split()[2] return rpm_version
[ "def", "version", "(", "self", ")", ":", "stdout", "=", "Cmd", ".", "sh_e_out", "(", "'{0} --version'", ".", "format", "(", "self", ".", "rpm_path", ")", ")", "rpm_version", "=", "stdout", ".", "split", "(", ")", "[", "2", "]", "return", "rpm_version" ...
RPM vesion string.
[ "RPM", "vesion", "string", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1435-L1439
6,782
junaruga/rpm-py-installer
install.py
Rpm.is_system_rpm
def is_system_rpm(self): """Check if the RPM is system RPM.""" sys_rpm_paths = [ '/usr/bin/rpm', # On CentOS6, system RPM is installed in this directory. '/bin/rpm', ] matched = False for sys_rpm_path in sys_rpm_paths: if self.rpm_path.startswith(sys_rpm_path): matched = True break return matched
python
def is_system_rpm(self): sys_rpm_paths = [ '/usr/bin/rpm', # On CentOS6, system RPM is installed in this directory. '/bin/rpm', ] matched = False for sys_rpm_path in sys_rpm_paths: if self.rpm_path.startswith(sys_rpm_path): matched = True break return matched
[ "def", "is_system_rpm", "(", "self", ")", ":", "sys_rpm_paths", "=", "[", "'/usr/bin/rpm'", ",", "# On CentOS6, system RPM is installed in this directory.", "'/bin/rpm'", ",", "]", "matched", "=", "False", "for", "sys_rpm_path", "in", "sys_rpm_paths", ":", "if", "self...
Check if the RPM is system RPM.
[ "Check", "if", "the", "RPM", "is", "system", "RPM", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1447-L1459
6,783
junaruga/rpm-py-installer
install.py
Rpm.is_package_installed
def is_package_installed(self, package_name): """Check if the RPM package is installed.""" if not package_name: raise ValueError('package_name required.') installed = True try: Cmd.sh_e('{0} --query {1} --quiet'.format(self.rpm_path, package_name)) except InstallError: installed = False return installed
python
def is_package_installed(self, package_name): if not package_name: raise ValueError('package_name required.') installed = True try: Cmd.sh_e('{0} --query {1} --quiet'.format(self.rpm_path, package_name)) except InstallError: installed = False return installed
[ "def", "is_package_installed", "(", "self", ",", "package_name", ")", ":", "if", "not", "package_name", ":", "raise", "ValueError", "(", "'package_name required.'", ")", "installed", "=", "True", "try", ":", "Cmd", ".", "sh_e", "(", "'{0} --query {1} --quiet'", ...
Check if the RPM package is installed.
[ "Check", "if", "the", "RPM", "package", "is", "installed", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1465-L1476
6,784
junaruga/rpm-py-installer
install.py
FedoraRpm.is_downloadable
def is_downloadable(self): """Return if rpm is downloadable by the package command. Check if dnf or yum plugin package exists. """ is_plugin_avaiable = False if self.is_dnf: is_plugin_avaiable = self.is_package_installed( 'dnf-plugins-core') else: """ yum environment. Make sure # yum -y --downloadonly --downloaddir=. install package_name is only available for root user. yumdownloader in yum-utils is available for normal user. https://access.redhat.com/solutions/10154 """ is_plugin_avaiable = self.is_package_installed( 'yum-utils') return is_plugin_avaiable
python
def is_downloadable(self): is_plugin_avaiable = False if self.is_dnf: is_plugin_avaiable = self.is_package_installed( 'dnf-plugins-core') else: """ yum environment. Make sure # yum -y --downloadonly --downloaddir=. install package_name is only available for root user. yumdownloader in yum-utils is available for normal user. https://access.redhat.com/solutions/10154 """ is_plugin_avaiable = self.is_package_installed( 'yum-utils') return is_plugin_avaiable
[ "def", "is_downloadable", "(", "self", ")", ":", "is_plugin_avaiable", "=", "False", "if", "self", ".", "is_dnf", ":", "is_plugin_avaiable", "=", "self", ".", "is_package_installed", "(", "'dnf-plugins-core'", ")", "else", ":", "\"\"\" yum environment.\n Ma...
Return if rpm is downloadable by the package command. Check if dnf or yum plugin package exists.
[ "Return", "if", "rpm", "is", "downloadable", "by", "the", "package", "command", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1561-L1581
6,785
junaruga/rpm-py-installer
install.py
FedoraRpm.download
def download(self, package_name): """Download given package.""" if not package_name: ValueError('package_name required.') if self.is_dnf: cmd = 'dnf download {0}.{1}'.format(package_name, self.arch) else: cmd = 'yumdownloader {0}.{1}'.format(package_name, self.arch) try: Cmd.sh_e(cmd, stdout=subprocess.PIPE) except CmdError as e: for out in (e.stdout, e.stderr): for line in out.split('\n'): if re.match(r'^No package [^ ]+ available', line) or \ re.match(r'^No Match for argument', line): raise RemoteFileNotFoundError( 'Package {0} not found on remote'.format( package_name ) ) raise e
python
def download(self, package_name): if not package_name: ValueError('package_name required.') if self.is_dnf: cmd = 'dnf download {0}.{1}'.format(package_name, self.arch) else: cmd = 'yumdownloader {0}.{1}'.format(package_name, self.arch) try: Cmd.sh_e(cmd, stdout=subprocess.PIPE) except CmdError as e: for out in (e.stdout, e.stderr): for line in out.split('\n'): if re.match(r'^No package [^ ]+ available', line) or \ re.match(r'^No Match for argument', line): raise RemoteFileNotFoundError( 'Package {0} not found on remote'.format( package_name ) ) raise e
[ "def", "download", "(", "self", ",", "package_name", ")", ":", "if", "not", "package_name", ":", "ValueError", "(", "'package_name required.'", ")", "if", "self", ".", "is_dnf", ":", "cmd", "=", "'dnf download {0}.{1}'", ".", "format", "(", "package_name", ","...
Download given package.
[ "Download", "given", "package", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1588-L1608
6,786
junaruga/rpm-py-installer
install.py
FedoraRpm.extract
def extract(self, package_name): """Extract given package.""" for cmd in ['rpm2cpio', 'cpio']: if not Cmd.which(cmd): message = '{0} command not found. Install {0}.'.format(cmd) raise InstallError(message) pattern = '{0}*{1}.rpm'.format(package_name, self.arch) rpm_files = Cmd.find('.', pattern) if not rpm_files: raise InstallError('PRM file not found.') cmd = 'rpm2cpio {0} | cpio -idmv'.format(rpm_files[0]) Cmd.sh_e(cmd)
python
def extract(self, package_name): for cmd in ['rpm2cpio', 'cpio']: if not Cmd.which(cmd): message = '{0} command not found. Install {0}.'.format(cmd) raise InstallError(message) pattern = '{0}*{1}.rpm'.format(package_name, self.arch) rpm_files = Cmd.find('.', pattern) if not rpm_files: raise InstallError('PRM file not found.') cmd = 'rpm2cpio {0} | cpio -idmv'.format(rpm_files[0]) Cmd.sh_e(cmd)
[ "def", "extract", "(", "self", ",", "package_name", ")", ":", "for", "cmd", "in", "[", "'rpm2cpio'", ",", "'cpio'", "]", ":", "if", "not", "Cmd", ".", "which", "(", "cmd", ")", ":", "message", "=", "'{0} command not found. Install {0}.'", ".", "format", ...
Extract given package.
[ "Extract", "given", "package", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1610-L1622
6,787
junaruga/rpm-py-installer
install.py
Cmd.sh_e
def sh_e(cls, cmd, **kwargs): """Run the command. It behaves like "sh -e". It raises InstallError if the command failed. """ Log.debug('CMD: {0}'.format(cmd)) cmd_kwargs = { 'shell': True, } cmd_kwargs.update(kwargs) env = os.environ.copy() # Better to parse English output env['LC_ALL'] = 'en_US.utf-8' if 'env' in kwargs: env.update(kwargs['env']) cmd_kwargs['env'] = env # Capture stderr to show it on error message. cmd_kwargs['stderr'] = subprocess.PIPE proc = None try: proc = subprocess.Popen(cmd, **cmd_kwargs) stdout, stderr = proc.communicate() returncode = proc.returncode message_format = ( 'CMD Return Code: [{0}], Stdout: [{1}], Stderr: [{2}]' ) Log.debug(message_format.format(returncode, stdout, stderr)) if stdout is not None: stdout = stdout.decode('utf-8') if stderr is not None: stderr = stderr.decode('utf-8') if returncode != 0: message = 'CMD: [{0}], Return Code: [{1}] at [{2}]'.format( cmd, returncode, os.getcwd()) if stderr is not None: message += ' Stderr: [{0}]'.format(stderr) ie = CmdError(message) ie.stdout = stdout ie.stderr = stderr raise ie return (stdout, stderr) except Exception as e: try: proc.kill() except Exception: pass raise e
python
def sh_e(cls, cmd, **kwargs): Log.debug('CMD: {0}'.format(cmd)) cmd_kwargs = { 'shell': True, } cmd_kwargs.update(kwargs) env = os.environ.copy() # Better to parse English output env['LC_ALL'] = 'en_US.utf-8' if 'env' in kwargs: env.update(kwargs['env']) cmd_kwargs['env'] = env # Capture stderr to show it on error message. cmd_kwargs['stderr'] = subprocess.PIPE proc = None try: proc = subprocess.Popen(cmd, **cmd_kwargs) stdout, stderr = proc.communicate() returncode = proc.returncode message_format = ( 'CMD Return Code: [{0}], Stdout: [{1}], Stderr: [{2}]' ) Log.debug(message_format.format(returncode, stdout, stderr)) if stdout is not None: stdout = stdout.decode('utf-8') if stderr is not None: stderr = stderr.decode('utf-8') if returncode != 0: message = 'CMD: [{0}], Return Code: [{1}] at [{2}]'.format( cmd, returncode, os.getcwd()) if stderr is not None: message += ' Stderr: [{0}]'.format(stderr) ie = CmdError(message) ie.stdout = stdout ie.stderr = stderr raise ie return (stdout, stderr) except Exception as e: try: proc.kill() except Exception: pass raise e
[ "def", "sh_e", "(", "cls", ",", "cmd", ",", "*", "*", "kwargs", ")", ":", "Log", ".", "debug", "(", "'CMD: {0}'", ".", "format", "(", "cmd", ")", ")", "cmd_kwargs", "=", "{", "'shell'", ":", "True", ",", "}", "cmd_kwargs", ".", "update", "(", "kw...
Run the command. It behaves like "sh -e". It raises InstallError if the command failed.
[ "Run", "the", "command", ".", "It", "behaves", "like", "sh", "-", "e", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1707-L1758
6,788
junaruga/rpm-py-installer
install.py
Cmd.sh_e_out
def sh_e_out(cls, cmd, **kwargs): """Run the command. and returns the stdout.""" cmd_kwargs = { 'stdout': subprocess.PIPE, } cmd_kwargs.update(kwargs) return cls.sh_e(cmd, **cmd_kwargs)[0]
python
def sh_e_out(cls, cmd, **kwargs): cmd_kwargs = { 'stdout': subprocess.PIPE, } cmd_kwargs.update(kwargs) return cls.sh_e(cmd, **cmd_kwargs)[0]
[ "def", "sh_e_out", "(", "cls", ",", "cmd", ",", "*", "*", "kwargs", ")", ":", "cmd_kwargs", "=", "{", "'stdout'", ":", "subprocess", ".", "PIPE", ",", "}", "cmd_kwargs", ".", "update", "(", "kwargs", ")", "return", "cls", ".", "sh_e", "(", "cmd", "...
Run the command. and returns the stdout.
[ "Run", "the", "command", ".", "and", "returns", "the", "stdout", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1761-L1767
6,789
junaruga/rpm-py-installer
install.py
Cmd.cd
def cd(cls, directory): """Change directory. It behaves like "cd directory".""" Log.debug('CMD: cd {0}'.format(directory)) os.chdir(directory)
python
def cd(cls, directory): Log.debug('CMD: cd {0}'.format(directory)) os.chdir(directory)
[ "def", "cd", "(", "cls", ",", "directory", ")", ":", "Log", ".", "debug", "(", "'CMD: cd {0}'", ".", "format", "(", "directory", ")", ")", "os", ".", "chdir", "(", "directory", ")" ]
Change directory. It behaves like "cd directory".
[ "Change", "directory", ".", "It", "behaves", "like", "cd", "directory", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1770-L1773
6,790
junaruga/rpm-py-installer
install.py
Cmd.pushd
def pushd(cls, new_dir): """Change directory, and back to previous directory. It behaves like "pushd directory; something; popd". """ previous_dir = os.getcwd() try: new_ab_dir = None if os.path.isabs(new_dir): new_ab_dir = new_dir else: new_ab_dir = os.path.join(previous_dir, new_dir) # Use absolute path to show it on FileNotFoundError message. cls.cd(new_ab_dir) yield finally: cls.cd(previous_dir)
python
def pushd(cls, new_dir): previous_dir = os.getcwd() try: new_ab_dir = None if os.path.isabs(new_dir): new_ab_dir = new_dir else: new_ab_dir = os.path.join(previous_dir, new_dir) # Use absolute path to show it on FileNotFoundError message. cls.cd(new_ab_dir) yield finally: cls.cd(previous_dir)
[ "def", "pushd", "(", "cls", ",", "new_dir", ")", ":", "previous_dir", "=", "os", ".", "getcwd", "(", ")", "try", ":", "new_ab_dir", "=", "None", "if", "os", ".", "path", ".", "isabs", "(", "new_dir", ")", ":", "new_ab_dir", "=", "new_dir", "else", ...
Change directory, and back to previous directory. It behaves like "pushd directory; something; popd".
[ "Change", "directory", "and", "back", "to", "previous", "directory", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1777-L1793
6,791
junaruga/rpm-py-installer
install.py
Cmd.which
def which(cls, cmd): """Return an absolute path of the command. It behaves like "which command". """ abs_path_cmd = None if sys.version_info >= (3, 3): abs_path_cmd = shutil.which(cmd) else: abs_path_cmd = find_executable(cmd) return abs_path_cmd
python
def which(cls, cmd): abs_path_cmd = None if sys.version_info >= (3, 3): abs_path_cmd = shutil.which(cmd) else: abs_path_cmd = find_executable(cmd) return abs_path_cmd
[ "def", "which", "(", "cls", ",", "cmd", ")", ":", "abs_path_cmd", "=", "None", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "3", ")", ":", "abs_path_cmd", "=", "shutil", ".", "which", "(", "cmd", ")", "else", ":", "abs_path_cmd", "=", "fi...
Return an absolute path of the command. It behaves like "which command".
[ "Return", "an", "absolute", "path", "of", "the", "command", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1796-L1806
6,792
junaruga/rpm-py-installer
install.py
Cmd.curl_remote_name
def curl_remote_name(cls, file_url): """Download file_url, and save as a file name of the URL. It behaves like "curl -O or --remote-name". It raises HTTPError if the file_url not found. """ tar_gz_file_name = file_url.split('/')[-1] if sys.version_info >= (3, 2): from urllib.request import urlopen from urllib.error import HTTPError else: from urllib2 import urlopen from urllib2 import HTTPError response = None try: response = urlopen(file_url) except HTTPError as e: message = 'Download failed: URL: {0}, reason: {1}'.format( file_url, e) if 'HTTP Error 404' in str(e): raise RemoteFileNotFoundError(message) else: raise InstallError(message) tar_gz_file_obj = io.BytesIO(response.read()) with open(tar_gz_file_name, 'wb') as f_out: f_out.write(tar_gz_file_obj.read()) return tar_gz_file_name
python
def curl_remote_name(cls, file_url): tar_gz_file_name = file_url.split('/')[-1] if sys.version_info >= (3, 2): from urllib.request import urlopen from urllib.error import HTTPError else: from urllib2 import urlopen from urllib2 import HTTPError response = None try: response = urlopen(file_url) except HTTPError as e: message = 'Download failed: URL: {0}, reason: {1}'.format( file_url, e) if 'HTTP Error 404' in str(e): raise RemoteFileNotFoundError(message) else: raise InstallError(message) tar_gz_file_obj = io.BytesIO(response.read()) with open(tar_gz_file_name, 'wb') as f_out: f_out.write(tar_gz_file_obj.read()) return tar_gz_file_name
[ "def", "curl_remote_name", "(", "cls", ",", "file_url", ")", ":", "tar_gz_file_name", "=", "file_url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ")", ":", "from", "urllib", ".", "...
Download file_url, and save as a file name of the URL. It behaves like "curl -O or --remote-name". It raises HTTPError if the file_url not found.
[ "Download", "file_url", "and", "save", "as", "a", "file", "name", "of", "the", "URL", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1809-L1838
6,793
junaruga/rpm-py-installer
install.py
Cmd.tar_extract
def tar_extract(cls, tar_comp_file_path): """Extract tar.gz or tar bz2 file. It behaves like - tar xzf tar_gz_file_path - tar xjf tar_bz2_file_path It raises tarfile.ReadError if the file is broken. """ try: with contextlib.closing(tarfile.open(tar_comp_file_path)) as tar: tar.extractall() except tarfile.ReadError as e: message_format = ( 'Extract failed: ' 'tar_comp_file_path: {0}, reason: {1}' ) raise InstallError(message_format.format(tar_comp_file_path, e))
python
def tar_extract(cls, tar_comp_file_path): try: with contextlib.closing(tarfile.open(tar_comp_file_path)) as tar: tar.extractall() except tarfile.ReadError as e: message_format = ( 'Extract failed: ' 'tar_comp_file_path: {0}, reason: {1}' ) raise InstallError(message_format.format(tar_comp_file_path, e))
[ "def", "tar_extract", "(", "cls", ",", "tar_comp_file_path", ")", ":", "try", ":", "with", "contextlib", ".", "closing", "(", "tarfile", ".", "open", "(", "tar_comp_file_path", ")", ")", "as", "tar", ":", "tar", ".", "extractall", "(", ")", "except", "ta...
Extract tar.gz or tar bz2 file. It behaves like - tar xzf tar_gz_file_path - tar xjf tar_bz2_file_path It raises tarfile.ReadError if the file is broken.
[ "Extract", "tar", ".", "gz", "or", "tar", "bz2", "file", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1841-L1857
6,794
junaruga/rpm-py-installer
install.py
Cmd.find
def find(cls, searched_dir, pattern): """Find matched files. It does not include symbolic file in the result. """ Log.debug('find {0} with pattern: {1}'.format(searched_dir, pattern)) matched_files = [] for root_dir, dir_names, file_names in os.walk(searched_dir, followlinks=False): for file_name in file_names: if fnmatch.fnmatch(file_name, pattern): file_path = os.path.join(root_dir, file_name) if not os.path.islink(file_path): matched_files.append(file_path) matched_files.sort() return matched_files
python
def find(cls, searched_dir, pattern): Log.debug('find {0} with pattern: {1}'.format(searched_dir, pattern)) matched_files = [] for root_dir, dir_names, file_names in os.walk(searched_dir, followlinks=False): for file_name in file_names: if fnmatch.fnmatch(file_name, pattern): file_path = os.path.join(root_dir, file_name) if not os.path.islink(file_path): matched_files.append(file_path) matched_files.sort() return matched_files
[ "def", "find", "(", "cls", ",", "searched_dir", ",", "pattern", ")", ":", "Log", ".", "debug", "(", "'find {0} with pattern: {1}'", ".", "format", "(", "searched_dir", ",", "pattern", ")", ")", "matched_files", "=", "[", "]", "for", "root_dir", ",", "dir_n...
Find matched files. It does not include symbolic file in the result.
[ "Find", "matched", "files", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1860-L1875
6,795
junaruga/rpm-py-installer
install.py
Utils.version_str2tuple
def version_str2tuple(cls, version_str): """Version info. tuple object. ex. ('4', '14', '0', 'rc1') """ if not isinstance(version_str, str): ValueError('version_str invalid instance.') version_info_list = re.findall(r'[0-9a-zA-Z]+', version_str) def convert_to_int(string): value = None if re.match(r'^\d+$', string): value = int(string) else: value = string return value version_info_list = [convert_to_int(s) for s in version_info_list] return tuple(version_info_list)
python
def version_str2tuple(cls, version_str): if not isinstance(version_str, str): ValueError('version_str invalid instance.') version_info_list = re.findall(r'[0-9a-zA-Z]+', version_str) def convert_to_int(string): value = None if re.match(r'^\d+$', string): value = int(string) else: value = string return value version_info_list = [convert_to_int(s) for s in version_info_list] return tuple(version_info_list)
[ "def", "version_str2tuple", "(", "cls", ",", "version_str", ")", ":", "if", "not", "isinstance", "(", "version_str", ",", "str", ")", ":", "ValueError", "(", "'version_str invalid instance.'", ")", "version_info_list", "=", "re", ".", "findall", "(", "r'[0-9a-zA...
Version info. tuple object. ex. ('4', '14', '0', 'rc1')
[ "Version", "info", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1890-L1909
6,796
junaruga/rpm-py-installer
setup.py
install_rpm_py
def install_rpm_py(): """Install RPM Python binding.""" python_path = sys.executable cmd = '{0} install.py'.format(python_path) exit_status = os.system(cmd) if exit_status != 0: raise Exception('Command failed: {0}'.format(cmd))
python
def install_rpm_py(): python_path = sys.executable cmd = '{0} install.py'.format(python_path) exit_status = os.system(cmd) if exit_status != 0: raise Exception('Command failed: {0}'.format(cmd))
[ "def", "install_rpm_py", "(", ")", ":", "python_path", "=", "sys", ".", "executable", "cmd", "=", "'{0} install.py'", ".", "format", "(", "python_path", ")", "exit_status", "=", "os", ".", "system", "(", "cmd", ")", "if", "exit_status", "!=", "0", ":", "...
Install RPM Python binding.
[ "Install", "RPM", "Python", "binding", "." ]
12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/setup.py#L14-L20
6,797
biocommons/biocommons.seqrepo
biocommons/seqrepo/fastadir/fabgz.py
_get_bgzip_version
def _get_bgzip_version(exe): """return bgzip version as string""" p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communicate() version_line = output[0].splitlines()[1] version = re.match(r"(?:Version:|bgzip \(htslib\))\s+(\d+\.\d+(\.\d+)?)", version_line).group(1) return version
python
def _get_bgzip_version(exe): p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communicate() version_line = output[0].splitlines()[1] version = re.match(r"(?:Version:|bgzip \(htslib\))\s+(\d+\.\d+(\.\d+)?)", version_line).group(1) return version
[ "def", "_get_bgzip_version", "(", "exe", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "exe", ",", "\"-h\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", ...
return bgzip version as string
[ "return", "bgzip", "version", "as", "string" ]
fb6d88682cb73ee6971cfa47d4dcd90a9c649167
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/biocommons/seqrepo/fastadir/fabgz.py#L32-L38
6,798
biocommons/biocommons.seqrepo
biocommons/seqrepo/fastadir/fabgz.py
_find_bgzip
def _find_bgzip(): """return path to bgzip if found and meets version requirements, else exception""" missing_file_exception = OSError if six.PY2 else FileNotFoundError min_bgzip_version = ".".join(map(str, min_bgzip_version_info)) exe = os.environ.get("SEQREPO_BGZIP_PATH", which("bgzip") or "/usr/bin/bgzip") try: bgzip_version = _get_bgzip_version(exe) except AttributeError: raise RuntimeError("Didn't find version string in bgzip executable ({exe})".format(exe=exe)) except missing_file_exception: raise RuntimeError("{exe} doesn't exist; you need to install htslib (See https://github.com/biocommons/biocommons.seqrepo#requirements)".format(exe=exe)) except Exception: raise RuntimeError("Unknown error while executing {exe}".format(exe=exe)) bgzip_version_info = tuple(map(int, bgzip_version.split("."))) if bgzip_version_info < min_bgzip_version_info: raise RuntimeError("bgzip ({exe}) {ev} is too old; >= {rv} is required; please upgrade".format( exe=exe, ev=bgzip_version, rv=min_bgzip_version)) logger.info("Using bgzip {ev} ({exe})".format(ev=bgzip_version, exe=exe)) return exe
python
def _find_bgzip(): missing_file_exception = OSError if six.PY2 else FileNotFoundError min_bgzip_version = ".".join(map(str, min_bgzip_version_info)) exe = os.environ.get("SEQREPO_BGZIP_PATH", which("bgzip") or "/usr/bin/bgzip") try: bgzip_version = _get_bgzip_version(exe) except AttributeError: raise RuntimeError("Didn't find version string in bgzip executable ({exe})".format(exe=exe)) except missing_file_exception: raise RuntimeError("{exe} doesn't exist; you need to install htslib (See https://github.com/biocommons/biocommons.seqrepo#requirements)".format(exe=exe)) except Exception: raise RuntimeError("Unknown error while executing {exe}".format(exe=exe)) bgzip_version_info = tuple(map(int, bgzip_version.split("."))) if bgzip_version_info < min_bgzip_version_info: raise RuntimeError("bgzip ({exe}) {ev} is too old; >= {rv} is required; please upgrade".format( exe=exe, ev=bgzip_version, rv=min_bgzip_version)) logger.info("Using bgzip {ev} ({exe})".format(ev=bgzip_version, exe=exe)) return exe
[ "def", "_find_bgzip", "(", ")", ":", "missing_file_exception", "=", "OSError", "if", "six", ".", "PY2", "else", "FileNotFoundError", "min_bgzip_version", "=", "\".\"", ".", "join", "(", "map", "(", "str", ",", "min_bgzip_version_info", ")", ")", "exe", "=", ...
return path to bgzip if found and meets version requirements, else exception
[ "return", "path", "to", "bgzip", "if", "found", "and", "meets", "version", "requirements", "else", "exception" ]
fb6d88682cb73ee6971cfa47d4dcd90a9c649167
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/biocommons/seqrepo/fastadir/fabgz.py#L41-L60
6,799
biocommons/biocommons.seqrepo
biocommons/seqrepo/seqrepo.py
SeqRepo.translate_alias
def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None): """given an alias and optional namespace, return a list of all other aliases for same sequence """ if translate_ncbi_namespace is None: translate_ncbi_namespace = self.translate_ncbi_namespace seq_id = self._get_unique_seqid(alias=alias, namespace=namespace) aliases = self.aliases.fetch_aliases(seq_id=seq_id, translate_ncbi_namespace=translate_ncbi_namespace) if target_namespaces: aliases = [a for a in aliases if a["namespace"] in target_namespaces] return aliases
python
def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None): if translate_ncbi_namespace is None: translate_ncbi_namespace = self.translate_ncbi_namespace seq_id = self._get_unique_seqid(alias=alias, namespace=namespace) aliases = self.aliases.fetch_aliases(seq_id=seq_id, translate_ncbi_namespace=translate_ncbi_namespace) if target_namespaces: aliases = [a for a in aliases if a["namespace"] in target_namespaces] return aliases
[ "def", "translate_alias", "(", "self", ",", "alias", ",", "namespace", "=", "None", ",", "target_namespaces", "=", "None", ",", "translate_ncbi_namespace", "=", "None", ")", ":", "if", "translate_ncbi_namespace", "is", "None", ":", "translate_ncbi_namespace", "=",...
given an alias and optional namespace, return a list of all other aliases for same sequence
[ "given", "an", "alias", "and", "optional", "namespace", "return", "a", "list", "of", "all", "other", "aliases", "for", "same", "sequence" ]
fb6d88682cb73ee6971cfa47d4dcd90a9c649167
https://github.com/biocommons/biocommons.seqrepo/blob/fb6d88682cb73ee6971cfa47d4dcd90a9c649167/biocommons/seqrepo/seqrepo.py#L175-L188