repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
genialis/resolwe
resolwe/flow/managers/listener.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/listener.py#L205-L331
def handle_update(self, obj, internal_call=False): """Handle an incoming ``Data`` object update request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'update', 'data_id': [id of th...
[ "def", "handle_update", "(", "self", ",", "obj", ",", "internal_call", "=", "False", ")", ":", "data_id", "=", "obj", "[", "ExecutorProtocol", ".", "DATA_ID", "]", "changeset", "=", "obj", "[", "ExecutorProtocol", ".", "UPDATE_CHANGESET", "]", "if", "not", ...
Handle an incoming ``Data`` object update request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'update', 'data_id': [id of the :class:`~resolwe.flow.models.Data` ...
[ "Handle", "an", "incoming", "Data", "object", "update", "request", "." ]
python
train
35.874016
tornadoweb/tornado
tornado/web.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1368-L1422
def xsrf_token(self) -> bytes: """The XSRF-prevention token for the current user/session. To prevent cross-site request forgery, we set an '_xsrf' cookie and include the same '_xsrf' value as an argument with all POST requests. If the two do not match, we reject the form submission ...
[ "def", "xsrf_token", "(", "self", ")", "->", "bytes", ":", "if", "not", "hasattr", "(", "self", ",", "\"_xsrf_token\"", ")", ":", "version", ",", "token", ",", "timestamp", "=", "self", ".", "_get_raw_xsrf_token", "(", ")", "output_version", "=", "self", ...
The XSRF-prevention token for the current user/session. To prevent cross-site request forgery, we set an '_xsrf' cookie and include the same '_xsrf' value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery. See h...
[ "The", "XSRF", "-", "prevention", "token", "for", "the", "current", "user", "/", "session", "." ]
python
train
46.909091
PMBio/limix-backup
limix/ensemble/lmm_forest.py
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/ensemble/lmm_forest.py#L609-L614
def get_X_slice(self, rmind): '''get X with slicing''' if self.forest.optimize_memory_use: return self.forest.X[:, rmind][self.subsample] else: return self.X[:, rmind]
[ "def", "get_X_slice", "(", "self", ",", "rmind", ")", ":", "if", "self", ".", "forest", ".", "optimize_memory_use", ":", "return", "self", ".", "forest", ".", "X", "[", ":", ",", "rmind", "]", "[", "self", ".", "subsample", "]", "else", ":", "return"...
get X with slicing
[ "get", "X", "with", "slicing" ]
python
train
35
JoelBender/bacpypes
py34/bacpypes/pdu.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/pdu.py#L385-L389
def pack_ip_addr(addr): """Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string useful for a BACnet address.""" addr, port = addr return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask)
[ "def", "pack_ip_addr", "(", "addr", ")", ":", "addr", ",", "port", "=", "addr", "return", "socket", ".", "inet_aton", "(", "addr", ")", "+", "struct", ".", "pack", "(", "'!H'", ",", "port", "&", "_short_mask", ")" ]
Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string useful for a BACnet address.
[ "Given", "an", "IP", "address", "tuple", "like", "(", "1", ".", "2", ".", "3", ".", "4", "47808", ")", "return", "the", "six", "-", "octet", "string", "useful", "for", "a", "BACnet", "address", "." ]
python
train
47.2
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_web.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L358-L367
def getconfigvar_escaped(config: configparser.ConfigParser, section: str, key: str) -> Optional[str]: """ Returns a CGI-escaped version of the value read from an INI file using :class:`ConfigParser`, or ``None``. """ value = config.get(section, key) ...
[ "def", "getconfigvar_escaped", "(", "config", ":", "configparser", ".", "ConfigParser", ",", "section", ":", "str", ",", "key", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "value", "=", "config", ".", "get", "(", "section", ",", "key", ")"...
Returns a CGI-escaped version of the value read from an INI file using :class:`ConfigParser`, or ``None``.
[ "Returns", "a", "CGI", "-", "escaped", "version", "of", "the", "value", "read", "from", "an", "INI", "file", "using", ":", "class", ":", "ConfigParser", "or", "None", "." ]
python
train
40.3
cisco-sas/kitty
kitty/model/low_level/aliases.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/aliases.py#L169-L171
def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): '''16-bit field, Little endian encoded''' return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range)
[ "def", "LE16", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ",", "full_range", "=", "False", ")", ":", "return", "UInt16", "(", "value", ",", "min_value", "=", "mi...
16-bit field, Little endian encoded
[ "16", "-", "bit", "field", "Little", "endian", "encoded" ]
python
train
92
google/grr
grr/server/grr_response_server/flows/general/transfer.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/transfer.py#L394-L402
def _ReceiveFetchedFile(self, tracker): """Remove pathspec for this index and call the ReceiveFetchedFile method.""" index = tracker["index"] _, request_data = self._RemoveCompletedPathspec(index) # Report the request_data for this flow's caller. self.ReceiveFetchedFile( tracker["stat_entr...
[ "def", "_ReceiveFetchedFile", "(", "self", ",", "tracker", ")", ":", "index", "=", "tracker", "[", "\"index\"", "]", "_", ",", "request_data", "=", "self", ".", "_RemoveCompletedPathspec", "(", "index", ")", "# Report the request_data for this flow's caller.", "self...
Remove pathspec for this index and call the ReceiveFetchedFile method.
[ "Remove", "pathspec", "for", "this", "index", "and", "call", "the", "ReceiveFetchedFile", "method", "." ]
python
train
40.444444
albu/albumentations
albumentations/augmentations/bbox_utils.py
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 't...
[ "def", "check_bbox", "(", "bbox", ")", ":", "for", "name", ",", "value", "in", "zip", "(", "[", "'x_min'", ",", "'y_min'", ",", "'x_max'", ",", "'y_max'", "]", ",", "bbox", "[", ":", "4", "]", ")", ":", "if", "not", "0", "<=", "value", "<=", "1...
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
[ "Check", "if", "bbox", "boundaries", "are", "in", "range", "0", "1", "and", "minimums", "are", "lesser", "then", "maximums" ]
python
train
38.666667
djgagne/hagelslag
hagelslag/util/munkres.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/util/munkres.py#L665-L670
def __erase_primes(self): """Erase all prime markings""" for i in range(self.n): for j in range(self.n): if self.marked[i][j] == 2: self.marked[i][j] = 0
[ "def", "__erase_primes", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n", ")", ":", "for", "j", "in", "range", "(", "self", ".", "n", ")", ":", "if", "self", ".", "marked", "[", "i", "]", "[", "j", "]", "==", "2", ":...
Erase all prime markings
[ "Erase", "all", "prime", "markings" ]
python
train
35.333333
ArchiveTeam/wpull
wpull/network/connection.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/connection.py#L277-L345
def run_network_operation(self, task, wait_timeout=None, close_timeout=None, name='Network operation'): '''Run the task and raise appropriate exceptions. Coroutine. ''' if wait_timeout is not None and close_timeout is not None:...
[ "def", "run_network_operation", "(", "self", ",", "task", ",", "wait_timeout", "=", "None", ",", "close_timeout", "=", "None", ",", "name", "=", "'Network operation'", ")", ":", "if", "wait_timeout", "is", "not", "None", "and", "close_timeout", "is", "not", ...
Run the task and raise appropriate exceptions. Coroutine.
[ "Run", "the", "task", "and", "raise", "appropriate", "exceptions", "." ]
python
train
40.565217
lucapinello/Haystack
haystack/external.py
https://github.com/lucapinello/Haystack/blob/cc080d741f36cd77b07c0b59d08ea6a4cf0ef2f7/haystack/external.py#L734-L747
def matchstartorient(self,seq, factor=0.7): """ m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of matches to the motif in the supplied sequence. Factor is multip...
[ "def", "matchstartorient", "(", "self", ",", "seq", ",", "factor", "=", "0.7", ")", ":", "ans", "=", "[", "]", "txts", ",", "endpoints", ",", "scores", "=", "self", ".", "scan", "(", "seq", ",", "factor", "=", "factor", ")", "for", "txt", ",", "s...
m.matchstartorient(,seq, factor=0.7) -- Returns list of (start,orientation) coordinate pairs of matches to the motif in the supplied sequence. Factor is multiplied by m.maxscore to get a match threshold.
[ "m", ".", "matchstartorient", "(", "seq", "factor", "=", "0", ".", "7", ")", "--", "Returns", "list", "of", "(", "start", "orientation", ")", "coordinate", "pairs", "of", "matches", "to", "the", "motif", "in", "the", "supplied", "sequence", ".", "Factor"...
python
train
49.857143
mistio/mist.client
examples/multi-provision.py
https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/examples/multi-provision.py#L34-L104
def get_args(): """ Supports the command-line arguments listed below. """ parser = argparse.ArgumentParser( description="Provision multiple VM's through mist.io. You can get " "information returned with the name of the virtual machine created " "and its main mac and ip address i...
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Provision multiple VM's through mist.io. You can get \"", "\"information returned with the name of the virtual machine created \"", "\"and its main mac and ip address in IPv4...
Supports the command-line arguments listed below.
[ "Supports", "the", "command", "-", "line", "arguments", "listed", "below", "." ]
python
train
58.957746
idlesign/uwsgiconf
uwsgiconf/options/locks.py
https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/locks.py#L32-L43
def set_ipcsem_params(self, ftok=None, persistent=None): """Sets ipcsem lock engine params. :param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates. :param bool persistent: Do not remove ipcsem's on shutdown. """ self._set('ftok', ftok) self._set...
[ "def", "set_ipcsem_params", "(", "self", ",", "ftok", "=", "None", ",", "persistent", "=", "None", ")", ":", "self", ".", "_set", "(", "'ftok'", ",", "ftok", ")", "self", ".", "_set", "(", "'persistent-ipcsem'", ",", "persistent", ",", "cast", "=", "bo...
Sets ipcsem lock engine params. :param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates. :param bool persistent: Do not remove ipcsem's on shutdown.
[ "Sets", "ipcsem", "lock", "engine", "params", "." ]
python
train
31.916667
radjkarl/fancyTools
fancytools/utils/incrementName.py
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/utils/incrementName.py#L3-L33
def incrementName(nameList, name): """ return a name that is unique in a given nameList through attaching a number to it >>> l = [] now we will add 3xfoo 2xbar and one klaus to our list: >>> l.append( incrementName(l,'foo') ) >>> l.append( incrementName(l,'bar') ) >>> l.append( increm...
[ "def", "incrementName", "(", "nameList", ",", "name", ")", ":", "if", "name", "not", "in", "nameList", ":", "return", "name", "newName", "=", "name", "+", "str", "(", "1", ")", "for", "n", "in", "range", "(", "1", ",", "len", "(", "nameList", ")", ...
return a name that is unique in a given nameList through attaching a number to it >>> l = [] now we will add 3xfoo 2xbar and one klaus to our list: >>> l.append( incrementName(l,'foo') ) >>> l.append( incrementName(l,'bar') ) >>> l.append( incrementName(l,'foo') ) >>> l.append( incrementN...
[ "return", "a", "name", "that", "is", "unique", "in", "a", "given", "nameList", "through", "attaching", "a", "number", "to", "it" ]
python
train
27.258065
dmort27/panphon
panphon/permissive.py
https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/permissive.py#L174-L191
def filter_segs(self, segs): """Given list of strings, return only those which are valid segments. Args: segs (list): list of unicode values Returns: list: values in `segs` that are valid segments (according to the definititions of bases and diacritics...
[ "def", "filter_segs", "(", "self", ",", "segs", ")", ":", "def", "whole_seg", "(", "seg", ")", ":", "m", "=", "self", ".", "seg_regex", ".", "match", "(", "seg", ")", "if", "m", "and", "m", ".", "group", "(", "0", ")", "==", "seg", ":", "return...
Given list of strings, return only those which are valid segments. Args: segs (list): list of unicode values Returns: list: values in `segs` that are valid segments (according to the definititions of bases and diacritics/modifiers known to the ...
[ "Given", "list", "of", "strings", "return", "only", "those", "which", "are", "valid", "segments", "." ]
python
train
32.944444
pyparsing/pyparsing
examples/searchparser.py
https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/searchparser.py#L76-L125
def parser(self): """ This function returns a parser. The grammar should be like most full text search engines (Google, Tsearch, Lucene). Grammar: - a query consists of alphanumeric words, with an optional '*' wildcard at the end of a word - a sequence ...
[ "def", "parser", "(", "self", ")", ":", "operatorOr", "=", "Forward", "(", ")", "operatorWord", "=", "Group", "(", "Combine", "(", "Word", "(", "alphanums", ")", "+", "Suppress", "(", "'*'", ")", ")", ")", ".", "setResultsName", "(", "'wordwildcard'", ...
This function returns a parser. The grammar should be like most full text search engines (Google, Tsearch, Lucene). Grammar: - a query consists of alphanumeric words, with an optional '*' wildcard at the end of a word - a sequence of words between quotes is a literal str...
[ "This", "function", "returns", "a", "parser", ".", "The", "grammar", "should", "be", "like", "most", "full", "text", "search", "engines", "(", "Google", "Tsearch", "Lucene", ")", ".", "Grammar", ":", "-", "a", "query", "consists", "of", "alphanumeric", "wo...
python
train
40.66
ml4ai/delphi
delphi/translators/for2py/translate.py
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/translate.py#L629-L637
def process_direct_map(self, root, state) -> List[Dict]: """Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes.""" val = {"tag": root.tag, "args": []} for node in root: val["args"] +=...
[ "def", "process_direct_map", "(", "self", ",", "root", ",", "state", ")", "->", "List", "[", "Dict", "]", ":", "val", "=", "{", "\"tag\"", ":", "root", ".", "tag", ",", "\"args\"", ":", "[", "]", "}", "for", "node", "in", "root", ":", "val", "[",...
Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes.
[ "Handles", "tags", "that", "are", "mapped", "directly", "from", "xml", "to", "IR", "with", "no", "additional", "processing", "other", "than", "recursive", "translation", "of", "any", "child", "nodes", "." ]
python
train
40.111111
spacetelescope/drizzlepac
drizzlepac/nicmosData.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/nicmosData.py#L170-L192
def getdarkimg(self,chip): """ Return an array representing the dark image for the detector. Returns ------- dark : array The dark array in the same shape as the image with **units of cps**. """ # Read the temperature dependeant dark file. The name...
[ "def", "getdarkimg", "(", "self", ",", "chip", ")", ":", "# Read the temperature dependeant dark file. The name for the file is taken from", "# the TEMPFILE keyword in the primary header.", "tddobj", "=", "readTDD", ".", "fromcalfile", "(", "self", ".", "name", ")", "if", ...
Return an array representing the dark image for the detector. Returns ------- dark : array The dark array in the same shape as the image with **units of cps**.
[ "Return", "an", "array", "representing", "the", "dark", "image", "for", "the", "detector", "." ]
python
train
37.347826
thespacedoctor/polyglot
polyglot/markdown/translate.py
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/markdown/translate.py#L612-L637
def blockquote( self, text): """*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to...
[ "def", "blockquote", "(", "self", ",", "text", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "return", "\"\\n> \"", "+", "(", "\"\\n> \"", ")", ".", "join", "(", "m", ".", "group", "(", "2", ")", ".", "split", "(", "\...
*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to a MMD blockquote: .. code-block:: python ...
[ "*", "convert", "plain", "-", "text", "to", "MMD", "blockquote", "*" ]
python
train
24.307692
biolink/ontobio
ontobio/io/assocparser.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/io/assocparser.py#L271-L330
def to_markdown(self): """ Generate a summary in markdown format """ json = self.to_report_json() # summary = json['summary'] s = "# Group: {group} - Dataset: {dataset}\n".format(group=json["group"], dataset=json["dataset"]) s += "\n## SUMMARY\n\n" s += "...
[ "def", "to_markdown", "(", "self", ")", ":", "json", "=", "self", ".", "to_report_json", "(", ")", "# summary = json['summary']", "s", "=", "\"# Group: {group} - Dataset: {dataset}\\n\"", ".", "format", "(", "group", "=", "json", "[", "\"group\"", "]", ",", "dat...
Generate a summary in markdown format
[ "Generate", "a", "summary", "in", "markdown", "format" ]
python
train
54.6
inspirehep/harvesting-kit
harvestingkit/inspire_cds_package/from_inspire.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L246-L255
def update_cnum(self): """Check if we shall add cnum in 035.""" if "ConferencePaper" not in self.collections: cnums = record_get_field_values(self.record, '773', code="w") for cnum in cnums: cnum_subs = [ ("9", "INSPIRE-CNUM"), ...
[ "def", "update_cnum", "(", "self", ")", ":", "if", "\"ConferencePaper\"", "not", "in", "self", ".", "collections", ":", "cnums", "=", "record_get_field_values", "(", "self", ".", "record", ",", "'773'", ",", "code", "=", "\"w\"", ")", "for", "cnum", "in", ...
Check if we shall add cnum in 035.
[ "Check", "if", "we", "shall", "add", "cnum", "in", "035", "." ]
python
valid
41.8
Qiskit/qiskit-terra
qiskit/visualization/text.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L473-L481
def dump(self, filename, encoding="utf8"): """ Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8". """ with open(filename, mode='w', encoding=encoding) as text_file: text...
[ "def", "dump", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf8\"", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'w'", ",", "encoding", "=", "encoding", ")", "as", "text_file", ":", "text_file", ".", "write", "(", "self", ...
Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8".
[ "Dumps", "the", "ascii", "art", "in", "the", "file", ".", "Args", ":", "filename", "(", "str", ")", ":", "File", "to", "dump", "the", "ascii", "art", ".", "encoding", "(", "str", ")", ":", "Optional", ".", "Default", "utf", "-", "8", "." ]
python
test
38.333333
ml4ai/delphi
delphi/AnalysisGraph.py
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L276-L303
def assemble_transition_model_from_gradable_adjectives(self): """ Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure. Args: adjective_data res """ df = pd.read_sql_table("grad...
[ "def", "assemble_transition_model_from_gradable_adjectives", "(", "self", ")", ":", "df", "=", "pd", ".", "read_sql_table", "(", "\"gradableAdjectiveData\"", ",", "con", "=", "engine", ")", "gb", "=", "df", ".", "groupby", "(", "\"adjective\"", ")", "rs", "=", ...
Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure. Args: adjective_data res
[ "Add", "probability", "distribution", "functions", "constructed", "from", "gradable", "adjective", "data", "to", "the", "edges", "of", "the", "analysis", "graph", "data", "structure", "." ]
python
train
31.535714
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L107-L119
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port, **kwargs): """Deletes resources for a hosting device in a plugin specific way.""" if mgmt_port is not None: try: self._cleanup_hosting_port(context, mgmt_port['id...
[ "def", "delete_hosting_device_resources", "(", "self", ",", "context", ",", "tenant_id", ",", "mgmt_port", ",", "*", "*", "kwargs", ")", ":", "if", "mgmt_port", "is", "not", "None", ":", "try", ":", "self", ".", "_cleanup_hosting_port", "(", "context", ",", ...
Deletes resources for a hosting device in a plugin specific way.
[ "Deletes", "resources", "for", "a", "hosting", "device", "in", "a", "plugin", "specific", "way", "." ]
python
train
54.307692
inveniosoftware/invenio-oauthclient
invenio_oauthclient/contrib/cern.py
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L232-L256
def account_groups_and_extra_data(account, resource, refresh_timedelta=None): """Fetch account groups and extra data from resource if necessary.""" updated = datetime.utcnow() modified_since = updated if refresh_timedelta is not None: modified_since += refresh_t...
[ "def", "account_groups_and_extra_data", "(", "account", ",", "resource", ",", "refresh_timedelta", "=", "None", ")", ":", "updated", "=", "datetime", ".", "utcnow", "(", ")", "modified_since", "=", "updated", "if", "refresh_timedelta", "is", "not", "None", ":", ...
Fetch account groups and extra data from resource if necessary.
[ "Fetch", "account", "groups", "and", "extra", "data", "from", "resource", "if", "necessary", "." ]
python
train
33
CyberReboot/vent
vent/api/system.py
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/system.py#L132-L167
def backup(self): """ Saves the configuration information of the current running vent instance to be used for restoring at a later time """ status = (True, None) # initialize all needed variables (names for backup files, etc.) backup_name = ('.vent-backup-' + '-'....
[ "def", "backup", "(", "self", ")", ":", "status", "=", "(", "True", ",", "None", ")", "# initialize all needed variables (names for backup files, etc.)", "backup_name", "=", "(", "'.vent-backup-'", "+", "'-'", ".", "join", "(", "Timestamp", "(", ")", ".", "split...
Saves the configuration information of the current running vent instance to be used for restoring at a later time
[ "Saves", "the", "configuration", "information", "of", "the", "current", "running", "vent", "instance", "to", "be", "used", "for", "restoring", "at", "a", "later", "time" ]
python
train
41.722222
jamieleshaw/lurklib
lurklib/squeries.py
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/squeries.py#L175-L190
def time(self, target=None): """ Get server time. Optional arguments: * target=None - Target server. """ with self.lock: if target: self.send('TIME %s' % target) else: self.send('TIME') time = '' ...
[ "def", "time", "(", "self", ",", "target", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "if", "target", ":", "self", ".", "send", "(", "'TIME %s'", "%", "target", ")", "else", ":", "self", ".", "send", "(", "'TIME'", ")", "time", "=",...
Get server time. Optional arguments: * target=None - Target server.
[ "Get", "server", "time", ".", "Optional", "arguments", ":", "*", "target", "=", "None", "-", "Target", "server", "." ]
python
train
29.375
arviz-devs/arviz
arviz/plots/plot_utils.py
https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/plot_utils.py#L20-L84
def _scale_fig_size(figsize, textsize, rows=1, cols=1): """Scale figure properties according to rows and cols. Parameters ---------- figsize : float or None Size of figure in inches textsize : float or None fontsize rows : int Number of rows cols : int Number...
[ "def", "_scale_fig_size", "(", "figsize", ",", "textsize", ",", "rows", "=", "1", ",", "cols", "=", "1", ")", ":", "params", "=", "mpl", ".", "rcParams", "rc_width", ",", "rc_height", "=", "tuple", "(", "params", "[", "\"figure.figsize\"", "]", ")", "r...
Scale figure properties according to rows and cols. Parameters ---------- figsize : float or None Size of figure in inches textsize : float or None fontsize rows : int Number of rows cols : int Number of columns Returns ------- figsize : float or Non...
[ "Scale", "figure", "properties", "according", "to", "rows", "and", "cols", "." ]
python
train
29.061538
LonamiWebs/Telethon
telethon/client/messageparse.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/messageparse.py#L62-L90
async def _parse_message_text(self, message, parse_mode): """ Returns a (parsed message, entities) tuple depending on ``parse_mode``. """ if parse_mode is (): parse_mode = self._parse_mode else: parse_mode = utils.sanitize_parse_mode(parse_mode) i...
[ "async", "def", "_parse_message_text", "(", "self", ",", "message", ",", "parse_mode", ")", ":", "if", "parse_mode", "is", "(", ")", ":", "parse_mode", "=", "self", ".", "_parse_mode", "else", ":", "parse_mode", "=", "utils", ".", "sanitize_parse_mode", "(",...
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
[ "Returns", "a", "(", "parsed", "message", "entities", ")", "tuple", "depending", "on", "parse_mode", "." ]
python
train
41.655172
closeio/tasktiger
tasktiger/schedule.py
https://github.com/closeio/tasktiger/blob/59f893152d6eb4b7f1f62fc4b35aeeca7f26c07a/tasktiger/schedule.py#L25-L41
def periodic(seconds=0, minutes=0, hours=0, days=0, weeks=0, start_date=None, end_date=None): """ Periodic task schedule: Use to schedule a task to run periodically, starting from start_date (or None to be active immediately) until end_date (or None to repeat forever). The period start...
[ "def", "periodic", "(", "seconds", "=", "0", ",", "minutes", "=", "0", ",", "hours", "=", "0", ",", "days", "=", "0", ",", "weeks", "=", "0", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "period", "=", "seconds", "+", ...
Periodic task schedule: Use to schedule a task to run periodically, starting from start_date (or None to be active immediately) until end_date (or None to repeat forever). The period starts at the given start_date, or on Jan 1st 2000. For more details, see README.
[ "Periodic", "task", "schedule", ":", "Use", "to", "schedule", "a", "task", "to", "run", "periodically", "starting", "from", "start_date", "(", "or", "None", "to", "be", "active", "immediately", ")", "until", "end_date", "(", "or", "None", "to", "repeat", "...
python
train
40.294118
google-research/batch-ppo
agents/algorithms/ppo/ppo.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/ppo.py#L546-L568
def _mask(self, tensor, length, padding_value=0): """Set padding elements of a batch of sequences to a constant. Useful for setting padding elements to zero before summing along the time dimension, or for preventing infinite results in padding elements. Args: tensor: Tensor of sequences. l...
[ "def", "_mask", "(", "self", ",", "tensor", ",", "length", ",", "padding_value", "=", "0", ")", ":", "with", "tf", ".", "name_scope", "(", "'mask'", ")", ":", "range_", "=", "tf", ".", "range", "(", "tensor", ".", "shape", "[", "1", "]", ".", "va...
Set padding elements of a batch of sequences to a constant. Useful for setting padding elements to zero before summing along the time dimension, or for preventing infinite results in padding elements. Args: tensor: Tensor of sequences. length: Batch of sequence lengths. padding_value: Va...
[ "Set", "padding", "elements", "of", "a", "batch", "of", "sequences", "to", "a", "constant", "." ]
python
train
37.695652
androguard/androguard
androguard/core/bytecodes/apk.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1273-L1286
def get_requested_aosp_permissions_details(self): """ Returns requested aosp permissions with details. :rtype: dictionary """ l = {} for i in self.permissions: try: l[i] = self.permission_module[i] except KeyError: ...
[ "def", "get_requested_aosp_permissions_details", "(", "self", ")", ":", "l", "=", "{", "}", "for", "i", "in", "self", ".", "permissions", ":", "try", ":", "l", "[", "i", "]", "=", "self", ".", "permission_module", "[", "i", "]", "except", "KeyError", "...
Returns requested aosp permissions with details. :rtype: dictionary
[ "Returns", "requested", "aosp", "permissions", "with", "details", "." ]
python
train
28.071429
talkincode/txradius
txradius/openvpn/statusdb.py
https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/statusdb.py#L150-L173
def cli(conf): """ OpenVPN status initdb method """ try: config = init_config(conf) debug = config.getboolean('DEFAULT', 'debug') conn = get_conn(config.get('DEFAULT','statusdb')) cur = conn.cursor() sqlstr = '''create table client_status (session_id text PRIM...
[ "def", "cli", "(", "conf", ")", ":", "try", ":", "config", "=", "init_config", "(", "conf", ")", "debug", "=", "config", ".", "getboolean", "(", "'DEFAULT'", ",", "'debug'", ")", "conn", "=", "get_conn", "(", "config", ".", "get", "(", "'DEFAULT'", "...
OpenVPN status initdb method
[ "OpenVPN", "status", "initdb", "method" ]
python
train
31.458333
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L762-L798
def load(filename, instruments = None): """ loads an script instance using pickle Args: filename: source filename instruments: optional - only needed if script requires instruments dictionary of form instruments = { ...
[ "def", "load", "(", "filename", ",", "instruments", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "infile", ":", "dataPickle", "=", "infile", ".", "read", "(", ")", "script_as_dict", "=", "pickle", ".", "loads", "(", ...
loads an script instance using pickle Args: filename: source filename instruments: optional - only needed if script requires instruments dictionary of form instruments = { name_of_instrument_1 : instance_of_instrument_1, ...
[ "loads", "an", "script", "instance", "using", "pickle", "Args", ":", "filename", ":", "source", "filename", "instruments", ":", "optional", "-", "only", "needed", "if", "script", "requires", "instruments", "dictionary", "of", "form" ]
python
train
33.243243
opencobra/cobrapy
cobra/flux_analysis/parsimonious.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/parsimonious.py#L74-L105
def add_pfba(model, objective=None, fraction_of_optimum=1.0): """Add pFBA objective Add objective to minimize the summed flux of all reactions to the current objective. See Also ------- pfba Parameters ---------- model : cobra.Model The model to add the objective to ob...
[ "def", "add_pfba", "(", "model", ",", "objective", "=", "None", ",", "fraction_of_optimum", "=", "1.0", ")", ":", "if", "objective", "is", "not", "None", ":", "model", ".", "objective", "=", "objective", "if", "model", ".", "solver", ".", "objective", "....
Add pFBA objective Add objective to minimize the summed flux of all reactions to the current objective. See Also ------- pfba Parameters ---------- model : cobra.Model The model to add the objective to objective : An objective to set in combination with the pFBA ob...
[ "Add", "pFBA", "objective" ]
python
valid
37.53125
Celeo/Pycord
pycord/__init__.py
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L269-L317
def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]): """Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for ma...
[ "def", "_ws_on_message", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ",", "raw", ":", "Union", "[", "str", ",", "bytes", "]", ")", ":", "if", "isinstance", "(", "raw", ",", "bytes", ")", ":", "decoded", "=", "zlib", ".", "decompres...
Callback for receiving messages from the websocket connection This method receives ALL events from the websocket connection, some of which are used for the initial authentication flow, some of which are used for maintaining the connection, some of which are for notifying this client of user sta...
[ "Callback", "for", "receiving", "messages", "from", "the", "websocket", "connection" ]
python
train
54.632653
vertexproject/synapse
synapse/lib/syntax.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/syntax.py#L724-L741
def proppivot(self, prop): ''' :foo:bar -> baz:faz ''' pval = s_ast.RelPropValue(kids=(prop,)) self.ignore(whitespace) self.nextmust('->') self.ignore(whitespace) if self.nextchar() == '*': self.offs += 1 return s_ast.PropPivotO...
[ "def", "proppivot", "(", "self", ",", "prop", ")", ":", "pval", "=", "s_ast", ".", "RelPropValue", "(", "kids", "=", "(", "prop", ",", ")", ")", "self", ".", "ignore", "(", "whitespace", ")", "self", ".", "nextmust", "(", "'->'", ")", "self", ".", ...
:foo:bar -> baz:faz
[ ":", "foo", ":", "bar", "-", ">", "baz", ":", "faz" ]
python
train
22.222222
pgmpy/pgmpy
pgmpy/readwrite/XMLBIF.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBIF.py#L161-L177
def get_property(self): """ Returns the property of the variable Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_property() {'bowel-problem': ['position = (190, 69)'], 'dog-out': ['position = (155, 165)'], 'f...
[ "def", "get_property", "(", "self", ")", ":", "variable_property", "=", "{", "variable", ".", "find", "(", "'NAME'", ")", ".", "text", ":", "[", "property", ".", "text", "for", "property", "in", "variable", ".", "findall", "(", "'PROPERTY'", ")", "]", ...
Returns the property of the variable Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_property() {'bowel-problem': ['position = (190, 69)'], 'dog-out': ['position = (155, 165)'], 'family-out': ['position = (112, 69)'], ...
[ "Returns", "the", "property", "of", "the", "variable" ]
python
train
39.941176
six8/anticipate
src/anticipate/decorators.py
https://github.com/six8/anticipate/blob/5c0651f9829ba0140e7cf185505da6109ef1f55c/src/anticipate/decorators.py#L95-L127
def input(self, *args, **kwargs): """ Adapt the input and check for errors. Returns a tuple of adapted (args, kwargs) or raises AnticipateErrors """ errors = [] if args and self.arg_names: args = list(args) # Replace args inline that have...
[ "def", "input", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "if", "args", "and", "self", ".", "arg_names", ":", "args", "=", "list", "(", "args", ")", "# Replace args inline that have adapters", "for", "i"...
Adapt the input and check for errors. Returns a tuple of adapted (args, kwargs) or raises AnticipateErrors
[ "Adapt", "the", "input", "and", "check", "for", "errors", "." ]
python
train
31.393939
timothycrosley/deprecated.frosted
frosted/reporter.py
https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/reporter.py#L34-L37
def flake(self, message): """Print an error message to stdout.""" self.stdout.write(str(message)) self.stdout.write('\n')
[ "def", "flake", "(", "self", ",", "message", ")", ":", "self", ".", "stdout", ".", "write", "(", "str", "(", "message", ")", ")", "self", ".", "stdout", ".", "write", "(", "'\\n'", ")" ]
Print an error message to stdout.
[ "Print", "an", "error", "message", "to", "stdout", "." ]
python
train
35.5
dwavesystems/dimod
dimod/reference/composites/scalecomposite.py
https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/scalecomposite.py#L281-L296
def _scaled_bqm(bqm, scalar, bias_range, quadratic_range, ignored_variables, ignored_interactions, ignore_offset): """Helper function of sample for scaling""" bqm_copy = bqm.copy() if scalar is None: scalar = _calc_norm_coeff(bqm_copy.linear, bqm_copy.quadratic, ...
[ "def", "_scaled_bqm", "(", "bqm", ",", "scalar", ",", "bias_range", ",", "quadratic_range", ",", "ignored_variables", ",", "ignored_interactions", ",", "ignore_offset", ")", ":", "bqm_copy", "=", "bqm", ".", "copy", "(", ")", "if", "scalar", "is", "None", ":...
Helper function of sample for scaling
[ "Helper", "function", "of", "sample", "for", "scaling" ]
python
train
42.375
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L442-L450
def _get_files(path): """ Returns the list of files contained in path (recursively). """ ret_val = [] for root, _, files in os.walk(path): for f in files: ret_val.append(os.path.join(root, f)) return ret_val
[ "def", "_get_files", "(", "path", ")", ":", "ret_val", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "files", ":", "ret_val", ".", "append", "(", "os", ".", "path", ".", ...
Returns the list of files contained in path (recursively).
[ "Returns", "the", "list", "of", "files", "contained", "in", "path", "(", "recursively", ")", "." ]
python
train
30.555556
nugget/python-insteonplm
insteonplm/plm.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L459-L465
def _get_next_all_link_record(self): """Request next ALL-Link record.""" _LOGGER.debug("Starting: _get_next_all_link_record") _LOGGER.debug("Requesting Next All-Link Record") msg = GetNextAllLinkRecord() self.send_msg(msg, wait_nak=True, wait_timeout=.5) _LOGGER.debug("En...
[ "def", "_get_next_all_link_record", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Starting: _get_next_all_link_record\"", ")", "_LOGGER", ".", "debug", "(", "\"Requesting Next All-Link Record\"", ")", "msg", "=", "GetNextAllLinkRecord", "(", ")", "self", "."...
Request next ALL-Link record.
[ "Request", "next", "ALL", "-", "Link", "record", "." ]
python
train
49.571429
oasis-open/cti-stix-validator
stix2validator/errors.py
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/errors.py#L71-L252
def pretty_error(error, verbose=False): """Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. """ error_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(...
[ "def", "pretty_error", "(", "error", ",", "verbose", "=", "False", ")", ":", "error_loc", "=", "''", "if", "error", ".", "path", ":", "while", "len", "(", "error", ".", "path", ")", ">", "0", ":", "path_elem", "=", "error", ".", "path", ".", "pople...
Return an error message that is easier to read and more useful. May require updating if the schemas change significantly.
[ "Return", "an", "error", "message", "that", "is", "easier", "to", "read", "and", "more", "useful", ".", "May", "require", "updating", "if", "the", "schemas", "change", "significantly", "." ]
python
train
54.010989
ptcryan/hydrawiser
hydrawiser/helpers.py
https://github.com/ptcryan/hydrawiser/blob/53acafb08b5cee0f6628414044b9b9f9a0b15e50/hydrawiser/helpers.py#L10-L34
def status_schedule(token): """ Returns the json string from the Hydrawise server after calling statusschedule.php. :param token: The users API token. :type token: string :returns: The response from the controller. If there was an error returns None. :rtype: string or None ...
[ "def", "status_schedule", "(", "token", ")", ":", "url", "=", "'https://app.hydrawise.com/api/v1/statusschedule.php'", "payload", "=", "{", "'api_key'", ":", "token", ",", "'hours'", ":", "168", "}", "get_response", "=", "requests", ".", "get", "(", "url", ",", ...
Returns the json string from the Hydrawise server after calling statusschedule.php. :param token: The users API token. :type token: string :returns: The response from the controller. If there was an error returns None. :rtype: string or None
[ "Returns", "the", "json", "string", "from", "the", "Hydrawise", "server", "after", "calling", "statusschedule", ".", "php", "." ]
python
train
26.2
jleinonen/pytmatrix
pytmatrix/psd.py
https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L455-L477
def save_scatter_table(self, fn, description=""): """Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the re...
[ "def", "save_scatter_table", "(", "self", ",", "fn", ",", "description", "=", "\"\"", ")", ":", "data", "=", "{", "\"description\"", ":", "description", ",", "\"time\"", ":", "datetime", ".", "now", "(", ")", ",", "\"psd_scatter\"", ":", "(", "self", "."...
Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the results of the computations are based only on the contents ...
[ "Save", "the", "scattering", "lookup", "tables", ".", "Save", "the", "state", "of", "the", "scattering", "lookup", "tables", "to", "a", "file", ".", "This", "can", "be", "loaded", "later", "with", "load_scatter_table", "." ]
python
train
40
LonamiWebs/Telethon
telethon/client/messages.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/messages.py#L612-L719
async def forward_messages(self, entity, messages, from_peer=None, *, silent=None, as_album=None): """ Forwards the given message(s) to the specified entity. Args: entity (`entity`): To which entity the message(s) will be forwarded. ...
[ "async", "def", "forward_messages", "(", "self", ",", "entity", ",", "messages", ",", "from_peer", "=", "None", ",", "*", ",", "silent", "=", "None", ",", "as_album", "=", "None", ")", ":", "single", "=", "not", "utils", ".", "is_list_like", "(", "mess...
Forwards the given message(s) to the specified entity. Args: entity (`entity`): To which entity the message(s) will be forwarded. messages (`list` | `int` | `Message <telethon.tl.custom.message.Message>`): The message(s) to forward, or their integer IDs....
[ "Forwards", "the", "given", "message", "(", "s", ")", "to", "the", "specified", "entity", "." ]
python
train
41.777778
dpkp/kafka-python
kafka/coordinator/base.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/coordinator/base.py#L713-L721
def generation(self): """Get the current generation state if the group is stable. Returns: the current generation or None if the group is unjoined/rebalancing """ with self._lock: if self.state is not MemberState.STABLE: return None return self._g...
[ "def", "generation", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "state", "is", "not", "MemberState", ".", "STABLE", ":", "return", "None", "return", "self", ".", "_generation" ]
Get the current generation state if the group is stable. Returns: the current generation or None if the group is unjoined/rebalancing
[ "Get", "the", "current", "generation", "state", "if", "the", "group", "is", "stable", "." ]
python
train
35.666667
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L435-L463
def match_term(self, value, required=True, new_group=False): """Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpe...
[ "def", "match_term", "(", "self", ",", "value", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "# If not the start of the query string, add an AND or OR", "if", "self", ".", "initialized", ":", "if", "required", ":", "self", ".", "_and_j...
Add a fulltext search term to the query. Warning: Do not use this method with any other query-building helpers. This method is only for building fulltext queries (in non-advanced mode). Using other helpers, such as ``match_field()``, will cause the query to run in advanced m...
[ "Add", "a", "fulltext", "search", "term", "to", "the", "query", "." ]
python
train
41.241379
cloud9ers/gurumate
environment/share/doc/ipython/examples/parallel/pi/pidigits.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/pi/pidigits.py#L134-L147
def plot_two_digit_freqs(f2): """ Plot two digits frequency counts using matplotlib. """ f2_copy = f2.copy() f2_copy.shape = (10,10) ax = plt.matshow(f2_copy) plt.colorbar() for i in range(10): for j in range(10): plt.text(i-0.2, j+0.2, str(j)+str(i)) plt.ylabel('...
[ "def", "plot_two_digit_freqs", "(", "f2", ")", ":", "f2_copy", "=", "f2", ".", "copy", "(", ")", "f2_copy", ".", "shape", "=", "(", "10", ",", "10", ")", "ax", "=", "plt", ".", "matshow", "(", "f2_copy", ")", "plt", ".", "colorbar", "(", ")", "fo...
Plot two digits frequency counts using matplotlib.
[ "Plot", "two", "digits", "frequency", "counts", "using", "matplotlib", "." ]
python
test
26.071429
Alignak-monitoring/alignak
alignak/basemodule.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L435-L457
def _main(self): """module "main" method. Only used by external modules. :return: None """ self.set_proctitle(self.name) self.set_signal_handler() logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid()) # Will block here! tr...
[ "def", "_main", "(", "self", ")", ":", "self", ".", "set_proctitle", "(", "self", ".", "name", ")", "self", ".", "set_signal_handler", "(", ")", "logger", ".", "info", "(", "\"process for module %s is now running (pid=%d)\"", ",", "self", ".", "name", ",", "...
module "main" method. Only used by external modules. :return: None
[ "module", "main", "method", ".", "Only", "used", "by", "external", "modules", "." ]
python
train
31.73913
Alignak-monitoring/alignak
alignak/action.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/action.py#L245-L262
def get_local_environnement(self): """ Mix the environment and the environment variables into a new local environment dictionary Note: We cannot just update the global os.environ because this would effect all other checks. :return: local environment variables :r...
[ "def", "get_local_environnement", "(", "self", ")", ":", "# Do not use copy.copy() here, as the resulting copy still", "# changes the real environment (it is still a os._Environment", "# instance).", "local_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "for", "local_v...
Mix the environment and the environment variables into a new local environment dictionary Note: We cannot just update the global os.environ because this would effect all other checks. :return: local environment variables :rtype: dict
[ "Mix", "the", "environment", "and", "the", "environment", "variables", "into", "a", "new", "local", "environment", "dictionary" ]
python
train
35.333333
brouberol/contexttimer
contexttimer/__init__.py
https://github.com/brouberol/contexttimer/blob/a866f420ed4c10f29abf252c58b11f9db6706100/contexttimer/__init__.py#L108-L141
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. """ ...
[ "def", "timer", "(", "logger", "=", "None", ",", "level", "=", "logging", ".", "INFO", ",", "fmt", "=", "\"function %(function_name)s execution time: %(execution_time).3f\"", ",", "*", "func_or_func_args", ",", "*", "*", "timer_kwargs", ")", ":", "# store Timer kwar...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor.
[ "Function", "decorator", "displaying", "the", "function", "execution", "time" ]
python
train
33.617647
noahbenson/neuropythy
neuropythy/io/core.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/io/core.py#L249-L267
def load_json(filename, to='auto'): ''' load_json(filename) yields the object represented by the json file or stream object filename. The optional argument to may be set to None to indicate that the JSON data should be returned verbatim rather than parsed by neuropythy's denormalize system. '''...
[ "def", "load_json", "(", "filename", ",", "to", "=", "'auto'", ")", ":", "from", "neuropythy", ".", "util", "import", "denormalize", "as", "denorm", "if", "pimms", ".", "is_str", "(", "filename", ")", ":", "try", ":", "with", "gzip", ".", "open", "(", ...
load_json(filename) yields the object represented by the json file or stream object filename. The optional argument to may be set to None to indicate that the JSON data should be returned verbatim rather than parsed by neuropythy's denormalize system.
[ "load_json", "(", "filename", ")", "yields", "the", "object", "represented", "by", "the", "json", "file", "or", "stream", "object", "filename", ".", "The", "optional", "argument", "to", "may", "be", "set", "to", "None", "to", "indicate", "that", "the", "JS...
python
train
40.473684
Telefonica/toolium
toolium/utils.py
https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/utils.py#L268-L284
def _expected_condition_value_in_element_attribute(self, element_attribute_value): """Tries to find the element and checks that it contains the requested attribute with the expected value, but does not thrown an exception if the element is not found :param element_attribute_value: Tuple with...
[ "def", "_expected_condition_value_in_element_attribute", "(", "self", ",", "element_attribute_value", ")", ":", "element", ",", "attribute", ",", "value", "=", "element_attribute_value", "web_element", "=", "self", ".", "_expected_condition_find_element", "(", "element", ...
Tries to find the element and checks that it contains the requested attribute with the expected value, but does not thrown an exception if the element is not found :param element_attribute_value: Tuple with 3 items where: [0] element: PageElement or element locator as a tuple (locator_ty...
[ "Tries", "to", "find", "the", "element", "and", "checks", "that", "it", "contains", "the", "requested", "attribute", "with", "the", "expected", "value", "but", "does", "not", "thrown", "an", "exception", "if", "the", "element", "is", "not", "found" ]
python
train
65.294118
WalletGuild/desw
desw/server.py
https://github.com/WalletGuild/desw/blob/f966c612e675961d9dbd8268749e349ba10a47c2/desw/server.py#L430-L453
def get_user(): """ Get your user object. Users may only get their own info, not others'. --- responses: '200': description: user response schema: $ref: '#/definitions/User' default: description: unexpected error schema: $ref: '#/defin...
[ "def", "get_user", "(", ")", ":", "userdict", "=", "json", ".", "loads", "(", "jsonify2", "(", "current_user", ".", "dbuser", ",", "'User'", ")", ")", "return", "current_app", ".", "bitjws", ".", "create_response", "(", "userdict", ")" ]
Get your user object. Users may only get their own info, not others'. --- responses: '200': description: user response schema: $ref: '#/definitions/User' default: description: unexpected error schema: $ref: '#/definitions/errorModel' descr...
[ "Get", "your", "user", "object", "." ]
python
train
23.875
knagra/farnsworth
base/views.py
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L305-L341
def my_profile_view(request): ''' The view of the profile page. ''' page_name = "Profile Page" if request.user.username == ANONYMOUS_USERNAME: return red_home(request, MESSAGES['SPINELESS']) userProfile = UserProfile.objects.get(user=request.user) change_password_form = PasswordChangeForm( ...
[ "def", "my_profile_view", "(", "request", ")", ":", "page_name", "=", "\"Profile Page\"", "if", "request", ".", "user", ".", "username", "==", "ANONYMOUS_USERNAME", ":", "return", "red_home", "(", "request", ",", "MESSAGES", "[", "'SPINELESS'", "]", ")", "user...
The view of the profile page.
[ "The", "view", "of", "the", "profile", "page", "." ]
python
train
44.162162
manns/pyspread
pyspread/src/actions/_grid_actions.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_actions.py#L942-L964
def selection_paste_data_gen(self, selection, data, freq=None): """Generator that yields data for selection paste""" (bb_top, bb_left), (bb_bottom, bb_right) = \ selection.get_grid_bbox(self.grid.code_array.shape) bbox_height = bb_bottom - bb_top + 1 bbox_width = bb_right - ...
[ "def", "selection_paste_data_gen", "(", "self", ",", "selection", ",", "data", ",", "freq", "=", "None", ")", ":", "(", "bb_top", ",", "bb_left", ")", ",", "(", "bb_bottom", ",", "bb_right", ")", "=", "selection", ".", "get_grid_bbox", "(", "self", ".", ...
Generator that yields data for selection paste
[ "Generator", "that", "yields", "data", "for", "selection", "paste" ]
python
train
41.130435
bird-house/twitcher
twitcher/api.py
https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/api.py#L107-L117
def revoke_all_tokens(self): """ Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`. """ try: self.store.clear_tokens() except Exception: LOGGER.exception('Failed to remove tokens.') return False else: re...
[ "def", "revoke_all_tokens", "(", "self", ")", ":", "try", ":", "self", ".", "store", ".", "clear_tokens", "(", ")", "except", "Exception", ":", "LOGGER", ".", "exception", "(", "'Failed to remove tokens.'", ")", "return", "False", "else", ":", "return", "Tru...
Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`.
[ "Implementation", "of", ":", "meth", ":", "twitcher", ".", "api", ".", "ITokenManager", ".", "revoke_all_tokens", "." ]
python
valid
29
PMEAL/OpenPNM
openpnm/utils/misc.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/misc.py#L359-L402
def conduit_lengths(network, throats=None, mode='pore'): r""" Return the respective lengths of the conduit components defined by the throat conns P1 T P2 mode = 'pore' - uses pore coordinates mode = 'centroid' uses pore and throat centroids """ if throats is None: throats = network.t...
[ "def", "conduit_lengths", "(", "network", ",", "throats", "=", "None", ",", "mode", "=", "'pore'", ")", ":", "if", "throats", "is", "None", ":", "throats", "=", "network", ".", "throats", "(", ")", "Ps", "=", "network", "[", "'throat.conns'", "]", "pdi...
r""" Return the respective lengths of the conduit components defined by the throat conns P1 T P2 mode = 'pore' - uses pore coordinates mode = 'centroid' uses pore and throat centroids
[ "r", "Return", "the", "respective", "lengths", "of", "the", "conduit", "components", "defined", "by", "the", "throat", "conns", "P1", "T", "P2", "mode", "=", "pore", "-", "uses", "pore", "coordinates", "mode", "=", "centroid", "uses", "pore", "and", "throa...
python
train
41.863636
langloisjp/tstore
tstore/pgtablestorage.py
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L398-L409
def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + ...
[ "def", "sqldelete", "(", "table", ",", "where", ")", ":", "validate_name", "(", "table", ")", "(", "whereclause", ",", "wherevalues", ")", "=", "sqlwhere", "(", "where", ")", "sql", "=", "\"delete from {}\"", ".", "format", "(", "table", ")", "if", "wher...
Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5])
[ "Generates", "SQL", "delete", "from", "...", "where", "..." ]
python
train
29.166667
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L3310-L3338
def image_export(cls, source_path, dest_url, **kwargs): """Export the specific image to remote host or local file system """ dest_path = urlparse.urlparse(dest_url).path if kwargs['remote_host']: target_path = ':'.join([kwargs['remote_host'], dest_path]) command = ' '.joi...
[ "def", "image_export", "(", "cls", ",", "source_path", ",", "dest_url", ",", "*", "*", "kwargs", ")", ":", "dest_path", "=", "urlparse", ".", "urlparse", "(", "dest_url", ")", ".", "path", "if", "kwargs", "[", "'remote_host'", "]", ":", "target_path", "=...
Export the specific image to remote host or local file system
[ "Export", "the", "specific", "image", "to", "remote", "host", "or", "local", "file", "system" ]
python
train
51.517241
project-rig/rig
rig/machine_control/machine_controller.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L966-L982
def iptag_get(self, iptag, x, y): """Get the value of an IPTag. Parameters ---------- iptag : int Index of the IPTag to get Returns ------- :py:class:`.IPTag` The IPTag returned from SpiNNaker. """ ack = self._send_scp(x, ...
[ "def", "iptag_get", "(", "self", ",", "iptag", ",", "x", ",", "y", ")", ":", "ack", "=", "self", ".", "_send_scp", "(", "x", ",", "y", ",", "0", ",", "SCPCommands", ".", "iptag", ",", "int", "(", "consts", ".", "IPTagCommands", ".", "get", ")", ...
Get the value of an IPTag. Parameters ---------- iptag : int Index of the IPTag to get Returns ------- :py:class:`.IPTag` The IPTag returned from SpiNNaker.
[ "Get", "the", "value", "of", "an", "IPTag", "." ]
python
train
29.294118
rikrd/inspire
inspirespeech/htk.py
https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk.py#L175-L188
def load_parameter(input_filename, only_header=False): """Load HTK parameter/feature file. :param input_filename: :param only_header: only load the metadata :return: a named tuple representing the HTK parmeter file """ with open(input_filename, 'rb') as f: meta = _parse_parameter_meta(...
[ "def", "load_parameter", "(", "input_filename", ",", "only_header", "=", "False", ")", ":", "with", "open", "(", "input_filename", ",", "'rb'", ")", "as", "f", ":", "meta", "=", "_parse_parameter_meta", "(", "f", ")", "if", "only_header", ":", "return", "m...
Load HTK parameter/feature file. :param input_filename: :param only_header: only load the metadata :return: a named tuple representing the HTK parmeter file
[ "Load", "HTK", "parameter", "/", "feature", "file", "." ]
python
train
29.071429
etalab/cada
cada/commands.py
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L87-L92
def error(msg, details=None, *args, **kwargs): '''Display an error message with optionnal details''' msg = '{0} {1}'.format(red(KO), white(msg)) if details: msg = '\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg), *args, **kwargs)
[ "def", "error", "(", "msg", ",", "details", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "'{0} {1}'", ".", "format", "(", "red", "(", "KO", ")", ",", "white", "(", "msg", ")", ")", "if", "details", ":", "msg", ...
Display an error message with optionnal details
[ "Display", "an", "error", "message", "with", "optionnal", "details" ]
python
train
44.333333
tchellomello/python-arlo
pyarlo/base_station.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L371-L379
def get_available_modes(self): """Return a list of available mode objects for an Arlo user.""" resource = "modes" resource_event = self.publish_and_get_event(resource) if resource_event: properties = resource_event.get("properties") return properties.get("modes") ...
[ "def", "get_available_modes", "(", "self", ")", ":", "resource", "=", "\"modes\"", "resource_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "resource_event", ":", "properties", "=", "resource_event", ".", "get", "(", "\"properties\"...
Return a list of available mode objects for an Arlo user.
[ "Return", "a", "list", "of", "available", "mode", "objects", "for", "an", "Arlo", "user", "." ]
python
train
36.888889
vijaykatam/django-cache-manager
django_cache_manager/models.py
https://github.com/vijaykatam/django-cache-manager/blob/05142c44eb349d3f24f962592945888d9d367375/django_cache_manager/models.py#L57-L72
def invalidate_m2m_cache(sender, instance, model, **kwargs): """ Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The c...
[ "def", "invalidate_m2m_cache", "(", "sender", ",", "instance", ",", "model", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Received m2m_changed signals from sender {0}'", ".", "format", "(", "sender", ")", ")", "update_model_cache", "(", "ins...
Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The class of the objects that are added to, removed from or cleared from the r...
[ "Signal", "receiver", "for", "models", "to", "invalidate", "model", "cache", "for", "many", "-", "to", "-", "many", "relationship", "." ]
python
train
35.4375
programa-stic/barf-project
barf/core/reil/builder.py
https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L90-L95
def gen_and(src1, src2, dst): """Return an AND instruction. """ assert src1.size == src2.size return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst)
[ "def", "gen_and", "(", "src1", ",", "src2", ",", "dst", ")", ":", "assert", "src1", ".", "size", "==", "src2", ".", "size", "return", "ReilBuilder", ".", "build", "(", "ReilMnemonic", ".", "AND", ",", "src1", ",", "src2", ",", "dst", ")" ]
Return an AND instruction.
[ "Return", "an", "AND", "instruction", "." ]
python
train
30.166667
genialis/resolwe-runtime-utils
resolwe_runtime_utils.py
https://github.com/genialis/resolwe-runtime-utils/blob/5657d7cf981972a5259b9b475eae220479401001/resolwe_runtime_utils.py#L259-L302
def checkrc(rc, *args): """Check if ``rc`` (return code) meets requirements. Check if ``rc`` is 0 or is in ``args`` list that contains acceptable return codes. Last argument of ``args`` can optionally be error message that is printed if ``rc`` doesn't meet requirements. Output is JSON of the f...
[ "def", "checkrc", "(", "rc", ",", "*", "args", ")", ":", "try", ":", "rc", "=", "int", "(", "rc", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "error", "(", "\"Invalid return code: '{}'.\"", ".", "format", "(", "rc", ")", "...
Check if ``rc`` (return code) meets requirements. Check if ``rc`` is 0 or is in ``args`` list that contains acceptable return codes. Last argument of ``args`` can optionally be error message that is printed if ``rc`` doesn't meet requirements. Output is JSON of the form: {"proc.rc": <rc>,...
[ "Check", "if", "rc", "(", "return", "code", ")", "meets", "requirements", "." ]
python
train
25.227273
aiortc/aioice
aioice/ice.py
https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L77-L86
def sort_candidate_pairs(pairs, ice_controlling): """ Sort a list of candidate pairs. """ def pair_priority(pair): return -candidate_pair_priority(pair.local_candidate, pair.remote_candidate, ice_controlling) pa...
[ "def", "sort_candidate_pairs", "(", "pairs", ",", "ice_controlling", ")", ":", "def", "pair_priority", "(", "pair", ")", ":", "return", "-", "candidate_pair_priority", "(", "pair", ".", "local_candidate", ",", "pair", ".", "remote_candidate", ",", "ice_controlling...
Sort a list of candidate pairs.
[ "Sort", "a", "list", "of", "candidate", "pairs", "." ]
python
train
33.8
beylsp/unisquid
unisquid/liveserver.py
https://github.com/beylsp/unisquid/blob/880787a2b6c9051b7f82a7f721434819984003e2/unisquid/liveserver.py#L29-L59
def run(self): """ Sets up live server, and then loops over handling http requests. """ try: # Go through the list of possible ports, hoping we can find # one that is free to use for the WSGI server. for index, port in enumerate(self.possible_ports): ...
[ "def", "run", "(", "self", ")", ":", "try", ":", "# Go through the list of possible ports, hoping we can find", "# one that is free to use for the WSGI server.", "for", "index", ",", "port", "in", "enumerate", "(", "self", ".", "possible_ports", ")", ":", "try", ":", ...
Sets up live server, and then loops over handling http requests.
[ "Sets", "up", "live", "server", "and", "then", "loops", "over", "handling", "http", "requests", "." ]
python
train
41.193548
mikedh/trimesh
trimesh/creation.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/creation.py#L526-L548
def icosahedron(): """ Create an icosahedron, a 20 faced polyhedron. Returns ------------- ico : trimesh.Trimesh Icosahederon centered at the origin. """ t = (1.0 + 5.0**.5) / 2.0 vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, ...
[ "def", "icosahedron", "(", ")", ":", "t", "=", "(", "1.0", "+", "5.0", "**", ".5", ")", "/", "2.0", "vertices", "=", "[", "-", "1", ",", "t", ",", "0", ",", "1", ",", "t", ",", "0", ",", "-", "1", ",", "-", "t", ",", "0", ",", "1", ",...
Create an icosahedron, a 20 faced polyhedron. Returns ------------- ico : trimesh.Trimesh Icosahederon centered at the origin.
[ "Create", "an", "icosahedron", "a", "20", "faced", "polyhedron", "." ]
python
train
37.347826
bcbio/bcbio-nextgen
bcbio/structural/cnvkit.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L100-L110
def _run_cnvkit_single(data, background=None): """Process a single input file with BAM or uniform background. """ if not background: background = [] ckouts = _run_cnvkit_shared([data], background) if not ckouts: return [data] else: assert len(ckouts) == 1 return _...
[ "def", "_run_cnvkit_single", "(", "data", ",", "background", "=", "None", ")", ":", "if", "not", "background", ":", "background", "=", "[", "]", "ckouts", "=", "_run_cnvkit_shared", "(", "[", "data", "]", ",", "background", ")", "if", "not", "ckouts", ":...
Process a single input file with BAM or uniform background.
[ "Process", "a", "single", "input", "file", "with", "BAM", "or", "uniform", "background", "." ]
python
train
31.454545
pazz/alot
alot/helper.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/helper.py#L579-L596
def RFC3156_canonicalize(text): """ Canonicalizes plain text (MIME-encoded usually) according to RFC3156. This function works as follows (in that order): 1. Convert all line endings to \\\\r\\\\n (DOS line endings). 2. Encode all occurrences of "From " at the beginning of a line to "From=20...
[ "def", "RFC3156_canonicalize", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "\"\\r?\\n\"", ",", "\"\\r\\n\"", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "\"^From \"", ",", "\"From=20\"", ",", "text", ",", "flags", "=", "re", ...
Canonicalizes plain text (MIME-encoded usually) according to RFC3156. This function works as follows (in that order): 1. Convert all line endings to \\\\r\\\\n (DOS line endings). 2. Encode all occurrences of "From " at the beginning of a line to "From=20" in order to prevent other mail programs to...
[ "Canonicalizes", "plain", "text", "(", "MIME", "-", "encoded", "usually", ")", "according", "to", "RFC3156", "." ]
python
train
37.333333
wummel/linkchecker
third_party/dnspython/dns/zone.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/zone.py#L764-L818
def from_file(f, origin = None, rdclass = dns.rdataclass.IN, relativize = True, zone_factory=Zone, filename=None, allow_include=True, check_origin=True): """Read a master file and build a zone object. @param f: file or string. If I{f} is a string, it is treated as the name of a...
[ "def", "from_file", "(", "f", ",", "origin", "=", "None", ",", "rdclass", "=", "dns", ".", "rdataclass", ".", "IN", ",", "relativize", "=", "True", ",", "zone_factory", "=", "Zone", ",", "filename", "=", "None", ",", "allow_include", "=", "True", ",", ...
Read a master file and build a zone object. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @param origin: The origin of the zone; if not specified, the first $ORIGIN statement in the master file will determine the origin of the zone. @type origin: d...
[ "Read", "a", "master", "file", "and", "build", "a", "zone", "object", "." ]
python
train
36.290909
Microsoft/botbuilder-python
libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py#L36-L47
def add_step(self, step): """ Adds a new step to the waterfall. :param step: Step to add :return: Waterfall dialog for fluent calls to `add_step()`. """ if not step: raise TypeError('WaterfallDialog.add_step(): step cannot be None.') self....
[ "def", "add_step", "(", "self", ",", "step", ")", ":", "if", "not", "step", ":", "raise", "TypeError", "(", "'WaterfallDialog.add_step(): step cannot be None.'", ")", "self", ".", "_steps", ".", "append", "(", "step", ")", "return", "self" ]
Adds a new step to the waterfall. :param step: Step to add :return: Waterfall dialog for fluent calls to `add_step()`.
[ "Adds", "a", "new", "step", "to", "the", "waterfall", ".", ":", "param", "step", ":", "Step", "to", "add", ":", "return", ":", "Waterfall", "dialog", "for", "fluent", "calls", "to", "add_step", "()", "." ]
python
test
29
saltstack/salt
salt/states/webutil.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L107-L150
def user_absent(name, htpasswd_file=None, runas=None): ''' Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with ''' ret = {'name': name, 'chang...
[ "def", "user_absent", "(", "name", ",", "htpasswd_file", "=", "None", ",", "runas", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "None", "}", "exi...
Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with
[ "Make", "sure", "the", "user", "is", "not", "in", "the", "specified", "htpasswd", "file" ]
python
train
26.5
b3j0f/utils
b3j0f/utils/runtime.py
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L315-L355
def bind_all(morc, builtin_only=False, stoplist=None, verbose=None): """Recursively apply constant binding to functions in a module or class. Use as the last line of the module (after everything is defined, but before test code). In modules that need modifiable globals, set builtin_only to True. :...
[ "def", "bind_all", "(", "morc", ",", "builtin_only", "=", "False", ",", "stoplist", "=", "None", ",", "verbose", "=", "None", ")", ":", "if", "stoplist", "is", "None", ":", "stoplist", "=", "[", "]", "def", "_bind_all", "(", "morc", ",", "builtin_only"...
Recursively apply constant binding to functions in a module or class. Use as the last line of the module (after everything is defined, but before test code). In modules that need modifiable globals, set builtin_only to True. :param morc: module or class to transform. :param bool builtin_only: only...
[ "Recursively", "apply", "constant", "binding", "to", "functions", "in", "a", "module", "or", "class", "." ]
python
train
39.853659
sdispater/orator
orator/orm/relations/relation.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/relation.py#L116-L134
def no_constraints(cls, with_subclasses=False): """ Runs a callback with constraints disabled on the relation. """ cls._constraints = False if with_subclasses: for klass in cls.__subclasses__(): klass._constraints = False try: yie...
[ "def", "no_constraints", "(", "cls", ",", "with_subclasses", "=", "False", ")", ":", "cls", ".", "_constraints", "=", "False", "if", "with_subclasses", ":", "for", "klass", "in", "cls", ".", "__subclasses__", "(", ")", ":", "klass", ".", "_constraints", "=...
Runs a callback with constraints disabled on the relation.
[ "Runs", "a", "callback", "with", "constraints", "disabled", "on", "the", "relation", "." ]
python
train
28.105263
google/mobly
mobly/controllers/android_device_lib/event_dispatcher.py
https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L121-L135
def start(self): """Starts the event dispatcher. Initiates executor and start polling events. Raises: IllegalStateError: Can't start a dispatcher again when it's already running. """ if not self.started: self.started = True se...
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "started", ":", "self", ".", "started", "=", "True", "self", ".", "executor", "=", "ThreadPoolExecutor", "(", "max_workers", "=", "32", ")", "self", ".", "poller", "=", "self", ".", "ex...
Starts the event dispatcher. Initiates executor and start polling events. Raises: IllegalStateError: Can't start a dispatcher again when it's already running.
[ "Starts", "the", "event", "dispatcher", "." ]
python
train
33.533333
SHDShim/pytheos
pytheos/scales/objs.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/scales/objs.py#L338-L350
def _hugoniot_p(self, v): """ calculate static pressure at 300 K. :param v: unit-cell volume in A^3 :return: static pressure at t_ref (=300 K) in GPa """ rho = self._get_rho(v) params = self._set_params(self.params_hugoniot) if self.nonlinear: ...
[ "def", "_hugoniot_p", "(", "self", ",", "v", ")", ":", "rho", "=", "self", ".", "_get_rho", "(", "v", ")", "params", "=", "self", ".", "_set_params", "(", "self", ".", "params_hugoniot", ")", "if", "self", ".", "nonlinear", ":", "return", "hugoniot_p_n...
calculate static pressure at 300 K. :param v: unit-cell volume in A^3 :return: static pressure at t_ref (=300 K) in GPa
[ "calculate", "static", "pressure", "at", "300", "K", "." ]
python
train
31
dropbox/stone
stone/backends/python_client.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_client.py#L307-L343
def _generate_route_method_decl( self, namespace, route, arg_data_type, request_binary_body, method_name_suffix='', extra_args=None): """Generates the method prototype for a route.""" args = ['self'] if extra_args: args += extra_args if request_binary_...
[ "def", "_generate_route_method_decl", "(", "self", ",", "namespace", ",", "route", ",", "arg_data_type", ",", "request_binary_body", ",", "method_name_suffix", "=", "''", ",", "extra_args", "=", "None", ")", ":", "args", "=", "[", "'self'", "]", "if", "extra_a...
Generates the method prototype for a route.
[ "Generates", "the", "method", "prototype", "for", "a", "route", "." ]
python
train
48.351351
zyga/python-glibc
pyglibc/select.py
https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/pyglibc/select.py#L160-L181
def fromfd(cls, fd): """ Create a new epoll object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``epoll_create(2)`` or ``epoll_create1(2)`` :raises ValueError: If fd is not a valid file descriptor :returns: ...
[ "def", "fromfd", "(", "cls", ",", "fd", ")", ":", "if", "fd", "<", "0", ":", "_err_closed", "(", ")", "self", "=", "cls", ".", "__new__", "(", ")", "object", ".", "__init__", "(", "self", ")", "self", ".", "_epfd", "=", "fd", "return", "self" ]
Create a new epoll object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``epoll_create(2)`` or ``epoll_create1(2)`` :raises ValueError: If fd is not a valid file descriptor :returns: A new epoll object ....
[ "Create", "a", "new", "epoll", "object", "from", "a", "given", "file", "descriptor" ]
python
train
29.454545
mseclab/PyJFuzz
gramfuzz/gramfuzz/fields.py
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L385-L411
def build(self, pre=None, shortest=False): """Build the ``Join`` field instance. :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: ...
[ "def", "build", "(", "self", ",", "pre", "=", "None", ",", "shortest", "=", "False", ")", ":", "if", "pre", "is", "None", ":", "pre", "=", "[", "]", "if", "self", ".", "max", "is", "not", "None", ":", "if", "shortest", ":", "vals", "=", "[", ...
Build the ``Join`` field instance. :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
[ "Build", "the", "Join", "field", "instance", ".", ":", "param", "list", "pre", ":", "The", "prerequisites", "list", ":", "param", "bool", "shortest", ":", "Whether", "or", "not", "the", "shortest", "reference", "-", "chain", "(", "most", "minimal", ")", ...
python
test
30.962963
fjwCode/cerium
cerium/androiddriver.py
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L458-L463
def app_broadcast(self, *args) -> None: '''Send a broadcast.''' _, error = self._execute('-s', self.device_sn, 'shell', 'am', 'broadcast', *args) if error: raise ApplicationsException(error.split(':', 1)[-1].strip())
[ "def", "app_broadcast", "(", "self", ",", "*", "args", ")", "->", "None", ":", "_", ",", "error", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'am'", ",", "'broadcast'", ",", "*", "args", ")", "if"...
Send a broadcast.
[ "Send", "a", "broadcast", "." ]
python
train
46.666667
Erotemic/utool
utool/util_graph.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_graph.py#L354-L558
def nx_edges_between(graph, nodes1, nodes2=None, assume_disjoint=False, assume_sparse=True): r""" Get edges between two components or within a single component Args: graph (nx.Graph): the graph nodes1 (set): list of nodes nodes2 (set): (default=None) if None it ...
[ "def", "nx_edges_between", "(", "graph", ",", "nodes1", ",", "nodes2", "=", "None", ",", "assume_disjoint", "=", "False", ",", "assume_sparse", "=", "True", ")", ":", "if", "assume_sparse", ":", "# Method 1 is where we check the intersection of existing edges", "# and...
r""" Get edges between two components or within a single component Args: graph (nx.Graph): the graph nodes1 (set): list of nodes nodes2 (set): (default=None) if None it is equivlanet to nodes2=nodes1 assume_disjoint (bool): skips expensive check to ensure edges arnt ...
[ "r", "Get", "edges", "between", "two", "components", "or", "within", "a", "single", "component" ]
python
train
41.780488
gem/oq-engine
openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py#L135-L163
def plot_trunc_gr_model( aval, bval, min_mag, max_mag, dmag, catalogue=None, completeness=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Plots a Gutenberg-Richter model """ input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval) if no...
[ "def", "plot_trunc_gr_model", "(", "aval", ",", "bval", ",", "min_mag", ",", "max_mag", ",", "dmag", ",", "catalogue", "=", "None", ",", "completeness", "=", "None", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", ...
Plots a Gutenberg-Richter model
[ "Plots", "a", "Gutenberg", "-", "Richter", "model" ]
python
train
38.862069
kubernetes-client/python
kubernetes/client/apis/core_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L13242-L13268
def list_node(self, **kwargs): """ list or watch objects of kind Node This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_node(async_req=True) >>> result = thread.get() :p...
[ "def", "list_node", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_node_with_http_info", "(", "*", "*", "...
list or watch objects of kind Node This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_node(async_req=True) >>> result = thread.get() :param async_req bool :param str pretty: If '...
[ "list", "or", "watch", "objects", "of", "kind", "Node", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread"...
python
train
164.703704
tensorflow/lucid
lucid/optvis/objectives.py
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L396-L425
def diversity(layer): """Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates th...
[ "def", "diversity", "(", "layer", ")", ":", "def", "inner", "(", "T", ")", ":", "layer_t", "=", "T", "(", "layer", ")", "batch_n", ",", "_", ",", "_", ",", "channels", "=", "layer_t", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "flatten...
Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates the correlation matrix of act...
[ "Encourage", "diversity", "between", "each", "batch", "element", "." ]
python
train
36.566667
gem/oq-engine
openquake/hazardlib/sourcewriter.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L104-L123
def build_simple_fault_geometry(fault_source): """ Returns the simple fault source geometry as a Node :param fault_source: Simple fault source model as an instance of the :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` :returns: Instance of :class:`openquake....
[ "def", "build_simple_fault_geometry", "(", "fault_source", ")", ":", "linestring_node", "=", "build_linestring_node", "(", "fault_source", ".", "fault_trace", ",", "with_depth", "=", "False", ")", "dip_node", "=", "Node", "(", "\"dip\"", ",", "text", "=", "fault_s...
Returns the simple fault source geometry as a Node :param fault_source: Simple fault source model as an instance of the :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Returns", "the", "simple", "fault", "source", "geometry", "as", "a", "Node" ]
python
train
42.9
bububa/pyTOP
pyTOP/packages/requests/utils.py
https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/utils.py#L262-L276
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. """ content_type = headers.get('content-type') if not content_type: return None content_type, params = cgi.parse_header(content_type) if...
[ "def", "get_encoding_from_headers", "(", "headers", ")", ":", "content_type", "=", "headers", ".", "get", "(", "'content-type'", ")", "if", "not", "content_type", ":", "return", "None", "content_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "cont...
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from.
[ "Returns", "encodings", "from", "given", "HTTP", "Header", "Dict", "." ]
python
train
24.866667
sosy-lab/benchexec
benchexec/benchexec.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/benchexec.py#L304-L312
def check_existing_results(self, benchmark): """ Check and abort if the target directory for the benchmark results already exists in order to avoid overwriting results. """ if os.path.exists(benchmark.log_folder): sys.exit('Output directory {0} already exists, will no...
[ "def", "check_existing_results", "(", "self", ",", "benchmark", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "benchmark", ".", "log_folder", ")", ":", "sys", ".", "exit", "(", "'Output directory {0} already exists, will not overwrite existing results.'", "...
Check and abort if the target directory for the benchmark results already exists in order to avoid overwriting results.
[ "Check", "and", "abort", "if", "the", "target", "directory", "for", "the", "benchmark", "results", "already", "exists", "in", "order", "to", "avoid", "overwriting", "results", "." ]
python
train
60
signalfx/signalfx-python
signalfx/rest.py
https://github.com/signalfx/signalfx-python/blob/650eb9a2b301bcc795e4e3a8c031574ade69849d/signalfx/rest.py#L201-L215
def search_dimensions(self, *args, **kwargs): """ Args: query (string): elasticsearch string query order_by (optional[string]): property by which to order results offset (optional[int]): number of results to skip for pagination (default=0) ...
[ "def", "search_dimensions", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_search_metrics_and_metadata", "(", "self", ".", "_DIMENSION_ENDPOINT_SUFFIX", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Args: query (string): elasticsearch string query order_by (optional[string]): property by which to order results offset (optional[int]): number of results to skip for pagination (default=0) limit (optional[int]): how many results to return (default=50) ...
[ "Args", ":", "query", "(", "string", ")", ":", "elasticsearch", "string", "query", "order_by", "(", "optional", "[", "string", "]", ")", ":", "property", "by", "which", "to", "order", "results", "offset", "(", "optional", "[", "int", "]", ")", ":", "nu...
python
train
42.6
gwastro/pycbc-glue
pycbc_glue/ligolw/table.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L463-L471
def index(self, value): """ Return the smallest index of the row(s) with this column equal to value. """ for i in xrange(len(self.parentNode)): if getattr(self.parentNode[i], self.Name) == value: return i raise ValueError(value)
[ "def", "index", "(", "self", ",", "value", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "parentNode", ")", ")", ":", "if", "getattr", "(", "self", ".", "parentNode", "[", "i", "]", ",", "self", ".", "Name", ")", "==", "va...
Return the smallest index of the row(s) with this column equal to value.
[ "Return", "the", "smallest", "index", "of", "the", "row", "(", "s", ")", "with", "this", "column", "equal", "to", "value", "." ]
python
train
26.555556
Richienb/quilt
src/quilt_lang/__init__.py
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1200-L1228
def amountdiv(number, minnum, maxnum): """ Get the amount of numbers divisable by a number. :type number: number :param number: The number to use. :type minnum: integer :param minnum: The minimum number to check. :type maxnum: integer :param maxnum: The maximum number to check. >...
[ "def", "amountdiv", "(", "number", ",", "minnum", ",", "maxnum", ")", ":", "# Set the amount to 0", "amount", "=", "0", "# For each item in range of minimum and maximum", "for", "i", "in", "range", "(", "minnum", ",", "maxnum", "+", "1", ")", ":", "# If the rema...
Get the amount of numbers divisable by a number. :type number: number :param number: The number to use. :type minnum: integer :param minnum: The minimum number to check. :type maxnum: integer :param maxnum: The maximum number to check. >>> amountdiv(20, 1, 15) 5
[ "Get", "the", "amount", "of", "numbers", "divisable", "by", "a", "number", "." ]
python
train
22.517241
saltstack/salt
salt/cloud/clouds/digitalocean.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L103-L121
def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locat...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "items", "=", "quer...
Return a dict of all available VM locations on the cloud provider with relevant data
[ "Return", "a", "dict", "of", "all", "available", "VM", "locations", "on", "the", "cloud", "provider", "with", "relevant", "data" ]
python
train
29.947368
thespacedoctor/fundamentals
fundamentals/mysql/writequery.py
https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/writequery.py#L20-L191
def writequery( log, sqlQuery, dbConn, Force=False, manyValueList=False ): """*Execute a MySQL write command given a sql query* **Key Arguments:** - ``sqlQuery`` -- the MySQL command to execute - ``dbConn`` -- the db connection - ``Force`` -- do not exit code if erro...
[ "def", "writequery", "(", "log", ",", "sqlQuery", ",", "dbConn", ",", "Force", "=", "False", ",", "manyValueList", "=", "False", ")", ":", "log", ".", "debug", "(", "'starting the ``writequery`` function'", ")", "import", "pymysql", "import", "warnings", "warn...
*Execute a MySQL write command given a sql query* **Key Arguments:** - ``sqlQuery`` -- the MySQL command to execute - ``dbConn`` -- the db connection - ``Force`` -- do not exit code if error occurs, move onto the next command - ``manyValueList`` -- a list of value tuples if executin...
[ "*", "Execute", "a", "MySQL", "write", "command", "given", "a", "sql", "query", "*" ]
python
train
33.959302
markovmodel/PyEMMA
pyemma/msm/api.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L1480-L1623
def tpt(msmobj, A, B): r""" A->B reactive flux from transition path theory (TPT) The returned :class:`ReactiveFlux <pyemma.msm.models.ReactiveFlux>` object can be used to extract various quantities of the flux, as well as to compute A -> B transition pathways, their weights, and to coarse-grain the...
[ "def", "tpt", "(", "msmobj", ",", "A", ",", "B", ")", ":", "from", "msmtools", ".", "flux", "import", "flux_matrix", ",", "to_netflux", "import", "msmtools", ".", "analysis", "as", "msmana", "T", "=", "msmobj", ".", "transition_matrix", "mu", "=", "msmob...
r""" A->B reactive flux from transition path theory (TPT) The returned :class:`ReactiveFlux <pyemma.msm.models.ReactiveFlux>` object can be used to extract various quantities of the flux, as well as to compute A -> B transition pathways, their weights, and to coarse-grain the flux onto sets of states. ...
[ "r", "A", "-", ">", "B", "reactive", "flux", "from", "transition", "path", "theory", "(", "TPT", ")" ]
python
train
34.361111
pyBookshelf/bookshelf
bookshelf/api_v2/os_helpers.py
https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v2/os_helpers.py#L12-L24
def add_usr_local_bin_to_path(log=False): """ adds /usr/local/bin to $PATH """ if log: bookshelf2.logging_helpers.log_green('inserts /usr/local/bin into PATH') with settings(hide('warnings', 'running', 'stdout', 'stderr'), capture=True): try: sudo('echo "export...
[ "def", "add_usr_local_bin_to_path", "(", "log", "=", "False", ")", ":", "if", "log", ":", "bookshelf2", ".", "logging_helpers", ".", "log_green", "(", "'inserts /usr/local/bin into PATH'", ")", "with", "settings", "(", "hide", "(", "'warnings'", ",", "'running'", ...
adds /usr/local/bin to $PATH
[ "adds", "/", "usr", "/", "local", "/", "bin", "to", "$PATH" ]
python
train
36.538462
aws/sagemaker-python-sdk
src/sagemaker/vpc_utils.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/vpc_utils.py#L44-L64
def from_dict(vpc_config, do_sanitize=False): """ Extracts subnets and security group ids as lists from a VpcConfig dict Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values ...
[ "def", "from_dict", "(", "vpc_config", ",", "do_sanitize", "=", "False", ")", ":", "if", "do_sanitize", ":", "vpc_config", "=", "sanitize", "(", "vpc_config", ")", "if", "vpc_config", "is", "None", ":", "return", "None", ",", "None", "return", "vpc_config", ...
Extracts subnets and security group ids as lists from a VpcConfig dict Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values Returns: Tuple of lists as (subnets, security...
[ "Extracts", "subnets", "and", "security", "group", "ids", "as", "lists", "from", "a", "VpcConfig", "dict" ]
python
train
36.857143