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
229,500
psss/did
did/plugins/trac.py
Trac.closed
def closed(self): """ True if ticket was closed in given time frame """ for who, what, old, new in self.history(): if what == "status" and new == "closed": return True return False
python
def closed(self): for who, what, old, new in self.history(): if what == "status" and new == "closed": return True return False
[ "def", "closed", "(", "self", ")", ":", "for", "who", ",", "what", ",", "old", ",", "new", "in", "self", ".", "history", "(", ")", ":", "if", "what", "==", "\"status\"", "and", "new", "==", "\"closed\"", ":", "return", "True", "return", "False" ]
True if ticket was closed in given time frame
[ "True", "if", "ticket", "was", "closed", "in", "given", "time", "frame" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trac.py#L119-L124
229,501
psss/did
did/plugins/git.py
GitRepo.commits
def commits(self, user, options): """ List commits for given user. """ # Prepare the command command = "git log --all --author={0}".format(user.login).split() command.append("--format=format:%h - %s") command.append("--since='{0} 00:00:00'".format(options.since)) command.append("--until='{0} 00:00:00'".format(options.until)) if options.verbose: command.append("--name-only") log.info(u"Checking commits in {0}".format(self.path)) log.details(pretty(command)) # Get the commit messages try: process = subprocess.Popen( command, cwd=self.path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as error: log.debug(error) raise did.base.ReportError( "Unable to access git repo '{0}'".format(self.path)) output, errors = process.communicate() log.debug("git log output:") log.debug(output) if process.returncode == 0: if not output: return [] else: if not options.verbose: return unicode(output, "utf8").split("\n") commits = [] for commit in unicode(output, "utf8").split("\n\n"): summary = commit.split("\n")[0] directory = re.sub("/[^/]+$", "", commit.split("\n")[1]) commits.append("{0}\n{1}* {2}".format( summary, 8 * " ", directory)) return commits else: log.debug(errors.strip()) log.warn("Unable to check commits in '{0}'".format(self.path)) return []
python
def commits(self, user, options): # Prepare the command command = "git log --all --author={0}".format(user.login).split() command.append("--format=format:%h - %s") command.append("--since='{0} 00:00:00'".format(options.since)) command.append("--until='{0} 00:00:00'".format(options.until)) if options.verbose: command.append("--name-only") log.info(u"Checking commits in {0}".format(self.path)) log.details(pretty(command)) # Get the commit messages try: process = subprocess.Popen( command, cwd=self.path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as error: log.debug(error) raise did.base.ReportError( "Unable to access git repo '{0}'".format(self.path)) output, errors = process.communicate() log.debug("git log output:") log.debug(output) if process.returncode == 0: if not output: return [] else: if not options.verbose: return unicode(output, "utf8").split("\n") commits = [] for commit in unicode(output, "utf8").split("\n\n"): summary = commit.split("\n")[0] directory = re.sub("/[^/]+$", "", commit.split("\n")[1]) commits.append("{0}\n{1}* {2}".format( summary, 8 * " ", directory)) return commits else: log.debug(errors.strip()) log.warn("Unable to check commits in '{0}'".format(self.path)) return []
[ "def", "commits", "(", "self", ",", "user", ",", "options", ")", ":", "# Prepare the command", "command", "=", "\"git log --all --author={0}\"", ".", "format", "(", "user", ".", "login", ")", ".", "split", "(", ")", "command", ".", "append", "(", "\"--format...
List commits for given user.
[ "List", "commits", "for", "given", "user", "." ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/git.py#L41-L81
229,502
psss/did
did/plugins/pagure.py
Pagure.search
def search(self, query, pagination, result_field): """ Perform Pagure query """ result = [] url = "/".join((self.url, query)) while url: log.debug("Pagure query: {0}".format(url)) try: response = requests.get(url, headers=self.headers) log.data("Response headers:\n{0}".format(response.headers)) except requests.RequestException as error: log.error(error) raise ReportError("Pagure search {0} failed.".format(self.url)) data = response.json() objects = data[result_field] log.debug("Result: {0} fetched".format( listed(len(objects), "item"))) log.data(pretty(data)) # FIXME later: Work around https://pagure.io/pagure/issue/4057 if not objects: break result.extend(objects) url = data[pagination]['next'] return result
python
def search(self, query, pagination, result_field): result = [] url = "/".join((self.url, query)) while url: log.debug("Pagure query: {0}".format(url)) try: response = requests.get(url, headers=self.headers) log.data("Response headers:\n{0}".format(response.headers)) except requests.RequestException as error: log.error(error) raise ReportError("Pagure search {0} failed.".format(self.url)) data = response.json() objects = data[result_field] log.debug("Result: {0} fetched".format( listed(len(objects), "item"))) log.data(pretty(data)) # FIXME later: Work around https://pagure.io/pagure/issue/4057 if not objects: break result.extend(objects) url = data[pagination]['next'] return result
[ "def", "search", "(", "self", ",", "query", ",", "pagination", ",", "result_field", ")", ":", "result", "=", "[", "]", "url", "=", "\"/\"", ".", "join", "(", "(", "self", ".", "url", ",", "query", ")", ")", "while", "url", ":", "log", ".", "debug...
Perform Pagure query
[ "Perform", "Pagure", "query" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/pagure.py#L43-L65
229,503
psss/did
did/plugins/gerrit.py
GerritUnit.fetch
def fetch(self, query_string="", common_query_options=None, limit_since=False): """ Backend for the actual gerrit query. query_string: basic query terms, e.g., 'status:abandoned' common_query_options: [optional] rest of the query string; if omitted, the default one is used (limit by the current user and since option); if empty, nothing will be added to query_string limit_since: [optional] Boolean (defaults to False) post-process the results to eliminate items created after since option. """ work_list = [] log.info(u"Searching for changes by {0}".format(self.user)) log.debug('query_string = {0}, common_query_options = {1}'.format( query_string, common_query_options)) self.since_date = self.get_gerrit_date(self.options.since) if common_query_options is None: # Calculate age from self.options.since # # Amount of time that has expired since the change was last # updated with a review comment or new patch set. # # Meaning that the last time we changed the review is # GREATER than the given age. # For age SMALLER we need -age:<time> common_query_options = '+owner:{0}'.format( self.user.login) if not limit_since: age = (TODAY - self.since_date).days common_query_options += '+-age:{0}d'.format(age) common_query_options += '+since:{0}+until:{1}'.format( self.get_gerrit_date(self.options.since), self.get_gerrit_date(self.options.until)) if isinstance(common_query_options, basestring) and \ len(common_query_options) > 0: query_string += common_query_options log.debug('query_string = {0}'.format(query_string)) log.debug('self.prefix = {0}'.format(self.prefix)) log.debug('[fetch] self.base_url = {0}'.format(self.base_url)) work_list = self.repo.search(query_string) if limit_since: tmplist = [] log.debug('Limiting by since option') self.stats = [] for chg in work_list: log.debug('chg = {0}'.format(chg)) chg_created = self.get_gerrit_date(chg['created'][:10]) log.debug('chg_created = {0}'.format(chg_created)) if chg_created >= self.since_date: tmplist.append(chg) work_list = tmplist[:] log.debug(u"work_list = {0}".format(work_list)) # Return the list of tick_data objects return [Change(ticket, prefix=self.prefix) for ticket in work_list]
python
def fetch(self, query_string="", common_query_options=None, limit_since=False): work_list = [] log.info(u"Searching for changes by {0}".format(self.user)) log.debug('query_string = {0}, common_query_options = {1}'.format( query_string, common_query_options)) self.since_date = self.get_gerrit_date(self.options.since) if common_query_options is None: # Calculate age from self.options.since # # Amount of time that has expired since the change was last # updated with a review comment or new patch set. # # Meaning that the last time we changed the review is # GREATER than the given age. # For age SMALLER we need -age:<time> common_query_options = '+owner:{0}'.format( self.user.login) if not limit_since: age = (TODAY - self.since_date).days common_query_options += '+-age:{0}d'.format(age) common_query_options += '+since:{0}+until:{1}'.format( self.get_gerrit_date(self.options.since), self.get_gerrit_date(self.options.until)) if isinstance(common_query_options, basestring) and \ len(common_query_options) > 0: query_string += common_query_options log.debug('query_string = {0}'.format(query_string)) log.debug('self.prefix = {0}'.format(self.prefix)) log.debug('[fetch] self.base_url = {0}'.format(self.base_url)) work_list = self.repo.search(query_string) if limit_since: tmplist = [] log.debug('Limiting by since option') self.stats = [] for chg in work_list: log.debug('chg = {0}'.format(chg)) chg_created = self.get_gerrit_date(chg['created'][:10]) log.debug('chg_created = {0}'.format(chg_created)) if chg_created >= self.since_date: tmplist.append(chg) work_list = tmplist[:] log.debug(u"work_list = {0}".format(work_list)) # Return the list of tick_data objects return [Change(ticket, prefix=self.prefix) for ticket in work_list]
[ "def", "fetch", "(", "self", ",", "query_string", "=", "\"\"", ",", "common_query_options", "=", "None", ",", "limit_since", "=", "False", ")", ":", "work_list", "=", "[", "]", "log", ".", "info", "(", "u\"Searching for changes by {0}\"", ".", "format", "(",...
Backend for the actual gerrit query. query_string: basic query terms, e.g., 'status:abandoned' common_query_options: [optional] rest of the query string; if omitted, the default one is used (limit by the current user and since option); if empty, nothing will be added to query_string limit_since: [optional] Boolean (defaults to False) post-process the results to eliminate items created after since option.
[ "Backend", "for", "the", "actual", "gerrit", "query", "." ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/gerrit.py#L133-L198
229,504
psss/did
did/utils.py
shorted
def shorted(text, width=79): """ Shorten text, make sure it's not cut in the middle of a word """ if len(text) <= width: return text # We remove any word after first overlapping non-word character return u"{0}...".format(re.sub(r"\W+\w*$", "", text[:width - 2]))
python
def shorted(text, width=79): if len(text) <= width: return text # We remove any word after first overlapping non-word character return u"{0}...".format(re.sub(r"\W+\w*$", "", text[:width - 2]))
[ "def", "shorted", "(", "text", ",", "width", "=", "79", ")", ":", "if", "len", "(", "text", ")", "<=", "width", ":", "return", "text", "# We remove any word after first overlapping non-word character", "return", "u\"{0}...\"", ".", "format", "(", "re", ".", "s...
Shorten text, make sure it's not cut in the middle of a word
[ "Shorten", "text", "make", "sure", "it", "s", "not", "cut", "in", "the", "middle", "of", "a", "word" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L54-L59
229,505
psss/did
did/utils.py
item
def item(text, level=0, options=None): """ Print indented item. """ # Extra line before in each section (unless brief) if level == 0 and not options.brief: print('') # Only top-level items displayed in brief mode if level == 1 and options.brief: return # Four space for each level, additional space for wiki format indent = level * 4 if options.format == "wiki" and level == 0: indent = 1 # Shorten the text if necessary to match the desired maximum width width = options.width - indent - 2 if options.width else 333 eprint(u"{0}* {1}".format(u" " * indent, shorted(unicode(text), width)))
python
def item(text, level=0, options=None): # Extra line before in each section (unless brief) if level == 0 and not options.brief: print('') # Only top-level items displayed in brief mode if level == 1 and options.brief: return # Four space for each level, additional space for wiki format indent = level * 4 if options.format == "wiki" and level == 0: indent = 1 # Shorten the text if necessary to match the desired maximum width width = options.width - indent - 2 if options.width else 333 eprint(u"{0}* {1}".format(u" " * indent, shorted(unicode(text), width)))
[ "def", "item", "(", "text", ",", "level", "=", "0", ",", "options", "=", "None", ")", ":", "# Extra line before in each section (unless brief)", "if", "level", "==", "0", "and", "not", "options", ".", "brief", ":", "print", "(", "''", ")", "# Only top-level ...
Print indented item.
[ "Print", "indented", "item", "." ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L62-L76
229,506
psss/did
did/utils.py
pluralize
def pluralize(singular=None): """ Naively pluralize words """ if singular.endswith("y") and not singular.endswith("ay"): plural = singular[:-1] + "ies" elif singular.endswith("s"): plural = singular + "es" else: plural = singular + "s" return plural
python
def pluralize(singular=None): if singular.endswith("y") and not singular.endswith("ay"): plural = singular[:-1] + "ies" elif singular.endswith("s"): plural = singular + "es" else: plural = singular + "s" return plural
[ "def", "pluralize", "(", "singular", "=", "None", ")", ":", "if", "singular", ".", "endswith", "(", "\"y\"", ")", "and", "not", "singular", ".", "endswith", "(", "\"ay\"", ")", ":", "plural", "=", "singular", "[", ":", "-", "1", "]", "+", "\"ies\"", ...
Naively pluralize words
[ "Naively", "pluralize", "words" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L79-L87
229,507
psss/did
did/utils.py
split
def split(values, separator=re.compile("[ ,]+")): """ Convert space-or-comma-separated values into a single list Common use case for this is merging content of options with multiple values allowed into a single list of strings thus allowing any of the formats below and converts them into ['a', 'b', 'c']:: --option a --option b --option c ... ['a', 'b', 'c'] --option a,b --option c ............ ['a,b', 'c'] --option 'a b c' ................... ['a b c'] Accepts both string and list. By default space and comma are used as value separators. Use any regular expression for custom separator. """ if not isinstance(values, list): values = [values] return sum([separator.split(value) for value in values], [])
python
def split(values, separator=re.compile("[ ,]+")): if not isinstance(values, list): values = [values] return sum([separator.split(value) for value in values], [])
[ "def", "split", "(", "values", ",", "separator", "=", "re", ".", "compile", "(", "\"[ ,]+\"", ")", ")", ":", "if", "not", "isinstance", "(", "values", ",", "list", ")", ":", "values", "=", "[", "values", "]", "return", "sum", "(", "[", "separator", ...
Convert space-or-comma-separated values into a single list Common use case for this is merging content of options with multiple values allowed into a single list of strings thus allowing any of the formats below and converts them into ['a', 'b', 'c']:: --option a --option b --option c ... ['a', 'b', 'c'] --option a,b --option c ............ ['a,b', 'c'] --option 'a b c' ................... ['a b c'] Accepts both string and list. By default space and comma are used as value separators. Use any regular expression for custom separator.
[ "Convert", "space", "-", "or", "-", "comma", "-", "separated", "values", "into", "a", "single", "list" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L140-L157
229,508
psss/did
did/utils.py
ascii
def ascii(text): """ Transliterate special unicode characters into pure ascii """ if not isinstance(text, unicode): text = unicode(text) return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
python
def ascii(text): if not isinstance(text, unicode): text = unicode(text) return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
[ "def", "ascii", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "text", "=", "unicode", "(", "text", ")", "return", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "text", ")", ".", "encode", "(", "'ascii...
Transliterate special unicode characters into pure ascii
[ "Transliterate", "special", "unicode", "characters", "into", "pure", "ascii" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L160-L164
229,509
psss/did
did/utils.py
Logging._create_logger
def _create_logger(name='did', level=None): """ Create did logger """ # Create logger, handler and formatter logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) # Save log levels in the logger itself (backward compatibility) for level in Logging.LEVELS: setattr(logger, level, getattr(logging, level)) # Additional logging constants and methods for details and data logger.DATA = LOG_DATA logger.DETAILS = LOG_DETAILS logger.ALL = LOG_ALL logger.details = lambda message: logger.log( LOG_DETAILS, message) # NOQA logger.data = lambda message: logger.log( LOG_DATA, message) # NOQA logger.all = lambda message: logger.log( LOG_ALL, message) # NOQA return logger
python
def _create_logger(name='did', level=None): # Create logger, handler and formatter logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) # Save log levels in the logger itself (backward compatibility) for level in Logging.LEVELS: setattr(logger, level, getattr(logging, level)) # Additional logging constants and methods for details and data logger.DATA = LOG_DATA logger.DETAILS = LOG_DETAILS logger.ALL = LOG_ALL logger.details = lambda message: logger.log( LOG_DETAILS, message) # NOQA logger.data = lambda message: logger.log( LOG_DATA, message) # NOQA logger.all = lambda message: logger.log( LOG_ALL, message) # NOQA return logger
[ "def", "_create_logger", "(", "name", "=", "'did'", ",", "level", "=", "None", ")", ":", "# Create logger, handler and formatter", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler...
Create did logger
[ "Create", "did", "logger" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L241-L261
229,510
psss/did
did/utils.py
Logging.set
def set(self, level=None): """ Set the default log level If the level is not specified environment variable DEBUG is used with the following meaning:: DEBUG=0 ... LOG_WARN (default) DEBUG=1 ... LOG_INFO DEBUG=2 ... LOG_DEBUG DEBUG=3 ... LOG_DETAILS DEBUG=4 ... LOG_DATA DEBUG=5 ... LOG_ALL (log all messages) """ # If level specified, use given if level is not None: Logging._level = level # Otherwise attempt to detect from the environment else: try: Logging._level = Logging.MAPPING[int(os.environ["DEBUG"])] except StandardError: Logging._level = logging.WARN self.logger.setLevel(Logging._level)
python
def set(self, level=None): # If level specified, use given if level is not None: Logging._level = level # Otherwise attempt to detect from the environment else: try: Logging._level = Logging.MAPPING[int(os.environ["DEBUG"])] except StandardError: Logging._level = logging.WARN self.logger.setLevel(Logging._level)
[ "def", "set", "(", "self", ",", "level", "=", "None", ")", ":", "# If level specified, use given", "if", "level", "is", "not", "None", ":", "Logging", ".", "_level", "=", "level", "# Otherwise attempt to detect from the environment", "else", ":", "try", ":", "Lo...
Set the default log level If the level is not specified environment variable DEBUG is used with the following meaning:: DEBUG=0 ... LOG_WARN (default) DEBUG=1 ... LOG_INFO DEBUG=2 ... LOG_DEBUG DEBUG=3 ... LOG_DETAILS DEBUG=4 ... LOG_DATA DEBUG=5 ... LOG_ALL (log all messages)
[ "Set", "the", "default", "log", "level" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L263-L286
229,511
psss/did
did/utils.py
Coloring.set
def set(self, mode=None): """ Set the coloring mode If enabled, some objects (like case run Status) are printed in color to easily spot failures, errors and so on. By default the feature is enabled when script is attached to a terminal. Possible values are:: COLOR=0 ... COLOR_OFF .... coloring disabled COLOR=1 ... COLOR_ON ..... coloring enabled COLOR=2 ... COLOR_AUTO ... if terminal attached (default) Environment variable COLOR can be used to set up the coloring to the desired mode without modifying code. """ # Detect from the environment if no mode given (only once) if mode is None: # Nothing to do if already detected if self._mode is not None: return # Detect from the environment variable COLOR try: mode = int(os.environ["COLOR"]) except StandardError: mode = COLOR_AUTO elif mode < 0 or mode > 2: raise RuntimeError("Invalid color mode '{0}'".format(mode)) self._mode = mode log.debug( "Coloring {0} ({1})".format( "enabled" if self.enabled() else "disabled", self.MODES[self._mode]))
python
def set(self, mode=None): # Detect from the environment if no mode given (only once) if mode is None: # Nothing to do if already detected if self._mode is not None: return # Detect from the environment variable COLOR try: mode = int(os.environ["COLOR"]) except StandardError: mode = COLOR_AUTO elif mode < 0 or mode > 2: raise RuntimeError("Invalid color mode '{0}'".format(mode)) self._mode = mode log.debug( "Coloring {0} ({1})".format( "enabled" if self.enabled() else "disabled", self.MODES[self._mode]))
[ "def", "set", "(", "self", ",", "mode", "=", "None", ")", ":", "# Detect from the environment if no mode given (only once)", "if", "mode", "is", "None", ":", "# Nothing to do if already detected", "if", "self", ".", "_mode", "is", "not", "None", ":", "return", "# ...
Set the coloring mode If enabled, some objects (like case run Status) are printed in color to easily spot failures, errors and so on. By default the feature is enabled when script is attached to a terminal. Possible values are:: COLOR=0 ... COLOR_OFF .... coloring disabled COLOR=1 ... COLOR_ON ..... coloring enabled COLOR=2 ... COLOR_AUTO ... if terminal attached (default) Environment variable COLOR can be used to set up the coloring to the desired mode without modifying code.
[ "Set", "the", "coloring", "mode" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L345-L376
229,512
psss/did
did/utils.py
Coloring.enabled
def enabled(self): """ True if coloring is currently enabled """ # In auto-detection mode color enabled when terminal attached if self._mode == COLOR_AUTO: return sys.stdout.isatty() return self._mode == COLOR_ON
python
def enabled(self): # In auto-detection mode color enabled when terminal attached if self._mode == COLOR_AUTO: return sys.stdout.isatty() return self._mode == COLOR_ON
[ "def", "enabled", "(", "self", ")", ":", "# In auto-detection mode color enabled when terminal attached", "if", "self", ".", "_mode", "==", "COLOR_AUTO", ":", "return", "sys", ".", "stdout", ".", "isatty", "(", ")", "return", "self", ".", "_mode", "==", "COLOR_O...
True if coloring is currently enabled
[ "True", "if", "coloring", "is", "currently", "enabled" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L382-L387
229,513
psss/did
did/cli.py
main
def main(arguments=None): """ Parse options, gather stats and show the results Takes optional parameter ``arguments`` which can be either command line string or list of options. This is very useful for testing purposes. Function returns a tuple of the form:: ([user_stats], team_stats) with the list of all gathered stats objects. """ try: # Parse options, initialize gathered stats options, header = Options(arguments).parse() gathered_stats = [] # Check for user email addresses (command line or config) emails = options.emails or did.base.Config().email emails = utils.split(emails, separator=re.compile(r"\s*,\s*")) users = [did.base.User(email=email) for email in emails] # Print header and prepare team stats object for data merging utils.eprint(header) team_stats = UserStats(options=options) if options.merge: utils.header("Total Report") utils.item("Users: {0}".format(len(users)), options=options) # Check individual user stats for user in users: if options.merge: utils.item(user, 1, options=options) else: utils.header(user) user_stats = UserStats(user=user, options=options) user_stats.check() team_stats.merge(user_stats) gathered_stats.append(user_stats) # Display merged team report if options.merge or options.total: if options.total: utils.header("Total Report") team_stats.show() # Return all gathered stats objects return gathered_stats, team_stats except did.base.ConfigFileError as error: utils.info("Create at least a minimum config file {0}:\n{1}".format( did.base.Config.path(), did.base.Config.example().strip())) raise
python
def main(arguments=None): try: # Parse options, initialize gathered stats options, header = Options(arguments).parse() gathered_stats = [] # Check for user email addresses (command line or config) emails = options.emails or did.base.Config().email emails = utils.split(emails, separator=re.compile(r"\s*,\s*")) users = [did.base.User(email=email) for email in emails] # Print header and prepare team stats object for data merging utils.eprint(header) team_stats = UserStats(options=options) if options.merge: utils.header("Total Report") utils.item("Users: {0}".format(len(users)), options=options) # Check individual user stats for user in users: if options.merge: utils.item(user, 1, options=options) else: utils.header(user) user_stats = UserStats(user=user, options=options) user_stats.check() team_stats.merge(user_stats) gathered_stats.append(user_stats) # Display merged team report if options.merge or options.total: if options.total: utils.header("Total Report") team_stats.show() # Return all gathered stats objects return gathered_stats, team_stats except did.base.ConfigFileError as error: utils.info("Create at least a minimum config file {0}:\n{1}".format( did.base.Config.path(), did.base.Config.example().strip())) raise
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "try", ":", "# Parse options, initialize gathered stats", "options", ",", "header", "=", "Options", "(", "arguments", ")", ".", "parse", "(", ")", "gathered_stats", "=", "[", "]", "# Check for user email ad...
Parse options, gather stats and show the results Takes optional parameter ``arguments`` which can be either command line string or list of options. This is very useful for testing purposes. Function returns a tuple of the form:: ([user_stats], team_stats) with the list of all gathered stats objects.
[ "Parse", "options", "gather", "stats", "and", "show", "the", "results" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/cli.py#L162-L214
229,514
psss/did
did/cli.py
Options.parse
def parse(self): """ Parse the options. """ # Run the parser opt, arg = self.parser.parse_known_args(self.arguments) self.opt = opt self.arg = arg self.check() # Enable --all if no particular stat or group selected opt.all = not any([ getattr(opt, stat.dest) or getattr(opt, group.dest) for group in self.sample_stats.stats for stat in group.stats]) # Time period handling if opt.since is None and opt.until is None: opt.since, opt.until, period = did.base.Date.period(arg) else: opt.since = did.base.Date(opt.since or "1993-01-01") opt.until = did.base.Date(opt.until or "today") # Make the 'until' limit inclusive opt.until.date += delta(days=1) period = "given date range" # Validate the date range if not opt.since.date < opt.until.date: raise RuntimeError( "Invalid date range ({0} to {1})".format( opt.since, opt.until.date - delta(days=1))) header = "Status report for {0} ({1} to {2}).".format( period, opt.since, opt.until.date - delta(days=1)) # Finito log.debug("Gathered options:") log.debug('options = {0}'.format(opt)) return opt, header
python
def parse(self): # Run the parser opt, arg = self.parser.parse_known_args(self.arguments) self.opt = opt self.arg = arg self.check() # Enable --all if no particular stat or group selected opt.all = not any([ getattr(opt, stat.dest) or getattr(opt, group.dest) for group in self.sample_stats.stats for stat in group.stats]) # Time period handling if opt.since is None and opt.until is None: opt.since, opt.until, period = did.base.Date.period(arg) else: opt.since = did.base.Date(opt.since or "1993-01-01") opt.until = did.base.Date(opt.until or "today") # Make the 'until' limit inclusive opt.until.date += delta(days=1) period = "given date range" # Validate the date range if not opt.since.date < opt.until.date: raise RuntimeError( "Invalid date range ({0} to {1})".format( opt.since, opt.until.date - delta(days=1))) header = "Status report for {0} ({1} to {2}).".format( period, opt.since, opt.until.date - delta(days=1)) # Finito log.debug("Gathered options:") log.debug('options = {0}'.format(opt)) return opt, header
[ "def", "parse", "(", "self", ")", ":", "# Run the parser", "opt", ",", "arg", "=", "self", ".", "parser", ".", "parse_known_args", "(", "self", ".", "arguments", ")", "self", ".", "opt", "=", "opt", "self", ".", "arg", "=", "arg", "self", ".", "check...
Parse the options.
[ "Parse", "the", "options", "." ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/cli.py#L112-L147
229,515
psss/did
did/cli.py
Options.check
def check(self): """ Perform additional check for given options """ keywords = "today yesterday this last week month quarter year".split() for argument in self.arg: if argument not in keywords: raise did.base.OptionError( "Invalid argument: '{0}'".format(argument))
python
def check(self): keywords = "today yesterday this last week month quarter year".split() for argument in self.arg: if argument not in keywords: raise did.base.OptionError( "Invalid argument: '{0}'".format(argument))
[ "def", "check", "(", "self", ")", ":", "keywords", "=", "\"today yesterday this last week month quarter year\"", ".", "split", "(", ")", "for", "argument", "in", "self", ".", "arg", ":", "if", "argument", "not", "in", "keywords", ":", "raise", "did", ".", "b...
Perform additional check for given options
[ "Perform", "additional", "check", "for", "given", "options" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/cli.py#L149-L155
229,516
psss/did
did/plugins/gitlab.py
GitLab.search
def search(self, user, since, until, target_type, action_name): """ Perform GitLab query """ if not self.user: self.user = self.get_user(user) if not self.events: self.events = self.user_events(self.user['id'], since, until) result = [] for event in self.events: created_at = dateutil.parser.parse(event['created_at']).date() if (event['target_type'] == target_type and event['action_name'] == action_name and since.date <= created_at and until.date >= created_at): result.append(event) log.debug("Result: {0} fetched".format(listed(len(result), "item"))) return result
python
def search(self, user, since, until, target_type, action_name): if not self.user: self.user = self.get_user(user) if not self.events: self.events = self.user_events(self.user['id'], since, until) result = [] for event in self.events: created_at = dateutil.parser.parse(event['created_at']).date() if (event['target_type'] == target_type and event['action_name'] == action_name and since.date <= created_at and until.date >= created_at): result.append(event) log.debug("Result: {0} fetched".format(listed(len(result), "item"))) return result
[ "def", "search", "(", "self", ",", "user", ",", "since", ",", "until", ",", "target_type", ",", "action_name", ")", ":", "if", "not", "self", ".", "user", ":", "self", ".", "user", "=", "self", ".", "get_user", "(", "user", ")", "if", "not", "self"...
Perform GitLab query
[ "Perform", "GitLab", "query" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/gitlab.py#L139-L153
229,517
psss/did
did/plugins/trello.py
TrelloAPI.board_links_to_ids
def board_links_to_ids(self): """ Convert board links to ids """ resp = self.stats.session.open( "{0}/members/{1}/boards?{2}".format( self.stats.url, self.username, urllib.urlencode({ "key": self.key, "token": self.token, "fields": "shortLink"}))) boards = json.loads(resp.read()) return [board['id'] for board in boards if self.board_links == [""] or board['shortLink'] in self.board_links]
python
def board_links_to_ids(self): resp = self.stats.session.open( "{0}/members/{1}/boards?{2}".format( self.stats.url, self.username, urllib.urlencode({ "key": self.key, "token": self.token, "fields": "shortLink"}))) boards = json.loads(resp.read()) return [board['id'] for board in boards if self.board_links == [""] or board['shortLink'] in self.board_links]
[ "def", "board_links_to_ids", "(", "self", ")", ":", "resp", "=", "self", ".", "stats", ".", "session", ".", "open", "(", "\"{0}/members/{1}/boards?{2}\"", ".", "format", "(", "self", ".", "stats", ".", "url", ",", "self", ".", "username", ",", "urllib", ...
Convert board links to ids
[ "Convert", "board", "links", "to", "ids" ]
04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trello.py#L114-L125
229,518
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_compatibility.py
EngineMixin.engine
def engine(self): """Return Render Engine.""" return self.backend({ 'APP_DIRS': True, 'DIRS': [str(ROOT / self.backend.app_dirname)], 'NAME': 'djangoforms', 'OPTIONS': {}, })
python
def engine(self): return self.backend({ 'APP_DIRS': True, 'DIRS': [str(ROOT / self.backend.app_dirname)], 'NAME': 'djangoforms', 'OPTIONS': {}, })
[ "def", "engine", "(", "self", ")", ":", "return", "self", ".", "backend", "(", "{", "'APP_DIRS'", ":", "True", ",", "'DIRS'", ":", "[", "str", "(", "ROOT", "/", "self", ".", "backend", ".", "app_dirname", ")", "]", ",", "'NAME'", ":", "'djangoforms'"...
Return Render Engine.
[ "Return", "Render", "Engine", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_compatibility.py#L37-L44
229,519
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_compatibility.py
CompatibleDateTimeBaseInput.format_value
def format_value(self, value): """ Return a value as it should appear when rendered in a template. Missing method of django.forms.widgets.Widget class """ if value == '' or value is None: return None return formats.localize_input(value, self.format)
python
def format_value(self, value): if value == '' or value is None: return None return formats.localize_input(value, self.format)
[ "def", "format_value", "(", "self", ",", "value", ")", ":", "if", "value", "==", "''", "or", "value", "is", "None", ":", "return", "None", "return", "formats", ".", "localize_input", "(", "value", ",", "self", ".", "format", ")" ]
Return a value as it should appear when rendered in a template. Missing method of django.forms.widgets.Widget class
[ "Return", "a", "value", "as", "it", "should", "appear", "when", "rendered", "in", "a", "template", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_compatibility.py#L71-L79
229,520
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_compatibility.py
CompatibleDateTimeBaseInput.render
def render(self, name, value, attrs=None, renderer=None): """ Render the widget as an HTML string. Missing method of django.forms.widgets.Widget class """ context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer)
python
def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer)
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "renderer", "=", "None", ")", ":", "context", "=", "self", ".", "get_context", "(", "name", ",", "value", ",", "attrs", ")", "return", "self", ".", "_render", ...
Render the widget as an HTML string. Missing method of django.forms.widgets.Widget class
[ "Render", "the", "widget", "as", "an", "HTML", "string", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_compatibility.py#L95-L102
229,521
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/__init__.py
YearPickerInput._link_to
def _link_to(self, linked_picker): """Customize the options when linked with other date-time input""" yformat = self.config['options']['format'].replace('-01-01', '-12-31') self.config['options']['format'] = yformat
python
def _link_to(self, linked_picker): yformat = self.config['options']['format'].replace('-01-01', '-12-31') self.config['options']['format'] = yformat
[ "def", "_link_to", "(", "self", ",", "linked_picker", ")", ":", "yformat", "=", "self", ".", "config", "[", "'options'", "]", "[", "'format'", "]", ".", "replace", "(", "'-01-01'", ",", "'-12-31'", ")", "self", ".", "config", "[", "'options'", "]", "["...
Customize the options when linked with other date-time input
[ "Customize", "the", "options", "when", "linked", "with", "other", "date", "-", "time", "input" ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/__init__.py#L90-L93
229,522
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput.format_py2js
def format_py2js(cls, datetime_format): """Convert python datetime format to moment datetime format.""" for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(py_format, js_format) return datetime_format
python
def format_py2js(cls, datetime_format): for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(py_format, js_format) return datetime_format
[ "def", "format_py2js", "(", "cls", ",", "datetime_format", ")", ":", "for", "js_format", ",", "py_format", "in", "cls", ".", "format_map", ":", "datetime_format", "=", "datetime_format", ".", "replace", "(", "py_format", ",", "js_format", ")", "return", "datet...
Convert python datetime format to moment datetime format.
[ "Convert", "python", "datetime", "format", "to", "moment", "datetime", "format", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L67-L71
229,523
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput.format_js2py
def format_js2py(cls, datetime_format): """Convert moment datetime format to python datetime format.""" for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(js_format, py_format) return datetime_format
python
def format_js2py(cls, datetime_format): for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(js_format, py_format) return datetime_format
[ "def", "format_js2py", "(", "cls", ",", "datetime_format", ")", ":", "for", "js_format", ",", "py_format", "in", "cls", ".", "format_map", ":", "datetime_format", "=", "datetime_format", ".", "replace", "(", "js_format", ",", "py_format", ")", "return", "datet...
Convert moment datetime format to python datetime format.
[ "Convert", "moment", "datetime", "format", "to", "python", "datetime", "format", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L74-L78
229,524
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput._calculate_options
def _calculate_options(self): """Calculate and Return the options.""" _options = self._default_options.copy() _options.update(self.options) if self.options_param: _options.update(self.options_param) return _options
python
def _calculate_options(self): _options = self._default_options.copy() _options.update(self.options) if self.options_param: _options.update(self.options_param) return _options
[ "def", "_calculate_options", "(", "self", ")", ":", "_options", "=", "self", ".", "_default_options", ".", "copy", "(", ")", "_options", ".", "update", "(", "self", ".", "options", ")", "if", "self", ".", "options_param", ":", "_options", ".", "update", ...
Calculate and Return the options.
[ "Calculate", "and", "Return", "the", "options", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L93-L99
229,525
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput._calculate_format
def _calculate_format(self): """Calculate and Return the datetime format.""" _format = self.format_param if self.format_param else self.format if self.config['options'].get('format'): _format = self.format_js2py(self.config['options'].get('format')) else: self.config['options']['format'] = self.format_py2js(_format) return _format
python
def _calculate_format(self): _format = self.format_param if self.format_param else self.format if self.config['options'].get('format'): _format = self.format_js2py(self.config['options'].get('format')) else: self.config['options']['format'] = self.format_py2js(_format) return _format
[ "def", "_calculate_format", "(", "self", ")", ":", "_format", "=", "self", ".", "format_param", "if", "self", ".", "format_param", "else", "self", ".", "format", "if", "self", ".", "config", "[", "'options'", "]", ".", "get", "(", "'format'", ")", ":", ...
Calculate and Return the datetime format.
[ "Calculate", "and", "Return", "the", "datetime", "format", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L101-L108
229,526
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput.get_context
def get_context(self, name, value, attrs): """Return widget context dictionary.""" context = super().get_context( name, value, attrs) context['widget']['attrs']['dp_config'] = json_dumps(self.config) return context
python
def get_context(self, name, value, attrs): context = super().get_context( name, value, attrs) context['widget']['attrs']['dp_config'] = json_dumps(self.config) return context
[ "def", "get_context", "(", "self", ",", "name", ",", "value", ",", "attrs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context", "(", "name", ",", "value", ",", "attrs", ")", "context", "[", "'widget'", "]", "[", "'attrs'", "]", "[", "'...
Return widget context dictionary.
[ "Return", "widget", "context", "dictionary", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L110-L115
229,527
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_base.py
BasePickerInput.end_of
def end_of(self, event_id, import_options=True): """ Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE """ event_id = str(event_id) if event_id in DatePickerDictionary.items: linked_picker = DatePickerDictionary.items[event_id] self.config['linked_to'] = linked_picker.config['id'] if import_options: backup_moment_format = self.config['options']['format'] self.config['options'].update(linked_picker.config['options']) self.config['options'].update(self.options_param) if self.format_param or 'format' in self.options_param: self.config['options']['format'] = backup_moment_format else: self.format = linked_picker.format # Setting useCurrent is necessary, see following issue # https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1075 self.config['options']['useCurrent'] = False self._link_to(linked_picker) else: raise KeyError( 'start-date not specified for event_id "%s"' % event_id) return self
python
def end_of(self, event_id, import_options=True): event_id = str(event_id) if event_id in DatePickerDictionary.items: linked_picker = DatePickerDictionary.items[event_id] self.config['linked_to'] = linked_picker.config['id'] if import_options: backup_moment_format = self.config['options']['format'] self.config['options'].update(linked_picker.config['options']) self.config['options'].update(self.options_param) if self.format_param or 'format' in self.options_param: self.config['options']['format'] = backup_moment_format else: self.format = linked_picker.format # Setting useCurrent is necessary, see following issue # https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1075 self.config['options']['useCurrent'] = False self._link_to(linked_picker) else: raise KeyError( 'start-date not specified for event_id "%s"' % event_id) return self
[ "def", "end_of", "(", "self", ",", "event_id", ",", "import_options", "=", "True", ")", ":", "event_id", "=", "str", "(", "event_id", ")", "if", "event_id", "in", "DatePickerDictionary", ".", "items", ":", "linked_picker", "=", "DatePickerDictionary", ".", "...
Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE
[ "Set", "Date", "-", "Picker", "as", "the", "end", "-", "date", "of", "a", "date", "-", "range", "." ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_base.py#L127-L155
229,528
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_helpers.py
get_base_input
def get_base_input(test=False): """ Return DateTimeBaseInput class from django.forms.widgets module Return _compatibility.DateTimeBaseInput class for older django versions. """ from django.forms.widgets import DateTimeBaseInput if 'get_context' in dir(DateTimeBaseInput) and not test: # django version 1.11 and above base_input = DateTimeBaseInput else: # django version below 1.11 from bootstrap_datepicker_plus._compatibility import ( CompatibleDateTimeBaseInput ) base_input = CompatibleDateTimeBaseInput return base_input
python
def get_base_input(test=False): from django.forms.widgets import DateTimeBaseInput if 'get_context' in dir(DateTimeBaseInput) and not test: # django version 1.11 and above base_input = DateTimeBaseInput else: # django version below 1.11 from bootstrap_datepicker_plus._compatibility import ( CompatibleDateTimeBaseInput ) base_input = CompatibleDateTimeBaseInput return base_input
[ "def", "get_base_input", "(", "test", "=", "False", ")", ":", "from", "django", ".", "forms", ".", "widgets", "import", "DateTimeBaseInput", "if", "'get_context'", "in", "dir", "(", "DateTimeBaseInput", ")", "and", "not", "test", ":", "# django version 1.11 and ...
Return DateTimeBaseInput class from django.forms.widgets module Return _compatibility.DateTimeBaseInput class for older django versions.
[ "Return", "DateTimeBaseInput", "class", "from", "django", ".", "forms", ".", "widgets", "module" ]
55819bf12507c98dba91c702e224afd9bae3ef9a
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_helpers.py#L4-L20
229,529
berkerpeksag/astor
astor/source_repr.py
split_lines
def split_lines(source, maxline=79): """Split inputs according to lines. If a line is short enough, just yield it. Otherwise, fix it. """ result = [] extend = result.extend append = result.append line = [] multiline = False count = 0 find = str.find for item in source: index = find(item, '\n') if index: line.append(item) multiline = index > 0 count += len(item) else: if line: if count <= maxline or multiline: extend(line) else: wrap_line(line, maxline, result) count = 0 multiline = False line = [] append(item) return result
python
def split_lines(source, maxline=79): result = [] extend = result.extend append = result.append line = [] multiline = False count = 0 find = str.find for item in source: index = find(item, '\n') if index: line.append(item) multiline = index > 0 count += len(item) else: if line: if count <= maxline or multiline: extend(line) else: wrap_line(line, maxline, result) count = 0 multiline = False line = [] append(item) return result
[ "def", "split_lines", "(", "source", ",", "maxline", "=", "79", ")", ":", "result", "=", "[", "]", "extend", "=", "result", ".", "extend", "append", "=", "result", ".", "append", "line", "=", "[", "]", "multiline", "=", "False", "count", "=", "0", ...
Split inputs according to lines. If a line is short enough, just yield it. Otherwise, fix it.
[ "Split", "inputs", "according", "to", "lines", ".", "If", "a", "line", "is", "short", "enough", "just", "yield", "it", ".", "Otherwise", "fix", "it", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/source_repr.py#L27-L55
229,530
berkerpeksag/astor
astor/source_repr.py
wrap_line
def wrap_line(line, maxline=79, result=[], count=count): """ We have a line that is too long, so we're going to try to wrap it. """ # Extract the indentation append = result.append extend = result.extend indentation = line[0] lenfirst = len(indentation) indent = lenfirst - len(indentation.lstrip()) assert indent in (0, lenfirst) indentation = line.pop(0) if indent else '' # Get splittable/non-splittable groups dgroups = list(delimiter_groups(line)) unsplittable = dgroups[::2] splittable = dgroups[1::2] # If the largest non-splittable group won't fit # on a line, try to add parentheses to the line. if max(count(x) for x in unsplittable) > maxline - indent: line = add_parens(line, maxline, indent) dgroups = list(delimiter_groups(line)) unsplittable = dgroups[::2] splittable = dgroups[1::2] # Deal with the first (always unsplittable) group, and # then set up to deal with the remainder in pairs. first = unsplittable[0] append(indentation) extend(first) if not splittable: return result pos = indent + count(first) indentation += ' ' indent += 4 if indent >= maxline/2: maxline = maxline/2 + indent for sg, nsg in zip(splittable, unsplittable[1:]): if sg: # If we already have stuff on the line and even # the very first item won't fit, start a new line if pos > indent and pos + len(sg[0]) > maxline: append('\n') append(indentation) pos = indent # Dump lines out of the splittable group # until the entire thing fits csg = count(sg) while pos + csg > maxline: ready, sg = split_group(sg, pos, maxline) if ready[-1].endswith(' '): ready[-1] = ready[-1][:-1] extend(ready) append('\n') append(indentation) pos = indent csg = count(sg) # Dump the remainder of the splittable group if sg: extend(sg) pos += csg # Dump the unsplittable group, optionally # preceded by a linefeed. cnsg = count(nsg) if pos > indent and pos + cnsg > maxline: append('\n') append(indentation) pos = indent extend(nsg) pos += cnsg
python
def wrap_line(line, maxline=79, result=[], count=count): # Extract the indentation append = result.append extend = result.extend indentation = line[0] lenfirst = len(indentation) indent = lenfirst - len(indentation.lstrip()) assert indent in (0, lenfirst) indentation = line.pop(0) if indent else '' # Get splittable/non-splittable groups dgroups = list(delimiter_groups(line)) unsplittable = dgroups[::2] splittable = dgroups[1::2] # If the largest non-splittable group won't fit # on a line, try to add parentheses to the line. if max(count(x) for x in unsplittable) > maxline - indent: line = add_parens(line, maxline, indent) dgroups = list(delimiter_groups(line)) unsplittable = dgroups[::2] splittable = dgroups[1::2] # Deal with the first (always unsplittable) group, and # then set up to deal with the remainder in pairs. first = unsplittable[0] append(indentation) extend(first) if not splittable: return result pos = indent + count(first) indentation += ' ' indent += 4 if indent >= maxline/2: maxline = maxline/2 + indent for sg, nsg in zip(splittable, unsplittable[1:]): if sg: # If we already have stuff on the line and even # the very first item won't fit, start a new line if pos > indent and pos + len(sg[0]) > maxline: append('\n') append(indentation) pos = indent # Dump lines out of the splittable group # until the entire thing fits csg = count(sg) while pos + csg > maxline: ready, sg = split_group(sg, pos, maxline) if ready[-1].endswith(' '): ready[-1] = ready[-1][:-1] extend(ready) append('\n') append(indentation) pos = indent csg = count(sg) # Dump the remainder of the splittable group if sg: extend(sg) pos += csg # Dump the unsplittable group, optionally # preceded by a linefeed. cnsg = count(nsg) if pos > indent and pos + cnsg > maxline: append('\n') append(indentation) pos = indent extend(nsg) pos += cnsg
[ "def", "wrap_line", "(", "line", ",", "maxline", "=", "79", ",", "result", "=", "[", "]", ",", "count", "=", "count", ")", ":", "# Extract the indentation", "append", "=", "result", ".", "append", "extend", "=", "result", ".", "extend", "indentation", "=...
We have a line that is too long, so we're going to try to wrap it.
[ "We", "have", "a", "line", "that", "is", "too", "long", "so", "we", "re", "going", "to", "try", "to", "wrap", "it", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/source_repr.py#L62-L143
229,531
berkerpeksag/astor
astor/source_repr.py
split_group
def split_group(source, pos, maxline): """ Split a group into two subgroups. The first will be appended to the current line, the second will start the new line. Note that the first group must always contain at least one item. The original group may be destroyed. """ first = [] source.reverse() while source: tok = source.pop() first.append(tok) pos += len(tok) if source: tok = source[-1] allowed = (maxline + 1) if tok.endswith(' ') else (maxline - 4) if pos + len(tok) > allowed: break source.reverse() return first, source
python
def split_group(source, pos, maxline): first = [] source.reverse() while source: tok = source.pop() first.append(tok) pos += len(tok) if source: tok = source[-1] allowed = (maxline + 1) if tok.endswith(' ') else (maxline - 4) if pos + len(tok) > allowed: break source.reverse() return first, source
[ "def", "split_group", "(", "source", ",", "pos", ",", "maxline", ")", ":", "first", "=", "[", "]", "source", ".", "reverse", "(", ")", "while", "source", ":", "tok", "=", "source", ".", "pop", "(", ")", "first", ".", "append", "(", "tok", ")", "p...
Split a group into two subgroups. The first will be appended to the current line, the second will start the new line. Note that the first group must always contain at least one item. The original group may be destroyed.
[ "Split", "a", "group", "into", "two", "subgroups", ".", "The", "first", "will", "be", "appended", "to", "the", "current", "line", "the", "second", "will", "start", "the", "new", "line", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/source_repr.py#L146-L169
229,532
berkerpeksag/astor
astor/source_repr.py
delimiter_groups
def delimiter_groups(line, begin_delim=begin_delim, end_delim=end_delim): """Split a line into alternating groups. The first group cannot have a line feed inserted, the next one can, etc. """ text = [] line = iter(line) while True: # First build and yield an unsplittable group for item in line: text.append(item) if item in begin_delim: break if not text: break yield text # Now build and yield a splittable group level = 0 text = [] for item in line: if item in begin_delim: level += 1 elif item in end_delim: level -= 1 if level < 0: yield text text = [item] break text.append(item) else: assert not text, text break
python
def delimiter_groups(line, begin_delim=begin_delim, end_delim=end_delim): text = [] line = iter(line) while True: # First build and yield an unsplittable group for item in line: text.append(item) if item in begin_delim: break if not text: break yield text # Now build and yield a splittable group level = 0 text = [] for item in line: if item in begin_delim: level += 1 elif item in end_delim: level -= 1 if level < 0: yield text text = [item] break text.append(item) else: assert not text, text break
[ "def", "delimiter_groups", "(", "line", ",", "begin_delim", "=", "begin_delim", ",", "end_delim", "=", "end_delim", ")", ":", "text", "=", "[", "]", "line", "=", "iter", "(", "line", ")", "while", "True", ":", "# First build and yield an unsplittable group", "...
Split a line into alternating groups. The first group cannot have a line feed inserted, the next one can, etc.
[ "Split", "a", "line", "into", "alternating", "groups", ".", "The", "first", "group", "cannot", "have", "a", "line", "feed", "inserted", "the", "next", "one", "can", "etc", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/source_repr.py#L177-L210
229,533
berkerpeksag/astor
astor/source_repr.py
add_parens
def add_parens(line, maxline, indent, statements=statements, count=count): """Attempt to add parentheses around the line in order to make it splittable. """ if line[0] in statements: index = 1 if not line[0].endswith(' '): index = 2 assert line[1] == ' ' line.insert(index, '(') if line[-1] == ':': line.insert(-1, ')') else: line.append(')') # That was the easy stuff. Now for assignments. groups = list(get_assign_groups(line)) if len(groups) == 1: # So sad, too bad return line counts = list(count(x) for x in groups) didwrap = False # If the LHS is large, wrap it first if sum(counts[:-1]) >= maxline - indent - 4: for group in groups[:-1]: didwrap = False # Only want to know about last group if len(group) > 1: group.insert(0, '(') group.insert(-1, ')') didwrap = True # Might not need to wrap the RHS if wrapped the LHS if not didwrap or counts[-1] > maxline - indent - 10: groups[-1].insert(0, '(') groups[-1].append(')') return [item for group in groups for item in group]
python
def add_parens(line, maxline, indent, statements=statements, count=count): if line[0] in statements: index = 1 if not line[0].endswith(' '): index = 2 assert line[1] == ' ' line.insert(index, '(') if line[-1] == ':': line.insert(-1, ')') else: line.append(')') # That was the easy stuff. Now for assignments. groups = list(get_assign_groups(line)) if len(groups) == 1: # So sad, too bad return line counts = list(count(x) for x in groups) didwrap = False # If the LHS is large, wrap it first if sum(counts[:-1]) >= maxline - indent - 4: for group in groups[:-1]: didwrap = False # Only want to know about last group if len(group) > 1: group.insert(0, '(') group.insert(-1, ')') didwrap = True # Might not need to wrap the RHS if wrapped the LHS if not didwrap or counts[-1] > maxline - indent - 10: groups[-1].insert(0, '(') groups[-1].append(')') return [item for group in groups for item in group]
[ "def", "add_parens", "(", "line", ",", "maxline", ",", "indent", ",", "statements", "=", "statements", ",", "count", "=", "count", ")", ":", "if", "line", "[", "0", "]", "in", "statements", ":", "index", "=", "1", "if", "not", "line", "[", "0", "]"...
Attempt to add parentheses around the line in order to make it splittable.
[ "Attempt", "to", "add", "parentheses", "around", "the", "line", "in", "order", "to", "make", "it", "splittable", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/source_repr.py#L216-L255
229,534
berkerpeksag/astor
astor/string_repr.py
_prep_triple_quotes
def _prep_triple_quotes(s, mysplit=mysplit, replacements=replacements): """ Split the string up and force-feed some replacements to make sure it will round-trip OK """ s = mysplit(s) s[1::2] = (replacements[x] for x in s[1::2]) return ''.join(s)
python
def _prep_triple_quotes(s, mysplit=mysplit, replacements=replacements): s = mysplit(s) s[1::2] = (replacements[x] for x in s[1::2]) return ''.join(s)
[ "def", "_prep_triple_quotes", "(", "s", ",", "mysplit", "=", "mysplit", ",", "replacements", "=", "replacements", ")", ":", "s", "=", "mysplit", "(", "s", ")", "s", "[", "1", ":", ":", "2", "]", "=", "(", "replacements", "[", "x", "]", "for", "x", ...
Split the string up and force-feed some replacements to make sure it will round-trip OK
[ "Split", "the", "string", "up", "and", "force", "-", "feed", "some", "replacements", "to", "make", "sure", "it", "will", "round", "-", "trip", "OK" ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/string_repr.py#L48-L55
229,535
berkerpeksag/astor
astor/string_repr.py
pretty_string
def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100): """There are a lot of reasons why we might not want to or be able to return a triple-quoted string. We can always punt back to the default normal string. """ default = repr(s) # Punt on abnormal strings if (isinstance(s, special_unicode) or not isinstance(s, basestring)): return default if uni_lit and isinstance(s, bytes): return 'b' + default len_s = len(default) if current_line.strip(): len_current = len(current_line) second_line_start = s.find('\n') + 1 if embedded > 1 and not second_line_start: return default if len_s < min_trip_str: return default line_indent = len_current - len(current_line.lstrip()) # Could be on a line by itself... if embedded and not second_line_start: return default total_len = len_current + len_s if total_len < max_line and not _properly_indented(s, line_indent): return default fancy = string_triplequote_repr(s) # Sometimes this doesn't work. One reason is that # the AST has no understanding of whether \r\n was # entered that way in the string or was a cr/lf in the # file. So we punt just so we can round-trip properly. try: if eval(fancy) == s and '\r' not in fancy: return fancy except: pass return default
python
def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100): default = repr(s) # Punt on abnormal strings if (isinstance(s, special_unicode) or not isinstance(s, basestring)): return default if uni_lit and isinstance(s, bytes): return 'b' + default len_s = len(default) if current_line.strip(): len_current = len(current_line) second_line_start = s.find('\n') + 1 if embedded > 1 and not second_line_start: return default if len_s < min_trip_str: return default line_indent = len_current - len(current_line.lstrip()) # Could be on a line by itself... if embedded and not second_line_start: return default total_len = len_current + len_s if total_len < max_line and not _properly_indented(s, line_indent): return default fancy = string_triplequote_repr(s) # Sometimes this doesn't work. One reason is that # the AST has no understanding of whether \r\n was # entered that way in the string or was a cr/lf in the # file. So we punt just so we can round-trip properly. try: if eval(fancy) == s and '\r' not in fancy: return fancy except: pass return default
[ "def", "pretty_string", "(", "s", ",", "embedded", ",", "current_line", ",", "uni_lit", "=", "False", ",", "min_trip_str", "=", "20", ",", "max_line", "=", "100", ")", ":", "default", "=", "repr", "(", "s", ")", "# Punt on abnormal strings", "if", "(", "...
There are a lot of reasons why we might not want to or be able to return a triple-quoted string. We can always punt back to the default normal string.
[ "There", "are", "a", "lot", "of", "reasons", "why", "we", "might", "not", "want", "to", "or", "be", "able", "to", "return", "a", "triple", "-", "quoted", "string", ".", "We", "can", "always", "punt", "back", "to", "the", "default", "normal", "string", ...
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/string_repr.py#L64-L112
229,536
berkerpeksag/astor
astor/tree_walk.py
TreeWalk.setup
def setup(self): """All the node-specific handlers are setup at object initialization time. """ self.pre_handlers = pre_handlers = {} self.post_handlers = post_handlers = {} for name in sorted(vars(type(self))): if name.startswith('init_'): getattr(self, name)() elif name.startswith('pre_'): pre_handlers[name[4:]] = getattr(self, name) elif name.startswith('post_'): post_handlers[name[5:]] = getattr(self, name)
python
def setup(self): self.pre_handlers = pre_handlers = {} self.post_handlers = post_handlers = {} for name in sorted(vars(type(self))): if name.startswith('init_'): getattr(self, name)() elif name.startswith('pre_'): pre_handlers[name[4:]] = getattr(self, name) elif name.startswith('post_'): post_handlers[name[5:]] = getattr(self, name)
[ "def", "setup", "(", "self", ")", ":", "self", ".", "pre_handlers", "=", "pre_handlers", "=", "{", "}", "self", ".", "post_handlers", "=", "post_handlers", "=", "{", "}", "for", "name", "in", "sorted", "(", "vars", "(", "type", "(", "self", ")", ")",...
All the node-specific handlers are setup at object initialization time.
[ "All", "the", "node", "-", "specific", "handlers", "are", "setup", "at", "object", "initialization", "time", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/tree_walk.py#L90-L103
229,537
berkerpeksag/astor
astor/tree_walk.py
TreeWalk.walk
def walk(self, node, name='', list=list, len=len, type=type): """Walk the tree starting at a given node. Maintain a stack of nodes. """ pre_handlers = self.pre_handlers.get post_handlers = self.post_handlers.get nodestack = self.nodestack emptystack = len(nodestack) append, pop = nodestack.append, nodestack.pop append([node, name, list(iter_node(node, name + '_item')), -1]) while len(nodestack) > emptystack: node, name, subnodes, index = nodestack[-1] if index >= len(subnodes): handler = (post_handlers(type(node).__name__) or post_handlers(name + '_name')) if handler is None: pop() continue self.cur_node = node self.cur_name = name handler() current = nodestack and nodestack[-1] popstack = current and current[0] is node if popstack and current[-1] >= len(current[-2]): pop() continue nodestack[-1][-1] = index + 1 if index < 0: handler = (pre_handlers(type(node).__name__) or pre_handlers(name + '_name')) if handler is not None: self.cur_node = node self.cur_name = name if handler(): pop() else: node, name = subnodes[index] append([node, name, list(iter_node(node, name + '_item')), -1])
python
def walk(self, node, name='', list=list, len=len, type=type): pre_handlers = self.pre_handlers.get post_handlers = self.post_handlers.get nodestack = self.nodestack emptystack = len(nodestack) append, pop = nodestack.append, nodestack.pop append([node, name, list(iter_node(node, name + '_item')), -1]) while len(nodestack) > emptystack: node, name, subnodes, index = nodestack[-1] if index >= len(subnodes): handler = (post_handlers(type(node).__name__) or post_handlers(name + '_name')) if handler is None: pop() continue self.cur_node = node self.cur_name = name handler() current = nodestack and nodestack[-1] popstack = current and current[0] is node if popstack and current[-1] >= len(current[-2]): pop() continue nodestack[-1][-1] = index + 1 if index < 0: handler = (pre_handlers(type(node).__name__) or pre_handlers(name + '_name')) if handler is not None: self.cur_node = node self.cur_name = name if handler(): pop() else: node, name = subnodes[index] append([node, name, list(iter_node(node, name + '_item')), -1])
[ "def", "walk", "(", "self", ",", "node", ",", "name", "=", "''", ",", "list", "=", "list", ",", "len", "=", "len", ",", "type", "=", "type", ")", ":", "pre_handlers", "=", "self", ".", "pre_handlers", ".", "get", "post_handlers", "=", "self", ".", ...
Walk the tree starting at a given node. Maintain a stack of nodes.
[ "Walk", "the", "tree", "starting", "at", "a", "given", "node", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/tree_walk.py#L105-L144
229,538
berkerpeksag/astor
astor/tree_walk.py
TreeWalk.replace
def replace(self, new_node): """Replace a node after first checking integrity of node stack.""" cur_node = self.cur_node nodestack = self.nodestack cur = nodestack.pop() prev = nodestack[-1] index = prev[-1] - 1 oldnode, name = prev[-2][index] assert cur[0] is cur_node is oldnode, (cur[0], cur_node, prev[-2], index) parent = prev[0] if isinstance(parent, list): parent[index] = new_node else: setattr(parent, name, new_node)
python
def replace(self, new_node): cur_node = self.cur_node nodestack = self.nodestack cur = nodestack.pop() prev = nodestack[-1] index = prev[-1] - 1 oldnode, name = prev[-2][index] assert cur[0] is cur_node is oldnode, (cur[0], cur_node, prev[-2], index) parent = prev[0] if isinstance(parent, list): parent[index] = new_node else: setattr(parent, name, new_node)
[ "def", "replace", "(", "self", ",", "new_node", ")", ":", "cur_node", "=", "self", ".", "cur_node", "nodestack", "=", "self", ".", "nodestack", "cur", "=", "nodestack", ".", "pop", "(", ")", "prev", "=", "nodestack", "[", "-", "1", "]", "index", "=",...
Replace a node after first checking integrity of node stack.
[ "Replace", "a", "node", "after", "first", "checking", "integrity", "of", "node", "stack", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/tree_walk.py#L162-L176
229,539
berkerpeksag/astor
astor/node_util.py
strip_tree
def strip_tree(node, # Runtime optimization iter_node=iter_node, special=ast.AST, list=list, isinstance=isinstance, type=type, len=len): """Strips an AST by removing all attributes not in _fields. Returns a set of the names of all attributes stripped. This canonicalizes two trees for comparison purposes. """ stripped = set() def strip(node, indent): unknown = set() leaf = True for subnode, _ in iter_node(node, unknown=unknown): leaf = False strip(subnode, indent + ' ') if leaf: if isinstance(node, special): unknown = set(vars(node)) stripped.update(unknown) for name in unknown: delattr(node, name) if hasattr(node, 'ctx'): delattr(node, 'ctx') if 'ctx' in node._fields: mylist = list(node._fields) mylist.remove('ctx') node._fields = mylist strip(node, '') return stripped
python
def strip_tree(node, # Runtime optimization iter_node=iter_node, special=ast.AST, list=list, isinstance=isinstance, type=type, len=len): stripped = set() def strip(node, indent): unknown = set() leaf = True for subnode, _ in iter_node(node, unknown=unknown): leaf = False strip(subnode, indent + ' ') if leaf: if isinstance(node, special): unknown = set(vars(node)) stripped.update(unknown) for name in unknown: delattr(node, name) if hasattr(node, 'ctx'): delattr(node, 'ctx') if 'ctx' in node._fields: mylist = list(node._fields) mylist.remove('ctx') node._fields = mylist strip(node, '') return stripped
[ "def", "strip_tree", "(", "node", ",", "# Runtime optimization", "iter_node", "=", "iter_node", ",", "special", "=", "ast", ".", "AST", ",", "list", "=", "list", ",", "isinstance", "=", "isinstance", ",", "type", "=", "type", ",", "len", "=", "len", ")",...
Strips an AST by removing all attributes not in _fields. Returns a set of the names of all attributes stripped. This canonicalizes two trees for comparison purposes.
[ "Strips", "an", "AST", "by", "removing", "all", "attributes", "not", "in", "_fields", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/node_util.py#L95-L126
229,540
berkerpeksag/astor
astor/node_util.py
fast_compare
def fast_compare(tree1, tree2): """ This is optimized to compare two AST trees for equality. It makes several assumptions that are currently true for AST trees used by rtrip, and it doesn't examine the _attributes. """ geta = ast.AST.__getattribute__ work = [(tree1, tree2)] pop = work.pop extend = work.extend # TypeError in cPython, AttributeError in PyPy exception = TypeError, AttributeError zipl = zip_longest type_ = type list_ = list while work: n1, n2 = pop() try: f1 = geta(n1, '_fields') f2 = geta(n2, '_fields') except exception: if type_(n1) is list_: extend(zipl(n1, n2)) continue if n1 == n2: continue return False else: f1 = [x for x in f1 if x != 'ctx'] if f1 != [x for x in f2 if x != 'ctx']: return False extend((geta(n1, fname), geta(n2, fname)) for fname in f1) return True
python
def fast_compare(tree1, tree2): geta = ast.AST.__getattribute__ work = [(tree1, tree2)] pop = work.pop extend = work.extend # TypeError in cPython, AttributeError in PyPy exception = TypeError, AttributeError zipl = zip_longest type_ = type list_ = list while work: n1, n2 = pop() try: f1 = geta(n1, '_fields') f2 = geta(n2, '_fields') except exception: if type_(n1) is list_: extend(zipl(n1, n2)) continue if n1 == n2: continue return False else: f1 = [x for x in f1 if x != 'ctx'] if f1 != [x for x in f2 if x != 'ctx']: return False extend((geta(n1, fname), geta(n2, fname)) for fname in f1) return True
[ "def", "fast_compare", "(", "tree1", ",", "tree2", ")", ":", "geta", "=", "ast", ".", "AST", ".", "__getattribute__", "work", "=", "[", "(", "tree1", ",", "tree2", ")", "]", "pop", "=", "work", ".", "pop", "extend", "=", "work", ".", "extend", "# T...
This is optimized to compare two AST trees for equality. It makes several assumptions that are currently true for AST trees used by rtrip, and it doesn't examine the _attributes.
[ "This", "is", "optimized", "to", "compare", "two", "AST", "trees", "for", "equality", ".", "It", "makes", "several", "assumptions", "that", "are", "currently", "true", "for", "AST", "trees", "used", "by", "rtrip", "and", "it", "doesn", "t", "examine", "the...
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/node_util.py#L174-L208
229,541
berkerpeksag/astor
astor/op_util.py
get_op_symbol
def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type): """Given an AST node object, returns a string containing the symbol. """ return fmt % symbol_data[type(obj)]
python
def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type): return fmt % symbol_data[type(obj)]
[ "def", "get_op_symbol", "(", "obj", ",", "fmt", "=", "'%s'", ",", "symbol_data", "=", "symbol_data", ",", "type", "=", "type", ")", ":", "return", "fmt", "%", "symbol_data", "[", "type", "(", "obj", ")", "]" ]
Given an AST node object, returns a string containing the symbol.
[ "Given", "an", "AST", "node", "object", "returns", "a", "string", "containing", "the", "symbol", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/op_util.py#L95-L98
229,542
berkerpeksag/astor
astor/file_util.py
CodeToAst.find_py_files
def find_py_files(srctree, ignore=None): """Return all the python files in a source tree Ignores any path that contains the ignore string This is not used by other class methods, but is designed to be used in code that uses this class. """ if not os.path.isdir(srctree): yield os.path.split(srctree) for srcpath, _, fnames in os.walk(srctree): # Avoid infinite recursion for silly users if ignore is not None and ignore in srcpath: continue for fname in (x for x in fnames if x.endswith('.py')): yield srcpath, fname
python
def find_py_files(srctree, ignore=None): if not os.path.isdir(srctree): yield os.path.split(srctree) for srcpath, _, fnames in os.walk(srctree): # Avoid infinite recursion for silly users if ignore is not None and ignore in srcpath: continue for fname in (x for x in fnames if x.endswith('.py')): yield srcpath, fname
[ "def", "find_py_files", "(", "srctree", ",", "ignore", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "srctree", ")", ":", "yield", "os", ".", "path", ".", "split", "(", "srctree", ")", "for", "srcpath", ",", "_", ",", ...
Return all the python files in a source tree Ignores any path that contains the ignore string This is not used by other class methods, but is designed to be used in code that uses this class.
[ "Return", "all", "the", "python", "files", "in", "a", "source", "tree" ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/file_util.py#L36-L52
229,543
berkerpeksag/astor
astor/file_util.py
CodeToAst.parse_file
def parse_file(fname): """Parse a python file into an AST. This is a very thin wrapper around ast.parse TODO: Handle encodings other than the default for Python 2 (issue #26) """ try: with fopen(fname) as f: fstr = f.read() except IOError: if fname != 'stdin': raise sys.stdout.write('\nReading from stdin:\n\n') fstr = sys.stdin.read() fstr = fstr.replace('\r\n', '\n').replace('\r', '\n') if not fstr.endswith('\n'): fstr += '\n' return ast.parse(fstr, filename=fname)
python
def parse_file(fname): try: with fopen(fname) as f: fstr = f.read() except IOError: if fname != 'stdin': raise sys.stdout.write('\nReading from stdin:\n\n') fstr = sys.stdin.read() fstr = fstr.replace('\r\n', '\n').replace('\r', '\n') if not fstr.endswith('\n'): fstr += '\n' return ast.parse(fstr, filename=fname)
[ "def", "parse_file", "(", "fname", ")", ":", "try", ":", "with", "fopen", "(", "fname", ")", "as", "f", ":", "fstr", "=", "f", ".", "read", "(", ")", "except", "IOError", ":", "if", "fname", "!=", "'stdin'", ":", "raise", "sys", ".", "stdout", "....
Parse a python file into an AST. This is a very thin wrapper around ast.parse TODO: Handle encodings other than the default for Python 2 (issue #26)
[ "Parse", "a", "python", "file", "into", "an", "AST", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/file_util.py#L55-L74
229,544
berkerpeksag/astor
astor/file_util.py
CodeToAst.get_file_info
def get_file_info(codeobj): """Returns the file and line number of a code object. If the code object has a __file__ attribute (e.g. if it is a module), then the returned line number will be 0 """ fname = getattr(codeobj, '__file__', None) linenum = 0 if fname is None: func_code = codeobj.__code__ fname = func_code.co_filename linenum = func_code.co_firstlineno fname = fname.replace('.pyc', '.py') return fname, linenum
python
def get_file_info(codeobj): fname = getattr(codeobj, '__file__', None) linenum = 0 if fname is None: func_code = codeobj.__code__ fname = func_code.co_filename linenum = func_code.co_firstlineno fname = fname.replace('.pyc', '.py') return fname, linenum
[ "def", "get_file_info", "(", "codeobj", ")", ":", "fname", "=", "getattr", "(", "codeobj", ",", "'__file__'", ",", "None", ")", "linenum", "=", "0", "if", "fname", "is", "None", ":", "func_code", "=", "codeobj", ".", "__code__", "fname", "=", "func_code"...
Returns the file and line number of a code object. If the code object has a __file__ attribute (e.g. if it is a module), then the returned line number will be 0
[ "Returns", "the", "file", "and", "line", "number", "of", "a", "code", "object", "." ]
d9e893eb49d9eb2e30779680f90cd632c30e0ba1
https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/file_util.py#L77-L91
229,545
aaronn/django-rest-framework-passwordless
drfpasswordless/utils.py
validate_token_age
def validate_token_age(callback_token): """ Returns True if a given token is within the age expiration limit. """ try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_settings.PASSWORDLESS_TOKEN_EXPIRE_TIME if seconds <= token_expiry_time: return True else: # Invalidate our token. token.is_active = False token.save() return False except CallbackToken.DoesNotExist: # No valid token. return False
python
def validate_token_age(callback_token): try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_settings.PASSWORDLESS_TOKEN_EXPIRE_TIME if seconds <= token_expiry_time: return True else: # Invalidate our token. token.is_active = False token.save() return False except CallbackToken.DoesNotExist: # No valid token. return False
[ "def", "validate_token_age", "(", "callback_token", ")", ":", "try", ":", "token", "=", "CallbackToken", ".", "objects", ".", "get", "(", "key", "=", "callback_token", ",", "is_active", "=", "True", ")", "seconds", "=", "(", "timezone", ".", "now", "(", ...
Returns True if a given token is within the age expiration limit.
[ "Returns", "True", "if", "a", "given", "token", "is", "within", "the", "age", "expiration", "limit", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/utils.py#L58-L77
229,546
aaronn/django-rest-framework-passwordless
drfpasswordless/utils.py
verify_user_alias
def verify_user_alias(user, token): """ Marks a user's contact point as verified depending on accepted token type. """ if token.to_alias_type == 'EMAIL': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME, True) elif token.to_alias_type == 'MOBILE': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME, True) else: return False user.save() return True
python
def verify_user_alias(user, token): if token.to_alias_type == 'EMAIL': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME, True) elif token.to_alias_type == 'MOBILE': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME, True) else: return False user.save() return True
[ "def", "verify_user_alias", "(", "user", ",", "token", ")", ":", "if", "token", ".", "to_alias_type", "==", "'EMAIL'", ":", "if", "token", ".", "to_alias", "==", "getattr", "(", "user", ",", "api_settings", ".", "PASSWORDLESS_USER_EMAIL_FIELD_NAME", ")", ":", ...
Marks a user's contact point as verified depending on accepted token type.
[ "Marks", "a", "user", "s", "contact", "point", "as", "verified", "depending", "on", "accepted", "token", "type", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/utils.py#L80-L93
229,547
aaronn/django-rest-framework-passwordless
drfpasswordless/utils.py
send_email_with_callback_token
def send_email_with_callback_token(user, email_token, **kwargs): """ Sends a Email to user.email. Passes silently without sending in test environment """ try: if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS: # Make sure we have a sending address before sending. # Get email subject and message email_subject = kwargs.get('email_subject', api_settings.PASSWORDLESS_EMAIL_SUBJECT) email_plaintext = kwargs.get('email_plaintext', api_settings.PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE) email_html = kwargs.get('email_html', api_settings.PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME) # Inject context if user specifies. context = inject_template_context({'callback_token': email_token.key, }) html_message = loader.render_to_string(email_html, context,) send_mail( email_subject, email_plaintext % email_token.key, api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS, [getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME)], fail_silently=False, html_message=html_message,) else: logger.debug("Failed to send token email. Missing PASSWORDLESS_EMAIL_NOREPLY_ADDRESS.") return False return True except Exception as e: logger.debug("Failed to send token email to user: %d." "Possibly no email on user object. Email entered was %s" % (user.id, getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME))) logger.debug(e) return False
python
def send_email_with_callback_token(user, email_token, **kwargs): try: if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS: # Make sure we have a sending address before sending. # Get email subject and message email_subject = kwargs.get('email_subject', api_settings.PASSWORDLESS_EMAIL_SUBJECT) email_plaintext = kwargs.get('email_plaintext', api_settings.PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE) email_html = kwargs.get('email_html', api_settings.PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME) # Inject context if user specifies. context = inject_template_context({'callback_token': email_token.key, }) html_message = loader.render_to_string(email_html, context,) send_mail( email_subject, email_plaintext % email_token.key, api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS, [getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME)], fail_silently=False, html_message=html_message,) else: logger.debug("Failed to send token email. Missing PASSWORDLESS_EMAIL_NOREPLY_ADDRESS.") return False return True except Exception as e: logger.debug("Failed to send token email to user: %d." "Possibly no email on user object. Email entered was %s" % (user.id, getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME))) logger.debug(e) return False
[ "def", "send_email_with_callback_token", "(", "user", ",", "email_token", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "api_settings", ".", "PASSWORDLESS_EMAIL_NOREPLY_ADDRESS", ":", "# Make sure we have a sending address before sending.", "# Get email subject and mes...
Sends a Email to user.email. Passes silently without sending in test environment
[ "Sends", "a", "Email", "to", "user", ".", "email", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/utils.py#L105-L145
229,548
aaronn/django-rest-framework-passwordless
drfpasswordless/utils.py
send_sms_with_callback_token
def send_sms_with_callback_token(user, mobile_token, **kwargs): """ Sends a SMS to user.mobile via Twilio. Passes silently without sending in test environment. """ base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE) try: if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER: # We need a sending number to send properly if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True: # we assume success to prevent spamming SMS during testing. return True from twilio.rest import Client twilio_client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) twilio_client.messages.create( body=base_string % mobile_token.key, to=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME), from_=api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER ) return True else: logger.debug("Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER.") return False except ImportError: logger.debug("Couldn't import Twilio client. Is twilio installed?") return False except KeyError: logger.debug("Couldn't send SMS." "Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?") except Exception as e: logger.debug("Failed to send token SMS to user: {}. " "Possibly no mobile number on user object or the twilio package isn't set up yet. " "Number entered was {}".format(user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME))) logger.debug(e) return False
python
def send_sms_with_callback_token(user, mobile_token, **kwargs): base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE) try: if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER: # We need a sending number to send properly if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True: # we assume success to prevent spamming SMS during testing. return True from twilio.rest import Client twilio_client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) twilio_client.messages.create( body=base_string % mobile_token.key, to=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME), from_=api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER ) return True else: logger.debug("Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER.") return False except ImportError: logger.debug("Couldn't import Twilio client. Is twilio installed?") return False except KeyError: logger.debug("Couldn't send SMS." "Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?") except Exception as e: logger.debug("Failed to send token SMS to user: {}. " "Possibly no mobile number on user object or the twilio package isn't set up yet. " "Number entered was {}".format(user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME))) logger.debug(e) return False
[ "def", "send_sms_with_callback_token", "(", "user", ",", "mobile_token", ",", "*", "*", "kwargs", ")", ":", "base_string", "=", "kwargs", ".", "get", "(", "'mobile_message'", ",", "api_settings", ".", "PASSWORDLESS_MOBILE_MESSAGE", ")", "try", ":", "if", "api_se...
Sends a SMS to user.mobile via Twilio. Passes silently without sending in test environment.
[ "Sends", "a", "SMS", "to", "user", ".", "mobile", "via", "Twilio", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/utils.py#L148-L186
229,549
aaronn/django-rest-framework-passwordless
drfpasswordless/signals.py
invalidate_previous_tokens
def invalidate_previous_tokens(sender, instance, **kwargs): """ Invalidates all previously issued tokens as a post_save signal. """ active_tokens = None if isinstance(instance, CallbackToken): active_tokens = CallbackToken.objects.active().filter(user=instance.user).exclude(id=instance.id) # Invalidate tokens if active_tokens: for token in active_tokens: token.is_active = False token.save()
python
def invalidate_previous_tokens(sender, instance, **kwargs): active_tokens = None if isinstance(instance, CallbackToken): active_tokens = CallbackToken.objects.active().filter(user=instance.user).exclude(id=instance.id) # Invalidate tokens if active_tokens: for token in active_tokens: token.is_active = False token.save()
[ "def", "invalidate_previous_tokens", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "active_tokens", "=", "None", "if", "isinstance", "(", "instance", ",", "CallbackToken", ")", ":", "active_tokens", "=", "CallbackToken", ".", "objects", "....
Invalidates all previously issued tokens as a post_save signal.
[ "Invalidates", "all", "previously", "issued", "tokens", "as", "a", "post_save", "signal", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/signals.py#L14-L26
229,550
aaronn/django-rest-framework-passwordless
drfpasswordless/signals.py
check_unique_tokens
def check_unique_tokens(sender, instance, **kwargs): """ Ensures that mobile and email tokens are unique or tries once more to generate. """ if isinstance(instance, CallbackToken): if CallbackToken.objects.filter(key=instance.key, is_active=True).exists(): instance.key = generate_numeric_token()
python
def check_unique_tokens(sender, instance, **kwargs): if isinstance(instance, CallbackToken): if CallbackToken.objects.filter(key=instance.key, is_active=True).exists(): instance.key = generate_numeric_token()
[ "def", "check_unique_tokens", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "instance", ",", "CallbackToken", ")", ":", "if", "CallbackToken", ".", "objects", ".", "filter", "(", "key", "=", "instance", ".", ...
Ensures that mobile and email tokens are unique or tries once more to generate.
[ "Ensures", "that", "mobile", "and", "email", "tokens", "are", "unique", "or", "tries", "once", "more", "to", "generate", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/signals.py#L30-L36
229,551
aaronn/django-rest-framework-passwordless
drfpasswordless/signals.py
update_alias_verification
def update_alias_verification(sender, instance, **kwargs): """ Flags a user's email as unverified if they change it. Optionally sends a verification token to the new endpoint. """ if isinstance(instance, User): if instance.id: if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED is True: """ For marking email aliases as not verified when a user changes it. """ email_field = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME email_verified_field = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME # Verify that this is an existing instance and not a new one. try: user_old = User.objects.get(id=instance.id) # Pre-save object instance_email = getattr(instance, email_field) # Incoming Email old_email = getattr(user_old, email_field) # Pre-save object email if instance_email != old_email and instance_email != "" and instance_email is not None: # Email changed, verification should be flagged setattr(instance, email_verified_field, False) if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True: email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME message_payload = {'email_subject': email_subject, 'email_plaintext': email_plaintext, 'email_html': email_html} success = TokenService.send_token(instance, 'email', **message_payload) if success: logger.info('drfpasswordless: Successfully sent email on updated address: %s' % instance_email) else: logger.info('drfpasswordless: Failed to send email to updated address: %s' % instance_email) except User.DoesNotExist: # User probably is just initially being created setattr(instance, email_verified_field, True) if api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED is True: """ For marking mobile aliases as not verified when a user changes it. """ mobile_field = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME mobile_verified_field = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME # Verify that this is an existing instance and not a new one. try: user_old = User.objects.get(id=instance.id) # Pre-save object instance_mobile = getattr(instance, mobile_field) # Incoming mobile old_mobile = getattr(user_old, mobile_field) # Pre-save object mobile if instance_mobile != old_mobile and instance_mobile != "" and instance_mobile is not None: # Mobile changed, verification should be flagged setattr(instance, mobile_verified_field, False) if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True: mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE message_payload = {'mobile_message': mobile_message} success = TokenService.send_token(instance, 'mobile', **message_payload) if success: logger.info('drfpasswordless: Successfully sent SMS on updated mobile: %s' % instance_mobile) else: logger.info('drfpasswordless: Failed to send SMS to updated mobile: %s' % instance_mobile) except User.DoesNotExist: # User probably is just initially being created setattr(instance, mobile_verified_field, True)
python
def update_alias_verification(sender, instance, **kwargs): if isinstance(instance, User): if instance.id: if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED is True: """ For marking email aliases as not verified when a user changes it. """ email_field = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME email_verified_field = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME # Verify that this is an existing instance and not a new one. try: user_old = User.objects.get(id=instance.id) # Pre-save object instance_email = getattr(instance, email_field) # Incoming Email old_email = getattr(user_old, email_field) # Pre-save object email if instance_email != old_email and instance_email != "" and instance_email is not None: # Email changed, verification should be flagged setattr(instance, email_verified_field, False) if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True: email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME message_payload = {'email_subject': email_subject, 'email_plaintext': email_plaintext, 'email_html': email_html} success = TokenService.send_token(instance, 'email', **message_payload) if success: logger.info('drfpasswordless: Successfully sent email on updated address: %s' % instance_email) else: logger.info('drfpasswordless: Failed to send email to updated address: %s' % instance_email) except User.DoesNotExist: # User probably is just initially being created setattr(instance, email_verified_field, True) if api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED is True: """ For marking mobile aliases as not verified when a user changes it. """ mobile_field = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME mobile_verified_field = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME # Verify that this is an existing instance and not a new one. try: user_old = User.objects.get(id=instance.id) # Pre-save object instance_mobile = getattr(instance, mobile_field) # Incoming mobile old_mobile = getattr(user_old, mobile_field) # Pre-save object mobile if instance_mobile != old_mobile and instance_mobile != "" and instance_mobile is not None: # Mobile changed, verification should be flagged setattr(instance, mobile_verified_field, False) if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True: mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE message_payload = {'mobile_message': mobile_message} success = TokenService.send_token(instance, 'mobile', **message_payload) if success: logger.info('drfpasswordless: Successfully sent SMS on updated mobile: %s' % instance_mobile) else: logger.info('drfpasswordless: Failed to send SMS to updated mobile: %s' % instance_mobile) except User.DoesNotExist: # User probably is just initially being created setattr(instance, mobile_verified_field, True)
[ "def", "update_alias_verification", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "instance", ",", "User", ")", ":", "if", "instance", ".", "id", ":", "if", "api_settings", ".", "PASSWORDLESS_USER_MARK_EMAIL_VERIFI...
Flags a user's email as unverified if they change it. Optionally sends a verification token to the new endpoint.
[ "Flags", "a", "user", "s", "email", "as", "unverified", "if", "they", "change", "it", ".", "Optionally", "sends", "a", "verification", "token", "to", "the", "new", "endpoint", "." ]
cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/signals.py#L43-L118
229,552
mosdef-hub/mbuild
mbuild/utils/geometry.py
calc_dihedral
def calc_dihedral(point1, point2, point3, point4): """Calculates a dihedral angle Here, two planes are defined by (point1, point2, point3) and (point2, point3, point4). The angle between them is returned. Parameters ---------- point1, point2, point3, point4 : array-like, shape=(3,), dtype=float Four points that define two planes Returns ------- float The dihedral angle between the two planes defined by the four points. """ points = np.array([point1, point2, point3, point4]) x = np.cross(points[1] - points[0], points[2] - points[1]) y = np.cross(points[2] - points[1], points[3] - points[2]) return angle(x, y)
python
def calc_dihedral(point1, point2, point3, point4): points = np.array([point1, point2, point3, point4]) x = np.cross(points[1] - points[0], points[2] - points[1]) y = np.cross(points[2] - points[1], points[3] - points[2]) return angle(x, y)
[ "def", "calc_dihedral", "(", "point1", ",", "point2", ",", "point3", ",", "point4", ")", ":", "points", "=", "np", ".", "array", "(", "[", "point1", ",", "point2", ",", "point3", ",", "point4", "]", ")", "x", "=", "np", ".", "cross", "(", "points",...
Calculates a dihedral angle Here, two planes are defined by (point1, point2, point3) and (point2, point3, point4). The angle between them is returned. Parameters ---------- point1, point2, point3, point4 : array-like, shape=(3,), dtype=float Four points that define two planes Returns ------- float The dihedral angle between the two planes defined by the four points.
[ "Calculates", "a", "dihedral", "angle" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/geometry.py#L6-L26
229,553
mosdef-hub/mbuild
mbuild/pattern.py
Pattern.scale
def scale(self, by): """Scale the points in the Pattern. Parameters ---------- by : float or np.ndarray, shape=(3,) The factor to scale by. If a scalar, scale all directions isotropically. If np.ndarray, scale each direction independently. """ self.points *= np.asarray([by]) self._adjust_ports()
python
def scale(self, by): self.points *= np.asarray([by]) self._adjust_ports()
[ "def", "scale", "(", "self", ",", "by", ")", ":", "self", ".", "points", "*=", "np", ".", "asarray", "(", "[", "by", "]", ")", "self", ".", "_adjust_ports", "(", ")" ]
Scale the points in the Pattern. Parameters ---------- by : float or np.ndarray, shape=(3,) The factor to scale by. If a scalar, scale all directions isotropically. If np.ndarray, scale each direction independently.
[ "Scale", "the", "points", "in", "the", "Pattern", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/pattern.py#L30-L40
229,554
mosdef-hub/mbuild
mbuild/pattern.py
Pattern.apply
def apply(self, compound, orientation='', compound_port=''): """Arrange copies of a Compound as specified by the Pattern. Parameters ---------- compound orientation Returns ------- """ compounds = list() if self.orientations.get(orientation): for port in self.orientations[orientation]: new_compound = clone(compound) new_port = new_compound.labels[compound_port] (new_compound, new_port['up'], port['up']) compounds.append(new_compound) else: for point in self.points: new_compound = clone(compound) new_compound.translate(point) compounds.append(new_compound) return compounds
python
def apply(self, compound, orientation='', compound_port=''): compounds = list() if self.orientations.get(orientation): for port in self.orientations[orientation]: new_compound = clone(compound) new_port = new_compound.labels[compound_port] (new_compound, new_port['up'], port['up']) compounds.append(new_compound) else: for point in self.points: new_compound = clone(compound) new_compound.translate(point) compounds.append(new_compound) return compounds
[ "def", "apply", "(", "self", ",", "compound", ",", "orientation", "=", "''", ",", "compound_port", "=", "''", ")", ":", "compounds", "=", "list", "(", ")", "if", "self", ".", "orientations", ".", "get", "(", "orientation", ")", ":", "for", "port", "i...
Arrange copies of a Compound as specified by the Pattern. Parameters ---------- compound orientation Returns -------
[ "Arrange", "copies", "of", "a", "Compound", "as", "specified", "by", "the", "Pattern", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/pattern.py#L47-L73
229,555
mosdef-hub/mbuild
mbuild/pattern.py
Pattern.apply_to_compound
def apply_to_compound(self, guest, guest_port_name='down', host=None, backfill=None, backfill_port_name='up', scale=True): """Attach copies of a guest Compound to Ports on a host Compound. Parameters ---------- guest : mb.Compound The Compound prototype to be applied to the host Compound guest_port_name : str, optional, default='down' The name of the port located on `guest` to attach to the host host : mb.Compound, optional, default=None A Compound with available ports to add copies of `guest` to backfill : mb.Compound, optional, default=None A Compound to add to the remaining available ports on `host` after clones of `guest` have been added for each point in the pattern backfill_port_name : str, optional, default='up' The name of the port located on `backfill` to attach to the host scale : bool, optional, default=True Scale the points in the pattern to the lengths of the `host`'s `boundingbox` and shift them by the `boundingbox`'s mins Returns ------- """ n_ports = len(host.available_ports()) assert n_ports >= self.points.shape[0], "Not enough ports for pattern." assert_port_exists(guest_port_name, guest) box = host.boundingbox if scale: self.scale(box.lengths) self.points += box.mins pattern = self.points port_positions = np.empty(shape=(n_ports, 3)) port_list = list() for port_idx, port in enumerate(host.available_ports()): port_positions[port_idx, :] = port['up']['middle'].pos port_list.append(port) used_ports = set() # Keep track of used ports for backfilling. guests = [] for point in pattern: closest_point_idx = np.argmin(host.min_periodic_distance(point, port_positions)) closest_port = port_list[closest_point_idx] used_ports.add(closest_port) # Attach the guest to the closest port. new_guest = clone(guest) force_overlap(new_guest, new_guest.labels[guest_port_name], closest_port) guests.append(new_guest) # Move the port as far away as possible (simpler than removing it). # There may well be a more elegant/efficient way of doing this. port_positions[closest_point_idx, :] = np.array([np.inf, np.inf, np.inf]) backfills = [] if backfill: assert_port_exists(backfill_port_name, backfill) # Attach the backfilling Compound to unused ports. for port in port_list: if port not in used_ports: new_backfill = clone(backfill) # Might make sense to have a backfill_port_name option... force_overlap(new_backfill, new_backfill.labels[backfill_port_name], port) backfills.append(new_backfill) return guests, backfills
python
def apply_to_compound(self, guest, guest_port_name='down', host=None, backfill=None, backfill_port_name='up', scale=True): n_ports = len(host.available_ports()) assert n_ports >= self.points.shape[0], "Not enough ports for pattern." assert_port_exists(guest_port_name, guest) box = host.boundingbox if scale: self.scale(box.lengths) self.points += box.mins pattern = self.points port_positions = np.empty(shape=(n_ports, 3)) port_list = list() for port_idx, port in enumerate(host.available_ports()): port_positions[port_idx, :] = port['up']['middle'].pos port_list.append(port) used_ports = set() # Keep track of used ports for backfilling. guests = [] for point in pattern: closest_point_idx = np.argmin(host.min_periodic_distance(point, port_positions)) closest_port = port_list[closest_point_idx] used_ports.add(closest_port) # Attach the guest to the closest port. new_guest = clone(guest) force_overlap(new_guest, new_guest.labels[guest_port_name], closest_port) guests.append(new_guest) # Move the port as far away as possible (simpler than removing it). # There may well be a more elegant/efficient way of doing this. port_positions[closest_point_idx, :] = np.array([np.inf, np.inf, np.inf]) backfills = [] if backfill: assert_port_exists(backfill_port_name, backfill) # Attach the backfilling Compound to unused ports. for port in port_list: if port not in used_ports: new_backfill = clone(backfill) # Might make sense to have a backfill_port_name option... force_overlap(new_backfill, new_backfill.labels[backfill_port_name], port) backfills.append(new_backfill) return guests, backfills
[ "def", "apply_to_compound", "(", "self", ",", "guest", ",", "guest_port_name", "=", "'down'", ",", "host", "=", "None", ",", "backfill", "=", "None", ",", "backfill_port_name", "=", "'up'", ",", "scale", "=", "True", ")", ":", "n_ports", "=", "len", "(",...
Attach copies of a guest Compound to Ports on a host Compound. Parameters ---------- guest : mb.Compound The Compound prototype to be applied to the host Compound guest_port_name : str, optional, default='down' The name of the port located on `guest` to attach to the host host : mb.Compound, optional, default=None A Compound with available ports to add copies of `guest` to backfill : mb.Compound, optional, default=None A Compound to add to the remaining available ports on `host` after clones of `guest` have been added for each point in the pattern backfill_port_name : str, optional, default='up' The name of the port located on `backfill` to attach to the host scale : bool, optional, default=True Scale the points in the pattern to the lengths of the `host`'s `boundingbox` and shift them by the `boundingbox`'s mins Returns -------
[ "Attach", "copies", "of", "a", "guest", "Compound", "to", "Ports", "on", "a", "host", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/pattern.py#L75-L141
229,556
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._sanitize_inputs
def _sanitize_inputs(self, lattice_spacing, lattice_vectors, lattice_points, angles): """Check for proper inputs and set instance attributes. validate_inputs takes the data passed to the constructor by the user and will ensure that the data is correctly formatted and will then set its instance attributes. validate_inputs checks that dimensionality is maintained, the unit cell is right handed, the area or volume of the unit cell is positive and non-zero for 2D and 3D respectively, lattice spacing are provided, basis vectors do not overlap when the unit cell is expanded. Exceptions Raised ----------------- TypeError : incorrect typing of the input parameters. ValueError : values are not within restrictions. """ if angles is not None and lattice_vectors is not None: raise ValueError('Overdefined system: angles and lattice_vectors ' 'provided. Only one of these should be passed.') self._validate_lattice_spacing(lattice_spacing) if angles is not None: self._validate_angles(angles) self.lattice_vectors = self._from_lattice_parameters(self.angles) else: self._validate_lattice_vectors(lattice_vectors) self.angles = self._from_lattice_vectors() self._validate_lattice_points(lattice_points)
python
def _sanitize_inputs(self, lattice_spacing, lattice_vectors, lattice_points, angles): if angles is not None and lattice_vectors is not None: raise ValueError('Overdefined system: angles and lattice_vectors ' 'provided. Only one of these should be passed.') self._validate_lattice_spacing(lattice_spacing) if angles is not None: self._validate_angles(angles) self.lattice_vectors = self._from_lattice_parameters(self.angles) else: self._validate_lattice_vectors(lattice_vectors) self.angles = self._from_lattice_vectors() self._validate_lattice_points(lattice_points)
[ "def", "_sanitize_inputs", "(", "self", ",", "lattice_spacing", ",", "lattice_vectors", ",", "lattice_points", ",", "angles", ")", ":", "if", "angles", "is", "not", "None", "and", "lattice_vectors", "is", "not", "None", ":", "raise", "ValueError", "(", "'Overd...
Check for proper inputs and set instance attributes. validate_inputs takes the data passed to the constructor by the user and will ensure that the data is correctly formatted and will then set its instance attributes. validate_inputs checks that dimensionality is maintained, the unit cell is right handed, the area or volume of the unit cell is positive and non-zero for 2D and 3D respectively, lattice spacing are provided, basis vectors do not overlap when the unit cell is expanded. Exceptions Raised ----------------- TypeError : incorrect typing of the input parameters. ValueError : values are not within restrictions.
[ "Check", "for", "proper", "inputs", "and", "set", "instance", "attributes", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L154-L188
229,557
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._validate_lattice_spacing
def _validate_lattice_spacing(self, lattice_spacing): """Ensure that lattice spacing is provided and correct. _validate_lattice_spacing will ensure that the lattice spacing provided are acceptable values. Additional Numpy errors can also occur due to the conversion to a Numpy array. Exceptions Raised ----------------- ValueError : Incorrect lattice_spacing input """ dataType = np.float64 if lattice_spacing is not None: lattice_spacing = np.asarray(lattice_spacing, dtype=dataType) lattice_spacing = lattice_spacing.reshape((3,)) if np.shape(lattice_spacing) != (self.dimension,): raise ValueError('Lattice spacing should be a vector of ' 'size:({},). Please include lattice spacing ' 'of size >= 0 depending on desired ' 'dimensionality.' .format(self.dimension)) else: raise ValueError('No lattice_spacing provided. Please provide ' 'lattice spacing\'s that are >= 0. with size ({},)' .format((self.dimension))) if np.any(np.isnan(lattice_spacing)): raise ValueError('None type or NaN type values present in ' 'lattice_spacing: {}.'.format(lattice_spacing)) elif np.any(lattice_spacing < 0.0): raise ValueError('Negative lattice spacing value. One of ' 'the spacing: {} is negative.' .format(lattice_spacing)) self.lattice_spacing = lattice_spacing
python
def _validate_lattice_spacing(self, lattice_spacing): dataType = np.float64 if lattice_spacing is not None: lattice_spacing = np.asarray(lattice_spacing, dtype=dataType) lattice_spacing = lattice_spacing.reshape((3,)) if np.shape(lattice_spacing) != (self.dimension,): raise ValueError('Lattice spacing should be a vector of ' 'size:({},). Please include lattice spacing ' 'of size >= 0 depending on desired ' 'dimensionality.' .format(self.dimension)) else: raise ValueError('No lattice_spacing provided. Please provide ' 'lattice spacing\'s that are >= 0. with size ({},)' .format((self.dimension))) if np.any(np.isnan(lattice_spacing)): raise ValueError('None type or NaN type values present in ' 'lattice_spacing: {}.'.format(lattice_spacing)) elif np.any(lattice_spacing < 0.0): raise ValueError('Negative lattice spacing value. One of ' 'the spacing: {} is negative.' .format(lattice_spacing)) self.lattice_spacing = lattice_spacing
[ "def", "_validate_lattice_spacing", "(", "self", ",", "lattice_spacing", ")", ":", "dataType", "=", "np", ".", "float64", "if", "lattice_spacing", "is", "not", "None", ":", "lattice_spacing", "=", "np", ".", "asarray", "(", "lattice_spacing", ",", "dtype", "="...
Ensure that lattice spacing is provided and correct. _validate_lattice_spacing will ensure that the lattice spacing provided are acceptable values. Additional Numpy errors can also occur due to the conversion to a Numpy array. Exceptions Raised ----------------- ValueError : Incorrect lattice_spacing input
[ "Ensure", "that", "lattice", "spacing", "is", "provided", "and", "correct", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L190-L226
229,558
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._validate_angles
def _validate_angles(self, angles): """Ensure that the angles between the lattice_vectors are correct""" dataType = np.float64 tempAngles = np.asarray(angles, dtype=dataType) tempAngles = tempAngles.reshape((3,)) if np.shape(tempAngles) == (self.dimension,): if np.sum(tempAngles) < 360.0 or np.sum(tempAngles) > -360.0: if (np.all(tempAngles != 180.0) and np.all(tempAngles != 0.0)): pass else: raise ValueError('Angles cannot be 180.0 or 0.0') else: raise ValueError('Angles sum: {} is either greater than ' '360.0 or less than -360.0' .format(np.sum(tempAngles))) for subset in it.permutations(tempAngles, r=self.dimension): if not subset[0] < np.sum(tempAngles) - subset[0]: raise ValueError('Each angle provided must be less' 'than the sum of the other angles. ' '{} is greater.'.format(subset[0])) else: raise ValueError('Incorrect array size. When converted to a ' 'Numpy array, the shape is: {}, expected {}.' .format(np.shape(tempAngles), (3,))) self.angles = tempAngles
python
def _validate_angles(self, angles): dataType = np.float64 tempAngles = np.asarray(angles, dtype=dataType) tempAngles = tempAngles.reshape((3,)) if np.shape(tempAngles) == (self.dimension,): if np.sum(tempAngles) < 360.0 or np.sum(tempAngles) > -360.0: if (np.all(tempAngles != 180.0) and np.all(tempAngles != 0.0)): pass else: raise ValueError('Angles cannot be 180.0 or 0.0') else: raise ValueError('Angles sum: {} is either greater than ' '360.0 or less than -360.0' .format(np.sum(tempAngles))) for subset in it.permutations(tempAngles, r=self.dimension): if not subset[0] < np.sum(tempAngles) - subset[0]: raise ValueError('Each angle provided must be less' 'than the sum of the other angles. ' '{} is greater.'.format(subset[0])) else: raise ValueError('Incorrect array size. When converted to a ' 'Numpy array, the shape is: {}, expected {}.' .format(np.shape(tempAngles), (3,))) self.angles = tempAngles
[ "def", "_validate_angles", "(", "self", ",", "angles", ")", ":", "dataType", "=", "np", ".", "float64", "tempAngles", "=", "np", ".", "asarray", "(", "angles", ",", "dtype", "=", "dataType", ")", "tempAngles", "=", "tempAngles", ".", "reshape", "(", "(",...
Ensure that the angles between the lattice_vectors are correct
[ "Ensure", "that", "the", "angles", "between", "the", "lattice_vectors", "are", "correct" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L228-L257
229,559
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._validate_lattice_vectors
def _validate_lattice_vectors(self, lattice_vectors): """Ensure that the lattice_vectors are reasonable inputs. """ dataType = np.float64 if lattice_vectors is None: lattice_vectors = np.identity(self.dimension, dtype=dataType) else: lattice_vectors = np.asarray(lattice_vectors, dtype=dataType) if (self.dimension, self.dimension) != np.shape(lattice_vectors): raise ValueError('Dimensionality of lattice_vectors is ' ' of shape {} not {}.' .format(np.shape(lattice_vectors), (self.dimension, self.dimension))) det = np.linalg.det(lattice_vectors) if abs(det) == 0.0: raise ValueError('Co-linear vectors: {}' 'have a determinant of 0.0. Does not ' 'define a unit cell.' .format(lattice_vectors)) if det <= 0.0: raise ValueError('Negative Determinant: the determinant ' 'of {} is negative, indicating a left-' 'handed system.' .format(det)) self.lattice_vectors = lattice_vectors
python
def _validate_lattice_vectors(self, lattice_vectors): dataType = np.float64 if lattice_vectors is None: lattice_vectors = np.identity(self.dimension, dtype=dataType) else: lattice_vectors = np.asarray(lattice_vectors, dtype=dataType) if (self.dimension, self.dimension) != np.shape(lattice_vectors): raise ValueError('Dimensionality of lattice_vectors is ' ' of shape {} not {}.' .format(np.shape(lattice_vectors), (self.dimension, self.dimension))) det = np.linalg.det(lattice_vectors) if abs(det) == 0.0: raise ValueError('Co-linear vectors: {}' 'have a determinant of 0.0. Does not ' 'define a unit cell.' .format(lattice_vectors)) if det <= 0.0: raise ValueError('Negative Determinant: the determinant ' 'of {} is negative, indicating a left-' 'handed system.' .format(det)) self.lattice_vectors = lattice_vectors
[ "def", "_validate_lattice_vectors", "(", "self", ",", "lattice_vectors", ")", ":", "dataType", "=", "np", ".", "float64", "if", "lattice_vectors", "is", "None", ":", "lattice_vectors", "=", "np", ".", "identity", "(", "self", ".", "dimension", ",", "dtype", ...
Ensure that the lattice_vectors are reasonable inputs.
[ "Ensure", "that", "the", "lattice_vectors", "are", "reasonable", "inputs", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L259-L286
229,560
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._from_lattice_parameters
def _from_lattice_parameters(self, angles): """Convert Bravais lattice parameters to lattice vectors. _from_lattice_parameters will generate the lattice vectors based on the parameters necessary to build a Bravais Lattice. The lattice vectors are in the lower diagonal matrix form. This was adapted from the ASE triclinic.py lattice parameter code. S. R. Bahn and K. W. Jacobsen An object-oriented scripting interface to a legacy electronic structure code Comput. Sci. Eng., Vol. 4, 56-66, 2002 Parameters ---------- angles : list-like, required Angles of bravais lattice. """ dataType = np.float64 (alpha, beta, gamma) = angles radianConversion = np.pi / 180.0 cosa = np.cos(alpha * radianConversion) cosb = np.cos(beta * radianConversion) sinb = np.sin(beta * radianConversion) cosg = np.cos(gamma * radianConversion) sing = np.sin(gamma * radianConversion) matCoef_y = (cosa - cosb * cosg) / sing matCoef_z = np.power(sinb, 2, dtype=dataType) - \ np.power(matCoef_y, 2, dtype=dataType) if matCoef_z > 0.: matCoef_z = np.sqrt(matCoef_z) else: raise ValueError('Incorrect lattice vector coefficients.' 'Lattice parameters chosen return a non-positive ' 'z vector.') lattice_vec = [[1, 0, 0], [cosg, sing, 0], [cosb, matCoef_y, matCoef_z]] return np.asarray(lattice_vec, dtype=np.float64)
python
def _from_lattice_parameters(self, angles): dataType = np.float64 (alpha, beta, gamma) = angles radianConversion = np.pi / 180.0 cosa = np.cos(alpha * radianConversion) cosb = np.cos(beta * radianConversion) sinb = np.sin(beta * radianConversion) cosg = np.cos(gamma * radianConversion) sing = np.sin(gamma * radianConversion) matCoef_y = (cosa - cosb * cosg) / sing matCoef_z = np.power(sinb, 2, dtype=dataType) - \ np.power(matCoef_y, 2, dtype=dataType) if matCoef_z > 0.: matCoef_z = np.sqrt(matCoef_z) else: raise ValueError('Incorrect lattice vector coefficients.' 'Lattice parameters chosen return a non-positive ' 'z vector.') lattice_vec = [[1, 0, 0], [cosg, sing, 0], [cosb, matCoef_y, matCoef_z]] return np.asarray(lattice_vec, dtype=np.float64)
[ "def", "_from_lattice_parameters", "(", "self", ",", "angles", ")", ":", "dataType", "=", "np", ".", "float64", "(", "alpha", ",", "beta", ",", "gamma", ")", "=", "angles", "radianConversion", "=", "np", ".", "pi", "/", "180.0", "cosa", "=", "np", ".",...
Convert Bravais lattice parameters to lattice vectors. _from_lattice_parameters will generate the lattice vectors based on the parameters necessary to build a Bravais Lattice. The lattice vectors are in the lower diagonal matrix form. This was adapted from the ASE triclinic.py lattice parameter code. S. R. Bahn and K. W. Jacobsen An object-oriented scripting interface to a legacy electronic structure code Comput. Sci. Eng., Vol. 4, 56-66, 2002 Parameters ---------- angles : list-like, required Angles of bravais lattice.
[ "Convert", "Bravais", "lattice", "parameters", "to", "lattice", "vectors", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L340-L383
229,561
mosdef-hub/mbuild
mbuild/lattice.py
Lattice._from_lattice_vectors
def _from_lattice_vectors(self): """Calculate the angles between the vectors that define the lattice. _from_lattice_vectors will calculate the angles alpha, beta, and gamma from the Lattice object attribute lattice_vectors. """ degreeConvsersion = 180.0 / np.pi vector_magnitudes = np.linalg.norm(self.lattice_vectors, axis=1) a_dot_b = np.dot(self.lattice_vectors[0], self.lattice_vectors[1]) b_dot_c = np.dot(self.lattice_vectors[1], self.lattice_vectors[2]) a_dot_c = np.dot(self.lattice_vectors[0], self.lattice_vectors[2]) alpha_raw = b_dot_c / (vector_magnitudes[1] * vector_magnitudes[2]) beta_raw = a_dot_c / (vector_magnitudes[0] * vector_magnitudes[2]) gamma_raw = a_dot_b / (vector_magnitudes[0] * vector_magnitudes[1]) alpha = np.arccos(np.clip(alpha_raw, -1.0, 1.0)) * degreeConvsersion beta = np.arccos(np.clip(beta_raw, -1.0, 1.0)) * degreeConvsersion gamma = np.arccos(np.clip(gamma_raw, -1.0, 1.0)) * degreeConvsersion return np.asarray([alpha, beta, gamma], dtype=np.float64)
python
def _from_lattice_vectors(self): degreeConvsersion = 180.0 / np.pi vector_magnitudes = np.linalg.norm(self.lattice_vectors, axis=1) a_dot_b = np.dot(self.lattice_vectors[0], self.lattice_vectors[1]) b_dot_c = np.dot(self.lattice_vectors[1], self.lattice_vectors[2]) a_dot_c = np.dot(self.lattice_vectors[0], self.lattice_vectors[2]) alpha_raw = b_dot_c / (vector_magnitudes[1] * vector_magnitudes[2]) beta_raw = a_dot_c / (vector_magnitudes[0] * vector_magnitudes[2]) gamma_raw = a_dot_b / (vector_magnitudes[0] * vector_magnitudes[1]) alpha = np.arccos(np.clip(alpha_raw, -1.0, 1.0)) * degreeConvsersion beta = np.arccos(np.clip(beta_raw, -1.0, 1.0)) * degreeConvsersion gamma = np.arccos(np.clip(gamma_raw, -1.0, 1.0)) * degreeConvsersion return np.asarray([alpha, beta, gamma], dtype=np.float64)
[ "def", "_from_lattice_vectors", "(", "self", ")", ":", "degreeConvsersion", "=", "180.0", "/", "np", ".", "pi", "vector_magnitudes", "=", "np", ".", "linalg", ".", "norm", "(", "self", ".", "lattice_vectors", ",", "axis", "=", "1", ")", "a_dot_b", "=", "...
Calculate the angles between the vectors that define the lattice. _from_lattice_vectors will calculate the angles alpha, beta, and gamma from the Lattice object attribute lattice_vectors.
[ "Calculate", "the", "angles", "between", "the", "vectors", "that", "define", "the", "lattice", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lattice.py#L385-L407
229,562
mosdef-hub/mbuild
mbuild/examples/bilayer/bilayer.py
Bilayer.create_layer
def create_layer(self, lipid_indices=None, flip_orientation=False): """Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, default=False Flip the orientation of the layer with respect to the z-dimension. """ layer = mb.Compound() if not lipid_indices: lipid_indices = list(range(self.n_lipids_per_layer)) shuffle(lipid_indices) for n_type, n_of_lipid_type in enumerate(self.number_of_each_lipid_per_layer): current_type = self.lipids[n_type][0] for n_this_type, n_this_lipid_type in enumerate(range(n_of_lipid_type)): lipids_placed = n_type + n_this_type new_lipid = clone(current_type) random_index = lipid_indices[lipids_placed] position = self.pattern[random_index] # Zero and space in z-direction particles = list(new_lipid.particles()) ref_atom = self.ref_atoms[n_type] new_lipid.translate(-particles[ref_atom].pos + self.spacing) # Move to point on pattern if flip_orientation == True: center = new_lipid.center center[2] = 0.0 new_lipid.translate(-center) new_lipid.rotate(np.pi, [1, 0, 0]) new_lipid.translate(center) new_lipid.translate(position) layer.add(new_lipid) return layer, lipid_indices
python
def create_layer(self, lipid_indices=None, flip_orientation=False): layer = mb.Compound() if not lipid_indices: lipid_indices = list(range(self.n_lipids_per_layer)) shuffle(lipid_indices) for n_type, n_of_lipid_type in enumerate(self.number_of_each_lipid_per_layer): current_type = self.lipids[n_type][0] for n_this_type, n_this_lipid_type in enumerate(range(n_of_lipid_type)): lipids_placed = n_type + n_this_type new_lipid = clone(current_type) random_index = lipid_indices[lipids_placed] position = self.pattern[random_index] # Zero and space in z-direction particles = list(new_lipid.particles()) ref_atom = self.ref_atoms[n_type] new_lipid.translate(-particles[ref_atom].pos + self.spacing) # Move to point on pattern if flip_orientation == True: center = new_lipid.center center[2] = 0.0 new_lipid.translate(-center) new_lipid.rotate(np.pi, [1, 0, 0]) new_lipid.translate(center) new_lipid.translate(position) layer.add(new_lipid) return layer, lipid_indices
[ "def", "create_layer", "(", "self", ",", "lipid_indices", "=", "None", ",", "flip_orientation", "=", "False", ")", ":", "layer", "=", "mb", ".", "Compound", "(", ")", "if", "not", "lipid_indices", ":", "lipid_indices", "=", "list", "(", "range", "(", "se...
Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, default=False Flip the orientation of the layer with respect to the z-dimension.
[ "Create", "a", "monolayer", "of", "lipids", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/examples/bilayer/bilayer.py#L108-L146
229,563
mosdef-hub/mbuild
mbuild/examples/bilayer/bilayer.py
Bilayer.solvate_bilayer
def solvate_bilayer(self): """Solvate the constructed bilayer. """ solvent_number_density = self.solvent.n_particles / np.prod(self.solvent.periodicity) lengths = self.lipid_box.lengths water_box_z = self.solvent_per_layer / (lengths[0] * lengths[1] * solvent_number_density) mins = self.lipid_box.mins maxs = self.lipid_box.maxs bilayer_solvent_box = mb.Box(mins=[mins[0], mins[1], maxs[2]], maxs=[maxs[0], maxs[1], maxs[2] + 2 * water_box_z]) self.solvent_components.add(mb.fill_box(self.solvent, bilayer_solvent_box))
python
def solvate_bilayer(self): solvent_number_density = self.solvent.n_particles / np.prod(self.solvent.periodicity) lengths = self.lipid_box.lengths water_box_z = self.solvent_per_layer / (lengths[0] * lengths[1] * solvent_number_density) mins = self.lipid_box.mins maxs = self.lipid_box.maxs bilayer_solvent_box = mb.Box(mins=[mins[0], mins[1], maxs[2]], maxs=[maxs[0], maxs[1], maxs[2] + 2 * water_box_z]) self.solvent_components.add(mb.fill_box(self.solvent, bilayer_solvent_box))
[ "def", "solvate_bilayer", "(", "self", ")", ":", "solvent_number_density", "=", "self", ".", "solvent", ".", "n_particles", "/", "np", ".", "prod", "(", "self", ".", "solvent", ".", "periodicity", ")", "lengths", "=", "self", ".", "lipid_box", ".", "length...
Solvate the constructed bilayer.
[ "Solvate", "the", "constructed", "bilayer", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/examples/bilayer/bilayer.py#L148-L160
229,564
mosdef-hub/mbuild
mbuild/examples/bilayer/bilayer.py
Bilayer.solvent_per_layer
def solvent_per_layer(self): """Determine the number of solvent molecules per single layer. """ if self._solvent_per_layer: return self._solvent_per_layer assert not (self.solvent_per_lipid is None and self.n_solvent is None) if self.solvent_per_lipid is not None: assert self.n_solvent is None self._solvent_per_layer = self.n_lipids_per_layer * self.solvent_per_lipid elif self.n_solvent is not None: assert self.solvent_per_lipid is None self._solvent_per_layer = self.n_solvent / 2 return self._solvent_per_layer
python
def solvent_per_layer(self): if self._solvent_per_layer: return self._solvent_per_layer assert not (self.solvent_per_lipid is None and self.n_solvent is None) if self.solvent_per_lipid is not None: assert self.n_solvent is None self._solvent_per_layer = self.n_lipids_per_layer * self.solvent_per_lipid elif self.n_solvent is not None: assert self.solvent_per_lipid is None self._solvent_per_layer = self.n_solvent / 2 return self._solvent_per_layer
[ "def", "solvent_per_layer", "(", "self", ")", ":", "if", "self", ".", "_solvent_per_layer", ":", "return", "self", ".", "_solvent_per_layer", "assert", "not", "(", "self", ".", "solvent_per_lipid", "is", "None", "and", "self", ".", "n_solvent", "is", "None", ...
Determine the number of solvent molecules per single layer.
[ "Determine", "the", "number", "of", "solvent", "molecules", "per", "single", "layer", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/examples/bilayer/bilayer.py#L163-L175
229,565
mosdef-hub/mbuild
mbuild/examples/bilayer/bilayer.py
Bilayer.number_of_each_lipid_per_layer
def number_of_each_lipid_per_layer(self): """The number of each lipid per layer. """ if self._number_of_each_lipid_per_layer: return self._number_of_each_lipid_per_layer for lipid in self.lipids[:-1]: self._number_of_each_lipid_per_layer.append(int(round(lipid[1] * self.n_lipids_per_layer))) # TODO: give warning if frac * n different than actual # Rounding errors may make this off by 1, so just do total - whats_been_added. self._number_of_each_lipid_per_layer.append(self.n_lipids_per_layer - sum(self._number_of_each_lipid_per_layer)) assert len(self._number_of_each_lipid_per_layer) == len(self.lipids) return self._number_of_each_lipid_per_layer
python
def number_of_each_lipid_per_layer(self): if self._number_of_each_lipid_per_layer: return self._number_of_each_lipid_per_layer for lipid in self.lipids[:-1]: self._number_of_each_lipid_per_layer.append(int(round(lipid[1] * self.n_lipids_per_layer))) # TODO: give warning if frac * n different than actual # Rounding errors may make this off by 1, so just do total - whats_been_added. self._number_of_each_lipid_per_layer.append(self.n_lipids_per_layer - sum(self._number_of_each_lipid_per_layer)) assert len(self._number_of_each_lipid_per_layer) == len(self.lipids) return self._number_of_each_lipid_per_layer
[ "def", "number_of_each_lipid_per_layer", "(", "self", ")", ":", "if", "self", ".", "_number_of_each_lipid_per_layer", ":", "return", "self", ".", "_number_of_each_lipid_per_layer", "for", "lipid", "in", "self", ".", "lipids", "[", ":", "-", "1", "]", ":", "self"...
The number of each lipid per layer.
[ "The", "number", "of", "each", "lipid", "per", "layer", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/examples/bilayer/bilayer.py#L178-L190
229,566
mosdef-hub/mbuild
mbuild/examples/bilayer/bilayer.py
Bilayer.lipid_box
def lipid_box(self): """The box containing all of the lipids. """ if self._lipid_box: return self._lipid_box else: self._lipid_box = self.lipid_components.boundingbox # Add buffer around lipid box. self._lipid_box.mins -= np.array([0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl)]) self._lipid_box.maxs += np.array([0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl)]) return self._lipid_box
python
def lipid_box(self): if self._lipid_box: return self._lipid_box else: self._lipid_box = self.lipid_components.boundingbox # Add buffer around lipid box. self._lipid_box.mins -= np.array([0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl)]) self._lipid_box.maxs += np.array([0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl), 0.5*np.sqrt(self.apl)]) return self._lipid_box
[ "def", "lipid_box", "(", "self", ")", ":", "if", "self", ".", "_lipid_box", ":", "return", "self", ".", "_lipid_box", "else", ":", "self", ".", "_lipid_box", "=", "self", ".", "lipid_components", ".", "boundingbox", "# Add buffer around lipid box.", "self", "....
The box containing all of the lipids.
[ "The", "box", "containing", "all", "of", "the", "lipids", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/examples/bilayer/bilayer.py#L193-L206
229,567
mosdef-hub/mbuild
mbuild/compound.py
load
def load(filename, relative_to_module=None, compound=None, coords_only=False, rigid=False, use_parmed=False, smiles=False, **kwargs): """Load a file into an mbuild compound. Files are read using the MDTraj package unless the `use_parmed` argument is specified as True. Please refer to http://mdtraj.org/1.8.0/load_functions.html for formats supported by MDTraj and https://parmed.github.io/ParmEd/html/ readwrite.html for formats supported by ParmEd. Parameters ---------- filename : str Name of the file from which to load atom and bond information. relative_to_module : str, optional, default=None Instead of looking in the current working directory, look for the file where this module is defined. This is typically used in Compound classes that will be instantiated from a different directory (such as the Compounds located in mbuild.lib). compound : mb.Compound, optional, default=None Existing compound to load atom and bond information into. coords_only : bool, optional, default=False Only load the coordinates into an existing compoint. rigid : bool, optional, default=False Treat the compound as a rigid body use_parmed : bool, optional, default=False Use readers from ParmEd instead of MDTraj. smiles: bool, optional, default=False Use Open Babel to parse filename as a SMILES string or file containing a SMILES string **kwargs : keyword arguments Key word arguments passed to mdTraj for loading. Returns ------- compound : mb.Compound """ # Handle mbuild *.py files containing a class that wraps a structure file # in its own folder. E.g., you build a system from ~/foo.py and it imports # from ~/bar/baz.py where baz.py loads ~/bar/baz.pdb. if relative_to_module: script_path = os.path.realpath( sys.modules[relative_to_module].__file__) file_dir = os.path.dirname(script_path) filename = os.path.join(file_dir, filename) if compound is None: compound = Compound() # Handle the case of a xyz file, which must use an internal reader extension = os.path.splitext(filename)[-1] if extension == '.xyz' and not 'top' in kwargs: if coords_only: tmp = read_xyz(filename) if tmp.n_particles != compound.n_particles: raise ValueError('Number of atoms in {filename} does not match' ' {compound}'.format(**locals())) ref_and_compound = zip(tmp._particles(include_ports=False), compound.particles(include_ports=False)) for ref_particle, particle in ref_and_compound: particle.pos = ref_particle.pos else: compound = read_xyz(filename) return compound if use_parmed: warn( "use_parmed set to True. Bonds may be inferred from inter-particle " "distances and standard residue templates!") structure = pmd.load_file(filename, structure=True, **kwargs) compound.from_parmed(structure, coords_only=coords_only) elif smiles: pybel = import_('pybel') # First we try treating filename as a SMILES string try: mymol = pybel.readstring("smi", filename) # Now we treat it as a filename except(OSError, IOError): # For now, we only support reading in a single smiles molecule, # but pybel returns a generator, so we get the first molecule # and warn the user if there is more mymol_generator = pybel.readfile("smi", filename) mymol_list = list(mymol_generator) if len(mymol_list) == 1: mymol = mymol_list[0] else: mymol = mymol_list[0] warn("More than one SMILES string in file, more than one SMILES " "string is not supported, using {}".format(mymol.write("smi"))) tmp_dir = tempfile.mkdtemp() temp_file = os.path.join(tmp_dir, 'smiles_to_mol2_intermediate.mol2') mymol.make3D() mymol.write("MOL2", temp_file) structure = pmd.load_file(temp_file, structure=True, **kwargs) compound.from_parmed(structure, coords_only=coords_only) else: traj = md.load(filename, **kwargs) compound.from_trajectory(traj, frame=-1, coords_only=coords_only) if rigid: compound.label_rigid_bodies() return compound
python
def load(filename, relative_to_module=None, compound=None, coords_only=False, rigid=False, use_parmed=False, smiles=False, **kwargs): # Handle mbuild *.py files containing a class that wraps a structure file # in its own folder. E.g., you build a system from ~/foo.py and it imports # from ~/bar/baz.py where baz.py loads ~/bar/baz.pdb. if relative_to_module: script_path = os.path.realpath( sys.modules[relative_to_module].__file__) file_dir = os.path.dirname(script_path) filename = os.path.join(file_dir, filename) if compound is None: compound = Compound() # Handle the case of a xyz file, which must use an internal reader extension = os.path.splitext(filename)[-1] if extension == '.xyz' and not 'top' in kwargs: if coords_only: tmp = read_xyz(filename) if tmp.n_particles != compound.n_particles: raise ValueError('Number of atoms in {filename} does not match' ' {compound}'.format(**locals())) ref_and_compound = zip(tmp._particles(include_ports=False), compound.particles(include_ports=False)) for ref_particle, particle in ref_and_compound: particle.pos = ref_particle.pos else: compound = read_xyz(filename) return compound if use_parmed: warn( "use_parmed set to True. Bonds may be inferred from inter-particle " "distances and standard residue templates!") structure = pmd.load_file(filename, structure=True, **kwargs) compound.from_parmed(structure, coords_only=coords_only) elif smiles: pybel = import_('pybel') # First we try treating filename as a SMILES string try: mymol = pybel.readstring("smi", filename) # Now we treat it as a filename except(OSError, IOError): # For now, we only support reading in a single smiles molecule, # but pybel returns a generator, so we get the first molecule # and warn the user if there is more mymol_generator = pybel.readfile("smi", filename) mymol_list = list(mymol_generator) if len(mymol_list) == 1: mymol = mymol_list[0] else: mymol = mymol_list[0] warn("More than one SMILES string in file, more than one SMILES " "string is not supported, using {}".format(mymol.write("smi"))) tmp_dir = tempfile.mkdtemp() temp_file = os.path.join(tmp_dir, 'smiles_to_mol2_intermediate.mol2') mymol.make3D() mymol.write("MOL2", temp_file) structure = pmd.load_file(temp_file, structure=True, **kwargs) compound.from_parmed(structure, coords_only=coords_only) else: traj = md.load(filename, **kwargs) compound.from_trajectory(traj, frame=-1, coords_only=coords_only) if rigid: compound.label_rigid_bodies() return compound
[ "def", "load", "(", "filename", ",", "relative_to_module", "=", "None", ",", "compound", "=", "None", ",", "coords_only", "=", "False", ",", "rigid", "=", "False", ",", "use_parmed", "=", "False", ",", "smiles", "=", "False", ",", "*", "*", "kwargs", "...
Load a file into an mbuild compound. Files are read using the MDTraj package unless the `use_parmed` argument is specified as True. Please refer to http://mdtraj.org/1.8.0/load_functions.html for formats supported by MDTraj and https://parmed.github.io/ParmEd/html/ readwrite.html for formats supported by ParmEd. Parameters ---------- filename : str Name of the file from which to load atom and bond information. relative_to_module : str, optional, default=None Instead of looking in the current working directory, look for the file where this module is defined. This is typically used in Compound classes that will be instantiated from a different directory (such as the Compounds located in mbuild.lib). compound : mb.Compound, optional, default=None Existing compound to load atom and bond information into. coords_only : bool, optional, default=False Only load the coordinates into an existing compoint. rigid : bool, optional, default=False Treat the compound as a rigid body use_parmed : bool, optional, default=False Use readers from ParmEd instead of MDTraj. smiles: bool, optional, default=False Use Open Babel to parse filename as a SMILES string or file containing a SMILES string **kwargs : keyword arguments Key word arguments passed to mdTraj for loading. Returns ------- compound : mb.Compound
[ "Load", "a", "file", "into", "an", "mbuild", "compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L35-L140
229,568
mosdef-hub/mbuild
mbuild/compound.py
Compound.successors
def successors(self): """Yield Compounds below self in the hierarchy. Yields ------- mb.Compound The next Particle below self in the hierarchy """ if not self.children: return for part in self.children: # Parts local to the current Compound. yield part # Parts further down the hierarchy. for subpart in part.successors(): yield subpart
python
def successors(self): if not self.children: return for part in self.children: # Parts local to the current Compound. yield part # Parts further down the hierarchy. for subpart in part.successors(): yield subpart
[ "def", "successors", "(", "self", ")", ":", "if", "not", "self", ".", "children", ":", "return", "for", "part", "in", "self", ".", "children", ":", "# Parts local to the current Compound.", "yield", "part", "# Parts further down the hierarchy.", "for", "subpart", ...
Yield Compounds below self in the hierarchy. Yields ------- mb.Compound The next Particle below self in the hierarchy
[ "Yield", "Compounds", "below", "self", "in", "the", "hierarchy", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L311-L327
229,569
mosdef-hub/mbuild
mbuild/compound.py
Compound.ancestors
def ancestors(self): """Generate all ancestors of the Compound recursively. Yields ------ mb.Compound The next Compound above self in the hierarchy """ if self.parent is not None: yield self.parent for ancestor in self.parent.ancestors(): yield ancestor
python
def ancestors(self): if self.parent is not None: yield self.parent for ancestor in self.parent.ancestors(): yield ancestor
[ "def", "ancestors", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "yield", "self", ".", "parent", "for", "ancestor", "in", "self", ".", "parent", ".", "ancestors", "(", ")", ":", "yield", "ancestor" ]
Generate all ancestors of the Compound recursively. Yields ------ mb.Compound The next Compound above self in the hierarchy
[ "Generate", "all", "ancestors", "of", "the", "Compound", "recursively", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L354-L366
229,570
mosdef-hub/mbuild
mbuild/compound.py
Compound.particles_by_name
def particles_by_name(self, name): """Return all Particles of the Compound with a specific name Parameters ---------- name : str Only particles with this name are returned Yields ------ mb.Compound The next Particle in the Compound with the user-specified name """ for particle in self.particles(): if particle.name == name: yield particle
python
def particles_by_name(self, name): for particle in self.particles(): if particle.name == name: yield particle
[ "def", "particles_by_name", "(", "self", ",", "name", ")", ":", "for", "particle", "in", "self", ".", "particles", "(", ")", ":", "if", "particle", ".", "name", "==", "name", ":", "yield", "particle" ]
Return all Particles of the Compound with a specific name Parameters ---------- name : str Only particles with this name are returned Yields ------ mb.Compound The next Particle in the Compound with the user-specified name
[ "Return", "all", "Particles", "of", "the", "Compound", "with", "a", "specific", "name" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L385-L401
229,571
mosdef-hub/mbuild
mbuild/compound.py
Compound.contains_rigid
def contains_rigid(self): """Returns True if the Compound contains rigid bodies If the Compound contains any particle with a rigid_id != None then contains_rigid will return True. If the Compound has no children (i.e. the Compound resides at the bottom of the containment hierarchy) then contains_rigid will return False. Returns ------- bool True if the Compound contains any particle with a rigid_id != None Notes ----- The private variable '_check_if_contains_rigid_bodies' is used to help cache the status of 'contains_rigid'. If '_check_if_contains_rigid_bodies' is False, then the rigid body containment of the Compound has not changed, and the particle tree is not traversed, boosting performance. """ if self._check_if_contains_rigid_bodies: self._check_if_contains_rigid_bodies = False if any(particle.rigid_id is not None for particle in self._particles()): self._contains_rigid = True else: self._contains_rigid = False return self._contains_rigid
python
def contains_rigid(self): if self._check_if_contains_rigid_bodies: self._check_if_contains_rigid_bodies = False if any(particle.rigid_id is not None for particle in self._particles()): self._contains_rigid = True else: self._contains_rigid = False return self._contains_rigid
[ "def", "contains_rigid", "(", "self", ")", ":", "if", "self", ".", "_check_if_contains_rigid_bodies", ":", "self", ".", "_check_if_contains_rigid_bodies", "=", "False", "if", "any", "(", "particle", ".", "rigid_id", "is", "not", "None", "for", "particle", "in", ...
Returns True if the Compound contains rigid bodies If the Compound contains any particle with a rigid_id != None then contains_rigid will return True. If the Compound has no children (i.e. the Compound resides at the bottom of the containment hierarchy) then contains_rigid will return False. Returns ------- bool True if the Compound contains any particle with a rigid_id != None Notes ----- The private variable '_check_if_contains_rigid_bodies' is used to help cache the status of 'contains_rigid'. If '_check_if_contains_rigid_bodies' is False, then the rigid body containment of the Compound has not changed, and the particle tree is not traversed, boosting performance.
[ "Returns", "True", "if", "the", "Compound", "contains", "rigid", "bodies" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L432-L459
229,572
mosdef-hub/mbuild
mbuild/compound.py
Compound.max_rigid_id
def max_rigid_id(self): """Returns the maximum rigid body ID contained in the Compound. This is usually used by compound.root to determine the maximum rigid_id in the containment hierarchy. Returns ------- int or None The maximum rigid body ID contained in the Compound. If no rigid body IDs are found, None is returned """ try: return max([particle.rigid_id for particle in self.particles() if particle.rigid_id is not None]) except ValueError: return
python
def max_rigid_id(self): try: return max([particle.rigid_id for particle in self.particles() if particle.rigid_id is not None]) except ValueError: return
[ "def", "max_rigid_id", "(", "self", ")", ":", "try", ":", "return", "max", "(", "[", "particle", ".", "rigid_id", "for", "particle", "in", "self", ".", "particles", "(", ")", "if", "particle", ".", "rigid_id", "is", "not", "None", "]", ")", "except", ...
Returns the maximum rigid body ID contained in the Compound. This is usually used by compound.root to determine the maximum rigid_id in the containment hierarchy. Returns ------- int or None The maximum rigid body ID contained in the Compound. If no rigid body IDs are found, None is returned
[ "Returns", "the", "maximum", "rigid", "body", "ID", "contained", "in", "the", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L462-L479
229,573
mosdef-hub/mbuild
mbuild/compound.py
Compound.rigid_particles
def rigid_particles(self, rigid_id=None): """Generate all particles in rigid bodies. If a rigid_id is specified, then this function will only yield particles with a matching rigid_id. Parameters ---------- rigid_id : int, optional Include only particles with this rigid body ID Yields ------ mb.Compound The next particle with a rigid_id that is not None, or the next particle with a matching rigid_id if specified """ for particle in self.particles(): if rigid_id is not None: if particle.rigid_id == rigid_id: yield particle else: if particle.rigid_id is not None: yield particle
python
def rigid_particles(self, rigid_id=None): for particle in self.particles(): if rigid_id is not None: if particle.rigid_id == rigid_id: yield particle else: if particle.rigid_id is not None: yield particle
[ "def", "rigid_particles", "(", "self", ",", "rigid_id", "=", "None", ")", ":", "for", "particle", "in", "self", ".", "particles", "(", ")", ":", "if", "rigid_id", "is", "not", "None", ":", "if", "particle", ".", "rigid_id", "==", "rigid_id", ":", "yiel...
Generate all particles in rigid bodies. If a rigid_id is specified, then this function will only yield particles with a matching rigid_id. Parameters ---------- rigid_id : int, optional Include only particles with this rigid body ID Yields ------ mb.Compound The next particle with a rigid_id that is not None, or the next particle with a matching rigid_id if specified
[ "Generate", "all", "particles", "in", "rigid", "bodies", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L481-L505
229,574
mosdef-hub/mbuild
mbuild/compound.py
Compound.label_rigid_bodies
def label_rigid_bodies(self, discrete_bodies=None, rigid_particles=None): """Designate which Compounds should be treated as rigid bodies If no arguments are provided, this function will treat the compound as a single rigid body by providing all particles in `self` with the same rigid_id. If `discrete_bodies` is not None, each instance of a Compound with a name found in `discrete_bodies` will be treated as a unique rigid body. If `rigid_particles` is not None, only Particles (Compounds at the bottom of the containment hierarchy) matching this name will be considered part of the rigid body. Parameters ---------- discrete_bodies : str or list of str, optional, default=None Name(s) of Compound instances to be treated as unique rigid bodies. Compound instances matching this (these) name(s) will be provided with unique rigid_ids rigid_particles : str or list of str, optional, default=None Name(s) of Compound instances at the bottom of the containment hierarchy (Particles) to be included in rigid bodies. Only Particles matching this (these) name(s) will have their rigid_ids altered to match the rigid body number. Examples -------- Creating a rigid benzene >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.label_rigid_bodies() Creating a semi-rigid benzene, where only the carbons are treated as a rigid body >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.label_rigid_bodies(rigid_particles='C') Create a box of rigid benzenes, where each benzene has a unique rigid body ID. >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.name = 'Benzene' >>> filled = mb.fill_box(benzene, ... n_compounds=10, ... box=[0, 0, 0, 4, 4, 4]) >>> filled.label_rigid_bodies(distinct_bodies='Benzene') Create a box of semi-rigid benzenes, where each benzene has a unique rigid body ID and only the carbon portion is treated as rigid. >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.name = 'Benzene' >>> filled = mb.fill_box(benzene, ... n_compounds=10, ... box=[0, 0, 0, 4, 4, 4]) >>> filled.label_rigid_bodies(distinct_bodies='Benzene', ... rigid_particles='C') """ if discrete_bodies is not None: if isinstance(discrete_bodies, string_types): discrete_bodies = [discrete_bodies] if rigid_particles is not None: if isinstance(rigid_particles, string_types): rigid_particles = [rigid_particles] if self.root.max_rigid_id is not None: rigid_id = self.root.max_rigid_id + 1 warn("{} rigid bodies already exist. Incrementing 'rigid_id'" "starting from {}.".format(rigid_id, rigid_id)) else: rigid_id = 0 for successor in self.successors(): if discrete_bodies and successor.name not in discrete_bodies: continue for particle in successor.particles(): if rigid_particles and particle.name not in rigid_particles: continue particle.rigid_id = rigid_id if discrete_bodies: rigid_id += 1
python
def label_rigid_bodies(self, discrete_bodies=None, rigid_particles=None): if discrete_bodies is not None: if isinstance(discrete_bodies, string_types): discrete_bodies = [discrete_bodies] if rigid_particles is not None: if isinstance(rigid_particles, string_types): rigid_particles = [rigid_particles] if self.root.max_rigid_id is not None: rigid_id = self.root.max_rigid_id + 1 warn("{} rigid bodies already exist. Incrementing 'rigid_id'" "starting from {}.".format(rigid_id, rigid_id)) else: rigid_id = 0 for successor in self.successors(): if discrete_bodies and successor.name not in discrete_bodies: continue for particle in successor.particles(): if rigid_particles and particle.name not in rigid_particles: continue particle.rigid_id = rigid_id if discrete_bodies: rigid_id += 1
[ "def", "label_rigid_bodies", "(", "self", ",", "discrete_bodies", "=", "None", ",", "rigid_particles", "=", "None", ")", ":", "if", "discrete_bodies", "is", "not", "None", ":", "if", "isinstance", "(", "discrete_bodies", ",", "string_types", ")", ":", "discret...
Designate which Compounds should be treated as rigid bodies If no arguments are provided, this function will treat the compound as a single rigid body by providing all particles in `self` with the same rigid_id. If `discrete_bodies` is not None, each instance of a Compound with a name found in `discrete_bodies` will be treated as a unique rigid body. If `rigid_particles` is not None, only Particles (Compounds at the bottom of the containment hierarchy) matching this name will be considered part of the rigid body. Parameters ---------- discrete_bodies : str or list of str, optional, default=None Name(s) of Compound instances to be treated as unique rigid bodies. Compound instances matching this (these) name(s) will be provided with unique rigid_ids rigid_particles : str or list of str, optional, default=None Name(s) of Compound instances at the bottom of the containment hierarchy (Particles) to be included in rigid bodies. Only Particles matching this (these) name(s) will have their rigid_ids altered to match the rigid body number. Examples -------- Creating a rigid benzene >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.label_rigid_bodies() Creating a semi-rigid benzene, where only the carbons are treated as a rigid body >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.label_rigid_bodies(rigid_particles='C') Create a box of rigid benzenes, where each benzene has a unique rigid body ID. >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.name = 'Benzene' >>> filled = mb.fill_box(benzene, ... n_compounds=10, ... box=[0, 0, 0, 4, 4, 4]) >>> filled.label_rigid_bodies(distinct_bodies='Benzene') Create a box of semi-rigid benzenes, where each benzene has a unique rigid body ID and only the carbon portion is treated as rigid. >>> import mbuild as mb >>> from mbuild.utils.io import get_fn >>> benzene = mb.load(get_fn('benzene.mol2')) >>> benzene.name = 'Benzene' >>> filled = mb.fill_box(benzene, ... n_compounds=10, ... box=[0, 0, 0, 4, 4, 4]) >>> filled.label_rigid_bodies(distinct_bodies='Benzene', ... rigid_particles='C')
[ "Designate", "which", "Compounds", "should", "be", "treated", "as", "rigid", "bodies" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L507-L595
229,575
mosdef-hub/mbuild
mbuild/compound.py
Compound.unlabel_rigid_bodies
def unlabel_rigid_bodies(self): """Remove all rigid body labels from the Compound """ self._check_if_contains_rigid_bodies = True for child in self.children: child._check_if_contains_rigid_bodies = True for particle in self.particles(): particle.rigid_id = None
python
def unlabel_rigid_bodies(self): self._check_if_contains_rigid_bodies = True for child in self.children: child._check_if_contains_rigid_bodies = True for particle in self.particles(): particle.rigid_id = None
[ "def", "unlabel_rigid_bodies", "(", "self", ")", ":", "self", ".", "_check_if_contains_rigid_bodies", "=", "True", "for", "child", "in", "self", ".", "children", ":", "child", ".", "_check_if_contains_rigid_bodies", "=", "True", "for", "particle", "in", "self", ...
Remove all rigid body labels from the Compound
[ "Remove", "all", "rigid", "body", "labels", "from", "the", "Compound" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L597-L603
229,576
mosdef-hub/mbuild
mbuild/compound.py
Compound._increment_rigid_ids
def _increment_rigid_ids(self, increment): """Increment the rigid_id of all rigid Particles in a Compound Adds `increment` to the rigid_id of all Particles in `self` that already have an integer rigid_id. """ for particle in self.particles(): if particle.rigid_id is not None: particle.rigid_id += increment
python
def _increment_rigid_ids(self, increment): for particle in self.particles(): if particle.rigid_id is not None: particle.rigid_id += increment
[ "def", "_increment_rigid_ids", "(", "self", ",", "increment", ")", ":", "for", "particle", "in", "self", ".", "particles", "(", ")", ":", "if", "particle", ".", "rigid_id", "is", "not", "None", ":", "particle", ".", "rigid_id", "+=", "increment" ]
Increment the rigid_id of all rigid Particles in a Compound Adds `increment` to the rigid_id of all Particles in `self` that already have an integer rigid_id.
[ "Increment", "the", "rigid_id", "of", "all", "rigid", "Particles", "in", "a", "Compound" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L605-L613
229,577
mosdef-hub/mbuild
mbuild/compound.py
Compound._reorder_rigid_ids
def _reorder_rigid_ids(self): """Reorder rigid body IDs ensuring consecutiveness. Primarily used internally to ensure consecutive rigid_ids following removal of a Compound. """ max_rigid = self.max_rigid_id unique_rigid_ids = sorted( set([p.rigid_id for p in self.rigid_particles()])) n_unique_rigid = len(unique_rigid_ids) if max_rigid and n_unique_rigid != max_rigid + 1: missing_rigid_id = ( unique_rigid_ids[-1] * (unique_rigid_ids[-1] + 1)) / 2 - sum(unique_rigid_ids) for successor in self.successors(): if successor.rigid_id is not None: if successor.rigid_id > missing_rigid_id: successor.rigid_id -= 1 if self.rigid_id: if self.rigid_id > missing_rigid_id: self.rigid_id -= 1
python
def _reorder_rigid_ids(self): max_rigid = self.max_rigid_id unique_rigid_ids = sorted( set([p.rigid_id for p in self.rigid_particles()])) n_unique_rigid = len(unique_rigid_ids) if max_rigid and n_unique_rigid != max_rigid + 1: missing_rigid_id = ( unique_rigid_ids[-1] * (unique_rigid_ids[-1] + 1)) / 2 - sum(unique_rigid_ids) for successor in self.successors(): if successor.rigid_id is not None: if successor.rigid_id > missing_rigid_id: successor.rigid_id -= 1 if self.rigid_id: if self.rigid_id > missing_rigid_id: self.rigid_id -= 1
[ "def", "_reorder_rigid_ids", "(", "self", ")", ":", "max_rigid", "=", "self", ".", "max_rigid_id", "unique_rigid_ids", "=", "sorted", "(", "set", "(", "[", "p", ".", "rigid_id", "for", "p", "in", "self", ".", "rigid_particles", "(", ")", "]", ")", ")", ...
Reorder rigid body IDs ensuring consecutiveness. Primarily used internally to ensure consecutive rigid_ids following removal of a Compound.
[ "Reorder", "rigid", "body", "IDs", "ensuring", "consecutiveness", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L615-L635
229,578
mosdef-hub/mbuild
mbuild/compound.py
Compound.add
def add(self, new_child, label=None, containment=True, replace=False, inherit_periodicity=True, reset_rigid_ids=True): """Add a part to the Compound. Note: This does not necessarily add the part to self.children but may instead be used to add a reference to the part to self.labels. See 'containment' argument. Parameters ---------- new_child : mb.Compound or list-like of mb.Compound The object(s) to be added to this Compound. label : str, optional A descriptive string for the part. containment : bool, optional, default=True Add the part to self.children. replace : bool, optional, default=True Replace the label if it already exists. inherit_periodicity : bool, optional, default=True Replace the periodicity of self with the periodicity of the Compound being added reset_rigid_ids : bool, optional, default=True If the Compound to be added contains rigid bodies, reset the rigid_ids such that values remain distinct from rigid_ids already present in `self`. Can be set to False if attempting to add Compounds to an existing rigid body. """ # Support batch add via lists, tuples and sets. if (isinstance(new_child, collections.Iterable) and not isinstance(new_child, string_types)): for child in new_child: self.add(child, reset_rigid_ids=reset_rigid_ids) return if not isinstance(new_child, Compound): raise ValueError('Only objects that inherit from mbuild.Compound ' 'can be added to Compounds. You tried to add ' '"{}".'.format(new_child)) if new_child.contains_rigid or new_child.rigid_id is not None: if self.contains_rigid and reset_rigid_ids: new_child._increment_rigid_ids(increment=self.max_rigid_id + 1) self._check_if_contains_rigid_bodies = True if self.rigid_id is not None: self.rigid_id = None # Create children and labels on the first add operation if self.children is None: self.children = OrderedSet() if self.labels is None: self.labels = OrderedDict() if containment: if new_child.parent is not None: raise MBuildError('Part {} already has a parent: {}'.format( new_child, new_child.parent)) self.children.add(new_child) new_child.parent = self if new_child.bond_graph is not None: if self.root.bond_graph is None: self.root.bond_graph = new_child.bond_graph else: self.root.bond_graph.compose(new_child.bond_graph) new_child.bond_graph = None # Add new_part to labels. Does not currently support batch add. if label is None: label = '{0}[$]'.format(new_child.__class__.__name__) if label.endswith('[$]'): label = label[:-3] if label not in self.labels: self.labels[label] = [] label_pattern = label + '[{}]' count = len(self.labels[label]) self.labels[label].append(new_child) label = label_pattern.format(count) if not replace and label in self.labels: raise MBuildError('Label "{0}" already exists in {1}.'.format( label, self)) else: self.labels[label] = new_child new_child.referrers.add(self) if (inherit_periodicity and isinstance(new_child, Compound) and new_child.periodicity.any()): self.periodicity = new_child.periodicity
python
def add(self, new_child, label=None, containment=True, replace=False, inherit_periodicity=True, reset_rigid_ids=True): # Support batch add via lists, tuples and sets. if (isinstance(new_child, collections.Iterable) and not isinstance(new_child, string_types)): for child in new_child: self.add(child, reset_rigid_ids=reset_rigid_ids) return if not isinstance(new_child, Compound): raise ValueError('Only objects that inherit from mbuild.Compound ' 'can be added to Compounds. You tried to add ' '"{}".'.format(new_child)) if new_child.contains_rigid or new_child.rigid_id is not None: if self.contains_rigid and reset_rigid_ids: new_child._increment_rigid_ids(increment=self.max_rigid_id + 1) self._check_if_contains_rigid_bodies = True if self.rigid_id is not None: self.rigid_id = None # Create children and labels on the first add operation if self.children is None: self.children = OrderedSet() if self.labels is None: self.labels = OrderedDict() if containment: if new_child.parent is not None: raise MBuildError('Part {} already has a parent: {}'.format( new_child, new_child.parent)) self.children.add(new_child) new_child.parent = self if new_child.bond_graph is not None: if self.root.bond_graph is None: self.root.bond_graph = new_child.bond_graph else: self.root.bond_graph.compose(new_child.bond_graph) new_child.bond_graph = None # Add new_part to labels. Does not currently support batch add. if label is None: label = '{0}[$]'.format(new_child.__class__.__name__) if label.endswith('[$]'): label = label[:-3] if label not in self.labels: self.labels[label] = [] label_pattern = label + '[{}]' count = len(self.labels[label]) self.labels[label].append(new_child) label = label_pattern.format(count) if not replace and label in self.labels: raise MBuildError('Label "{0}" already exists in {1}.'.format( label, self)) else: self.labels[label] = new_child new_child.referrers.add(self) if (inherit_periodicity and isinstance(new_child, Compound) and new_child.periodicity.any()): self.periodicity = new_child.periodicity
[ "def", "add", "(", "self", ",", "new_child", ",", "label", "=", "None", ",", "containment", "=", "True", ",", "replace", "=", "False", ",", "inherit_periodicity", "=", "True", ",", "reset_rigid_ids", "=", "True", ")", ":", "# Support batch add via lists, tuple...
Add a part to the Compound. Note: This does not necessarily add the part to self.children but may instead be used to add a reference to the part to self.labels. See 'containment' argument. Parameters ---------- new_child : mb.Compound or list-like of mb.Compound The object(s) to be added to this Compound. label : str, optional A descriptive string for the part. containment : bool, optional, default=True Add the part to self.children. replace : bool, optional, default=True Replace the label if it already exists. inherit_periodicity : bool, optional, default=True Replace the periodicity of self with the periodicity of the Compound being added reset_rigid_ids : bool, optional, default=True If the Compound to be added contains rigid bodies, reset the rigid_ids such that values remain distinct from rigid_ids already present in `self`. Can be set to False if attempting to add Compounds to an existing rigid body.
[ "Add", "a", "part", "to", "the", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L637-L729
229,579
mosdef-hub/mbuild
mbuild/compound.py
Compound.remove
def remove(self, objs_to_remove): """Remove children from the Compound. Parameters ---------- objs_to_remove : mb.Compound or list of mb.Compound The Compound(s) to be removed from self """ if not self.children: return if not hasattr(objs_to_remove, '__iter__'): objs_to_remove = [objs_to_remove] objs_to_remove = set(objs_to_remove) if len(objs_to_remove) == 0: return remove_from_here = objs_to_remove.intersection(self.children) self.children -= remove_from_here yet_to_remove = objs_to_remove - remove_from_here for removed in remove_from_here: for child in removed.children: removed.remove(child) for removed_part in remove_from_here: if removed_part.rigid_id is not None: for ancestor in removed_part.ancestors(): ancestor._check_if_contains_rigid_bodies = True if self.root.bond_graph and self.root.bond_graph.has_node( removed_part): for neighbor in self.root.bond_graph.neighbors(removed_part): self.root.remove_bond((removed_part, neighbor)) self.root.bond_graph.remove_node(removed_part) self._remove_references(removed_part) # Remove the part recursively from sub-compounds. for child in self.children: child.remove(yet_to_remove) if child.contains_rigid: self.root._reorder_rigid_ids()
python
def remove(self, objs_to_remove): if not self.children: return if not hasattr(objs_to_remove, '__iter__'): objs_to_remove = [objs_to_remove] objs_to_remove = set(objs_to_remove) if len(objs_to_remove) == 0: return remove_from_here = objs_to_remove.intersection(self.children) self.children -= remove_from_here yet_to_remove = objs_to_remove - remove_from_here for removed in remove_from_here: for child in removed.children: removed.remove(child) for removed_part in remove_from_here: if removed_part.rigid_id is not None: for ancestor in removed_part.ancestors(): ancestor._check_if_contains_rigid_bodies = True if self.root.bond_graph and self.root.bond_graph.has_node( removed_part): for neighbor in self.root.bond_graph.neighbors(removed_part): self.root.remove_bond((removed_part, neighbor)) self.root.bond_graph.remove_node(removed_part) self._remove_references(removed_part) # Remove the part recursively from sub-compounds. for child in self.children: child.remove(yet_to_remove) if child.contains_rigid: self.root._reorder_rigid_ids()
[ "def", "remove", "(", "self", ",", "objs_to_remove", ")", ":", "if", "not", "self", ".", "children", ":", "return", "if", "not", "hasattr", "(", "objs_to_remove", ",", "'__iter__'", ")", ":", "objs_to_remove", "=", "[", "objs_to_remove", "]", "objs_to_remove...
Remove children from the Compound. Parameters ---------- objs_to_remove : mb.Compound or list of mb.Compound The Compound(s) to be removed from self
[ "Remove", "children", "from", "the", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L731-L773
229,580
mosdef-hub/mbuild
mbuild/compound.py
Compound._remove_references
def _remove_references(self, removed_part): """Remove labels pointing to this part and vice versa. """ removed_part.parent = None # Remove labels in the hierarchy pointing to this part. referrers_to_remove = set() for referrer in removed_part.referrers: if removed_part not in referrer.ancestors(): for label, referred_part in list(referrer.labels.items()): if referred_part is removed_part: del referrer.labels[label] referrers_to_remove.add(referrer) removed_part.referrers -= referrers_to_remove # Remove labels in this part pointing into the hierarchy. labels_to_delete = [] if isinstance(removed_part, Compound): for label, part in list(removed_part.labels.items()): if not isinstance(part, Compound): for p in part: self._remove_references(p) elif removed_part not in part.ancestors(): try: part.referrers.discard(removed_part) except KeyError: pass else: labels_to_delete.append(label) for label in labels_to_delete: removed_part.labels.pop(label, None)
python
def _remove_references(self, removed_part): removed_part.parent = None # Remove labels in the hierarchy pointing to this part. referrers_to_remove = set() for referrer in removed_part.referrers: if removed_part not in referrer.ancestors(): for label, referred_part in list(referrer.labels.items()): if referred_part is removed_part: del referrer.labels[label] referrers_to_remove.add(referrer) removed_part.referrers -= referrers_to_remove # Remove labels in this part pointing into the hierarchy. labels_to_delete = [] if isinstance(removed_part, Compound): for label, part in list(removed_part.labels.items()): if not isinstance(part, Compound): for p in part: self._remove_references(p) elif removed_part not in part.ancestors(): try: part.referrers.discard(removed_part) except KeyError: pass else: labels_to_delete.append(label) for label in labels_to_delete: removed_part.labels.pop(label, None)
[ "def", "_remove_references", "(", "self", ",", "removed_part", ")", ":", "removed_part", ".", "parent", "=", "None", "# Remove labels in the hierarchy pointing to this part.", "referrers_to_remove", "=", "set", "(", ")", "for", "referrer", "in", "removed_part", ".", "...
Remove labels pointing to this part and vice versa.
[ "Remove", "labels", "pointing", "to", "this", "part", "and", "vice", "versa", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L775-L804
229,581
mosdef-hub/mbuild
mbuild/compound.py
Compound.referenced_ports
def referenced_ports(self): """Return all Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all ports referenced by the Compound """ from mbuild.port import Port return [port for port in self.labels.values() if isinstance(port, Port)]
python
def referenced_ports(self): from mbuild.port import Port return [port for port in self.labels.values() if isinstance(port, Port)]
[ "def", "referenced_ports", "(", "self", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "return", "[", "port", "for", "port", "in", "self", ".", "labels", ".", "values", "(", ")", "if", "isinstance", "(", "port", ",", "Port", ")", "]" ]
Return all Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all ports referenced by the Compound
[ "Return", "all", "Ports", "referenced", "by", "this", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L806-L817
229,582
mosdef-hub/mbuild
mbuild/compound.py
Compound.all_ports
def all_ports(self): """Return all Ports referenced by this Compound and its successors Returns ------- list of mb.Compound A list of all Ports referenced by this Compound and its successors """ from mbuild.port import Port return [successor for successor in self.successors() if isinstance(successor, Port)]
python
def all_ports(self): from mbuild.port import Port return [successor for successor in self.successors() if isinstance(successor, Port)]
[ "def", "all_ports", "(", "self", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "return", "[", "successor", "for", "successor", "in", "self", ".", "successors", "(", ")", "if", "isinstance", "(", "successor", ",", "Port", ")", "]" ]
Return all Ports referenced by this Compound and its successors Returns ------- list of mb.Compound A list of all Ports referenced by this Compound and its successors
[ "Return", "all", "Ports", "referenced", "by", "this", "Compound", "and", "its", "successors" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L819-L830
229,583
mosdef-hub/mbuild
mbuild/compound.py
Compound.available_ports
def available_ports(self): """Return all unoccupied Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all unoccupied ports referenced by the Compound """ from mbuild.port import Port return [port for port in self.labels.values() if isinstance(port, Port) and not port.used]
python
def available_ports(self): from mbuild.port import Port return [port for port in self.labels.values() if isinstance(port, Port) and not port.used]
[ "def", "available_ports", "(", "self", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "return", "[", "port", "for", "port", "in", "self", ".", "labels", ".", "values", "(", ")", "if", "isinstance", "(", "port", ",", "Port", ")", "and", "n...
Return all unoccupied Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all unoccupied ports referenced by the Compound
[ "Return", "all", "unoccupied", "Ports", "referenced", "by", "this", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L832-L843
229,584
mosdef-hub/mbuild
mbuild/compound.py
Compound.bonds
def bonds(self): """Return all bonds in the Compound and sub-Compounds. Yields ------- tuple of mb.Compound The next bond in the Compound See Also -------- bond_graph.edges_iter : Iterates over all edges in a BondGraph """ if self.root.bond_graph: if self.root == self: return self.root.bond_graph.edges_iter() else: return self.root.bond_graph.subgraph( self.particles()).edges_iter() else: return iter(())
python
def bonds(self): if self.root.bond_graph: if self.root == self: return self.root.bond_graph.edges_iter() else: return self.root.bond_graph.subgraph( self.particles()).edges_iter() else: return iter(())
[ "def", "bonds", "(", "self", ")", ":", "if", "self", ".", "root", ".", "bond_graph", ":", "if", "self", ".", "root", "==", "self", ":", "return", "self", ".", "root", ".", "bond_graph", ".", "edges_iter", "(", ")", "else", ":", "return", "self", "....
Return all bonds in the Compound and sub-Compounds. Yields ------- tuple of mb.Compound The next bond in the Compound See Also -------- bond_graph.edges_iter : Iterates over all edges in a BondGraph
[ "Return", "all", "bonds", "in", "the", "Compound", "and", "sub", "-", "Compounds", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L845-L865
229,585
mosdef-hub/mbuild
mbuild/compound.py
Compound.add_bond
def add_bond(self, particle_pair): """Add a bond between two Particles. Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to add a bond between """ if self.root.bond_graph is None: self.root.bond_graph = BondGraph() self.root.bond_graph.add_edge(particle_pair[0], particle_pair[1])
python
def add_bond(self, particle_pair): if self.root.bond_graph is None: self.root.bond_graph = BondGraph() self.root.bond_graph.add_edge(particle_pair[0], particle_pair[1])
[ "def", "add_bond", "(", "self", ",", "particle_pair", ")", ":", "if", "self", ".", "root", ".", "bond_graph", "is", "None", ":", "self", ".", "root", ".", "bond_graph", "=", "BondGraph", "(", ")", "self", ".", "root", ".", "bond_graph", ".", "add_edge"...
Add a bond between two Particles. Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to add a bond between
[ "Add", "a", "bond", "between", "two", "Particles", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L879-L891
229,586
mosdef-hub/mbuild
mbuild/compound.py
Compound.remove_bond
def remove_bond(self, particle_pair): """Deletes a bond between a pair of Particles Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to remove the bond between """ from mbuild.port import Port if self.root.bond_graph is None or not self.root.bond_graph.has_edge( *particle_pair): warn("Bond between {} and {} doesn't exist!".format(*particle_pair)) return self.root.bond_graph.remove_edge(*particle_pair) bond_vector = particle_pair[0].pos - particle_pair[1].pos if np.allclose(bond_vector, np.zeros(3)): warn("Particles {} and {} overlap! Ports will not be added." "".format(*particle_pair)) return distance = np.linalg.norm(bond_vector) particle_pair[0].parent.add(Port(anchor=particle_pair[0], orientation=-bond_vector, separation=distance / 2), 'port[$]') particle_pair[1].parent.add(Port(anchor=particle_pair[1], orientation=bond_vector, separation=distance / 2), 'port[$]')
python
def remove_bond(self, particle_pair): from mbuild.port import Port if self.root.bond_graph is None or not self.root.bond_graph.has_edge( *particle_pair): warn("Bond between {} and {} doesn't exist!".format(*particle_pair)) return self.root.bond_graph.remove_edge(*particle_pair) bond_vector = particle_pair[0].pos - particle_pair[1].pos if np.allclose(bond_vector, np.zeros(3)): warn("Particles {} and {} overlap! Ports will not be added." "".format(*particle_pair)) return distance = np.linalg.norm(bond_vector) particle_pair[0].parent.add(Port(anchor=particle_pair[0], orientation=-bond_vector, separation=distance / 2), 'port[$]') particle_pair[1].parent.add(Port(anchor=particle_pair[1], orientation=bond_vector, separation=distance / 2), 'port[$]')
[ "def", "remove_bond", "(", "self", ",", "particle_pair", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "if", "self", ".", "root", ".", "bond_graph", "is", "None", "or", "not", "self", ".", "root", ".", "bond_graph", ".", "has_edge", "(", "...
Deletes a bond between a pair of Particles Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to remove the bond between
[ "Deletes", "a", "bond", "between", "a", "pair", "of", "Particles" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L927-L953
229,587
mosdef-hub/mbuild
mbuild/compound.py
Compound.xyz
def xyz(self): """Return all particle coordinates in this compound. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles. """ if not self.children: pos = np.expand_dims(self._pos, axis=0) else: arr = np.fromiter(itertools.chain.from_iterable( particle.pos for particle in self.particles()), dtype=float) pos = arr.reshape((-1, 3)) return pos
python
def xyz(self): if not self.children: pos = np.expand_dims(self._pos, axis=0) else: arr = np.fromiter(itertools.chain.from_iterable( particle.pos for particle in self.particles()), dtype=float) pos = arr.reshape((-1, 3)) return pos
[ "def", "xyz", "(", "self", ")", ":", "if", "not", "self", ".", "children", ":", "pos", "=", "np", ".", "expand_dims", "(", "self", ".", "_pos", ",", "axis", "=", "0", ")", "else", ":", "arr", "=", "np", ".", "fromiter", "(", "itertools", ".", "...
Return all particle coordinates in this compound. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles.
[ "Return", "all", "particle", "coordinates", "in", "this", "compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L979-L993
229,588
mosdef-hub/mbuild
mbuild/compound.py
Compound.xyz_with_ports
def xyz_with_ports(self): """Return all particle coordinates in this compound including ports. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles and ports. """ if not self.children: pos = self._pos else: arr = np.fromiter( itertools.chain.from_iterable( particle.pos for particle in self.particles( include_ports=True)), dtype=float) pos = arr.reshape((-1, 3)) return pos
python
def xyz_with_ports(self): if not self.children: pos = self._pos else: arr = np.fromiter( itertools.chain.from_iterable( particle.pos for particle in self.particles( include_ports=True)), dtype=float) pos = arr.reshape((-1, 3)) return pos
[ "def", "xyz_with_ports", "(", "self", ")", ":", "if", "not", "self", ".", "children", ":", "pos", "=", "self", ".", "_pos", "else", ":", "arr", "=", "np", ".", "fromiter", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "particle", ".", "p...
Return all particle coordinates in this compound including ports. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles and ports.
[ "Return", "all", "particle", "coordinates", "in", "this", "compound", "including", "ports", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L996-L1013
229,589
mosdef-hub/mbuild
mbuild/compound.py
Compound.xyz
def xyz(self, arrnx3): """Set the positions of the particles in the Compound, excluding the Ports. This function does not set the position of the ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions """ if not self.children: if not arrnx3.shape[0] == 1: raise ValueError( 'Trying to set position of {} with more than one' 'coordinate: {}'.format( self, arrnx3)) self.pos = np.squeeze(arrnx3) else: for atom, coords in zip( self._particles( include_ports=False), arrnx3): atom.pos = coords
python
def xyz(self, arrnx3): if not self.children: if not arrnx3.shape[0] == 1: raise ValueError( 'Trying to set position of {} with more than one' 'coordinate: {}'.format( self, arrnx3)) self.pos = np.squeeze(arrnx3) else: for atom, coords in zip( self._particles( include_ports=False), arrnx3): atom.pos = coords
[ "def", "xyz", "(", "self", ",", "arrnx3", ")", ":", "if", "not", "self", ".", "children", ":", "if", "not", "arrnx3", ".", "shape", "[", "0", "]", "==", "1", ":", "raise", "ValueError", "(", "'Trying to set position of {} with more than one'", "'coordinate: ...
Set the positions of the particles in the Compound, excluding the Ports. This function does not set the position of the ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions
[ "Set", "the", "positions", "of", "the", "particles", "in", "the", "Compound", "excluding", "the", "Ports", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1016-L1038
229,590
mosdef-hub/mbuild
mbuild/compound.py
Compound.xyz_with_ports
def xyz_with_ports(self, arrnx3): """Set the positions of the particles in the Compound, including the Ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions """ if not self.children: if not arrnx3.shape[0] == 1: raise ValueError( 'Trying to set position of {} with more than one' 'coordinate: {}'.format( self, arrnx3)) self.pos = np.squeeze(arrnx3) else: for atom, coords in zip( self._particles( include_ports=True), arrnx3): atom.pos = coords
python
def xyz_with_ports(self, arrnx3): if not self.children: if not arrnx3.shape[0] == 1: raise ValueError( 'Trying to set position of {} with more than one' 'coordinate: {}'.format( self, arrnx3)) self.pos = np.squeeze(arrnx3) else: for atom, coords in zip( self._particles( include_ports=True), arrnx3): atom.pos = coords
[ "def", "xyz_with_ports", "(", "self", ",", "arrnx3", ")", ":", "if", "not", "self", ".", "children", ":", "if", "not", "arrnx3", ".", "shape", "[", "0", "]", "==", "1", ":", "raise", "ValueError", "(", "'Trying to set position of {} with more than one'", "'c...
Set the positions of the particles in the Compound, including the Ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions
[ "Set", "the", "positions", "of", "the", "particles", "in", "the", "Compound", "including", "the", "Ports", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1041-L1061
229,591
mosdef-hub/mbuild
mbuild/compound.py
Compound.center
def center(self): """The cartesian center of the Compound based on its Particles. Returns ------- np.ndarray, shape=(3,), dtype=float The cartesian center of the Compound based on its Particles """ if np.all(np.isfinite(self.xyz)): return np.mean(self.xyz, axis=0)
python
def center(self): if np.all(np.isfinite(self.xyz)): return np.mean(self.xyz, axis=0)
[ "def", "center", "(", "self", ")", ":", "if", "np", ".", "all", "(", "np", ".", "isfinite", "(", "self", ".", "xyz", ")", ")", ":", "return", "np", ".", "mean", "(", "self", ".", "xyz", ",", "axis", "=", "0", ")" ]
The cartesian center of the Compound based on its Particles. Returns ------- np.ndarray, shape=(3,), dtype=float The cartesian center of the Compound based on its Particles
[ "The", "cartesian", "center", "of", "the", "Compound", "based", "on", "its", "Particles", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1064-L1075
229,592
mosdef-hub/mbuild
mbuild/compound.py
Compound.boundingbox
def boundingbox(self): """Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound """ xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
python
def boundingbox(self): xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
[ "def", "boundingbox", "(", "self", ")", ":", "xyz", "=", "self", ".", "xyz", "return", "Box", "(", "mins", "=", "xyz", ".", "min", "(", "axis", "=", "0", ")", ",", "maxs", "=", "xyz", ".", "max", "(", "axis", "=", "0", ")", ")" ]
Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound
[ "Compute", "the", "bounding", "box", "of", "the", "compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1078-L1088
229,593
mosdef-hub/mbuild
mbuild/compound.py
Compound.min_periodic_distance
def min_periodic_distance(self, xyz0, xyz1): """Vectorized distance calculation considering minimum image. Parameters ---------- xyz0 : np.ndarray, shape=(3,), dtype=float Coordinates of first point xyz1 : np.ndarray, shape=(3,), dtype=float Coordinates of second point Returns ------- float Vectorized distance between the two points following minimum image convention """ d = np.abs(xyz0 - xyz1) d = np.where(d > 0.5 * self.periodicity, self.periodicity - d, d) return np.sqrt((d ** 2).sum(axis=-1))
python
def min_periodic_distance(self, xyz0, xyz1): d = np.abs(xyz0 - xyz1) d = np.where(d > 0.5 * self.periodicity, self.periodicity - d, d) return np.sqrt((d ** 2).sum(axis=-1))
[ "def", "min_periodic_distance", "(", "self", ",", "xyz0", ",", "xyz1", ")", ":", "d", "=", "np", ".", "abs", "(", "xyz0", "-", "xyz1", ")", "d", "=", "np", ".", "where", "(", "d", ">", "0.5", "*", "self", ".", "periodicity", ",", "self", ".", "...
Vectorized distance calculation considering minimum image. Parameters ---------- xyz0 : np.ndarray, shape=(3,), dtype=float Coordinates of first point xyz1 : np.ndarray, shape=(3,), dtype=float Coordinates of second point Returns ------- float Vectorized distance between the two points following minimum image convention
[ "Vectorized", "distance", "calculation", "considering", "minimum", "image", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1090-L1109
229,594
mosdef-hub/mbuild
mbuild/compound.py
Compound.particles_in_range
def particles_in_range( self, compound, dmax, max_particles=20, particle_kdtree=None, particle_array=None): """Find particles within a specified range of another particle. Parameters ---------- compound : mb.Compound Reference particle to find other particles in range of dmax : float Maximum distance from 'compound' to look for Particles max_particles : int, optional, default=20 Maximum number of Particles to return particle_kdtree : mb.PeriodicCKDTree, optional KD-tree for looking up nearest neighbors. If not provided, a KD- tree will be generated from all Particles in self particle_array : np.ndarray, shape=(n,), dtype=mb.Compound, optional Array of possible particles to consider for return. If not provided, this defaults to all Particles in self Returns ------- np.ndarray, shape=(n,), dtype=mb.Compound Particles in range of compound according to user-defined limits See Also -------- periodic_kdtree.PerioidicCKDTree : mBuild implementation of kd-trees scipy.spatial.ckdtree : Further details on kd-trees """ if particle_kdtree is None: particle_kdtree = PeriodicCKDTree( data=self.xyz, bounds=self.periodicity) _, idxs = particle_kdtree.query( compound.pos, k=max_particles, distance_upper_bound=dmax) idxs = idxs[idxs != self.n_particles] if particle_array is None: particle_array = np.array(list(self.particles())) return particle_array[idxs]
python
def particles_in_range( self, compound, dmax, max_particles=20, particle_kdtree=None, particle_array=None): if particle_kdtree is None: particle_kdtree = PeriodicCKDTree( data=self.xyz, bounds=self.periodicity) _, idxs = particle_kdtree.query( compound.pos, k=max_particles, distance_upper_bound=dmax) idxs = idxs[idxs != self.n_particles] if particle_array is None: particle_array = np.array(list(self.particles())) return particle_array[idxs]
[ "def", "particles_in_range", "(", "self", ",", "compound", ",", "dmax", ",", "max_particles", "=", "20", ",", "particle_kdtree", "=", "None", ",", "particle_array", "=", "None", ")", ":", "if", "particle_kdtree", "is", "None", ":", "particle_kdtree", "=", "P...
Find particles within a specified range of another particle. Parameters ---------- compound : mb.Compound Reference particle to find other particles in range of dmax : float Maximum distance from 'compound' to look for Particles max_particles : int, optional, default=20 Maximum number of Particles to return particle_kdtree : mb.PeriodicCKDTree, optional KD-tree for looking up nearest neighbors. If not provided, a KD- tree will be generated from all Particles in self particle_array : np.ndarray, shape=(n,), dtype=mb.Compound, optional Array of possible particles to consider for return. If not provided, this defaults to all Particles in self Returns ------- np.ndarray, shape=(n,), dtype=mb.Compound Particles in range of compound according to user-defined limits See Also -------- periodic_kdtree.PerioidicCKDTree : mBuild implementation of kd-trees scipy.spatial.ckdtree : Further details on kd-trees
[ "Find", "particles", "within", "a", "specified", "range", "of", "another", "particle", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1111-L1154
229,595
mosdef-hub/mbuild
mbuild/compound.py
Compound.visualize
def visualize(self, show_ports=False): """Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. Parameters ---------- show_ports : bool, optional, default=False Visualize Ports in addition to Particles """ nglview = import_('nglview') from mdtraj.geometry.sasa import _ATOMIC_RADII if run_from_ipython(): remove_digits = lambda x: ''.join(i for i in x if not i.isdigit() or i == '_') for particle in self.particles(): particle.name = remove_digits(particle.name).upper() if not particle.name: particle.name = 'UNK' tmp_dir = tempfile.mkdtemp() self.save(os.path.join(tmp_dir, 'tmp.mol2'), show_ports=show_ports, overwrite=True) widget = nglview.show_file(os.path.join(tmp_dir, 'tmp.mol2')) widget.clear() widget.add_ball_and_stick(cylinderOnly=True) elements = set([particle.name for particle in self.particles()]) scale = 50.0 for element in elements: try: widget.add_ball_and_stick('_{}'.format( element.upper()), aspect_ratio=_ATOMIC_RADII[element.title()]**1.5 * scale) except KeyError: ids = [str(i) for i, particle in enumerate(self.particles()) if particle.name == element] widget.add_ball_and_stick( '@{}'.format( ','.join(ids)), aspect_ratio=0.17**1.5 * scale, color='grey') if show_ports: widget.add_ball_and_stick('_VS', aspect_ratio=1.0, color='#991f00') return widget else: raise RuntimeError('Visualization is only supported in Jupyter ' 'Notebooks.')
python
def visualize(self, show_ports=False): nglview = import_('nglview') from mdtraj.geometry.sasa import _ATOMIC_RADII if run_from_ipython(): remove_digits = lambda x: ''.join(i for i in x if not i.isdigit() or i == '_') for particle in self.particles(): particle.name = remove_digits(particle.name).upper() if not particle.name: particle.name = 'UNK' tmp_dir = tempfile.mkdtemp() self.save(os.path.join(tmp_dir, 'tmp.mol2'), show_ports=show_ports, overwrite=True) widget = nglview.show_file(os.path.join(tmp_dir, 'tmp.mol2')) widget.clear() widget.add_ball_and_stick(cylinderOnly=True) elements = set([particle.name for particle in self.particles()]) scale = 50.0 for element in elements: try: widget.add_ball_and_stick('_{}'.format( element.upper()), aspect_ratio=_ATOMIC_RADII[element.title()]**1.5 * scale) except KeyError: ids = [str(i) for i, particle in enumerate(self.particles()) if particle.name == element] widget.add_ball_and_stick( '@{}'.format( ','.join(ids)), aspect_ratio=0.17**1.5 * scale, color='grey') if show_ports: widget.add_ball_and_stick('_VS', aspect_ratio=1.0, color='#991f00') return widget else: raise RuntimeError('Visualization is only supported in Jupyter ' 'Notebooks.')
[ "def", "visualize", "(", "self", ",", "show_ports", "=", "False", ")", ":", "nglview", "=", "import_", "(", "'nglview'", ")", "from", "mdtraj", ".", "geometry", ".", "sasa", "import", "_ATOMIC_RADII", "if", "run_from_ipython", "(", ")", ":", "remove_digits",...
Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. Parameters ---------- show_ports : bool, optional, default=False Visualize Ports in addition to Particles
[ "Visualize", "the", "Compound", "using", "nglview", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1156-L1203
229,596
mosdef-hub/mbuild
mbuild/compound.py
Compound.update_coordinates
def update_coordinates(self, filename, update_port_locations=True): """Update the coordinates of this Compound from a file. Parameters ---------- filename : str Name of file from which to load coordinates. Supported file types are the same as those supported by load() update_port_locations : bool, optional, default=True Update the locations of Ports so that they are shifted along with their anchor particles. Note: This conserves the location of Ports with respect to the anchor Particle, but does not conserve the orientation of Ports with respect to the molecule as a whole. See Also -------- load : Load coordinates from a file """ if update_port_locations: xyz_init = self.xyz self = load(filename, compound=self, coords_only=True) self._update_port_locations(xyz_init) else: self = load(filename, compound=self, coords_only=True)
python
def update_coordinates(self, filename, update_port_locations=True): if update_port_locations: xyz_init = self.xyz self = load(filename, compound=self, coords_only=True) self._update_port_locations(xyz_init) else: self = load(filename, compound=self, coords_only=True)
[ "def", "update_coordinates", "(", "self", ",", "filename", ",", "update_port_locations", "=", "True", ")", ":", "if", "update_port_locations", ":", "xyz_init", "=", "self", ".", "xyz", "self", "=", "load", "(", "filename", ",", "compound", "=", "self", ",", ...
Update the coordinates of this Compound from a file. Parameters ---------- filename : str Name of file from which to load coordinates. Supported file types are the same as those supported by load() update_port_locations : bool, optional, default=True Update the locations of Ports so that they are shifted along with their anchor particles. Note: This conserves the location of Ports with respect to the anchor Particle, but does not conserve the orientation of Ports with respect to the molecule as a whole. See Also -------- load : Load coordinates from a file
[ "Update", "the", "coordinates", "of", "this", "Compound", "from", "a", "file", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1205-L1229
229,597
mosdef-hub/mbuild
mbuild/compound.py
Compound._update_port_locations
def _update_port_locations(self, initial_coordinates): """Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the location of Ports with respect to their anchor Particles, but does not conserve the orientation of Ports with respect to the molecule as a whole. Parameters ---------- initial_coordinates : np.ndarray, shape=(n, 3), dtype=float Reference coordinates to use for comparing how far anchor Particles have shifted. """ particles = list(self.particles()) for port in self.all_ports(): if port.anchor: idx = particles.index(port.anchor) shift = particles[idx].pos - initial_coordinates[idx] port.translate(shift)
python
def _update_port_locations(self, initial_coordinates): particles = list(self.particles()) for port in self.all_ports(): if port.anchor: idx = particles.index(port.anchor) shift = particles[idx].pos - initial_coordinates[idx] port.translate(shift)
[ "def", "_update_port_locations", "(", "self", ",", "initial_coordinates", ")", ":", "particles", "=", "list", "(", "self", ".", "particles", "(", ")", ")", "for", "port", "in", "self", ".", "all_ports", "(", ")", ":", "if", "port", ".", "anchor", ":", ...
Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the location of Ports with respect to their anchor Particles, but does not conserve the orientation of Ports with respect to the molecule as a whole. Parameters ---------- initial_coordinates : np.ndarray, shape=(n, 3), dtype=float Reference coordinates to use for comparing how far anchor Particles have shifted.
[ "Adjust", "port", "locations", "after", "particles", "have", "moved" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1231-L1252
229,598
mosdef-hub/mbuild
mbuild/compound.py
Compound._kick
def _kick(self): """Slightly adjust all coordinates in a Compound Provides a slight adjustment to coordinates to kick them out of local energy minima. """ xyz_init = self.xyz for particle in self.particles(): particle.pos += (np.random.rand(3,) - 0.5) / 100 self._update_port_locations(xyz_init)
python
def _kick(self): xyz_init = self.xyz for particle in self.particles(): particle.pos += (np.random.rand(3,) - 0.5) / 100 self._update_port_locations(xyz_init)
[ "def", "_kick", "(", "self", ")", ":", "xyz_init", "=", "self", ".", "xyz", "for", "particle", "in", "self", ".", "particles", "(", ")", ":", "particle", ".", "pos", "+=", "(", "np", ".", "random", ".", "rand", "(", "3", ",", ")", "-", "0.5", "...
Slightly adjust all coordinates in a Compound Provides a slight adjustment to coordinates to kick them out of local energy minima.
[ "Slightly", "adjust", "all", "coordinates", "in", "a", "Compound" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1254-L1263
229,599
mosdef-hub/mbuild
mbuild/compound.py
Compound.save
def save(self, filename, show_ports=False, forcefield_name=None, forcefield_files=None, forcefield_debug=False, box=None, overwrite=False, residues=None, references_file=None, combining_rule='lorentz', foyerkwargs={}, **kwargs): """Save the Compound to a file. Parameters ---------- filename : str Filesystem path in which to save the trajectory. The extension or prefix will be parsed and control the format. Supported extensions are: 'hoomdxml', 'gsd', 'gro', 'top', 'lammps', 'lmp' show_ports : bool, optional, default=False Save ports contained within the compound. forcefield_files : str, optional, default=None Apply a forcefield to the output file using a forcefield provided by the `foyer` package. forcefield_name : str, optional, default=None Apply a named forcefield to the output file using the `foyer` package, e.g. 'oplsaa'. Forcefields listed here: https://github.com/mosdef-hub/foyer/tree/master/foyer/forcefields forcefield_debug : bool, optional, default=False Choose level of verbosity when applying a forcefield through `foyer`. Specifically, when missing atom types in the forcefield xml file, determine if the warning is condensed or verbose. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be written to the output file. If 'None', a bounding box is used with 0.25nm buffers at each face to avoid overlapping atoms. overwrite : bool, optional, default=False Overwrite if the filename already exists residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. references_file : str, optional, default=None Specify a filename to write references for the forcefield that is to be applied. References are written in BiBTeX format. combining_rule : str, optional, default='lorentz' Specify the combining rule for nonbonded interactions. Only relevant when the `foyer` package is used to apply a forcefield. Valid options are 'lorentz' and 'geometric', specifying Lorentz-Berthelot and geometric combining rules respectively. Other Parameters ---------------- foyerkwargs : dict, optional Specify keyword arguments when applying the foyer Forcefield ref_distance : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting distance values to reduced units. ref_energy : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting energy values to reduced units. ref_mass : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting mass values to reduced units. atom_style: str, default='full' Defines the style of atoms to be saved in a LAMMPS data file. The following atom styles are currently supported: 'full', 'atomic', 'charge', 'molecular' see http://lammps.sandia.gov/doc/atom_style.html for more information on atom styles. See Also -------- formats.gsdwrite.write_gsd : Write to GSD format formats.hoomdxml.write_hoomdxml : Write to Hoomd XML format formats.lammpsdata.write_lammpsdata : Write to LAMMPS data format """ extension = os.path.splitext(filename)[-1] if extension == '.xyz': traj = self.to_trajectory(show_ports=show_ports) traj.save(filename) return # Savers supported by mbuild.formats savers = {'.hoomdxml': write_hoomdxml, '.gsd': write_gsd, '.lammps': write_lammpsdata, '.lmp': write_lammpsdata} try: saver = savers[extension] except KeyError: saver = None if os.path.exists(filename) and not overwrite: raise IOError('{0} exists; not overwriting'.format(filename)) structure = self.to_parmed(box=box, residues=residues, show_ports=show_ports) # Apply a force field with foyer if specified if forcefield_name or forcefield_files: foyer = import_('foyer') ff = foyer.Forcefield(forcefield_files=forcefield_files, name=forcefield_name, debug=forcefield_debug) structure = ff.apply(structure, references_file=references_file, **foyerkwargs) structure.combining_rule = combining_rule total_charge = sum([atom.charge for atom in structure]) if round(total_charge, 4) != 0.0: warn('System is not charge neutral. Total charge is {}.' ''.format(total_charge)) # Provide a warning if rigid_ids are not sequential from 0 if self.contains_rigid: unique_rigid_ids = sorted(set([ p.rigid_id for p in self.rigid_particles()])) if max(unique_rigid_ids) != len(unique_rigid_ids) - 1: warn("Unique rigid body IDs are not sequential starting from zero.") if saver: # mBuild supported saver. if extension in ['.gsd', '.hoomdxml']: kwargs['rigid_bodies'] = [ p.rigid_id for p in self.particles()] saver(filename=filename, structure=structure, **kwargs) else: # ParmEd supported saver. structure.save(filename, overwrite=overwrite, **kwargs)
python
def save(self, filename, show_ports=False, forcefield_name=None, forcefield_files=None, forcefield_debug=False, box=None, overwrite=False, residues=None, references_file=None, combining_rule='lorentz', foyerkwargs={}, **kwargs): extension = os.path.splitext(filename)[-1] if extension == '.xyz': traj = self.to_trajectory(show_ports=show_ports) traj.save(filename) return # Savers supported by mbuild.formats savers = {'.hoomdxml': write_hoomdxml, '.gsd': write_gsd, '.lammps': write_lammpsdata, '.lmp': write_lammpsdata} try: saver = savers[extension] except KeyError: saver = None if os.path.exists(filename) and not overwrite: raise IOError('{0} exists; not overwriting'.format(filename)) structure = self.to_parmed(box=box, residues=residues, show_ports=show_ports) # Apply a force field with foyer if specified if forcefield_name or forcefield_files: foyer = import_('foyer') ff = foyer.Forcefield(forcefield_files=forcefield_files, name=forcefield_name, debug=forcefield_debug) structure = ff.apply(structure, references_file=references_file, **foyerkwargs) structure.combining_rule = combining_rule total_charge = sum([atom.charge for atom in structure]) if round(total_charge, 4) != 0.0: warn('System is not charge neutral. Total charge is {}.' ''.format(total_charge)) # Provide a warning if rigid_ids are not sequential from 0 if self.contains_rigid: unique_rigid_ids = sorted(set([ p.rigid_id for p in self.rigid_particles()])) if max(unique_rigid_ids) != len(unique_rigid_ids) - 1: warn("Unique rigid body IDs are not sequential starting from zero.") if saver: # mBuild supported saver. if extension in ['.gsd', '.hoomdxml']: kwargs['rigid_bodies'] = [ p.rigid_id for p in self.particles()] saver(filename=filename, structure=structure, **kwargs) else: # ParmEd supported saver. structure.save(filename, overwrite=overwrite, **kwargs)
[ "def", "save", "(", "self", ",", "filename", ",", "show_ports", "=", "False", ",", "forcefield_name", "=", "None", ",", "forcefield_files", "=", "None", ",", "forcefield_debug", "=", "False", ",", "box", "=", "None", ",", "overwrite", "=", "False", ",", ...
Save the Compound to a file. Parameters ---------- filename : str Filesystem path in which to save the trajectory. The extension or prefix will be parsed and control the format. Supported extensions are: 'hoomdxml', 'gsd', 'gro', 'top', 'lammps', 'lmp' show_ports : bool, optional, default=False Save ports contained within the compound. forcefield_files : str, optional, default=None Apply a forcefield to the output file using a forcefield provided by the `foyer` package. forcefield_name : str, optional, default=None Apply a named forcefield to the output file using the `foyer` package, e.g. 'oplsaa'. Forcefields listed here: https://github.com/mosdef-hub/foyer/tree/master/foyer/forcefields forcefield_debug : bool, optional, default=False Choose level of verbosity when applying a forcefield through `foyer`. Specifically, when missing atom types in the forcefield xml file, determine if the warning is condensed or verbose. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be written to the output file. If 'None', a bounding box is used with 0.25nm buffers at each face to avoid overlapping atoms. overwrite : bool, optional, default=False Overwrite if the filename already exists residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. references_file : str, optional, default=None Specify a filename to write references for the forcefield that is to be applied. References are written in BiBTeX format. combining_rule : str, optional, default='lorentz' Specify the combining rule for nonbonded interactions. Only relevant when the `foyer` package is used to apply a forcefield. Valid options are 'lorentz' and 'geometric', specifying Lorentz-Berthelot and geometric combining rules respectively. Other Parameters ---------------- foyerkwargs : dict, optional Specify keyword arguments when applying the foyer Forcefield ref_distance : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting distance values to reduced units. ref_energy : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting energy values to reduced units. ref_mass : float, optional, default=1.0 Normalization factor used when saving to .gsd and .hoomdxml formats for converting mass values to reduced units. atom_style: str, default='full' Defines the style of atoms to be saved in a LAMMPS data file. The following atom styles are currently supported: 'full', 'atomic', 'charge', 'molecular' see http://lammps.sandia.gov/doc/atom_style.html for more information on atom styles. See Also -------- formats.gsdwrite.write_gsd : Write to GSD format formats.hoomdxml.write_hoomdxml : Write to Hoomd XML format formats.lammpsdata.write_lammpsdata : Write to LAMMPS data format
[ "Save", "the", "Compound", "to", "a", "file", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1650-L1769