repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
jxtech/wechatpy
wechatpy/client/api/wifi.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/wifi.py#L133-L151
def set_homepage(self, shop_id, template_id, url=None): """ 设置商家主页 详情请参考 http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html :param shop_id: 门店 ID :param template_id: 模板ID,0-默认模板,1-自定义url :param url: 自定义链接,当template_id为1时必填 :return: 返回的 ...
[ "def", "set_homepage", "(", "self", ",", "shop_id", ",", "template_id", ",", "url", "=", "None", ")", ":", "data", "=", "{", "'shop_id'", ":", "shop_id", ",", "'template_id'", ":", "template_id", ",", "}", "if", "url", ":", "data", "[", "'struct'", "]"...
设置商家主页 详情请参考 http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html :param shop_id: 门店 ID :param template_id: 模板ID,0-默认模板,1-自定义url :param url: 自定义链接,当template_id为1时必填 :return: 返回的 JSON 数据包
[ "设置商家主页" ]
python
train
28
OpenMath/py-openmath
openmath/convert.py
https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert.py#L151-L163
def to_openmath(self, obj): """ Convert Python object to OpenMath """ for cl, conv in reversed(self._conv_to_om): if cl is None or isinstance(obj, cl): try: return conv(obj) except CannotConvertError: continue i...
[ "def", "to_openmath", "(", "self", ",", "obj", ")", ":", "for", "cl", ",", "conv", "in", "reversed", "(", "self", ".", "_conv_to_om", ")", ":", "if", "cl", "is", "None", "or", "isinstance", "(", "obj", ",", "cl", ")", ":", "try", ":", "return", "...
Convert Python object to OpenMath
[ "Convert", "Python", "object", "to", "OpenMath" ]
python
test
34.076923
Unity-Technologies/ml-agents
ml-agents/mlagents/trainers/tensorflow_to_barracuda.py
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/tensorflow_to_barracuda.py#L523-L530
def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == 'NCHW': return [shape[2], shape[3]] return [shape[1], shape[2]]
[ "def", "pool_to_HW", "(", "shape", ",", "data_frmt", ")", ":", "if", "len", "(", "shape", ")", "!=", "4", ":", "return", "shape", "# Not NHWC|NCHW, return as is", "if", "data_frmt", "==", "'NCHW'", ":", "return", "[", "shape", "[", "2", "]", ",", "shape"...
Convert from NHWC|NCHW => HW
[ "Convert", "from", "NHWC|NCHW", "=", ">", "HW" ]
python
train
30.25
rackerlabs/simpl
simpl/db/mongodb.py
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/db/mongodb.py#L265-L278
def client(self): """Return a lazy-instantiated pymongo client. When running with eventlet, connection causes IO and can result in more than one MongoDB client getting instantiatied, so we wrap the code in a semaphore to make sure only one mongodb client is instantiated per Simp...
[ "def", "client", "(", "self", ")", ":", "if", "eventlet", ":", "with", "self", ".", "client_lock", ":", "self", ".", "_set_client", "(", ")", "else", ":", "self", ".", "_set_client", "(", ")", "return", "self", ".", "_client" ]
Return a lazy-instantiated pymongo client. When running with eventlet, connection causes IO and can result in more than one MongoDB client getting instantiatied, so we wrap the code in a semaphore to make sure only one mongodb client is instantiated per SimplDB class.
[ "Return", "a", "lazy", "-", "instantiated", "pymongo", "client", "." ]
python
train
35.214286
shreyaspotnis/rampage
rampage/daq/daq.py
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L255-L267
def padDigitalData(self, dig_data, n): """Pad dig_data with its last element so that the new array is a multiple of n. """ n = int(n) l0 = len(dig_data) if l0 % n == 0: return dig_data # no need of padding else: ladd = n - (l0 % n) ...
[ "def", "padDigitalData", "(", "self", ",", "dig_data", ",", "n", ")", ":", "n", "=", "int", "(", "n", ")", "l0", "=", "len", "(", "dig_data", ")", "if", "l0", "%", "n", "==", "0", ":", "return", "dig_data", "# no need of padding", "else", ":", "lad...
Pad dig_data with its last element so that the new array is a multiple of n.
[ "Pad", "dig_data", "with", "its", "last", "element", "so", "that", "the", "new", "array", "is", "a", "multiple", "of", "n", "." ]
python
train
35.538462
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L264-L276
def send(self, request): """Queue a request to be sent to the RPC.""" if self._UNARY_REQUESTS: try: self._send_unary_request(request) except exceptions.GoogleAPICallError: _LOGGER.debug( "Exception while sending unary RPC. This ...
[ "def", "send", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_UNARY_REQUESTS", ":", "try", ":", "self", ".", "_send_unary_request", "(", "request", ")", "except", "exceptions", ".", "GoogleAPICallError", ":", "_LOGGER", ".", "debug", "(", "\"E...
Queue a request to be sent to the RPC.
[ "Queue", "a", "request", "to", "be", "sent", "to", "the", "RPC", "." ]
python
train
38
LonamiWebs/Telethon
telethon/client/messages.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/messages.py#L879-L932
async def send_read_acknowledge( self, entity, message=None, *, max_id=None, clear_mentions=False): """ Sends a "read acknowledge" (i.e., notifying the given peer that we've read their messages, also known as the "double check"). This effectively marks a message as read (or ...
[ "async", "def", "send_read_acknowledge", "(", "self", ",", "entity", ",", "message", "=", "None", ",", "*", ",", "max_id", "=", "None", ",", "clear_mentions", "=", "False", ")", ":", "if", "max_id", "is", "None", ":", "if", "not", "message", ":", "max_...
Sends a "read acknowledge" (i.e., notifying the given peer that we've read their messages, also known as the "double check"). This effectively marks a message as read (or more than one) in the given conversation. If neither message nor maximum ID are provided, all messages will be ...
[ "Sends", "a", "read", "acknowledge", "(", "i", ".", "e", ".", "notifying", "the", "given", "peer", "that", "we", "ve", "read", "their", "messages", "also", "known", "as", "the", "double", "check", ")", "." ]
python
train
36.518519
noxdafox/clipspy
clips/classes.py
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L272-L281
def module(self): """The module in which the Class is defined. Python equivalent of the CLIPS defglobal-module command. """ modname = ffi.string(lib.EnvDefclassModule(self._env, self._cls)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, d...
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDefclassModule", "(", "self", ".", "_env", ",", "self", ".", "_cls", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "_en...
The module in which the Class is defined. Python equivalent of the CLIPS defglobal-module command.
[ "The", "module", "in", "which", "the", "Class", "is", "defined", "." ]
python
train
32
pycontribs/python-crowd
crowd.py
https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L136-L148
def _delete(self, *args, **kwargs): """Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.delete(*args, **kwargs) ...
[ "def", "_delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'timeout'", "not", "in", "kwargs", ":", "kwargs", "[", "'timeout'", "]", "=", "self", ".", "timeout", "req", "=", "self", ".", "session", ".", "delete", "(",...
Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object
[ "Wrapper", "around", "Requests", "for", "DELETE", "requests" ]
python
train
25.076923
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L579-L645
def metrics(ty, query, query_type, **kwargs): """ Outputs runtime metrics collected from cocaine-runtime and its services. This command shows runtime metrics collected from cocaine-runtime and its services during their lifetime. There are four kind of metrics available: gauges, counters, meters and...
[ "def", "metrics", "(", "ty", ",", "query", ",", "query_type", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'metrics'", ",", "*", "*", "{", "'metrics'", ":", "ctx", ".", ...
Outputs runtime metrics collected from cocaine-runtime and its services. This command shows runtime metrics collected from cocaine-runtime and its services during their lifetime. There are four kind of metrics available: gauges, counters, meters and timers. \b - Gauges - an instantaneous measure...
[ "Outputs", "runtime", "metrics", "collected", "from", "cocaine", "-", "runtime", "and", "its", "services", "." ]
python
train
45.970149
celiao/tmdbsimple
tmdbsimple/movies.py
https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/movies.py#L185-L200
def releases(self, **kwargs): """ Get the release date and certification information by country for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the ...
[ "def", "releases", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_id_path", "(", "'releases'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "respo...
Get the release date and certification information by country for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API.
[ "Get", "the", "release", "date", "and", "certification", "information", "by", "country", "for", "a", "specific", "movie", "id", "." ]
python
test
29.875
corpusops/pdbclone
lib/pdb_clone/pdb.py
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1291-L1317
def do_jump(self, arg): """j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are...
[ "def", "do_jump", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "curindex", "+", "1", "!=", "len", "(", "self", ".", "stack", ")", ":", "self", ".", "error", "(", "'You can only jump within the bottom frame'", ")", "return", "try", ":", "arg", ...
j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are allowed -- for instance it...
[ "j", "(", "ump", ")", "lineno", "Set", "the", "next", "line", "that", "will", "be", "executed", ".", "Only", "available", "in", "the", "bottom", "-", "most", "frame", ".", "This", "lets", "you", "jump", "back", "and", "execute", "code", "again", "or", ...
python
train
41.333333
inveniosoftware-attic/invenio-upgrader
invenio_upgrader/engine.py
https://github.com/inveniosoftware-attic/invenio-upgrader/blob/cee4bcb118515463ecf6de1421642007f79a9fcd/invenio_upgrader/engine.py#L314-L318
def register_success(self, upgrade): """Register a successful upgrade.""" u = Upgrade(upgrade=upgrade.name, applied=datetime.now()) db.session.add(u) db.session.commit()
[ "def", "register_success", "(", "self", ",", "upgrade", ")", ":", "u", "=", "Upgrade", "(", "upgrade", "=", "upgrade", ".", "name", ",", "applied", "=", "datetime", ".", "now", "(", ")", ")", "db", ".", "session", ".", "add", "(", "u", ")", "db", ...
Register a successful upgrade.
[ "Register", "a", "successful", "upgrade", "." ]
python
train
39.4
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L421-L438
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None): """ Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected column...
[ "def", "set_selection_strategy", "(", "self", ",", "strategy", "=", "'spectral-oasis'", ",", "nsel", "=", "1", ",", "neig", "=", "None", ")", ":", "self", ".", "_selection_strategy", "=", "selection_strategy", "(", "self", ",", "strategy", ",", "nsel", ",", ...
Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` s...
[ "Defines", "the", "column", "selection", "strategy" ]
python
train
47.833333
cloudmesh-cmd3/cmd3
cmd3/shell.py
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/shell.py#L380-L503
def main(): """cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, ...
[ "def", "main", "(", ")", ":", "echo", "=", "False", "try", ":", "arguments", "=", "docopt", "(", "main", ".", "__doc__", ",", "help", "=", "True", ")", "# fixing the help parameter parsing", "if", "arguments", "[", "'help'", "]", ":", "arguments", "[", "...
cm. Usage: cm [-q] help cm [-v] [-b] [--file=SCRIPT] [-i] [COMMAND ...] Arguments: COMMAND A command to be executed Options: --file=SCRIPT -f SCRIPT Executes the script -i After start keep the shell interactive, ot...
[ "cm", "." ]
python
train
26.419355
juju/python-libjuju
juju/client/gocookies.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L78-L102
def py_to_go_cookie(py_cookie): '''Convert a python cookie to the JSON-marshalable Go-style cookie form.''' # TODO (perhaps): # HttpOnly # Creation # LastAccess # Updated # not done properly: CanonicalHost. go_cookie = { 'Name': py_cookie.name, 'Value': py_cookie....
[ "def", "py_to_go_cookie", "(", "py_cookie", ")", ":", "# TODO (perhaps):", "# HttpOnly", "# Creation", "# LastAccess", "# Updated", "# not done properly: CanonicalHost.", "go_cookie", "=", "{", "'Name'", ":", "py_cookie", ".", "name", ",", "'Value'", ":", "py_co...
Convert a python cookie to the JSON-marshalable Go-style cookie form.
[ "Convert", "a", "python", "cookie", "to", "the", "JSON", "-", "marshalable", "Go", "-", "style", "cookie", "form", "." ]
python
train
37
openid/JWTConnect-Python-OidcService
src/oidcservice/util.py
https://github.com/openid/JWTConnect-Python-OidcService/blob/759ab7adef30a7e3b9d75475e2971433b9613788/src/oidcservice/util.py#L72-L83
def modsplit(s): """Split importable""" if ':' in s: c = s.split(':') if len(c) != 2: raise ValueError("Syntax error: {s}") return c[0], c[1] else: c = s.split('.') if len(c) < 2: raise ValueError("Syntax error: {s}") return '.'.join(c[...
[ "def", "modsplit", "(", "s", ")", ":", "if", "':'", "in", "s", ":", "c", "=", "s", ".", "split", "(", "':'", ")", "if", "len", "(", "c", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Syntax error: {s}\"", ")", "return", "c", "[", "0", "]"...
Split importable
[ "Split", "importable" ]
python
train
26.75
SmokinCaterpillar/pypet
pypet/parameter.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/parameter.py#L889-L930
def _values_of_same_type(self, val1, val2): """Checks if two values agree in type. Raises a TypeError if both values are not supported by the parameter. Returns false if only one of the two values is supported by the parameter. Example usage: >>>param._values_of_same_type(42,4...
[ "def", "_values_of_same_type", "(", "self", ",", "val1", ",", "val2", ")", ":", "if", "self", ".", "f_supports", "(", "val1", ")", "!=", "self", ".", "f_supports", "(", "val2", ")", ":", "return", "False", "if", "not", "self", ".", "f_supports", "(", ...
Checks if two values agree in type. Raises a TypeError if both values are not supported by the parameter. Returns false if only one of the two values is supported by the parameter. Example usage: >>>param._values_of_same_type(42,43) True >>>param._values_of_same_type(...
[ "Checks", "if", "two", "values", "agree", "in", "type", "." ]
python
test
33.285714
Fuyukai/ConfigMaster
configmaster/JSONConfigFile.py
https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/JSONConfigFile.py#L49-L58
def json_dump_hook(cfg, text: bool=False): """ Dumps all the data into a JSON file. """ data = cfg.config.dump() if not text: json.dump(data, cfg.fd) else: return json.dumps(data)
[ "def", "json_dump_hook", "(", "cfg", ",", "text", ":", "bool", "=", "False", ")", ":", "data", "=", "cfg", ".", "config", ".", "dump", "(", ")", "if", "not", "text", ":", "json", ".", "dump", "(", "data", ",", "cfg", ".", "fd", ")", "else", ":"...
Dumps all the data into a JSON file.
[ "Dumps", "all", "the", "data", "into", "a", "JSON", "file", "." ]
python
train
21.1
tensorflow/tensorboard
tensorboard/backend/event_processing/event_accumulator.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/event_accumulator.py#L220-L231
def Reload(self): """Loads all events added since the last call to `Reload`. If `Reload` was never called, loads all events in the file. Returns: The `EventAccumulator`. """ with self._generator_mutex: for event in self._generator.Load(): self._ProcessEvent(event) return se...
[ "def", "Reload", "(", "self", ")", ":", "with", "self", ".", "_generator_mutex", ":", "for", "event", "in", "self", ".", "_generator", ".", "Load", "(", ")", ":", "self", ".", "_ProcessEvent", "(", "event", ")", "return", "self" ]
Loads all events added since the last call to `Reload`. If `Reload` was never called, loads all events in the file. Returns: The `EventAccumulator`.
[ "Loads", "all", "events", "added", "since", "the", "last", "call", "to", "Reload", "." ]
python
train
25.916667
log2timeline/plaso
plaso/analysis/browser_search.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/browser_search.py#L311-L361
def ExamineEvent(self, mediator, event): """Analyzes an event. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event to examine. """ # This event requires an URL attribute. ...
[ "def", "ExamineEvent", "(", "self", ",", "mediator", ",", "event", ")", ":", "# This event requires an URL attribute.", "url", "=", "getattr", "(", "event", ",", "'url'", ",", "None", ")", "if", "not", "url", ":", "return", "# TODO: refactor this the source should...
Analyzes an event. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event to examine.
[ "Analyzes", "an", "event", "." ]
python
train
33.019608
Neurita/boyle
boyle/nifti/utils.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L216-L250
def filter_icc(icc, mask=None, thr=2, zscore=True, mode="+"): """ Threshold then mask an IC correlation map. Parameters ---------- icc: img-like The 'raw' ICC map. mask: img-like If not None. Will apply this masks in the end of the process. thr: float The threshold valu...
[ "def", "filter_icc", "(", "icc", ",", "mask", "=", "None", ",", "thr", "=", "2", ",", "zscore", "=", "True", ",", "mode", "=", "\"+\"", ")", ":", "if", "zscore", ":", "icc_filt", "=", "thr_img", "(", "icc_img_to_zscore", "(", "icc", ")", ",", "thr"...
Threshold then mask an IC correlation map. Parameters ---------- icc: img-like The 'raw' ICC map. mask: img-like If not None. Will apply this masks in the end of the process. thr: float The threshold value. zscore: bool If True will calculate the z-score of the...
[ "Threshold", "then", "mask", "an", "IC", "correlation", "map", ".", "Parameters", "----------", "icc", ":", "img", "-", "like", "The", "raw", "ICC", "map", "." ]
python
valid
25.457143
mjirik/imcut
imcut/graph.py
https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L404-L415
def generate_base_grid(self, vtk_filename=None): """ Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return: """ nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize) self.add_nodes(nd) self.add_edges(ed, ed_dir, ...
[ "def", "generate_base_grid", "(", "self", ",", "vtk_filename", "=", "None", ")", ":", "nd", ",", "ed", ",", "ed_dir", "=", "self", ".", "gen_grid_fcn", "(", "self", ".", "data", ".", "shape", ",", "self", ".", "voxelsize", ")", "self", ".", "add_nodes"...
Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return:
[ "Run", "first", "step", "of", "algorithm", ".", "Next", "step", "is", "split_voxels", ":", "param", "vtk_filename", ":", ":", "return", ":" ]
python
train
33.916667
devassistant/devassistant
devassistant/yaml_checker.py
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L80-L96
def _check_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.a...
[ "def", "_check_args", "(", "self", ",", "source", ")", ":", "path", "=", "[", "source", "]", "args", "=", "self", ".", "parsed_yaml", ".", "get", "(", "'args'", ",", "{", "}", ")", "self", ".", "_assert_struct_type", "(", "args", ",", "'args'", ",", ...
Validate the argument section. Args may be either a dict or a list (to allow multiple positional args).
[ "Validate", "the", "argument", "section", "." ]
python
train
45.941176
saltstack/salt
salt/modules/pkg_resource.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L91-L177
def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well ...
[ "def", "parse_targets", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "saltenv", "=", "'base'", ",", "normalize", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "'__env__'", "in", "kwargs", ":", "# \"env...
Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets
[ "Parses", "the", "input", "to", "pkg", ".", "install", "and", "returns", "back", "the", "package", "(", "s", ")", "to", "be", "installed", ".", "Returns", "a", "list", "of", "packages", "as", "well", "as", "a", "string", "noting", "whether", "the", "pa...
python
train
34.37931
hsolbrig/pyjsg
pyjsg/parser_impl/jsg_pairdef_parser.py
https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/parser_impl/jsg_pairdef_parser.py#L43-L57
def members_entries(self, all_are_optional: Optional[bool] = False) -> List[Tuple[str, str]]: """ Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing reference types :param all_are_optional: If true, all types are forced optional :return: raw...
[ "def", "members_entries", "(", "self", ",", "all_are_optional", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "if", "self", ".", "_type_reference", ":", "rval", ":", "List", "...
Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing reference types :param all_are_optional: If true, all types are forced optional :return: raw name/ signature type for all elements in this pair
[ "Generate", "a", "list", "quoted", "raw", "name", "signature", "type", "entries", "for", "this", "pairdef", "recursively", "traversing", "reference", "types" ]
python
train
57.666667
RiotGames/cloud-inquisitor
backend/cloud_inquisitor/plugins/notifiers/email.py
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/notifiers/email.py#L150-L200
def __send_smtp_email(self, recipients, subject, html_body, text_body): """Send an email using SMTP Args: recipients (`list` of `str`): List of recipient email addresses subject (str): Subject of the email html_body (str): HTML body of the email text_body...
[ "def", "__send_smtp_email", "(", "self", ",", "recipients", ",", "subject", ",", "html_body", ",", "text_body", ")", ":", "smtp", "=", "smtplib", ".", "SMTP", "(", "dbconfig", ".", "get", "(", "'smtp_server'", ",", "NS_EMAIL", ",", "'localhost'", ")", ",",...
Send an email using SMTP Args: recipients (`list` of `str`): List of recipient email addresses subject (str): Subject of the email html_body (str): HTML body of the email text_body (str): Text body of the email Returns: `None`
[ "Send", "an", "email", "using", "SMTP" ]
python
train
34.235294
ScottDuckworth/python-anyvcs
anyvcs/git.py
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/git.py#L66-L70
def create(cls, path, encoding='utf-8'): """Create a new bare repository""" cmd = [GIT, 'init', '--quiet', '--bare', path] subprocess.check_call(cmd) return cls(path, encoding)
[ "def", "create", "(", "cls", ",", "path", ",", "encoding", "=", "'utf-8'", ")", ":", "cmd", "=", "[", "GIT", ",", "'init'", ",", "'--quiet'", ",", "'--bare'", ",", "path", "]", "subprocess", ".", "check_call", "(", "cmd", ")", "return", "cls", "(", ...
Create a new bare repository
[ "Create", "a", "new", "bare", "repository" ]
python
train
40.8
googleads/googleads-python-lib
examples/adwords/adwords_appengine_demo/views/init_view.py
https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/adwords_appengine_demo/views/init_view.py#L29-L41
def get(self): """Handle get request.""" try: app_user = InitUser() if (app_user.client_id and app_user.client_secret and app_user.adwords_manager_cid and app_user.developer_token and app_user.refresh_token): self.redirect('/showAccounts') else: self.redire...
[ "def", "get", "(", "self", ")", ":", "try", ":", "app_user", "=", "InitUser", "(", ")", "if", "(", "app_user", ".", "client_id", "and", "app_user", ".", "client_secret", "and", "app_user", ".", "adwords_manager_cid", "and", "app_user", ".", "developer_token"...
Handle get request.
[ "Handle", "get", "request", "." ]
python
train
29.461538
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L203-L248
def error_page( participant=None, error_text=None, compensate=True, error_type="default", request_data="", ): """Render HTML for error page.""" config = _config() if error_text is None: error_text = """There has been an error and so you are unable to continue, sorry!""" ...
[ "def", "error_page", "(", "participant", "=", "None", ",", "error_text", "=", "None", ",", "compensate", "=", "True", ",", "error_type", "=", "\"default\"", ",", "request_data", "=", "\"\"", ",", ")", ":", "config", "=", "_config", "(", ")", "if", "error...
Render HTML for error page.
[ "Render", "HTML", "for", "error", "page", "." ]
python
train
29.195652
HDI-Project/BTB
examples/rosenbrock.py
https://github.com/HDI-Project/BTB/blob/7f489ebc5591bd0886652ef743098c022d7f7460/examples/rosenbrock.py#L13-L15
def rosenbrock(x, y, a=1, b=100): """Bigger is better; global optimum at x=a, y=a**2""" return -1 * ((a - x)**2 + b * (y - x**2)**2)
[ "def", "rosenbrock", "(", "x", ",", "y", ",", "a", "=", "1", ",", "b", "=", "100", ")", ":", "return", "-", "1", "*", "(", "(", "a", "-", "x", ")", "**", "2", "+", "b", "*", "(", "y", "-", "x", "**", "2", ")", "**", "2", ")" ]
Bigger is better; global optimum at x=a, y=a**2
[ "Bigger", "is", "better", ";", "global", "optimum", "at", "x", "=", "a", "y", "=", "a", "**", "2" ]
python
train
46
sdispater/poetry
poetry/mixology/partial_solution.py
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L141-L169
def _register(self, assignment): # type: (Assignment) -> None """ Registers an Assignment in _positive or _negative. """ name = assignment.dependency.name old_positive = self._positive.get(name) if old_positive is not None: self._positive[name] = old_positive...
[ "def", "_register", "(", "self", ",", "assignment", ")", ":", "# type: (Assignment) -> None", "name", "=", "assignment", ".", "dependency", ".", "name", "old_positive", "=", "self", ".", "_positive", ".", "get", "(", "name", ")", "if", "old_positive", "is", ...
Registers an Assignment in _positive or _negative.
[ "Registers", "an", "Assignment", "in", "_positive", "or", "_negative", "." ]
python
train
32.448276
gabstopper/smc-python
smc/elements/other.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/other.py#L64-L83
def add_element(self, element): """ Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: elemen...
[ "def", "add_element", "(", "self", ",", "element", ")", ":", "element", "=", "element_resolver", "(", "element", ")", "self", ".", "make_request", "(", "ModificationFailed", ",", "method", "=", "'create'", ",", "resource", "=", "'category_add_element'", ",", "...
Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed:...
[ "Element", "can", "be", "href", "or", "type", ":", "py", ":", "class", ":", "smc", ".", "base", ".", "model", ".", "Element", "::" ]
python
train
31.2
brianhie/scanorama
scanorama/scanorama.py
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L172-L216
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
[ "def", "correct_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "if", "'return_dimred'", "in", "kwargs", "and", "kwargs", "[", "'return_dimred'", "]", ":", "datasets_dimred", ",", "datasets", ",", "genes", "=", "correct", "(", "[", "adata", ".",...
Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of parameters to use for batch correction. Returns...
[ "Batch", "correct", "a", "list", "of", "scanpy", ".", "api", ".", "AnnData", "." ]
python
train
32.155556
welbornprod/colr
colr/__main__.py
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L333-L344
def list_known_codes(s, unique=True, rgb_mode=False): """ Find and print all known escape codes in a string, using get_known_codes. """ total = 0 for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode): total += 1 print(codedesc) plural = 'code' if total == 1 els...
[ "def", "list_known_codes", "(", "s", ",", "unique", "=", "True", ",", "rgb_mode", "=", "False", ")", ":", "total", "=", "0", "for", "codedesc", "in", "get_known_codes", "(", "s", ",", "unique", "=", "unique", ",", "rgb_mode", "=", "rgb_mode", ")", ":",...
Find and print all known escape codes in a string, using get_known_codes.
[ "Find", "and", "print", "all", "known", "escape", "codes", "in", "a", "string", "using", "get_known_codes", "." ]
python
train
38.583333
flatangle/flatlib
flatlib/predictives/primarydirections.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/predictives/primarydirections.py#L136-L153
def G(self, ID, lat, lon): """ Creates a generic entry for an object. """ # Equatorial coordinates eqM = utils.eqCoords(lon, lat) eqZ = eqM if lat != 0: eqZ = utils.eqCoords(lon, 0) return { 'id': ID, 'lat': lat, ...
[ "def", "G", "(", "self", ",", "ID", ",", "lat", ",", "lon", ")", ":", "# Equatorial coordinates", "eqM", "=", "utils", ".", "eqCoords", "(", "lon", ",", "lat", ")", "eqZ", "=", "eqM", "if", "lat", "!=", "0", ":", "eqZ", "=", "utils", ".", "eqCoor...
Creates a generic entry for an object.
[ "Creates", "a", "generic", "entry", "for", "an", "object", "." ]
python
train
24.5
saltstack/salt
salt/thorium/check.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/check.py#L277-L305
def event(name): ''' Chekcs for a specific event match and returns result True if the match happens USAGE: .. code-block:: yaml salt/foo/*/bar: check.event run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
[ "def", "event", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "False", "}", "for", "event", "in", "__events__", ":", "if", "salt", ".", "utils", ...
Chekcs for a specific event match and returns result True if the match happens USAGE: .. code-block:: yaml salt/foo/*/bar: check.event run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: - check: salt/foo...
[ "Chekcs", "for", "a", "specific", "event", "match", "and", "returns", "result", "True", "if", "the", "match", "happens" ]
python
train
20.172414
gwastro/pycbc
pycbc/distributions/power_law.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/power_law.py#L214-L238
def from_config(cls, cp, section, variable_args): """Returns a distribution based on a configuration file. The parameters for the distribution are retrieved from the section titled "[`section`-`variable_args`]" in the config file. Parameters ---------- cp : pycbc.workflo...
[ "def", "from_config", "(", "cls", ",", "cp", ",", "section", ",", "variable_args", ")", ":", "return", "super", "(", "UniformPowerLaw", ",", "cls", ")", ".", "from_config", "(", "cp", ",", "section", ",", "variable_args", ",", "bounds_required", "=", "True...
Returns a distribution based on a configuration file. The parameters for the distribution are retrieved from the section titled "[`section`-`variable_args`]" in the config file. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration fil...
[ "Returns", "a", "distribution", "based", "on", "a", "configuration", "file", ".", "The", "parameters", "for", "the", "distribution", "are", "retrieved", "from", "the", "section", "titled", "[", "section", "-", "variable_args", "]", "in", "the", "config", "file...
python
train
42.08
reingart/pyafipws
padron.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L397-L410
def DescargarConstancia(self, nro_doc, filename="constancia.pdf"): "Llama a la API para descargar una constancia de inscripcion (PDF)" if not self.client: self.Conectar() self.response = self.client("sr-padron", "v1", "constancia", str(nro_doc)) if self.response.startswith("{...
[ "def", "DescargarConstancia", "(", "self", ",", "nro_doc", ",", "filename", "=", "\"constancia.pdf\"", ")", ":", "if", "not", "self", ".", "client", ":", "self", ".", "Conectar", "(", ")", "self", ".", "response", "=", "self", ".", "client", "(", "\"sr-p...
Llama a la API para descargar una constancia de inscripcion (PDF)
[ "Llama", "a", "la", "API", "para", "descargar", "una", "constancia", "de", "inscripcion", "(", "PDF", ")" ]
python
train
42.857143
nprapps/copydoc
copydoc.py
https://github.com/nprapps/copydoc/blob/e1ab09b287beb0439748c319cf165cbc06c66624/copydoc.py#L110-L116
def create_italic(self, tag): """ See if span tag has italic style and wrap with em tag. """ style = tag.get('style') if style and 'font-style:italic' in style: tag.wrap(self.soup.new_tag('em'))
[ "def", "create_italic", "(", "self", ",", "tag", ")", ":", "style", "=", "tag", ".", "get", "(", "'style'", ")", "if", "style", "and", "'font-style:italic'", "in", "style", ":", "tag", ".", "wrap", "(", "self", ".", "soup", ".", "new_tag", "(", "'em'...
See if span tag has italic style and wrap with em tag.
[ "See", "if", "span", "tag", "has", "italic", "style", "and", "wrap", "with", "em", "tag", "." ]
python
test
34.285714
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/helpers.py
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/helpers.py#L12-L63
def get_list_url_filtered_by_field_value(view, model, name, reverse=False): """Get the URL if a filter of model[name] value was appended. This allows programatically adding filters. This is used in the specialized case of filtering deeper into a list by a field's value. For instance, since there can b...
[ "def", "get_list_url_filtered_by_field_value", "(", "view", ",", "model", ",", "name", ",", "reverse", "=", "False", ")", ":", "view_args", "=", "view", ".", "_get_list_extra_args", "(", ")", "def", "create_filter_arg", "(", "field_name", ",", "value", ")", ":...
Get the URL if a filter of model[name] value was appended. This allows programatically adding filters. This is used in the specialized case of filtering deeper into a list by a field's value. For instance, since there can be multiple assignments in a list of handins. The assignment column can have a U...
[ "Get", "the", "URL", "if", "a", "filter", "of", "model", "[", "name", "]", "value", "was", "appended", "." ]
python
train
31.307692
calebsmith/django-template-debug
template_debug/templatetags/debug_tags.py
https://github.com/calebsmith/django-template-debug/blob/f3d52638da571164d63e5c8331d409b0743c628f/template_debug/templatetags/debug_tags.py#L107-L128
def pydevd(context): """ Start a pydev settrace """ global pdevd_not_available if pdevd_not_available: return '' try: import pydevd except ImportError: pdevd_not_available = True return '' render = lambda s: template.Template(s).render(context) availab...
[ "def", "pydevd", "(", "context", ")", ":", "global", "pdevd_not_available", "if", "pdevd_not_available", ":", "return", "''", "try", ":", "import", "pydevd", "except", "ImportError", ":", "pdevd_not_available", "=", "True", "return", "''", "render", "=", "lambda...
Start a pydev settrace
[ "Start", "a", "pydev", "settrace" ]
python
valid
24.954545
spyder-ide/spyder
spyder/plugins/editor/lsp/decorators.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/decorators.py#L12-L24
def send_request(req=None, method=None, requires_response=True): """Call function req and then send its results via ZMQ.""" if req is None: return functools.partial(send_request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapp...
[ "def", "send_request", "(", "req", "=", "None", ",", "method", "=", "None", ",", "requires_response", "=", "True", ")", ":", "if", "req", "is", "None", ":", "return", "functools", ".", "partial", "(", "send_request", ",", "method", "=", "method", ",", ...
Call function req and then send its results via ZMQ.
[ "Call", "function", "req", "and", "then", "send", "its", "results", "via", "ZMQ", "." ]
python
train
38.692308
materialsproject/pymatgen
pymatgen/core/trajectory.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/trajectory.py#L98-L107
def to_positions(self): """ Converts fractional coordinates of trajectory into positions """ if self.coords_are_displacement: cumulative_displacements = np.cumsum(self.frac_coords, axis=0) positions = self.base_positions + cumulative_displacements self...
[ "def", "to_positions", "(", "self", ")", ":", "if", "self", ".", "coords_are_displacement", ":", "cumulative_displacements", "=", "np", ".", "cumsum", "(", "self", ".", "frac_coords", ",", "axis", "=", "0", ")", "positions", "=", "self", ".", "base_positions...
Converts fractional coordinates of trajectory into positions
[ "Converts", "fractional", "coordinates", "of", "trajectory", "into", "positions" ]
python
train
39.9
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1219-L1342
def setup_new_conf(self): # pylint: disable=too-many-locals """ Setup a new configuration received from a Master arbiter. TODO: perharps we should not accept the configuration or raise an error if we do not find our own configuration data in the data. Thus this should never happen... ...
[ "def", "setup_new_conf", "(", "self", ")", ":", "# pylint: disable=too-many-locals", "# Execute the base class treatment...", "super", "(", "Arbiter", ",", "self", ")", ".", "setup_new_conf", "(", ")", "with", "self", ".", "conf_lock", ":", "logger", ".", "info", ...
Setup a new configuration received from a Master arbiter. TODO: perharps we should not accept the configuration or raise an error if we do not find our own configuration data in the data. Thus this should never happen... :return: None
[ "Setup", "a", "new", "configuration", "received", "from", "a", "Master", "arbiter", "." ]
python
train
49.064516
bxlab/bx-python
lib/bx_extras/stats.py
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1361-L1400
def lzprob(z): """ Returns the area under the normal curve 'to the left of' the given z value. Thus, for z<0, zprob(z) = 1-tail probability for z>0, 1.0-zprob(z) = 1-tail probability for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability Adapted from z.c in Gary Perlman's |Stat. Usage: lzprob(z) ""...
[ "def", "lzprob", "(", "z", ")", ":", "Z_MAX", "=", "6.0", "# maximum meaningful z-value", "if", "z", "==", "0.0", ":", "x", "=", "0.0", "else", ":", "y", "=", "0.5", "*", "math", ".", "fabs", "(", "z", ")", "if", "y", ">=", "(", "Z_MAX", "*", "...
Returns the area under the normal curve 'to the left of' the given z value. Thus, for z<0, zprob(z) = 1-tail probability for z>0, 1.0-zprob(z) = 1-tail probability for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability Adapted from z.c in Gary Perlman's |Stat. Usage: lzprob(z)
[ "Returns", "the", "area", "under", "the", "normal", "curve", "to", "the", "left", "of", "the", "given", "z", "value", ".", "Thus", "for", "z<0", "zprob", "(", "z", ")", "=", "1", "-", "tail", "probability", "for", "z", ">", "0", "1", ".", "0", "-...
python
train
35.875
ioos/compliance-checker
compliance_checker/cfutil.py
https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L383-L421
def get_z_variables(nc): ''' Returns a list of all variables matching definitions for Z :param netcdf4.dataset nc: an open netcdf dataset object ''' z_variables = [] # Vertical coordinates will be identifiable by units of pressure or the # presence of the positive attribute with a value of ...
[ "def", "get_z_variables", "(", "nc", ")", ":", "z_variables", "=", "[", "]", "# Vertical coordinates will be identifiable by units of pressure or the", "# presence of the positive attribute with a value of up/down", "# optionally, the vertical type may be indicated by providing the", "# st...
Returns a list of all variables matching definitions for Z :param netcdf4.dataset nc: an open netcdf dataset object
[ "Returns", "a", "list", "of", "all", "variables", "matching", "definitions", "for", "Z" ]
python
train
43.410256
jupyter-widgets/ipywidgets
ipywidgets/widgets/widget.py
https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget.py#L595-L605
def notify_change(self, change): """Called when a property has changed.""" # Send the state to the frontend before the user-registered callbacks # are called. name = change['name'] if self.comm is not None and self.comm.kernel is not None: # Make sure this isn't infor...
[ "def", "notify_change", "(", "self", ",", "change", ")", ":", "# Send the state to the frontend before the user-registered callbacks", "# are called.", "name", "=", "change", "[", "'name'", "]", "if", "self", ".", "comm", "is", "not", "None", "and", "self", ".", "...
Called when a property has changed.
[ "Called", "when", "a", "property", "has", "changed", "." ]
python
train
52.636364
smnorris/bcdata
bcdata/wfs.py
https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L51-L58
def bcdc_package_show(package): """Query DataBC Catalogue API about given package """ params = {"id": package} r = requests.get(bcdata.BCDC_API_URL + "package_show", params=params) if r.status_code != 200: raise ValueError("{d} is not present in DataBC API list".format(d=package)) return...
[ "def", "bcdc_package_show", "(", "package", ")", ":", "params", "=", "{", "\"id\"", ":", "package", "}", "r", "=", "requests", ".", "get", "(", "bcdata", ".", "BCDC_API_URL", "+", "\"package_show\"", ",", "params", "=", "params", ")", "if", "r", ".", "...
Query DataBC Catalogue API about given package
[ "Query", "DataBC", "Catalogue", "API", "about", "given", "package" ]
python
train
41.5
materialsproject/pymatgen
pymatgen/electronic_structure/boltztrap.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/boltztrap.py#L1125-L1196
def get_thermal_conductivity(self, output='eigs', doping_levels=True, k_el=True, relaxation_time=1e-14): """ Gives the electronic part of the thermal conductivity in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If ...
[ "def", "get_thermal_conductivity", "(", "self", ",", "output", "=", "'eigs'", ",", "doping_levels", "=", "True", ",", "k_el", "=", "True", ",", "relaxation_time", "=", "1e-14", ")", ":", "result", "=", "None", "result_doping", "=", "None", "if", "doping_leve...
Gives the electronic part of the thermal conductivity in either a full 3x3 tensor form, as 3 eigenvalues, or as the average value (trace/3.0) If doping_levels=True, the results are given at different p and n doping levels (given by self.doping), otherwise it is given as a series ...
[ "Gives", "the", "electronic", "part", "of", "the", "thermal", "conductivity", "in", "either", "a", "full", "3x3", "tensor", "form", "as", "3", "eigenvalues", "or", "as", "the", "average", "value", "(", "trace", "/", "3", ".", "0", ")", "If", "doping_leve...
python
train
49.722222
trailofbits/manticore
manticore/core/smtlib/visitors.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L541-L561
def visit_ArraySelect(self, expression, *operands): """ ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0) -> v0 """ arr, index = operands if isinstance(arr, ArrayVariable): return if isinstance(index, BitVecConstant): ival = ind...
[ "def", "visit_ArraySelect", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "arr", ",", "index", "=", "operands", "if", "isinstance", "(", "arr", ",", "ArrayVariable", ")", ":", "return", "if", "isinstance", "(", "index", ",", "BitVecConsta...
ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0) -> v0
[ "ArraySelect", "(", "ArrayStore", "((", "ArrayStore", "(", "x0", "v0", ")", "...", ")", "xn", "vn", ")", "x0", ")", "-", ">", "v0" ]
python
valid
46.333333
erget/StereoVision
stereovision/calibration.py
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L218-L270
def calibrate_cameras(self): """Calibrate cameras based on found chessboard corners.""" criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_SAME_FOCAL_LENGTH)...
[ "def", "calibrate_cameras", "(", "self", ")", ":", "criteria", "=", "(", "cv2", ".", "TERM_CRITERIA_MAX_ITER", "+", "cv2", ".", "TERM_CRITERIA_EPS", ",", "100", ",", "1e-5", ")", "flags", "=", "(", "cv2", ".", "CALIB_FIX_ASPECT_RATIO", "+", "cv2", ".", "CA...
Calibrate cameras based on found chessboard corners.
[ "Calibrate", "cameras", "based", "on", "found", "chessboard", "corners", "." ]
python
train
61.641509
romankoblov/leaf
leaf/__init__.py
https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L26-L34
def get(self, selector, index=0, default=None): """ Get first element from CSSSelector """ elements = self(selector) if elements: try: return elements[index] except (IndexError): pass return default
[ "def", "get", "(", "self", ",", "selector", ",", "index", "=", "0", ",", "default", "=", "None", ")", ":", "elements", "=", "self", "(", "selector", ")", "if", "elements", ":", "try", ":", "return", "elements", "[", "index", "]", "except", "(", "In...
Get first element from CSSSelector
[ "Get", "first", "element", "from", "CSSSelector" ]
python
train
30.888889
genialis/resolwe
resolwe/permissions/shortcuts.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/shortcuts.py#L31-L58
def get_groups_with_perms(obj, attach_perms=False): """Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.""" ctype = get_content_type(obj) group_model = get_group_obj_perms_model(obj) if not attach_perms: # It's much easier without attached perms so we...
[ "def", "get_groups_with_perms", "(", "obj", ",", "attach_perms", "=", "False", ")", ":", "ctype", "=", "get_content_type", "(", "obj", ")", "group_model", "=", "get_group_obj_perms_model", "(", "obj", ")", "if", "not", "attach_perms", ":", "# It's much easier with...
Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.
[ "Return", "queryset", "of", "all", "Group", "objects", "with", "*", "any", "*", "object", "permissions", "for", "the", "given", "obj", "." ]
python
train
48.321429
markokr/rarfile
rarfile.py
https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2503-L2518
def update(self, data): """Hash data. """ view = memoryview(data) bs = self.block_size if self._buf: need = bs - len(self._buf) if len(view) < need: self._buf += view.tobytes() return self._add_block(self._buf + ...
[ "def", "update", "(", "self", ",", "data", ")", ":", "view", "=", "memoryview", "(", "data", ")", "bs", "=", "self", ".", "block_size", "if", "self", ".", "_buf", ":", "need", "=", "bs", "-", "len", "(", "self", ".", "_buf", ")", "if", "len", "...
Hash data.
[ "Hash", "data", "." ]
python
train
30.75
opencobra/cobrapy
cobra/util/solver.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L411-L421
def check_solver_status(status, raise_error=False): """Perform standard checks on a solver's status.""" if status == OPTIMAL: return elif (status in has_primals) and not raise_error: warn("solver status is '{}'".format(status), UserWarning) elif status is None: raise Optimization...
[ "def", "check_solver_status", "(", "status", ",", "raise_error", "=", "False", ")", ":", "if", "status", "==", "OPTIMAL", ":", "return", "elif", "(", "status", "in", "has_primals", ")", "and", "not", "raise_error", ":", "warn", "(", "\"solver status is '{}'\""...
Perform standard checks on a solver's status.
[ "Perform", "standard", "checks", "on", "a", "solver", "s", "status", "." ]
python
valid
42.545455
materialsproject/pymatgen
pymatgen/analysis/ferroelectricity/polarization.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/ferroelectricity/polarization.py#L113-L133
def get_nearest_site(self, coords, site, r=None): """ Given coords and a site, find closet site to coords. Args: coords (3x1 array): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cel...
[ "def", "get_nearest_site", "(", "self", ",", "coords", ",", "site", ",", "r", "=", "None", ")", ":", "index", "=", "self", ".", "index", "(", "site", ")", "if", "r", "is", "None", ":", "r", "=", "np", ".", "linalg", ".", "norm", "(", "np", ".",...
Given coords and a site, find closet site to coords. Args: coords (3x1 array): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cell Returns: Closest site and distance.
[ "Given", "coords", "and", "a", "site", "find", "closet", "site", "to", "coords", ".", "Args", ":", "coords", "(", "3x1", "array", ")", ":", "cartesian", "coords", "of", "center", "of", "sphere", "site", ":", "site", "to", "find", "closest", "to", "coor...
python
train
38.857143
ThreatConnect-Inc/tcex
tcex/tcex_ti_batch.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1118-L1135
def registry_key(self, key_name, value_name, value_type, **kwargs): """Add Registry Key data to Batch object. Args: key_name (str): The key_name value for this Indicator. value_name (str): The value_name value for this Indicator. value_type (str): The value_type valu...
[ "def", "registry_key", "(", "self", ",", "key_name", ",", "value_name", ",", "value_type", ",", "*", "*", "kwargs", ")", ":", "indicator_obj", "=", "RegistryKey", "(", "key_name", ",", "value_name", ",", "value_type", ",", "*", "*", "kwargs", ")", "return"...
Add Registry Key data to Batch object. Args: key_name (str): The key_name value for this Indicator. value_name (str): The value_name value for this Indicator. value_type (str): The value_type value for this Indicator. confidence (str, kwargs): The threat confiden...
[ "Add", "Registry", "Key", "data", "to", "Batch", "object", "." ]
python
train
51.222222
PMEAL/OpenPNM
openpnm/algorithms/OrdinaryPercolation.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/algorithms/OrdinaryPercolation.py#L250-L278
def set_residual(self, pores=[], throats=[], overwrite=False): r""" Specify locations of any residual invader. These locations are set to invaded at the start of the simulation. Parameters ---------- pores : array_like The pores locations that are to be fill...
[ "def", "set_residual", "(", "self", ",", "pores", "=", "[", "]", ",", "throats", "=", "[", "]", ",", "overwrite", "=", "False", ")", ":", "Ps", "=", "self", ".", "_parse_indices", "(", "pores", ")", "if", "overwrite", ":", "self", "[", "'pore.residua...
r""" Specify locations of any residual invader. These locations are set to invaded at the start of the simulation. Parameters ---------- pores : array_like The pores locations that are to be filled with invader at the beginning of the simulation. ...
[ "r", "Specify", "locations", "of", "any", "residual", "invader", ".", "These", "locations", "are", "set", "to", "invaded", "at", "the", "start", "of", "the", "simulation", "." ]
python
train
36.827586
hobson/aima
aima/search.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L151-L161
def tree_search(problem, frontier): """Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Don't worry about repeated paths to a state. [Fig. 3.7]""" frontier.append(Node(problem.initial)) while frontier: node = frontier.pop() if...
[ "def", "tree_search", "(", "problem", ",", "frontier", ")", ":", "frontier", ".", "append", "(", "Node", "(", "problem", ".", "initial", ")", ")", "while", "frontier", ":", "node", "=", "frontier", ".", "pop", "(", ")", "if", "problem", ".", "goal_test...
Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Don't worry about repeated paths to a state. [Fig. 3.7]
[ "Search", "through", "the", "successors", "of", "a", "problem", "to", "find", "a", "goal", ".", "The", "argument", "frontier", "should", "be", "an", "empty", "queue", ".", "Don", "t", "worry", "about", "repeated", "paths", "to", "a", "state", ".", "[", ...
python
valid
38.818182
tanghaibao/goatools
goatools/parsers/ncbi_gene_file_reader.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/parsers/ncbi_gene_file_reader.py#L84-L94
def do_hdr(self, line, hdrs_usr): """Initialize self.h2i.""" # If there is no header hint, consider the first line the header. if self.hdr_ex is None: self._init_hdr(line, hdrs_usr) return True # If there is a header hint, examine each beginning line until header ...
[ "def", "do_hdr", "(", "self", ",", "line", ",", "hdrs_usr", ")", ":", "# If there is no header hint, consider the first line the header.", "if", "self", ".", "hdr_ex", "is", "None", ":", "self", ".", "_init_hdr", "(", "line", ",", "hdrs_usr", ")", "return", "Tru...
Initialize self.h2i.
[ "Initialize", "self", ".", "h2i", "." ]
python
train
40.545455
pyblish/pyblish-qml
pyblish_qml/ipc/formatting.py
https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L61-L94
def format_record(record): """Serialise LogRecord instance""" record = dict( (key, getattr(record, key, None)) for key in ( "threadName", "name", "thread", "created", "process", "processName", "args", ...
[ "def", "format_record", "(", "record", ")", ":", "record", "=", "dict", "(", "(", "key", ",", "getattr", "(", "record", ",", "key", ",", "None", ")", ")", "for", "key", "in", "(", "\"threadName\"", ",", "\"name\"", ",", "\"thread\"", ",", "\"created\""...
Serialise LogRecord instance
[ "Serialise", "LogRecord", "instance" ]
python
train
22.264706
Demonware/jose
jose.py
https://github.com/Demonware/jose/blob/5835ec9c9fcab17eddea3c3169881ec12df552d4/jose.py#L705-L752
def _validate(claims, validate_claims, expiry_seconds): """ Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided. """ if not validate_claims: ret...
[ "def", "_validate", "(", "claims", ",", "validate_claims", ",", "expiry_seconds", ")", ":", "if", "not", "validate_claims", ":", "return", "now", "=", "time", "(", ")", "# TODO: implement support for clock skew", "# The exp (expiration time) claim identifies the expiration ...
Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided.
[ "Validate", "expiry", "related", "claims", "." ]
python
train
35.083333
jobovy/galpy
galpy/df/jeans.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/jeans.py#L60-L125
def sigmalos(Pot,R,dens=None,surfdens=None,beta=0.,sigma_r=None): """ NAME: sigmalos PURPOSE: Compute the line-of-sight velocity dispersion using the spherical Jeans equation INPUT: Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not chec...
[ "def", "sigmalos", "(", "Pot", ",", "R", ",", "dens", "=", "None", ",", "surfdens", "=", "None", ",", "beta", "=", "0.", ",", "sigma_r", "=", "None", ")", ":", "Pot", "=", "flatten_pot", "(", "Pot", ")", "if", "dens", "is", "None", ":", "densPot"...
NAME: sigmalos PURPOSE: Compute the line-of-sight velocity dispersion using the spherical Jeans equation INPUT: Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not checked) R - Galactocentric projected radius (can be Quantity) den...
[ "NAME", ":" ]
python
train
33.848485
jahuth/litus
spikes.py
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L363-L381
def logspace(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True): """ bins overwrites resolution """ if type(bins) in [list, np.ndarray]: return bins min = conversion_function(self.min,from_units=self.units,to_units=units) max = convers...
[ "def", "logspace", "(", "self", ",", "bins", "=", "None", ",", "units", "=", "None", ",", "conversion_function", "=", "convert_time", ",", "resolution", "=", "None", ",", "end_at_end", "=", "True", ")", ":", "if", "type", "(", "bins", ")", "in", "[", ...
bins overwrites resolution
[ "bins", "overwrites", "resolution" ]
python
train
52.368421
Qiskit/qiskit-terra
qiskit/transpiler/passes/unroller.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/unroller.py#L29-L69
def run(self, dag): """Expand all op nodes to the given basis. Args: dag(DAGCircuit): input dag Raises: QiskitError: if unable to unroll given the basis due to undefined decomposition rules (such as a bad basis) or excessive recursion. Returns: ...
[ "def", "run", "(", "self", ",", "dag", ")", ":", "# Walk through the DAG and expand each non-basis node", "for", "node", "in", "dag", ".", "op_nodes", "(", ")", ":", "basic_insts", "=", "[", "'measure'", ",", "'reset'", ",", "'barrier'", ",", "'snapshot'", "]"...
Expand all op nodes to the given basis. Args: dag(DAGCircuit): input dag Raises: QiskitError: if unable to unroll given the basis due to undefined decomposition rules (such as a bad basis) or excessive recursion. Returns: DAGCircuit: output unro...
[ "Expand", "all", "op", "nodes", "to", "the", "given", "basis", "." ]
python
test
42.560976
scopus-api/scopus
scopus/scopus_search.py
https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/scopus_search.py#L23-L104
def results(self): """A list of namedtuples in the form (eid doi pii pubmed_id title subtype creator afid affilname affiliation_city affiliation_country author_count author_names author_ids author_afids coverDate coverDisplayDate publicationName issn source_id eIssn aggregationType ...
[ "def", "results", "(", "self", ")", ":", "out", "=", "[", "]", "fields", "=", "'eid doi pii pubmed_id title subtype creator afid affilname '", "'affiliation_city affiliation_country author_count '", "'author_names author_ids author_afids coverDate '", "'coverDisplayDate publicationName...
A list of namedtuples in the form (eid doi pii pubmed_id title subtype creator afid affilname affiliation_city affiliation_country author_count author_names author_ids author_afids coverDate coverDisplayDate publicationName issn source_id eIssn aggregationType volume issueIdentifier arti...
[ "A", "list", "of", "namedtuples", "in", "the", "form", "(", "eid", "doi", "pii", "pubmed_id", "title", "subtype", "creator", "afid", "affilname", "affiliation_city", "affiliation_country", "author_count", "author_names", "author_ids", "author_afids", "coverDate", "cov...
python
train
55.646341
pywbem/pywbem
pywbem/_subscription_manager.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_subscription_manager.py#L389-L440
def remove_server(self, server_id): """ Remove a registered WBEM server from the subscription manager. This also unregisters listeners from that server and removes all owned indication subscriptions, owned indication filters and owned listener destinations. Parameters: ...
[ "def", "remove_server", "(", "self", ",", "server_id", ")", ":", "# Validate server_id", "server", "=", "self", ".", "_get_server", "(", "server_id", ")", "# Delete any instances we recorded to be cleaned up", "if", "server_id", "in", "self", ".", "_owned_subscriptions"...
Remove a registered WBEM server from the subscription manager. This also unregisters listeners from that server and removes all owned indication subscriptions, owned indication filters and owned listener destinations. Parameters: server_id (:term:`string`): The se...
[ "Remove", "a", "registered", "WBEM", "server", "from", "the", "subscription", "manager", ".", "This", "also", "unregisters", "listeners", "from", "that", "server", "and", "removes", "all", "owned", "indication", "subscriptions", "owned", "indication", "filters", "...
python
train
37.903846
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L1137-L1155
def _parse_raw_members( self, leaderboard_name, members, members_only=False, **options): ''' Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_nam...
[ "def", "_parse_raw_members", "(", "self", ",", "leaderboard_name", ",", "members", ",", "members_only", "=", "False", ",", "*", "*", "options", ")", ":", "if", "members_only", ":", "return", "[", "{", "self", ".", "MEMBER_KEY", ":", "m", "}", "for", "m",...
Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_name [String] Name of the leaderboard. @param members [List] A list of members as returned from a sorted set range q...
[ "Parse", "the", "raw", "leaders", "data", "as", "returned", "from", "a", "given", "leader", "board", "query", ".", "Do", "associative", "lookups", "with", "the", "member", "to", "rank", "score", "and", "potentially", "sort", "the", "results", "." ]
python
train
46.736842
log2timeline/plaso
plaso/cli/storage_media_tool.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/storage_media_tool.py#L593-L630
def _PrintVSSStoreIdentifiersOverview( self, volume_system, volume_identifiers): """Prints an overview of VSS store identifiers. Args: volume_system (dfvfs.VShadowVolumeSystem): volume system. volume_identifiers (list[str]): allowed volume identifiers. Raises: SourceScannerError: i...
[ "def", "_PrintVSSStoreIdentifiersOverview", "(", "self", ",", "volume_system", ",", "volume_identifiers", ")", ":", "header", "=", "'The following Volume Shadow Snapshots (VSS) were found:\\n'", "self", ".", "_output_writer", ".", "Write", "(", "header", ")", "column_names"...
Prints an overview of VSS store identifiers. Args: volume_system (dfvfs.VShadowVolumeSystem): volume system. volume_identifiers (list[str]): allowed volume identifiers. Raises: SourceScannerError: if a volume cannot be resolved from the volume identifier.
[ "Prints", "an", "overview", "of", "VSS", "store", "identifiers", "." ]
python
train
36.368421
merll/docker-fabric
dockerfabric/cli.py
https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/cli.py#L366-L386
def isolate_and_get(src_container, src_resources, local_dst_dir, **kwargs): """ Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball and downloads it. :param src_container: Container name or id. :type src_container: unicode :param src_res...
[ "def", "isolate_and_get", "(", "src_container", ",", "src_resources", ",", "local_dst_dir", ",", "*", "*", "kwargs", ")", ":", "with", "temp_dir", "(", ")", "as", "remote_tmp", ":", "copy_path", "=", "posixpath", ".", "join", "(", "remote_tmp", ",", "'copy_t...
Uses :func:`copy_resources` to copy resources from a container, but afterwards generates a compressed tarball and downloads it. :param src_container: Container name or id. :type src_container: unicode :param src_resources: Resources, as (file or directory) names to copy. :type src_resources: iterab...
[ "Uses", ":", "func", ":", "copy_resources", "to", "copy", "resources", "from", "a", "container", "but", "afterwards", "generates", "a", "compressed", "tarball", "and", "downloads", "it", "." ]
python
train
49.761905
funilrys/PyFunceble
PyFunceble/config.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L822-L878
def is_cloned(cls): """ Let us know if we are currently in the cloned version of PyFunceble which implicitly mean that we are in developement mode. """ if not PyFunceble.path.isdir(".git"): # The git directory does not exist. # We return False, the curre...
[ "def", "is_cloned", "(", "cls", ")", ":", "if", "not", "PyFunceble", ".", "path", ".", "isdir", "(", "\".git\"", ")", ":", "# The git directory does not exist.", "# We return False, the current version is not the cloned version.", "return", "False", "# We list the list of f...
Let us know if we are currently in the cloned version of PyFunceble which implicitly mean that we are in developement mode.
[ "Let", "us", "know", "if", "we", "are", "currently", "in", "the", "cloned", "version", "of", "PyFunceble", "which", "implicitly", "mean", "that", "we", "are", "in", "developement", "mode", "." ]
python
test
32.526316
ynop/audiomate
audiomate/feeding/dataset.py
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/dataset.py#L198-L210
def longest_utterances_per_container(self): """ Return a tuple/list containing the length of the longest utterance of ever container. """ lengths = [] for cnt in self.containers: longest_in_container = 0 for utt_idx in self.utt_ids: utt_length = cnt._file...
[ "def", "longest_utterances_per_container", "(", "self", ")", ":", "lengths", "=", "[", "]", "for", "cnt", "in", "self", ".", "containers", ":", "longest_in_container", "=", "0", "for", "utt_idx", "in", "self", ".", "utt_ids", ":", "utt_length", "=", "cnt", ...
Return a tuple/list containing the length of the longest utterance of ever container.
[ "Return", "a", "tuple", "/", "list", "containing", "the", "length", "of", "the", "longest", "utterance", "of", "ever", "container", "." ]
python
train
36.692308
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3000-L3034
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None): """Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Neg...
[ "def", "ones_matrix_band_part", "(", "rows", ",", "cols", ",", "num_lower", ",", "num_upper", ",", "out_shape", "=", "None", ")", ":", "if", "all", "(", "[", "isinstance", "(", "el", ",", "int", ")", "for", "el", "in", "[", "rows", ",", "cols", ",", ...
Matrix band part of ones. Args: rows: int determining number of rows in output cols: int num_lower: int, maximum distance backward. Negative values indicate unlimited. num_upper: int, maximum distance forward. Negative values indicate unlimited. out_shape: shape to reshape output by. ...
[ "Matrix", "band", "part", "of", "ones", "." ]
python
train
32.657143
KvasirSecurity/kvasirapi-python
KvasirAPI/config.py
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/config.py#L51-L76
def load(self, configuration): """ Load a YAML configuration file. :param configuration: Configuration filename or YAML string """ try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load...
[ "def", "load", "(", "self", ",", "configuration", ")", ":", "try", ":", "self", ".", "config", "=", "yaml", ".", "load", "(", "open", "(", "configuration", ",", "\"rb\"", ")", ")", "except", "IOError", ":", "try", ":", "self", ".", "config", "=", "...
Load a YAML configuration file. :param configuration: Configuration filename or YAML string
[ "Load", "a", "YAML", "configuration", "file", "." ]
python
train
35.961538
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/core_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L16771-L16795
def patch_namespaced_service(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_service # noqa: E501 partially update the specified Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass as...
[ "def", "patch_namespaced_service", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ...
patch_namespaced_service # noqa: E501 partially update the specified Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_service(name, namespace, body, async_re...
[ "patch_namespaced_service", "#", "noqa", ":", "E501" ]
python
train
60.2
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L990-L996
def get_name_from_name_hash128( self, name ): """ Get the name from a name hash """ cur = self.db.cursor() name = namedb_get_name_from_name_hash128( cur, name, self.lastblock ) return name
[ "def", "get_name_from_name_hash128", "(", "self", ",", "name", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "name", "=", "namedb_get_name_from_name_hash128", "(", "cur", ",", "name", ",", "self", ".", "lastblock", ")", "return", "name"...
Get the name from a name hash
[ "Get", "the", "name", "from", "a", "name", "hash" ]
python
train
32.857143
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/row.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L921-L958
def _parse_rmw_row_response(row_response): """Parses the response to a ``ReadModifyWriteRow`` request. :type row_response: :class:`.data_v2_pb2.Row` :param row_response: The response row (with only modified cells) from a ``ReadModifyWriteRow`` request. :rtype: dict :return...
[ "def", "_parse_rmw_row_response", "(", "row_response", ")", ":", "result", "=", "{", "}", "for", "column_family", "in", "row_response", ".", "row", ".", "families", ":", "column_family_id", ",", "curr_family", "=", "_parse_family_pb", "(", "column_family", ")", ...
Parses the response to a ``ReadModifyWriteRow`` request. :type row_response: :class:`.data_v2_pb2.Row` :param row_response: The response row (with only modified cells) from a ``ReadModifyWriteRow`` request. :rtype: dict :returns: The new contents of all modified cells. Returne...
[ "Parses", "the", "response", "to", "a", "ReadModifyWriteRow", "request", "." ]
python
train
40.973684
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/RequestEvent.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/RequestEvent.py#L80-L84
def _set(self): """Called internally by Client to indicate this request has finished""" self.__event.set() if self._complete_func: self.__run_completion_func(self._complete_func, self.id_)
[ "def", "_set", "(", "self", ")", ":", "self", ".", "__event", ".", "set", "(", ")", "if", "self", ".", "_complete_func", ":", "self", ".", "__run_completion_func", "(", "self", ".", "_complete_func", ",", "self", ".", "id_", ")" ]
Called internally by Client to indicate this request has finished
[ "Called", "internally", "by", "Client", "to", "indicate", "this", "request", "has", "finished" ]
python
train
44
Diviyan-Kalainathan/CausalDiscoveryToolbox
cdt/causality/graph/CGNN.py
https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/causality/graph/CGNN.py#L162-L172
def parallel_graph_evaluation(data, adj_matrix, nb_runs=16, nb_jobs=None, **kwargs): """Parallelize the various runs of CGNN to evaluate a graph.""" nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs) if nb_runs == 1: return graph_evaluation(data, adj_matrix, **kwargs) ...
[ "def", "parallel_graph_evaluation", "(", "data", ",", "adj_matrix", ",", "nb_runs", "=", "16", ",", "nb_jobs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "nb_jobs", "=", "SETTINGS", ".", "get_default", "(", "nb_jobs", "=", "nb_jobs", ")", "if", "nb_...
Parallelize the various runs of CGNN to evaluate a graph.
[ "Parallelize", "the", "various", "runs", "of", "CGNN", "to", "evaluate", "a", "graph", "." ]
python
valid
53.545455
LettError/MutatorMath
Lib/mutatorMath/ufo/document.py
https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L240-L289
def writeGlyph(self, name, unicodes=None, location=None, masters=None, note=None, mute=False, ): """ Add a new glyph to the current instance. * name: the glyph name. Required. * unicodes: unicode values f...
[ "def", "writeGlyph", "(", "self", ",", "name", ",", "unicodes", "=", "None", ",", "location", "=", "None", ",", "masters", "=", "None", ",", "note", "=", "None", ",", "mute", "=", "False", ",", ")", ":", "if", "self", ".", "currentInstance", "is", ...
Add a new glyph to the current instance. * name: the glyph name. Required. * unicodes: unicode values for this glyph if it needs to be different from the unicode values associated with this glyph name in the masters. * location: a design space location for this glyph if it needs to b...
[ "Add", "a", "new", "glyph", "to", "the", "current", "instance", ".", "*", "name", ":", "the", "glyph", "name", ".", "Required", ".", "*", "unicodes", ":", "unicode", "values", "for", "this", "glyph", "if", "it", "needs", "to", "be", "different", "from"...
python
train
47.82
graphql-python/graphql-core
graphql/validation/rules/overlapping_fields_can_be_merged.py
https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L348-L426
def _find_conflicts_between_sub_selection_sets( context, # type: ValidationContext cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]] compared_fragments, # type: PairSet are_...
[ "def", "_find_conflicts_between_sub_selection_sets", "(", "context", ",", "# type: ValidationContext", "cached_fields_and_fragment_names", ",", "# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]", "compar...
Find all conflicts found between two selection sets. Includes those found via spreading in fragments. Called when determining if conflicts exist between the sub-fields of two overlapping fields.
[ "Find", "all", "conflicts", "found", "between", "two", "selection", "sets", "." ]
python
train
38.924051
LEMS/pylems
lems/sim/build.py
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L231-L289
def build_event_connections(self, component, runnable, structure): """ Adds event connections to a runnable component based on the structure specifications in the component model. @param component: Component model containing structure specifications. @type component: lems.model....
[ "def", "build_event_connections", "(", "self", ",", "component", ",", "runnable", ",", "structure", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"\\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s\"", "%", "(", "component", ".", ...
Adds event connections to a runnable component based on the structure specifications in the component model. @param component: Component model containing structure specifications. @type component: lems.model.component.FatComponent @param runnable: Runnable component to which structure ...
[ "Adds", "event", "connections", "to", "a", "runnable", "component", "based", "on", "the", "structure", "specifications", "in", "the", "component", "model", "." ]
python
train
50.237288
saschpe/rapport
rapport/report.py
https://github.com/saschpe/rapport/blob/ccceb8f84bd7e8add88ab5e137cdab6424aa4683/rapport/report.py#L50-L60
def get_report(report=None): """Returns details of a specific report """ if not report: report = list_reports()[-1:][0] report_path = _get_reports_path(report) report_dict = {"report": report} for filename in os.listdir(report_path): with open(os.path.join(report_path, filename),...
[ "def", "get_report", "(", "report", "=", "None", ")", ":", "if", "not", "report", ":", "report", "=", "list_reports", "(", ")", "[", "-", "1", ":", "]", "[", "0", "]", "report_path", "=", "_get_reports_path", "(", "report", ")", "report_dict", "=", "...
Returns details of a specific report
[ "Returns", "details", "of", "a", "specific", "report" ]
python
train
35.363636
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L1966-L1985
def get_mod_log(self, subreddit, mod=None, action=None, *args, **kwargs): """Return a get_content generator for moderation log items. :param subreddit: Either a Subreddit object or the name of the subreddit to return the modlog for. :param mod: If given, only return the actions made...
[ "def", "get_mod_log", "(", "self", ",", "subreddit", ",", "mod", "=", "None", ",", "action", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", ".", "setdefault", "(", "'params'", ",", "{", "}", ")", "if", ...
Return a get_content generator for moderation log items. :param subreddit: Either a Subreddit object or the name of the subreddit to return the modlog for. :param mod: If given, only return the actions made by this moderator. Both a moderator name or Redditor object can be used ...
[ "Return", "a", "get_content", "generator", "for", "moderation", "log", "items", "." ]
python
train
47.85
pydata/xarray
xarray/core/resample.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/resample.py#L276-L305
def reduce(self, func, dim=None, keep_attrs=None, **kwargs): """Reduce the items in this group by applying `func` along the pre-defined resampling dimension. Parameters ---------- func : function Function which can be called in the form `func(x, axis=axis...
[ "def", "reduce", "(", "self", ",", "func", ",", "dim", "=", "None", ",", "keep_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "dim", "==", "DEFAULT_DIMS", ":", "dim", "=", "None", "return", "super", "(", "DatasetResample", ",", "self",...
Reduce the items in this group by applying `func` along the pre-defined resampling dimension. Parameters ---------- func : function Function which can be called in the form `func(x, axis=axis, **kwargs)` to return the result of collapsing an np.ndarra...
[ "Reduce", "the", "items", "in", "this", "group", "by", "applying", "func", "along", "the", "pre", "-", "defined", "resampling", "dimension", "." ]
python
train
37.933333
wbond/oscrypto
oscrypto/_tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L77-L95
def detect_client_auth_request(server_handshake_bytes): """ Determines if a CertificateRequest message is sent from the server asking the client for a certificate :param server_handshake_bytes: A byte string of the handshake data received from the server :return: A boolean - if a c...
[ "def", "detect_client_auth_request", "(", "server_handshake_bytes", ")", ":", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x16'", ":", "continue", "for", "mess...
Determines if a CertificateRequest message is sent from the server asking the client for a certificate :param server_handshake_bytes: A byte string of the handshake data received from the server :return: A boolean - if a client certificate request was found
[ "Determines", "if", "a", "CertificateRequest", "message", "is", "sent", "from", "the", "server", "asking", "the", "client", "for", "a", "certificate" ]
python
valid
34.210526
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/exportxml.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/exportxml.py#L668-L675
def element_attribs_to_dict(self, element): """ Convert the ``.attrib`` attributes of an etree element into a dict, leaving out the xml:id attribute. Each key will be prepended by graph's namespace. """ return {self.ns+':'+key: val for (key, val) in element.attrib.items()...
[ "def", "element_attribs_to_dict", "(", "self", ",", "element", ")", ":", "return", "{", "self", ".", "ns", "+", "':'", "+", "key", ":", "val", "for", "(", "key", ",", "val", ")", "in", "element", ".", "attrib", ".", "items", "(", ")", "if", "key", ...
Convert the ``.attrib`` attributes of an etree element into a dict, leaving out the xml:id attribute. Each key will be prepended by graph's namespace.
[ "Convert", "the", ".", "attrib", "attributes", "of", "an", "etree", "element", "into", "a", "dict", "leaving", "out", "the", "xml", ":", "id", "attribute", ".", "Each", "key", "will", "be", "prepended", "by", "graph", "s", "namespace", "." ]
python
train
44.125
kibitzr/kibitzr
kibitzr/storage.py
https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L46-L60
def report_changes(self, content): """ 1) Write changes in file, 2) Commit changes in git 3.1) If something changed, return tuple(True, changes) 3.2) If nothing changed, return tuple(False, None) If style is "verbose", return changes in human-friendly format, els...
[ "def", "report_changes", "(", "self", ",", "content", ")", ":", "self", ".", "write", "(", "content", ")", "if", "self", ".", "commit", "(", ")", ":", "return", "True", ",", "self", ".", "reporter", ".", "report", "(", ")", "else", ":", "return", "...
1) Write changes in file, 2) Commit changes in git 3.1) If something changed, return tuple(True, changes) 3.2) If nothing changed, return tuple(False, None) If style is "verbose", return changes in human-friendly format, else use unified diff
[ "1", ")", "Write", "changes", "in", "file", "2", ")", "Commit", "changes", "in", "git", "3", ".", "1", ")", "If", "something", "changed", "return", "tuple", "(", "True", "changes", ")", "3", ".", "2", ")", "If", "nothing", "changed", "return", "tuple...
python
train
32.2
cvxopt/chompack
src/python/maxchord.py
https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/maxchord.py#L5-L83
def maxchord(A, ve = None): """ Maximal chordal subgraph of sparsity graph. Returns a lower triangular sparse matrix which is the projection of :math:`A` on a maximal chordal subgraph and a perfect elimination order :math:`p`. Only the lower triangular part of :math:`A` is accessed. The opt...
[ "def", "maxchord", "(", "A", ",", "ve", "=", "None", ")", ":", "n", "=", "A", ".", "size", "[", "0", "]", "assert", "A", ".", "size", "[", "1", "]", "==", "n", ",", "\"A must be a square matrix\"", "assert", "type", "(", "A", ")", "is", "spmatrix...
Maximal chordal subgraph of sparsity graph. Returns a lower triangular sparse matrix which is the projection of :math:`A` on a maximal chordal subgraph and a perfect elimination order :math:`p`. Only the lower triangular part of :math:`A` is accessed. The optional argument `ve` is the index of the ...
[ "Maximal", "chordal", "subgraph", "of", "sparsity", "graph", "." ]
python
train
32.670886
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_span.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_span.py#L53-L66
def monitor_session_span_command_src_tengigabitethernet(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_numb...
[ "def", "monitor_session_span_command_src_tengigabitethernet", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "monitor", "=", "ET", ".", "SubElement", "(", "config", ",", "\"monitor\"", ",", "xmlns",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
52.428571
knagra/farnsworth
workshift/views.py
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L196-L249
def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """ page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) ...
[ "def", "start_semester_view", "(", "request", ")", ":", "page_name", "=", "\"Start Semester\"", "year", ",", "season", "=", "utils", ".", "get_year_season", "(", ")", "start_date", ",", "end_date", "=", "utils", ".", "get_semester_start_end", "(", "year", ",", ...
Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester.
[ "Initiates", "a", "semester", "s", "worth", "of", "workshift", "with", "the", "option", "to", "copy", "workshift", "types", "from", "the", "previous", "semester", "." ]
python
train
32.314815
rosshamish/catan-py
catan/boardbuilder.py
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L40-L72
def get_opts(opts): """ Validate options and apply defaults for options not supplied. :param opts: dictionary mapping str->str. :return: dictionary mapping str->Opt. All possible keys are present. """ defaults = { 'board': None, 'terrain': Opt.random, 'numbers': Opt.pres...
[ "def", "get_opts", "(", "opts", ")", ":", "defaults", "=", "{", "'board'", ":", "None", ",", "'terrain'", ":", "Opt", ".", "random", ",", "'numbers'", ":", "Opt", ".", "preset", ",", "'ports'", ":", "Opt", ".", "preset", ",", "'pieces'", ":", "Opt", ...
Validate options and apply defaults for options not supplied. :param opts: dictionary mapping str->str. :return: dictionary mapping str->Opt. All possible keys are present.
[ "Validate", "options", "and", "apply", "defaults", "for", "options", "not", "supplied", "." ]
python
train
31.454545
numenta/nupic
src/nupic/regions/knn_classifier_region.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L1191-L1202
def getOutputElementCount(self, name): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`. """ if name == 'categoriesOut': return self.maxCategoryCount elif name == 'categoryProbabilitiesOut': return self.maxCategoryCount elif name == 'bestPrototypeI...
[ "def", "getOutputElementCount", "(", "self", ",", "name", ")", ":", "if", "name", "==", "'categoriesOut'", ":", "return", "self", ".", "maxCategoryCount", "elif", "name", "==", "'categoryProbabilitiesOut'", ":", "return", "self", ".", "maxCategoryCount", "elif", ...
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
[ "Overrides", ":", "meth", ":", "nupic", ".", "bindings", ".", "regions", ".", "PyRegion", ".", "PyRegion", ".", "getOutputElementCount", "." ]
python
valid
38.25
ekmmetering/ekmmeters
ekmmeters.py
https://github.com/ekmmetering/ekmmeters/blob/b3748bdf30263bfa46ea40157bdf8df2522e1904/ekmmeters.py#L2576-L2653
def setHolidayDates(self, cmd_dict=None, password="00000000"): """ Serial call to set holiday list. If a buffer dictionary is not supplied, the method will use the class object buffer populated with assignHolidayDate. Args: cmd_dict (dict): Optional dictionary of holidays. ...
[ "def", "setHolidayDates", "(", "self", ",", "cmd_dict", "=", "None", ",", "password", "=", "\"00000000\"", ")", ":", "result", "=", "False", "self", ".", "setContext", "(", "\"setHolidayDates\"", ")", "if", "not", "cmd_dict", ":", "cmd_dict", "=", "self", ...
Serial call to set holiday list. If a buffer dictionary is not supplied, the method will use the class object buffer populated with assignHolidayDate. Args: cmd_dict (dict): Optional dictionary of holidays. password (str): Optional password. Returns: ...
[ "Serial", "call", "to", "set", "holiday", "list", "." ]
python
test
65.25641
materialsproject/pymatgen
pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py#L575-L585
def from_dict(cls, d): """ Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object created using the as_dict method. :param d: dict representation of the SimplestChemenvStrategy object :return: StructureEnvironments object ...
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "return", "cls", "(", "distance_cutoff", "=", "d", "[", "\"distance_cutoff\"", "]", ",", "angle_cutoff", "=", "d", "[", "\"angle_cutoff\"", "]", ",", "additional_condition", "=", "d", "[", "\"additional_con...
Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object created using the as_dict method. :param d: dict representation of the SimplestChemenvStrategy object :return: StructureEnvironments object
[ "Reconstructs", "the", "SimplestChemenvStrategy", "object", "from", "a", "dict", "representation", "of", "the", "SimplestChemenvStrategy", "object", "created", "using", "the", "as_dict", "method", ".", ":", "param", "d", ":", "dict", "representation", "of", "the", ...
python
train
58.272727
bitcraft/PyTMX
pytmx/pytmx.py
https://github.com/bitcraft/PyTMX/blob/3fb9788dd66ecfd0c8fa0e9f38c582337d89e1d9/pytmx/pytmx.py#L982-L993
def tiles(self): """ Iterate over tile images of this layer This is an optimised generator function that returns (tile_x, tile_y, tile_image) tuples, :rtype: Generator :return: (x, y, image) tuples """ images = self.parent.images for x, y, gid in [i for ...
[ "def", "tiles", "(", "self", ")", ":", "images", "=", "self", ".", "parent", ".", "images", "for", "x", ",", "y", ",", "gid", "in", "[", "i", "for", "i", "in", "self", ".", "iter_data", "(", ")", "if", "i", "[", "2", "]", "]", ":", "yield", ...
Iterate over tile images of this layer This is an optimised generator function that returns (tile_x, tile_y, tile_image) tuples, :rtype: Generator :return: (x, y, image) tuples
[ "Iterate", "over", "tile", "images", "of", "this", "layer" ]
python
train
31.333333
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L26-L31
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
[ "def", "setup", "(", "self", ")", ":", "self", ".", "allow", "=", "self", ".", "config", "[", "'allow'", "]", "self", ".", "halt", "=", "self", ".", "config", "[", "'halt'", "]", "self", ".", "skip", "=", "self", ".", "config", "[", "'skip'", "]"...
Get default configuration.
[ "Get", "default", "configuration", "." ]
python
train
29.166667
JosuaKrause/quick_cache
quick_cache.py
https://github.com/JosuaKrause/quick_cache/blob/a6001f2d77247ae278e679a026174c83ff195d5a/quick_cache.py#L223-L228
def remove_all_locks(self): """Removes all locks and ensures their content is written to disk.""" locks = list(self._locks.items()) locks.sort(key=lambda l: l[1].get_last_access()) for l in locks: self._remove_lock(l[0])
[ "def", "remove_all_locks", "(", "self", ")", ":", "locks", "=", "list", "(", "self", ".", "_locks", ".", "items", "(", ")", ")", "locks", ".", "sort", "(", "key", "=", "lambda", "l", ":", "l", "[", "1", "]", ".", "get_last_access", "(", ")", ")",...
Removes all locks and ensures their content is written to disk.
[ "Removes", "all", "locks", "and", "ensures", "their", "content", "is", "written", "to", "disk", "." ]
python
train
43.166667
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L449-L461
def show_in_view(self, sourceview, matches, targetname=None): """ Show search result in ncurses view. """ append = self.options.append_view or self.options.alter_view == 'append' remove = self.options.alter_view == 'remove' action_name = ', appending to' if append else ', removin...
[ "def", "show_in_view", "(", "self", ",", "sourceview", ",", "matches", ",", "targetname", "=", "None", ")", ":", "append", "=", "self", ".", "options", ".", "append_view", "or", "self", ".", "options", ".", "alter_view", "==", "'append'", "remove", "=", ...
Show search result in ncurses view.
[ "Show", "search", "result", "in", "ncurses", "view", "." ]
python
train
56.461538