code
stringlengths
1
18.2k
def valid_options(kwargs, allowed_options): """ Checks that kwargs are valid API options""" diff = set(kwargs) - set(allowed_options) if diff: print("Invalid option(s): ", ', '.join(diff)) return False return True
def create(self, fullname, shortname, category_id, **kwargs): """ Create a new course :param string fullname: The course's fullname :param string shortname: The course's shortname :param int category_id: The course's category :keyword string idnumber: (optional) Course ID number. \ Yes, it's a string, blame Moodle. :ke...
\ Largest size of file that can be uploaded into the course :keyword bool showreports: Default to True. Are activity report shown? :keyword bool visible: (optional) Determines if course is \ visible to students :keyword int groupmode: (optional) Defaults to 2. options: (0 = no group, 1 = separate, 2 = visible) :keyword...
Usage:: >>> import muddle >>> muddle.course().create('a new course', 'new-course', 20) """ allowed_options = ['idnumber', 'summaryformat', 'format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible', 'groupmode', 'groupmodeforce', 'jdefaultgroupingid', 'enablecompletion', 'completionstartonen...
def delete(self): """ Deletes a specified courses Example Usage:: >>> import muddle >>> muddle.course(10).delete() """ params = {'wsfunction': 'core_course_delete_courses', 'courseids[0]': self.course_id} params.update(self.request_params) return requests.post(self.api_url, params=params, verify=False)
def contents(self): """ Returns entire contents of course page :returns: response object Example Usage:: >>> import muddle >>> muddle.course(10).content() """ params = self.request_params params.update({'wsfunction': 'core_course_get_contents', 'courseid': self.course_id}) return requests.get(self.api_url, params=param...
def duplicate(self, fullname, shortname, categoryid, visible=True, **kwargs): """ Duplicates an existing course with options. Note: Can be very slow running. :param string fullname: The new course's full name :param string shortname: The new course's short name :param string categoryid: Category new course should be cr...
Include user course completion information :keyword bool logs: (optional) Defaults to False. Include course logs :keyword bool grade_histories: (optional) Defaults to False. \ Include histories :returns: response object Example Usage:: >>> import muddle >>> muddle.course(10).duplicate('new-fullname', 'new-shortname', 2...
def export_data(self, export_to, delete_content=False): """ Export course data to another course. Does not include any user data. :param bool delete_content: (optional) Delete content \ from source course. Example Usage:: >>> import muddle >>> muddle.course(10).export_data(12) """ params = {'wsfunction': 'core_course_i...
def details(self): """ Returns details for given category :returns: category response object Example Usage:: >>> import muddle >>> muddle.category(10).details() """ params = {'wsfunction': 'core_course_get_categories', 'criteria[0][key]': 'id', 'criteria[0][value]': self.category_id} params.update(self.request_params) ...
def delete(self, new_parent=None, recursive=False): """ Deletes a category. Optionally moves content to new category. Note: If category is in root, new_parent must be specified. :param int new_parent: (optional) Category ID of new parent :param bool recursive: recursively delete contents inside this category Example Us...
def check_path(path): """Check that a path is legal. :return: the path if all is OK :raise ValueError: if the path is illegal """ if path is None or path == b'' or path.startswith(b'/'): raise ValueError("illegal path '%s'" % path) if ( (sys.version_info[0] >= 3 and not isinstance(path, bytes)) and (sys.version_info[0]...
def format_path(p, quote_spaces=False): """Format a path in utf8, quoting it if necessary.""" if b'\n' in p: p = re.sub(b'\n', b'\\n', p) quote = True else: quote = p[0] == b'"' or (quote_spaces and b' ' in p) if quote: extra = GIT_FAST_IMPORT_NEEDS_EXTRA_SPACE_AFTER_QUOTE and b' ' or b'' p = b'"' + p + b'"' + extra re...
def format_who_when(fields): """Format a tuple of name,email,secs-since-epoch,utc-offset-secs as a string.""" offset = fields[3] if offset < 0: offset_sign = b'-' offset = abs(offset) else: offset_sign = b'+' offset_hours = offset // 3600 offset_minutes = offset // 60 - offset_hours * 60 offset_str = offset_sign + ('%0...
def format_property(name, value): """Format the name and value (both unicode) of a property as a string.""" result = b'' utf8_name = utf8_bytes_string(name) result = b'property ' + utf8_name if value is not None: utf8_value = utf8_bytes_string(value) result += b' ' + ('%d' % len(utf8_value)).encode('ascii') + b' ' + ut...
def dump_str(self, names=None, child_lists=None, verbose=False): """Dump fields as a string. For debugging. :param names: the list of fields to include or None for all public fields :param child_lists: dictionary of child command names to fields for that child command to include :param verbose: if True, prefix each lin...
in fields])
def iter_files(self): """Iterate over files.""" # file_iter may be a callable or an iterator if callable(self.file_iter): return self.file_iter() return iter(self.file_iter)
def get_range(self): """ Get range """ if not self.page: return (1, self.last_blocks[self.coinid]) # Get start of the range start = self.page * self.limit # Get finish of the range end = (self.page + 1) * self.limit if start > self.last_blocks[self.coinid]: return (1,1) if end > self.last_blocks[self.coinid]: return (s...
def _open_repo(args, path_key='<path>'): """Open and return the repository containing the specified file. The file is specified by looking up `path_key` in `args`. This value or `None` is passed to `open_repository`. Returns: A `Repository` instance. Raises: ExitError: If there is a problem opening the repo. """ path =...
def _get_anchor(repo, id_prefix): """Get an anchor by ID, or a prefix of its id. """ result = None for anchor_id, anchor in repo.items(): if anchor_id.startswith(id_prefix): if result is not None: raise ExitError( ExitCode.DATA_ERR, 'Ambiguous ID specification') result = (anchor_id, anchor) if result is None: raise Exi...
def init_handler(args): """usage: {program} init Initialize a new spor repository in the current directory. """ try: initialize_repository(pathlib.Path.cwd()) except ValueError as exc: print(exc, file=sys.stderr) return ExitCode.DATAERR return ExitCode.OK
def list_handler(args): """usage: {program} list List the anchors for a file. """ repo = open_repository(None) for anchor_id, anchor in repo.items(): print("{} {}:{} => {}".format(anchor_id, anchor.file_path.relative_to(repo.root), anchor.context.offset, anchor.metadata)) return ExitCode.OK
def add_handler(args): """usage: {program} add <source-file> <offset> <width> <context-width> Add a new anchor for a file. """ file_path = pathlib.Path(args['<source-file>']).resolve() try: offset = int(args['<offset>']) width = int(args['<width>']) context_width = int(args['<context-width>']) except ValueError as exc:...
def remove_handler(args): """usage: {program} remove <anchor-id> [<path>] Remove an existing anchor. """ repo = _open_repo(args) anchor_id, anchor = _get_anchor(repo, args['<anchor-id>']) del repo[anchor_id] return ExitCode.OK
def _launch_editor(starting_text=''): "Launch editor, let user write text, then return that text." # TODO: What is a reasonable default for windows? Does this approach even # make sense on windows? editor = os.environ.get('EDITOR', 'vim') with tempfile.TemporaryDirectory() as dirname: filename = pathlib.Path(dirname) /...
def update_handler(args): """usage: {program} update [<path>] Update out of date anchors in the current repository. """ repo = _open_repo(args) for anchor_id, anchor in repo.items(): try: anchor = update(anchor) except AlignmentError as e: print('Unable to update anchor {}. Reason: {}'.format( anchor_id, e)) else: repo...
def status_handler(args): """usage: {program} status [<path>] Validate the anchors in the current repository. """ repo = _open_repo(args) for anchor_id, anchor in repo.items(): diff_lines = get_anchor_diff(anchor) if diff_lines: print('{} {}:{} out-of-date'.format( anchor_id, anchor.file_path, anchor.context.offset)) r...
def diff_handler(args): """usage: {program} diff <anchor-id> Show the difference between an anchor and the current state of the source. """ repo = _open_repo(args) anchor_id, anchor = _get_anchor(repo, args['<anchor-id>']) diff_lines = get_anchor_diff(anchor) sys.stdout.writelines(diff_lines) return ExitCode.OK
def details_handler(args): """usage: {program} details <anchor-id> [<path>] Get the details of a single anchor. """ repo = _open_repo(args) _, anchor = _get_anchor(repo, args['<anchor-id>']) print("""path: {file_path} encoding: {encoding} [before] {before} -------------- [topic] {topic} -------------- [after] {after} -...
def _days_from_3744(hebrew_year): """Return: Number of days since 3,1,3744.""" # Start point for calculation is Molad new year 3744 (16BC) years_from_3744 = hebrew_year - 3744 molad_3744 = get_chalakim(1 + 6, 779) # Molad 3744 + 6 hours in parts # Time in months # Number of leap months leap_months = (years_from_3744 * ...
date in corrections # 28 % 7 = 0 so only corrections counts parts_left_in_week = parts % PARTS_IN_WEEK parts_left_in_day = parts % PARTS_IN_DAY week_day = parts_left_in_week // PARTS_IN_DAY # pylint: disable=too-many-boolean-expressions # pylint-comment: Splitting the 'if' below might create a bug in case # the order i...
def gdate_to_jdn(date): """ Compute Julian day from Gregorian day, month and year. Algorithm from wikipedia's julian_day article. Return: The julian day number """ not_jan_or_feb = (14 - date.month) // 12 year_since_4800bc = date.year + 4800 - not_jan_or_feb month_since_4800bc = date.month + 12 * not_jan_or_feb - 3 jdn...
def hdate_to_jdn(date): """ Compute Julian day from Hebrew day, month and year. Return: julian day number, 1 of tishrey julians, 1 of tishrey julians next year """ day = date.day month = date.month if date.month == 13: month = 6 if date.month == 14: month = 6 day += 30 # Calculate days since 1,1,3744 day = _days_from_3...
30 # adjust to julian return day + 1715118
def jdn_to_gdate(jdn): """ Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year """ # pylint: disable=invalid-name # The algorithm is a verbatim copy from Peter Meyer's article # No explanation in the article is given for the variab...
(2447 * j) // 80 l = j // 11 # noqa: E741 month = j + 2 - (12 * l) year = 100 * (n - 49) + i + l # that's a lower-case L return datetime.date(year, month, day)
def jdn_to_hdate(jdn): """Convert from the Julian day to the Hebrew day.""" # calculate Gregorian date date = jdn_to_gdate(jdn) # Guess Hebrew year is Gregorian year + 3760 year = date.year + 3760 jdn_tishrey1 = hdate_to_jdn(HebrewDate(year, 1, 1)) jdn_tishrey1_next_year = hdate_to_jdn(HebrewDate(year + 1, 1, 1)) # Che...
// 2 + 1 month = month + 4 + 1 # if leap if size_of_year > 355 and month <= 6: month = month + 8 else: # in 4-5 first months # Special cases for this year if size_of_year % 10 > 4 and days == 59: # long Heshvan (day 30) month = 1 day = 30 elif size_of_year % 10 > 4 and days > 59: # long Heshvan month = (days - 1) * 2 /...
else: # regular months month = days * 2 // 59 day = days - (month * 59 + 1) // 2 + 1 month = month + 1 return HebrewDate(year, month, day)
def update(anchor, handle=None): """Update an anchor based on the current contents of its source file. Args: anchor: The `Anchor` to be updated. handle: File-like object containing contents of the anchor's file. If `None`, then this function will open the file and read it. Returns: A new `Anchor`, possibly identical to...
anchor_offset = ctxt.offset - len(ctxt.before) source_indices = tuple( s_idx for (a_idx, s_idx) in alignment if a_idx is not None if s_idx is not None if _index_in_topic(a_idx + anchor_offset, anchor)) if not source_indices: raise AlignmentError( "Best alignment does not map topic to updated source.") return make_ancho...
def get(context, tags: List[str], version: int, verbose: bool, bundle: str): """Get files.""" store = Store(context.obj['database'], context.obj['root']) files = store.files(bundle=bundle, tags=tags, version=version) for file_obj in files: if verbose: tags = ', '.join(tag.name for tag in file_obj.tags) click.echo(f"{cl...
def _get_callargs(self, *args, **kwargs): """ Retrieve all arguments that `self.func` needs and return a dictionary with call arguments. """ callargs = getcallargs(self.func, *args, **kwargs) return callargs
def search_by(url=None, file=None): """ TODO: support file """ image_url = url # image_file = file """ Search result page """ result_url = GOOGLE_SEARCH_BY_ENDPOINT + image_url referer = 'http://www.google.com/imghp' result_html = fire_request(result_url, referer) result = SBIResult() result.result_page = result_url re...
def export(self): """Export all attributes of the user to a dict. :return: attributes of the user. :rtype: dict. """ data = {} data["name"] = self.name data["contributions"] = self.contributions data["avatar"] = self.avatar data["followers"] = self.followers data["join"] = self.join data["organizations"] = self.organiz...
def __getContributions(self, web): """Scrap the contributions from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ contributions_raw = web.find_all('h2', {'class': 'f4 text-normal mb-2'}) try: contrText = contributions_raw[0].text contrText = contrText.lstrip().split(" ")[0] contrText = con...
def __getAvatar(self, web): """Scrap the avatar from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ try: self.avatar = web.find("img", {"class": "avatar"})['src'][:-10] except IndexError as error: print("There was an error with the user " + self.name) print(error) except AttributeError as ...
def __getNumberOfRepositories(self, web): """Scrap the number of repositories from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ counters = web.find_all('span', {'class': 'Counter'}) try: if 'k' not in counters[0].text: self.numberOfRepos = int(counters[0].text) else: reposText = counters...
def __getNumberOfFollowers(self, web): """Scrap the number of followers from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ counters = web.find_all('span', {'class': 'Counter'}) try: if 'k' not in counters[2].text: self.followers = int(counters[2].text) else: follText = counters[2].text.re...
def __getLocation(self, web): """Scrap the location from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ try: self.location = web.find("span", {"class": "p-label"}).text except AttributeError as error: print("There was an error with the user " + self.name) print(error)
def __getJoin(self, web): """Scrap the join date from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ join = web.findAll("a", {"class": "dropdown-item"}) for j in join: try: if "Joined GitHub" in j.text: self.join = j["href"][-10:] except IndexError as error: print("There was an error with ...
def __getBio(self, web): """Scrap the bio from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ bio = web.find_all("div", {"class": "user-profile-bio"}) if bio: try: bio = bio[0].text if bio and GitHubUser.isASCII(bio): bioText = bio.replace("\n", "") bioText = bioText.replace("\t", " ").rep...
def __getOrganizations(self, web): """Scrap the number of organizations from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ orgsElements = web.find_all("a", {"class": "avatar-group-item"}) self.organizations = len(orgsElements)
def getData(self): """Get data of the GitHub user.""" url = self.server + self.name data = GitHubUser.__getDataFromURL(url) web = BeautifulSoup(data, "lxml") self.__getContributions(web) self.__getLocation(web) self.__getAvatar(web) self.__getNumberOfRepositories(web) self.__getNumberOfFollowers(web) self.__getBio(web)...
def getRealContributions(self): """Get the real number of contributions (private + public).""" datefrom = datetime.now() - relativedelta(days=366) dateto = datefrom + relativedelta(months=1) - relativedelta(days=1) private = 0 while datefrom < datetime.now(): fromstr = datefrom.strftime("%Y-%m-%d") tostr = dateto.strft...
was an error with the user " + self.name) print(error) except AttributeError as error: print("There was an error with the user " + self.name) print(error) datefrom += relativedelta(months=1) dateto += relativedelta(months=1) self.private = private self.public = self.contributions - private if self.public < 0: # Is not ...
def __getDataFromURL(url): """Read HTML data from an user GitHub profile. :param url: URL of the webpage to download. :type url: str. :return: webpage donwloaded. :rtype: str. """ code = 0 while code != 200: req = Request(url) try: response = urlopen(req) code = response.code sleep(0.01) except HTTPError as error: code...
def clean(self, settings): """ Filter given settings to keep only key names available in ``DEFAULT_SETTINGS``. Args: settings (dict): Loaded settings. Returns: dict: Settings object filtered. """ return {k: v for k, v in settings.items() if k in DEFAULT_SETTINGS}
def set_settings(self, settings): """ Set every given settings as object attributes. Args: settings (dict): Dictionnary of settings. """ for k, v in settings.items(): setattr(self, k, v)
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) # Update internal dict self._settings.update(settings) # Push every setting items ...
def parse_with_retrieved(self, retrieved): """ Receives in input a dictionary of retrieved nodes. Does all the logic here. """ from aiida.common.exceptions import InvalidOperation import os output_path = None error_path = None try: output_path, error_path = self._fetch_output_files(retrieved) except InvalidOperation: r...
def _fetch_output_files(self, retrieved): """ Checks the output folder for standard output and standard error files, returns their absolute paths on success. :param retrieved: A dictionary of retrieved nodes, as obtained from the parser. """ from aiida.common.datastructures import calc_states from aiida.common.exceptio...
def reset(self): """ (re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``. """ self.config = None self.html = None self.parsed_tree = None self.tidied = False self.next_page_link = None self.title = None self.author = set() se...
def _process_replacements(self, html): """ Do raw string replacements on :param:`html`. """ if self.config.find_string: for find_pattern, replace_pattern in self.config.replace_patterns: html = html.replace(find_pattern, replace_pattern) LOGGER.info(u'Done replacements.', extra={'siteconfig': self.config.host}) return ...
def _tidy(self, html, smart_tidy): """ Tidy HTML if we have a tidy method. This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing. Although sometimes it makes the problem worse, which is why we can override it in site config files. """ if self.config.tidy and tidylib and smart_tidy...
def _parse_html(self): """ Load the parser and parse `self.html`. """ if self.config.parser != 'lxml': raise NotImplementedError('%s parser not implemented' % self.config.parser) self.parser = etree.HTMLParser() try: self.parsed_tree = etree.parse(StringIO(self.html), self.parser) except ValueError, e: if u'Unicode str...
def _extract_next_page_link(self): """ Try to get next page link. """ # HEADS UP: we do not abort if next_page_link is already set: # we try to find next (eg. find 3 if already at page 2). for pattern in self.config.next_page_link: items = self.parsed_tree.xpath(pattern) if not items: continue if len(items) == 1: item ...
def _extract_title(self): """ Extract the title and remove it from the document. If title has already been extracted, this method will do nothing. If removal cannot happen or fails, the document is left untouched. """ if self.title: return for pattern in self.config.title: items = self.parsed_tree.xpath(pattern) if not...
this is begnin except: LOGGER.exception(u'Could not remove title from document.', extra={'siteconfig': self.config.host}) # Exit at first item found. break else: LOGGER.warning(u'Multiple items (%s) for title pattern %s.', items, pattern, extra={'siteconfig': self.config.host})
def _extract_author(self): """ Extract author(s) if not already done. """ if bool(self.author): return for pattern in self.config.author: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only one element. items = [items] for item in items: if isinstance(item, basestring)...
def _extract_language(self): """ Extract language from the HTML ``<head>`` tags. """ if self.language: return found = False for pattern in self.config.language: for item in self.parsed_tree.xpath(pattern): stripped_language = item.strip() if stripped_language: self.language = stripped_language LOGGER.info(u'Language ex...
def _extract_date(self): """ Extract date from HTML. """ if self.date: return found = False for pattern in self.config.date: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only one element. items = [items] for item in items: if isinstance(item, basestring): # '_Element...
def _extract_body(self): """ Extract the body content from HTML. """ def is_descendant_node(parent, node): node = node.getparent() while node is not None: if node == parent: return True node = node.getparent() return False for pattern in self.config.body: items = self.parsed_tree.xpath(pattern) if len(items) == 1: if s...
try: body.append( new_tree.xpath('//html/body/div/div')[0] ) except IndexError: if 'id="readabilityBody"' in pruned_string: try: body.append( new_tree.xpath('//body') ) except: failed = True else: failed = True if failed: LOGGER.error(u'Pruning item failed:' u'\n\n%s\n\nWe got: “%s” ' u'and skipped it.', etree.tostring...
def _auto_extract_if_failed(self): """ Try to automatically extract as much as possible. """ if not self.config.autodetect_on_failure: return readabilitized = Document(self.html) if self.title is None: if bool(self.config.title): self.failures.add('title') title = readabilitized.title().strip() if title: self.title = t...
def process(self, html, url=None, smart_tidy=True): u""" Process HTML content or URL. For automatic extraction patterns and cleanups, :mod:`readability-lxml` is used, to stick as much as possible to the original PHP implementation and produce at least similar results with the same site config on the same article/conten...
or ``None`` :param smart_tidy: When ``True`` (default), runs :mod:`pytidylib` to tidy the HTML, after after run ``find_string``/``replace_string`` replacements and before running extractions. :type smart_tidy: bool :returns: ``True`` on success, ``False`` on failure. :raises: - :class:`RuntimeError` if config has not b...
nobody's perfect, and errors can happen in the Python world too, thus the *tidy* behavior was thought sane enough to be keep. """ # TODO: re-implement URL handling with self.reset() here. if self.config is None: raise RuntimeError(u'extractor site config is not set.') # TODO: If re-running ourselves over an already-rep...
not None \ or bool(self.author) or self.date is not None \ or self.language is not None: self.success = True # if we've had no success and we've used tidy, there's a chance # that tidy has messed up. So let's try again without tidy... if not self.success and self.tidied and smart_tidy: self.process(html, url=None, smar...
def staticflatpage(request, path): """Load/render a template corresponding to the path (a URL)""" # Don't render a base.html template. if path.replace("/", '').lower() == "base": raise Http404 if not path.startswith('/'): path = "/{0}".format(path) if path.endswith('/'): path = path[:-1] # Support for index.html templa...
def list_from_url(cls, url): '''return a list of DatalakeRecords for the specified url''' key = cls._get_key(url) metadata = cls._get_metadata_from_key(key) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadata, t, ct, key.size) for t in time_buckets]
def list_from_metadata(cls, url, metadata): '''return a list of DatalakeRecords for the url and metadata''' key = cls._get_key(url) metadata = Metadata(**metadata) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadata, t, ct, key.size) for t in time_buckets...
def get_time_buckets_from_metadata(metadata): '''return a list of time buckets in which the metadata falls''' start = metadata['start'] end = metadata.get('end') or start buckets = DatalakeRecord.get_time_buckets(start, end) if len(buckets) > DatalakeRecord.MAXIMUM_BUCKET_SPAN: msg = 'metadata spans too many time bucke...
def get_time_buckets(start, end): '''get the time buckets spanned by the start and end times''' d = DatalakeRecord.TIME_BUCKET_SIZE_IN_MS first_bucket = start / d last_bucket = end / d return list(range( int(first_bucket), int(last_bucket) + 1))
def write_pdb(residues, chain_id=' ', alt_states=False, strip_states=False): """Writes a pdb file for a list of residues. Parameters ---------- residues : list List of Residue objects. chain_id : str String of the chain id, defaults to ' '. alt_states : bool, optional If true, include all occupancy states of residues, ...
poly_id = monomer.tags['chain_id'] for atom_t, atom in atom_list: if strip_states: state_label = ' ' elif (atom.tags['state'] == 'A') and (len(monomer.states) == 1): state_label = ' ' else: state_label = atom.tags['state'] atom_data = { 'atom_number': '{:>5}'.format(cap(atom.id, 5)), 'atom_name': '{:<4}'.format(cap(pdb...
def centre_of_mass(self): """Returns the centre of mass of AMPAL object. Notes ----- All atoms are included in calculation, call `centre_of_mass` manually if another selection is require. Returns ------- centre_of_mass : numpy.array 3D coordinate for the centre of mass. """ elts = set([x.element for x in self.get_atoms...
def get_atoms(self, inc_alt_states=False): """Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. """ if inc_alt_states: return itertools.chain(*[x[1].values() for x in sorted(list(self.states.items()))]) return self.atoms.values...
def make_pdb(self): """Generates a PDB string for the `Monomer`.""" pdb_str = write_pdb( [self], ' ' if not self.parent else self.parent.id) return pdb_str
def close_monomers(self, group, cutoff=4.0): """Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Distance cut off. Returns ------- nearby_residues: [Monomers] List of ...
def unique_id(self): """Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id) """ chain = self.parent.parent.id residue = self.parent.id return chain, residue, self.id
def translate(self, vector): """Translates `Atom`. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternate conformations for sidechains. """ vector = numpy.array(vector) self._vector...
def main(args=None): """Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int """ parser = ArgumentParser( prog='baseline', description=DESCRIPTION) parser.add_argument( 'path', nargs='*', help='module or directory path') parser.add_argument( '--movepath',...
+ '.py' for pth in update_paths] print('Found updates for:') for path in script_paths: print(' ' + path) print() if not args.movepath: try: input('Hit [ENTER] to update, [Ctrl-C] to cancel ') except KeyboardInterrupt: print() print('Update canceled.') exitcode = 1 else: print() if exitcode == 0: for script_path, update...
def recv(self): """Receives a message from PS and decrypts it and returns a Message""" LOGGER.debug('Receiving') try: message_length = struct.unpack('>i', self._socket.recv(4))[0] message_length -= Connection.COMM_LENGTH LOGGER.debug('Length: %i', message_length) except socket.timeout: return None comm_status = struct....
def send(self, content): """Sends a JavaScript command to PS :param content: Script content :type content: str :yields: :class:`.Message` """ LOGGER.debug('Sending: %s', content) all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION) all_bytes += struct.pack('>i', self._id) all_bytes += struct.pack('>i', 2) self._i...
def watch_command(context, backend, config, poll): """ Watch for change on your Sass project sources then compile them to CSS. Watched events are: \b * Create: when a new source file is created; * Change: when a source is changed; * Delete: when a source is deleted; * Move: When a source file is moved in watched dirs. ...
= project.backend_engine.load(filepath=config_filepath) except BoussoleBaseException as e: logger.critical(six.text_type(e)) raise click.Abort() logger.debug(u"Settings file: {} ({})".format( config_filepath, config_engine._kind_name)) logger.debug(u"Project sources directory: {}".format( settings.SOURCES_PATH)) logger...
observer.stop() observer.join()