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
CTPUG/wafer
wafer/utils.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/utils.py#L34-L54
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if...
[ "def", "cache_result", "(", "cache_key", ",", "timeout", ")", ":", "def", "decorator", "(", "f", ")", ":", "cache_name", "=", "settings", ".", "WAFER_CACHE", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", ...
A decorator for caching the result of a function.
[ "A", "decorator", "for", "caching", "the", "result", "of", "a", "function", "." ]
python
train
29.666667
saltstack/salt
salt/modules/nilrt_ip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L898-L912
def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: ...
[ "def", "get_interface", "(", "iface", ")", ":", "_interfaces", "=", "get_interfaces_details", "(", ")", "for", "_interface", "in", "_interfaces", "[", "'interfaces'", "]", ":", "if", "_interface", "[", "'connectionid'", "]", "==", "iface", ":", "return", "_dic...
Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0
[ "Returns", "details", "about", "given", "interface", "." ]
python
train
23.8
google/transitfeed
unusual_trip_filter.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/unusual_trip_filter.py#L92-L96
def filter(self, dataset): """Mark unusual trips for all the routes in the dataset.""" self.info('Going to filter infrequent routes in the dataset') for route in dataset.routes.values(): self.filter_line(route)
[ "def", "filter", "(", "self", ",", "dataset", ")", ":", "self", ".", "info", "(", "'Going to filter infrequent routes in the dataset'", ")", "for", "route", "in", "dataset", ".", "routes", ".", "values", "(", ")", ":", "self", ".", "filter_line", "(", "route...
Mark unusual trips for all the routes in the dataset.
[ "Mark", "unusual", "trips", "for", "all", "the", "routes", "in", "the", "dataset", "." ]
python
train
44.8
welbornprod/colr
colr/colr.py
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L1666-L1721
def gradient_rgb( self, text=None, fore=None, back=None, style=None, start=None, stop=None, step=1, linemode=True, movefactor=0): """ Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, ...
[ "def", "gradient_rgb", "(", "self", ",", "text", "=", "None", ",", "fore", "=", "None", ",", "back", "=", "None", ",", "style", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "1", ",", "linemode", "=", "True",...
Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, background will be gradient. back : Background color, foreground will be gradient. style : Name of style to use for the gra...
[ "Return", "a", "black", "and", "white", "gradient", ".", "Arguments", ":", "text", ":", "String", "to", "colorize", ".", "fore", ":", "Foreground", "color", "background", "will", "be", "gradient", ".", "back", ":", "Background", "color", "foreground", "will"...
python
train
33.892857
pypa/pipenv
pipenv/vendor/requests/sessions.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L548-L557
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_red...
[ "def", "options", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'OPTIONS'", ",", "url", ",", "*", "*", "kwargs", ")" ]
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
[ "r", "Sends", "a", "OPTIONS", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
python
train
37.9
DataONEorg/d1_python
client_onedrive/src/d1_onedrive/impl/drivers/dokan/dokan.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/dokan/dokan.py#L679-L706
def getFileSecurity( self, fileName, securityInformation, securityDescriptor, lengthSecurityDescriptorBuffer, lengthNeeded, dokanFileInfo, ): """Get security attributes of a file. :param fileName: name of file to get security for :type...
[ "def", "getFileSecurity", "(", "self", ",", "fileName", ",", "securityInformation", ",", "securityDescriptor", ",", "lengthSecurityDescriptorBuffer", ",", "lengthNeeded", ",", "dokanFileInfo", ",", ")", ":", "return", "self", ".", "operations", "(", "'getFileSecurity'...
Get security attributes of a file. :param fileName: name of file to get security for :type fileName: ctypes.c_wchar_p :param securityInformation: buffer for security information :type securityInformation: PSECURITY_INFORMATION :param securityDescriptor: buffer for security descr...
[ "Get", "security", "attributes", "of", "a", "file", "." ]
python
train
37.107143
wearpants/instrument
instrument/output/plot.py
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/plot.py#L51-L60
def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only""" weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5) plt.title(r'%s %s: $\mu=%.2f$, $\si...
[ "def", "_histogram", "(", "self", ",", "which", ",", "mu", ",", "sigma", ",", "data", ")", ":", "weights", "=", "np", ".", "ones_like", "(", "data", ")", "/", "len", "(", "data", ")", "# make bar heights sum to 100%", "n", ",", "bins", ",", "patches", ...
plot a histogram. For internal use only
[ "plot", "a", "histogram", ".", "For", "internal", "use", "only" ]
python
train
56.6
ttinoco/OPTALG
optalg/lin_solver/_mumps/__init__.py
https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L136-L142
def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc): """Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0. """ self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc) self.set_distributed_assembled_values(a_loc)
[ "def", "set_distributed_assembled", "(", "self", ",", "irn_loc", ",", "jcn_loc", ",", "a_loc", ")", ":", "self", ".", "set_distributed_assembled_rows_cols", "(", "irn_loc", ",", "jcn_loc", ")", "self", ".", "set_distributed_assembled_values", "(", "a_loc", ")" ]
Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0.
[ "Set", "the", "distributed", "assembled", "matrix", "." ]
python
train
44
libtcod/python-tcod
tcod/image.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/image.py#L185-L194
def put_pixel(self, x: int, y: int, color: Tuple[int, int, int]) -> None: """Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int]...
[ "def", "put_pixel", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "color", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_image_put_pixel", "(", "self", ".", "image_c", ",", "x", ...
Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
[ "Change", "a", "pixel", "on", "this", "Image", "." ]
python
train
45.8
aio-libs/aiohttp
aiohttp/client.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/client.py#L835-L841
def head(self, url: StrOrURL, *, allow_redirects: bool=False, **kwargs: Any) -> '_RequestContextManager': """Perform HTTP HEAD request.""" return _RequestContextManager( self._request(hdrs.METH_HEAD, url, allow_redirects=allow_redirects, ...
[ "def", "head", "(", "self", ",", "url", ":", "StrOrURL", ",", "*", ",", "allow_redirects", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "'_RequestContextManager'", ":", "return", "_RequestContextManager", "(", "self", ".", "...
Perform HTTP HEAD request.
[ "Perform", "HTTP", "HEAD", "request", "." ]
python
train
47.857143
childsish/lhc-python
lhc/misc/performance_measures.py
https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/misc/performance_measures.py#L152-L173
def confusion_matrix(exp, obs): """Create a confusion matrix In each axis of the resulting confusion matrix the negative case is 0-index and the positive case 1-index. The labels get sorted, in a True/False scenario true positives will occur at (1,1). The first dimension (rows) of the resulting...
[ "def", "confusion_matrix", "(", "exp", ",", "obs", ")", ":", "assert", "len", "(", "exp", ")", "==", "len", "(", "obs", ")", "# Expected in the first dimension (0;rows), observed in the second (1;cols)", "lbls", "=", "sorted", "(", "set", "(", "exp", ")", ")", ...
Create a confusion matrix In each axis of the resulting confusion matrix the negative case is 0-index and the positive case 1-index. The labels get sorted, in a True/False scenario true positives will occur at (1,1). The first dimension (rows) of the resulting matrix is the expected class and the s...
[ "Create", "a", "confusion", "matrix", "In", "each", "axis", "of", "the", "resulting", "confusion", "matrix", "the", "negative", "case", "is", "0", "-", "index", "and", "the", "positive", "case", "1", "-", "index", ".", "The", "labels", "get", "sorted", "...
python
train
39.909091
urschrei/pyzotero
pyzotero/zotero.py
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1269-L1284
def attachment_both(self, files, parentid=None): """ Add child attachments using title, filename Arguments: One or more lists or tuples containing title, file path An optional Item ID, which will create child attachments """ orig = self._attachment_template("impor...
[ "def", "attachment_both", "(", "self", ",", "files", ",", "parentid", "=", "None", ")", ":", "orig", "=", "self", ".", "_attachment_template", "(", "\"imported_file\"", ")", "to_add", "=", "[", "orig", ".", "copy", "(", ")", "for", "f", "in", "files", ...
Add child attachments using title, filename Arguments: One or more lists or tuples containing title, file path An optional Item ID, which will create child attachments
[ "Add", "child", "attachments", "using", "title", "filename", "Arguments", ":", "One", "or", "more", "lists", "or", "tuples", "containing", "title", "file", "path", "An", "optional", "Item", "ID", "which", "will", "create", "child", "attachments" ]
python
valid
39.25
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_terminal.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_terminal.py#L12-L22
def terminal_cfg_line_sessionid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mgmt:brocade-terminal") line = ET.SubElement(terminal_cfg, "line") sessionid = ET.SubEleme...
[ "def", "terminal_cfg_line_sessionid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "terminal_cfg", "=", "ET", ".", "SubElement", "(", "config", ",", "\"terminal-cfg\"", ",", "xmlns", "=", "\"u...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
42.818182
aio-libs/aiozipkin
aiozipkin/helpers.py
https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L79-L90
def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: context.trace_id, SPAN_ID_HEADER: context.span_id, FLAGS_HEADER: '0', SAMPLED_ID_HEADER: '1' if context.sampled else '0', ...
[ "def", "make_headers", "(", "context", ":", "TraceContext", ")", "->", "Headers", ":", "headers", "=", "{", "TRACE_ID_HEADER", ":", "context", ".", "trace_id", ",", "SPAN_ID_HEADER", ":", "context", ".", "span_id", ",", "FLAGS_HEADER", ":", "'0'", ",", "SAMP...
Creates dict with zipkin headers from supplied trace context.
[ "Creates", "dict", "with", "zipkin", "headers", "from", "supplied", "trace", "context", "." ]
python
train
35.083333
earlzo/hfut
hfut/shortcut.py
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/shortcut.py#L59-L70
def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xq...
[ "def", "get_class_info", "(", "self", ",", "xqdm", ",", "kcdm", ",", "jxbh", ")", ":", "return", "self", ".", "query", "(", "GetClassInfo", "(", "xqdm", ",", "kcdm", ",", "jxbh", ")", ")" ]
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
[ "获取教学班详情", "包括上课时间地点", "考查方式", "老师", "选中人数", "课程容量等等信息" ]
python
train
36.583333
Yelp/py_zipkin
py_zipkin/encoding/protobuf/__init__.py
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/protobuf/__init__.py#L22-L32
def encode_pb_list(pb_spans): """Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes """ pb_list = zipkin_pb2.ListOfSpans() pb_list.spans.extend(pb_spans) return pb_list.Serial...
[ "def", "encode_pb_list", "(", "pb_spans", ")", ":", "pb_list", "=", "zipkin_pb2", ".", "ListOfSpans", "(", ")", "pb_list", ".", "spans", ".", "extend", "(", "pb_spans", ")", "return", "pb_list", ".", "SerializeToString", "(", ")" ]
Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes
[ "Encode", "list", "of", "protobuf", "Spans", "to", "binary", "." ]
python
test
29.363636
bwohlberg/sporco
sporco/admm/tvl1.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/tvl1.py#L204-L217
def uinit(self, ushape): """Return initialiser for working variable U.""" if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: # If initial Y is non-zero, initial U is chosen so that # the relevant dual optimality criterion (see (3.10) ...
[ "def", "uinit", "(", "self", ",", "ushape", ")", ":", "if", "self", ".", "opt", "[", "'Y0'", "]", "is", "None", ":", "return", "np", ".", "zeros", "(", "ushape", ",", "dtype", "=", "self", ".", "dtype", ")", "else", ":", "# If initial Y is non-zero, ...
Return initialiser for working variable U.
[ "Return", "initialiser", "for", "working", "variable", "U", "." ]
python
train
48.428571
mordred-descriptor/mordred
mordred/surface_area/_sasa.py
https://github.com/mordred-descriptor/mordred/blob/2848b088fd7b6735590242b5e22573babc724f10/mordred/surface_area/_sasa.py#L58-L85
def atomic_sa(self, i): r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float """ sa = 4.0 * np.pi * self.rads2[i] neighbors = self.neighbors.get(i) if neighbors is None: return sa XYZi = self.xyzs[i, n...
[ "def", "atomic_sa", "(", "self", ",", "i", ")", ":", "sa", "=", "4.0", "*", "np", ".", "pi", "*", "self", ".", "rads2", "[", "i", "]", "neighbors", "=", "self", ".", "neighbors", ".", "get", "(", "i", ")", "if", "neighbors", "is", "None", ":", ...
r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float
[ "r", "Calculate", "atomic", "surface", "area", "." ]
python
test
23.464286
svenevs/exhale
exhale/graph.py
https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/graph.py#L701-L863
def toHierarchy(self, classView, level, stream, lastChild=False): ''' **Parameters** ``classView`` (bool) ``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy. ``level`` (int) Recursion level used to determine indentation. ...
[ "def", "toHierarchy", "(", "self", ",", "classView", ",", "level", ",", "stream", ",", "lastChild", "=", "False", ")", ":", "if", "self", ".", "inHierarchy", "(", "classView", ")", ":", "# For the Tree Views, we need to know if there are nested children before", "# ...
**Parameters** ``classView`` (bool) ``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy. ``level`` (int) Recursion level used to determine indentation. ``stream`` (StringIO) The stream to write the contents to. ...
[ "**", "Parameters", "**", "classView", "(", "bool", ")", "True", "if", "generating", "the", "Class", "Hierarchy", "False", "for", "File", "Hierarchy", "." ]
python
train
49.680982
pazz/alot
alot/ui.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L719-L737
def handle_signal(self, signum, frame): """ handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/...
[ "def", "handle_signal", "(", "self", ",", "signum", ",", "frame", ")", ":", "# it is a SIGINT ?", "if", "signum", "==", "signal", ".", "SIGINT", ":", "logging", ".", "info", "(", "'shut down cleanly'", ")", "asyncio", ".", "ensure_future", "(", "self", ".", ...
handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects)
[ "handles", "UNIX", "signals" ]
python
train
37.789474
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L867-L872
def htmlNewDocNoDtD(URI, ExternalID): """Creates a new HTML document without a DTD node if @URI and @ExternalID are None """ ret = libxml2mod.htmlNewDocNoDtD(URI, ExternalID) if ret is None:raise treeError('htmlNewDocNoDtD() failed') return xmlDoc(_obj=ret)
[ "def", "htmlNewDocNoDtD", "(", "URI", ",", "ExternalID", ")", ":", "ret", "=", "libxml2mod", ".", "htmlNewDocNoDtD", "(", "URI", ",", "ExternalID", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'htmlNewDocNoDtD() failed'", ")", "return", "...
Creates a new HTML document without a DTD node if @URI and @ExternalID are None
[ "Creates", "a", "new", "HTML", "document", "without", "a", "DTD", "node", "if" ]
python
train
45.833333
numenta/htmresearch
htmresearch/frameworks/pytorch/sparse_speech_experiment.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/sparse_speech_experiment.py#L56-L149
def reset(self, params, repetition): """ Called once at the beginning of each experiment. """ self.startTime = time.time() print(params) seed = params["seed"] + repetition torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) # Get our directories correct self.dataD...
[ "def", "reset", "(", "self", ",", "params", ",", "repetition", ")", ":", "self", ".", "startTime", "=", "time", ".", "time", "(", ")", "print", "(", "params", ")", "seed", "=", "params", "[", "\"seed\"", "]", "+", "repetition", "torch", ".", "manual_...
Called once at the beginning of each experiment.
[ "Called", "once", "at", "the", "beginning", "of", "each", "experiment", "." ]
python
train
34.478723
peopledoc/django-agnocomplete
agnocomplete/fields.py
https://github.com/peopledoc/django-agnocomplete/blob/9bf21db2f2036ba5059b843acd32902a09192053/agnocomplete/fields.py#L230-L249
def clean(self, value): """ Clean the field values. """ if not self.create: # No new value can be created, use the regular clean field return super(AgnocompleteModelMultipleField, self).clean(value) # We have to do this here before the call to "super". ...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "create", ":", "# No new value can be created, use the regular clean field", "return", "super", "(", "AgnocompleteModelMultipleField", ",", "self", ")", ".", "clean", "(", "value", ")",...
Clean the field values.
[ "Clean", "the", "field", "values", "." ]
python
train
41.1
mrstephenneal/dirutility
dirutility/backup.py
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L72-L77
def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter.""" # Only supported in Python 3.7+ with ZipFile(self.zip_filename, 'w', compresslevel=self.compress_level) as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): ...
[ "def", "_backup_compresslevel", "(", "self", ",", "dirs", ")", ":", "# Only supported in Python 3.7+", "with", "ZipFile", "(", "self", ".", "zip_filename", ",", "'w'", ",", "compresslevel", "=", "self", ".", "compress_level", ")", "as", "backup_zip", ":", "for",...
Create a backup file with a compresslevel parameter.
[ "Create", "a", "backup", "file", "with", "a", "compresslevel", "parameter", "." ]
python
train
64.5
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L315-L328
def get(self, token): ''' Check the token, returns a 401 if the token is invalid. Else open the websocket connection ''' log.debug('In the websocket get method') self.token = token # close the connection, if not authenticated if not self.application.auth....
[ "def", "get", "(", "self", ",", "token", ")", ":", "log", ".", "debug", "(", "'In the websocket get method'", ")", "self", ".", "token", "=", "token", "# close the connection, if not authenticated", "if", "not", "self", ".", "application", ".", "auth", ".", "g...
Check the token, returns a 401 if the token is invalid. Else open the websocket connection
[ "Check", "the", "token", "returns", "a", "401", "if", "the", "token", "is", "invalid", ".", "Else", "open", "the", "websocket", "connection" ]
python
train
35
dmlc/gluon-nlp
scripts/machine_translation/bleu.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L252-L284
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
[ "def", "_compute_precision", "(", "references", ",", "translation", ",", "n", ")", ":", "matches", "=", "0", "candidates", "=", "0", "ref_ngram_counts", "=", "Counter", "(", ")", "for", "reference", "in", "references", ":", "ref_ngram_counts", "|=", "_ngrams",...
Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number of matched nth order n-grams candidates Number ...
[ "Compute", "ngram", "precision", "." ]
python
train
25.69697
klen/muffin-rest
muffin_rest/filters.py
https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/filters.py#L61-L64
def apply(self, collection, ops, **kwargs): """Apply the filter to collection.""" validator = lambda obj: all(op(obj, val) for (op, val) in ops) # noqa return [o for o in collection if validator(o)]
[ "def", "apply", "(", "self", ",", "collection", ",", "ops", ",", "*", "*", "kwargs", ")", ":", "validator", "=", "lambda", "obj", ":", "all", "(", "op", "(", "obj", ",", "val", ")", "for", "(", "op", ",", "val", ")", "in", "ops", ")", "# noqa",...
Apply the filter to collection.
[ "Apply", "the", "filter", "to", "collection", "." ]
python
train
55
hardbyte/python-can
can/interfaces/pcan/basic.py
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/pcan/basic.py#L395-L426
def InitializeFD( self, Channel, BitrateFD): """ Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_*...
[ "def", "InitializeFD", "(", "self", ",", "Channel", ",", "BitrateFD", ")", ":", "try", ":", "res", "=", "self", ".", "__m_dllBasic", ".", "CAN_InitializeFD", "(", "Channel", ",", "BitrateFD", ")", "return", "TPCANStatus", "(", "res", ")", "except", ":", ...
Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_* values. * parameter and values must be separated by '=' * Couples of Pa...
[ "Initializes", "a", "FD", "capable", "PCAN", "Channel" ]
python
train
33.9375
saltstack/salt
salt/utils/openstack/nova.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L819-L828
def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ...
[ "def", "flavor_access_add", "(", "self", ",", "flavor_id", ",", "project_id", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "ret", "=", "{", "flavor_id", ":", "[", "]", "}", "flavor_accesses", "=", "nt_ks", ".", "flavor_access", ".", "add_tenant_acces...
Add a project to the flavor access list
[ "Add", "a", "project", "to", "the", "flavor", "access", "list" ]
python
train
37.7
taskcluster/taskcluster-client.py
taskcluster/hooks.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/hooks.py#L95-L109
def getHookStatus(self, *args, **kwargs): """ Get hook status This endpoint will return the current status of the hook. This represents a snapshot in time and may vary from one call to the next. This method is deprecated in favor of listLastFires. This method gives ou...
[ "def", "getHookStatus", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"getHookStatus\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Get hook status This endpoint will return the current status of the hook. This represents a snapshot in time and may vary from one call to the next. This method is deprecated in favor of listLastFires. This method gives output: ``v1/hook-status.json#`` This method is ``depre...
[ "Get", "hook", "status" ]
python
train
31.333333
quantmind/pulsar
pulsar/utils/httpurl.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L475-L483
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
Checks to see if the response has a given header name in its Vary header.
[ "Checks", "to", "see", "if", "the", "response", "has", "a", "given", "header", "name", "in", "its", "Vary", "header", "." ]
python
train
41.111111
coderholic/pyradio
pyradio/log.py
https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/log.py#L46-L59
def write_right(self, msg, thread_lock=None): """ msg may or may not be encoded """ if self.cursesScreen: if thread_lock is not None: thread_lock.acquire() try: a_msg = msg.strip() self.cursesScreen.addstr(0, self.width + 5 - len(a_...
[ "def", "write_right", "(", "self", ",", "msg", ",", "thread_lock", "=", "None", ")", ":", "if", "self", ".", "cursesScreen", ":", "if", "thread_lock", "is", "not", "None", ":", "thread_lock", ".", "acquire", "(", ")", "try", ":", "a_msg", "=", "msg", ...
msg may or may not be encoded
[ "msg", "may", "or", "may", "not", "be", "encoded" ]
python
train
48.571429
sassoo/goldman
goldman/deserializers/form_data.py
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/deserializers/form_data.py#L129-L150
def parse(self, mimetypes): """ Invoke the RFC 2388 spec compliant parser """ self._parse_top_level_content_type() link = 'tools.ietf.org/html/rfc2388' parts = cgi.FieldStorage( fp=self.req.stream, environ=self.req.env, ) if not parts: ...
[ "def", "parse", "(", "self", ",", "mimetypes", ")", ":", "self", ".", "_parse_top_level_content_type", "(", ")", "link", "=", "'tools.ietf.org/html/rfc2388'", "parts", "=", "cgi", ".", "FieldStorage", "(", "fp", "=", "self", ".", "req", ".", "stream", ",", ...
Invoke the RFC 2388 spec compliant parser
[ "Invoke", "the", "RFC", "2388", "spec", "compliant", "parser" ]
python
train
37.727273
openfisca/openfisca-web-api
openfisca_web_api/urls.py
https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/urls.py#L63-L129
def make_router(*routings): """Return a WSGI application that dispatches requests to controllers """ routes = [] for routing in routings: methods, regex, app = routing[:3] if isinstance(methods, basestring): methods = (methods,) vars = routing[3] if len(routing) >= 4 else...
[ "def", "make_router", "(", "*", "routings", ")", ":", "routes", "=", "[", "]", "for", "routing", "in", "routings", ":", "methods", ",", "regex", ",", "app", "=", "routing", "[", ":", "3", "]", "if", "isinstance", "(", "methods", ",", "basestring", ")...
Return a WSGI application that dispatches requests to controllers
[ "Return", "a", "WSGI", "application", "that", "dispatches", "requests", "to", "controllers" ]
python
train
44.940299
rwl/pylon
pylon/io/rst.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/rst.py#L358-L435
def write_how_much(self, file): """ Write component quantities to a table. """ report = CaseReport(self.case) col1_header = "Attribute" col1_width = 24 col2_header = "P (MW)" col3_header = "Q (MVAr)" col_width = 8 sep = "="*col1_width +" "+ "=...
[ "def", "write_how_much", "(", "self", ",", "file", ")", ":", "report", "=", "CaseReport", "(", "self", ".", "case", ")", "col1_header", "=", "\"Attribute\"", "col1_width", "=", "24", "col2_header", "=", "\"P (MW)\"", "col3_header", "=", "\"Q (MVAr)\"", "col_wi...
Write component quantities to a table.
[ "Write", "component", "quantities", "to", "a", "table", "." ]
python
train
33.628205
twisted/txaws
txaws/ec2/client.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L237-L249
def authorize_group_permission( self, group_name, source_group_name, source_group_owner_id): """ This is a convenience function that wraps the "authorize group" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_securit...
[ "def", "authorize_group_permission", "(", "self", ",", "group_name", ",", "source_group_name", ",", "source_group_owner_id", ")", ":", "d", "=", "self", ".", "authorize_security_group", "(", "group_name", ",", "source_group_name", "=", "source_group_name", ",", "sourc...
This is a convenience function that wraps the "authorize group" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_security_group}.
[ "This", "is", "a", "convenience", "function", "that", "wraps", "the", "authorize", "group", "functionality", "of", "the", "C", "{", "authorize_security_group", "}", "method", "." ]
python
train
39.923077
stevearc/dql
dql/engine.py
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/engine.py#L132-L137
def connect(self, *args, **kwargs): """ Proxy to DynamoDBConnection.connect. """ self.connection = DynamoDBConnection.connect(*args, **kwargs) self._session = kwargs.get("session") if self._session is None: self._session = botocore.session.get_session()
[ "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "connection", "=", "DynamoDBConnection", ".", "connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_session", "=", "kwargs", ".", "...
Proxy to DynamoDBConnection.connect.
[ "Proxy", "to", "DynamoDBConnection", ".", "connect", "." ]
python
train
48.666667
tBaxter/tango-comments
build/lib/tango_comments/views/moderation.py
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/moderation.py#L15-L37
def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk...
[ "def", "flag", "(", "request", ",", "comment_id", ",", "next", "=", "None", ")", ":", "comment", "=", "get_object_or_404", "(", "comments", ".", "get_model", "(", ")", ",", "pk", "=", "comment_id", ",", "site__pk", "=", "settings", ".", "SITE_ID", ")", ...
Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object
[ "Flags", "a", "comment", ".", "Confirmation", "on", "GET", "action", "on", "POST", "." ]
python
train
30.782609
FactoryBoy/factory_boy
factory/helpers.py
https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/helpers.py#L91-L93
def simple_generate_batch(klass, create, size, **kwargs): """Create a factory for the given class, and simple_generate instances.""" return make_factory(klass, **kwargs).simple_generate_batch(create, size)
[ "def", "simple_generate_batch", "(", "klass", ",", "create", ",", "size", ",", "*", "*", "kwargs", ")", ":", "return", "make_factory", "(", "klass", ",", "*", "*", "kwargs", ")", ".", "simple_generate_batch", "(", "create", ",", "size", ")" ]
Create a factory for the given class, and simple_generate instances.
[ "Create", "a", "factory", "for", "the", "given", "class", "and", "simple_generate", "instances", "." ]
python
train
70.333333
Karaage-Cluster/karaage
karaage/common/passwords.py
https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/common/passwords.py#L50-L67
def assert_strong_password(username, password, old_password=None): """Raises ValueError if the password isn't strong. Returns the password otherwise.""" # test the length try: minlength = settings.MIN_PASSWORD_LENGTH except AttributeError: minlength = 12 if len(password) < minl...
[ "def", "assert_strong_password", "(", "username", ",", "password", ",", "old_password", "=", "None", ")", ":", "# test the length", "try", ":", "minlength", "=", "settings", ".", "MIN_PASSWORD_LENGTH", "except", "AttributeError", ":", "minlength", "=", "12", "if",...
Raises ValueError if the password isn't strong. Returns the password otherwise.
[ "Raises", "ValueError", "if", "the", "password", "isn", "t", "strong", "." ]
python
train
31.666667
googleapis/google-cloud-python
storage/google/cloud/storage/bucket.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L486-L509
def notification( self, topic_name, topic_project=None, custom_attributes=None, event_types=None, blob_name_prefix=None, payload_format=NONE_PAYLOAD_FORMAT, ): """Factory: create a notification resource for the bucket. See: :class:`.BucketNot...
[ "def", "notification", "(", "self", ",", "topic_name", ",", "topic_project", "=", "None", ",", "custom_attributes", "=", "None", ",", "event_types", "=", "None", ",", "blob_name_prefix", "=", "None", ",", "payload_format", "=", "NONE_PAYLOAD_FORMAT", ",", ")", ...
Factory: create a notification resource for the bucket. See: :class:`.BucketNotification` for parameters. :rtype: :class:`.BucketNotification`
[ "Factory", ":", "create", "a", "notification", "resource", "for", "the", "bucket", "." ]
python
train
28.541667
KrishnaswamyLab/PHATE
Python/phate/plot.py
https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L17-L49
def _get_plot_data(data, ndim=None): """Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions """ out = data if isinstance(data, PHATE): out = data...
[ "def", "_get_plot_data", "(", "data", ",", "ndim", "=", "None", ")", ":", "out", "=", "data", "if", "isinstance", "(", "data", ",", "PHATE", ")", ":", "out", "=", "data", ".", "transform", "(", ")", "else", ":", "try", ":", "if", "isinstance", "(",...
Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions
[ "Get", "plot", "data", "out", "of", "an", "input", "object" ]
python
train
32.515152
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1743-L1749
def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params """ m = len(data) self.params[:m] += data
[ "def", "Update", "(", "self", ",", "data", ")", ":", "m", "=", "len", "(", "data", ")", "self", ".", "params", "[", ":", "m", "]", "+=", "data" ]
Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params
[ "Updates", "a", "Dirichlet", "distribution", "." ]
python
train
28.857143
yyuu/botornado
boto/sqs/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sqs/connection.py#L62-L91
def create_queue(self, queue_name, visibility_timeout=None): """ Create an SQS Queue. :type queue_name: str or unicode :param queue_name: The name of the new queue. Names are scoped to an account and need to be unique within that ac...
[ "def", "create_queue", "(", "self", ",", "queue_name", ",", "visibility_timeout", "=", "None", ")", ":", "params", "=", "{", "'QueueName'", ":", "queue_name", "}", "if", "visibility_timeout", ":", "params", "[", "'Attribute.1.Name'", "]", "=", "'VisibilityTimeou...
Create an SQS Queue. :type queue_name: str or unicode :param queue_name: The name of the new queue. Names are scoped to an account and need to be unique within that account. Calling this method on an existing queue name ...
[ "Create", "an", "SQS", "Queue", "." ]
python
train
48.966667
dmwm/DBS
Server/Python/src/dbs/web/DBSReaderModel.py
https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/web/DBSReaderModel.py#L490-L532
def listDatasetArray(self): """ API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :param dataset_id: lis...
[ "def", "listDatasetArray", "(", "self", ")", ":", "ret", "=", "[", "]", "try", ":", "body", "=", "request", ".", "body", ".", "read", "(", ")", "if", "body", ":", "data", "=", "cjson", ".", "decode", "(", "body", ")", "data", "=", "validateJSONInpu...
API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :param dataset_id: list of dataset ids [dataset_id1,dataset_id2,..,dat...
[ "API", "to", "list", "datasets", "in", "DBS", ".", "To", "be", "called", "by", "datasetlist", "url", "with", "post", "call", "." ]
python
train
65.27907
dancsalo/TensorBase
tensorbase/base.py
https://github.com/dancsalo/TensorBase/blob/3d42a326452bd03427034916ff2fb90730020204/tensorbase/base.py#L664-L681
def flatten(self, keep_prob=1): """ Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer) :param keep_prob: int. set to 1 for no dropout """ self.count['flat'] += 1 scope = 'flat_' + str(self.count['flat']) with tf.variable_scope(scope): # ...
[ "def", "flatten", "(", "self", ",", "keep_prob", "=", "1", ")", ":", "self", ".", "count", "[", "'flat'", "]", "+=", "1", "scope", "=", "'flat_'", "+", "str", "(", "self", ".", "count", "[", "'flat'", "]", ")", "with", "tf", ".", "variable_scope", ...
Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer) :param keep_prob: int. set to 1 for no dropout
[ "Flattens", "4D", "Tensor", "(", "from", "Conv", "Layer", ")", "into", "2D", "Tensor", "(", "to", "FC", "Layer", ")", ":", "param", "keep_prob", ":", "int", ".", "set", "to", "1", "for", "no", "dropout" ]
python
train
43.277778
robehickman/simple-http-file-sync
shttpfs/versioned_storage.py
https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L94-L100
def read_dir_tree(self, file_hash): """ Recursively read the directory structure beginning at hash """ json_d = self.read_index_object(file_hash, 'tree') node = {'files' : json_d['files'], 'dirs' : {}} for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(...
[ "def", "read_dir_tree", "(", "self", ",", "file_hash", ")", ":", "json_d", "=", "self", ".", "read_index_object", "(", "file_hash", ",", "'tree'", ")", "node", "=", "{", "'files'", ":", "json_d", "[", "'files'", "]", ",", "'dirs'", ":", "{", "}", "}", ...
Recursively read the directory structure beginning at hash
[ "Recursively", "read", "the", "directory", "structure", "beginning", "at", "hash" ]
python
train
48.285714
inspirehep/inspire-crawler
inspire_crawler/receivers.py
https://github.com/inspirehep/inspire-crawler/blob/36d5cc0cd87cc597ba80e680b7de7254b120173a/inspire_crawler/receivers.py#L39-L54
def receive_oaiharvest_job(request, records, name, **kwargs): """Receive a list of harvested OAI-PMH records and schedule crawls.""" spider = kwargs.get('spider') workflow = kwargs.get('workflow') if not spider or not workflow: return files_created, _ = write_to_dir( records, ...
[ "def", "receive_oaiharvest_job", "(", "request", ",", "records", ",", "name", ",", "*", "*", "kwargs", ")", ":", "spider", "=", "kwargs", ".", "get", "(", "'spider'", ")", "workflow", "=", "kwargs", ".", "get", "(", "'workflow'", ")", "if", "not", "spi...
Receive a list of harvested OAI-PMH records and schedule crawls.
[ "Receive", "a", "list", "of", "harvested", "OAI", "-", "PMH", "records", "and", "schedule", "crawls", "." ]
python
train
35.9375
nicolargo/glances
glances/plugins/glances_gpu.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_gpu.py#L134-L217
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist, not empty (issue #871) and plugin not disabled if not self.stats or (self.stats == []) or self.is_disable():...
[ "def", "msg_curse", "(", "self", ",", "args", "=", "None", ",", "max_width", "=", "None", ")", ":", "# Init the return message", "ret", "=", "[", "]", "# Only process if stats exist, not empty (issue #871) and plugin not disabled", "if", "not", "self", ".", "stats", ...
Return the dict to display in the curse interface.
[ "Return", "the", "dict", "to", "display", "in", "the", "curse", "interface", "." ]
python
train
39.583333
flaviogrossi/sockjs-cyclone
sockjs/cyclone/session.py
https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L330-L338
def send_message(self, msg, stats=True): """ Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes """ self.send_jsonified(proto.json_encode(msg), stats)
[ "def", "send_message", "(", "self", ",", "msg", ",", "stats", "=", "True", ")", ":", "self", ".", "send_jsonified", "(", "proto", ".", "json_encode", "(", "msg", ")", ",", "stats", ")" ]
Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes
[ "Send", "or", "queue", "outgoing", "message" ]
python
train
32.555556
saltstack/salt
salt/cloud/clouds/openstack.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L619-L658
def request_instance(vm_, conn=None, call=None): ''' Request an instance to be built ''' if call == 'function': # Technically this function may be called other ways too, but it # definitely cannot be called with --function. raise SaltCloudSystemExit( 'The request_inst...
[ "def", "request_instance", "(", "vm_", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "# Technically this function may be called other ways too, but it", "# definitely cannot be called with --function.", "raise", "Salt...
Request an instance to be built
[ "Request", "an", "instance", "to", "be", "built" ]
python
train
40.725
pilosus/ForgeryPy3
forgery_py/forgery/lorem_ipsum.py
https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L65-L69
def title(words_quantity=4): """Return a random sentence to be used as e.g. an e-mail subject.""" result = words(quantity=words_quantity) result += random.choice('?.!') return result.capitalize()
[ "def", "title", "(", "words_quantity", "=", "4", ")", ":", "result", "=", "words", "(", "quantity", "=", "words_quantity", ")", "result", "+=", "random", ".", "choice", "(", "'?.!'", ")", "return", "result", ".", "capitalize", "(", ")" ]
Return a random sentence to be used as e.g. an e-mail subject.
[ "Return", "a", "random", "sentence", "to", "be", "used", "as", "e", ".", "g", ".", "an", "e", "-", "mail", "subject", "." ]
python
valid
41.4
codeinn/vcs
vcs/backends/git/config.py
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/config.py#L153-L163
def _unescape_value(value): """Unescape a value.""" def unescape(c): return { "\\\\": "\\", "\\\"": "\"", "\\n": "\n", "\\t": "\t", "\\b": "\b", }[c.group(0)] return re.sub(r"(\\.)", unescape, value)
[ "def", "_unescape_value", "(", "value", ")", ":", "def", "unescape", "(", "c", ")", ":", "return", "{", "\"\\\\\\\\\"", ":", "\"\\\\\"", ",", "\"\\\\\\\"\"", ":", "\"\\\"\"", ",", "\"\\\\n\"", ":", "\"\\n\"", ",", "\"\\\\t\"", ":", "\"\\t\"", ",", "\"\\\\b...
Unescape a value.
[ "Unescape", "a", "value", "." ]
python
train
25.545455
saltstack/salt
salt/version.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L627-L704
def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.jo...
[ "def", "system_information", "(", ")", ":", "def", "system_version", "(", ")", ":", "'''\n Return host system version.\n '''", "lin_ver", "=", "linux_distribution", "(", ")", "mac_ver", "=", "platform", ".", "mac_ver", "(", ")", "win_ver", "=", "platfo...
Report system versions.
[ "Report", "system", "versions", "." ]
python
train
34.717949
elifesciences/elife-article
elifearticle/parse.py
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L376-L384
def build_self_uri_list(self_uri_list): "parse the self-uri tags, build Uri objects" uri_list = [] for self_uri in self_uri_list: uri = ea.Uri() utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href')) utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-t...
[ "def", "build_self_uri_list", "(", "self_uri_list", ")", ":", "uri_list", "=", "[", "]", "for", "self_uri", "in", "self_uri_list", ":", "uri", "=", "ea", ".", "Uri", "(", ")", "utils", ".", "set_attr_if_value", "(", "uri", ",", "'xlink_href'", ",", "self_u...
parse the self-uri tags, build Uri objects
[ "parse", "the", "self", "-", "uri", "tags", "build", "Uri", "objects" ]
python
train
40.777778
teepark/junction
junction/client.py
https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/client.py#L40-L55
def wait_connected(self, timeout=None): '''Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were mad...
[ "def", "wait_connected", "(", "self", ",", "timeout", "=", "None", ")", ":", "result", "=", "self", ".", "_peer", ".", "wait_connected", "(", "timeout", ")", "if", "not", "result", ":", "if", "timeout", "is", "not", "None", ":", "log", ".", "warn", "...
Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were made, ``False`` if one or more failed.
[ "Wait", "for", "connections", "to", "be", "made", "and", "their", "handshakes", "to", "finish" ]
python
train
36.0625
nameko/nameko
nameko/messaging.py
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/messaging.py#L390-L396
def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
[ "def", "on_iteration", "(", "self", ")", ":", "self", ".", "_cancel_consumers_if_requested", "(", ")", "if", "len", "(", "self", ".", "_consumers", ")", "==", "0", ":", "_log", ".", "debug", "(", "'requesting stop after iteration'", ")", "self", ".", "should...
Kombu callback for each `drain_events` loop iteration.
[ "Kombu", "callback", "for", "each", "drain_events", "loop", "iteration", "." ]
python
train
38
Chilipp/psy-simple
psy_simple/plotters.py
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L41-L93
def round_to_05(n, exp=None, mode='s'): """ Round to the next 0.5-value. This function applies the round function `func` to round `n` to the next 0.5-value with respect to its exponent with base 10 (i.e. 1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect to the given exponent in...
[ "def", "round_to_05", "(", "n", ",", "exp", "=", "None", ",", "mode", "=", "'s'", ")", ":", "n", "=", "np", ".", "asarray", "(", "n", ")", "if", "exp", "is", "None", ":", "exp", "=", "np", ".", "floor", "(", "np", ".", "log10", "(", "np", "...
Round to the next 0.5-value. This function applies the round function `func` to round `n` to the next 0.5-value with respect to its exponent with base 10 (i.e. 1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect to the given exponent in `exp`. Parameters ---------- n: numpy....
[ "Round", "to", "the", "next", "0", ".", "5", "-", "value", "." ]
python
train
31.981132
fumitoh/modelx
modelx/io/pandas.py
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/pandas.py#L133-L194
def cells_to_series(cells, args): """Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant args are ignored. """ ...
[ "def", "cells_to_series", "(", "cells", ",", "args", ")", ":", "paramlen", "=", "len", "(", "cells", ".", "formula", ".", "parameters", ")", "is_multidx", "=", "paramlen", ">", "1", "if", "len", "(", "cells", ".", "data", ")", "==", "0", ":", "data",...
Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant args are ignored.
[ "Convert", "a", "CellImpl", "into", "a", "Series", "." ]
python
valid
28.145161
Clinical-Genomics/scout
scout/adapter/mongo/variant.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/variant.py#L225-L252
def variant(self, document_id, gene_panels=None, case_id=None): """Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant...
[ "def", "variant", "(", "self", ",", "document_id", ",", "gene_panels", "=", "None", ",", "case_id", "=", "None", ")", ":", "query", "=", "{", "}", "if", "case_id", ":", "# search for a variant in a case", "query", "[", "'case_id'", "]", "=", "case_id", "qu...
Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant_id") Returns: variant_object(Variant): A odm va...
[ "Returns", "the", "specified", "variant", "." ]
python
test
38.642857
rosenbrockc/fortpy
fortpy/msg.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/msg.py#L72-L81
def will_print(level=1): """Returns True if the current global status of messaging would print a message using any of the printing functions in this module. """ if level == 1: #We only affect printability using the quiet setting. return quiet is None or quiet == False else: r...
[ "def", "will_print", "(", "level", "=", "1", ")", ":", "if", "level", "==", "1", ":", "#We only affect printability using the quiet setting.", "return", "quiet", "is", "None", "or", "quiet", "==", "False", "else", ":", "return", "(", "(", "isinstance", "(", ...
Returns True if the current global status of messaging would print a message using any of the printing functions in this module.
[ "Returns", "True", "if", "the", "current", "global", "status", "of", "messaging", "would", "print", "a", "message", "using", "any", "of", "the", "printing", "functions", "in", "this", "module", "." ]
python
train
44.1
yyuu/botornado
boto/iam/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/iam/connection.py#L642-L661
def upload_signing_cert(self, cert_body, user_name=None): """ Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type ce...
[ "def", "upload_signing_cert", "(", "self", ",", "cert_body", ",", "user_name", "=", "None", ")", ":", "params", "=", "{", "'CertificateBody'", ":", "cert_body", "}", "if", "user_name", ":", "params", "[", "'UserName'", "]", "=", "user_name", "return", "self"...
Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type cert_body: string :param cert_body: The body of the signing certificate....
[ "Uploads", "an", "X", ".", "509", "signing", "certificate", "and", "associates", "it", "with", "the", "specified", "user", "." ]
python
train
35.25
facebook/pyre-check
sapp/sapp/cli_lib.py
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/cli_lib.py#L78-L86
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]): """Try to guess a reasonable database name by looking at the repository path""" if value: return value if ctx.params["repository"]: return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE) raise...
[ "def", "default_database", "(", "ctx", ":", "click", ".", "Context", ",", "_param", ":", "Parameter", ",", "value", ":", "Optional", "[", "str", "]", ")", ":", "if", "value", ":", "return", "value", "if", "ctx", ".", "params", "[", "\"repository\"", "]...
Try to guess a reasonable database name by looking at the repository path
[ "Try", "to", "guess", "a", "reasonable", "database", "name", "by", "looking", "at", "the", "repository", "path" ]
python
train
41.111111
christophertbrown/bioscripts
ctbBio/ncbi_download.py
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/ncbi_download.py#L18-L31
def calcMD5(path): """ calc MD5 based on path """ # check that file exists if os.path.exists(path) is False: yield False else: command = ['md5sum', path] p = Popen(command, stdout = PIPE) for line in p.communicate()[0].splitlines(): yield line.decode('...
[ "def", "calcMD5", "(", "path", ")", ":", "# check that file exists", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "is", "False", ":", "yield", "False", "else", ":", "command", "=", "[", "'md5sum'", ",", "path", "]", "p", "=", "Popen", "(...
calc MD5 based on path
[ "calc", "MD5", "based", "on", "path" ]
python
train
26.428571
aganezov/bg
bg/breakpoint_graph.py
https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/breakpoint_graph.py#L260-L280
def __get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to i...
[ "def", "__get_edges_by_vertex", "(", "self", ",", "vertex", ",", "keys", "=", "False", ")", ":", "if", "vertex", "in", "self", ".", "bg", ":", "for", "vertex2", ",", "edges", "in", "self", ".", "bg", "[", "vertex", "]", ".", "items", "(", ")", ":",...
Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to it. Wraps each yielded object into :class:`bg.edge.BGEdge` object....
[ "Iterates", "over", "edges", "that", "are", "incident", "to", "supplied", "vertex", "argument", "in", "current", ":", "class", ":", "BreakpointGraph" ]
python
train
65
BerkeleyAutomation/perception
ros_nodes/weight_publisher.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/ros_nodes/weight_publisher.py#L124-L150
def _read_weights(self): """Reads weights from each of the load cells. """ weights = [] grams_per_pound = 453.592 # Read from each of the sensors for ser in self._serials: ser.write('W\r') ser.flush() time.sleep(0.02) for ser in s...
[ "def", "_read_weights", "(", "self", ")", ":", "weights", "=", "[", "]", "grams_per_pound", "=", "453.592", "# Read from each of the sensors", "for", "ser", "in", "self", ".", "_serials", ":", "ser", ".", "write", "(", "'W\\r'", ")", "ser", ".", "flush", "...
Reads weights from each of the load cells.
[ "Reads", "weights", "from", "each", "of", "the", "load", "cells", "." ]
python
train
26.037037
kensho-technologies/graphql-compiler
graphql_compiler/schema_generation/schema_graph.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/schema_generation/schema_graph.py#L64-L71
def _validate_collections_have_default_values(class_name, property_name, property_descriptor): """Validate that if the property is of collection type, it has a specified default value.""" # We don't want properties of collection type having "null" values, since that may cause # unexpected errors during Grap...
[ "def", "_validate_collections_have_default_values", "(", "class_name", ",", "property_name", ",", "property_descriptor", ")", ":", "# We don't want properties of collection type having \"null\" values, since that may cause", "# unexpected errors during GraphQL query execution and other operati...
Validate that if the property is of collection type, it has a specified default value.
[ "Validate", "that", "if", "the", "property", "is", "of", "collection", "type", "it", "has", "a", "specified", "default", "value", "." ]
python
train
83.25
hyperledger/indy-node
environment/vagrant/sandbox/DevelopmentEnvironment/common/indypool.py
https://github.com/hyperledger/indy-node/blob/8fabd364eaf7d940a56df2911d9215b1e512a2de/environment/vagrant/sandbox/DevelopmentEnvironment/common/indypool.py#L66-L87
def runContainer(image, **kwargs): '''Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions. ''' container = Non...
[ "def", "runContainer", "(", "image", ",", "*", "*", "kwargs", ")", ":", "container", "=", "None", "try", ":", "container", "=", "client", ".", "containers", ".", "run", "(", "image", ",", "*", "*", "kwargs", ")", "if", "\"name\"", "in", "kwargs", "."...
Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions.
[ "Run", "a", "docker", "container", "using", "a", "given", "image", ";", "passing", "keyword", "arguments", "documented", "to", "be", "accepted", "by", "docker", "s", "client", ".", "containers", ".", "run", "function", "No", "extra", "side", "effects", ".", ...
python
train
35.590909
xtrementl/focus
focus/daemon.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/daemon.py#L530-L545
def shutdown(self, skip_hooks=False): """ Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins. """ if not self._exited: self._exited = True if not skip_hooks: self._run_events(shutd...
[ "def", "shutdown", "(", "self", ",", "skip_hooks", "=", "False", ")", ":", "if", "not", "self", ".", "_exited", ":", "self", ".", "_exited", "=", "True", "if", "not", "skip_hooks", ":", "self", ".", "_run_events", "(", "shutdown", "=", "True", ")", "...
Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins.
[ "Shuts", "down", "the", "process", "." ]
python
train
25.8125
jazzband/django-ddp
dddp/postgres.py
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/postgres.py#L99-L150
def poll(self, conn): """Poll DB socket and process async tasks.""" while 1: state = conn.poll() if state == psycopg2.extensions.POLL_OK: while conn.notifies: notify = conn.notifies.pop() self.logger.info( ...
[ "def", "poll", "(", "self", ",", "conn", ")", ":", "while", "1", ":", "state", "=", "conn", ".", "poll", "(", ")", "if", "state", "==", "psycopg2", ".", "extensions", ".", "POLL_OK", ":", "while", "conn", ".", "notifies", ":", "notify", "=", "conn"...
Poll DB socket and process async tasks.
[ "Poll", "DB", "socket", "and", "process", "async", "tasks", "." ]
python
test
44.076923
fuzeman/trakt.py
examples/authentication/device.py
https://github.com/fuzeman/trakt.py/blob/14c6b72e3c13ea2975007aeac0c01ad2222b67f3/examples/authentication/device.py#L84-L101
def on_authenticated(self, authorization): """Device authenticated. :param authorization: Authentication token details :type authorization: dict """ # Acquire condition self.is_authenticating.acquire() # Store authorization for future calls self.authori...
[ "def", "on_authenticated", "(", "self", ",", "authorization", ")", ":", "# Acquire condition", "self", ".", "is_authenticating", ".", "acquire", "(", ")", "# Store authorization for future calls", "self", ".", "authorization", "=", "authorization", "print", "(", "'Aut...
Device authenticated. :param authorization: Authentication token details :type authorization: dict
[ "Device", "authenticated", "." ]
python
train
29.444444
agoragames/haigha
haigha/connection.py
https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connection.py#L204-L252
def connect(self, host, port): ''' Connect to a host and port. ''' # Clear the connect state immediately since we're no longer connected # at this point. self._connected = False # Only after the socket has connected do we clear this state; closed # must b...
[ "def", "connect", "(", "self", ",", "host", ",", "port", ")", ":", "# Clear the connect state immediately since we're no longer connected", "# at this point.", "self", ".", "_connected", "=", "False", "# Only after the socket has connected do we clear this state; closed", "# must...
Connect to a host and port.
[ "Connect", "to", "a", "host", "and", "port", "." ]
python
train
49.632653
user-cont/conu
conu/backend/podman/image.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L179-L189
def rmi(self, force=False, via_name=False): """ remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID :return: None """ identifier = self.get_full_name() if via_name else (self....
[ "def", "rmi", "(", "self", ",", "force", "=", "False", ",", "via_name", "=", "False", ")", ":", "identifier", "=", "self", ".", "get_full_name", "(", ")", "if", "via_name", "else", "(", "self", ".", "_id", "or", "self", ".", "get_id", "(", ")", ")"...
remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID :return: None
[ "remove", "this", "image" ]
python
train
39.272727
huge-success/sanic
sanic/app.py
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L501-L535
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class ...
[ "def", "add_websocket_route", "(", "self", ",", "handler", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "subprotocols", "=", "None", ",", "name", "=", "None", ",", ")", ":", "if", "strict_slashes", "is", "None", ":", "...
A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket ...
[ "A", "helper", "method", "to", "register", "a", "function", "as", "a", "websocket", "route", "." ]
python
train
32.771429
treycucco/bidon
bidon/util/transform.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L137-L144
def get_xml_text(source, path=None): """Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path. """ if path is None: return source.text else: return get_xml_text(get_xml_child(source, path))
[ "def", "get_xml_text", "(", "source", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "return", "source", ".", "text", "else", ":", "return", "get_xml_text", "(", "get_xml_child", "(", "source", ",", "path", ")", ")" ]
Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path.
[ "Get", "the", "text", "of", "the", "XML", "node", ".", "If", "path", "is", "not", "None", "it", "will", "get", "the", "text", "of", "the", "descendant", "of", "source", "indicated", "by", "path", "." ]
python
train
33
GoogleCloudPlatform/datastore-ndb-python
ndb/blobstore.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L191-L202
def get_multi(cls, blob_keys, **ctx_options): """Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None. """ futs = cls.get_multi_async(blob_ke...
[ "def", "get_multi", "(", "cls", ",", "blob_keys", ",", "*", "*", "ctx_options", ")", ":", "futs", "=", "cls", ".", "get_multi_async", "(", "blob_keys", ",", "*", "*", "ctx_options", ")", "return", "[", "fut", ".", "get_result", "(", ")", "for", "fut", ...
Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None.
[ "Multi", "-", "key", "version", "of", "get", "()", "." ]
python
train
31.083333
django-parler/django-parler
parler/admin.py
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L570-L580
def default_change_form_template(self): """ Determine what the actual `change_form_template` should be. """ opts = self.model._meta app_label = opts.app_label return select_template_name(( "admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.low...
[ "def", "default_change_form_template", "(", "self", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "app_label", "=", "opts", ".", "app_label", "return", "select_template_name", "(", "(", "\"admin/{0}/{1}/change_form.html\"", ".", "format", "(", "app_la...
Determine what the actual `change_form_template` should be.
[ "Determine", "what", "the", "actual", "change_form_template", "should", "be", "." ]
python
train
38.545455
titusjan/argos
argos/inspector/qtplugins/table.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L58-L98
def makeReplacementField(formatSpec, altFormatSpec='', testValue=None): """ Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://doc...
[ "def", "makeReplacementField", "(", "formatSpec", ",", "altFormatSpec", "=", "''", ",", "testValue", "=", "None", ")", ":", "check_is_a_string", "(", "formatSpec", ")", "check_is_a_string", "(", "altFormatSpec", ")", "fmt", "=", "altFormatSpec", "if", "not", "fo...
Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.org/3/library/string.html#format-string-syntax https://docs...
[ "Prepends", "a", "colon", "and", "wraps", "the", "formatSpec", "in", "curly", "braces", "to", "yield", "a", "replacement", "field", "." ]
python
train
42.658537
razor-x/scipy-data_fitting
scipy_data_fitting/fit.py
https://github.com/razor-x/scipy-data_fitting/blob/c756a645da8629699b3f22244bfb7d5d4d88b179/scipy_data_fitting/fit.py#L609-L632
def curve_fit(self): """ Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm. """ if not ha...
[ "def", "curve_fit", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_curve_fit'", ")", ":", "options", "=", "self", ".", "options", ".", "copy", "(", ")", "fit_function", "=", "options", ".", "pop", "(", "'fit_function'", ")", "indep...
Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm.
[ "Fits", "scipy_data_fitting", ".", "Fit", ".", "function", "to", "the", "data", "and", "returns", "the", "output", "from", "the", "specified", "curve", "fit", "function", "." ]
python
train
43.916667
PyGithub/PyGithub
github/AuthenticatedUser.py
https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/AuthenticatedUser.py#L1129-L1139
def remove_from_watched(self, watched): """ :calls: `DELETE /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: None """ assert isinstance(watched, github.Repository.Repository...
[ "def", "remove_from_watched", "(", "self", ",", "watched", ")", ":", "assert", "isinstance", "(", "watched", ",", "github", ".", "Repository", ".", "Repository", ")", ",", "watched", "headers", ",", "data", "=", "self", ".", "_requester", ".", "requestJsonAn...
:calls: `DELETE /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: None
[ ":", "calls", ":", "DELETE", "/", "repos", "/", ":", "owner", "/", ":", "repo", "/", "subscription", "<http", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "activity", "/", "watching", ">", "_", ":", "param", "watched", ":", ":...
python
train
43
learningequality/ricecooker
ricecooker/classes/files.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/files.py#L139-L162
def write_and_get_hash(path, write_to_file, hash=None): """ write_and_get_hash: write file Args: None Returns: Hash of file's contents """ hash = hash or hashlib.md5() try: # Access path r = config.DOWNLOAD_SESSION.get(path, stream=True) r.raise_for_status() ...
[ "def", "write_and_get_hash", "(", "path", ",", "write_to_file", ",", "hash", "=", "None", ")", ":", "hash", "=", "hash", "or", "hashlib", ".", "md5", "(", ")", "try", ":", "# Access path", "r", "=", "config", ".", "DOWNLOAD_SESSION", ".", "get", "(", "...
write_and_get_hash: write file Args: None Returns: Hash of file's contents
[ "write_and_get_hash", ":", "write", "file", "Args", ":", "None", "Returns", ":", "Hash", "of", "file", "s", "contents" ]
python
train
33.125
deep-compute/logagg
logagg/collector.py
https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L23-L31
def load_formatter_fn(formatter): ''' >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> ''' obj = util.load_object(formatter) if not hasattr(obj, 'ispartial'): obj.ispartial = util.ispartial return obj
[ "def", "load_formatter_fn", "(", "formatter", ")", ":", "obj", "=", "util", ".", "load_object", "(", "formatter", ")", "if", "not", "hasattr", "(", "obj", ",", "'ispartial'", ")", ":", "obj", ".", "ispartial", "=", "util", ".", "ispartial", "return", "ob...
>>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...>
[ ">>>", "load_formatter_fn", "(", "logagg", ".", "formatters", ".", "basescript", ")", "#doctest", ":", "+", "ELLIPSIS", "<function", "basescript", "at", "0x", "...", ">" ]
python
train
31.555556
inasafe/inasafe
safe/impact_function/impact_function.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L959-L970
def set_state_process(self, context, process): """Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. ...
[ "def", "set_state_process", "(", "self", ",", "context", ",", "process", ")", ":", "LOGGER", ".", "info", "(", "'%s: %s'", "%", "(", "context", ",", "process", ")", ")", "self", ".", "state", "[", "context", "]", "[", "\"process\"", "]", ".", "append",...
Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode
[ "Method", "to", "append", "process", "for", "a", "context", "in", "the", "IF", "state", "." ]
python
train
38
jfilter/text-classification-keras
texcla/preprocessing/utils.py
https://github.com/jfilter/text-classification-keras/blob/a59c652805da41d18937c7fdad0d9fd943cf8578/texcla/preprocessing/utils.py#L64-L74
def finalize(self): """This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed easily. """ for i in rang...
[ "def", "finalize", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "_local_counts", ")", ")", ":", "self", ".", "counts", "[", "i", "]", ".", "append", "(", "self", ".", "_local_counts", "[", "i", "]", ...
This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed easily.
[ "This", "will", "add", "the", "very", "last", "document", "to", "counts", ".", "We", "also", "get", "rid", "of", "counts", "[", "0", "]", "since", "that", "represents", "document", "level", "which", "doesnt", "come", "under", "anything", "else", ".", "We...
python
train
47.363636
MAVENSDC/cdflib
cdflib/cdfwrite.py
https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfwrite.py#L1286-L1293
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset): ''' This sets a VXR to be the first and last VXR in the VDR ''' # VDR's VXRhead self._update_offset_value(f, vdr_offset+28, 8, VXRoffset) # VDR's VXRtail self._update_offset_value(f, vdr_offset+36, 8, VX...
[ "def", "_update_vdr_vxrheadtail", "(", "self", ",", "f", ",", "vdr_offset", ",", "VXRoffset", ")", ":", "# VDR's VXRhead", "self", ".", "_update_offset_value", "(", "f", ",", "vdr_offset", "+", "28", ",", "8", ",", "VXRoffset", ")", "# VDR's VXRtail", "self", ...
This sets a VXR to be the first and last VXR in the VDR
[ "This", "sets", "a", "VXR", "to", "be", "the", "first", "and", "last", "VXR", "in", "the", "VDR" ]
python
train
40.125
janpipek/physt
physt/binnings.py
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L77-L86
def to_dict(self) -> OrderedDict: """Dictionary representation of the binning schema. This serves as template method, please implement _update_dict """ result = OrderedDict() result["adaptive"] = self._adaptive result["binning_type"] = type(self).__name__ self._u...
[ "def", "to_dict", "(", "self", ")", "->", "OrderedDict", ":", "result", "=", "OrderedDict", "(", ")", "result", "[", "\"adaptive\"", "]", "=", "self", ".", "_adaptive", "result", "[", "\"binning_type\"", "]", "=", "type", "(", "self", ")", ".", "__name__...
Dictionary representation of the binning schema. This serves as template method, please implement _update_dict
[ "Dictionary", "representation", "of", "the", "binning", "schema", "." ]
python
train
35.1
elbow-jason/Uno-deprecated
uno/helpers.py
https://github.com/elbow-jason/Uno-deprecated/blob/4ad07d7b84e5b6e3e2b2c89db69448906f24b4e4/uno/helpers.py#L8-L22
def math_func(f): """ Statics the methods. wut. """ @wraps(f) def wrapper(*args, **kwargs): if len(args) > 0: return_type = type(args[0]) if kwargs.has_key('return_type'): return_type = kwargs['return_type'] kwargs.pop('return_type') re...
[ "def", "math_func", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "0", ":", "return_type", "=", "type", "(", "args", "[", "0", "]", ...
Statics the methods. wut.
[ "Statics", "the", "methods", ".", "wut", "." ]
python
train
30.333333
nwilming/ocupy
ocupy/parallel.py
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L268-L289
def ind2sub(ind, dimensions): """ Calculates subscripts for indices into regularly spaced matrixes. """ # check that the index is within range if ind >= np.prod(dimensions): raise RuntimeError("ind2sub: index exceeds array size") cum_dims = list(dimensions) cum_dims.reverse() m =...
[ "def", "ind2sub", "(", "ind", ",", "dimensions", ")", ":", "# check that the index is within range", "if", "ind", ">=", "np", ".", "prod", "(", "dimensions", ")", ":", "raise", "RuntimeError", "(", "\"ind2sub: index exceeds array size\"", ")", "cum_dims", "=", "li...
Calculates subscripts for indices into regularly spaced matrixes.
[ "Calculates", "subscripts", "for", "indices", "into", "regularly", "spaced", "matrixes", "." ]
python
train
24.954545
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L4614-L4620
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None): """Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)""" E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/...
[ "def", "relaxng", "(", "cls", ",", "includechildren", "=", "True", ",", "extraattribs", "=", "None", ",", "extraelements", "=", "None", ",", "origclass", "=", "None", ")", ":", "E", "=", "ElementMaker", "(", "namespace", "=", "\"http://relaxng.org/ns/structure...
Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)
[ "Returns", "a", "RelaxNG", "definition", "for", "this", "element", "(", "as", "an", "XML", "element", "(", "lxml", ".", "etree", ")", "rather", "than", "a", "string", ")" ]
python
train
97.714286
HewlettPackard/python-hpOneView
hpOneView/resources/networking/logical_interconnects.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L153-L168
def update_ethernet_settings(self, configuration, force=False, timeout=-1): """ Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any probl...
[ "def", "update_ethernet_settings", "(", "self", ",", "configuration", ",", "force", "=", "False", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}/ethernetSettings\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ")", "return", ...
Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is f...
[ "Updates", "the", "Ethernet", "interconnect", "settings", "for", "the", "logical", "interconnect", "." ]
python
train
50.9375
revelc/pyaccumulo
pyaccumulo/proxy/AccumuloProxy.py
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L1617-L1624
def offlineTable(self, login, tableName): """ Parameters: - login - tableName """ self.send_offlineTable(login, tableName) self.recv_offlineTable()
[ "def", "offlineTable", "(", "self", ",", "login", ",", "tableName", ")", ":", "self", ".", "send_offlineTable", "(", "login", ",", "tableName", ")", "self", ".", "recv_offlineTable", "(", ")" ]
Parameters: - login - tableName
[ "Parameters", ":", "-", "login", "-", "tableName" ]
python
train
21.25
bitesofcode/projexui
projexui/widgets/xoverlaywizard.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L174-L182
def setSubTitle(self, title): """ Sets the sub-title for this page to the inputed title. :param title | <str> """ self._subTitleLabel.setText(title) self._subTitleLabel.adjustSize() self.adjustMargins()
[ "def", "setSubTitle", "(", "self", ",", "title", ")", ":", "self", ".", "_subTitleLabel", ".", "setText", "(", "title", ")", "self", ".", "_subTitleLabel", ".", "adjustSize", "(", ")", "self", ".", "adjustMargins", "(", ")" ]
Sets the sub-title for this page to the inputed title. :param title | <str>
[ "Sets", "the", "sub", "-", "title", "for", "this", "page", "to", "the", "inputed", "title", "." ]
python
train
28.444444
saltstack/salt
salt/modules/apf.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apf.py#L57-L66
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
[ "def", "_status_apf", "(", ")", ":", "status", "=", "0", "table", "=", "iptc", ".", "Table", "(", "iptc", ".", "Table", ".", "FILTER", ")", "for", "chain", "in", "table", ".", "chains", ":", "if", "'sanity'", "in", "chain", ".", "name", ".", "lower...
Return True if apf is running otherwise return False
[ "Return", "True", "if", "apf", "is", "running", "otherwise", "return", "False" ]
python
train
27.3
h2oai/h2o-3
h2o-py/h2o/frame.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/frame.py#L3219-L3241
def cut(self, breaks, labels=None, include_lowest=False, right=True, dig_lab=3): """ Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[st...
[ "def", "cut", "(", "self", ",", "breaks", ",", "labels", "=", "None", ",", "include_lowest", "=", "False", ",", "right", "=", "True", ",", "dig_lab", "=", "3", ")", ":", "assert_is_type", "(", "breaks", ",", "[", "numeric", "]", ")", "if", "self", ...
Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[str] labels: Labels for categorical levels produced. Defaults to set notation of intervals ...
[ "Cut", "a", "numeric", "vector", "into", "categorical", "buckets", "." ]
python
test
57.347826
mozilla/python_moztelemetry
moztelemetry/dataset.py
https://github.com/mozilla/python_moztelemetry/blob/09ddf1ec7d953a4308dfdcb0ed968f27bd5921bb/moztelemetry/dataset.py#L174-L197
def select(self, *properties, **aliased_properties): """Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties: JME...
[ "def", "select", "(", "self", ",", "*", "properties", ",", "*", "*", "aliased_properties", ")", ":", "if", "not", "(", "properties", "or", "aliased_properties", ")", ":", "return", "self", "merged_properties", "=", "dict", "(", "zip", "(", "properties", ",...
Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties: JMESPath to use for the property extraction. ...
[ "Specify", "which", "properties", "of", "the", "dataset", "must", "be", "returned" ]
python
train
48.125
materialsproject/pymatgen
pymatgen/io/abinit/tasks.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L2596-L2605
def from_input(cls, input, workdir=None, manager=None): """ Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object. """ return c...
[ "def", "from_input", "(", "cls", ",", "input", ",", "workdir", "=", "None", ",", "manager", "=", "None", ")", ":", "return", "cls", "(", "input", ",", "workdir", "=", "workdir", ",", "manager", "=", "manager", ")" ]
Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object.
[ "Create", "an", "instance", "of", "AbinitTask", "from", "an", "ABINIT", "input", "." ]
python
train
35.4
pedroburon/tbk
tbk/webpay/payment.py
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/payment.py#L76-L85
def token(self): """ Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred. """ if not self._token: self._token = self.fetch_token() logger.payment(self) return self._token
[ "def", "token", "(", "self", ")", ":", "if", "not", "self", ".", "_token", ":", "self", ".", "_token", "=", "self", ".", "fetch_token", "(", ")", "logger", ".", "payment", "(", "self", ")", "return", "self", ".", "_token" ]
Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred.
[ "Token", "given", "by", "Transbank", "for", "payment", "initialization", "url", "." ]
python
train
28.5
azraq27/gini
gini/semantics.py
https://github.com/azraq27/gini/blob/3c2b5265d096d606b303bfe25ac9adb74b8cee14/gini/semantics.py#L117-L122
def match_concept(self,string): '''Find all matches in this :class:`Bottle` for ``string`` and return the best match''' matches = self.match_all_concepts(string) if len(matches)>0: return matches[0] return None
[ "def", "match_concept", "(", "self", ",", "string", ")", ":", "matches", "=", "self", ".", "match_all_concepts", "(", "string", ")", "if", "len", "(", "matches", ")", ">", "0", ":", "return", "matches", "[", "0", "]", "return", "None" ]
Find all matches in this :class:`Bottle` for ``string`` and return the best match
[ "Find", "all", "matches", "in", "this", ":", "class", ":", "Bottle", "for", "string", "and", "return", "the", "best", "match" ]
python
train
41.5
mozilla/socorrolib
socorrolib/lib/ver_tools.py
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ver_tools.py#L27-L53
def _memoizeArgsOnly (max_cache_size=1000): """Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. ...
[ "def", "_memoizeArgsOnly", "(", "max_cache_size", "=", "1000", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "fn", "(", "*", "args", ")", ":", "try", ":", "return", "fn", ".", "cache", "[", "args", "]", "except", "KeyError", ":", "if", "fn...
Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cache_size - the size to w...
[ "Python", "2", ".", "4", "compatible", "memoize", "decorator", ".", "It", "creates", "a", "cache", "that", "has", "a", "maximum", "size", ".", "If", "the", "cache", "exceeds", "the", "max", "it", "is", "thrown", "out", "and", "a", "new", "one", "made",...
python
train
32.333333
arve0/leicascanningtemplate
leicascanningtemplate/template.py
https://github.com/arve0/leicascanningtemplate/blob/053e075d3bed11e335b61ce048c47067b8e9e921/leicascanningtemplate/template.py#L370-L415
def write(self, filename=None): """Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename. """ if not filename: ...
[ "def", "write", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "filename", "# update time", "self", ".", "properties", ".", "CurrentDate", "=", "_current_time", "(", ")", "# set rubber band to...
Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename.
[ "Save", "template", "to", "xml", ".", "Before", "saving", "template", "will", "update", "date", "start", "position", "well", "positions", "and", "counts", "." ]
python
train
30.586957