repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
alex-kostirin/pyatomac
atomac/ldtpd/combo_box.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/combo_box.py#L260-L284
def verifydropdown(self, window_name, object_name): """ Verify drop down list / menu poped up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled or not object_handle.AXChildren: return 0 # Get AXMenu children = object_handle.AXChildren[0] if children: return 1 except LdtpServerException: pass return 0
[ "def", "verifydropdown", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", "or", "not...
Verify drop down list / menu poped up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success 0 on failure. @rtype: integer
[ "Verify", "drop", "down", "list", "/", "menu", "poped", "up", "@param", "window_name", ":", "Window", "name", "to", "type", "in", "either", "full", "name", "LDTP", "s", "name", "convention", "or", "a", "Unix", "glob", ".", "@type", "window_name", ":", "s...
python
valid
hazelcast/hazelcast-python-client
hazelcast/proxy/transactional_set.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_set.py#L11-L19
def add(self, item): """ Transactional implementation of :func:`Set.add(item) <hazelcast.proxy.set.Set.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if item is added successfully, ``false`` otherwise. """ check_not_none(item, "item can't be none") return self._encode_invoke(transactional_set_add_codec, item=self._to_data(item))
[ "def", "add", "(", "self", ",", "item", ")", ":", "check_not_none", "(", "item", ",", "\"item can't be none\"", ")", "return", "self", ".", "_encode_invoke", "(", "transactional_set_add_codec", ",", "item", "=", "self", ".", "_to_data", "(", "item", ")", ")"...
Transactional implementation of :func:`Set.add(item) <hazelcast.proxy.set.Set.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if item is added successfully, ``false`` otherwise.
[ "Transactional", "implementation", "of", ":", "func", ":", "Set", ".", "add", "(", "item", ")", "<hazelcast", ".", "proxy", ".", "set", ".", "Set", ".", "add", ">" ]
python
train
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L836-L846
def _desc_has_data(desc): """Returns true if there is any data set for a particular PhoneNumberDesc.""" if desc is None: return False # Checking most properties since we don't know what's present, since a custom build may have # stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the # possibleLengthsLocalOnly, since if this is the only thing that's present we don't really # support the type at all: no type-specific methods will work with only this data. return ((desc.example_number is not None) or _desc_has_possible_number_data(desc) or (desc.national_number_pattern is not None))
[ "def", "_desc_has_data", "(", "desc", ")", ":", "if", "desc", "is", "None", ":", "return", "False", "# Checking most properties since we don't know what's present, since a custom build may have", "# stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking...
Returns true if there is any data set for a particular PhoneNumberDesc.
[ "Returns", "true", "if", "there", "is", "any", "data", "set", "for", "a", "particular", "PhoneNumberDesc", "." ]
python
train
andreikop/qutepart
qutepart/__init__.py
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1329-L1336
def _onShortcutSelectAndScroll(self, down): """Ctrl+Shift+Up/Down pressed. Select line and scroll viewport """ cursor = self.textCursor() cursor.movePosition(QTextCursor.Down if down else QTextCursor.Up, QTextCursor.KeepAnchor) self.setTextCursor(cursor) self._onShortcutScroll(down)
[ "def", "_onShortcutSelectAndScroll", "(", "self", ",", "down", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "Down", "if", "down", "else", "QTextCursor", ".", "Up", ",", "QTextCursor", ...
Ctrl+Shift+Up/Down pressed. Select line and scroll viewport
[ "Ctrl", "+", "Shift", "+", "Up", "/", "Down", "pressed", ".", "Select", "line", "and", "scroll", "viewport" ]
python
train
valsaven/md5hash
md5hash/md5hash.py
https://github.com/valsaven/md5hash/blob/83208769a8e9c74bd9e4ce72ac1df00615af82f2/md5hash/md5hash.py#L70-L93
def scan(tree): """Scan the directory and send the obtained tuple to calculate. :param tree: path to file or directory""" tree = os.path.normpath(tree) assert os.path.exists(tree), "#Error. The path '{}' is" \ " invalid or doesn't exist.".format(str(tree)) if os.path.isfile(tree): return md5(tree) elif os.path.isdir(tree): tree = os.walk(tree) for directory in tree: print('...................') print('Current directory:') print(directory[0]) # Current directory if not directory[2]: # Empty directory check print('An empty directory.') continue else: print('List of the files in the current directory:') print(directory[2]) # Files in the current directory print() calculate(directory)
[ "def", "scan", "(", "tree", ")", ":", "tree", "=", "os", ".", "path", ".", "normpath", "(", "tree", ")", "assert", "os", ".", "path", ".", "exists", "(", "tree", ")", ",", "\"#Error. The path '{}' is\"", "\" invalid or doesn't exist.\"", ".", "format", "("...
Scan the directory and send the obtained tuple to calculate. :param tree: path to file or directory
[ "Scan", "the", "directory", "and", "send", "the", "obtained", "tuple", "to", "calculate", ".", ":", "param", "tree", ":", "path", "to", "file", "or", "directory" ]
python
test
sdispater/eloquent
eloquent/query/builder.py
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1400-L1413
def merge_wheres(self, wheres, bindings): """ Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None """ self.wheres = self.wheres + wheres self._bindings['where'] = self._bindings['where'] + bindings
[ "def", "merge_wheres", "(", "self", ",", "wheres", ",", "bindings", ")", ":", "self", ".", "wheres", "=", "self", ".", "wheres", "+", "wheres", "self", ".", "_bindings", "[", "'where'", "]", "=", "self", ".", "_bindings", "[", "'where'", "]", "+", "b...
Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None
[ "Merge", "a", "list", "of", "where", "clauses", "and", "bindings" ]
python
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L492-L514
def connect(self, chassis_list): """Establish connection to one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) Return: List of chassis addresses. """ self._check_session() if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)): chassis_list = (chassis_list,) if len(chassis_list) == 1: status, data = self._rest.put_request( 'connections', chassis_list[0]) data = [data] else: params = {chassis: True for chassis in chassis_list} params['action'] = 'connect' status, data = self._rest.post_request('connections', None, params) return data
[ "def", "connect", "(", "self", ",", "chassis_list", ")", ":", "self", ".", "_check_session", "(", ")", "if", "not", "isinstance", "(", "chassis_list", ",", "(", "list", ",", "tuple", ",", "set", ",", "dict", ",", "frozenset", ")", ")", ":", "chassis_li...
Establish connection to one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) Return: List of chassis addresses.
[ "Establish", "connection", "to", "one", "or", "more", "chassis", "." ]
python
train
saschpe/rapport
rapport/timeframe.py
https://github.com/saschpe/rapport/blob/ccceb8f84bd7e8add88ab5e137cdab6424aa4683/rapport/timeframe.py#L31-L34
def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
[ "def", "iso_to_gregorian", "(", "iso_year", ",", "iso_week", ",", "iso_day", ")", ":", "year_start", "=", "iso_year_start", "(", "iso_year", ")", "return", "year_start", "+", "datetime", ".", "timedelta", "(", "days", "=", "iso_day", "-", "1", ",", "weeks", ...
Gregorian calendar date for the given ISO year, week and day
[ "Gregorian", "calendar", "date", "for", "the", "given", "ISO", "year", "week", "and", "day" ]
python
train
iterative/dvc
dvc/scm/git/tree.py
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/git/tree.py#L126-L139
def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument """ tree = self.git_object_by_path(top) if tree is None: raise IOError(errno.ENOENT, "No such file") for x in self._walk(tree, topdown): yield x
[ "def", "walk", "(", "self", ",", "top", ",", "topdown", "=", "True", ",", "ignore_file_handler", "=", "None", ")", ":", "tree", "=", "self", ".", "git_object_by_path", "(", "top", ")", "if", "tree", "is", "None", ":", "raise", "IOError", "(", "errno", ...
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument
[ "Directory", "tree", "generator", "." ]
python
train
ranaroussi/pywallet
pywallet/utils/bip32.py
https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L190-L249
def get_child_for_path(self, path): """Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or, in other words, the 10th publicly derived child of the 1st privately derived child of the 0th publicly derived child of master. You can use either ' or p to denote a prime (that is, privately derived) child. A child that has had its private key stripped can be requested by either passing a capital M or appending '.pub' to the end of the path. These three paths all give the same child that has had its private key scrubbed: M/0/1 m/0/1.pub M/0/1.pub """ path = ensure_str(path) if not path: raise InvalidPathError("%s is not a valid path" % path) # Figure out public/private derivation as_private = True if path.startswith("M"): as_private = False if path.endswith(".pub"): as_private = False path = path[:-4] parts = path.split("/") if len(parts) == 0: raise InvalidPathError() child = self for part in parts: if part.lower() == "m": continue is_prime = None # Let primeness be figured out by the child number if part[-1] in "'p": is_prime = True part = part.replace("'", "").replace("p", "") try: child_number = long_or_int(part) except ValueError: raise InvalidPathError("%s is not a valid path" % path) child = child.get_child(child_number, is_prime) if not as_private: return child.public_copy() return child
[ "def", "get_child_for_path", "(", "self", ",", "path", ")", ":", "path", "=", "ensure_str", "(", "path", ")", "if", "not", "path", ":", "raise", "InvalidPathError", "(", "\"%s is not a valid path\"", "%", "path", ")", "# Figure out public/private derivation", "as_...
Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or, in other words, the 10th publicly derived child of the 1st privately derived child of the 0th publicly derived child of master. You can use either ' or p to denote a prime (that is, privately derived) child. A child that has had its private key stripped can be requested by either passing a capital M or appending '.pub' to the end of the path. These three paths all give the same child that has had its private key scrubbed: M/0/1 m/0/1.pub M/0/1.pub
[ "Get", "a", "child", "for", "a", "given", "path", "." ]
python
train
Nic30/ipCorePackager
ipCorePackager/packager.py
https://github.com/Nic30/ipCorePackager/blob/0af4e56ebfdc3749fffa40d50d9ccbf8b5445881/ipCorePackager/packager.py#L194-L202
def getTypeWidth(self, dtype: "HdlType", do_eval=False) -> Tuple[int, str, bool]: """ :return: tuple (current value of width, string of value (can be ID or int), Flag which specifies if width of signal is locked or can be changed by parameter) """ raise NotImplementedError( "Implement this method in your HdlType classes")
[ "def", "getTypeWidth", "(", "self", ",", "dtype", ":", "\"HdlType\"", ",", "do_eval", "=", "False", ")", "->", "Tuple", "[", "int", ",", "str", ",", "bool", "]", ":", "raise", "NotImplementedError", "(", "\"Implement this method in your HdlType classes\"", ")" ]
:return: tuple (current value of width, string of value (can be ID or int), Flag which specifies if width of signal is locked or can be changed by parameter)
[ ":", "return", ":", "tuple", "(", "current", "value", "of", "width", "string", "of", "value", "(", "can", "be", "ID", "or", "int", ")", "Flag", "which", "specifies", "if", "width", "of", "signal", "is", "locked", "or", "can", "be", "changed", "by", "...
python
train
Ex-Mente/auxi.0
auxi/modelling/process/materials/thermo.py
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1513-L1522
def Hfr(self, Hfr): """ Set the enthalpy flow rate of the stream to the specified value, and recalculate it's temperature. :param H: The new enthalpy flow rate value. [kWh/h] """ self._Hfr = Hfr self._T = self._calculate_T(Hfr)
[ "def", "Hfr", "(", "self", ",", "Hfr", ")", ":", "self", ".", "_Hfr", "=", "Hfr", "self", ".", "_T", "=", "self", ".", "_calculate_T", "(", "Hfr", ")" ]
Set the enthalpy flow rate of the stream to the specified value, and recalculate it's temperature. :param H: The new enthalpy flow rate value. [kWh/h]
[ "Set", "the", "enthalpy", "flow", "rate", "of", "the", "stream", "to", "the", "specified", "value", "and", "recalculate", "it", "s", "temperature", "." ]
python
valid
loli/medpy
medpy/metric/histogram.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L117-L126
def manhattan(h1, h2): # # 7 us @array, 31 us @list \w 100 bins r""" Equal to Minowski distance with :math:`p=1`. See also -------- minowski """ h1, h2 = __prepare_histogram(h1, h2) return scipy.sum(scipy.absolute(h1 - h2))
[ "def", "manhattan", "(", "h1", ",", "h2", ")", ":", "# # 7 us @array, 31 us @list \\w 100 bins", "h1", ",", "h2", "=", "__prepare_histogram", "(", "h1", ",", "h2", ")", "return", "scipy", ".", "sum", "(", "scipy", ".", "absolute", "(", "h1", "-", "h2", "...
r""" Equal to Minowski distance with :math:`p=1`. See also -------- minowski
[ "r", "Equal", "to", "Minowski", "distance", "with", ":", "math", ":", "p", "=", "1", ".", "See", "also", "--------", "minowski" ]
python
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L373-L384
def execute_lines(self, lines): """ Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands """ for line in lines.splitlines(): stripped_line = line.strip() if stripped_line.startswith('#'): continue self.write(line+os.linesep, flush=True) self.execute_command(line+"\n") self.flush()
[ "def", "execute_lines", "(", "self", ",", "lines", ")", ":", "for", "line", "in", "lines", ".", "splitlines", "(", ")", ":", "stripped_line", "=", "line", ".", "strip", "(", ")", "if", "stripped_line", ".", "startswith", "(", "'#'", ")", ":", "continue...
Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands
[ "Execute", "a", "set", "of", "lines", "as", "multiple", "command", "lines", ":", "multiple", "lines", "of", "text", "to", "be", "executed", "as", "single", "commands" ]
python
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L129-L134
def clear(self): """ Clear Screen """ widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1) widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2) widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3) widgets.StringWidget(self, ref="_w4_", text=" " * 20, x=1, y=4)
[ "def", "clear", "(", "self", ")", ":", "widgets", ".", "StringWidget", "(", "self", ",", "ref", "=", "\"_w1_\"", ",", "text", "=", "\" \"", "*", "20", ",", "x", "=", "1", ",", "y", "=", "1", ")", "widgets", ".", "StringWidget", "(", "self", ",", ...
Clear Screen
[ "Clear", "Screen" ]
python
train
bioasp/caspo
caspo/core/logicalnetwork.py
https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L754-L764
def formulas_iter(self): """ Iterates over all variable-clauses in the logical network Yields ------ tuple[str,frozenset[caspo.core.clause.Clause]] The next tuple of the form (variable, set of clauses) in the logical network. """ for var in it.ifilter(self.has_node, self.variables()): yield var, frozenset(self.predecessors(var))
[ "def", "formulas_iter", "(", "self", ")", ":", "for", "var", "in", "it", ".", "ifilter", "(", "self", ".", "has_node", ",", "self", ".", "variables", "(", ")", ")", ":", "yield", "var", ",", "frozenset", "(", "self", ".", "predecessors", "(", "var", ...
Iterates over all variable-clauses in the logical network Yields ------ tuple[str,frozenset[caspo.core.clause.Clause]] The next tuple of the form (variable, set of clauses) in the logical network.
[ "Iterates", "over", "all", "variable", "-", "clauses", "in", "the", "logical", "network" ]
python
train
BD2KGenomics/toil-scripts
src/toil_scripts/spladder_pipeline/spladder_pipeline.py
https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/spladder_pipeline/spladder_pipeline.py#L337-L376
def consolidate_output_tarballs(job, inputs, vcqc_id, spladder_id): """ Combine the contents of separate tarballs into one. :param JobFunctionWrappingJob job: passed by Toil automatically :param Namespace inputs: Stores input arguments (see main) :param str vcqc_id: FileStore ID of variant calling and QC tarball :param str spladder_id: FileStore ID of spladder tarball """ job.fileStore.logToMaster('Consolidating files and uploading: {}'.format(inputs.uuid)) work_dir = job.fileStore.getLocalTempDir() # Retrieve IDs uuid = inputs.uuid # Unpack IDs # Retrieve output file paths to consolidate vcqc_tar = job.fileStore.readGlobalFile(vcqc_id, os.path.join(work_dir, 'vcqc.tar.gz')) spladder_tar = job.fileStore.readGlobalFile(spladder_id, os.path.join(work_dir, 'spladder.tar.gz')) # I/O fname = uuid + '.tar.gz' if not inputs.improper_pair else 'IMPROPER_PAIR' + uuid + '.tar.gz' out_tar = os.path.join(work_dir, fname) # Consolidate separate tarballs into one with tarfile.open(os.path.join(work_dir, out_tar), 'w:gz') as f_out: for tar in [vcqc_tar, spladder_tar]: with tarfile.open(tar, 'r') as f_in: for tarinfo in f_in: with closing(f_in.extractfile(tarinfo)) as f_in_file: if tar == vcqc_tar: tarinfo.name = os.path.join(uuid, 'variants_and_qc', os.path.basename(tarinfo.name)) else: tarinfo.name = os.path.join(uuid, 'spladder', os.path.basename(tarinfo.name)) f_out.addfile(tarinfo, fileobj=f_in_file) # Move to output directory if inputs.output_dir: mkdir_p(inputs.output_dir) shutil.copy(out_tar, os.path.join(inputs.output_dir, os.path.basename(out_tar))) # Upload to S3 if inputs.output_s3_dir: out_id = job.fileStore.writeGlobalFile(out_tar) job.addChildJobFn(s3am_upload_job, file_id=out_id, s3_dir=inputs.output_s3_dir, file_name=fname, key_path=inputs.ssec, cores=inputs.cores)
[ "def", "consolidate_output_tarballs", "(", "job", ",", "inputs", ",", "vcqc_id", ",", "spladder_id", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Consolidating files and uploading: {}'", ".", "format", "(", "inputs", ".", "uuid", ")", ")", "work...
Combine the contents of separate tarballs into one. :param JobFunctionWrappingJob job: passed by Toil automatically :param Namespace inputs: Stores input arguments (see main) :param str vcqc_id: FileStore ID of variant calling and QC tarball :param str spladder_id: FileStore ID of spladder tarball
[ "Combine", "the", "contents", "of", "separate", "tarballs", "into", "one", "." ]
python
train
senaite/senaite.core
bika/lims/content/instrumentscheduledtask.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/instrumentscheduledtask.py#L110-L121
def getTaskTypes(self): """ Return the current list of task types """ types = [ ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')), ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')), ('Preventive', safe_unicode(_('Preventive')).encode('utf-8')), ('Repair', safe_unicode(_('Repair')).encode('utf-8')), ('Validation', safe_unicode(_('Validation')).encode('utf-8')), ] return DisplayList(types)
[ "def", "getTaskTypes", "(", "self", ")", ":", "types", "=", "[", "(", "'Calibration'", ",", "safe_unicode", "(", "_", "(", "'Calibration'", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ",", "(", "'Enhancement'", ",", "safe_unicode", "(", "_", "("...
Return the current list of task types
[ "Return", "the", "current", "list", "of", "task", "types" ]
python
train
mbedmicro/pyOCD
pyocd/flash/flash_builder.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash_builder.py#L767-L805
def _scan_pages_for_same(self, progress_cb=_stub_progress): """! @brief Read the full page data to determine if it is unchanged. When this function exits, the same flag will be set to either True or False for every page. In addition, sectors that need at least one page programmed will have the same flag set to False for all pages within that sector. """ progress = 0 # Read page data if unknown - after this page.same will be True or False unknown_pages = [page for page in self.page_list if page.same is None] if unknown_pages: self._enable_read_access() for page in unknown_pages: if page.cached_estimate_data is not None: data = page.cached_estimate_data offset = len(data) else: data = [] offset = 0 assert len(page.data) == page.size data.extend(self.flash.target.read_memory_block8(page.addr + offset, page.size - offset)) page.same = same(page.data, data) page.cached_estimate_data = None # This data isn't needed anymore. progress += page.get_verify_weight() # Update progress if self.sector_erase_weight > 0: progress_cb(float(progress) / float(self.sector_erase_weight)) # If we have to program any pages of a sector, then mark all pages of that sector # as needing to be programmed, since the sector will be erased. for sector in self.sector_list: if sector.are_any_pages_not_same(): sector.mark_all_pages_not_same() return progress
[ "def", "_scan_pages_for_same", "(", "self", ",", "progress_cb", "=", "_stub_progress", ")", ":", "progress", "=", "0", "# Read page data if unknown - after this page.same will be True or False", "unknown_pages", "=", "[", "page", "for", "page", "in", "self", ".", "page_...
! @brief Read the full page data to determine if it is unchanged. When this function exits, the same flag will be set to either True or False for every page. In addition, sectors that need at least one page programmed will have the same flag set to False for all pages within that sector.
[ "!" ]
python
train
pandas-dev/pandas
pandas/core/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L8609-L8743
def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False): """ Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__. """ inplace = validate_bool_kwarg(inplace, 'inplace') # align the cond to same shape as myself cond = com.apply_if_callable(cond, self) if isinstance(cond, NDFrame): cond, _ = cond.align(self, join='right', broadcast_axis=1) else: if not hasattr(cond, 'shape'): cond = np.asanyarray(cond) if cond.shape != self.shape: raise ValueError('Array conditional must be same shape as ' 'self') cond = self._constructor(cond, **self._construct_axes_dict()) # make sure we are boolean fill_value = bool(inplace) cond = cond.fillna(fill_value) msg = "Boolean array expected for the condition, not {dtype}" if not isinstance(cond, pd.DataFrame): # This is a single-dimensional object. if not is_bool_dtype(cond): raise ValueError(msg.format(dtype=cond.dtype)) elif not cond.empty: for dt in cond.dtypes: if not is_bool_dtype(dt): raise ValueError(msg.format(dtype=dt)) cond = -cond if inplace else cond # try to align with other try_quick = True if hasattr(other, 'align'): # align with me if other.ndim <= self.ndim: _, other = self.align(other, join='left', axis=axis, level=level, fill_value=np.nan) # if we are NOT aligned, raise as we cannot where index if (axis is None and not all(other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes))): raise InvalidIndexError # slice me out of the other else: raise NotImplementedError("cannot align with a higher " "dimensional NDFrame") if isinstance(other, np.ndarray): if other.shape != self.shape: if self.ndim == 1: icond = cond.values # GH 2745 / GH 4192 # treat like a scalar if len(other) == 1: other = np.array(other[0]) # GH 3235 # match True cond to other elif len(cond[icond]) == len(other): # try to not change dtype at first (if try_quick) if try_quick: try: new_other = com.values_from_object(self) new_other = new_other.copy() new_other[icond] = other other = new_other except Exception: try_quick = False # let's create a new (if we failed at the above # or not try_quick if not try_quick: dtype, fill_value = maybe_promote(other.dtype) new_other = np.empty(len(icond), dtype=dtype) new_other.fill(fill_value) maybe_upcast_putmask(new_other, icond, other) other = new_other else: raise ValueError('Length of replacements must equal ' 'series length') else: raise ValueError('other must be the same shape as self ' 'when an ndarray') # we are the same shape, so create an actual object for alignment else: other = self._constructor(other, **self._construct_axes_dict()) if axis is None: axis = 0 if self.ndim == getattr(other, 'ndim', 0): align = True else: align = (self._get_axis_number(axis) == 1) block_axis = self._get_block_manager_axis(axis) if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager self._check_inplace_setting(other) new_data = self._data.putmask(mask=cond, new=other, align=align, inplace=True, axis=block_axis, transpose=self._AXIS_REVERSED) self._update_inplace(new_data) else: new_data = self._data.where(other=other, cond=cond, align=align, errors=errors, try_cast=try_cast, axis=block_axis, transpose=self._AXIS_REVERSED) return self._constructor(new_data).__finalize__(self)
[ "def", "_where", "(", "self", ",", "cond", ",", "other", "=", "np", ".", "nan", ",", "inplace", "=", "False", ",", "axis", "=", "None", ",", "level", "=", "None", ",", "errors", "=", "'raise'", ",", "try_cast", "=", "False", ")", ":", "inplace", ...
Equivalent to public method `where`, except that `other` is not applied as a function even if callable. Used in __setitem__.
[ "Equivalent", "to", "public", "method", "where", "except", "that", "other", "is", "not", "applied", "as", "a", "function", "even", "if", "callable", ".", "Used", "in", "__setitem__", "." ]
python
train
onjin/runenv
runenv/__init__.py
https://github.com/onjin/runenv/blob/1a1d31bc2d20a48e3c251d8e490bbad485b09e1c/runenv/__init__.py#L17-L41
def run(*args): """Load given `envfile` and run `command` with `params`""" if not args: args = sys.argv[1:] if len(args) < 2: print('Usage: runenv <envfile> <command> <params>') sys.exit(0) os.environ.update(create_env(args[0])) os.environ['_RUNENV_WRAPPED'] = '1' runnable_path = args[1] if not runnable_path.startswith(('/', '.')): runnable_path = spawn.find_executable(runnable_path) try: if not(stat.S_IXUSR & os.stat(runnable_path)[stat.ST_MODE]): print('File `%s is not executable' % runnable_path) sys.exit(1) return subprocess.check_call( args[1:], env=os.environ ) except subprocess.CalledProcessError as e: return e.returncode
[ "def", "run", "(", "*", "args", ")", ":", "if", "not", "args", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "len", "(", "args", ")", "<", "2", ":", "print", "(", "'Usage: runenv <envfile> <command> <params>'", ")", "sys", ".", "e...
Load given `envfile` and run `command` with `params`
[ "Load", "given", "envfile", "and", "run", "command", "with", "params" ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py#L88-L100
def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = ctypes.c_voidp(0) else: if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']: data = data.copy('C') data_ = data size = data_.nbytes data = data_.ctypes.data res = _lib.glBufferData(target, size, data, usage)
[ "def", "glBufferData", "(", "target", ",", "data", ",", "usage", ")", ":", "if", "isinstance", "(", "data", ",", "int", ")", ":", "size", "=", "data", "data", "=", "ctypes", ".", "c_voidp", "(", "0", ")", "else", ":", "if", "not", "data", ".", "f...
Data can be numpy array or the size of data to allocate.
[ "Data", "can", "be", "numpy", "array", "or", "the", "size", "of", "data", "to", "allocate", "." ]
python
train
pandas-dev/pandas
pandas/core/indexes/base.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1402-L1420
def _validate_index_level(self, level): """ Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex. """ if isinstance(level, int): if level < 0 and level != -1: raise IndexError("Too many levels: Index has only 1 level," " %d is not a valid level number" % (level, )) elif level > 0: raise IndexError("Too many levels:" " Index has only 1 level, not %d" % (level + 1)) elif level != self.name: raise KeyError('Level %s must be same as name (%s)' % (level, self.name))
[ "def", "_validate_index_level", "(", "self", ",", "level", ")", ":", "if", "isinstance", "(", "level", ",", "int", ")", ":", "if", "level", "<", "0", "and", "level", "!=", "-", "1", ":", "raise", "IndexError", "(", "\"Too many levels: Index has only 1 level,...
Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex.
[ "Validate", "index", "level", "." ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1543-L1547
def help_center_article_translation_show(self, article_id, locale, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/translations#show-translation" api_path = "/api/v2/help_center/articles/{article_id}/translations/{locale}.json" api_path = api_path.format(article_id=article_id, locale=locale) return self.call(api_path, **kwargs)
[ "def", "help_center_article_translation_show", "(", "self", ",", "article_id", ",", "locale", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/articles/{article_id}/translations/{locale}.json\"", "api_path", "=", "api_path", ".", "format", "(", ...
https://developer.zendesk.com/rest_api/docs/help_center/translations#show-translation
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "help_center", "/", "translations#show", "-", "translation" ]
python
train
sffjunkie/astral
src/astral.py
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2213-L2252
def time_at_elevation_utc(self, elevation, direction, date, latitude, longitude, observer_elevation=0): """Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date. Note: This method uses positive elevations for those above the horizon. :param elevation: Elevation in degrees above the horizon to calculate for. :type elevation: float :param direction: Determines whether the calculated time is for the sun rising or setting. Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising. :type direction: int :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float :param longitude: Longitude - Eastern longitudes should be positive :type longitude: float :param observer_elevation: Elevation in metres to calculate time at elevation for :type observer_elevation: int :return: The UTC date and time at which the sun is at the required elevation. :rtype: :class:`~datetime.datetime` """ if elevation > 90.0: elevation = 180.0 - elevation direction = SUN_SETTING depression = 90 - elevation try: return self._calc_time(depression, direction, date, latitude, longitude, observer_elevation) except ValueError as exc: if exc.args[0] == "math domain error": raise AstralError( ("Sun never reaches an elevation of %d degrees" "at this location.") % elevation ) else: raise
[ "def", "time_at_elevation_utc", "(", "self", ",", "elevation", ",", "direction", ",", "date", ",", "latitude", ",", "longitude", ",", "observer_elevation", "=", "0", ")", ":", "if", "elevation", ">", "90.0", ":", "elevation", "=", "180.0", "-", "elevation", ...
Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date. Note: This method uses positive elevations for those above the horizon. :param elevation: Elevation in degrees above the horizon to calculate for. :type elevation: float :param direction: Determines whether the calculated time is for the sun rising or setting. Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising. :type direction: int :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float :param longitude: Longitude - Eastern longitudes should be positive :type longitude: float :param observer_elevation: Elevation in metres to calculate time at elevation for :type observer_elevation: int :return: The UTC date and time at which the sun is at the required elevation. :rtype: :class:`~datetime.datetime`
[ "Calculate", "the", "time", "in", "the", "UTC", "timezone", "when", "the", "sun", "is", "at", "the", "specified", "elevation", "on", "the", "specified", "date", "." ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/bindings/dxfile_functions.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxfile_functions.py#L621-L708
def download_folder(project, destdir, folder="/", overwrite=False, chunksize=dxfile.DEFAULT_BUFFER_SIZE, show_progress=False, **kwargs): ''' :param project: Project ID to use as context for this download. :type project: string :param destdir: Local destination location :type destdir: string :param folder: Path to the remote folder to download :type folder: string :param overwrite: Overwrite existing files :type overwrite: boolean Downloads the contents of the remote *folder* of the *project* into the local directory specified by *destdir*. Example:: download_folder("project-xxxx", "/home/jsmith/input", folder="/input") ''' def ensure_local_dir(d): if not os.path.isdir(d): if os.path.exists(d): raise DXFileError("Destination location '{}' already exists and is not a directory".format(d)) logger.debug("Creating destination directory: '%s'", d) os.makedirs(d) def compose_local_dir(d, remote_folder, remote_subfolder): suffix = remote_subfolder[1:] if remote_folder == "/" else remote_subfolder[len(remote_folder) + 1:] if os.sep != '/': suffix = suffix.replace('/', os.sep) return os.path.join(d, suffix) if suffix != "" else d normalized_folder = folder.strip() if normalized_folder != "/" and normalized_folder.endswith("/"): normalized_folder = normalized_folder[:-1] if normalized_folder == "": raise DXFileError("Invalid remote folder name: '{}'".format(folder)) normalized_dest_dir = os.path.normpath(destdir).strip() if normalized_dest_dir == "": raise DXFileError("Invalid destination directory name: '{}'".format(destdir)) # Creating target directory tree remote_folders = list(list_subfolders(project, normalized_folder, recurse=True)) if len(remote_folders) <= 0: raise DXFileError("Remote folder '{}' not found".format(normalized_folder)) remote_folders.sort() for remote_subfolder in remote_folders: ensure_local_dir(compose_local_dir(normalized_dest_dir, normalized_folder, remote_subfolder)) # Downloading files describe_input = dict(fields=dict(folder=True, name=True, id=True, parts=True, size=True, drive=True, md5=True)) # A generator that returns the files one by one. We don't want to materialize it, because # there could be many files here. files_gen = dxpy.search.find_data_objects(classname='file', state='closed', project=project, folder=normalized_folder, recurse=True, describe=describe_input) if files_gen is None: # In python 3, the generator can be None, and iterating on it # will cause an error. return # Now it is safe, in both python 2 and 3, to iterate on the generator for remote_file in files_gen: local_filename = os.path.join(compose_local_dir(normalized_dest_dir, normalized_folder, remote_file['describe']['folder']), remote_file['describe']['name']) if os.path.exists(local_filename) and not overwrite: raise DXFileError( "Destination file '{}' already exists but no overwrite option is provided".format(local_filename) ) logger.debug("Downloading '%s/%s' remote file to '%s' location", ("" if remote_file['describe']['folder'] == "/" else remote_file['describe']['folder']), remote_file['describe']['name'], local_filename) download_dxfile(remote_file['describe']['id'], local_filename, chunksize=chunksize, project=project, show_progress=show_progress, describe_output=remote_file['describe'], **kwargs)
[ "def", "download_folder", "(", "project", ",", "destdir", ",", "folder", "=", "\"/\"", ",", "overwrite", "=", "False", ",", "chunksize", "=", "dxfile", ".", "DEFAULT_BUFFER_SIZE", ",", "show_progress", "=", "False", ",", "*", "*", "kwargs", ")", ":", "def"...
:param project: Project ID to use as context for this download. :type project: string :param destdir: Local destination location :type destdir: string :param folder: Path to the remote folder to download :type folder: string :param overwrite: Overwrite existing files :type overwrite: boolean Downloads the contents of the remote *folder* of the *project* into the local directory specified by *destdir*. Example:: download_folder("project-xxxx", "/home/jsmith/input", folder="/input")
[ ":", "param", "project", ":", "Project", "ID", "to", "use", "as", "context", "for", "this", "download", ".", ":", "type", "project", ":", "string", ":", "param", "destdir", ":", "Local", "destination", "location", ":", "type", "destdir", ":", "string", "...
python
train
bokeh/bokeh
bokeh/io/notebook.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L433-L501
def show_app(app, state, notebook_url, port=0, **kw): ''' Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook server that is running the embedded app. If ``notebook_url`` is a string, the value string is parsed to construct the origin and full server URLs. If notebook_url is a callable, it must accept one parameter, which will be the server port, or None. If passed a port, the callable must generate the server URL, otherwise if passed None, it must generate the origin URL for the server. port (int) : A port for the embedded server will listen on. By default the port is 0, which results in the server listening on a random dynamic port. Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1) Returns: None ''' logging.basicConfig() from tornado.ioloop import IOLoop from ..server.server import Server loop = IOLoop.current() if callable(notebook_url): origin = notebook_url(None) else: origin = _origin_url(notebook_url) server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw) server_id = uuid4().hex curstate().uuid_to_server[server_id] = server server.start() if callable(notebook_url): url = notebook_url(server.port) else: url = _server_url(notebook_url, server.port) logging.debug("Server URL is %s" % url) logging.debug("Origin URL is %s" % origin) from ..embed import server_document script = server_document(url, resources=None) publish_display_data({ HTML_MIME_TYPE: script, EXEC_MIME_TYPE: "" }, metadata={ EXEC_MIME_TYPE: {"server_id": server_id} })
[ "def", "show_app", "(", "app", ",", "state", ",", "notebook_url", ",", "port", "=", "0", ",", "*", "*", "kw", ")", ":", "logging", ".", "basicConfig", "(", ")", "from", "tornado", ".", "ioloop", "import", "IOLoop", "from", ".", ".", "server", ".", ...
Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook server that is running the embedded app. If ``notebook_url`` is a string, the value string is parsed to construct the origin and full server URLs. If notebook_url is a callable, it must accept one parameter, which will be the server port, or None. If passed a port, the callable must generate the server URL, otherwise if passed None, it must generate the origin URL for the server. port (int) : A port for the embedded server will listen on. By default the port is 0, which results in the server listening on a random dynamic port. Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1) Returns: None
[ "Embed", "a", "Bokeh", "server", "application", "in", "a", "Jupyter", "Notebook", "output", "cell", "." ]
python
train
Karaage-Cluster/python-tldap
tldap/fields.py
https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/fields.py#L316-L326
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, datetime.date) assert not isinstance(value, datetime.datetime) try: value = value - datetime.date(year=1970, month=1, day=1) except OverflowError: raise tldap.exceptions.ValidationError("is too big a date") return str(value.days).encode("utf_8")
[ "def", "value_to_db", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", "assert", "not", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", "try", ":", "value", "=", "value", "...
Returns field's single value prepared for saving into a database.
[ "Returns", "field", "s", "single", "value", "prepared", "for", "saving", "into", "a", "database", "." ]
python
train
pyout/pyout
pyout/elements.py
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/elements.py#L241-L265
def validate(style): """Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid. """ try: import jsonschema except ImportError: return try: jsonschema.validate(style, schema) except jsonschema.ValidationError as exc: new_exc = StyleValidationError(exc) # Don't dump the original jsonschema exception because it is already # included in the StyleValidationError's message. new_exc.__cause__ = None raise new_exc
[ "def", "validate", "(", "style", ")", ":", "try", ":", "import", "jsonschema", "except", "ImportError", ":", "return", "try", ":", "jsonschema", ".", "validate", "(", "style", ",", "schema", ")", "except", "jsonschema", ".", "ValidationError", "as", "exc", ...
Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid.
[ "Check", "style", "against", "pyout", ".", "styling", ".", "schema", "." ]
python
train
projectatomic/atomic-reactor
atomic_reactor/plugins/input_path.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/input_path.py#L32-L47
def run(self): """ get json with build config from path """ path = self.path or CONTAINER_BUILD_JSON_PATH try: with open(path, 'r') as build_cfg_fd: build_cfg_json = json.load(build_cfg_fd) except ValueError: self.log.error("couldn't decode json from file '%s'", path) return None except IOError: self.log.error("couldn't read json from file '%s'", path) return None else: return self.substitute_configuration(build_cfg_json)
[ "def", "run", "(", "self", ")", ":", "path", "=", "self", ".", "path", "or", "CONTAINER_BUILD_JSON_PATH", "try", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "build_cfg_fd", ":", "build_cfg_json", "=", "json", ".", "load", "(", "build_cfg_fd"...
get json with build config from path
[ "get", "json", "with", "build", "config", "from", "path" ]
python
train
rigetti/quantumflow
quantumflow/states.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L329-L345
def random_density(qubits: Union[int, Qubits]) -> Density: """ Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) https://arxiv.org/abs/quant-ph/0012101 """ N, qubits = qubits_count_tuple(qubits) size = (2**N, 2**N) ginibre_ensemble = (np.random.normal(size=size) + 1j * np.random.normal(size=size)) / np.sqrt(2.0) matrix = ginibre_ensemble @ np.transpose(np.conjugate(ginibre_ensemble)) matrix /= np.trace(matrix) return Density(matrix, qubits=qubits)
[ "def", "random_density", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Density", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "size", "=", "(", "2", "**", "N", ",", "2", "**", "N", ")", "ginibre...
Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) https://arxiv.org/abs/quant-ph/0012101
[ "Returns", ":", "A", "randomly", "sampled", "Density", "from", "the", "Hilbert–Schmidt", "ensemble", "of", "quantum", "states" ]
python
train
DataBiosphere/dsub
dsub/providers/google_v2_operations.py
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L167-L179
def get_last_update(op): """Return the most recent timestamp in the operation.""" last_update = get_end_time(op) if not last_update: last_event = get_last_event(op) if last_event: last_update = last_event['timestamp'] if not last_update: last_update = get_create_time(op) return last_update
[ "def", "get_last_update", "(", "op", ")", ":", "last_update", "=", "get_end_time", "(", "op", ")", "if", "not", "last_update", ":", "last_event", "=", "get_last_event", "(", "op", ")", "if", "last_event", ":", "last_update", "=", "last_event", "[", "'timesta...
Return the most recent timestamp in the operation.
[ "Return", "the", "most", "recent", "timestamp", "in", "the", "operation", "." ]
python
valid
log2timeline/plaso
plaso/engine/profilers.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/profilers.py#L125-L138
def StopTiming(self, profile_name): """Stops timing CPU time. Args: profile_name (str): name of the profile to sample. """ measurements = self._profile_measurements.get(profile_name) if measurements: measurements.SampleStop() sample = '{0:f}\t{1:s}\t{2:f}\n'.format( measurements.start_sample_time, profile_name, measurements.total_cpu_time) self._WritesString(sample)
[ "def", "StopTiming", "(", "self", ",", "profile_name", ")", ":", "measurements", "=", "self", ".", "_profile_measurements", ".", "get", "(", "profile_name", ")", "if", "measurements", ":", "measurements", ".", "SampleStop", "(", ")", "sample", "=", "'{0:f}\\t{...
Stops timing CPU time. Args: profile_name (str): name of the profile to sample.
[ "Stops", "timing", "CPU", "time", "." ]
python
train
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/display.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L76-L121
def display_replica_imbalance(cluster_topologies): """Display replica replication-group distribution imbalance statistics. :param cluster_topologies: A dictionary mapping a string name to a ClusterTopology object. """ assert cluster_topologies rg_ids = list(next(six.itervalues(cluster_topologies)).rgs.keys()) assert all( set(rg_ids) == set(cluster_topology.rgs.keys()) for cluster_topology in six.itervalues(cluster_topologies) ) rg_imbalances = [ stats.get_replication_group_imbalance_stats( list(cluster_topology.rgs.values()), list(cluster_topology.partitions.values()), ) for cluster_topology in six.itervalues(cluster_topologies) ] _display_table_title_multicolumn( 'Extra Replica Count', 'Replication Group', rg_ids, list(cluster_topologies.keys()), [ [erc[rg_id] for rg_id in rg_ids] for _, erc in rg_imbalances ], ) for name, imbalance in zip( six.iterkeys(cluster_topologies), (imbalance for imbalance, _ in rg_imbalances) ): print( '\n' '{name}' 'Total extra replica count: {imbalance}' .format( name='' if len(cluster_topologies) == 1 else name + '\n', imbalance=imbalance, ) )
[ "def", "display_replica_imbalance", "(", "cluster_topologies", ")", ":", "assert", "cluster_topologies", "rg_ids", "=", "list", "(", "next", "(", "six", ".", "itervalues", "(", "cluster_topologies", ")", ")", ".", "rgs", ".", "keys", "(", ")", ")", "assert", ...
Display replica replication-group distribution imbalance statistics. :param cluster_topologies: A dictionary mapping a string name to a ClusterTopology object.
[ "Display", "replica", "replication", "-", "group", "distribution", "imbalance", "statistics", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py#L109-L123
def ntp_authentication_key_encryption_type_md5_type_md5(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp") authentication_key = ET.SubElement(ntp, "authentication-key") keyid_key = ET.SubElement(authentication_key, "keyid") keyid_key.text = kwargs.pop('keyid') encryption_type = ET.SubElement(authentication_key, "encryption-type") md5_type = ET.SubElement(encryption_type, "md5-type") md5 = ET.SubElement(md5_type, "md5") md5.text = kwargs.pop('md5') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "ntp_authentication_key_encryption_type_md5_type_md5", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ntp", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ntp\"", ",", "xmlns", "=", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
NASA-AMMOS/AIT-Core
ait/core/seq.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L150-L166
def printText (self, stream=None): """Prints a text representation of this sequence to the given stream or standard output. """ if stream is None: stream = sys.stdout stream.write('# seqid : %u\n' % self.seqid ) stream.write('# version : %u\n' % self.version ) stream.write('# crc32 : 0x%04x\n' % self.crc32 ) stream.write('# ncmds : %u\n' % len(self.commands) ) stream.write('# duration: %.3fs\n' % self.duration ) stream.write('\n') for line in self.lines: stream.write( str(line) ) stream.write('\n')
[ "def", "printText", "(", "self", ",", "stream", "=", "None", ")", ":", "if", "stream", "is", "None", ":", "stream", "=", "sys", ".", "stdout", "stream", ".", "write", "(", "'# seqid : %u\\n'", "%", "self", ".", "seqid", ")", "stream", ".", "write", ...
Prints a text representation of this sequence to the given stream or standard output.
[ "Prints", "a", "text", "representation", "of", "this", "sequence", "to", "the", "given", "stream", "or", "standard", "output", "." ]
python
train
apache/incubator-heron
third_party/python/cpplint/cpplint.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L757-L764
def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s)
[ "def", "Match", "(", "pattern", ",", "s", ")", ":", "# The regexp compilation caching is inlined in both Match and Search for", "# performance reasons; factoring it out into a separate function turns out", "# to be noticeably expensive.", "if", "pattern", "not", "in", "_regexp_compile_...
Matches the string with the pattern, caching the compiled regexp.
[ "Matches", "the", "string", "with", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
python
valid
liampauling/betfair
betfairlightweight/streaming/betfairstream.py
https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L176-L184
def _create_socket(self): """Creates ssl socket, connects to stream api and sets timeout. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = ssl.wrap_socket(s) s.connect((self.host, self.__port)) s.settimeout(self.timeout) return s
[ "def", "_create_socket", "(", "self", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "s", "=", "ssl", ".", "wrap_socket", "(", "s", ")", "s", ".", "connect", "(", "(", "self", "."...
Creates ssl socket, connects to stream api and sets timeout.
[ "Creates", "ssl", "socket", "connects", "to", "stream", "api", "and", "sets", "timeout", "." ]
python
train
HewlettPackard/python-hpOneView
hpOneView/resources/networking/logical_interconnects.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L423-L435
def create_forwarding_information_base(self, timeout=-1): """ Generates the forwarding information base dump file for a logical interconnect. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Interconnect Forwarding Information Base DataInfo. """ uri = "{}{}".format(self.data["uri"], self.FORWARDING_INFORMATION_PATH) return self._helper.do_post(uri, None, timeout, None)
[ "def", "create_forwarding_information_base", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ",", "self", ".", "FORWARDING_INFORMATION_PATH", ")", "return", "self", ...
Generates the forwarding information base dump file for a logical interconnect. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Interconnect Forwarding Information Base DataInfo.
[ "Generates", "the", "forwarding", "information", "base", "dump", "file", "for", "a", "logical", "interconnect", "." ]
python
train
gabstopper/smc-python
smc/base/util.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L71-L103
def element_resolver(elements, do_raise=True): """ Element resolver takes either a single class instance or a list of elements to resolve the href. It does not assume a specific interface, instead if it's a class, it just needs an 'href' attribute that should hold the http url for the resource. If a list is provided, a list is returned. If you want to suppress raising an exception and just return None or [] instead, set do_raise=False. :raises ElementNotFound: if this is of type Element, ElementLocator will attempt to retrieve meta if it doesn't already exist but the element was not found. """ if isinstance(elements, list): e = [] for element in elements: try: e.append(element.href) except AttributeError: e.append(element) except smc.api.exceptions.ElementNotFound: if do_raise: raise return e try: return elements.href except AttributeError: return elements except smc.api.exceptions.ElementNotFound: if do_raise: raise
[ "def", "element_resolver", "(", "elements", ",", "do_raise", "=", "True", ")", ":", "if", "isinstance", "(", "elements", ",", "list", ")", ":", "e", "=", "[", "]", "for", "element", "in", "elements", ":", "try", ":", "e", ".", "append", "(", "element...
Element resolver takes either a single class instance or a list of elements to resolve the href. It does not assume a specific interface, instead if it's a class, it just needs an 'href' attribute that should hold the http url for the resource. If a list is provided, a list is returned. If you want to suppress raising an exception and just return None or [] instead, set do_raise=False. :raises ElementNotFound: if this is of type Element, ElementLocator will attempt to retrieve meta if it doesn't already exist but the element was not found.
[ "Element", "resolver", "takes", "either", "a", "single", "class", "instance", "or", "a", "list", "of", "elements", "to", "resolve", "the", "href", ".", "It", "does", "not", "assume", "a", "specific", "interface", "instead", "if", "it", "s", "a", "class", ...
python
train
mitsei/dlkit
dlkit/records/assessment/mecqbank/mecqbank_base_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/mecqbank/mecqbank_base_records.py#L449-L456
def _init_metadata(self): """stub""" SimpleDifficultyItemFormRecord._init_metadata(self) SourceItemFormRecord._init_metadata(self) PDFPreviewFormRecord._init_metadata(self) PublishedFormRecord._init_metadata(self) ProvenanceFormRecord._init_metadata(self) super(MecQBankBaseMixin, self)._init_metadata()
[ "def", "_init_metadata", "(", "self", ")", ":", "SimpleDifficultyItemFormRecord", ".", "_init_metadata", "(", "self", ")", "SourceItemFormRecord", ".", "_init_metadata", "(", "self", ")", "PDFPreviewFormRecord", ".", "_init_metadata", "(", "self", ")", "PublishedFormR...
stub
[ "stub" ]
python
train
kellerza/pysma
pysma/__init__.py
https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L209-L225
def new_session(self): """Establish a new session.""" body = yield from self._fetch_json(URL_LOGIN, self._new_session_data) self.sma_sid = jmespath.search('result.sid', body) if self.sma_sid: return True msg = 'Could not start session, %s, got {}'.format(body) if body.get('err'): if body.get('err') == 503: _LOGGER.error("Max amount of sessions reached") else: _LOGGER.error(msg, body.get('err')) else: _LOGGER.error(msg, "Session ID expected [result.sid]") return False
[ "def", "new_session", "(", "self", ")", ":", "body", "=", "yield", "from", "self", ".", "_fetch_json", "(", "URL_LOGIN", ",", "self", ".", "_new_session_data", ")", "self", ".", "sma_sid", "=", "jmespath", ".", "search", "(", "'result.sid'", ",", "body", ...
Establish a new session.
[ "Establish", "a", "new", "session", "." ]
python
train
saltstack/salt
salt/modules/mdadm_raid.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mdadm_raid.py#L174-L259
def create(name, level, devices, metadata='default', test_mode=False, **kwargs): ''' Create a RAID device. .. versionchanged:: 2014.7.0 .. warning:: Use with CAUTION, as this function can be very destructive if not used properly! CLI Examples: .. code-block:: bash salt '*' raid.create /dev/md0 level=1 chunk=256 devices="['/dev/xvdd', '/dev/xvde']" test_mode=True .. note:: Adding ``test_mode=True`` as an argument will print out the mdadm command that would have been run. name The name of the array to create. level The RAID level to use when creating the raid. devices A list of devices used to build the array. metadata Version of metadata to use when creating the array. kwargs Optional arguments to be passed to mdadm. returns test_mode=True: Prints out the full command. test_mode=False (Default): Executes command on remote the host(s) and Prints out the mdadm output. .. note:: It takes time to create a RAID array. You can check the progress in "resync_status:" field of the results from the following command: .. code-block:: bash salt '*' raid.detail /dev/md0 For more info, read the ``mdadm(8)`` manpage ''' opts = [] raid_devices = len(devices) for key in kwargs: if not key.startswith('__'): opts.append('--{0}'.format(key)) if kwargs[key] is not True: opts.append(six.text_type(kwargs[key])) if key == 'spare-devices': raid_devices -= int(kwargs[key]) cmd = ['mdadm', '-C', name, '-R', '-v', '-l', six.text_type(level), ] + opts + [ '-e', six.text_type(metadata), '-n', six.text_type(raid_devices), ] + devices cmd_str = ' '.join(cmd) if test_mode is True: return cmd_str elif test_mode is False: return __salt__['cmd.run'](cmd, python_shell=False)
[ "def", "create", "(", "name", ",", "level", ",", "devices", ",", "metadata", "=", "'default'", ",", "test_mode", "=", "False", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "[", "]", "raid_devices", "=", "len", "(", "devices", ")", "for", "key", ...
Create a RAID device. .. versionchanged:: 2014.7.0 .. warning:: Use with CAUTION, as this function can be very destructive if not used properly! CLI Examples: .. code-block:: bash salt '*' raid.create /dev/md0 level=1 chunk=256 devices="['/dev/xvdd', '/dev/xvde']" test_mode=True .. note:: Adding ``test_mode=True`` as an argument will print out the mdadm command that would have been run. name The name of the array to create. level The RAID level to use when creating the raid. devices A list of devices used to build the array. metadata Version of metadata to use when creating the array. kwargs Optional arguments to be passed to mdadm. returns test_mode=True: Prints out the full command. test_mode=False (Default): Executes command on remote the host(s) and Prints out the mdadm output. .. note:: It takes time to create a RAID array. You can check the progress in "resync_status:" field of the results from the following command: .. code-block:: bash salt '*' raid.detail /dev/md0 For more info, read the ``mdadm(8)`` manpage
[ "Create", "a", "RAID", "device", "." ]
python
train
threeML/astromodels
astromodels/sources/particle_source.py
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/sources/particle_source.py#L62-L68
def get_flux(self, energies): """Get the total flux of this particle source at the given energies (summed over the components)""" results = [component.shape(energies) for component in self.components.values()] return numpy.sum(results, 0)
[ "def", "get_flux", "(", "self", ",", "energies", ")", ":", "results", "=", "[", "component", ".", "shape", "(", "energies", ")", "for", "component", "in", "self", ".", "components", ".", "values", "(", ")", "]", "return", "numpy", ".", "sum", "(", "r...
Get the total flux of this particle source at the given energies (summed over the components)
[ "Get", "the", "total", "flux", "of", "this", "particle", "source", "at", "the", "given", "energies", "(", "summed", "over", "the", "components", ")" ]
python
train
rbuffat/pyepw
pyepw/epw.py
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L4612-L4634
def holiday_day(self, value=None): """Corresponds to IDD Field `holiday_day` Args: value (str): value for IDD Field `holiday_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value """ if value is not None: try: value = str(value) except ValueError: raise ValueError('value {} need to be of type str ' 'for field `holiday_day`'.format(value)) if ',' in value: raise ValueError('value should not contain a comma ' 'for field `holiday_day`') self._holiday_day = value
[ "def", "holiday_day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str ...
Corresponds to IDD Field `holiday_day` Args: value (str): value for IDD Field `holiday_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "holiday_day" ]
python
train
Qiskit/qiskit-terra
qiskit/quantum_info/operators/predicates.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L74-L83
def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if an array is a diagonal matrix""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(mat) if mat.ndim != 2: return False return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=atol)
[ "def", "is_diagonal_matrix", "(", "mat", ",", "rtol", "=", "RTOL_DEFAULT", ",", "atol", "=", "ATOL_DEFAULT", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "ATOL_DEFAULT", "if", "rtol", "is", "None", ":", "rtol", "=", "RTOL_DEFAULT", "mat", "=",...
Test if an array is a diagonal matrix
[ "Test", "if", "an", "array", "is", "a", "diagonal", "matrix" ]
python
test
satori-ng/hooker
hooker/hook_list.py
https://github.com/satori-ng/hooker/blob/8ef1fffe1537f06313799d1e5e6f7acc4ab405b4/hooker/hook_list.py#L103-L124
def isloaded(self, name): """Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded """ if name is None: return True if isinstance(name, str): return (name in [x.__module__ for x in self]) if isinstance(name, Iterable): return set(name).issubset([x.__module__ for x in self]) return False
[ "def", "isloaded", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "return", "True", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "(", "name", "in", "[", "x", ".", "__module__", "for", "x", "in", "self", "...
Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True -- Loaded False -- Not Loaded
[ "Checks", "if", "given", "hook", "module", "has", "been", "loaded" ]
python
train
Azure/azure-cosmos-python
samples/IndexManagement/Program.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/samples/IndexManagement/Program.py#L171-L231
def ExplicitlyExcludeFromIndex(client, database_id): """ The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added. There may be scenarios where you want to exclude a specific doc from the index even though all other documents are being indexed automatically. This method demonstrates how to use an index directive to control this """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) # Create a collection with default index policy (i.e. automatic = true) created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID}) print(created_Container) print("\n" + "-" * 25 + "\n1. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) # Create a document and query on it immediately. # Will work as automatic indexing is still True collection_link = GetContainerLink(database_id, COLLECTION_ID) doc = client.CreateItem(collection_link, { "id" : "doc1", "orderId" : "order1" }) print("\n" + "-" * 25 + "Document doc1 created with order1" + "-" * 25) print(doc) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order1" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) # Now, create a document but this time explictly exclude it from the collection using IndexingDirective # Then query for that document # Shoud NOT find it, because we excluded it from the index # BUT, the document is there and doing a ReadDocument by Id will prove it doc2 = client.CreateItem(collection_link, { "id" : "doc2", "orderId" : "order2" }, {'indexingDirective' : documents.IndexingDirective.Exclude}) print("\n" + "-" * 25 + "Document doc2 created with order2" + "-" * 25) print(doc2) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order2" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) docRead = client.ReadItem(GetDocumentLink(database_id, COLLECTION_ID, "doc2")) print("Document read by ID: \n", docRead["id"]) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
[ "def", "ExplicitlyExcludeFromIndex", "(", "client", ",", "database_id", ")", ":", "try", ":", "DeleteContainerIfExists", "(", "client", ",", "database_id", ",", "COLLECTION_ID", ")", "database_link", "=", "GetDatabaseLink", "(", "database_id", ")", "# collections = Qu...
The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added. There may be scenarios where you want to exclude a specific doc from the index even though all other documents are being indexed automatically. This method demonstrates how to use an index directive to control this
[ "The", "default", "index", "policy", "on", "a", "DocumentContainer", "will", "AUTOMATICALLY", "index", "ALL", "documents", "added", ".", "There", "may", "be", "scenarios", "where", "you", "want", "to", "exclude", "a", "specific", "doc", "from", "the", "index",...
python
train
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L263-L280
def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True): """ Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on the grid :param cmap: colormap name :param alpha: color alpha :param vmin: minimum value for the colormap :param vmax: maximum value for the colormap :param levels: number of levels for the colormap :param colormap_scale: colormap scale :param show_colorbar: show the colorbar in the UI """ from geoplotlib.layers import GridLayer _global_config.layers.append( GridLayer(lon_edges, lat_edges, values, cmap, alpha, vmin, vmax, levels, colormap_scale, show_colorbar))
[ "def", "grid", "(", "lon_edges", ",", "lat_edges", ",", "values", ",", "cmap", ",", "alpha", "=", "255", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "levels", "=", "10", ",", "colormap_scale", "=", "'lin'", ",", "show_colorbar", "=", "Tr...
Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on the grid :param cmap: colormap name :param alpha: color alpha :param vmin: minimum value for the colormap :param vmax: maximum value for the colormap :param levels: number of levels for the colormap :param colormap_scale: colormap scale :param show_colorbar: show the colorbar in the UI
[ "Values", "on", "a", "uniform", "grid", ":", "param", "lon_edges", ":", "longitude", "edges", ":", "param", "lat_edges", ":", "latitude", "edges", ":", "param", "values", ":", "matrix", "representing", "values", "on", "the", "grid", ":", "param", "cmap", "...
python
train
ArduPilot/MAVProxy
MAVProxy/modules/lib/mp_module.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_module.py#L170-L176
def speed_convert_units(self, val_ms): '''return a speed in configured units''' if self.settings.speed_unit == 'knots': return val_ms * 1.94384 elif self.settings.speed_unit == 'mph': return val_ms * 2.23694 return val_ms
[ "def", "speed_convert_units", "(", "self", ",", "val_ms", ")", ":", "if", "self", ".", "settings", ".", "speed_unit", "==", "'knots'", ":", "return", "val_ms", "*", "1.94384", "elif", "self", ".", "settings", ".", "speed_unit", "==", "'mph'", ":", "return"...
return a speed in configured units
[ "return", "a", "speed", "in", "configured", "units" ]
python
train
tensorflow/probability
tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L246-L368
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an Estimator. Arguments: features: The input features for the Estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionary. config: The RunConfig, unused here. Returns: EstimatorSpec: A tf.estimator.EstimatorSpec instance. """ del labels, config # Set up the model's learnable parameters. logit_concentration = tf.compat.v1.get_variable( "logit_concentration", shape=[1, params["num_topics"]], initializer=tf.compat.v1.initializers.constant( _softplus_inverse(params["prior_initial_value"]))) concentration = _clip_dirichlet_parameters( tf.nn.softplus(logit_concentration)) num_words = features.shape[1] topics_words_logits = tf.compat.v1.get_variable( "topics_words_logits", shape=[params["num_topics"], num_words], initializer=tf.compat.v1.glorot_normal_initializer()) topics_words = tf.nn.softmax(topics_words_logits, axis=-1) # Compute expected log-likelihood. First, sample from the variational # distribution; second, compute the log-likelihood given the sample. lda_variational = make_lda_variational( params["activation"], params["num_topics"], params["layer_sizes"]) with ed.tape() as variational_tape: _ = lda_variational(features) with ed.tape() as model_tape: with ed.interception( make_value_setter(topics=variational_tape["topics_posterior"])): posterior_predictive = latent_dirichlet_allocation(concentration, topics_words) log_likelihood = posterior_predictive.distribution.log_prob(features) tf.compat.v1.summary.scalar("log_likelihood", tf.reduce_mean(input_tensor=log_likelihood)) # Compute the KL-divergence between two Dirichlets analytically. # The sampled KL does not work well for "sparse" distributions # (see Appendix D of [2]). kl = variational_tape["topics_posterior"].distribution.kl_divergence( model_tape["topics"].distribution) tf.compat.v1.summary.scalar("kl", tf.reduce_mean(input_tensor=kl)) # Ensure that the KL is non-negative (up to a very small slack). # Negative KL can happen due to numerical instability. with tf.control_dependencies( [tf.compat.v1.assert_greater(kl, -1e-3, message="kl")]): kl = tf.identity(kl) elbo = log_likelihood - kl avg_elbo = tf.reduce_mean(input_tensor=elbo) tf.compat.v1.summary.scalar("elbo", avg_elbo) loss = -avg_elbo # Perform variational inference by minimizing the -ELBO. global_step = tf.compat.v1.train.get_or_create_global_step() optimizer = tf.compat.v1.train.AdamOptimizer(params["learning_rate"]) # This implements the "burn-in" for prior parameters (see Appendix D of [2]). # For the first prior_burn_in_steps steps they are fixed, and then trained # jointly with the other parameters. grads_and_vars = optimizer.compute_gradients(loss) grads_and_vars_except_prior = [ x for x in grads_and_vars if x[1] != logit_concentration] def train_op_except_prior(): return optimizer.apply_gradients( grads_and_vars_except_prior, global_step=global_step) def train_op_all(): return optimizer.apply_gradients( grads_and_vars, global_step=global_step) train_op = tf.cond( pred=global_step < params["prior_burn_in_steps"], true_fn=train_op_except_prior, false_fn=train_op_all) # The perplexity is an exponent of the average negative ELBO per word. words_per_document = tf.reduce_sum(input_tensor=features, axis=1) log_perplexity = -elbo / words_per_document tf.compat.v1.summary.scalar( "perplexity", tf.exp(tf.reduce_mean(input_tensor=log_perplexity))) (log_perplexity_tensor, log_perplexity_update) = tf.compat.v1.metrics.mean(log_perplexity) perplexity_tensor = tf.exp(log_perplexity_tensor) # Obtain the topics summary. Implemented as a py_func for simplicity. topics = tf.compat.v1.py_func( functools.partial(get_topics_strings, vocabulary=params["vocabulary"]), [topics_words, concentration], tf.string, stateful=False) tf.compat.v1.summary.text("topics", topics) return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, eval_metric_ops={ "elbo": tf.compat.v1.metrics.mean(elbo), "log_likelihood": tf.compat.v1.metrics.mean(log_likelihood), "kl": tf.compat.v1.metrics.mean(kl), "perplexity": (perplexity_tensor, log_perplexity_update), "topics": (topics, tf.no_op()), }, )
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ",", "config", ")", ":", "del", "labels", ",", "config", "# Set up the model's learnable parameters.", "logit_concentration", "=", "tf", ".", "compat", ".", "v1", ".", "get_variable",...
Builds the model function for use in an Estimator. Arguments: features: The input features for the Estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionary. config: The RunConfig, unused here. Returns: EstimatorSpec: A tf.estimator.EstimatorSpec instance.
[ "Builds", "the", "model", "function", "for", "use", "in", "an", "Estimator", "." ]
python
test
michael-lazar/rtv
rtv/page.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/page.py#L72-L99
def loop(self): """ Main control loop runs the following steps: 1. Re-draw the screen 2. Wait for user to press a key (includes terminal resizing) 3. Trigger the method registered to the input key 4. Check if there are any nested pages that need to be looped over The loop will run until self.active is set to False from within one of the methods. """ self.active = True # This needs to be called once before the main loop, in case a subpage # was pre-selected before the loop started. This happens in __main__.py # with ``page.open_submission(url=url)`` while self.selected_page and self.active: self.handle_selected_page() while self.active: self.draw() ch = self.term.stdscr.getch() self.controller.trigger(ch) while self.selected_page and self.active: self.handle_selected_page() return self.selected_page
[ "def", "loop", "(", "self", ")", ":", "self", ".", "active", "=", "True", "# This needs to be called once before the main loop, in case a subpage", "# was pre-selected before the loop started. This happens in __main__.py", "# with ``page.open_submission(url=url)``", "while", "self", ...
Main control loop runs the following steps: 1. Re-draw the screen 2. Wait for user to press a key (includes terminal resizing) 3. Trigger the method registered to the input key 4. Check if there are any nested pages that need to be looped over The loop will run until self.active is set to False from within one of the methods.
[ "Main", "control", "loop", "runs", "the", "following", "steps", ":", "1", ".", "Re", "-", "draw", "the", "screen", "2", ".", "Wait", "for", "user", "to", "press", "a", "key", "(", "includes", "terminal", "resizing", ")", "3", ".", "Trigger", "the", "...
python
train
c-soft/satel_integra
satel_integra/satel_integra.py
https://github.com/c-soft/satel_integra/blob/3b6d2020d1e10dc5aa40f30ee4ecc0f3a053eb3c/satel_integra/satel_integra.py#L31-L47
def verify_and_strip(resp): """Verify checksum and strip header and footer of received frame.""" if resp[0:2] != b'\xFE\xFE': _LOGGER.error("Houston, we got problem:") print_hex(resp) raise Exception("Wrong header - got %X%X" % (resp[0], resp[1])) if resp[-2:] != b'\xFE\x0D': raise Exception("Wrong footer - got %X%X" % (resp[-2], resp[-1])) output = resp[2:-2].replace(b'\xFE\xF0', b'\xFE') c = checksum(bytearray(output[0:-2])) if (256 * output[-2:-1][0] + output[-1:][0]) != c: raise Exception("Wrong checksum - got %d expected %d" % ( (256 * output[-2:-1][0] + output[-1:][0]), c)) return output[0:-2]
[ "def", "verify_and_strip", "(", "resp", ")", ":", "if", "resp", "[", "0", ":", "2", "]", "!=", "b'\\xFE\\xFE'", ":", "_LOGGER", ".", "error", "(", "\"Houston, we got problem:\"", ")", "print_hex", "(", "resp", ")", "raise", "Exception", "(", "\"Wrong header ...
Verify checksum and strip header and footer of received frame.
[ "Verify", "checksum", "and", "strip", "header", "and", "footer", "of", "received", "frame", "." ]
python
test
census-instrumentation/opencensus-python
opencensus/trace/propagation/b3_format.py
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/b3_format.py#L95-L117
def to_headers(self, span_context): """Convert a SpanContext object to B3 propagation headers. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: dict :returns: B3 propagation headers. """ if not span_context.span_id: span_id = INVALID_SPAN_ID else: span_id = span_context.span_id sampled = span_context.trace_options.enabled return { _TRACE_ID_KEY: span_context.trace_id, _SPAN_ID_KEY: span_id, _SAMPLED_KEY: '1' if sampled else '0' }
[ "def", "to_headers", "(", "self", ",", "span_context", ")", ":", "if", "not", "span_context", ".", "span_id", ":", "span_id", "=", "INVALID_SPAN_ID", "else", ":", "span_id", "=", "span_context", ".", "span_id", "sampled", "=", "span_context", ".", "trace_optio...
Convert a SpanContext object to B3 propagation headers. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: dict :returns: B3 propagation headers.
[ "Convert", "a", "SpanContext", "object", "to", "B3", "propagation", "headers", "." ]
python
train
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L707-L754
def _build_command(self): """ Command to start the IOU process. (to be passed to subprocess.Popen()) IOU command line: Usage: <image> [options] <application id> <image>: unix-js-m | unix-is-m | unix-i-m | ... <application id>: instance identifier (0 < id <= 1024) Options: -e <n> Number of Ethernet interfaces (default 2) -s <n> Number of Serial interfaces (default 2) -n <n> Size of nvram in Kb (default 64KB) -b <string> IOS debug string -c <name> Configuration file name -d Generate debug information -t Netio message trace -q Suppress informational messages -h Display this help -C Turn off use of host clock -m <n> Megabytes of router memory (default 256MB) -L Disable local console, use remote console -l Enable Layer 1 keepalive messages -u <n> UDP port base for distributed networks -R Ignore options from the IOURC file -U Disable unix: file system location -W Disable watchdog timer -N Ignore the NETMAP file """ command = [self._path] if len(self._ethernet_adapters) != 2: command.extend(["-e", str(len(self._ethernet_adapters))]) if len(self._serial_adapters) != 2: command.extend(["-s", str(len(self._serial_adapters))]) if not self.use_default_iou_values: command.extend(["-n", str(self._nvram)]) command.extend(["-m", str(self._ram)]) # do not let IOU create the NVRAM anymore #startup_config_file = self.startup_config_file # if startup_config_file: # command.extend(["-c", os.path.basename(startup_config_file)]) if self._l1_keepalives: yield from self._enable_l1_keepalives(command) command.extend([str(self.application_id)]) return command
[ "def", "_build_command", "(", "self", ")", ":", "command", "=", "[", "self", ".", "_path", "]", "if", "len", "(", "self", ".", "_ethernet_adapters", ")", "!=", "2", ":", "command", ".", "extend", "(", "[", "\"-e\"", ",", "str", "(", "len", "(", "se...
Command to start the IOU process. (to be passed to subprocess.Popen()) IOU command line: Usage: <image> [options] <application id> <image>: unix-js-m | unix-is-m | unix-i-m | ... <application id>: instance identifier (0 < id <= 1024) Options: -e <n> Number of Ethernet interfaces (default 2) -s <n> Number of Serial interfaces (default 2) -n <n> Size of nvram in Kb (default 64KB) -b <string> IOS debug string -c <name> Configuration file name -d Generate debug information -t Netio message trace -q Suppress informational messages -h Display this help -C Turn off use of host clock -m <n> Megabytes of router memory (default 256MB) -L Disable local console, use remote console -l Enable Layer 1 keepalive messages -u <n> UDP port base for distributed networks -R Ignore options from the IOURC file -U Disable unix: file system location -W Disable watchdog timer -N Ignore the NETMAP file
[ "Command", "to", "start", "the", "IOU", "process", ".", "(", "to", "be", "passed", "to", "subprocess", ".", "Popen", "()", ")" ]
python
train
biolink/biolink-model
metamodel/generators/dotgen.py
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/dotgen.py#L101-L103
def cli(yamlfile, directory, out, classname, format): """ Generate graphviz representations of the biolink model """ DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
[ "def", "cli", "(", "yamlfile", ",", "directory", ",", "out", ",", "classname", ",", "format", ")", ":", "DotGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "classname", "=", "classname", ",", "dirname", "=", "directory", ",", "fil...
Generate graphviz representations of the biolink model
[ "Generate", "graphviz", "representations", "of", "the", "biolink", "model" ]
python
train
saltstack/salt
salt/modules/consul.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L963-L1074
def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret
[ "def", "agent_service_register", "(", "consul_url", "=", "None", ",", "token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "data", "=", "{", "}", "if", "not", "consul_url", ":", "consul_url", "=", "_get_config", "(", ")", "i...
The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s"
[ "The", "used", "to", "add", "a", "new", "service", "with", "an", "optional", "health", "check", "to", "the", "local", "agent", "." ]
python
train
hamstah/ukpostcodeparser
ukpostcodeparser/parser.py
https://github.com/hamstah/ukpostcodeparser/blob/e36d6f07e5d410382641b5599f122d7c1b3dabdd/ukpostcodeparser/parser.py#L66-L146
def parse_uk_postcode(postcode, strict=True, incode_mandatory=True): '''Split UK postcode into outcode and incode portions. Arguments: postcode The postcode to be split. strict If true, the postcode will be validated according to the rules as specified at the Universal Postal Union[1] and The UK Government Data Standards Catalogue[2]. If the supplied postcode doesn't adhere to these rules a ValueError will be thrown. incode_mandatory If true, and only an outcode has been supplied, the function will throw a ValueError. Returns: outcode, incode Raises: ValueError, if postcode is longer than seven characters, or if 'strict' or 'incode_mandatory' conditions are broken - see above. Usage example: >>> from postcode import parse_uk_postcode >>> parse_uk_postcode('cr0 2yr') ('CR0', '2YR') >>> parse_uk_postcode('cr0') Traceback (most recent call last): File "<interactive input>", line 1, in ? File "postcode.py", line 101, in parse_uk_postcode raise ValueError('Incode mandatory') ValueError: Incode mandatory >>> parse_uk_postcode('cr0', False, False) ('CR0', '') [1] http://www.upu.int/fileadmin/documentsFiles/activities/addressingUnit/gbrEn.pdf [2] http://web.archive.org/web/20090930140939/http://www.govtalk.gov.uk/gdsc/html/noframes/PostCode-2-1-Release.htm ''' postcode = postcode.replace(' ', '').upper() # Normalize if len(postcode) > 7: raise exceptions.MaxLengthExceededError() # Validate postcode if strict: # Try for full postcode match postcode_match = POSTCODE_REGEX.match(postcode) if postcode_match: return postcode_match.group(1, 2) # Try for outcode only match outcode_match = STANDALONE_OUTCODE_REGEX.match(postcode) if outcode_match: if incode_mandatory: raise exceptions.IncodeNotFoundError('Incode mandatory') else: return outcode_match.group(1), '' # Try Girobank special case if postcode == 'GIR0AA': return 'GIR', '0AA' elif postcode == 'GIR': if incode_mandatory: raise exceptions.IncodeNotFoundError('Incode mandatory') else: return 'GIR', '' # None of the above raise exceptions.InvalidPostcodeError( 'Value provided does not align with UK postcode rules' ) # Just chop up whatever we've been given. else: # Outcode only if len(postcode) <= 4: if incode_mandatory: raise exceptions.IncodeNotFoundError('Incode mandatory') else: return postcode, '' # Full postcode else: return postcode[:-3], postcode[-3:]
[ "def", "parse_uk_postcode", "(", "postcode", ",", "strict", "=", "True", ",", "incode_mandatory", "=", "True", ")", ":", "postcode", "=", "postcode", ".", "replace", "(", "' '", ",", "''", ")", ".", "upper", "(", ")", "# Normalize", "if", "len", "(", "...
Split UK postcode into outcode and incode portions. Arguments: postcode The postcode to be split. strict If true, the postcode will be validated according to the rules as specified at the Universal Postal Union[1] and The UK Government Data Standards Catalogue[2]. If the supplied postcode doesn't adhere to these rules a ValueError will be thrown. incode_mandatory If true, and only an outcode has been supplied, the function will throw a ValueError. Returns: outcode, incode Raises: ValueError, if postcode is longer than seven characters, or if 'strict' or 'incode_mandatory' conditions are broken - see above. Usage example: >>> from postcode import parse_uk_postcode >>> parse_uk_postcode('cr0 2yr') ('CR0', '2YR') >>> parse_uk_postcode('cr0') Traceback (most recent call last): File "<interactive input>", line 1, in ? File "postcode.py", line 101, in parse_uk_postcode raise ValueError('Incode mandatory') ValueError: Incode mandatory >>> parse_uk_postcode('cr0', False, False) ('CR0', '') [1] http://www.upu.int/fileadmin/documentsFiles/activities/addressingUnit/gbrEn.pdf [2] http://web.archive.org/web/20090930140939/http://www.govtalk.gov.uk/gdsc/html/noframes/PostCode-2-1-Release.htm
[ "Split", "UK", "postcode", "into", "outcode", "and", "incode", "portions", "." ]
python
train
revelc/pyaccumulo
pyaccumulo/proxy/AccumuloProxy.py
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L2259-L2267
def setProperty(self, login, property, value): """ Parameters: - login - property - value """ self.send_setProperty(login, property, value) self.recv_setProperty()
[ "def", "setProperty", "(", "self", ",", "login", ",", "property", ",", "value", ")", ":", "self", ".", "send_setProperty", "(", "login", ",", "property", ",", "value", ")", "self", ".", "recv_setProperty", "(", ")" ]
Parameters: - login - property - value
[ "Parameters", ":", "-", "login", "-", "property", "-", "value" ]
python
train
geomet/geomet
geomet/wkb.py
https://github.com/geomet/geomet/blob/b82d7118113ab723751eba3de5df98c368423c2b/geomet/wkb.py#L525-L559
def _dump_multipolygon(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`. """ coords = obj['coordinates'] vertex = coords[0][0][0] num_dims = len(vertex) wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder( 'MultiPolygon', num_dims, big_endian, meta ) poly_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Polygon'] if big_endian: poly_type = BIG_ENDIAN + poly_type else: poly_type = LITTLE_ENDIAN + poly_type[::-1] # apped the number of polygons wkb_string += struct.pack('%sl' % byte_order, len(coords)) for polygon in coords: # append polygon header wkb_string += poly_type # append the number of rings in this polygon wkb_string += struct.pack('%sl' % byte_order, len(polygon)) for ring in polygon: # append the number of vertices in this ring wkb_string += struct.pack('%sl' % byte_order, len(ring)) for vertex in ring: wkb_string += struct.pack(byte_fmt, *vertex) return wkb_string
[ "def", "_dump_multipolygon", "(", "obj", ",", "big_endian", ",", "meta", ")", ":", "coords", "=", "obj", "[", "'coordinates'", "]", "vertex", "=", "coords", "[", "0", "]", "[", "0", "]", "[", "0", "]", "num_dims", "=", "len", "(", "vertex", ")", "w...
Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`.
[ "Dump", "a", "GeoJSON", "-", "like", "dict", "to", "a", "multipolygon", "WKB", "string", "." ]
python
train
moralrecordings/mrcrowbar
mrcrowbar/utils.py
https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/utils.py#L394-L447
def pixdump_iter( source, start=None, end=None, length=None, width=64, height=None, palette=None ): """Return the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Width of image to render in pixels (default: 64) height Height of image to render in pixels (default: auto) palette List of Colours to use (default: test palette) """ assert is_bytes( source ) if not palette: palette = colour.TEST_PALETTE start = 0 if (start is None) else start if (end is not None) and (length is not None): raise ValueError( 'Can\'t define both an end and a length!' ) elif (length is not None): end = start+length elif (end is not None): pass else: end = len( source ) start = max( start, 0 ) end = min( end, len( source ) ) if len( source ) == 0 or (start == end == 0): return iter(()) if height is None: height = math.ceil( (end-start)/width ) def data_fetch( x_pos, y_pos, frame ): index = y_pos*width + x_pos + start if index >= end: return (0, 0, 0, 0) return palette[source[index]] return ansi.format_image_iter( data_fetch, width=width, height=height )
[ "def", "pixdump_iter", "(", "source", ",", "start", "=", "None", ",", "end", "=", "None", ",", "length", "=", "None", ",", "width", "=", "64", ",", "height", "=", "None", ",", "palette", "=", "None", ")", ":", "assert", "is_bytes", "(", "source", "...
Return the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Width of image to render in pixels (default: 64) height Height of image to render in pixels (default: auto) palette List of Colours to use (default: test palette)
[ "Return", "the", "contents", "of", "a", "byte", "string", "as", "a", "256", "colour", "image", "." ]
python
train
yandex/yandex-tank
yandextank/plugins/NeUploader/plugin.py
https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/NeUploader/plugin.py#L81-L93
def get_uploader(data_session, column_mapping, overall_only=False): """ :type column_mapping: dict :type data_session: DataSession """ overall = {col_name: data_session.new_aggregated_metric(name + ' overall') for col_name, name in column_mapping.items()} def upload_df(df): for col_name, metric in overall.items(): df['value'] = df[col_name] metric.put(df) return upload_df
[ "def", "get_uploader", "(", "data_session", ",", "column_mapping", ",", "overall_only", "=", "False", ")", ":", "overall", "=", "{", "col_name", ":", "data_session", ".", "new_aggregated_metric", "(", "name", "+", "' overall'", ")", "for", "col_name", ",", "na...
:type column_mapping: dict :type data_session: DataSession
[ ":", "type", "column_mapping", ":", "dict", ":", "type", "data_session", ":", "DataSession" ]
python
test
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3479-L3489
def global_fixes(): """Yield multiple (code, function) tuples.""" for function in list(globals().values()): if inspect.isfunction(function): arguments = _get_parameters(function) if arguments[:1] != ['source']: continue code = extract_code_from_function(function) if code: yield (code, function)
[ "def", "global_fixes", "(", ")", ":", "for", "function", "in", "list", "(", "globals", "(", ")", ".", "values", "(", ")", ")", ":", "if", "inspect", ".", "isfunction", "(", "function", ")", ":", "arguments", "=", "_get_parameters", "(", "function", ")"...
Yield multiple (code, function) tuples.
[ "Yield", "multiple", "(", "code", "function", ")", "tuples", "." ]
python
train
eyeseast/python-metalsmyth
metalsmyth/__init__.py
https://github.com/eyeseast/python-metalsmyth/blob/8c99746d4987ab8ec88d6ba84b6092c51dfbbe3e/metalsmyth/__init__.py#L99-L126
def build(self, dest=None): "Build out results to dest directory (creating if needed)" # dest can be set here or on init if not dest: dest = self.dest # raise an error if dest is None if dest is None: raise ValueError('destination directory must not be None') # store build dir for later self.dest = dest # ensure a build dir if not os.path.isdir(self.dest): os.makedirs(self.dest) # make sure we have files if not self.files: self.run() # write the content of each post to dest, using keys as filenames for filename, post in self.files.items(): # join filename to dest dir path = os.path.join(self.dest, filename) with open(path, 'wb') as f: f.write(post.content.encode('utf-8'))
[ "def", "build", "(", "self", ",", "dest", "=", "None", ")", ":", "# dest can be set here or on init", "if", "not", "dest", ":", "dest", "=", "self", ".", "dest", "# raise an error if dest is None", "if", "dest", "is", "None", ":", "raise", "ValueError", "(", ...
Build out results to dest directory (creating if needed)
[ "Build", "out", "results", "to", "dest", "directory", "(", "creating", "if", "needed", ")" ]
python
train
quantopian/pgcontents
pgcontents/query.py
https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/query.py#L201-L216
def _dir_exists(db, user_id, db_dirname): """ Internal implementation of dir_exists. Expects a db-style path name. """ return db.execute( select( [func.count(directories.c.name)], ).where( and_( directories.c.user_id == user_id, directories.c.name == db_dirname, ), ) ).scalar() != 0
[ "def", "_dir_exists", "(", "db", ",", "user_id", ",", "db_dirname", ")", ":", "return", "db", ".", "execute", "(", "select", "(", "[", "func", ".", "count", "(", "directories", ".", "c", ".", "name", ")", "]", ",", ")", ".", "where", "(", "and_", ...
Internal implementation of dir_exists. Expects a db-style path name.
[ "Internal", "implementation", "of", "dir_exists", "." ]
python
test
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L2233-L2251
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_brief_info = ET.Element("get_stp_brief_info") config = get_stp_brief_info output = ET.SubElement(get_stp_brief_info, "output") spanning_tree_info = ET.SubElement(output, "spanning-tree-info") spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode") pvstp = ET.SubElement(spanning_tree_mode, "pvstp") pvstp = ET.SubElement(pvstp, "pvstp") vlan_id_key = ET.SubElement(pvstp, "vlan-id") vlan_id_key.text = kwargs.pop('vlan_id') root_bridge = ET.SubElement(pvstp, "root-bridge") priority = ET.SubElement(root_bridge, "priority") priority.text = kwargs.pop('priority') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_brief_info", "=", "ET", ".", "Element", "(", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_resnet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L333-L376
def mtf_resnet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 32 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-parallelism hparams.add_hparam("mesh_shape", "batch:8") hparams.add_hparam("layout", "batch:batch") hparams.add_hparam("filter_size", 1024) hparams.add_hparam("num_layers", 6) # Share weights between input and target embeddings hparams.shared_embedding = True hparams.shared_embedding_and_softmax_weights = True hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 hparams.add_hparam("d_kv", 32) # Image related hparams hparams.add_hparam("img_len", 32) hparams.add_hparam("num_channels", 3) hparams.add_hparam("row_blocks", 1) hparams.add_hparam("col_blocks", 1) hparams.add_hparam("rows_size", 32) hparams.add_hparam("cols_size", 32) # Model-specific parameters hparams.add_hparam("layer_sizes", [3, 4, 6, 3]) hparams.add_hparam("filter_sizes", [64, 64, 128, 256, 512]) hparams.add_hparam("is_cifar", False) # Variable init hparams.initializer = "normal_unit_scaling" hparams.initializer_gain = 2. # TODO(nikip): Change optimization scheme? hparams.learning_rate = 0.1 return hparams
[ "def", "mtf_resnet_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "no_data_parallelism", "=", "True", "hparams", ".", "use_fixed_batch_size", "=", "True", "hparams", ".", "batch_size", "=", "32", "hparams"...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
python
train
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/basic.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L257-L292
def _connect_model(self, model): """ Used internally to connect the property into the model, and register self as a value observer for that property""" parts = self._prop_name.split(".") if len(parts) > 1: # identifies the model models = parts[:-1] Intermediate(model, models, self) for name in models: model = getattr(model, name) if not isinstance(model, Model): raise TypeError("Attribute '" + name + "' was expected to be a Model, but found: " + str(model)) prop = parts[-1] else: prop = parts[0] # prop is inside model? if not hasattr(model, prop): raise ValueError("Attribute '" + prop + "' not found in model " + str(model)) # is it observable? if model.has_property(prop): # we need to create an observing method before registering meth = types.MethodType(self._get_observer_fun(prop), self) setattr(self, meth.__name__, meth) self._prop = getattr(model, prop) self._prop_name = prop # registration of model: self._model = model self.observe_model(model)
[ "def", "_connect_model", "(", "self", ",", "model", ")", ":", "parts", "=", "self", ".", "_prop_name", ".", "split", "(", "\".\"", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "# identifies the model", "models", "=", "parts", "[", ":", "-", "1...
Used internally to connect the property into the model, and register self as a value observer for that property
[ "Used", "internally", "to", "connect", "the", "property", "into", "the", "model", "and", "register", "self", "as", "a", "value", "observer", "for", "that", "property" ]
python
train
cgarciae/phi
phi/dsl.py
https://github.com/cgarciae/phi/blob/87fd7100a76f823232f4fd8360498b4b80675265/phi/dsl.py#L675-L680
def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs): """ `Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2, arg3, arg4) + args return self.ThenAt(5, f, *args, **kwargs)
[ "def", "Then5", "(", "self", ",", "f", ",", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ")", "+", "args", "return", "self...
`Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
[ "Then5", "(", "f", "...", ")", "is", "equivalent", "to", "ThenAt", "(", "5", "f", "...", ")", ".", "Checkout", "phi", ".", "builder", ".", "Builder", ".", "ThenAt", "for", "more", "information", "." ]
python
train
linzhonghong/zapi
zapi/core/db.py
https://github.com/linzhonghong/zapi/blob/ac55c3ddbc4153561472faaf59fb72ef794f13a5/zapi/core/db.py#L524-L544
def _escape_identifiers(self, item): """ This function escapes column and table names @param item: """ if self._escape_char == '': return item for field in self._reserved_identifiers: if item.find('.%s' % field) != -1: _str = "%s%s" % (self._escape_char, item.replace('.', '%s.' % self._escape_char)) # remove duplicates if the user already included the escape return re.sub(r'[%s]+'%self._escape_char, self._escape_char, _str) if item.find('.') != -1: _str = "%s%s%s" % (self._escape_char, item.replace('.', '%s.%s'%(self._escape_char, self._escape_char)), self._escape_char) else: _str = self._escape_char+item+self._escape_char # remove duplicates if the user already included the escape return re.sub(r'[%s]+'%self._escape_char, self._escape_char, _str)
[ "def", "_escape_identifiers", "(", "self", ",", "item", ")", ":", "if", "self", ".", "_escape_char", "==", "''", ":", "return", "item", "for", "field", "in", "self", ".", "_reserved_identifiers", ":", "if", "item", ".", "find", "(", "'.%s'", "%", "field"...
This function escapes column and table names @param item:
[ "This", "function", "escapes", "column", "and", "table", "names" ]
python
train
koenedaele/skosprovider_oe
skosprovider_oe/providers.py
https://github.com/koenedaele/skosprovider_oe/blob/099b23cccd3884b06354102955dbc71f59d8fdb0/skosprovider_oe/providers.py#L277-L306
def get_children_display(self, id, **kwargs): ''' Return a list of concepts or collections that should be displayed under this concept or collection. :param id: A concept or collection id. :rtype: A list of concepts and collections. For each an id is present and a label. The label is determined by looking at the `**kwargs` parameter, the default language of the provider and falls back to `en` if nothing is present. If the id does not exist, return `False`. ''' language = self._get_language(**kwargs) item = self.get_by_id(id) res = [] if isinstance(item, Collection): for mid in item.members: m = self.get_by_id(mid) res.append({ 'id': m.id, 'label': m.label(language) }) else: for cid in item.narrower: c = self.get_by_id(cid) res.append({ 'id': c.id, 'label': c.label(language) }) return res
[ "def", "get_children_display", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "language", "=", "self", ".", "_get_language", "(", "*", "*", "kwargs", ")", "item", "=", "self", ".", "get_by_id", "(", "id", ")", "res", "=", "[", "]", "if"...
Return a list of concepts or collections that should be displayed under this concept or collection. :param id: A concept or collection id. :rtype: A list of concepts and collections. For each an id is present and a label. The label is determined by looking at the `**kwargs` parameter, the default language of the provider and falls back to `en` if nothing is present. If the id does not exist, return `False`.
[ "Return", "a", "list", "of", "concepts", "or", "collections", "that", "should", "be", "displayed", "under", "this", "concept", "or", "collection", "." ]
python
train
pvizeli/ha-ffmpeg
haffmpeg/tools.py
https://github.com/pvizeli/ha-ffmpeg/blob/fce1d4b77e76b9cb07d814bcb858b89657e1f32b/haffmpeg/tools.py#L57-L85
async def get_version(self, timeout: int = 15) -> Optional[str]: """Execute FFmpeg process and parse the version information. Return full FFmpeg version string. Such as 3.4.2-tessus """ command = ["-version"] # open input for capture 1 frame is_open = await self.open(cmd=command, input_source=None, output="") # error after open? if not is_open: _LOGGER.warning("Error starting FFmpeg.") return # read output try: proc_func = functools.partial(self._proc.communicate, timeout=timeout) output, _ = await self._loop.run_in_executor(None, proc_func) result = re.search(r"ffmpeg version (\S*)", output.decode()) if result is not None: return result.group(1) except (subprocess.TimeoutExpired, ValueError): _LOGGER.warning("Timeout reading stdout.") self.kill() return None
[ "async", "def", "get_version", "(", "self", ",", "timeout", ":", "int", "=", "15", ")", "->", "Optional", "[", "str", "]", ":", "command", "=", "[", "\"-version\"", "]", "# open input for capture 1 frame", "is_open", "=", "await", "self", ".", "open", "(",...
Execute FFmpeg process and parse the version information. Return full FFmpeg version string. Such as 3.4.2-tessus
[ "Execute", "FFmpeg", "process", "and", "parse", "the", "version", "information", "." ]
python
train
gem/oq-engine
openquake/commands/plot_agg_curve.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_agg_curve.py#L42-L50
def plot_ac(calc_id): """ Aggregate loss curves plotter. """ # read the hazard data dstore = util.read(calc_id) agg_curve = dstore['agg_curve-rlzs'] plt = make_figure(agg_curve) plt.show()
[ "def", "plot_ac", "(", "calc_id", ")", ":", "# read the hazard data", "dstore", "=", "util", ".", "read", "(", "calc_id", ")", "agg_curve", "=", "dstore", "[", "'agg_curve-rlzs'", "]", "plt", "=", "make_figure", "(", "agg_curve", ")", "plt", ".", "show", "...
Aggregate loss curves plotter.
[ "Aggregate", "loss", "curves", "plotter", "." ]
python
train
ibm-watson-iot/iot-python
src/wiotp/sdk/api/registry/devices.py
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/registry/devices.py#L482-L498
def delete(self, devices): """ Delete one or more devices, each request can contain a maximum of 512Kb It accepts accepts a list of devices (List of Dictionary of Devices) In case of failure it throws APIException """ if not isinstance(devices, list): listOfDevices = [devices] else: listOfDevices = devices r = self._apiClient.post("api/v0002/bulk/devices/remove", listOfDevices) if r.status_code in [200, 202]: return r.json() else: raise ApiException(r)
[ "def", "delete", "(", "self", ",", "devices", ")", ":", "if", "not", "isinstance", "(", "devices", ",", "list", ")", ":", "listOfDevices", "=", "[", "devices", "]", "else", ":", "listOfDevices", "=", "devices", "r", "=", "self", ".", "_apiClient", ".",...
Delete one or more devices, each request can contain a maximum of 512Kb It accepts accepts a list of devices (List of Dictionary of Devices) In case of failure it throws APIException
[ "Delete", "one", "or", "more", "devices", "each", "request", "can", "contain", "a", "maximum", "of", "512Kb", "It", "accepts", "accepts", "a", "list", "of", "devices", "(", "List", "of", "Dictionary", "of", "Devices", ")", "In", "case", "of", "failure", ...
python
test
DataDog/integrations-core
datadog_checks_base/datadog_checks/base/utils/subprocess_output.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/utils/subprocess_output.py#L28-L69
def get_subprocess_output(command, log, raise_on_empty_output=True, log_debug=True): """ Run the given subprocess command and return its output. Raise an Exception if an error occurs. :param command: The command to run. Using a list of strings is recommended. The command will be run in a subprocess without using a shell, as such shell features like shell pipes, wildcard expansion, environment variable expansion, etc., are not supported. :type command: list(str) or str :param logging.Logger log: The log object to use :param bool raise_on_empty_output: Whether to raise a SubprocessOutputEmptyError exception when the subprocess doesn't output anything to its stdout. :param bool log_debug: Whether to enable debug logging of full command. :returns: The stdout contents, stderr contents and status code of the command :rtype: tuple(str, str, int) """ cmd_args = [] if isinstance(command, string_types): for arg in command.split(): cmd_args.append(arg) elif hasattr(type(command), '__iter__'): for arg in command: cmd_args.append(arg) else: raise TypeError('command must be a sequence or string') if log_debug: log.debug('Running get_subprocess_output with cmd: {}'.format(cmd_args)) out, err, returncode = subprocess_output(cmd_args, raise_on_empty_output) log.debug( 'get_subprocess_output returned ' '(len(out): {} ; len(err): {} ; returncode: {})'.format(len(out), len(err), returncode) ) out = ensure_unicode(out) if out is not None else None err = ensure_unicode(err) if err is not None else None return out, err, returncode
[ "def", "get_subprocess_output", "(", "command", ",", "log", ",", "raise_on_empty_output", "=", "True", ",", "log_debug", "=", "True", ")", ":", "cmd_args", "=", "[", "]", "if", "isinstance", "(", "command", ",", "string_types", ")", ":", "for", "arg", "in"...
Run the given subprocess command and return its output. Raise an Exception if an error occurs. :param command: The command to run. Using a list of strings is recommended. The command will be run in a subprocess without using a shell, as such shell features like shell pipes, wildcard expansion, environment variable expansion, etc., are not supported. :type command: list(str) or str :param logging.Logger log: The log object to use :param bool raise_on_empty_output: Whether to raise a SubprocessOutputEmptyError exception when the subprocess doesn't output anything to its stdout. :param bool log_debug: Whether to enable debug logging of full command. :returns: The stdout contents, stderr contents and status code of the command :rtype: tuple(str, str, int)
[ "Run", "the", "given", "subprocess", "command", "and", "return", "its", "output", ".", "Raise", "an", "Exception", "if", "an", "error", "occurs", "." ]
python
train
bokeh/bokeh
bokeh/server/tornado.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L425-L441
def start(self): ''' Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run. ''' self._stats_job.start() if self._mem_job is not None: self._mem_job.start() self._cleanup_job.start() if self._ping_job is not None: self._ping_job.start() for context in self._applications.values(): context.run_load_hook()
[ "def", "start", "(", "self", ")", ":", "self", ".", "_stats_job", ".", "start", "(", ")", "if", "self", ".", "_mem_job", "is", "not", "None", ":", "self", ".", "_mem_job", ".", "start", "(", ")", "self", ".", "_cleanup_job", ".", "start", "(", ")",...
Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run.
[ "Start", "the", "Bokeh", "Server", "application", "." ]
python
train
coursera/courseraoauth2client
courseraoauth2client/oauth2.py
https://github.com/coursera/courseraoauth2client/blob/4edd991defe26bfc768ab28a30368cace40baf44/courseraoauth2client/oauth2.py#L417-L434
def _exchange_refresh_tokens(self): 'Exchanges a refresh token for an access token' if self.token_cache is not None and 'refresh' in self.token_cache: # Attempt to use the refresh token to get a new access token. refresh_form = { 'grant_type': 'refresh_token', 'refresh_token': self.token_cache['refresh'], 'client_id': self.client_id, 'client_secret': self.client_secret, } try: tokens = self._request_tokens_from_token_endpoint(refresh_form) tokens['refresh'] = self.token_cache['refresh'] return tokens except OAuth2Exception: logging.exception( 'Encountered an exception during refresh token flow.') return None
[ "def", "_exchange_refresh_tokens", "(", "self", ")", ":", "if", "self", ".", "token_cache", "is", "not", "None", "and", "'refresh'", "in", "self", ".", "token_cache", ":", "# Attempt to use the refresh token to get a new access token.", "refresh_form", "=", "{", "'gra...
Exchanges a refresh token for an access token
[ "Exchanges", "a", "refresh", "token", "for", "an", "access", "token" ]
python
train
SmokinCaterpillar/pypet
examples/example_24_large_scale_brian2_simulation/clusternet.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L287-L325
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.connections) self._pre_build = (self._pre_build and 'neurons_i' in network_dict and 'neurons_e' in network_dict) if self._pre_build: self._build_connections(traj, brian_list, network_dict)
[ "def", "pre_build", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "self", ".", "_pre_build", "=", "not", "_explored_parameters_in_group", "(", "traj", ",", "traj", ".", "parameters", ".", "connections", ")", "self", ".", "_pre_b...
Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering
[ "Pre", "-", "builds", "the", "connections", "." ]
python
test
PyHDI/Pyverilog
pyverilog/vparser/parser.py
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L408-L411
def p_ioport(self, p): 'ioport : sigtypes portname' p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2)) p.set_lineno(0, p.lineno(1))
[ "def", "p_ioport", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "create_ioport", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "2", ")", ")", "p", ".", "set_lineno",...
ioport : sigtypes portname
[ "ioport", ":", "sigtypes", "portname" ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4792-L4799
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'credential_id'", ")", "and", "self", ".", "credential_id", "is", "not", "None", ":", "_dict", "[", "'credential_id'", "]", "=", "self", ".", "credent...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
hubo1016/namedstruct
namedstruct/namedstruct.py
https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L1246-L1255
def parse(self, buffer, inlineparent = None): ''' Compatible to Parser.parse() ''' if len(buffer) < self.struct.size: return None try: return (self.struct.unpack(buffer[:self.struct.size])[0], self.struct.size) except struct.error as exc: raise BadFormatError(exc)
[ "def", "parse", "(", "self", ",", "buffer", ",", "inlineparent", "=", "None", ")", ":", "if", "len", "(", "buffer", ")", "<", "self", ".", "struct", ".", "size", ":", "return", "None", "try", ":", "return", "(", "self", ".", "struct", ".", "unpack"...
Compatible to Parser.parse()
[ "Compatible", "to", "Parser", ".", "parse", "()" ]
python
train
amzn/ion-python
amazon/ion/reader.py
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L43-L59
def _narrow_unichr(code_point): """Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'. """ try: if len(code_point.char) > 1: return code_point.char except AttributeError: pass return six.unichr(code_point)
[ "def", "_narrow_unichr", "(", "code_point", ")", ":", "try", ":", "if", "len", "(", "code_point", ".", "char", ")", ">", "1", ":", "return", "code_point", ".", "char", "except", "AttributeError", ":", "pass", "return", "six", ".", "unichr", "(", "code_po...
Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds. This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2); ordinals above 0xFFFF would require recalculating and combining surrogate pairs. This avoids that by retrieving the unicode character that was initially read. Args: code_point (int|CodePoint): An int or a subclass of int that contains the unicode character representing its code point in an attribute named 'char'.
[ "Retrieves", "the", "unicode", "character", "representing", "any", "given", "code", "point", "in", "a", "way", "that", "won", "t", "break", "on", "narrow", "builds", "." ]
python
train
log2timeline/plaso
plaso/analysis/interface.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/interface.py#L314-L333
def EstimateTimeRemaining(self): """Estimates how long until all hashes have been analyzed. Returns: int: estimated number of seconds until all hashes have been analyzed. """ number_of_hashes = self.hash_queue.qsize() hashes_per_batch = self._analyzer.hashes_per_batch wait_time_per_batch = self._analyzer.wait_after_analysis analyses_performed = self._analyzer.analyses_performed if analyses_performed == 0: average_analysis_time = self._analyzer.seconds_spent_analyzing else: average_analysis_time, _ = divmod( self._analyzer.seconds_spent_analyzing, analyses_performed) batches_remaining, _ = divmod(number_of_hashes, hashes_per_batch) estimated_seconds_per_batch = average_analysis_time + wait_time_per_batch return batches_remaining * estimated_seconds_per_batch
[ "def", "EstimateTimeRemaining", "(", "self", ")", ":", "number_of_hashes", "=", "self", ".", "hash_queue", ".", "qsize", "(", ")", "hashes_per_batch", "=", "self", ".", "_analyzer", ".", "hashes_per_batch", "wait_time_per_batch", "=", "self", ".", "_analyzer", "...
Estimates how long until all hashes have been analyzed. Returns: int: estimated number of seconds until all hashes have been analyzed.
[ "Estimates", "how", "long", "until", "all", "hashes", "have", "been", "analyzed", "." ]
python
train
astropy/regions
regions/io/ds9/read.py
https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L235-L279
def parse_line(self, line): """ Parse one line """ log.debug('Parsing {}'.format(line)) # Skip blanks if line == '': return # Skip comments if line[0] == '#': return # Special case / header: parse global parameters into metadata if line.lstrip()[:6] == 'global': self.global_meta = self.parse_meta(line) # global_meta can specify "include=1"; never seen other options # used but presumably =0 means false self.global_meta['include'] = (False if self.global_meta.get('include') in ('0', 'False', False) else True) return # Try to parse the line region_type_search = regex_global.search(line) if region_type_search: include = region_type_search.groups()[0] region_type = region_type_search.groups()[1] else: self._raise_error("No region type found for line '{0}'.".format(line)) return if region_type in self.coordinate_systems: # Found coord system definition self.set_coordsys(region_type) return if region_type not in DS9RegionParser.language_spec: self._raise_error("Region type '{0}' was identified, but it is not one of " "the known region types.".format(region_type)) return else: # Found region specification, region_end = region_type_search.span()[1] self.parse_region(include, region_type, region_end, line)
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "log", ".", "debug", "(", "'Parsing {}'", ".", "format", "(", "line", ")", ")", "# Skip blanks", "if", "line", "==", "''", ":", "return", "# Skip comments", "if", "line", "[", "0", "]", "==", "...
Parse one line
[ "Parse", "one", "line" ]
python
train
materialsproject/pymatgen
pymatgen/analysis/gb/grain.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L729-L1169
def get_trans_mat(r_axis, angle, normal=False, trans_cry=np.eye(3), lat_type='c', ratio=None, surface=None, max_search=20, quick_gen=False): """ Find the two transformation matrix for each grain from given rotation axis, GB plane, rotation angle and corresponding ratio (see explanation for ratio below). The structure of each grain can be obtained by applying the corresponding transformation matrix to the conventional cell. The algorithm for this code is from reference, Acta Cryst, A32,783(1976). Args: r_axis (list of three integers, e.g. u, v, w or four integers, e.g. u, v, t, w for hex/rho system only): the rotation axis of the grain boundary. angle (float, in unit of degree) : the rotation angle of the grain boundary normal (logic): determine if need to require the c axis of one grain associated with the first transformation matrix perperdicular to the surface or not. default to false. trans_cry (3 by 3 array): if the structure given are primitive cell in cubic system, e.g. bcc or fcc system, trans_cry is the transformation matrix from its conventional cell to the primitive cell. lat_type ( one character): 'c' or 'C': cubic system 't' or 'T': tetragonal system 'o' or 'O': orthorhombic system 'h' or 'H': hexagonal system 'r' or 'R': rhombohedral system default to cubic system ratio (list of integers): lattice axial ratio. For cubic system, ratio is not needed. For tetragonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. For orthorhombic system, ratio = [mu, lam, mv], list of three integers, that is, mu:lam:mv = c2:b2:a2. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational. For rhombohedral system, ratio = [mu, mv], list of two integers, that is, mu/mv is the ratio of (1+2*cos(alpha)/cos(alpha). If irrational, set it to None. For hexagonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. surface (list of three integers, e.g. h, k, l or four integers, e.g. h, k, i, l for hex/rho system only): the miller index of grain boundary plane, with the format of [h,k,l] if surface is not given, the default is perpendicular to r_axis, which is a twist grain boundary. max_search (int): max search for the GB lattice vectors that give the smallest GB lattice. If normal is true, also max search the GB c vector that perpendicular to the plane. quick_gen (bool): whether to quickly generate a supercell, if set to true, no need to find the smallest cell. Returns: t1 (3 by 3 integer array): The transformation array for one grain. t2 (3 by 3 integer array): The transformation array for the other grain """ # transform four index notation to three index notation if len(r_axis) == 4: u1 = r_axis[0] v1 = r_axis[1] w1 = r_axis[3] if lat_type.lower() == 'h': u = 2 * u1 + v1 v = 2 * v1 + u1 w = w1 r_axis = [u, v, w] elif lat_type.lower() == 'r': u = 2 * u1 + v1 + w1 v = v1 + w1 - u1 w = w1 - 2 * v1 - u1 r_axis = [u, v, w] # make sure gcd(r_axis)==1 if reduce(gcd, r_axis) != 1: r_axis = [int(round(x / reduce(gcd, r_axis))) for x in r_axis] if surface is not None: if len(surface) == 4: u1 = surface[0] v1 = surface[1] w1 = surface[3] surface = [u1, v1, w1] # set the surface for grain boundary. if surface is None: if lat_type.lower() == 'c': surface = r_axis else: if lat_type.lower() == 'h': if ratio is None: c2_a2_ratio = 1 else: c2_a2_ratio = ratio[0] / ratio[1] metric = np.array([[1, -0.5, 0], [-0.5, 1, 0], [0, 0, c2_a2_ratio]]) elif lat_type.lower() == 'r': if ratio is None: cos_alpha = 0.5 else: cos_alpha = 1.0 / (ratio[0] / ratio[1] - 2) metric = np.array([[1, cos_alpha, cos_alpha], [cos_alpha, 1, cos_alpha], [cos_alpha, cos_alpha, 1]]) elif lat_type.lower() == 't': if ratio is None: c2_a2_ratio = 1 else: c2_a2_ratio = ratio[0] / ratio[1] metric = np.array([[1, 0, 0], [0, 1, 0], [0, 0, c2_a2_ratio]]) elif lat_type.lower() == 'o': for i in range(3): if ratio[i] is None: ratio[i] = 1 metric = np.array([[1, 0, 0], [0, ratio[1] / ratio[2], 0], [0, 0, ratio[0] / ratio[2]]]) else: raise RuntimeError('Lattice type has not implemented.') surface = np.matmul(r_axis, metric) fractions = [Fraction(x).limit_denominator() for x in surface] least_mul = reduce(lcm, [f.denominator for f in fractions]) surface = [int(round(x * least_mul)) for x in surface] if reduce(gcd, surface) != 1: index = reduce(gcd, surface) surface = [int(round(x / index)) for x in surface] if lat_type.lower() == 'h': # set the value for u,v,w,mu,mv,m,n,d,x # check the reference for the meaning of these parameters u, v, w = r_axis # make sure mu, mv are coprime integers. if ratio is None: mu, mv = [1, 1] if w != 0: if u != 0 or (v != 0): raise RuntimeError('For irrational c2/a2, CSL only exist for [0,0,1] ' 'or [u,v,0] and m = 0') else: mu, mv = ratio if gcd(mu, mv) != 1: temp = gcd(mu, mv) mu = int(round(mu / temp)) mv = int(round(mv / temp)) d = (u ** 2 + v ** 2 - u * v) * mv + w ** 2 * mu if abs(angle - 180.0) < 1.e0: m = 0 n = 1 else: fraction = Fraction(np.tan(angle / 2 / 180.0 * np.pi) / np.sqrt(float(d) / 3.0 / mu)).limit_denominator() m = fraction.denominator n = fraction.numerator # construct the rotation matrix, check reference for details r_list = [(u ** 2 * mv - v ** 2 * mv - w ** 2 * mu) * n ** 2 + 2 * w * mu * m * n + 3 * mu * m ** 2, (2 * v - u) * u * mv * n ** 2 - 4 * w * mu * m * n, 2 * u * w * mu * n ** 2 + 2 * (2 * v - u) * mu * m * n, (2 * u - v) * v * mv * n ** 2 + 4 * w * mu * m * n, (v ** 2 * mv - u ** 2 * mv - w ** 2 * mu) * n ** 2 - 2 * w * mu * m * n + 3 * mu * m ** 2, 2 * v * w * mu * n ** 2 - 2 * (2 * u - v) * mu * m * n, (2 * u - v) * w * mv * n ** 2 - 3 * v * mv * m * n, (2 * v - u) * w * mv * n ** 2 + 3 * u * mv * m * n, (w ** 2 * mu - u ** 2 * mv - v ** 2 * mv + u * v * mv) * n ** 2 + 3 * mu * m ** 2] m = -1 * m r_list_inv = [(u ** 2 * mv - v ** 2 * mv - w ** 2 * mu) * n ** 2 + 2 * w * mu * m * n + 3 * mu * m ** 2, (2 * v - u) * u * mv * n ** 2 - 4 * w * mu * m * n, 2 * u * w * mu * n ** 2 + 2 * (2 * v - u) * mu * m * n, (2 * u - v) * v * mv * n ** 2 + 4 * w * mu * m * n, (v ** 2 * mv - u ** 2 * mv - w ** 2 * mu) * n ** 2 - 2 * w * mu * m * n + 3 * mu * m ** 2, 2 * v * w * mu * n ** 2 - 2 * (2 * u - v) * mu * m * n, (2 * u - v) * w * mv * n ** 2 - 3 * v * mv * m * n, (2 * v - u) * w * mv * n ** 2 + 3 * u * mv * m * n, (w ** 2 * mu - u ** 2 * mv - v ** 2 * mv + u * v * mv) * n ** 2 + 3 * mu * m ** 2] m = -1 * m F = 3 * mu * m ** 2 + d * n ** 2 all_list = r_list + r_list_inv + [F] com_fac = reduce(gcd, all_list) sigma = F / com_fac r_matrix = (np.array(r_list) / com_fac / sigma).reshape(3, 3) elif lat_type.lower() == 'r': # set the value for u,v,w,mu,mv,m,n,d # check the reference for the meaning of these parameters u, v, w = r_axis # make sure mu, mv are coprime integers. if ratio is None: mu, mv = [1, 1] if u + v + w != 0: if u != v or u != w: raise RuntimeError('For irrational ratio_alpha, CSL only exist for [1,1,1]' 'or [u, v, -(u+v)] and m =0') else: mu, mv = ratio if gcd(mu, mv) != 1: temp = gcd(mu, mv) mu = int(round(mu / temp)) mv = int(round(mv / temp)) d = (u ** 2 + v ** 2 + w ** 2) * (mu - 2 * mv) + \ 2 * mv * (v * w + w * u + u * v) if abs(angle - 180.0) < 1.e0: m = 0 n = 1 else: fraction = Fraction(np.tan(angle / 2 / 180.0 * np.pi) / np.sqrt(float(d) / mu)).limit_denominator() m = fraction.denominator n = fraction.numerator # construct the rotation matrix, check reference for details r_list = [(mu - 2 * mv) * (u ** 2 - v ** 2 - w ** 2) * n ** 2 + 2 * mv * (v - w) * m * n - 2 * mv * v * w * n ** 2 + mu * m ** 2, 2 * (mv * u * n * (w * n + u * n - m) - (mu - mv) * m * w * n + (mu - 2 * mv) * u * v * n ** 2), 2 * (mv * u * n * (v * n + u * n + m) + (mu - mv) * m * v * n + (mu - 2 * mv) * w * u * n ** 2), 2 * (mv * v * n * (w * n + v * n + m) + (mu - mv) * m * w * n + (mu - 2 * mv) * u * v * n ** 2), (mu - 2 * mv) * (v ** 2 - w ** 2 - u ** 2) * n ** 2 + 2 * mv * (w - u) * m * n - 2 * mv * u * w * n ** 2 + mu * m ** 2, 2 * (mv * v * n * (v * n + u * n - m) - (mu - mv) * m * u * n + (mu - 2 * mv) * w * v * n ** 2), 2 * (mv * w * n * (w * n + v * n - m) - (mu - mv) * m * v * n + (mu - 2 * mv) * w * u * n ** 2), 2 * (mv * w * n * (w * n + u * n + m) + (mu - mv) * m * u * n + (mu - 2 * mv) * w * v * n ** 2), (mu - 2 * mv) * (w ** 2 - u ** 2 - v ** 2) * n ** 2 + 2 * mv * (u - v) * m * n - 2 * mv * u * v * n ** 2 + mu * m ** 2] m = -1 * m r_list_inv = [(mu - 2 * mv) * (u ** 2 - v ** 2 - w ** 2) * n ** 2 + 2 * mv * (v - w) * m * n - 2 * mv * v * w * n ** 2 + mu * m ** 2, 2 * (mv * u * n * (w * n + u * n - m) - (mu - mv) * m * w * n + (mu - 2 * mv) * u * v * n ** 2), 2 * (mv * u * n * (v * n + u * n + m) + (mu - mv) * m * v * n + (mu - 2 * mv) * w * u * n ** 2), 2 * (mv * v * n * (w * n + v * n + m) + (mu - mv) * m * w * n + (mu - 2 * mv) * u * v * n ** 2), (mu - 2 * mv) * (v ** 2 - w ** 2 - u ** 2) * n ** 2 + 2 * mv * (w - u) * m * n - 2 * mv * u * w * n ** 2 + mu * m ** 2, 2 * (mv * v * n * (v * n + u * n - m) - (mu - mv) * m * u * n + (mu - 2 * mv) * w * v * n ** 2), 2 * (mv * w * n * (w * n + v * n - m) - (mu - mv) * m * v * n + (mu - 2 * mv) * w * u * n ** 2), 2 * (mv * w * n * (w * n + u * n + m) + (mu - mv) * m * u * n + (mu - 2 * mv) * w * v * n ** 2), (mu - 2 * mv) * (w ** 2 - u ** 2 - v ** 2) * n ** 2 + 2 * mv * (u - v) * m * n - 2 * mv * u * v * n ** 2 + mu * m ** 2] m = -1 * m F = mu * m ** 2 + d * n ** 2 all_list = r_list_inv + r_list + [F] com_fac = reduce(gcd, all_list) sigma = F / com_fac r_matrix = (np.array(r_list) / com_fac / sigma).reshape(3, 3) else: u, v, w = r_axis if lat_type.lower() == 'c': mu = 1 lam = 1 mv = 1 elif lat_type.lower() == 't': if ratio is None: mu, mv = [1, 1] if w != 0: if u != 0 or (v != 0): raise RuntimeError('For irrational c2/a2, CSL only exist for [0,0,1] ' 'or [u,v,0] and m = 0') else: mu, mv = ratio lam = mv elif lat_type.lower() == 'o': if None in ratio: mu, lam, mv = ratio non_none = [i for i in ratio if i is not None] if len(non_none) < 2: raise RuntimeError('No CSL exist for two irrational numbers') non1, non2 = non_none if mu is None: lam = non1 mv = non2 mu = 1 if w != 0: if u != 0 or (v != 0): raise RuntimeError('For irrational c2, CSL only exist for [0,0,1] ' 'or [u,v,0] and m = 0') elif lam is None: mu = non1 mv = non2 lam = 1 if v != 0: if u != 0 or (w != 0): raise RuntimeError('For irrational b2, CSL only exist for [0,1,0] ' 'or [u,0,w] and m = 0') elif mv is None: mu = non1 lam = non2 mv = 1 if u != 0: if w != 0 or (v != 0): raise RuntimeError('For irrational a2, CSL only exist for [1,0,0] ' 'or [0,v,w] and m = 0') else: mu, lam, mv = ratio if u == 0 and v == 0: mu = 1 if u == 0 and w == 0: lam = 1 if v == 0 and w == 0: mv = 1 # make sure mu, lambda, mv are coprime integers. if reduce(gcd, [mu, lam, mv]) != 1: temp = reduce(gcd, [mu, lam, mv]) mu = int(round(mu / temp)) mv = int(round(mv / temp)) lam = int(round(lam / temp)) d = (mv * u ** 2 + lam * v ** 2) * mv + w ** 2 * mu * mv if abs(angle - 180.0) < 1.e0: m = 0 n = 1 else: fraction = Fraction(np.tan(angle / 2 / 180.0 * np.pi) / np.sqrt(d / mu / lam)).limit_denominator() m = fraction.denominator n = fraction.numerator r_list = [(u ** 2 * mv * mv - lam * v ** 2 * mv - w ** 2 * mu * mv) * n ** 2 + lam * mu * m ** 2, 2 * lam * (v * u * mv * n ** 2 - w * mu * m * n), 2 * mu * (u * w * mv * n ** 2 + v * lam * m * n), 2 * mv * (u * v * mv * n ** 2 + w * mu * m * n), (v ** 2 * mv * lam - u ** 2 * mv * mv - w ** 2 * mu * mv) * n ** 2 + lam * mu * m ** 2, 2 * mv * mu * (v * w * n ** 2 - u * m * n), 2 * mv * (u * w * mv * n ** 2 - v * lam * m * n), 2 * lam * mv * (v * w * n ** 2 + u * m * n), (w ** 2 * mu * mv - u ** 2 * mv * mv - v ** 2 * mv * lam) * n ** 2 + lam * mu * m ** 2] m = -1 * m r_list_inv = [(u ** 2 * mv * mv - lam * v ** 2 * mv - w ** 2 * mu * mv) * n ** 2 + lam * mu * m ** 2, 2 * lam * (v * u * mv * n ** 2 - w * mu * m * n), 2 * mu * (u * w * mv * n ** 2 + v * lam * m * n), 2 * mv * (u * v * mv * n ** 2 + w * mu * m * n), (v ** 2 * mv * lam - u ** 2 * mv * mv - w ** 2 * mu * mv) * n ** 2 + lam * mu * m ** 2, 2 * mv * mu * (v * w * n ** 2 - u * m * n), 2 * mv * (u * w * mv * n ** 2 - v * lam * m * n), 2 * lam * mv * (v * w * n ** 2 + u * m * n), (w ** 2 * mu * mv - u ** 2 * mv * mv - v ** 2 * mv * lam) * n ** 2 + lam * mu * m ** 2] m = -1 * m F = mu * lam * m ** 2 + d * n ** 2 all_list = r_list + r_list_inv + [F] com_fac = reduce(gcd, all_list) sigma = F / com_fac r_matrix = (np.array(r_list) / com_fac / sigma).reshape(3, 3) if (sigma > 1000): raise RuntimeError('Sigma >1000 too large. Are you sure what you are doing, ' 'Please check the GB if exist') # transform surface, r_axis, r_matrix in terms of primitive lattice surface = np.matmul(surface, np.transpose(trans_cry)) fractions = [Fraction(x).limit_denominator() for x in surface] least_mul = reduce(lcm, [f.denominator for f in fractions]) surface = [int(round(x * least_mul)) for x in surface] if reduce(gcd, surface) != 1: index = reduce(gcd, surface) surface = [int(round(x / index)) for x in surface] r_axis = np.rint(np.matmul(r_axis, np.linalg.inv(trans_cry))).astype(int) if reduce(gcd, r_axis) != 1: r_axis = [int(round(x / reduce(gcd, r_axis))) for x in r_axis] r_matrix = np.dot(np.dot(np.linalg.inv(trans_cry.T), r_matrix), trans_cry.T) # set one vector of the basis to the rotation axis direction, and # obtain the corresponding transform matrix eye = np.eye(3, dtype=np.int) for h in range(3): if abs(r_axis[h]) != 0: eye[h] = np.array(r_axis) k = h + 1 if h + 1 < 3 else abs(2 - h) l = h + 2 if h + 2 < 3 else abs(1 - h) break trans = eye.T new_rot = np.array(r_matrix) # with the rotation matrix to construct the CSL lattice, check reference for details fractions = [Fraction(x).limit_denominator() for x in new_rot[:, k]] least_mul = reduce(lcm, [f.denominator for f in fractions]) scale = np.zeros((3, 3)) scale[h, h] = 1 scale[k, k] = least_mul scale[l, l] = sigma / least_mul for i in range(least_mul): check_int = i * new_rot[:, k] + (sigma / least_mul) * new_rot[:, l] if all([np.round(x, 5).is_integer() for x in list(check_int)]): n_final = i break try: n_final except NameError: raise RuntimeError('Something is wrong. Check if this GB exists or not') scale[k, l] = n_final # each row of mat_csl is the CSL lattice vector csl_init = np.rint(np.dot(np.dot(r_matrix, trans), scale)).astype(int).T if abs(r_axis[h]) > 1: csl_init = GrainBoundaryGenerator.reduce_mat(np.array(csl_init), r_axis[h], r_matrix) csl = np.rint(Lattice(csl_init).get_niggli_reduced_lattice().matrix).astype(int) # find the best slab supercell in terms of the conventional cell from the csl lattice, # which is the transformation matrix # now trans_cry is the transformation matrix from crystal to cartesian coordinates. # for cubic, do not need to change. if lat_type.lower() != 'c': if lat_type.lower() == 'h': trans_cry = np.array([[1, 0, 0], [-0.5, np.sqrt(3.0) / 2.0, 0], [0, 0, np.sqrt(mu / mv)]]) elif lat_type.lower() == 'r': if ratio is None: c2_a2_ratio = 1 else: c2_a2_ratio = 3.0 / (2 - 6 * mv / mu) trans_cry = np.array([[0.5, np.sqrt(3.0) / 6.0, 1.0 / 3 * np.sqrt(c2_a2_ratio)], [-0.5, np.sqrt(3.0) / 6.0, 1.0 / 3 * np.sqrt(c2_a2_ratio)], [0, -1 * np.sqrt(3.0) / 3.0, 1.0 / 3 * np.sqrt(c2_a2_ratio)]]) else: trans_cry = np.array([[1, 0, 0], [0, np.sqrt(lam / mv), 0], [0, 0, np.sqrt(mu / mv)]]) t1_final = GrainBoundaryGenerator.slab_from_csl(csl, surface, normal, trans_cry, max_search=max_search, quick_gen=quick_gen) t2_final = np.array(np.rint(np.dot(t1_final, np.linalg.inv(r_matrix.T)))).astype(int) return t1_final, t2_final
[ "def", "get_trans_mat", "(", "r_axis", ",", "angle", ",", "normal", "=", "False", ",", "trans_cry", "=", "np", ".", "eye", "(", "3", ")", ",", "lat_type", "=", "'c'", ",", "ratio", "=", "None", ",", "surface", "=", "None", ",", "max_search", "=", "...
Find the two transformation matrix for each grain from given rotation axis, GB plane, rotation angle and corresponding ratio (see explanation for ratio below). The structure of each grain can be obtained by applying the corresponding transformation matrix to the conventional cell. The algorithm for this code is from reference, Acta Cryst, A32,783(1976). Args: r_axis (list of three integers, e.g. u, v, w or four integers, e.g. u, v, t, w for hex/rho system only): the rotation axis of the grain boundary. angle (float, in unit of degree) : the rotation angle of the grain boundary normal (logic): determine if need to require the c axis of one grain associated with the first transformation matrix perperdicular to the surface or not. default to false. trans_cry (3 by 3 array): if the structure given are primitive cell in cubic system, e.g. bcc or fcc system, trans_cry is the transformation matrix from its conventional cell to the primitive cell. lat_type ( one character): 'c' or 'C': cubic system 't' or 'T': tetragonal system 'o' or 'O': orthorhombic system 'h' or 'H': hexagonal system 'r' or 'R': rhombohedral system default to cubic system ratio (list of integers): lattice axial ratio. For cubic system, ratio is not needed. For tetragonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. For orthorhombic system, ratio = [mu, lam, mv], list of three integers, that is, mu:lam:mv = c2:b2:a2. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational. For rhombohedral system, ratio = [mu, mv], list of two integers, that is, mu/mv is the ratio of (1+2*cos(alpha)/cos(alpha). If irrational, set it to None. For hexagonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. surface (list of three integers, e.g. h, k, l or four integers, e.g. h, k, i, l for hex/rho system only): the miller index of grain boundary plane, with the format of [h,k,l] if surface is not given, the default is perpendicular to r_axis, which is a twist grain boundary. max_search (int): max search for the GB lattice vectors that give the smallest GB lattice. If normal is true, also max search the GB c vector that perpendicular to the plane. quick_gen (bool): whether to quickly generate a supercell, if set to true, no need to find the smallest cell. Returns: t1 (3 by 3 integer array): The transformation array for one grain. t2 (3 by 3 integer array): The transformation array for the other grain
[ "Find", "the", "two", "transformation", "matrix", "for", "each", "grain", "from", "given", "rotation", "axis", "GB", "plane", "rotation", "angle", "and", "corresponding", "ratio", "(", "see", "explanation", "for", "ratio", "below", ")", ".", "The", "structure"...
python
train
yprez/django-useful
useful/helpers/json_response.py
https://github.com/yprez/django-useful/blob/288aa46df6f40fb0323c3d0c0efcded887472538/useful/helpers/json_response.py#L9-L17
def json_response(data, status=200, serializer=None): """ Returns an HttpResponse object containing JSON serialized data. The mime-type is set to application/json, and the charset to UTF-8. """ return HttpResponse(json.dumps(data, default=serializer), status=status, content_type='application/json; charset=UTF-8')
[ "def", "json_response", "(", "data", ",", "status", "=", "200", ",", "serializer", "=", "None", ")", ":", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "data", ",", "default", "=", "serializer", ")", ",", "status", "=", "status", ",", "cont...
Returns an HttpResponse object containing JSON serialized data. The mime-type is set to application/json, and the charset to UTF-8.
[ "Returns", "an", "HttpResponse", "object", "containing", "JSON", "serialized", "data", "." ]
python
train
Cadasta/django-tutelary
tutelary/mixins.py
https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/mixins.py#L146-L180
def check_permissions(self, request): """Permission checking for DRF.""" objs = [None] if hasattr(self, 'get_perms_objects'): objs = self.get_perms_objects() else: if hasattr(self, 'get_object'): try: objs = [self.get_object()] except Http404: raise except: pass if objs == [None]: objs = self.get_queryset() if len(objs) == 0: objs = [None] if (hasattr(self, 'permission_filter_queryset') and self.permission_filter_queryset is not False and self.request.method == 'GET'): if objs != [None]: self.perms_filter_queryset(objs) else: has_perm = check_perms(self.request.user, self.get_permission_required(), objs, self.request.method) if not has_perm: msg = self.get_permission_denied_message( default="Permission denied." ) if isinstance(msg, Sequence): msg = msg[0] self.permission_denied(request, message=msg)
[ "def", "check_permissions", "(", "self", ",", "request", ")", ":", "objs", "=", "[", "None", "]", "if", "hasattr", "(", "self", ",", "'get_perms_objects'", ")", ":", "objs", "=", "self", ".", "get_perms_objects", "(", ")", "else", ":", "if", "hasattr", ...
Permission checking for DRF.
[ "Permission", "checking", "for", "DRF", "." ]
python
train
OpenTreeOfLife/peyotl
peyotl/git_storage/git_action.py
https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/git_storage/git_action.py#L143-L149
def path_for_doc(self, doc_id): """Returns doc_dir and doc_filepath for doc_id. """ full_path = self.path_for_doc_fn(self.repo, doc_id) # _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn)) # _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc returning: [{}]'.format(full_path)) return full_path
[ "def", "path_for_doc", "(", "self", ",", "doc_id", ")", ":", "full_path", "=", "self", ".", "path_for_doc_fn", "(", "self", ".", "repo", ",", "doc_id", ")", "# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))", "# _LOG.debug('>>>>>>>>>...
Returns doc_dir and doc_filepath for doc_id.
[ "Returns", "doc_dir", "and", "doc_filepath", "for", "doc_id", "." ]
python
train
pyBookshelf/bookshelf
bookshelf/api_v2/os_helpers.py
https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v2/os_helpers.py#L35-L58
def dir_attribs(location, mode=None, owner=None, group=None, recursive=False, use_sudo=False): """ cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory.""" args = '' if recursive: args = args + ' -R ' if mode: if use_sudo: sudo('chmod %s %s %s' % (args, mode, location)) else: run('chmod %s %s %s' % (args, mode, location)) if owner: if use_sudo: sudo('chown %s %s %s' % (args, owner, location)) else: run('chown %s %s %s' % (args, owner, location)) if group: if use_sudo: sudo('chgrp %s %s %s' % (args, group, location)) else: run('chgrp %s %s %s' % (args, group, location)) return True
[ "def", "dir_attribs", "(", "location", ",", "mode", "=", "None", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "args", "=", "''", "if", "recursive", ":", "args", "=", ...
cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory.
[ "cuisine", "dir_attribs", "doesn", "t", "do", "sudo", "so", "we", "implement", "our", "own", "Updates", "the", "mode", "/", "owner", "/", "group", "for", "the", "given", "remote", "directory", "." ]
python
train
eykd/paved
paved/docs.py
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L119-L138
def showhtml(): """Open your web browser and display the generated html documentation. """ import webbrowser # copy from paver opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." % docroot) builddir = docroot / opts.get("builddir", ".build") # end of copy builddir=builddir / 'html' if not builddir.exists(): raise BuildFailure("Sphinx build directory (%s) does not exist." % builddir) webbrowser.open(builddir / 'index.html')
[ "def", "showhtml", "(", ")", ":", "import", "webbrowser", "# copy from paver", "opts", "=", "options", "docroot", "=", "path", "(", "opts", ".", "get", "(", "'docroot'", ",", "'docs'", ")", ")", "if", "not", "docroot", ".", "exists", "(", ")", ":", "ra...
Open your web browser and display the generated html documentation.
[ "Open", "your", "web", "browser", "and", "display", "the", "generated", "html", "documentation", "." ]
python
valid
tensorflow/tensor2tensor
tensor2tensor/models/transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L2416-L2425
def transformer_tpu_range(rhp): """Small range of hyperparameters.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.3, 3.0, scale=rhp.LOG_SCALE) rhp.set_discrete("learning_rate_warmup_steps", [1000, 2000, 4000, 8000, 16000]) rhp.set_float("initializer_gain", 0.5, 2.0) rhp.set_float("optimizer_adam_beta1", 0.85, 0.95) rhp.set_float("optimizer_adam_beta2", 0.97, 0.99) rhp.set_float("weight_decay", 0.0, 2.0)
[ "def", "transformer_tpu_range", "(", "rhp", ")", ":", "# After starting from base, set intervals for some parameters.", "rhp", ".", "set_float", "(", "\"learning_rate\"", ",", "0.3", ",", "3.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_discr...
Small range of hyperparameters.
[ "Small", "range", "of", "hyperparameters", "." ]
python
train
gem/oq-engine
openquake/calculators/views.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L145-L170
def sum_tbl(tbl, kfield, vfields): """ Aggregate a composite array and compute the totals on a given key. >>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)]) >>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt) >>> sum_tbl(tbl, 'name', ['value'])['value'] array([3, 3]) """ pairs = [(n, tbl.dtype[n]) for n in [kfield] + vfields] dt = numpy.dtype(pairs + [('counts', int)]) def sum_all(group): vals = numpy.zeros(1, dt)[0] for rec in group: for vfield in vfields: vals[vfield] += rec[vfield] vals['counts'] += 1 vals[kfield] = rec[kfield] return vals rows = groupby(tbl, operator.itemgetter(kfield), sum_all).values() array = numpy.zeros(len(rows), dt) for i, row in enumerate(rows): for j, name in enumerate(dt.names): array[i][name] = row[j] return array
[ "def", "sum_tbl", "(", "tbl", ",", "kfield", ",", "vfields", ")", ":", "pairs", "=", "[", "(", "n", ",", "tbl", ".", "dtype", "[", "n", "]", ")", "for", "n", "in", "[", "kfield", "]", "+", "vfields", "]", "dt", "=", "numpy", ".", "dtype", "("...
Aggregate a composite array and compute the totals on a given key. >>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)]) >>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt) >>> sum_tbl(tbl, 'name', ['value'])['value'] array([3, 3])
[ "Aggregate", "a", "composite", "array", "and", "compute", "the", "totals", "on", "a", "given", "key", "." ]
python
train
scopus-api/scopus
scopus/abstract_retrieval.py
https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L639-L676
def get_bibtex(self): """Bibliographic entry in BibTeX format. Raises ------ ValueError If the item's aggregationType is not Journal. """ if self.aggregationType != 'Journal': raise ValueError('Only Journal articles supported.') # Item key year = self.coverDate[0:4] first = self.title.split()[0].title() last = self.title.split()[-1].title() key = ''.join([self.authors[0].surname, year, first, last]) # Authors authors = ' and '.join(["{} {}".format(a.given_name, a.surname) for a in self.authors]) # Pages if self.pageRange: pages = self.pageRange elif self.startingPage: pages = '{}-{}'.format(self.startingPage, self.endingPage) else: pages = '-' # All information bib = "@article{{{key},\n author = {{{auth}}},\n title = "\ "{{{{{title}}}}},\n journal = {{{jour}}},\n year = "\ "{{{year}}},\n volume = {{{vol}}},\n number = {{{number}}},"\ "\n pages = {{{pages}}}".format( key=key, auth=authors, title=self.title, year=year, jour=self.publicationName, vol=self.volume, number=self.issueIdentifier, pages=pages) # DOI if self.doi: bib += ",\n doi = {{{}}}".format(self.doi) bib += "}" return bib
[ "def", "get_bibtex", "(", "self", ")", ":", "if", "self", ".", "aggregationType", "!=", "'Journal'", ":", "raise", "ValueError", "(", "'Only Journal articles supported.'", ")", "# Item key", "year", "=", "self", ".", "coverDate", "[", "0", ":", "4", "]", "fi...
Bibliographic entry in BibTeX format. Raises ------ ValueError If the item's aggregationType is not Journal.
[ "Bibliographic", "entry", "in", "BibTeX", "format", "." ]
python
train
manns/pyspread
pyspread/src/gui/_dialogs.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_dialogs.py#L1163-L1171
def _set_properties(self): """Setup title and label""" self.SetTitle(_("About pyspread")) label = _("pyspread {version}\nCopyright Martin Manns") label = label.format(version=VERSION) self.about_label.SetLabel(label)
[ "def", "_set_properties", "(", "self", ")", ":", "self", ".", "SetTitle", "(", "_", "(", "\"About pyspread\"", ")", ")", "label", "=", "_", "(", "\"pyspread {version}\\nCopyright Martin Manns\"", ")", "label", "=", "label", ".", "format", "(", "version", "=", ...
Setup title and label
[ "Setup", "title", "and", "label" ]
python
train
projecthamster/hamster
src/hamster/lib/graphics.py
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L688-L700
def traverse(self, attr_name = None, attr_value = None): """traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute """ for sprite in self.sprites: if (attr_name is None) or \ (attr_value is None and hasattr(sprite, attr_name)) or \ (attr_value is not None and getattr(sprite, attr_name, None) == attr_value): yield sprite for child in sprite.traverse(attr_name, attr_value): yield child
[ "def", "traverse", "(", "self", ",", "attr_name", "=", "None", ",", "attr_value", "=", "None", ")", ":", "for", "sprite", "in", "self", ".", "sprites", ":", "if", "(", "attr_name", "is", "None", ")", "or", "(", "attr_value", "is", "None", "and", "has...
traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute
[ "traverse", "the", "whole", "sprite", "tree", "and", "return", "child", "sprites", "which", "have", "the", "attribute", "and", "it", "s", "set", "to", "the", "specified", "value", ".", "If", "falue", "is", "None", "will", "return", "all", "sprites", "that"...
python
train
data-8/datascience
datascience/tables.py
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L384-L387
def move_to_start(self, column_label): """Move a column to the first in order.""" self._columns.move_to_end(column_label, last=False) return self
[ "def", "move_to_start", "(", "self", ",", "column_label", ")", ":", "self", ".", "_columns", ".", "move_to_end", "(", "column_label", ",", "last", "=", "False", ")", "return", "self" ]
Move a column to the first in order.
[ "Move", "a", "column", "to", "the", "first", "in", "order", "." ]
python
train
google/transitfeed
examples/google_random_queries.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L87-L91
def GetRandomDatetime(): """Return a datetime in the next week.""" seconds_offset = random.randint(0, 60 * 60 * 24 * 7) dt = datetime.today() + timedelta(seconds=seconds_offset) return dt.replace(second=0, microsecond=0)
[ "def", "GetRandomDatetime", "(", ")", ":", "seconds_offset", "=", "random", ".", "randint", "(", "0", ",", "60", "*", "60", "*", "24", "*", "7", ")", "dt", "=", "datetime", ".", "today", "(", ")", "+", "timedelta", "(", "seconds", "=", "seconds_offse...
Return a datetime in the next week.
[ "Return", "a", "datetime", "in", "the", "next", "week", "." ]
python
train
hubo1016/vlcp
vlcp/config/config.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L411-L427
def config(key): """ Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping. """ def decorator(cls): parent = cls.getConfigurableParent() if parent is None: parentbase = None else: parentbase = getattr(parent, 'configbase', None) if parentbase is None: cls.configkey = key else: cls.configkey = parentbase + '.' + key return cls return decorator
[ "def", "config", "(", "key", ")", ":", "def", "decorator", "(", "cls", ")", ":", "parent", "=", "cls", ".", "getConfigurableParent", "(", ")", "if", "parent", "is", "None", ":", "parentbase", "=", "None", "else", ":", "parentbase", "=", "getattr", "(",...
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping.
[ "Decorator", "to", "map", "this", "class", "directly", "to", "a", "configuration", "node", ".", "It", "uses", "<parentbase", ">", ".", "key", "for", "configuration", "base", "and", "configuration", "mapping", "." ]
python
train
mitsei/dlkit
dlkit/json_/grading/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L3681-L3714
def delete_gradebook_column(self, gradebook_column_id): """Deletes the ``GradebookColumn`` identified by the given ``Id``. arg: gradebook_column_id (osid.id.Id): the ``Id`` of the ``GradebookColumn`` to delete raise: NotFound - a ``GradebookColumn`` was not found identified by the given ``Id`` raise: NullArgument - ``gradebook_column_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ if not isinstance(gradebook_column_id, ABCId): raise errors.InvalidArgument('the argument is not a valid OSID Id') # check that no entries already exist for this gradebook column grading_manager = self._get_provider_manager('GRADING') gels = grading_manager.get_grade_entry_lookup_session(proxy=getattr(self, "_proxy", None)) gels.use_federated_gradebook_view() entries = gels.get_grade_entries_for_gradebook_column(gradebook_column_id) if self._has_entries(gradebook_column_id): raise errors.IllegalState('Entries exist in this gradebook column. Cannot delete it.') collection = JSONClientValidated('grading', collection='GradebookColumn', runtime=self._runtime) gradebook_column_map = collection.find_one({'_id': ObjectId(gradebook_column_id.get_identifier())}) objects.GradebookColumn(osid_object_map=gradebook_column_map, runtime=self._runtime, proxy=self._proxy)._delete() collection.delete_one({'_id': ObjectId(gradebook_column_id.get_identifier())})
[ "def", "delete_gradebook_column", "(", "self", ",", "gradebook_column_id", ")", ":", "if", "not", "isinstance", "(", "gradebook_column_id", ",", "ABCId", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", "'the argument is not a valid OSID Id'", ")", "# check t...
Deletes the ``GradebookColumn`` identified by the given ``Id``. arg: gradebook_column_id (osid.id.Id): the ``Id`` of the ``GradebookColumn`` to delete raise: NotFound - a ``GradebookColumn`` was not found identified by the given ``Id`` raise: NullArgument - ``gradebook_column_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
[ "Deletes", "the", "GradebookColumn", "identified", "by", "the", "given", "Id", "." ]
python
train
google/grr
grr/server/grr_response_server/flows/general/administrative.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/administrative.py#L137-L232
def ProcessMessages(self, msgs=None, token=None): """Processes this event.""" nanny_msg = "" for crash_details in msgs: client_urn = crash_details.client_id client_id = client_urn.Basename() # The session id of the flow that crashed. session_id = crash_details.session_id # Log. logging.info("Client crash reported, client %s.", client_urn) # Export. stats_collector_instance.Get().IncrementCounter("grr_client_crashes") # Write crash data. if data_store.RelationalDBEnabled(): client = data_store.REL_DB.ReadClientSnapshot(client_id) if client: crash_details.client_info = client.startup_info.client_info hostname = client.knowledge_base.fqdn else: hostname = "" if data_store.AFF4Enabled(): client = aff4.FACTORY.Open(client_urn, token=token) client_info = client.Get(client.Schema.CLIENT_INFO) hostname = client.Get(client.Schema.FQDN) if client_info: crash_details.client_info = client_info crash_details.crash_type = "Client Crash" if nanny_msg: termination_msg = "Client crashed, " + nanny_msg else: termination_msg = "Client crashed." # Terminate the flow. if data_store.RelationalDBEnabled(): flow_id = session_id.Basename() flow_base.TerminateFlow( client_id, flow_id, reason=termination_msg, flow_state=rdf_flow_objects.Flow.FlowState.CRASHED) else: flow.GRRFlow.TerminateAFF4Flow( session_id, reason=termination_msg, token=token) WriteAllCrashDetails( client_id, crash_details, flow_session_id=session_id, token=token) # Also send email. to_send = [] try: hunt_session_id = ExtractHuntId(session_id) if hunt_session_id and hunt_session_id != session_id: # TODO(amoser): Enable this for the relational db once we have hunt # metadata. if data_store.AFF4Enabled(): hunt_obj = aff4.FACTORY.Open( hunt_session_id, aff4_type=implementation.GRRHunt, token=token) email = hunt_obj.runner_args.crash_alert_email if email: to_send.append(email) except aff4.InstantiationError: logging.error("Failed to open hunt %s.", hunt_session_id) email = config.CONFIG["Monitoring.alert_email"] if email: to_send.append(email) for email_address in to_send: if crash_details.nanny_status: nanny_msg = "Nanny status: %s" % crash_details.nanny_status body = self.__class__.mail_template.render( client_id=client_id, admin_ui=config.CONFIG["AdminUI.url"], hostname=utils.SmartUnicode(hostname), url="/clients/%s" % client_id, nanny_msg=utils.SmartUnicode(nanny_msg), signature=config.CONFIG["Email.signature"]) email_alerts.EMAIL_ALERTER.SendEmail( email_address, "GRR server", "Client %s reported a crash." % client_id, utils.SmartStr(body), is_html=True)
[ "def", "ProcessMessages", "(", "self", ",", "msgs", "=", "None", ",", "token", "=", "None", ")", ":", "nanny_msg", "=", "\"\"", "for", "crash_details", "in", "msgs", ":", "client_urn", "=", "crash_details", ".", "client_id", "client_id", "=", "client_urn", ...
Processes this event.
[ "Processes", "this", "event", "." ]
python
train