repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
lago-project/lago
lago/lago_ansible.py
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/lago_ansible.py#L144-L167
def get_inventory_temp_file(self, keys=None): """ Context manager which returns the inventory written on a tempfile. The tempfile will be deleted as soon as this context manger ends. Args: keys (list of str): Path to the keys that will be used to create group...
[ "def", "get_inventory_temp_file", "(", "self", ",", "keys", "=", "None", ")", ":", "temp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'r+t'", ")", "inventory", "=", "self", ".", "get_inventory_str", "(", "keys", ")", "LOGGER", ".", ...
Context manager which returns the inventory written on a tempfile. The tempfile will be deleted as soon as this context manger ends. Args: keys (list of str): Path to the keys that will be used to create groups. Yields: tempfile.NamedTemporaryFile: Temp ...
[ "Context", "manager", "which", "returns", "the", "inventory", "written", "on", "a", "tempfile", ".", "The", "tempfile", "will", "be", "deleted", "as", "soon", "as", "this", "context", "manger", "ends", "." ]
python
train
Microsoft/ApplicationInsights-Python
applicationinsights/channel/contracts/Device.py
https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/Device.py#L128-L137
def os_version(self, value): """The os_version property. Args: value (string). the property value. """ if value == self._defaults['ai.device.osVersion'] and 'ai.device.osVersion' in self._values: del self._values['ai.device.osVersion'] else: ...
[ "def", "os_version", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'ai.device.osVersion'", "]", "and", "'ai.device.osVersion'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'ai.device.osV...
The os_version property. Args: value (string). the property value.
[ "The", "os_version", "property", ".", "Args", ":", "value", "(", "string", ")", ".", "the", "property", "value", "." ]
python
train
authomatic/liveandletdie
liveandletdie/__init__.py
https://github.com/authomatic/liveandletdie/blob/bf3bcdbd679452ec7c248e9910d85c7fcdca586b/liveandletdie/__init__.py#L87-L143
def port_in_use(port, kill=False, logging=False): """ Checks whether a port is free or not. :param int port: The port number to check for. :param bool kill: If ``True`` the process will be killed. :returns: The process id as :class:`int` if in use, otherwis...
[ "def", "port_in_use", "(", "port", ",", "kill", "=", "False", ",", "logging", "=", "False", ")", ":", "command_template", "=", "'lsof -iTCP:{0} -sTCP:LISTEN'", "process", "=", "subprocess", ".", "Popen", "(", "command_template", ".", "format", "(", "port", ")"...
Checks whether a port is free or not. :param int port: The port number to check for. :param bool kill: If ``True`` the process will be killed. :returns: The process id as :class:`int` if in use, otherwise ``False`` .
[ "Checks", "whether", "a", "port", "is", "free", "or", "not", ".", ":", "param", "int", "port", ":", "The", "port", "number", "to", "check", "for", ".", ":", "param", "bool", "kill", ":", "If", "True", "the", "process", "will", "be", "killed", ".", ...
python
train
timofurrer/tag-expressions
tagexpressions/models.py
https://github.com/timofurrer/tag-expressions/blob/9b58c34296b31530f31517ffefc8715516c73da3/tagexpressions/models.py#L34-L40
def evaluate(self, values): """Evaluate the "OR" expression Check if the left "or" right expression evaluate to True. """ return self.left.evaluate(values) or self.right.evaluate(values)
[ "def", "evaluate", "(", "self", ",", "values", ")", ":", "return", "self", ".", "left", ".", "evaluate", "(", "values", ")", "or", "self", ".", "right", ".", "evaluate", "(", "values", ")" ]
Evaluate the "OR" expression Check if the left "or" right expression evaluate to True.
[ "Evaluate", "the", "OR", "expression" ]
python
train
fracpete/python-weka-wrapper3
python/weka/flow/source.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/source.py#L598-L611
def to_config(self, k, v): """ Hook method that allows conversion of individual options. :param k: the key of the option :type k: str :param v: the value :type v: object :return: the potentially processed value :rtype: object """ if k == "...
[ "def", "to_config", "(", "self", ",", "k", ",", "v", ")", ":", "if", "k", "==", "\"setup\"", ":", "return", "base", ".", "to_commandline", "(", "v", ")", "return", "super", "(", "DataGenerator", ",", "self", ")", ".", "to_config", "(", "k", ",", "v...
Hook method that allows conversion of individual options. :param k: the key of the option :type k: str :param v: the value :type v: object :return: the potentially processed value :rtype: object
[ "Hook", "method", "that", "allows", "conversion", "of", "individual", "options", "." ]
python
train
corpusops/pdbclone
lib/pdb_clone/bootstrappdb_gdb.py
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bootstrappdb_gdb.py#L80-L103
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') ...
[ "def", "get_curline", "(", ")", ":", "if", "Frame", ":", "frame", "=", "Frame", ".", "get_selected_python_frame", "(", ")", "if", "frame", ":", "line", "=", "''", "f", "=", "frame", ".", "get_pyop", "(", ")", "if", "f", "and", "not", "f", ".", "is_...
Return the current python source line.
[ "Return", "the", "current", "python", "source", "line", "." ]
python
train
projectatomic/atomic-reactor
atomic_reactor/plugins/pre_add_yum_repo_by_url.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_add_yum_repo_by_url.py#L50-L76
def run(self): """ run the plugin """ if self.workflow.builder.base_from_scratch and not self.workflow.builder.parent_images: self.log.info("Skipping add yum repo by url: unsupported for FROM-scratch images") return if self.repourls: for repou...
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "workflow", ".", "builder", ".", "base_from_scratch", "and", "not", "self", ".", "workflow", ".", "builder", ".", "parent_images", ":", "self", ".", "log", ".", "info", "(", "\"Skipping add yum repo b...
run the plugin
[ "run", "the", "plugin" ]
python
train
jtwhite79/pyemu
pyemu/utils/gw_utils.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/gw_utils.py#L1855-L1935
def load_sfr_out(sfr_out_file, selection=None): """load an ASCII SFR output file into a dictionary of kper: dataframes. aggregates flow to aquifer for segments and returns and flow out at downstream end of segment. Parameters ---------- sfr_out_file : str SFR ASCII output file Returns...
[ "def", "load_sfr_out", "(", "sfr_out_file", ",", "selection", "=", "None", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "sfr_out_file", ")", ",", "\"couldn't find sfr out file {0}\"", ".", "format", "(", "sfr_out_file", ")", "tag", "=", "\" strea...
load an ASCII SFR output file into a dictionary of kper: dataframes. aggregates flow to aquifer for segments and returns and flow out at downstream end of segment. Parameters ---------- sfr_out_file : str SFR ASCII output file Returns ------- sfr_dict : dict dictio...
[ "load", "an", "ASCII", "SFR", "output", "file", "into", "a", "dictionary", "of", "kper", ":", "dataframes", ".", "aggregates", "flow", "to", "aquifer", "for", "segments", "and", "returns", "and", "flow", "out", "at", "downstream", "end", "of", "segment", "...
python
train
linkedin/naarad
src/naarad/metrics/metric.py
https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/metric.py#L494-L547
def plot_timeseries(self, graphing_library='matplotlib'): """ plot timeseries for sub-metrics """ if self.groupby: plot_data = {} # plot time series data for submetrics for out_csv in sorted(self.csv_files, reverse=True): csv_filename = os.path.basename(out_csv) transac...
[ "def", "plot_timeseries", "(", "self", ",", "graphing_library", "=", "'matplotlib'", ")", ":", "if", "self", ".", "groupby", ":", "plot_data", "=", "{", "}", "# plot time series data for submetrics", "for", "out_csv", "in", "sorted", "(", "self", ".", "csv_files...
plot timeseries for sub-metrics
[ "plot", "timeseries", "for", "sub", "-", "metrics" ]
python
valid
mk-fg/txboxdotnet
txboxdotnet/api_v2.py
https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L737-L757
def listdir( self, folder_id='0', type_filter=None, offset=None, limit=None, **listdir_kwz ): '''Return a list of objects in the specified folder_id. limit is passed to the API, so might be used as optimization. None means "fetch all items, with several requests, if necessary". type_filter can be set to ...
[ "def", "listdir", "(", "self", ",", "folder_id", "=", "'0'", ",", "type_filter", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "listdir_kwz", ")", ":", "res", "=", "yield", "super", "(", "txBox", ",", "self", ")...
Return a list of objects in the specified folder_id. limit is passed to the API, so might be used as optimization. None means "fetch all items, with several requests, if necessary". type_filter can be set to type (str) or sequence of object types to return, post-api-call processing.
[ "Return", "a", "list", "of", "objects", "in", "the", "specified", "folder_id", ".", "limit", "is", "passed", "to", "the", "API", "so", "might", "be", "used", "as", "optimization", ".", "None", "means", "fetch", "all", "items", "with", "several", "requests"...
python
train
pypa/pipenv
pipenv/vendor/six.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L892-L908
def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encodin...
[ "def", "ensure_text", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", ".", "decode", "(", "encoding", ",", "errors", ")", "elif", "isinstanc...
Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
[ "Coerce", "*", "s", "*", "to", "six", ".", "text_type", "." ]
python
train
Telefonica/toolium
toolium/utils.py
https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/utils.py#L418-L459
def get_remote_node(self): """Return the remote node that it's executing the actual test session :returns: tuple with server type (local, grid, ggr, selenium) and remote node name """ logging.getLogger("requests").setLevel(logging.WARNING) remote_node = None server_type ...
[ "def", "get_remote_node", "(", "self", ")", ":", "logging", ".", "getLogger", "(", "\"requests\"", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "remote_node", "=", "None", "server_type", "=", "'local'", "if", "self", ".", "driver_wrapper", ".",...
Return the remote node that it's executing the actual test session :returns: tuple with server type (local, grid, ggr, selenium) and remote node name
[ "Return", "the", "remote", "node", "that", "it", "s", "executing", "the", "actual", "test", "session" ]
python
train
pymupdf/PyMuPDF
fitz/fitz.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L624-L629
def includePoint(self, p): """Extend rectangle to include point p.""" if not len(p) == 2: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._include_point_in_rect(self, p) return self
[ "def", "includePoint", "(", "self", ",", "p", ")", ":", "if", "not", "len", "(", "p", ")", "==", "2", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", "....
Extend rectangle to include point p.
[ "Extend", "rectangle", "to", "include", "point", "p", "." ]
python
train
StanfordBioinformatics/loom
server/loomengine_server/api/async.py
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/async.py#L66-L81
def check_for_missed_cleanup(): """Check for TaskAttempts that were never cleaned up """ if get_setting('PRESERVE_ALL'): return from api.models.tasks import TaskAttempt if get_setting('PRESERVE_ON_FAILURE'): for task_attempt in TaskAttempt.objects.filter( status_is_ru...
[ "def", "check_for_missed_cleanup", "(", ")", ":", "if", "get_setting", "(", "'PRESERVE_ALL'", ")", ":", "return", "from", "api", ".", "models", ".", "tasks", "import", "TaskAttempt", "if", "get_setting", "(", "'PRESERVE_ON_FAILURE'", ")", ":", "for", "task_attem...
Check for TaskAttempts that were never cleaned up
[ "Check", "for", "TaskAttempts", "that", "were", "never", "cleaned", "up" ]
python
train
saltstack/salt
salt/output/no_return.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/no_return.py#L33-L56
def display(self, ret, indent, prefix, out): ''' Recursively iterate down through data structures to determine output ''' if isinstance(ret, six.string_types): lines = ret.split('\n') for line in lines: out += '{0}{1}{2}{3}{4}\n'.format( ...
[ "def", "display", "(", "self", ",", "ret", ",", "indent", ",", "prefix", ",", "out", ")", ":", "if", "isinstance", "(", "ret", ",", "six", ".", "string_types", ")", ":", "lines", "=", "ret", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "...
Recursively iterate down through data structures to determine output
[ "Recursively", "iterate", "down", "through", "data", "structures", "to", "determine", "output" ]
python
train
Yubico/python-pyhsm
pyhsm/util.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L152-L164
def validate_cmd_response_nonce(got, used): """ Check that the returned nonce matches nonce used in request. A request nonce of 000000000000 means the HSM should generate a nonce internally though, so if 'used' is all zeros we actually check that 'got' does NOT match 'used'. """ if used == '000...
[ "def", "validate_cmd_response_nonce", "(", "got", ",", "used", ")", ":", "if", "used", "==", "'000000000000'", ".", "decode", "(", "'hex'", ")", ":", "if", "got", "==", "used", ":", "raise", "(", "pyhsm", ".", "exception", ".", "YHSM_Error", "(", "\"Bad ...
Check that the returned nonce matches nonce used in request. A request nonce of 000000000000 means the HSM should generate a nonce internally though, so if 'used' is all zeros we actually check that 'got' does NOT match 'used'.
[ "Check", "that", "the", "returned", "nonce", "matches", "nonce", "used", "in", "request", "." ]
python
train
hugapi/hug
hug/output_format.py
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/output_format.py#L369-L393
def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'): """Returns a content in a different format based on the prefix placed at the end of the URL route should pass in a dict with the following format: {'[prefix]': action, ... ...
[ "def", "prefix", "(", "handlers", ",", "default", "=", "None", ",", "error", "=", "'The requested prefix does not match any of those allowed'", ")", ":", "def", "output_type", "(", "data", ",", "request", ",", "response", ")", ":", "path", "=", "request", ".", ...
Returns a content in a different format based on the prefix placed at the end of the URL route should pass in a dict with the following format: {'[prefix]': action, ... }
[ "Returns", "a", "content", "in", "a", "different", "format", "based", "on", "the", "prefix", "placed", "at", "the", "end", "of", "the", "URL", "route", "should", "pass", "in", "a", "dict", "with", "the", "following", "format", ":" ]
python
train
mitsei/dlkit
dlkit/records/assessment/basic/simple_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/simple_records.py#L453-L465
def set_min_string_length(self, length=None): """stub""" if self.get_min_string_length_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal( length, self.get_min_string_length_metadata()): raise Inv...
[ "def", "set_min_string_length", "(", "self", ",", "length", "=", "None", ")", ":", "if", "self", ".", "get_min_string_length_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "NoAccess", "(", ")", "if", "not", "self", ".", "my_osid_object_for...
stub
[ "stub" ]
python
train
Scille/mestr
mestr/mestr.py
https://github.com/Scille/mestr/blob/344092aac77ad222fb6cd62927c7801c2ece33fc/mestr/mestr.py#L61-L109
def authenticate(realm, authid, details): """ application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0...
[ "def", "authenticate", "(", "realm", ",", "authid", ",", "details", ")", ":", "global", "_start", "global", "_waiting", "import", "json", "ticket", "=", "json", ".", "loads", "(", "details", "[", "'ticket'", "]", ")", "if", "'application_name'", "not", "in...
application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0.1", ... } when all the diffe...
[ "application_name", ":", "name", "of", "your", "application", "version", ":", "version", "of", "your", "application", "required_components", "dictionary", "of", "components", "required", "for", "you", "application", "and", "their", "version", "required" ]
python
train
tadashi-aikawa/jumeaux
jumeaux/executor.py
https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/executor.py#L248-L398
def challenge(arg: ChallengeArg) -> dict: """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled. """ name: str = arg.req.name.get_or(str(arg.seq)) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" logger.info_lv3(f"{log_prefix} {'-'*80}") logger.info_lv3(f"{log_prefix}...
[ "def", "challenge", "(", "arg", ":", "ChallengeArg", ")", "->", "dict", ":", "name", ":", "str", "=", "arg", ".", "req", ".", "name", ".", "get_or", "(", "str", "(", "arg", ".", "seq", ")", ")", "log_prefix", "=", "f\"[{arg.seq} / {arg.number_of_request}...
Response is dict like `Trial` because Status(OwlEnum) can't be pickled.
[ "Response", "is", "dict", "like", "Trial", "because", "Status", "(", "OwlEnum", ")", "can", "t", "be", "pickled", "." ]
python
train
dswah/pyGAM
pygam/datasets/load_datasets.py
https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L17-L20
def _clean_X_y(X, y): """ensure that X and y data are float and correct shapes """ return make_2d(X, verbose=False).astype('float'), y.astype('float')
[ "def", "_clean_X_y", "(", "X", ",", "y", ")", ":", "return", "make_2d", "(", "X", ",", "verbose", "=", "False", ")", ".", "astype", "(", "'float'", ")", ",", "y", ".", "astype", "(", "'float'", ")" ]
ensure that X and y data are float and correct shapes
[ "ensure", "that", "X", "and", "y", "data", "are", "float", "and", "correct", "shapes" ]
python
train
nerdvegas/rez
src/rez/vendor/pygraph/readwrite/dot.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/dot.py#L107-L176
def write(G, weighted=False): """ Return a string specifying the given graph in Dot language. @type G: graph @param G: Graph. @type weighted: boolean @param weighted: Whether edges should be labelled with their weight. @rtype: string @return: String specifying the graph in ...
[ "def", "write", "(", "G", ",", "weighted", "=", "False", ")", ":", "dotG", "=", "pydot", ".", "Dot", "(", ")", "if", "not", "'name'", "in", "dir", "(", "G", ")", ":", "dotG", ".", "set_name", "(", "'graphname'", ")", "else", ":", "dotG", ".", "...
Return a string specifying the given graph in Dot language. @type G: graph @param G: Graph. @type weighted: boolean @param weighted: Whether edges should be labelled with their weight. @rtype: string @return: String specifying the graph in Dot Language.
[ "Return", "a", "string", "specifying", "the", "given", "graph", "in", "Dot", "language", ".", "@type", "G", ":", "graph", "@param", "G", ":", "Graph", "." ]
python
train
thewca/wca-regulations-compiler
wrc/codegen/cghtml.py
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/codegen/cghtml.py#L70-L74
def link2html(text): ''' Turns md links to html ''' match = r'\[([^\]]+)\]\(([^)]+)\)' replace = r'<a href="\2">\1</a>' return re.sub(match, replace, text)
[ "def", "link2html", "(", "text", ")", ":", "match", "=", "r'\\[([^\\]]+)\\]\\(([^)]+)\\)'", "replace", "=", "r'<a href=\"\\2\">\\1</a>'", "return", "re", ".", "sub", "(", "match", ",", "replace", ",", "text", ")" ]
Turns md links to html
[ "Turns", "md", "links", "to", "html" ]
python
train
bitcraze/crazyflie-lib-python
cflib/crtp/radiodriver.py
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/radiodriver.py#L273-L288
def close(self): """ Close the link. """ # Stop the comm thread self._thread.stop() # Close the USB dongle if self._radio_manager: self._radio_manager.close() self._radio_manager = None while not self.out_queue.empty(): self.out_queue.get...
[ "def", "close", "(", "self", ")", ":", "# Stop the comm thread", "self", ".", "_thread", ".", "stop", "(", ")", "# Close the USB dongle", "if", "self", ".", "_radio_manager", ":", "self", ".", "_radio_manager", ".", "close", "(", ")", "self", ".", "_radio_ma...
Close the link.
[ "Close", "the", "link", "." ]
python
train
cloudmesh/cloudmesh-common
cloudmesh/common/Shell.py
https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Shell.py#L435-L446
def ping(cls, host=None, count=1): """ execute ping :param host: the host to ping :param count: the number of pings :return: """ option = '-n' if platform.system().lower() == 'windows' else '-c' return cls.execute('ping', "{opt...
[ "def", "ping", "(", "cls", ",", "host", "=", "None", ",", "count", "=", "1", ")", ":", "option", "=", "'-n'", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'windows'", "else", "'-c'", "return", "cls", ".", "execute", "...
execute ping :param host: the host to ping :param count: the number of pings :return:
[ "execute", "ping", ":", "param", "host", ":", "the", "host", "to", "ping", ":", "param", "count", ":", "the", "number", "of", "pings", ":", "return", ":" ]
python
train
JelteF/PyLaTeX
pylatex/lists.py
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/lists.py#L74-L85
def add_item(self, label, s): """Add an item to the list. Args ---- label: str Description of the item. s: str or `~.LatexObject` The item itself. """ self.append(Command('item', options=label)) self.append(s)
[ "def", "add_item", "(", "self", ",", "label", ",", "s", ")", ":", "self", ".", "append", "(", "Command", "(", "'item'", ",", "options", "=", "label", ")", ")", "self", ".", "append", "(", "s", ")" ]
Add an item to the list. Args ---- label: str Description of the item. s: str or `~.LatexObject` The item itself.
[ "Add", "an", "item", "to", "the", "list", "." ]
python
train
fbcotter/py3nvml
py3nvml/py3nvml.py
https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L1104-L1138
def _LoadNvmlLibrary(): """ Load the library if it isn't loaded already """ global nvmlLib if (nvmlLib is None): # lock to ensure only one caller loads the library libLoadLock.acquire() try: # ensure the library still isn't loaded if (nvmlLib is None...
[ "def", "_LoadNvmlLibrary", "(", ")", ":", "global", "nvmlLib", "if", "(", "nvmlLib", "is", "None", ")", ":", "# lock to ensure only one caller loads the library", "libLoadLock", ".", "acquire", "(", ")", "try", ":", "# ensure the library still isn't loaded", "if", "("...
Load the library if it isn't loaded already
[ "Load", "the", "library", "if", "it", "isn", "t", "loaded", "already" ]
python
train
thunder-project/thunder
thunder/images/readers.py
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L159-L221
def frompath(path, accessor=None, ext=None, start=None, stop=None, recursive=False, npartitions=None, dims=None, dtype=None, labels=None, recount=False, engine=None, credentials=None): """ Load images from a path using the given accessor. Supports both local and remote filesystems. Parameters ----...
[ "def", "frompath", "(", "path", ",", "accessor", "=", "None", ",", "ext", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "recursive", "=", "False", ",", "npartitions", "=", "None", ",", "dims", "=", "None", ",", "dtype", "="...
Load images from a path using the given accessor. Supports both local and remote filesystems. Parameters ---------- accessor : function Apply to each item after loading to yield an image. ext : str, optional, default=None File extension. npartitions : int, optional, default=N...
[ "Load", "images", "from", "a", "path", "using", "the", "given", "accessor", "." ]
python
train
aiortc/aioice
aioice/ice.py
https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L299-L319
def add_remote_candidate(self, remote_candidate): """ Add a remote candidate or signal end-of-candidates. To signal end-of-candidates, pass `None`. """ if self._remote_candidates_end: raise ValueError('Cannot add remote candidate after end-of-candidates.') i...
[ "def", "add_remote_candidate", "(", "self", ",", "remote_candidate", ")", ":", "if", "self", ".", "_remote_candidates_end", ":", "raise", "ValueError", "(", "'Cannot add remote candidate after end-of-candidates.'", ")", "if", "remote_candidate", "is", "None", ":", "self...
Add a remote candidate or signal end-of-candidates. To signal end-of-candidates, pass `None`.
[ "Add", "a", "remote", "candidate", "or", "signal", "end", "-", "of", "-", "candidates", "." ]
python
train
cloudant/python-cloudant
src/cloudant/document.py
https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/document.py#L196-L211
def list_field_append(doc, field, value): """ Appends a value to a list field in a locally cached Document object. If a field does not exist it will be created first. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. ...
[ "def", "list_field_append", "(", "doc", ",", "field", ",", "value", ")", ":", "if", "doc", ".", "get", "(", "field", ")", "is", "None", ":", "doc", "[", "field", "]", "=", "[", "]", "if", "not", "isinstance", "(", "doc", "[", "field", "]", ",", ...
Appends a value to a list field in a locally cached Document object. If a field does not exist it will be created first. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field list to append to. ...
[ "Appends", "a", "value", "to", "a", "list", "field", "in", "a", "locally", "cached", "Document", "object", ".", "If", "a", "field", "does", "not", "exist", "it", "will", "be", "created", "first", "." ]
python
train
prometheus/client_python
prometheus_client/exposition.py
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/exposition.py#L229-L245
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None): """Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.""" ...
[ "def", "basic_auth_handler", "(", "url", ",", "method", ",", "timeout", ",", "headers", ",", "data", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "def", "handle", "(", ")", ":", "\"\"\"Handler that implements HTTP Basic Auth.\n \"...
Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.
[ "Handler", "that", "implements", "HTTP", "/", "HTTPS", "connections", "with", "Basic", "Auth", "." ]
python
train
QuantEcon/QuantEcon.py
quantecon/markov/ddp.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/markov/ddp.py#L797-L834
def policy_iteration(self, v_init=None, max_iter=None): """ Solve the optimization problem by policy iteration. See the `solve` method. """ if self.beta == 1: raise NotImplementedError(self._error_msg_no_discounting) if max_iter is None: max_iter...
[ "def", "policy_iteration", "(", "self", ",", "v_init", "=", "None", ",", "max_iter", "=", "None", ")", ":", "if", "self", ".", "beta", "==", "1", ":", "raise", "NotImplementedError", "(", "self", ".", "_error_msg_no_discounting", ")", "if", "max_iter", "is...
Solve the optimization problem by policy iteration. See the `solve` method.
[ "Solve", "the", "optimization", "problem", "by", "policy", "iteration", ".", "See", "the", "solve", "method", "." ]
python
train
Fuyukai/asyncwebsockets
asyncwebsockets/client.py
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/client.py#L65-L76
async def open_websocket_client(sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[list] = None, subprotocols: Optional[list] = None): """Create a websocket on top of a socke...
[ "async", "def", "open_websocket_client", "(", "sock", ":", "anyio", ".", "abc", ".", "SocketStream", ",", "addr", ",", "path", ":", "str", ",", "headers", ":", "Optional", "[", "list", "]", "=", "None", ",", "subprotocols", ":", "Optional", "[", "list", ...
Create a websocket on top of a socket.
[ "Create", "a", "websocket", "on", "top", "of", "a", "socket", "." ]
python
train
rgs1/zk_shell
zk_shell/xclient.py
https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L147-L157
def get(self, *args, **kwargs): """ wraps the default get() and deals with encoding """ value, stat = super(XClient, self).get(*args, **kwargs) try: if value is not None: value = value.decode(encoding="utf-8") except UnicodeDecodeError: pass ...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", ",", "stat", "=", "super", "(", "XClient", ",", "self", ")", ".", "get", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "if", "value", "is",...
wraps the default get() and deals with encoding
[ "wraps", "the", "default", "get", "()", "and", "deals", "with", "encoding" ]
python
train
yyuu/botornado
boto/cloudfront/invalidation.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/cloudfront/invalidation.py#L70-L79
def to_xml(self): """Get this batch as XML""" assert self.connection != None s = '<?xml version="1.0" encoding="UTF-8"?>\n' s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version for p in self.paths: s += ' <Path>%s</...
[ "def", "to_xml", "(", "self", ")", ":", "assert", "self", ".", "connection", "!=", "None", "s", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'", "s", "+=", "'<InvalidationBatch xmlns=\"http://cloudfront.amazonaws.com/doc/%s/\">\\n'", "%", "self", ".", "connection", ...
Get this batch as XML
[ "Get", "this", "batch", "as", "XML" ]
python
train
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1029-L1049
def console_map_ascii_codes_to_font( firstAsciiCode: int, nbCodes: int, fontCharX: int, fontCharY: int ) -> None: """Remap a contiguous set of codes to a contiguous set of tiles. Both the tile-set and character codes must be contiguous to use this function. If this is not the case you may want to use ...
[ "def", "console_map_ascii_codes_to_font", "(", "firstAsciiCode", ":", "int", ",", "nbCodes", ":", "int", ",", "fontCharX", ":", "int", ",", "fontCharY", ":", "int", ")", "->", "None", ":", "lib", ".", "TCOD_console_map_ascii_codes_to_font", "(", "_int", "(", "...
Remap a contiguous set of codes to a contiguous set of tiles. Both the tile-set and character codes must be contiguous to use this function. If this is not the case you may want to use :any:`console_map_ascii_code_to_font`. Args: firstAsciiCode (int): The starting character code. nbCo...
[ "Remap", "a", "contiguous", "set", "of", "codes", "to", "a", "contiguous", "set", "of", "tiles", "." ]
python
train
googledatalab/pydatalab
datalab/bigquery/_query.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_query.py#L434-L494
def execute_async(self, table_name=None, table_mode='create', use_cache=True, priority='interactive', allow_large_results=False, dialect=None, billing_tier=None): """ Initiate the query and return a QueryJob. Args: table_name: the result table name as a string or T...
[ "def", "execute_async", "(", "self", ",", "table_name", "=", "None", ",", "table_mode", "=", "'create'", ",", "use_cache", "=", "True", ",", "priority", "=", "'interactive'", ",", "allow_large_results", "=", "False", ",", "dialect", "=", "None", ",", "billin...
Initiate the query and return a QueryJob. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table...
[ "Initiate", "the", "query", "and", "return", "a", "QueryJob", "." ]
python
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L932-L959
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFull...
[ "def", "_AddEqualsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "(", "not", "isinstance", "(", "other", ",", "message_mod", ".", "Message", ")", "or", "other", ".", "DESCRIPTOR", "!=...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
python
train
PSU-OIT-ARC/elasticmodels
elasticmodels/analysis.py
https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L74-L102
def is_analysis_compatible(using): """ Returns True if the analysis defined in Python land and ES for the connection `using` are compatible """ python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) if es_analysis == DOES_NOT_EXIST: return True # we want to...
[ "def", "is_analysis_compatible", "(", "using", ")", ":", "python_analysis", "=", "collect_analysis", "(", "using", ")", "es_analysis", "=", "existing_analysis", "(", "using", ")", "if", "es_analysis", "==", "DOES_NOT_EXIST", ":", "return", "True", "# we want to ensu...
Returns True if the analysis defined in Python land and ES for the connection `using` are compatible
[ "Returns", "True", "if", "the", "analysis", "defined", "in", "Python", "land", "and", "ES", "for", "the", "connection", "using", "are", "compatible" ]
python
train
dereneaton/ipyrad
ipyrad/assemble/cluster_within.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1323-L1350
def reconcat(data, sample): """ takes aligned chunks (usually 10) and concatenates them """ try: ## get chunks chunks = glob.glob(os.path.join(data.tmpdir, sample.name+"_chunk_[0-9].aligned")) ## sort by chunk number, cuts off last 8 =(aligned) chunks.sort(key=...
[ "def", "reconcat", "(", "data", ",", "sample", ")", ":", "try", ":", "## get chunks", "chunks", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ".", "tmpdir", ",", "sample", ".", "name", "+", "\"_chunk_[0-9].aligned\"", ")",...
takes aligned chunks (usually 10) and concatenates them
[ "takes", "aligned", "chunks", "(", "usually", "10", ")", "and", "concatenates", "them" ]
python
valid
jtwhite79/pyemu
pyemu/utils/helpers.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/helpers.py#L809-L877
def zero_order_tikhonov(pst, parbounds=True,par_groups=None, reset=True): """setup preferred-value regularization Parameters ---------- pst : pyemu.Pst the control file instance parbounds : bool flag to weight the prior information equations according ...
[ "def", "zero_order_tikhonov", "(", "pst", ",", "parbounds", "=", "True", ",", "par_groups", "=", "None", ",", "reset", "=", "True", ")", ":", "if", "par_groups", "is", "None", ":", "par_groups", "=", "pst", ".", "par_groups", "pilbl", ",", "obgnme", ",",...
setup preferred-value regularization Parameters ---------- pst : pyemu.Pst the control file instance parbounds : bool flag to weight the prior information equations according to parameter bound width - approx the KL transform. Default is True par_groups : list ...
[ "setup", "preferred", "-", "value", "regularization" ]
python
train
PrefPy/prefpy
prefpy/mechanismMcmcSampleGenerator.py
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L125-L157
def getNextSample(self, V): """ We generate a new ranking based on a Mallows-based jumping distribution. The algorithm is described in "Bayesian Ordinal Peer Grading" by Raman and Joachims. :ivar list<int> V: Contains integer representations of each candidate in order of their ...
[ "def", "getNextSample", "(", "self", ",", "V", ")", ":", "phi", "=", "self", ".", "phi", "wmg", "=", "self", ".", "wmg", "W", "=", "[", "]", "W", ".", "append", "(", "V", "[", "0", "]", ")", "for", "j", "in", "range", "(", "2", ",", "len", ...
We generate a new ranking based on a Mallows-based jumping distribution. The algorithm is described in "Bayesian Ordinal Peer Grading" by Raman and Joachims. :ivar list<int> V: Contains integer representations of each candidate in order of their ranking in a vote, from first to last.
[ "We", "generate", "a", "new", "ranking", "based", "on", "a", "Mallows", "-", "based", "jumping", "distribution", ".", "The", "algorithm", "is", "described", "in", "Bayesian", "Ordinal", "Peer", "Grading", "by", "Raman", "and", "Joachims", "." ]
python
train
etingof/pysnmp
pysnmp/smi/mibs/SNMPv2-SMI.py
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3308-L3329
def getInstIdFromIndices(self, *indices): """Return column instance identification from indices""" try: return self._idxToIdCache[indices] except TypeError: cacheable = False except KeyError: cacheable = True idx = 0 instId = () ...
[ "def", "getInstIdFromIndices", "(", "self", ",", "*", "indices", ")", ":", "try", ":", "return", "self", ".", "_idxToIdCache", "[", "indices", "]", "except", "TypeError", ":", "cacheable", "=", "False", "except", "KeyError", ":", "cacheable", "=", "True", ...
Return column instance identification from indices
[ "Return", "column", "instance", "identification", "from", "indices" ]
python
train
maas/python-libmaas
maas/client/viscera/boot_source_selections.py
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_source_selections.py#L105-L108
async def delete(self): """Delete boot source selection.""" await self._handler.delete( boot_source_id=self.boot_source.id, id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "await", "self", ".", "_handler", ".", "delete", "(", "boot_source_id", "=", "self", ".", "boot_source", ".", "id", ",", "id", "=", "self", ".", "id", ")" ]
Delete boot source selection.
[ "Delete", "boot", "source", "selection", "." ]
python
train
pyviz/holoviews
holoviews/core/options.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/options.py#L204-L212
def options_policy(skip_invalid, warn_on_skip): """ Context manager to temporarily set the skip_invalid and warn_on_skip class parameters on Options. """ settings = (Options.skip_invalid, Options.warn_on_skip) (Options.skip_invalid, Options.warn_on_skip) = (skip_invalid, warn_on_skip) yield ...
[ "def", "options_policy", "(", "skip_invalid", ",", "warn_on_skip", ")", ":", "settings", "=", "(", "Options", ".", "skip_invalid", ",", "Options", ".", "warn_on_skip", ")", "(", "Options", ".", "skip_invalid", ",", "Options", ".", "warn_on_skip", ")", "=", "...
Context manager to temporarily set the skip_invalid and warn_on_skip class parameters on Options.
[ "Context", "manager", "to", "temporarily", "set", "the", "skip_invalid", "and", "warn_on_skip", "class", "parameters", "on", "Options", "." ]
python
train
SheffieldML/GPy
GPy/util/datasets.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/datasets.py#L114-L169
def download_url(url, store_directory, save_name=None, messages=True, suffix=''): """Download a file from a url and save it to disk.""" i = url.rfind('/') file = url[i+1:] print(file) dir_name = os.path.join(data_path, store_directory) if save_name is None: save_name = os.path.join(dir_name, fi...
[ "def", "download_url", "(", "url", ",", "store_directory", ",", "save_name", "=", "None", ",", "messages", "=", "True", ",", "suffix", "=", "''", ")", ":", "i", "=", "url", ".", "rfind", "(", "'/'", ")", "file", "=", "url", "[", "i", "+", "1", ":...
Download a file from a url and save it to disk.
[ "Download", "a", "file", "from", "a", "url", "and", "save", "it", "to", "disk", "." ]
python
train
cltk/cltk
cltk/corpus/readers.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L211-L232
def docs(self, fileids=None) -> Generator[str, str, None]: """ Returns the complete text of an Text document, closing the document after we are done reading it and yielding it in a memory safe fashion. """ if not fileids: fileids = self.fileids() # Create a ge...
[ "def", "docs", "(", "self", ",", "fileids", "=", "None", ")", "->", "Generator", "[", "str", ",", "str", ",", "None", "]", ":", "if", "not", "fileids", ":", "fileids", "=", "self", ".", "fileids", "(", ")", "# Create a generator, loading one document into ...
Returns the complete text of an Text document, closing the document after we are done reading it and yielding it in a memory safe fashion.
[ "Returns", "the", "complete", "text", "of", "an", "Text", "document", "closing", "the", "document", "after", "we", "are", "done", "reading", "it", "and", "yielding", "it", "in", "a", "memory", "safe", "fashion", "." ]
python
train
deepmipt/DeepPavlov
deeppavlov/core/layers/tf_csoftmax_attention.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_csoftmax_attention.py#L142-L173
def attention_gen_block(hidden_for_sketch, hidden_for_attn_alignment, key, attention_depth): """ It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax). Based on the papers: https://arxiv.org/abs/1508.04025 "Effective Approaches to At...
[ "def", "attention_gen_block", "(", "hidden_for_sketch", ",", "hidden_for_attn_alignment", ",", "key", ",", "attention_depth", ")", ":", "with", "tf", ".", "name_scope", "(", "'attention_block'", ")", ":", "sketch_dims", "=", "tf", ".", "shape", "(", "hidden_for_sk...
It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax). Based on the papers: https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation" https://andre-martins.github.io/docs/emnlp2017_fina...
[ "It", "is", "a", "implementation", "of", "the", "Luong", "et", "al", ".", "attention", "mechanism", "with", "general", "score", "and", "the", "constrained", "softmax", "(", "csoftmax", ")", ".", "Based", "on", "the", "papers", ":", "https", ":", "//", "a...
python
test
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/memory_profiler.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/memory_profiler.py#L248-L257
def trace_memory_usage(self, frame, event, arg): """Callback for sys.settrace""" if event in ('line', 'return') and frame.f_code in self.code_map: lineno = frame.f_lineno if event == 'return': lineno += 1 entry = self.code_map[frame.f_c...
[ "def", "trace_memory_usage", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "if", "event", "in", "(", "'line'", ",", "'return'", ")", "and", "frame", ".", "f_code", "in", "self", ".", "code_map", ":", "lineno", "=", "frame", ".", "f_l...
Callback for sys.settrace
[ "Callback", "for", "sys", ".", "settrace" ]
python
train
Kortemme-Lab/klab
klab/bio/pdb.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2490-L2502
def get_residue_id_to_type_map(self): '''Returns a dictionary mapping 6-character residue IDs (Chain, residue number, insertion code e.g. "A 123B") to the corresponding one-letter amino acid. Caveat: This function ignores occupancy - this function should be called once occupancy has been ...
[ "def", "get_residue_id_to_type_map", "(", "self", ")", ":", "resid2type", "=", "{", "}", "atomlines", "=", "self", ".", "parsed_lines", "[", "'ATOM '", "]", "for", "line", "in", "atomlines", ":", "resname", "=", "line", "[", "17", ":", "20", "]", "if", ...
Returns a dictionary mapping 6-character residue IDs (Chain, residue number, insertion code e.g. "A 123B") to the corresponding one-letter amino acid. Caveat: This function ignores occupancy - this function should be called once occupancy has been dealt with appropriately.
[ "Returns", "a", "dictionary", "mapping", "6", "-", "character", "residue", "IDs", "(", "Chain", "residue", "number", "insertion", "code", "e", ".", "g", ".", "A", "123B", ")", "to", "the", "corresponding", "one", "-", "letter", "amino", "acid", "." ]
python
train
respeaker/respeaker_python_library
respeaker/usb_hid/pyusb_backend.py
https://github.com/respeaker/respeaker_python_library/blob/905a5334ccdc2d474ad973caf6a23d05c65bbb25/respeaker/usb_hid/pyusb_backend.py#L119-L144
def write(self, data): """ write data on the OUT endpoint associated to the HID interface """ # report_size = 64 # if self.ep_out: # report_size = self.ep_out.wMaxPacketSize # # for _ in range(report_size - len(data)): # data.append(0) ...
[ "def", "write", "(", "self", ",", "data", ")", ":", "# report_size = 64", "# if self.ep_out:", "# report_size = self.ep_out.wMaxPacketSize", "#", "# for _ in range(report_size - len(data)):", "# data.append(0)", "self", ".", "read_sem", ".", "release", "(", ")", "if"...
write data on the OUT endpoint associated to the HID interface
[ "write", "data", "on", "the", "OUT", "endpoint", "associated", "to", "the", "HID", "interface" ]
python
train
Cornices/cornice.ext.sphinx
cornice_sphinx/__init__.py
https://github.com/Cornices/cornice.ext.sphinx/blob/f73fdcc94d78fb5c94262adb9adc187c96378a53/cornice_sphinx/__init__.py#L117-L128
def _get_attributes(schema, location): """Return the schema's children, filtered by location.""" schema = DottedNameResolver(__name__).maybe_resolve(schema) def _filter(attr): if not hasattr(attr, "location"): valid_location = 'body' in location else: ...
[ "def", "_get_attributes", "(", "schema", ",", "location", ")", ":", "schema", "=", "DottedNameResolver", "(", "__name__", ")", ".", "maybe_resolve", "(", "schema", ")", "def", "_filter", "(", "attr", ")", ":", "if", "not", "hasattr", "(", "attr", ",", "\...
Return the schema's children, filtered by location.
[ "Return", "the", "schema", "s", "children", "filtered", "by", "location", "." ]
python
train
snare/voltron
voltron/plugin.py
https://github.com/snare/voltron/blob/4ee3cbe6f7c1e38303f5dc6114c48b60217253c3/voltron/plugin.py#L91-L104
def valid_api_plugin(self, plugin): """ Validate an API plugin, ensuring it is an API plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, APIPlugin) and hasattr(plugin, 'plugin_type')...
[ "def", "valid_api_plugin", "(", "self", ",", "plugin", ")", ":", "if", "(", "issubclass", "(", "plugin", ",", "APIPlugin", ")", "and", "hasattr", "(", "plugin", ",", "'plugin_type'", ")", "and", "plugin", ".", "plugin_type", "==", "'api'", "and", "hasattr"...
Validate an API plugin, ensuring it is an API plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
[ "Validate", "an", "API", "plugin", "ensuring", "it", "is", "an", "API", "plugin", "and", "has", "the", "necessary", "fields", "present", "." ]
python
train
openearth/bmi-python
bmi/runner.py
https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/runner.py#L82-L126
def main(): """main bmi runner program""" arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments[...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", ".", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "colorlogs", "(", ")", "# Read input file file", "wrapper", "=", "BMIWrapper", "(", "engine", "=", "arguments", "[", "'<engine>'...
main bmi runner program
[ "main", "bmi", "runner", "program" ]
python
train
rocky/python3-trepan
trepan/processor/frame.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/frame.py#L45-L81
def adjust_frame(proc_obj, name, pos, absolute_pos): """Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.""" if not proc_obj.curframe: proc_obj.errmsg("No stack.") return ...
[ "def", "adjust_frame", "(", "proc_obj", ",", "name", ",", "pos", ",", "absolute_pos", ")", ":", "if", "not", "proc_obj", ".", "curframe", ":", "proc_obj", ".", "errmsg", "(", "\"No stack.\"", ")", "return", "# Below we remove any negativity. At the end, pos will be"...
Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.
[ "Adjust", "stack", "frame", "by", "pos", "positions", ".", "If", "absolute_pos", "then", "pos", "is", "an", "absolute", "number", ".", "Otherwise", "it", "is", "a", "relative", "number", "." ]
python
test
pvlib/pvlib-python
pvlib/forecast.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/forecast.py#L149-L166
def set_dataset(self): ''' Retrieves the designated dataset, creates NCSS object, and creates a NCSS query object. ''' keys = list(self.model.datasets.keys()) labels = [item.split()[0].lower() for item in keys] if self.set_type == 'best': self.dataset...
[ "def", "set_dataset", "(", "self", ")", ":", "keys", "=", "list", "(", "self", ".", "model", ".", "datasets", ".", "keys", "(", ")", ")", "labels", "=", "[", "item", ".", "split", "(", ")", "[", "0", "]", ".", "lower", "(", ")", "for", "item", ...
Retrieves the designated dataset, creates NCSS object, and creates a NCSS query object.
[ "Retrieves", "the", "designated", "dataset", "creates", "NCSS", "object", "and", "creates", "a", "NCSS", "query", "object", "." ]
python
train
luckydonald/pytgbot
code_generation/code_generator_template.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L235-L249
def class_name_teleflask_message(self) -> str: """ If it starts with `Send` remove that. """ # strip leading "Send" name = self.class_name # "sendPhoto" -> "SendPhoto" name = name[4:] if name.startswith('Send') else name # "SendPhoto" -> "Photo" name = name + "M...
[ "def", "class_name_teleflask_message", "(", "self", ")", "->", "str", ":", "# strip leading \"Send\"", "name", "=", "self", ".", "class_name", "# \"sendPhoto\" -> \"SendPhoto\"", "name", "=", "name", "[", "4", ":", "]", "if", "name", ".", "startswith", "(", "'Se...
If it starts with `Send` remove that.
[ "If", "it", "starts", "with", "Send", "remove", "that", "." ]
python
train
aarongarrett/inspyred
inspyred/ec/observers.py
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/observers.py#L337-L407
def plot_observer(population, num_generations, num_evaluations, args): """Plot the output of the evolutionary computation as a graph. This function plots the performance of the EC as a line graph using matplotlib and numpy. The graph consists of a blue line representing the best fitness, a gr...
[ "def", "plot_observer", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "numpy", "stats", "=", "inspyred", ".", "ec", ".", "analysis", ".", "fitness_statist...
Plot the output of the evolutionary computation as a graph. This function plots the performance of the EC as a line graph using matplotlib and numpy. The graph consists of a blue line representing the best fitness, a green line representing the average fitness, and a red line representing the me...
[ "Plot", "the", "output", "of", "the", "evolutionary", "computation", "as", "a", "graph", ".", "This", "function", "plots", "the", "performance", "of", "the", "EC", "as", "a", "line", "graph", "using", "matplotlib", "and", "numpy", ".", "The", "graph", "con...
python
train
pandas-dev/pandas
pandas/core/groupby/generic.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1202-L1213
def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): """Calcuate pct_change of each value to previous entry in group""" # TODO: Remove this conditional when #23918 is fixed if freq: return self.apply(lambda x: x.pct_change(periods=periods, ...
[ "def", "pct_change", "(", "self", ",", "periods", "=", "1", ",", "fill_method", "=", "'pad'", ",", "limit", "=", "None", ",", "freq", "=", "None", ")", ":", "# TODO: Remove this conditional when #23918 is fixed", "if", "freq", ":", "return", "self", ".", "ap...
Calcuate pct_change of each value to previous entry in group
[ "Calcuate", "pct_change", "of", "each", "value", "to", "previous", "entry", "in", "group" ]
python
train
scanny/python-pptx
pptx/parts/slide.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/slide.py#L89-L97
def _new_theme_part(cls, package): """ Create and return a default theme part suitable for use with a notes master. """ partname = package.next_partname('/ppt/theme/theme%d.xml') content_type = CT.OFC_THEME theme = CT_OfficeStyleSheet.new_default() return ...
[ "def", "_new_theme_part", "(", "cls", ",", "package", ")", ":", "partname", "=", "package", ".", "next_partname", "(", "'/ppt/theme/theme%d.xml'", ")", "content_type", "=", "CT", ".", "OFC_THEME", "theme", "=", "CT_OfficeStyleSheet", ".", "new_default", "(", ")"...
Create and return a default theme part suitable for use with a notes master.
[ "Create", "and", "return", "a", "default", "theme", "part", "suitable", "for", "use", "with", "a", "notes", "master", "." ]
python
train
johnnoone/json-spec
src/jsonspec/pointer/bases.py
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L96-L121
def parse(self, pointer): """parse pointer into tokens""" if isinstance(pointer, Pointer): return pointer.tokens[:] elif pointer == '': return [] tokens = [] staged, _, children = pointer.partition('/') if staged: try: ...
[ "def", "parse", "(", "self", ",", "pointer", ")", ":", "if", "isinstance", "(", "pointer", ",", "Pointer", ")", ":", "return", "pointer", ".", "tokens", "[", ":", "]", "elif", "pointer", "==", "''", ":", "return", "[", "]", "tokens", "=", "[", "]",...
parse pointer into tokens
[ "parse", "pointer", "into", "tokens" ]
python
train
brian-rose/climlab
climlab/process/process.py
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L407-L441
def add_diagnostic(self, name, value=None): """Create a new diagnostic variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the diagnostics...
[ "def", "add_diagnostic", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "self", ".", "_diag_vars", ".", "append", "(", "name", ")", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
Create a new diagnostic variable called ``name`` for this process and initialize it with the given ``value``. Quantity is accessible in two ways: * as a process attribute, i.e. ``proc.name`` * as a member of the diagnostics dictionary, i.e. ``proc.diagnostics['nam...
[ "Create", "a", "new", "diagnostic", "variable", "called", "name", "for", "this", "process", "and", "initialize", "it", "with", "the", "given", "value", "." ]
python
train
CTPUG/wafer
wafer/compare/admin.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/compare/admin.py#L156-L177
def comparelist_view(self, request, object_id, extra_context=None): """Allow selecting versions to compare.""" opts = self.model._meta object_id = unquote(object_id) current = get_object_or_404(self.model, pk=object_id) # As done by reversion's history_view action_list = ...
[ "def", "comparelist_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "object_id", "=", "unquote", "(", "object_id", ")", "current", "=", "get_object_or_404", ...
Allow selecting versions to compare.
[ "Allow", "selecting", "versions", "to", "compare", "." ]
python
train
has2k1/plotnine
plotnine/stats/stat_ellipse.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat_ellipse.py#L88-L230
def cov_trob(x, wt=None, cor=False, center=True, nu=5, maxit=25, tol=0.01): """ Covariance Estimation for Multivariate t Distribution Estimates a covariance or correlation matrix assuming the data came from a multivariate t distribution: this provides some degree of robustness to outli...
[ "def", "cov_trob", "(", "x", ",", "wt", "=", "None", ",", "cor", "=", "False", ",", "center", "=", "True", ",", "nu", "=", "5", ",", "maxit", "=", "25", ",", "tol", "=", "0.01", ")", ":", "def", "test_values", "(", "x", ")", ":", "if", "pd", ...
Covariance Estimation for Multivariate t Distribution Estimates a covariance or correlation matrix assuming the data came from a multivariate t distribution: this provides some degree of robustness to outlier without giving a high breakdown point. **credit**: This function a port of the R function...
[ "Covariance", "Estimation", "for", "Multivariate", "t", "Distribution" ]
python
train
saltstack/salt
salt/cloud/clouds/softlayer_hw.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L646-L663
def show_all_categories(call=None): ''' Return a dict of all available categories on the cloud provider. .. versionadded:: 2016.3.0 ''' if call == 'action': raise SaltCloudSystemExit( 'The show_all_categories function must be called with -f or --function.' ) conn = ...
[ "def", "show_all_categories", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_all_categories function must be called with -f or --function.'", ")", "conn", "=", "get_conn", "(", "service", "=", "...
Return a dict of all available categories on the cloud provider. .. versionadded:: 2016.3.0
[ "Return", "a", "dict", "of", "all", "available", "categories", "on", "the", "cloud", "provider", "." ]
python
train
CxAalto/gtfspy
gtfspy/gtfs.py
https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/gtfs.py#L1113-L1131
def increment_day_start_ut(self, day_start_ut, n_days=1): """Increment the GTFS-definition of "day start". Parameters ---------- day_start_ut : int unixtime of the previous start of day. If this time is between 12:00 or greater, there *will* be bugs. To solve t...
[ "def", "increment_day_start_ut", "(", "self", ",", "day_start_ut", ",", "n_days", "=", "1", ")", ":", "old_tz", "=", "self", ".", "set_current_process_time_zone", "(", ")", "day0", "=", "time", ".", "localtime", "(", "day_start_ut", "+", "43200", ")", "# tim...
Increment the GTFS-definition of "day start". Parameters ---------- day_start_ut : int unixtime of the previous start of day. If this time is between 12:00 or greater, there *will* be bugs. To solve this, run the input through day_start_ut first. n_...
[ "Increment", "the", "GTFS", "-", "definition", "of", "day", "start", "." ]
python
valid
berkeley-cocosci/Wallace
wallace/experiments.py
https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/experiments.py#L230-L234
def log(self, text, key="?????", force=False): """Print a string to the logs.""" if force or self.verbose: print ">>>> {} {}".format(key, text) sys.stdout.flush()
[ "def", "log", "(", "self", ",", "text", ",", "key", "=", "\"?????\"", ",", "force", "=", "False", ")", ":", "if", "force", "or", "self", ".", "verbose", ":", "print", "\">>>> {} {}\"", ".", "format", "(", "key", ",", "text", ")", "sys", ".", "stdou...
Print a string to the logs.
[ "Print", "a", "string", "to", "the", "logs", "." ]
python
train
funilrys/PyFunceble
PyFunceble/expiration_date.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L434-L593
def _extract(self): # pragma: no cover """ Extract the expiration date from the whois record. :return: The status of the domain. :rtype: str """ # We try to get the expiration date from the database. expiration_date_from_database = Whois().get_expiration_date()...
[ "def", "_extract", "(", "self", ")", ":", "# pragma: no cover", "# We try to get the expiration date from the database.", "expiration_date_from_database", "=", "Whois", "(", ")", ".", "get_expiration_date", "(", ")", "if", "expiration_date_from_database", ":", "# The hash of ...
Extract the expiration date from the whois record. :return: The status of the domain. :rtype: str
[ "Extract", "the", "expiration", "date", "from", "the", "whois", "record", "." ]
python
test
datasift/datasift-python
datasift/managed_sources.py
https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/managed_sources.py#L220-L247
def get(self, source_id=None, source_type=None, page=None, per_page=None): """ Get a specific managed source or a list of them. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceget :param source_id: (optional) target Source ID :type source_id...
[ "def", "get", "(", "self", ",", "source_id", "=", "None", ",", "source_type", "=", "None", ",", "page", "=", "None", ",", "per_page", "=", "None", ")", ":", "params", "=", "{", "}", "if", "source_type", ":", "params", "[", "'source_type'", "]", "=", ...
Get a specific managed source or a list of them. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceget :param source_id: (optional) target Source ID :type source_id: str :param source_type: (optional) data source name e.g. facebook_page, g...
[ "Get", "a", "specific", "managed", "source", "or", "a", "list", "of", "them", "." ]
python
train
taskcluster/taskcluster-client.py
taskcluster/aio/awsprovisioner.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/awsprovisioner.py#L251-L265
async def removeSecret(self, *args, **kwargs): """ Remove a Secret Remove a secret. After this call, a call to `getSecret` with the given token will return no information. It is very important that the consumer of a secret delete the secret from storage before handing ...
[ "async", "def", "removeSecret", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"removeSecret\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", "...
Remove a Secret Remove a secret. After this call, a call to `getSecret` with the given token will return no information. It is very important that the consumer of a secret delete the secret from storage before handing over control to untrusted processes to prevent credential a...
[ "Remove", "a", "Secret" ]
python
train
savvastj/nbashots
nbashots/api.py
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L361-L383
def get_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbrevia...
[ "def", "get_team_id", "(", "team_name", ")", ":", "df", "=", "get_all_team_ids", "(", ")", "df", "=", "df", "[", "df", ".", "TEAM_NAME", "==", "team_name", "]", "if", "len", "(", "df", ")", "==", "0", ":", "er", "=", "\"Invalid team name or there is no t...
Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbreviation. Returns ------- t...
[ "Returns", "the", "team", "ID", "associated", "with", "the", "team", "name", "that", "is", "passed", "in", "." ]
python
train
voidpp/python-tools
voidpp_tools/terminal.py
https://github.com/voidpp/python-tools/blob/0fc7460c827b02d8914411cedddadc23ccb3cc73/voidpp_tools/terminal.py#L10-L29
def get_size(): """ - get width and height of console - works on linux,os x,windows,cygwin(windows) originally retrieved from: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python """ current_os = platform.system() tuple_xy = None if current_os == '...
[ "def", "get_size", "(", ")", ":", "current_os", "=", "platform", ".", "system", "(", ")", "tuple_xy", "=", "None", "if", "current_os", "==", "'Windows'", ":", "tuple_xy", "=", "_get_terminal_size_windows", "(", ")", "if", "tuple_xy", "is", "None", ":", "tu...
- get width and height of console - works on linux,os x,windows,cygwin(windows) originally retrieved from: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
[ "-", "get", "width", "and", "height", "of", "console", "-", "works", "on", "linux", "os", "x", "windows", "cygwin", "(", "windows", ")", "originally", "retrieved", "from", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "56674...
python
train
APSL/transmanager
transmanager/manager.py
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/manager.py#L362-L371
def get_main_language(): """ returns the main language :return: """ try: main_language = TransLanguage.objects.filter(main_language=True).get() return main_language.code except TransLanguage.DoesNotExist: return TM_DEFAULT_LANGUAGE_CODE
[ "def", "get_main_language", "(", ")", ":", "try", ":", "main_language", "=", "TransLanguage", ".", "objects", ".", "filter", "(", "main_language", "=", "True", ")", ".", "get", "(", ")", "return", "main_language", ".", "code", "except", "TransLanguage", ".",...
returns the main language :return:
[ "returns", "the", "main", "language", ":", "return", ":" ]
python
train
KoffeinFlummi/Chronyk
chronyk/chronyk.py
https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L541-L552
def ctime(self, timezone=None): """Returns a ctime string. :param timezone = self.timezone The timezone (in seconds west of UTC) to return the value in. By default, the timezone used when constructing the class is used (local one by default). To use UTC, use timezone...
[ "def", "ctime", "(", "self", ",", "timezone", "=", "None", ")", ":", "if", "timezone", "is", "None", ":", "timezone", "=", "self", ".", "timezone", "return", "time", ".", "ctime", "(", "self", ".", "__timestamp__", "-", "timezone", ")" ]
Returns a ctime string. :param timezone = self.timezone The timezone (in seconds west of UTC) to return the value in. By default, the timezone used when constructing the class is used (local one by default). To use UTC, use timezone = 0. To use the local tz, use ...
[ "Returns", "a", "ctime", "string", "." ]
python
train
raphaelm/python-sepaxml
sepaxml/utils.py
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L64-L76
def int_to_decimal_str(integer): """ Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full...
[ "def", "int_to_decimal_str", "(", "integer", ")", ":", "int_string", "=", "str", "(", "integer", ")", "if", "len", "(", "int_string", ")", "<", "2", ":", "return", "\"0.\"", "+", "int_string", ".", "zfill", "(", "2", ")", "else", ":", "return", "int_st...
Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full stop decimal separator
[ "Helper", "to", "convert", "integers", "(", "representing", "cents", ")", "into", "decimal", "currency", "string", ".", "WARNING", ":", "DO", "NOT", "TRY", "TO", "DO", "THIS", "BY", "DIVISION", "FLOATING", "POINT", "ERRORS", "ARE", "NO", "FUN", "IN", "FINA...
python
train
davgeo/clear
clear/renamer.py
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L150-L261
def _GetShowID(self, stringSearch, origStringSearch = None): """ Search for given string as an existing entry in the database file name table or, if no match is found, as a show name from the TV guide. If an exact match is not found in the database the user can accept or decline the best match from...
[ "def", "_GetShowID", "(", "self", ",", "stringSearch", ",", "origStringSearch", "=", "None", ")", ":", "showInfo", "=", "tvfile", ".", "ShowInfo", "(", ")", "if", "origStringSearch", "is", "None", ":", "goodlogging", ".", "Log", ".", "Info", "(", "\"RENAME...
Search for given string as an existing entry in the database file name table or, if no match is found, as a show name from the TV guide. If an exact match is not found in the database the user can accept or decline the best match from the TV guide or can provide an alternate match to lookup. Param...
[ "Search", "for", "given", "string", "as", "an", "existing", "entry", "in", "the", "database", "file", "name", "table", "or", "if", "no", "match", "is", "found", "as", "a", "show", "name", "from", "the", "TV", "guide", "." ]
python
train
tansey/gfl
pygfl/utils.py
https://github.com/tansey/gfl/blob/ae0f078bab57aba9e827ed6162f247ff9dc2aa19/pygfl/utils.py#L160-L163
def vector_str(p, decimal_places=2, print_zero=True): '''Pretty-print the vector values.''' style = '{0:.' + str(decimal_places) + 'f}' return '[{0}]'.format(", ".join([' ' if not print_zero and a == 0 else style.format(a) for a in p]))
[ "def", "vector_str", "(", "p", ",", "decimal_places", "=", "2", ",", "print_zero", "=", "True", ")", ":", "style", "=", "'{0:.'", "+", "str", "(", "decimal_places", ")", "+", "'f}'", "return", "'[{0}]'", ".", "format", "(", "\", \"", ".", "join", "(", ...
Pretty-print the vector values.
[ "Pretty", "-", "print", "the", "vector", "values", "." ]
python
train
tcalmant/ipopo
pelix/shell/report.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L503-L511
def pelix_infos(self): """ Basic information about the Pelix framework instance """ framework = self.__context.get_framework() return { "version": framework.get_version(), "properties": framework.get_properties(), }
[ "def", "pelix_infos", "(", "self", ")", ":", "framework", "=", "self", ".", "__context", ".", "get_framework", "(", ")", "return", "{", "\"version\"", ":", "framework", ".", "get_version", "(", ")", ",", "\"properties\"", ":", "framework", ".", "get_properti...
Basic information about the Pelix framework instance
[ "Basic", "information", "about", "the", "Pelix", "framework", "instance" ]
python
train
datajoint/datajoint-python
datajoint/table.py
https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L571-L604
def lookup_class_name(name, context, depth=3): """ given a table name in the form `schema_name`.`table_name`, find its class in the context. :param name: `schema_name`.`table_name` :param context: dictionary representing the namespace :param depth: search depth into imported modules, helps avoid inf...
[ "def", "lookup_class_name", "(", "name", ",", "context", ",", "depth", "=", "3", ")", ":", "# breadth-first search", "nodes", "=", "[", "dict", "(", "context", "=", "context", ",", "context_name", "=", "''", ",", "depth", "=", "depth", ")", "]", "while",...
given a table name in the form `schema_name`.`table_name`, find its class in the context. :param name: `schema_name`.`table_name` :param context: dictionary representing the namespace :param depth: search depth into imported modules, helps avoid infinite recursion. :return: class name found in the conte...
[ "given", "a", "table", "name", "in", "the", "form", "schema_name", ".", "table_name", "find", "its", "class", "in", "the", "context", ".", ":", "param", "name", ":", "schema_name", ".", "table_name", ":", "param", "context", ":", "dictionary", "representing"...
python
train
clalancette/pycdlib
pycdlib/udf.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L1503-L1538
def new(self): # type: () -> None ''' A method to create a new UDF Partition Volume Descriptor. Parameters: None. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Partition Volume Descripto...
[ "def", "new", "(", "self", ")", ":", "# type: () -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'UDF Partition Volume Descriptor already initialized'", ")", "self", ".", "desc_tag", "=", "UDFTag", "(",...
A method to create a new UDF Partition Volume Descriptor. Parameters: None. Returns: Nothing.
[ "A", "method", "to", "create", "a", "new", "UDF", "Partition", "Volume", "Descriptor", "." ]
python
train
futursolo/magichttp
magichttp/readers.py
https://github.com/futursolo/magichttp/blob/84445d21d6829a43132da6d50a72501739d64ca4/magichttp/readers.py#L342-L400
async def read_until( self, separator: bytes=b"\n", *, keep_separator: bool=True) -> bytes: """ Read until the separator has been found. When the max size of the buffer has been reached, and the separator is not found, this method will raise a :class:`MaxBuff...
[ "async", "def", "read_until", "(", "self", ",", "separator", ":", "bytes", "=", "b\"\\n\"", ",", "*", ",", "keep_separator", ":", "bool", "=", "True", ")", "->", "bytes", ":", "async", "with", "self", ".", "_read_lock", ":", "self", ".", "_raise_exc_if_f...
Read until the separator has been found. When the max size of the buffer has been reached, and the separator is not found, this method will raise a :class:`MaxBufferLengthReachedError`. Similarly, if the end has been reached before found the separator it will raise a :class:`Sep...
[ "Read", "until", "the", "separator", "has", "been", "found", "." ]
python
train
cloud-custodian/cloud-custodian
c7n/filters/revisions.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/revisions.py#L156-L159
def transform_revision(self, revision): """make config revision look like describe output.""" config = self.manager.get_source('config') return config.load_resource(revision)
[ "def", "transform_revision", "(", "self", ",", "revision", ")", ":", "config", "=", "self", ".", "manager", ".", "get_source", "(", "'config'", ")", "return", "config", ".", "load_resource", "(", "revision", ")" ]
make config revision look like describe output.
[ "make", "config", "revision", "look", "like", "describe", "output", "." ]
python
train
UCSBarchlab/PyRTL
pyrtl/inputoutput.py
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L544-L551
def block_to_svg(block=None): """ Return an SVG for the block. """ block = working_block(block) try: from graphviz import Source return Source(block_to_graphviz_string())._repr_svg_() except ImportError: raise PyrtlError('need graphviz installed (try "pip install graphviz")')
[ "def", "block_to_svg", "(", "block", "=", "None", ")", ":", "block", "=", "working_block", "(", "block", ")", "try", ":", "from", "graphviz", "import", "Source", "return", "Source", "(", "block_to_graphviz_string", "(", ")", ")", ".", "_repr_svg_", "(", ")...
Return an SVG for the block.
[ "Return", "an", "SVG", "for", "the", "block", "." ]
python
train
tjcsl/ion
intranet/apps/emailfwd/views.py
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/emailfwd/views.py#L14-L43
def senior_email_forward_view(request): """Add a forwarding address for graduating seniors.""" if not request.user.is_senior: messages.error(request, "Only seniors can set their forwarding address.") return redirect("index") try: forward = SeniorEmailForward.objects.get(user=request....
[ "def", "senior_email_forward_view", "(", "request", ")", ":", "if", "not", "request", ".", "user", ".", "is_senior", ":", "messages", ".", "error", "(", "request", ",", "\"Only seniors can set their forwarding address.\"", ")", "return", "redirect", "(", "\"index\""...
Add a forwarding address for graduating seniors.
[ "Add", "a", "forwarding", "address", "for", "graduating", "seniors", "." ]
python
train
Julius2342/pyvlx
pyvlx/house_status_monitor.py
https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/house_status_monitor.py#L39-L44
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorDisableConfirmation): return False self.success = True return True
[ "async", "def", "handle_frame", "(", "self", ",", "frame", ")", ":", "if", "not", "isinstance", "(", "frame", ",", "FrameHouseStatusMonitorDisableConfirmation", ")", ":", "return", "False", "self", ".", "success", "=", "True", "return", "True" ]
Handle incoming API frame, return True if this was the expected frame.
[ "Handle", "incoming", "API", "frame", "return", "True", "if", "this", "was", "the", "expected", "frame", "." ]
python
train
gbowerman/azurerm
azurerm/keyvault.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/keyvault.py#L169-L183
def delete_keyvault_secret(access_token, vault_uri, secret_name): '''Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret...
[ "def", "delete_keyvault_secret", "(", "access_token", ",", "vault_uri", ",", "secret_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "vault_uri", ",", "'/secrets/'", ",", "secret_name", ",", "'?api-version='", ",", "'7.0'", "]", ")", "return", ...
Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret to add. Returns: HTTP response. 200 OK.
[ "Deletes", "a", "secret", "from", "a", "key", "vault", "using", "the", "key", "vault", "URI", "." ]
python
train
apache/incubator-heron
heron/tools/tracker/src/python/utils.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/utils.py#L137-L143
def get_heron_tracker_dir(): """ This will extract heron tracker directory from .pex file. :return: root location for heron-tools. """ path = "/".join(os.path.realpath(__file__).split('/')[:-8]) return normalized_class_path(path)
[ "def", "get_heron_tracker_dir", "(", ")", ":", "path", "=", "\"/\"", ".", "join", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ".", "split", "(", "'/'", ")", "[", ":", "-", "8", "]", ")", "return", "normalized_class_path", "(", "pat...
This will extract heron tracker directory from .pex file. :return: root location for heron-tools.
[ "This", "will", "extract", "heron", "tracker", "directory", "from", ".", "pex", "file", ".", ":", "return", ":", "root", "location", "for", "heron", "-", "tools", "." ]
python
valid
vsoch/helpme
helpme/action/record.py
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/record.py#L80-L101
def record_asciinema(): '''a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status. ''' import asciinema.conf...
[ "def", "record_asciinema", "(", ")", ":", "import", "asciinema", ".", "config", "as", "aconfig", "from", "asciinema", ".", "api", "import", "Api", "# Load the API class", "cfg", "=", "aconfig", ".", "load", "(", ")", "api", "=", "Api", "(", "cfg", ".", "...
a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status.
[ "a", "wrapper", "around", "generation", "of", "an", "asciinema", ".", "api", ".", "Api", "and", "a", "custom", "recorder", "to", "pull", "out", "the", "input", "arguments", "to", "the", "Record", "from", "argparse", ".", "The", "function", "generates", "a"...
python
train
inasafe/inasafe
safe/utilities/profiling.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L56-L65
def elapsed_time(self): """To know the duration of the function. This property might return None if the function is still running. """ if self._end_time: elapsed_time = round(self._end_time - self._start_time, 3) return elapsed_time else: retu...
[ "def", "elapsed_time", "(", "self", ")", ":", "if", "self", ".", "_end_time", ":", "elapsed_time", "=", "round", "(", "self", ".", "_end_time", "-", "self", ".", "_start_time", ",", "3", ")", "return", "elapsed_time", "else", ":", "return", "None" ]
To know the duration of the function. This property might return None if the function is still running.
[ "To", "know", "the", "duration", "of", "the", "function", "." ]
python
train
jonhadfield/python-hosts
python_hosts/utils.py
https://github.com/jonhadfield/python-hosts/blob/9ccaa8edc63418a91f10bf732b26070f21dd2ad0/python_hosts/utils.py#L63-L70
def dedupe_list(seq): """ Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
[ "def", "dedupe_list", "(", "seq", ")", ":", "seen", "=", "set", "(", ")", "return", "[", "x", "for", "x", "in", "seq", "if", "not", "(", "x", "in", "seen", "or", "seen", ".", "add", "(", "x", ")", ")", "]" ]
Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed
[ "Utility", "function", "to", "remove", "duplicates", "from", "a", "list", ":", "param", "seq", ":", "The", "sequence", "(", "list", ")", "to", "deduplicate", ":", "return", ":", "A", "list", "with", "original", "duplicates", "removed" ]
python
train
ninuxorg/nodeshot
nodeshot/networking/net/views.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/views.py#L145-L165
def initial(self, request, *args, **kwargs): """ Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node """ super(BaseInterfaceList, self).initial(request, *args, **kwargs) ...
[ "def", "initial", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "BaseInterfaceList", ",", "self", ")", ".", "initial", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# ensure device ...
Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node
[ "Custom", "initial", "method", ":", "*", "ensure", "device", "exists", "and", "store", "it", "in", "an", "instance", "attribute", "*", "change", "queryset", "to", "return", "only", "devices", "of", "current", "node" ]
python
train
choderalab/pymbar
pymbar/old_mbar.py
https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L1106-L1212
def computePerturbedFreeEnergies(self, u_ln, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Compute the free energies for a new set of states. Here, we desire the free energy differences among a set of new states, as well as the uncertainty estimates ...
[ "def", "computePerturbedFreeEnergies", "(", "self", ",", "u_ln", ",", "compute_uncertainty", "=", "True", ",", "uncertainty_method", "=", "None", ",", "warning_cutoff", "=", "1.0e-10", ",", "return_theta", "=", "False", ")", ":", "# Convert to np matrix.", "u_ln", ...
Compute the free energies for a new set of states. Here, we desire the free energy differences among a set of new states, as well as the uncertainty estimates in these differences. Parameters ---------- u_ln : np.ndarray, float, shape=(L, Nmax) u_ln[l,n] is the reduced pote...
[ "Compute", "the", "free", "energies", "for", "a", "new", "set", "of", "states", "." ]
python
train
maaku/python-bitcoin
bitcoin/authtree.py
https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/authtree.py#L61-L65
def count(self): "The number of items, pruned or otherwise, contained by this branch." if getattr(self, '_count', None) is None: self._count = getattr(self.node, 'count', 0) return self._count
[ "def", "count", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_count'", ",", "None", ")", "is", "None", ":", "self", ".", "_count", "=", "getattr", "(", "self", ".", "node", ",", "'count'", ",", "0", ")", "return", "self", ".", "_co...
The number of items, pruned or otherwise, contained by this branch.
[ "The", "number", "of", "items", "pruned", "or", "otherwise", "contained", "by", "this", "branch", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15270-L15285
def vzerog(v, ndim): """ Indicate whether a general-dimensional vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzerog_c.html :param v: Vector to be tested :type v: Array of floats :param ndim: Dimension of v :type ndim: int :return: true if and onl...
[ "def", "vzerog", "(", "v", ",", "ndim", ")", ":", "v", "=", "stypes", ".", "toDoubleVector", "(", "v", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "return", "bool", "(", "libspice", ".", "vzerog_c", "(", "v", ",", "ndim", ")", ")"...
Indicate whether a general-dimensional vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzerog_c.html :param v: Vector to be tested :type v: Array of floats :param ndim: Dimension of v :type ndim: int :return: true if and only if v is the zero vector :rt...
[ "Indicate", "whether", "a", "general", "-", "dimensional", "vector", "is", "the", "zero", "vector", "." ]
python
train
radjkarl/appBase
appbase/Session.py
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L397-L401
def open(self): """open a session to define in a dialog in an extra window""" filename = self.dialogs.getOpenFileName(filter="*.%s" % self.FTYPE) if filename: self.new(filename)
[ "def", "open", "(", "self", ")", ":", "filename", "=", "self", ".", "dialogs", ".", "getOpenFileName", "(", "filter", "=", "\"*.%s\"", "%", "self", ".", "FTYPE", ")", "if", "filename", ":", "self", ".", "new", "(", "filename", ")" ]
open a session to define in a dialog in an extra window
[ "open", "a", "session", "to", "define", "in", "a", "dialog", "in", "an", "extra", "window" ]
python
train
voicecom/pgtool
pgtool/pgtool.py
https://github.com/voicecom/pgtool/blob/36b8682bfca614d784fe58451e0cbc41315bc72e/pgtool/pgtool.py#L321-L328
def cmd_kill(): """Kills all active connections to the specified database(s).""" db = connect() count = terminate(db, args.databases) if count == 0: log.error("No connections could be killed") # Return status 1, like killall sys.exit(1)
[ "def", "cmd_kill", "(", ")", ":", "db", "=", "connect", "(", ")", "count", "=", "terminate", "(", "db", ",", "args", ".", "databases", ")", "if", "count", "==", "0", ":", "log", ".", "error", "(", "\"No connections could be killed\"", ")", "# Return stat...
Kills all active connections to the specified database(s).
[ "Kills", "all", "active", "connections", "to", "the", "specified", "database", "(", "s", ")", "." ]
python
train
pywbem/pywbem
pywbem/cim_obj.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_obj.py#L1302-L1310
def namespace(self, namespace): """Setter method; for a description see the getter method.""" # pylint: disable=attribute-defined-outside-init self._namespace = _ensure_unicode(namespace) if self._namespace is not None: # In Python 3, a byte string cannot be stripped by a uni...
[ "def", "namespace", "(", "self", ",", "namespace", ")", ":", "# pylint: disable=attribute-defined-outside-init", "self", ".", "_namespace", "=", "_ensure_unicode", "(", "namespace", ")", "if", "self", ".", "_namespace", "is", "not", "None", ":", "# In Python 3, a by...
Setter method; for a description see the getter method.
[ "Setter", "method", ";", "for", "a", "description", "see", "the", "getter", "method", "." ]
python
train
saltstack/salt
salt/modules/syslog_ng.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L738-L745
def _run_command(cmd, options=(), env=None): ''' Runs the command cmd with options as its CLI parameters and returns the result as a dictionary. ''' params = [cmd] params.extend(options) return __salt__['cmd.run_all'](params, env=env, python_shell=False)
[ "def", "_run_command", "(", "cmd", ",", "options", "=", "(", ")", ",", "env", "=", "None", ")", ":", "params", "=", "[", "cmd", "]", "params", ".", "extend", "(", "options", ")", "return", "__salt__", "[", "'cmd.run_all'", "]", "(", "params", ",", ...
Runs the command cmd with options as its CLI parameters and returns the result as a dictionary.
[ "Runs", "the", "command", "cmd", "with", "options", "as", "its", "CLI", "parameters", "and", "returns", "the", "result", "as", "a", "dictionary", "." ]
python
train
docker/docker-py
docker/api/image.py
https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/image.py#L61-L93
def images(self, name=None, quiet=False, all=False, filters=None): """ List images. Similar to the ``docker images`` command. Args: name (str): Only show images belonging to the repository ``name`` quiet (bool): Only return numeric IDs as a list. all (bool): ...
[ "def", "images", "(", "self", ",", "name", "=", "None", ",", "quiet", "=", "False", ",", "all", "=", "False", ",", "filters", "=", "None", ")", ":", "params", "=", "{", "'filter'", ":", "name", ",", "'only_ids'", ":", "1", "if", "quiet", "else", ...
List images. Similar to the ``docker images`` command. Args: name (str): Only show images belonging to the repository ``name`` quiet (bool): Only return numeric IDs as a list. all (bool): Show intermediate image layers. By default, these are filtered out. ...
[ "List", "images", ".", "Similar", "to", "the", "docker", "images", "command", "." ]
python
train
Microsoft/ApplicationInsights-Python
applicationinsights/channel/contracts/PageViewPerfData.py
https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/PageViewPerfData.py#L93-L102
def perf_total(self, value): """The perf_total property. Args: value (string). the property value. """ if value == self._defaults['perfTotal'] and 'perfTotal' in self._values: del self._values['perfTotal'] else: self._values['perfTotal...
[ "def", "perf_total", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'perfTotal'", "]", "and", "'perfTotal'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'perfTotal'", "]", "else", "...
The perf_total property. Args: value (string). the property value.
[ "The", "perf_total", "property", ".", "Args", ":", "value", "(", "string", ")", ".", "the", "property", "value", "." ]
python
train