repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
msikma/kanaconv
kanaconv/converter.py
https://github.com/msikma/kanaconv/blob/194f142e616ab5dd6d13a687b96b9f8abd1b4ea8/kanaconv/converter.py#L455-L463
def _set_digraph_b(self, char): ''' Sets the second part of a digraph. ''' self.has_digraph_b = True # Change the active vowel to the one provided by the second part # of the digraph. self.active_vowel_ro = di_b_lt[char][0] self.active_dgr_b_info = di_b_lt...
[ "def", "_set_digraph_b", "(", "self", ",", "char", ")", ":", "self", ".", "has_digraph_b", "=", "True", "# Change the active vowel to the one provided by the second part", "# of the digraph.", "self", ".", "active_vowel_ro", "=", "di_b_lt", "[", "char", "]", "[", "0",...
Sets the second part of a digraph.
[ "Sets", "the", "second", "part", "of", "a", "digraph", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/document.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L103-L120
def set(self, dct) : """Set the store using a dictionary""" # if not self.mustValidate : # self.store = dct # self.patchStore = dct # return for field, value in dct.items() : if field not in self.collection.arangoPrivates : if isin...
[ "def", "set", "(", "self", ",", "dct", ")", ":", "# if not self.mustValidate :", "# self.store = dct", "# self.patchStore = dct", "# return", "for", "field", ",", "value", "in", "dct", ".", "items", "(", ")", ":", "if", "field", "not", "in", "self", ...
Set the store using a dictionary
[ "Set", "the", "store", "using", "a", "dictionary" ]
python
train
chrisrink10/basilisp
src/basilisp/lang/runtime.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L1246-L1253
def _basilisp_fn(f): """Create a Basilisp function, setting meta and supplying a with_meta method implementation.""" assert not hasattr(f, "meta") f._basilisp_fn = True f.meta = None f.with_meta = partial(_fn_with_meta, f) return f
[ "def", "_basilisp_fn", "(", "f", ")", ":", "assert", "not", "hasattr", "(", "f", ",", "\"meta\"", ")", "f", ".", "_basilisp_fn", "=", "True", "f", ".", "meta", "=", "None", "f", ".", "with_meta", "=", "partial", "(", "_fn_with_meta", ",", "f", ")", ...
Create a Basilisp function, setting meta and supplying a with_meta method implementation.
[ "Create", "a", "Basilisp", "function", "setting", "meta", "and", "supplying", "a", "with_meta", "method", "implementation", "." ]
python
test
dshean/pygeotools
pygeotools/lib/malib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/malib.py#L1630-L1655
def get_stats_dict(a_in, full=True): """Compute and print statistics for input array """ d = {} a = checkma(a_in) d['count'] = a.count() thresh = 4E6 if not full and d['count'] > thresh: a = a.compressed() stride = int(np.around(a.size / thresh)) #a = np.ma.array(a[::...
[ "def", "get_stats_dict", "(", "a_in", ",", "full", "=", "True", ")", ":", "d", "=", "{", "}", "a", "=", "checkma", "(", "a_in", ")", "d", "[", "'count'", "]", "=", "a", ".", "count", "(", ")", "thresh", "=", "4E6", "if", "not", "full", "and", ...
Compute and print statistics for input array
[ "Compute", "and", "print", "statistics", "for", "input", "array" ]
python
train
lago-project/lago
lago/config.py
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/config.py#L122-L146
def load(self): """ Load all configurations from available resources, skip if empty: 1. :attr:`default`` dict passed to :func:`ConfigLoad.__init__`. 2. Custom paths as defined in :attr:`CONFS_PATH` in :class:`~lago.constants`. 3. XDG standard paths. ...
[ "def", "load", "(", "self", ")", ":", "configp", "=", "configparser", ".", "ConfigParser", "(", ")", "configp", ".", "read_dict", "(", "self", ".", "_defaults", ")", "for", "path", "in", "_get_configs_path", "(", ")", ":", "try", ":", "with", "open", "...
Load all configurations from available resources, skip if empty: 1. :attr:`default`` dict passed to :func:`ConfigLoad.__init__`. 2. Custom paths as defined in :attr:`CONFS_PATH` in :class:`~lago.constants`. 3. XDG standard paths. 4. Environment variables....
[ "Load", "all", "configurations", "from", "available", "resources", "skip", "if", "empty", ":" ]
python
train
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L93-L98
def _calculate_remaining_battery_percentage(self, voltage): """Calculate percentage.""" min_voltage = 2500 max_voltage = 3000 percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200 return min(200, percent)
[ "def", "_calculate_remaining_battery_percentage", "(", "self", ",", "voltage", ")", ":", "min_voltage", "=", "2500", "max_voltage", "=", "3000", "percent", "=", "(", "voltage", "-", "min_voltage", ")", "/", "(", "max_voltage", "-", "min_voltage", ")", "*", "20...
Calculate percentage.
[ "Calculate", "percentage", "." ]
python
train
horazont/aioxmpp
aioxmpp/pep/service.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L90-L146
def claim_pep_node(self, node_namespace, *, register_feature=True, notify=False): """ Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` ...
[ "def", "claim_pep_node", "(", "self", ",", "node_namespace", ",", "*", ",", "register_feature", "=", "True", ",", "notify", "=", "False", ")", ":", "if", "node_namespace", "in", "self", ".", "_pep_node_claims", ":", "raise", "RuntimeError", "(", "\"claiming al...
Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` as feature. :param notify: Whether to register the ``+notify`` feature to receive notification ...
[ "Claim", "node", "node_namespace", "." ]
python
train
Ouranosinc/xclim
xclim/indices.py
https://github.com/Ouranosinc/xclim/blob/2080d139188bd8de2aeca097a025c2d89d6e0e09/xclim/indices.py#L1971-L1998
def tx_min(tasmax, freq='YS'): r"""Lowest max temperature The minimum of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Min...
[ "def", "tx_min", "(", "tasmax", ",", "freq", "=", "'YS'", ")", ":", "return", "tasmax", ".", "resample", "(", "time", "=", "freq", ")", ".", "min", "(", "dim", "=", "'time'", ",", "keep_attrs", "=", "True", ")" ]
r"""Lowest max temperature The minimum of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Minimum of daily maximum temperature. ...
[ "r", "Lowest", "max", "temperature" ]
python
train
coldfix/udiskie
udiskie/udisks2.py
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L357-L366
def drive(self): """Get wrapper to the drive containing this device.""" if self.is_drive: return self cleartext = self.luks_cleartext_slave if cleartext: return cleartext.drive if self.is_block: return self._daemon[self._P.Block.Drive] ...
[ "def", "drive", "(", "self", ")", ":", "if", "self", ".", "is_drive", ":", "return", "self", "cleartext", "=", "self", ".", "luks_cleartext_slave", "if", "cleartext", ":", "return", "cleartext", ".", "drive", "if", "self", ".", "is_block", ":", "return", ...
Get wrapper to the drive containing this device.
[ "Get", "wrapper", "to", "the", "drive", "containing", "this", "device", "." ]
python
train
jciskey/pygraph
pygraph/functions/planarity/kocay_algorithm.py
https://github.com/jciskey/pygraph/blob/037bb2f32503fecb60d62921f9766d54109f15e2/pygraph/functions/planarity/kocay_algorithm.py#L403-L436
def __do_case_5_work(d_w, d_u, case_1, case_2, case_3, dfs_data): """Encapsulates the work that will be done for case 5 of __embed_frond, since it gets used in more than one place.""" # --We should only ever see u-cases 1 and 2 if case_3: # --We should never get here return False co...
[ "def", "__do_case_5_work", "(", "d_w", ",", "d_u", ",", "case_1", ",", "case_2", ",", "case_3", ",", "dfs_data", ")", ":", "# --We should only ever see u-cases 1 and 2", "if", "case_3", ":", "# --We should never get here", "return", "False", "comp_d_w", "=", "abs", ...
Encapsulates the work that will be done for case 5 of __embed_frond, since it gets used in more than one place.
[ "Encapsulates", "the", "work", "that", "will", "be", "done", "for", "case", "5", "of", "__embed_frond", "since", "it", "gets", "used", "in", "more", "than", "one", "place", "." ]
python
train
CalebBell/fluids
fluids/fittings.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L2579-L2629
def diffuser_conical_staged(Di1, Di2, DEs, ls, fd=None, method='Rennels'): r'''Returns loss coefficient for any series of staged conical pipe expansions as shown in [1]_. Five different formulas are used, depending on the angle and the ratio of diameters. This function calls diffuser_conical. Parameter...
[ "def", "diffuser_conical_staged", "(", "Di1", ",", "Di2", ",", "DEs", ",", "ls", ",", "fd", "=", "None", ",", "method", "=", "'Rennels'", ")", ":", "K", "=", "0", "DEs", ".", "insert", "(", "0", ",", "Di1", ")", "DEs", ".", "append", "(", "Di2", ...
r'''Returns loss coefficient for any series of staged conical pipe expansions as shown in [1]_. Five different formulas are used, depending on the angle and the ratio of diameters. This function calls diffuser_conical. Parameters ---------- Di1 : float Inside diameter of original pipe (smal...
[ "r", "Returns", "loss", "coefficient", "for", "any", "series", "of", "staged", "conical", "pipe", "expansions", "as", "shown", "in", "[", "1", "]", "_", ".", "Five", "different", "formulas", "are", "used", "depending", "on", "the", "angle", "and", "the", ...
python
train
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2328-L2341
def makedev(self, tarinfo, targetpath): """Make a character or block device called targetpath. """ if not hasattr(os, "mknod") or not hasattr(os, "makedev"): raise ExtractError("special devices not supported by system") mode = tarinfo.mode if tarinfo.isblk(): ...
[ "def", "makedev", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "\"mknod\"", ")", "or", "not", "hasattr", "(", "os", ",", "\"makedev\"", ")", ":", "raise", "ExtractError", "(", "\"special devices not supp...
Make a character or block device called targetpath.
[ "Make", "a", "character", "or", "block", "device", "called", "targetpath", "." ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L228-L242
def __get_pid_by_scanning(self): 'Internally used by get_pid().' dwProcessId = None dwThreadId = self.get_tid() with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot: te = win32.Thread32First(hSnapshot) while te is not None: if ...
[ "def", "__get_pid_by_scanning", "(", "self", ")", ":", "dwProcessId", "=", "None", "dwThreadId", "=", "self", ".", "get_tid", "(", ")", "with", "win32", ".", "CreateToolhelp32Snapshot", "(", "win32", ".", "TH32CS_SNAPTHREAD", ")", "as", "hSnapshot", ":", "te",...
Internally used by get_pid().
[ "Internally", "used", "by", "get_pid", "()", "." ]
python
train
Esri/ArcREST
src/arcresthelper/publishingtools.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/publishingtools.py#L2004-L2044
def publishApp(self, app_info, map_info=None, fsInfo=None): """Publishes apps to AGOL/Portal Args: app_info (list): A list of JSON configuration apps to publish. map_info (list): Defaults to ``None``. fsInfo (list): Defaults to ``None``. Returns: ...
[ "def", "publishApp", "(", "self", ",", "app_info", ",", "map_info", "=", "None", ",", "fsInfo", "=", "None", ")", ":", "if", "self", ".", "securityhandler", "is", "None", ":", "print", "(", "\"Security handler required\"", ")", "return", "appDet", "=", "No...
Publishes apps to AGOL/Portal Args: app_info (list): A list of JSON configuration apps to publish. map_info (list): Defaults to ``None``. fsInfo (list): Defaults to ``None``. Returns: dict: A dictionary of results objects.
[ "Publishes", "apps", "to", "AGOL", "/", "Portal", "Args", ":", "app_info", "(", "list", ")", ":", "A", "list", "of", "JSON", "configuration", "apps", "to", "publish", ".", "map_info", "(", "list", ")", ":", "Defaults", "to", "None", ".", "fsInfo", "(",...
python
train
pypa/pipenv
pipenv/vendor/ptyprocess/ptyprocess.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L564-L590
def sendcontrol(self, char): '''Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). ...
[ "def", "sendcontrol", "(", "self", ",", "char", ")", ":", "char", "=", "char", ".", "lower", "(", ")", "a", "=", "ord", "(", "char", ")", "if", "97", "<=", "a", "<=", "122", ":", "a", "=", "a", "-", "ord", "(", "'a'", ")", "+", "1", "byte",...
Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof().
[ "Helper", "method", "that", "wraps", "send", "()", "with", "mnemonic", "access", "for", "sending", "control", "character", "to", "the", "child", "(", "such", "as", "Ctrl", "-", "C", "or", "Ctrl", "-", "D", ")", ".", "For", "example", "to", "send", "Ctr...
python
train
ironfroggy/django-better-cache
bettercache/objects.py
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/objects.py#L163-L177
def from_miss(self, **kwargs): """Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(us...
[ "def", "from_miss", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "type", "(", "self", ")", ".", "Missing", "(", "type", "(", "self", ")", "(", "*", "*", "kwargs", ")", ".", "key", "(", ")", ")" ]
Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the database to populate the cache, ... def from_miss(self, username): user = User.objects.get(username=username) self.emai...
[ "Called", "to", "initialize", "an", "instance", "when", "it", "is", "not", "found", "in", "the", "cache", "." ]
python
train
boriel/zxbasic
arch/zx48k/backend/__32bit.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__32bit.py#L439-L457
def _gtu32(ins): """ Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 32 bit unsigned version """ op1, op2 = tuple(ins.quad[2:]) rev = op1[0] != 't' and not is_int(op1) and op2[0] == 't...
[ "def", "_gtu32", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "rev", "=", "op1", "[", "0", "]", "!=", "'t'", "and", "not", "is_int", "(", "op1", ")", "and", "op2", "[", "0", "]", ...
Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 32 bit unsigned version
[ "Compares", "&", "pops", "top", "2", "operands", "out", "of", "the", "stack", "and", "checks", "if", "the", "1st", "operand", ">", "2nd", "operand", "(", "top", "of", "the", "stack", ")", ".", "Pushes", "0", "if", "False", "1", "if", "True", "." ]
python
train
robertmartin8/PyPortfolioOpt
pypfopt/cla.py
https://github.com/robertmartin8/PyPortfolioOpt/blob/dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc/pypfopt/cla.py#L347-L363
def efficient_frontier(self, points): """Get the efficient frontier""" mu, sigma, weights = [], [], [] # remove the 1, to avoid duplications a = np.linspace(0, 1, points / len(self.w))[:-1] b = list(range(len(self.w) - 1)) for i in b: w0, w1 = self.w[i], self....
[ "def", "efficient_frontier", "(", "self", ",", "points", ")", ":", "mu", ",", "sigma", ",", "weights", "=", "[", "]", ",", "[", "]", ",", "[", "]", "# remove the 1, to avoid duplications", "a", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "po...
Get the efficient frontier
[ "Get", "the", "efficient", "frontier" ]
python
train
loli/medpy
medpy/metric/binary.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/binary.py#L723-L775
def obj_assd(result, reference, voxelspacing=None, connectivity=1): """ Average symmetric surface distance. Computes the average symmetric surface distance (ASSD) between the binary objects in two images. Parameters ---------- result : array_like Input data containing objec...
[ "def", "obj_assd", "(", "result", ",", "reference", ",", "voxelspacing", "=", "None", ",", "connectivity", "=", "1", ")", ":", "assd", "=", "numpy", ".", "mean", "(", "(", "obj_asd", "(", "result", ",", "reference", ",", "voxelspacing", ",", "connectivit...
Average symmetric surface distance. Computes the average symmetric surface distance (ASSD) between the binary objects in two images. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where ...
[ "Average", "symmetric", "surface", "distance", ".", "Computes", "the", "average", "symmetric", "surface", "distance", "(", "ASSD", ")", "between", "the", "binary", "objects", "in", "two", "images", ".", "Parameters", "----------", "result", ":", "array_like", "I...
python
train
MJL85/natlas
natlas/mac.py
https://github.com/MJL85/natlas/blob/5e7ae3cc7b5dd7ad884fa2b8b93bbdd9275474c4/natlas/mac.py#L64-L97
def get_macs(self, ip, display_progress): ''' Return array of MAC addresses from single node at IP ''' if (ip == '0.0.0.0'): return None ret_macs = [] snmpobj = natlas_snmp(ip) # find valid credentials for this node if (snmpobj.get_cred(self....
[ "def", "get_macs", "(", "self", ",", "ip", ",", "display_progress", ")", ":", "if", "(", "ip", "==", "'0.0.0.0'", ")", ":", "return", "None", "ret_macs", "=", "[", "]", "snmpobj", "=", "natlas_snmp", "(", "ip", ")", "# find valid credentials for this node", ...
Return array of MAC addresses from single node at IP
[ "Return", "array", "of", "MAC", "addresses", "from", "single", "node", "at", "IP" ]
python
train
CxAalto/gtfspy
gtfspy/routing/node_profile_simple.py
https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_simple.py#L76-L97
def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin): """ Get the earliest arrival time at the target, given a departure time. Parameters ---------- dep_time : float, int time in unix seconds transfer_margin: float, int tr...
[ "def", "evaluate_earliest_arrival_time_at_target", "(", "self", ",", "dep_time", ",", "transfer_margin", ")", ":", "minimum", "=", "dep_time", "+", "self", ".", "_walk_to_target_duration", "dep_time_plus_transfer_margin", "=", "dep_time", "+", "transfer_margin", "for", ...
Get the earliest arrival time at the target, given a departure time. Parameters ---------- dep_time : float, int time in unix seconds transfer_margin: float, int transfer margin in seconds Returns ------- arrival_time : float ...
[ "Get", "the", "earliest", "arrival", "time", "at", "the", "target", "given", "a", "departure", "time", "." ]
python
valid
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L1716-L1745
def _update_zipimporter_cache(normalized_path, cache, updater=None): """ Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry ...
[ "def", "_update_zipimporter_cache", "(", "normalized_path", ",", "cache", ",", "updater", "=", "None", ")", ":", "for", "p", "in", "_collect_zipimporter_cache_entries", "(", "normalized_path", ",", "cache", ")", ":", "# N.B. pypy's custom zipimport._zip_directory_cache im...
Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry key and the original entry (after already removing the entry from the cache),...
[ "Update", "zipimporter", "cache", "data", "for", "a", "given", "normalized", "path", "." ]
python
test
eleme/meepo
meepo/apps/eventsourcing/event_store.py
https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/apps/eventsourcing/event_store.py#L190-L210
def replay(self, event, ts=0, end_ts=None, with_ts=False): """Replay events based on timestamp. If you split namespace with ts, the replay will only return events within the same namespace. :param event: event name :param ts: replay events after ts, default from 0. :par...
[ "def", "replay", "(", "self", ",", "event", ",", "ts", "=", "0", ",", "end_ts", "=", "None", ",", "with_ts", "=", "False", ")", ":", "key", "=", "self", ".", "_keygen", "(", "event", ",", "ts", ")", "end_ts", "=", "end_ts", "if", "end_ts", "else"...
Replay events based on timestamp. If you split namespace with ts, the replay will only return events within the same namespace. :param event: event name :param ts: replay events after ts, default from 0. :param end_ts: replay events to ts, default to "+inf". :param with...
[ "Replay", "events", "based", "on", "timestamp", "." ]
python
train
gazpachoking/jsonref
jsonref.py
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/jsonref.py#L324-L345
def load(fp, base_uri="", loader=None, jsonschema=False, load_on_repr=True, **kwargs): """ Drop in replacement for :func:`json.load`, where JSON references are proxied to their referent data. :param fp: File-like object containing JSON document :param kwargs: This function takes any of the keyword ...
[ "def", "load", "(", "fp", ",", "base_uri", "=", "\"\"", ",", "loader", "=", "None", ",", "jsonschema", "=", "False", ",", "load_on_repr", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "loader", "is", "None", ":", "loader", "=", "functools", ...
Drop in replacement for :func:`json.load`, where JSON references are proxied to their referent data. :param fp: File-like object containing JSON document :param kwargs: This function takes any of the keyword arguments from :meth:`JsonRef.replace_refs`. Any other keyword arguments will be passed to ...
[ "Drop", "in", "replacement", "for", ":", "func", ":", "json", ".", "load", "where", "JSON", "references", "are", "proxied", "to", "their", "referent", "data", "." ]
python
train
noahgoldman/adbpy
adbpy/socket.py
https://github.com/noahgoldman/adbpy/blob/ecbff8a8f151852b5c36847dc812582a8674a503/adbpy/socket.py#L102-L131
def receive_until_end(self, timeout=None): """ Reads and blocks until the socket closes Used for the "shell" command, where STDOUT and STDERR are just redirected to the terminal with no length """ if self.receive_fixed_length(4) != "OKAY": raise SocketError("...
[ "def", "receive_until_end", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "receive_fixed_length", "(", "4", ")", "!=", "\"OKAY\"", ":", "raise", "SocketError", "(", "\"Socket communication failed: \"", "\"the server did not return a valid resp...
Reads and blocks until the socket closes Used for the "shell" command, where STDOUT and STDERR are just redirected to the terminal with no length
[ "Reads", "and", "blocks", "until", "the", "socket", "closes" ]
python
train
google/apitools
apitools/base/protorpclite/util.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/protorpclite/util.py#L55-L155
def positional(max_positional_args): """A decorator that declares only the first N arguments may be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... ...
[ "def", "positional", "(", "max_positional_args", ")", ":", "def", "positional_decorator", "(", "wrapped", ")", ":", "\"\"\"Creates a function wraper to enforce number of arguments.\"\"\"", "@", "functools", ".", "wraps", "(", "wrapped", ")", "def", "positional_wrapper", "...
A decorator that declares only the first N arguments may be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after * must be a k...
[ "A", "decorator", "that", "declares", "only", "the", "first", "N", "arguments", "may", "be", "positional", "." ]
python
train
EpistasisLab/tpot
tpot/builtins/stacking_estimator.py
https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/builtins/stacking_estimator.py#L70-L92
def transform(self, X): """Transform data by adding two synthetic feature(s). Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "check_array", "(", "X", ")", "X_transformed", "=", "np", ".", "copy", "(", "X", ")", "# add class probabilities as a synthetic feature", "if", "issubclass", "(", "self", ".", "estimator", ".", ...
Transform data by adding two synthetic feature(s). Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_transformed: array-like, s...
[ "Transform", "data", "by", "adding", "two", "synthetic", "feature", "(", "s", ")", "." ]
python
train
ace0/pyrelic
pyrelic/vpopProfile.py
https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/vpopProfile.py#L52-L72
def proveGt(x,tTilde,kw,y): """ Generate a zero-knowledge proof that DL(g^kw) == DL(e(x,t)^kw) where g,e(..) \in Gt. @return pi = (p,c,u) """ # Verify types assertType(x, G1Element) assertType(tTilde, G2Element) # Compute the proof. beta = pair(x,tTilde) g = generatorGt() ...
[ "def", "proveGt", "(", "x", ",", "tTilde", ",", "kw", ",", "y", ")", ":", "# Verify types", "assertType", "(", "x", ",", "G1Element", ")", "assertType", "(", "tTilde", ",", "G2Element", ")", "# Compute the proof.", "beta", "=", "pair", "(", "x", ",", "...
Generate a zero-knowledge proof that DL(g^kw) == DL(e(x,t)^kw) where g,e(..) \in Gt. @return pi = (p,c,u)
[ "Generate", "a", "zero", "-", "knowledge", "proof", "that", "DL", "(", "g^kw", ")", "==", "DL", "(", "e", "(", "x", "t", ")", "^kw", ")", "where", "g", "e", "(", "..", ")", "\\", "in", "Gt", "." ]
python
train
spry-group/python-vultr
vultr/v1_dns.py
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/vultr/v1_dns.py#L38-L46
def delete_domain(self, domain, params=None): ''' /v1/dns/delete_domain POST - account Delete a domain name (and all associated records) Link: https://www.vultr.com/api/#dns_delete_domain ''' params = update_params(params, {'domain': domain}) return self.request(...
[ "def", "delete_domain", "(", "self", ",", "domain", ",", "params", "=", "None", ")", ":", "params", "=", "update_params", "(", "params", ",", "{", "'domain'", ":", "domain", "}", ")", "return", "self", ".", "request", "(", "'/v1/dns/delete_domain'", ",", ...
/v1/dns/delete_domain POST - account Delete a domain name (and all associated records) Link: https://www.vultr.com/api/#dns_delete_domain
[ "/", "v1", "/", "dns", "/", "delete_domain", "POST", "-", "account", "Delete", "a", "domain", "name", "(", "and", "all", "associated", "records", ")" ]
python
train
nesaro/pydsl
pydsl/file/python.py
https://github.com/nesaro/pydsl/blob/00b4fffd72036b80335e1a44a888fac57917ab41/pydsl/file/python.py#L34-L63
def load_python_file(moduleobject): """ Try to create an indexable instance from a module""" if isinstance(moduleobject, str): moduleobject = load_module(moduleobject) if not hasattr(moduleobject, "iclass"): raise KeyError("Element" + str(moduleobject)) iclass = getattr(moduleobject, "ic...
[ "def", "load_python_file", "(", "moduleobject", ")", ":", "if", "isinstance", "(", "moduleobject", ",", "str", ")", ":", "moduleobject", "=", "load_module", "(", "moduleobject", ")", "if", "not", "hasattr", "(", "moduleobject", ",", "\"iclass\"", ")", ":", "...
Try to create an indexable instance from a module
[ "Try", "to", "create", "an", "indexable", "instance", "from", "a", "module" ]
python
train
base4sistemas/satcfe
satcfe/clientesathub.py
https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/clientesathub.py#L271-L284
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSA...
[ "def", "trocar_codigo_de_ativacao", "(", "self", ",", "novo_codigo_ativacao", ",", "opcao", "=", "constantes", ".", "CODIGO_ATIVACAO_REGULAR", ",", "codigo_emergencia", "=", "None", ")", ":", "resp", "=", "self", ".", "_http_post", "(", "'trocarcodigodeativacao'", "...
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
[ "Sobrepõe", ":", "meth", ":", "~satcfe", ".", "base", ".", "FuncoesSAT", ".", "trocar_codigo_de_ativacao", "." ]
python
train
nickoala/telepot
telepot/helper.py
https://github.com/nickoala/telepot/blob/3792fde251d0f1d5a6ca16c8ad1a71f89360c41d/telepot/helper.py#L77-L88
def wait(self): """ Block until a matched message appears. """ if not self._patterns: raise RuntimeError('Listener has nothing to capture') while 1: msg = self._queue.get(block=True) if any(map(lambda p: filtering.match_all(msg, p), self._pat...
[ "def", "wait", "(", "self", ")", ":", "if", "not", "self", ".", "_patterns", ":", "raise", "RuntimeError", "(", "'Listener has nothing to capture'", ")", "while", "1", ":", "msg", "=", "self", ".", "_queue", ".", "get", "(", "block", "=", "True", ")", ...
Block until a matched message appears.
[ "Block", "until", "a", "matched", "message", "appears", "." ]
python
train
NICTA/revrand
revrand/basis_functions.py
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/basis_functions.py#L1599-L1627
def transform(self, X, *params): """ Return the basis function applied to X. I.e. Phi(X, params), where params can also optionally be used and learned. Parameters ---------- X : ndarray (N, d) array of observations where N is the number of samples, a...
[ "def", "transform", "(", "self", ",", "X", ",", "*", "params", ")", ":", "Phi", "=", "[", "]", "args", "=", "list", "(", "params", ")", "for", "base", "in", "self", ".", "bases", ":", "phi", ",", "args", "=", "base", ".", "_transform_popargs", "(...
Return the basis function applied to X. I.e. Phi(X, params), where params can also optionally be used and learned. Parameters ---------- X : ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. ...
[ "Return", "the", "basis", "function", "applied", "to", "X", "." ]
python
train
manns/pyspread
pyspread/src/lib/vlc.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L6882-L6890
def debug_callback(event, *args, **kwds): '''Example callback, useful for debugging. ''' l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l))
[ "def", "debug_callback", "(", "event", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "l", "=", "[", "'event %s'", "%", "(", "event", ".", "type", ",", ")", "]", "if", "args", ":", "l", ".", "extend", "(", "map", "(", "str", ",", "args", ...
Example callback, useful for debugging.
[ "Example", "callback", "useful", "for", "debugging", "." ]
python
train
biolink/ontobio
ontobio/golr/golr_query.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_query.py#L1263-L1375
def exec(self, **kwargs): """ Execute solr query Result object is a dict with the following keys: - raw - associations : list - compact_associations : list - facet_counts - facet_pivot """ params = self.solr_params() loggin...
[ "def", "exec", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "self", ".", "solr_params", "(", ")", "logging", ".", "info", "(", "\"PARAMS=\"", "+", "str", "(", "params", ")", ")", "results", "=", "self", ".", "solr", ".", "search",...
Execute solr query Result object is a dict with the following keys: - raw - associations : list - compact_associations : list - facet_counts - facet_pivot
[ "Execute", "solr", "query" ]
python
train
sibirrer/lenstronomy
lenstronomy/SimulationAPI/observation_api.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/SimulationAPI/observation_api.py#L140-L151
def scaled_exposure_time(self): """ scaled "effective" exposure time of IID counts. This can be used by lenstronomy to estimate the Poisson errors keeping the assumption that the counts are IIDs (even if they are not). :return: scaled exposure time """ if self._data_coun...
[ "def", "scaled_exposure_time", "(", "self", ")", ":", "if", "self", ".", "_data_count_unit", "==", "'ADU'", ":", "exp_time", "=", "self", ".", "ccd_gain", "*", "self", ".", "exposure_time", "else", ":", "exp_time", "=", "self", ".", "exposure_time", "return"...
scaled "effective" exposure time of IID counts. This can be used by lenstronomy to estimate the Poisson errors keeping the assumption that the counts are IIDs (even if they are not). :return: scaled exposure time
[ "scaled", "effective", "exposure", "time", "of", "IID", "counts", ".", "This", "can", "be", "used", "by", "lenstronomy", "to", "estimate", "the", "Poisson", "errors", "keeping", "the", "assumption", "that", "the", "counts", "are", "IIDs", "(", "even", "if", ...
python
train
iotile/coretools
iotilecore/iotile/core/scripts/virtualdev_script.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L49-L162
def main(argv=None, loop=SharedLoop): """Serve access to a virtual IOTile device using a virtual iotile interface.""" if argv is None: argv = sys.argv[1:] list_parser = argparse.ArgumentParser(add_help=False) list_parser.add_argument('-l', '--list', action='store_true', help="List all known in...
[ "def", "main", "(", "argv", "=", "None", ",", "loop", "=", "SharedLoop", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "list_parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "F...
Serve access to a virtual IOTile device using a virtual iotile interface.
[ "Serve", "access", "to", "a", "virtual", "IOTile", "device", "using", "a", "virtual", "iotile", "interface", "." ]
python
train
gagneurlab/concise
concise/hyopt.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L354-L389
def eval_model(model, test, add_eval_metrics={}): """Evaluate model's performance on the test-set. # Arguments model: Keras model test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`. add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of f...
[ "def", "eval_model", "(", "model", ",", "test", ",", "add_eval_metrics", "=", "{", "}", ")", ":", "# evaluate the model", "logger", ".", "info", "(", "\"Evaluate...\"", ")", "# - model_metrics", "model_metrics_values", "=", "model", ".", "evaluate", "(", "test",...
Evaluate model's performance on the test-set. # Arguments model: Keras model test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`. add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of functions accepting arguments: `y_true`, `y_predicted`...
[ "Evaluate", "model", "s", "performance", "on", "the", "test", "-", "set", "." ]
python
train
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L375-L454
def service_configuration_check(config): """Perform a sanity check against options for each service check. Arguments: config (obj): A configparser object which holds our configuration. Returns: None if all sanity checks are successfully passed otherwise raises a ValueError exceptio...
[ "def", "service_configuration_check", "(", "config", ")", ":", "ipv4_enabled", "=", "config", ".", "getboolean", "(", "'daemon'", ",", "'ipv4'", ")", "ipv6_enabled", "=", "config", ".", "getboolean", "(", "'daemon'", ",", "'ipv6'", ")", "services", "=", "confi...
Perform a sanity check against options for each service check. Arguments: config (obj): A configparser object which holds our configuration. Returns: None if all sanity checks are successfully passed otherwise raises a ValueError exception.
[ "Perform", "a", "sanity", "check", "against", "options", "for", "each", "service", "check", "." ]
python
train
RockFeng0/rtsf-web
webuidriver/actions.py
https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L637-L643
def Ctrl(cls, key): """ 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.CONTROL, key)
[ "def", "Ctrl", "(", "cls", ",", "key", ")", ":", "element", "=", "cls", ".", "_element", "(", ")", "element", ".", "send_keys", "(", "Keys", ".", "CONTROL", ",", "key", ")" ]
在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X'
[ "在指定元素上执行ctrl组合键事件" ]
python
train
saltstack/salt
salt/cloud/clouds/qingcloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/qingcloud.py#L204-L232
def avail_locations(call=None): ''' Return a dict of all available locations on the provider with relevant data. CLI Examples: .. code-block:: bash salt-cloud --list-locations my-qingcloud ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "params", "=", "{",...
Return a dict of all available locations on the provider with relevant data. CLI Examples: .. code-block:: bash salt-cloud --list-locations my-qingcloud
[ "Return", "a", "dict", "of", "all", "available", "locations", "on", "the", "provider", "with", "relevant", "data", "." ]
python
train
idmillington/layout
layout/managers/grid.py
https://github.com/idmillington/layout/blob/c452d1d7a74c9a74f7639c1b49e2a41c4e354bb5/layout/managers/grid.py#L143-L218
def render(self, rect, data): """Draws the cells in grid.""" size = self.get_minimum_size(data) # Find how much extra space we have. extra_width = rect.w - size.x extra_height = rect.h - size.y # Distribute the extra space into the correct rows and columns. if s...
[ "def", "render", "(", "self", ",", "rect", ",", "data", ")", ":", "size", "=", "self", ".", "get_minimum_size", "(", "data", ")", "# Find how much extra space we have.", "extra_width", "=", "rect", ".", "w", "-", "size", ".", "x", "extra_height", "=", "rec...
Draws the cells in grid.
[ "Draws", "the", "cells", "in", "grid", "." ]
python
train
postmanlabs/httpbin
httpbin/filters.py
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/filters.py#L71-L92
def deflate(f, *args, **kwargs): """Deflate Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflater = zlib.compressobj() deflated_data = deflater.compress(content) deflated_data += deflater.flu...
[ "def", "deflate", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "data", ",", "Response", ")", ":", "content", "=", "data", ".", "data", ...
Deflate Flask Response Decorator.
[ "Deflate", "Flask", "Response", "Decorator", "." ]
python
train
lemieuxl/pyGenClean
pyGenClean/DupSNPs/duplicated_snps.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/DupSNPs/duplicated_snps.py#L181-L228
def createFinalTPEDandTFAM(tped, toReadPrefix, prefix, snpToRemove): """Creates the final TPED and TFAM. :param tped: a representation of the ``tped`` of duplicated markers. :param toReadPrefix: the prefix of the unique files. :param prefix: the prefix of the output files. :param snpToRemove: the m...
[ "def", "createFinalTPEDandTFAM", "(", "tped", ",", "toReadPrefix", ",", "prefix", ",", "snpToRemove", ")", ":", "# First, copying the tfam", "try", ":", "shutil", ".", "copy", "(", "toReadPrefix", "+", "\".tfam\"", ",", "prefix", "+", "\".final.tfam\"", ")", "ex...
Creates the final TPED and TFAM. :param tped: a representation of the ``tped`` of duplicated markers. :param toReadPrefix: the prefix of the unique files. :param prefix: the prefix of the output files. :param snpToRemove: the markers to remove. :type tped: numpy.array :type toReadPrefix: str ...
[ "Creates", "the", "final", "TPED", "and", "TFAM", "." ]
python
train
nocarryr/python-dispatch
pydispatch/dispatch.py
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L236-L251
def emit(self, name, *args, **kwargs): """Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :clas...
[ "def", "emit", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "e", "=", "self", ".", "__property_events", ".", "get", "(", "name", ")", "if", "e", "is", "None", ":", "e", "=", "self", ".", "__events", "[", "name"...
Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :class:`Event` to dispatch *args (Optional)...
[ "Dispatches", "an", "event", "to", "any", "subscribed", "listeners" ]
python
train
xu2243051/easyui-menu
easyui/mixins/view_mixins.py
https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/mixins/view_mixins.py#L21-L27
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIDatagridView, self).get_template_names() names.append('easyui/datagrid.html') return names
[ "def", "get_template_names", "(", "self", ")", ":", "names", "=", "super", "(", "EasyUIDatagridView", ",", "self", ")", ".", "get_template_names", "(", ")", "names", ".", "append", "(", "'easyui/datagrid.html'", ")", "return", "names" ]
datagrid的默认模板
[ "datagrid的默认模板" ]
python
valid
yamcs/yamcs-python
yamcs-client/examples/archive_retrieval.py
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/archive_retrieval.py#L38-L47
def iterate_specific_event_range(): """Count the number of events in a specific range.""" now = datetime.utcnow() start = now - timedelta(hours=1) total = 0 for event in archive.list_events(start=start, stop=now): total += 1 # print(event) print('Found', total, 'events in range'...
[ "def", "iterate_specific_event_range", "(", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "start", "=", "now", "-", "timedelta", "(", "hours", "=", "1", ")", "total", "=", "0", "for", "event", "in", "archive", ".", "list_events", "(", "sta...
Count the number of events in a specific range.
[ "Count", "the", "number", "of", "events", "in", "a", "specific", "range", "." ]
python
train
DataMedSci/mcpartools
mcpartools/mcengine/shieldhit.py
https://github.com/DataMedSci/mcpartools/blob/84f869094d05bf70f09e8aaeca671ddaa1c56ec4/mcpartools/mcengine/shieldhit.py#L225-L244
def _rewrite_paths_in_file(config_file, paths_to_replace): """ Rewrite paths in config files to match convention job_xxxx/symlink Requires path to run_xxxx/input/config_file and a list of paths_to_replace """ lines = [] # make a copy of config import shutil ...
[ "def", "_rewrite_paths_in_file", "(", "config_file", ",", "paths_to_replace", ")", ":", "lines", "=", "[", "]", "# make a copy of config", "import", "shutil", "shutil", ".", "copyfile", "(", "config_file", ",", "str", "(", "config_file", "+", "'_original'", ")", ...
Rewrite paths in config files to match convention job_xxxx/symlink Requires path to run_xxxx/input/config_file and a list of paths_to_replace
[ "Rewrite", "paths", "in", "config", "files", "to", "match", "convention", "job_xxxx", "/", "symlink", "Requires", "path", "to", "run_xxxx", "/", "input", "/", "config_file", "and", "a", "list", "of", "paths_to_replace" ]
python
train
flo-compbio/goparser
goparser/parser.py
https://github.com/flo-compbio/goparser/blob/5e27d7d04a26a70a1d9dc113357041abff72be3f/goparser/parser.py#L246-L286
def get_term_by_name(self, name): """Get the GO term with the given GO term name. If the given name is not associated with any GO term, the function will search for it among synonyms. Parameters ---------- name: str The name of the GO term. Returns ...
[ "def", "get_term_by_name", "(", "self", ",", "name", ")", ":", "term", "=", "None", "func_name", "=", "'get_term_by_name'", "try", ":", "term", "=", "self", ".", "terms", "[", "self", ".", "_name2id", "[", "name", "]", "]", "except", "KeyError", ":", "...
Get the GO term with the given GO term name. If the given name is not associated with any GO term, the function will search for it among synonyms. Parameters ---------- name: str The name of the GO term. Returns ------- GOTerm Th...
[ "Get", "the", "GO", "term", "with", "the", "given", "GO", "term", "name", "." ]
python
train
ulf1/oxyba
oxyba/leland94.py
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/leland94.py#L2-L225
def leland94(V, s, r, a, t, C=None, d=None, PosEq=False): """Leland94 Capital Structure model, Corporate Bond valuation model Parameters: ----------- V : float Asset Value of the unlevered firm s : float Volatility s of the asset value V of the unlevered firm r : float ...
[ "def", "leland94", "(", "V", ",", "s", ",", "r", ",", "a", ",", "t", ",", "C", "=", "None", ",", "d", "=", "None", ",", "PosEq", "=", "False", ")", ":", "# subfunction for", "def", "netcashpayout_by_dividend", "(", "r", ",", "d", ",", "s", ")", ...
Leland94 Capital Structure model, Corporate Bond valuation model Parameters: ----------- V : float Asset Value of the unlevered firm s : float Volatility s of the asset value V of the unlevered firm r : float Risk free rate a : float Bankruptcy cost t : f...
[ "Leland94", "Capital", "Structure", "model", "Corporate", "Bond", "valuation", "model" ]
python
train
mozilla/taar
taar/flask_app.py
https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/flask_app.py#L41-L86
def flaskrun(app, default_host="127.0.0.1", default_port="8000"): """ Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app. """ # Set up the command-line options parser = optparse.OptionParser() parser.add_option( "-H", "--host", h...
[ "def", "flaskrun", "(", "app", ",", "default_host", "=", "\"127.0.0.1\"", ",", "default_port", "=", "\"8000\"", ")", ":", "# Set up the command-line options", "parser", "=", "optparse", ".", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "\"-H\"", "...
Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app.
[ "Takes", "a", "flask", ".", "Flask", "instance", "and", "runs", "it", ".", "Parses", "command", "-", "line", "flags", "to", "configure", "the", "app", "." ]
python
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/gui/windows_and_widgets/widgets.py
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/widgets.py#L416-L421
def sizeHint(self): """ gives qt a starting point for widget size during window resizing """ w, h = self.get_width_height() return QtCore.QSize(w, h)
[ "def", "sizeHint", "(", "self", ")", ":", "w", ",", "h", "=", "self", ".", "get_width_height", "(", ")", "return", "QtCore", ".", "QSize", "(", "w", ",", "h", ")" ]
gives qt a starting point for widget size during window resizing
[ "gives", "qt", "a", "starting", "point", "for", "widget", "size", "during", "window", "resizing" ]
python
train
shad7/tvrenamer
tvrenamer/core/formatter.py
https://github.com/shad7/tvrenamer/blob/7fb59cb02669357e73b7acb92dcb6d74fdff4654/tvrenamer/core/formatter.py#L153-L239
def _make_valid_filename(value): """Takes a string and makes it into a valid filename. replaces accented characters with ASCII equivalent, and removes characters that cannot be converted sensibly to ASCII. additional characters that will removed. This will not touch the extension separator: ...
[ "def", "_make_valid_filename", "(", "value", ")", ":", "sysname", "=", "platform", ".", "system", "(", ")", "# If the filename starts with a . prepend it with an underscore, so it", "# doesn't become hidden.", "# This is done before calling splitext to handle filename of \".\", as", ...
Takes a string and makes it into a valid filename. replaces accented characters with ASCII equivalent, and removes characters that cannot be converted sensibly to ASCII. additional characters that will removed. This will not touch the extension separator: >>> _make_valid_filename("T.est.avi")...
[ "Takes", "a", "string", "and", "makes", "it", "into", "a", "valid", "filename", "." ]
python
train
msztolcman/versionner
versionner/commands/files_management.py
https://github.com/msztolcman/versionner/blob/78fca02859e3e3eb71c9eb7ea230758944177c54/versionner/commands/files_management.py#L14-L76
def update_project_files(cfg, proj_version): """ Update version string in project files :rtype : dict :param cfg:project configuration :param proj_version:current version :return:dict :raise ValueError: """ counters = {'files': 0, 'changes': 0} for project_file in cfg.files: ...
[ "def", "update_project_files", "(", "cfg", ",", "proj_version", ")", ":", "counters", "=", "{", "'files'", ":", "0", ",", "'changes'", ":", "0", "}", "for", "project_file", "in", "cfg", ".", "files", ":", "if", "not", "project_file", ".", "file", ".", ...
Update version string in project files :rtype : dict :param cfg:project configuration :param proj_version:current version :return:dict :raise ValueError:
[ "Update", "version", "string", "in", "project", "files" ]
python
train
cloudnull/turbolift
turbolift/clouderator/actions.py
https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/clouderator/actions.py#L346-L384
def _list_getter(self, uri, headers, last_obj=None, spr=False): """Get a list of all objects in a container. :param uri: :param headers: :return list: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` """ # Quote the...
[ "def", "_list_getter", "(", "self", ",", "uri", ",", "headers", ",", "last_obj", "=", "None", ",", "spr", "=", "False", ")", ":", "# Quote the file path.", "base_path", "=", "marked_path", "=", "(", "'%s?limit=10000&format=json'", "%", "uri", ".", "path", ")...
Get a list of all objects in a container. :param uri: :param headers: :return list: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol``
[ "Get", "a", "list", "of", "all", "objects", "in", "a", "container", "." ]
python
train
pysal/giddy
giddy/markov.py
https://github.com/pysal/giddy/blob/13fae6c18933614be78e91a6b5060693bea33a04/giddy/markov.py#L1212-L1333
def spillover(self, quadrant=1, neighbors_on=False): """ Detect spillover locations for diffusion in LISA Markov. Parameters ---------- quadrant : int which quadrant in the scatterplot should form the core of a cluster. n...
[ "def", "spillover", "(", "self", ",", "quadrant", "=", "1", ",", "neighbors_on", "=", "False", ")", ":", "n", ",", "k", "=", "self", ".", "q", ".", "shape", "if", "self", ".", "permutations", ":", "spill_over", "=", "np", ".", "zeros", "(", "(", ...
Detect spillover locations for diffusion in LISA Markov. Parameters ---------- quadrant : int which quadrant in the scatterplot should form the core of a cluster. neighbors_on : binary If false, then only the 1st o...
[ "Detect", "spillover", "locations", "for", "diffusion", "in", "LISA", "Markov", "." ]
python
train
senaite/senaite.core
bika/lims/browser/publish/emailview.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/publish/emailview.py#L605-L645
def get_recipients(self, ar): """Return the AR recipients in the same format like the AR Report expects in the records field `Recipients` """ plone_utils = api.get_tool("plone_utils") def is_email(email): if not plone_utils.validateSingleEmailAddress(email): ...
[ "def", "get_recipients", "(", "self", ",", "ar", ")", ":", "plone_utils", "=", "api", ".", "get_tool", "(", "\"plone_utils\"", ")", "def", "is_email", "(", "email", ")", ":", "if", "not", "plone_utils", ".", "validateSingleEmailAddress", "(", "email", ")", ...
Return the AR recipients in the same format like the AR Report expects in the records field `Recipients`
[ "Return", "the", "AR", "recipients", "in", "the", "same", "format", "like", "the", "AR", "Report", "expects", "in", "the", "records", "field", "Recipients" ]
python
train
SpectoLabs/hoverpy
hoverpy/hp.py
https://github.com/SpectoLabs/hoverpy/blob/e153ec57f80634019d827d378f184c01fedc5a0e/hoverpy/hp.py#L292-L304
def __writepid(self, pid): """ HoverFly fails to launch if it's already running on the same ports. So we have to keep track of them using temp files with the proxy port and admin port, containing the processe's PID. """ import tempfile d = tempfile.gettem...
[ "def", "__writepid", "(", "self", ",", "pid", ")", ":", "import", "tempfile", "d", "=", "tempfile", ".", "gettempdir", "(", ")", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "\"hoverpy.%i.%i\"", "%", "(", "self", ".", "_proxyPort", ","...
HoverFly fails to launch if it's already running on the same ports. So we have to keep track of them using temp files with the proxy port and admin port, containing the processe's PID.
[ "HoverFly", "fails", "to", "launch", "if", "it", "s", "already", "running", "on", "the", "same", "ports", ".", "So", "we", "have", "to", "keep", "track", "of", "them", "using", "temp", "files", "with", "the", "proxy", "port", "and", "admin", "port", "c...
python
train
kimvais/ike
ike/protocol.py
https://github.com/kimvais/ike/blob/4a5622c878a43a3d3cc19c54aa7cc7be29318eae/ike/protocol.py#L130-L173
def init_recv(self): """ Parses the IKE_INIT response packet received from Responder. Assigns the correct values of rSPI and Nr Calculates Diffie-Hellman exchange and assigns all keys to self. """ assert len(self.packets) == 2 packet = self.packets[-1] f...
[ "def", "init_recv", "(", "self", ")", ":", "assert", "len", "(", "self", ".", "packets", ")", "==", "2", "packet", "=", "self", ".", "packets", "[", "-", "1", "]", "for", "p", "in", "packet", ".", "payloads", ":", "if", "p", ".", "_type", "==", ...
Parses the IKE_INIT response packet received from Responder. Assigns the correct values of rSPI and Nr Calculates Diffie-Hellman exchange and assigns all keys to self.
[ "Parses", "the", "IKE_INIT", "response", "packet", "received", "from", "Responder", "." ]
python
train
napalm-automation/napalm
napalm/base/helpers.py
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/base/helpers.py#L353-L380
def canonical_interface_name(interface, addl_name_map=None): """Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false posit...
[ "def", "canonical_interface_name", "(", "interface", ",", "addl_name_map", "=", "None", ")", ":", "name_map", "=", "{", "}", "name_map", ".", "update", "(", "base_interfaces", ")", "interface_type", ",", "interface_number", "=", "split_interface", "(", "interface"...
Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false positive matches. As an example, it would make sense to do "[P|p][O|o]" w...
[ "Function", "to", "return", "an", "interface", "s", "canonical", "name", "(", "fully", "expanded", "name", ")", "." ]
python
train
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L104-L135
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
[ "def", "k_fold_cross_valid", "(", "k", ",", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "assert", "k", ">", "1", "fold_size", "=", "X_train", ".", "shape", "[", "0"...
Conducts k-fold cross validation for the model.
[ "Conducts", "k", "-", "fold", "cross", "validation", "for", "the", "model", "." ]
python
train
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L431-L446
def transform(self, crs): """ Transforms Geometry from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Geometry in target CRS :rtype: Geometry """ new_crs = CRS(crs) geometry = self.geometry if new_crs is not se...
[ "def", "transform", "(", "self", ",", "crs", ")", ":", "new_crs", "=", "CRS", "(", "crs", ")", "geometry", "=", "self", ".", "geometry", "if", "new_crs", "is", "not", "self", ".", "crs", ":", "project", "=", "functools", ".", "partial", "(", "pyproj"...
Transforms Geometry from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Geometry in target CRS :rtype: Geometry
[ "Transforms", "Geometry", "from", "current", "CRS", "to", "target", "CRS" ]
python
train
pandas-dev/pandas
pandas/core/indexes/multi.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/multi.py#L2191-L2252
def reindex(self, target, method=None, level=None, limit=None, tolerance=None): """ Create index with target's values (move/add/delete values as necessary) Returns ------- new_index : pd.MultiIndex Resulting index indexer : np.ndarray or None ...
[ "def", "reindex", "(", "self", ",", "target", ",", "method", "=", "None", ",", "level", "=", "None", ",", "limit", "=", "None", ",", "tolerance", "=", "None", ")", ":", "# GH6552: preserve names when reindexing to non-named target", "# (i.e. neither Index nor Series...
Create index with target's values (move/add/delete values as necessary) Returns ------- new_index : pd.MultiIndex Resulting index indexer : np.ndarray or None Indices of output values in original index.
[ "Create", "index", "with", "target", "s", "values", "(", "move", "/", "add", "/", "delete", "values", "as", "necessary", ")" ]
python
train
futursolo/magichttp
magichttp/writers.py
https://github.com/futursolo/magichttp/blob/84445d21d6829a43132da6d50a72501739d64ca4/magichttp/writers.py#L137-L160
def finish(self, data: bytes=b"") -> None: """ Finish the stream. """ if self.finished(): if self._exc: raise self._exc if data: raise WriteAfterFinishedError return try: self._delegate.write_data(...
[ "def", "finish", "(", "self", ",", "data", ":", "bytes", "=", "b\"\"", ")", "->", "None", ":", "if", "self", ".", "finished", "(", ")", ":", "if", "self", ".", "_exc", ":", "raise", "self", ".", "_exc", "if", "data", ":", "raise", "WriteAfterFinish...
Finish the stream.
[ "Finish", "the", "stream", "." ]
python
train
eofs/aws
aws/main.py
https://github.com/eofs/aws/blob/479cbe27a9f289b43f32f8e3de7d048a4a8993fe/aws/main.py#L222-L330
def main(): """ AWS support script's main method """ p = argparse.ArgumentParser(description='Manage Amazon AWS services', prog='aws', version=__version__) subparsers = p.add_subparsers(help='Select Amazon AWS service to use') # Au...
[ "def", "main", "(", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Manage Amazon AWS services'", ",", "prog", "=", "'aws'", ",", "version", "=", "__version__", ")", "subparsers", "=", "p", ".", "add_subparsers", "(", "help"...
AWS support script's main method
[ "AWS", "support", "script", "s", "main", "method" ]
python
train
getsentry/raven-python
raven/utils/serializer/base.py
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/serializer/base.py#L51-L68
def recurse(self, value, max_depth=6, _depth=0, **kwargs): """ Given ``value``, recurse (using the parent serializer) to handle coercing of newly defined values. """ string_max_length = kwargs.get('string_max_length', None) _depth += 1 if _depth >= max_depth: ...
[ "def", "recurse", "(", "self", ",", "value", ",", "max_depth", "=", "6", ",", "_depth", "=", "0", ",", "*", "*", "kwargs", ")", ":", "string_max_length", "=", "kwargs", ".", "get", "(", "'string_max_length'", ",", "None", ")", "_depth", "+=", "1", "i...
Given ``value``, recurse (using the parent serializer) to handle coercing of newly defined values.
[ "Given", "value", "recurse", "(", "using", "the", "parent", "serializer", ")", "to", "handle", "coercing", "of", "newly", "defined", "values", "." ]
python
train
diffeo/rejester
rejester/_task_master.py
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_task_master.py#L786-L798
def workers(self, alive=True): '''Get a listing of all workers. This returns a dictionary mapping worker ID to the mode constant for their last observed mode. :param bool alive: if true (default), only include workers that have called :meth:`Worker.heartbeat` sufficiently rec...
[ "def", "workers", "(", "self", ",", "alive", "=", "True", ")", ":", "return", "self", ".", "registry", ".", "filter", "(", "WORKER_OBSERVED_MODE", ",", "priority_min", "=", "alive", "and", "time", ".", "time", "(", ")", "or", "'-inf'", ")" ]
Get a listing of all workers. This returns a dictionary mapping worker ID to the mode constant for their last observed mode. :param bool alive: if true (default), only include workers that have called :meth:`Worker.heartbeat` sufficiently recently
[ "Get", "a", "listing", "of", "all", "workers", "." ]
python
train
tcalmant/ipopo
pelix/misc/ssl_wrap.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/ssl_wrap.py#L54-L139
def wrap_socket(socket, certfile, keyfile, password=None): """ Wraps an existing TCP socket and returns an SSLSocket object :param socket: The socket to wrap :param certfile: The server certificate file :param keyfile: The server private key file :param password: Password for the private key fi...
[ "def", "wrap_socket", "(", "socket", ",", "certfile", ",", "keyfile", ",", "password", "=", "None", ")", ":", "# Log warnings when some", "logger", "=", "logging", ".", "getLogger", "(", "\"ssl_wrap\"", ")", "def", "_password_support_error", "(", ")", ":", "\"...
Wraps an existing TCP socket and returns an SSLSocket object :param socket: The socket to wrap :param certfile: The server certificate file :param keyfile: The server private key file :param password: Password for the private key file (Python >= 3.3) :return: The wrapped socket :raise SSLError:...
[ "Wraps", "an", "existing", "TCP", "socket", "and", "returns", "an", "SSLSocket", "object" ]
python
train
UDST/urbansim
urbansim/models/dcm.py
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/dcm.py#L278-L320
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a DiscreteChoiceModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. s...
[ "def", "from_yaml", "(", "cls", ",", "yaml_str", "=", "None", ",", "str_or_buffer", "=", "None", ")", ":", "cfg", "=", "yamlio", ".", "yaml_to_dict", "(", "yaml_str", ",", "str_or_buffer", ")", "model", "=", "cls", "(", "cfg", "[", "'model_expression'", ...
Create a DiscreteChoiceModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer f...
[ "Create", "a", "DiscreteChoiceModel", "instance", "from", "a", "saved", "YAML", "configuration", ".", "Arguments", "are", "mutally", "exclusive", "." ]
python
train
pkkid/python-plexapi
plexapi/myplex.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L853-L864
def _chooseConnection(ctype, name, results): """ Chooses the first (best) connection from the given _connect results. """ # At this point we have a list of result tuples containing (url, token, PlexServer, runtime) # or (url, token, None, runtime) in the case a connection could not be established. for u...
[ "def", "_chooseConnection", "(", "ctype", ",", "name", ",", "results", ")", ":", "# At this point we have a list of result tuples containing (url, token, PlexServer, runtime)", "# or (url, token, None, runtime) in the case a connection could not be established.", "for", "url", ",", "to...
Chooses the first (best) connection from the given _connect results.
[ "Chooses", "the", "first", "(", "best", ")", "connection", "from", "the", "given", "_connect", "results", "." ]
python
train
google/grr
grr/core/grr_response_core/lib/parsers/firefox3_history.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/firefox3_history.py#L54-L60
def Parse(self): """Iterator returning dict for each entry in history.""" for timestamp, url, title in self.Query(self.VISITS_QUERY): if not isinstance(timestamp, (long, int)): timestamp = 0 yield [timestamp, "FIREFOX3_VISIT", url, title]
[ "def", "Parse", "(", "self", ")", ":", "for", "timestamp", ",", "url", ",", "title", "in", "self", ".", "Query", "(", "self", ".", "VISITS_QUERY", ")", ":", "if", "not", "isinstance", "(", "timestamp", ",", "(", "long", ",", "int", ")", ")", ":", ...
Iterator returning dict for each entry in history.
[ "Iterator", "returning", "dict", "for", "each", "entry", "in", "history", "." ]
python
train
DataONEorg/d1_python
lib_common/src/d1_common/cert/subject_info_renderer.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/cert/subject_info_renderer.py#L72-L105
def render_to_image_file( self, image_out_path, width_pixels=None, height_pixels=None, dpi=90 ): """Render the SubjectInfo to an image file. Args: image_out_path : str Path to where image image will be written. Valid extensions are ``.svg,`` ``.pd...
[ "def", "render_to_image_file", "(", "self", ",", "image_out_path", ",", "width_pixels", "=", "None", ",", "height_pixels", "=", "None", ",", "dpi", "=", "90", ")", ":", "self", ".", "_render_type", "=", "\"file\"", "self", ".", "_tree", ".", "render", "(",...
Render the SubjectInfo to an image file. Args: image_out_path : str Path to where image image will be written. Valid extensions are ``.svg,`` ``.pdf``, and ``.png``. width_pixels : int Width of image to write. height_pixels :...
[ "Render", "the", "SubjectInfo", "to", "an", "image", "file", "." ]
python
train
vatlab/SoS
src/sos/utils.py
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L933-L939
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [int(c) if c.isdigit() else c for c in re.split(r'(\d+)', text)]
[ "def", "natural_keys", "(", "text", ")", ":", "return", "[", "int", "(", "c", ")", "if", "c", ".", "isdigit", "(", ")", "else", "c", "for", "c", "in", "re", ".", "split", "(", "r'(\\d+)'", ",", "text", ")", "]" ]
alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments)
[ "alist", ".", "sort", "(", "key", "=", "natural_keys", ")", "sorts", "in", "human", "order", "http", ":", "//", "nedbatchelder", ".", "com", "/", "blog", "/", "200712", "/", "human_sorting", ".", "html", "(", "See", "Toothy", "s", "implementation", "in",...
python
train
portfors-lab/sparkle
sparkle/gui/stim/stimulusview.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L338-L349
def grabImage(self, index): """Gets an image of the item at *index* :param index: index of an item in the view :type index: :qtdoc:`QModelIndex` :returns: :qtdoc:`QPixmap` """ # rect = self._rects[index.row()][index.column()] rect = self.visualRect(index) ...
[ "def", "grabImage", "(", "self", ",", "index", ")", ":", "# rect = self._rects[index.row()][index.column()]", "rect", "=", "self", ".", "visualRect", "(", "index", ")", "pixmap", "=", "QtGui", ".", "QPixmap", "(", ")", "pixmap", "=", "pixmap", ".", "grabWidget...
Gets an image of the item at *index* :param index: index of an item in the view :type index: :qtdoc:`QModelIndex` :returns: :qtdoc:`QPixmap`
[ "Gets", "an", "image", "of", "the", "item", "at", "*", "index", "*" ]
python
train
Azure/azure-sdk-for-python
azure-keyvault/azure/keyvault/v2016_10_01/key_vault_client.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-keyvault/azure/keyvault/v2016_10_01/key_vault_client.py#L1566-L1644
def set_secret( self, vault_base_url, secret_name, value, tags=None, content_type=None, secret_attributes=None, custom_headers=None, raw=False, **operation_config): """Sets a secret in a specified key vault. The SET operation adds a secret to the Azure Key Vault. If the named secret...
[ "def", "set_secret", "(", "self", ",", "vault_base_url", ",", "secret_name", ",", "value", ",", "tags", "=", "None", ",", "content_type", "=", "None", ",", "secret_attributes", "=", "None", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",",...
Sets a secret in a specified key vault. The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault creates a new version of that secret. This operation requires the secrets/set permission. :param vault_base_url: The vault name, for examp...
[ "Sets", "a", "secret", "in", "a", "specified", "key", "vault", "." ]
python
test
pudo/normality
normality/cleaning.py
https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L17-L28
def decompose_nfkd(text): """Perform unicode compatibility decomposition. This will replace some non-standard value representations in unicode and normalise them, while also separating characters and their diacritics into two separate codepoints. """ if text is None: return None if ...
[ "def", "decompose_nfkd", "(", "text", ")", ":", "if", "text", "is", "None", ":", "return", "None", "if", "not", "hasattr", "(", "decompose_nfkd", ",", "'_tr'", ")", ":", "decompose_nfkd", ".", "_tr", "=", "Transliterator", ".", "createInstance", "(", "'Any...
Perform unicode compatibility decomposition. This will replace some non-standard value representations in unicode and normalise them, while also separating characters and their diacritics into two separate codepoints.
[ "Perform", "unicode", "compatibility", "decomposition", "." ]
python
train
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L142-L172
def gpg_stash_key( appname, key_bin, config_dir=None, gpghome=None ): """ Store a key locally to our app keyring. Does NOT put it into a blockchain ID Return the key ID on success Return None on error """ assert is_valid_appname(appname) key_bin = str(key_bin) assert len(key_bin) > ...
[ "def", "gpg_stash_key", "(", "appname", ",", "key_bin", ",", "config_dir", "=", "None", ",", "gpghome", "=", "None", ")", ":", "assert", "is_valid_appname", "(", "appname", ")", "key_bin", "=", "str", "(", "key_bin", ")", "assert", "len", "(", "key_bin", ...
Store a key locally to our app keyring. Does NOT put it into a blockchain ID Return the key ID on success Return None on error
[ "Store", "a", "key", "locally", "to", "our", "app", "keyring", ".", "Does", "NOT", "put", "it", "into", "a", "blockchain", "ID", "Return", "the", "key", "ID", "on", "success", "Return", "None", "on", "error" ]
python
train
gwastro/pycbc
pycbc/inference/option_utils.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/option_utils.py#L436-L463
def prior_from_config(cp, prior_section='prior'): """Loads a prior distribution from the given config file. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser The config file to read. sections : list of str, optional The sections to retrieve the prior from. If ``None`` (...
[ "def", "prior_from_config", "(", "cp", ",", "prior_section", "=", "'prior'", ")", ":", "# Read variable and static parameters from the config file", "variable_params", ",", "_", "=", "distributions", ".", "read_params_from_config", "(", "cp", ",", "prior_section", "=", ...
Loads a prior distribution from the given config file. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser The config file to read. sections : list of str, optional The sections to retrieve the prior from. If ``None`` (the default), will look in sections starting with...
[ "Loads", "a", "prior", "distribution", "from", "the", "given", "config", "file", "." ]
python
train
Jajcus/pyxmpp2
pyxmpp2/ext/component.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L160-L203
def _process_node(self,node): """Process first level element of the stream. Handle component handshake (authentication) element, and treat elements in "jabber:component:accept", "jabber:client" and "jabber:server" equally (pass to `self.process_stanza`). All other elements are p...
[ "def", "_process_node", "(", "self", ",", "node", ")", ":", "ns", "=", "node", ".", "ns", "(", ")", "if", "ns", ":", "ns_uri", "=", "node", ".", "ns", "(", ")", ".", "getContent", "(", ")", "if", "(", "not", "ns", "or", "ns_uri", "==", "\"jabbe...
Process first level element of the stream. Handle component handshake (authentication) element, and treat elements in "jabber:component:accept", "jabber:client" and "jabber:server" equally (pass to `self.process_stanza`). All other elements are passed to `Stream._process_node`. ...
[ "Process", "first", "level", "element", "of", "the", "stream", "." ]
python
valid
collectiveacuity/labPack
labpack/parsing/conversion.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/conversion.py#L105-L123
def camelcase_to_lowercase(camelcase_input, python_input=None): ''' a function to recursively convert data with camelcase key names into lowercase keys :param camelcase_input: list or dictionary with camelcase keys :param python_input: [optional] list or dictionary with default lower...
[ "def", "camelcase_to_lowercase", "(", "camelcase_input", ",", "python_input", "=", "None", ")", ":", "if", "python_input", ":", "if", "camelcase_input", ".", "__class__", "!=", "python_input", ".", "__class__", ":", "raise", "ValueError", "(", "'python_input type %s...
a function to recursively convert data with camelcase key names into lowercase keys :param camelcase_input: list or dictionary with camelcase keys :param python_input: [optional] list or dictionary with default lowercase keys in output :return: dictionary with lowercase key names
[ "a", "function", "to", "recursively", "convert", "data", "with", "camelcase", "key", "names", "into", "lowercase", "keys", ":", "param", "camelcase_input", ":", "list", "or", "dictionary", "with", "camelcase", "keys", ":", "param", "python_input", ":", "[", "o...
python
train
dropbox/stone
stone/backends/python_client.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_client.py#L529-L540
def _format_type_in_doc(self, namespace, data_type): """ Returns a string that can be recognized by Sphinx as a type reference in a docstring. """ if is_void_type(data_type): return 'None' elif is_user_defined_type(data_type): return ':class:`{}.{}...
[ "def", "_format_type_in_doc", "(", "self", ",", "namespace", ",", "data_type", ")", ":", "if", "is_void_type", "(", "data_type", ")", ":", "return", "'None'", "elif", "is_user_defined_type", "(", "data_type", ")", ":", "return", "':class:`{}.{}.{}`'", ".", "form...
Returns a string that can be recognized by Sphinx as a type reference in a docstring.
[ "Returns", "a", "string", "that", "can", "be", "recognized", "by", "Sphinx", "as", "a", "type", "reference", "in", "a", "docstring", "." ]
python
train
UDST/urbansim
scripts/cache_to_hdf5.py
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/scripts/cache_to_hdf5.py#L72-L130
def convert_dirs(base_dir, hdf_name, complib=None, complevel=0): """ Convert nested set of directories to """ print('Converting directories in {}'.format(base_dir)) dirs = glob.glob(os.path.join(base_dir, '*')) dirs = {d for d in dirs if os.path.basename(d) in DIRECTORIES} if not dirs: ...
[ "def", "convert_dirs", "(", "base_dir", ",", "hdf_name", ",", "complib", "=", "None", ",", "complevel", "=", "0", ")", ":", "print", "(", "'Converting directories in {}'", ".", "format", "(", "base_dir", ")", ")", "dirs", "=", "glob", ".", "glob", "(", "...
Convert nested set of directories to
[ "Convert", "nested", "set", "of", "directories", "to" ]
python
train
pandas-dev/pandas
pandas/core/arrays/categorical.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2549-L2582
def _get_codes_for_values(values, categories): """ utility routine to turn values into codes given the specified categories """ from pandas.core.algorithms import _get_data_algo, _hashtables dtype_equal = is_dtype_equal(values.dtype, categories.dtype) if dtype_equal: # To prevent errone...
[ "def", "_get_codes_for_values", "(", "values", ",", "categories", ")", ":", "from", "pandas", ".", "core", ".", "algorithms", "import", "_get_data_algo", ",", "_hashtables", "dtype_equal", "=", "is_dtype_equal", "(", "values", ".", "dtype", ",", "categories", "....
utility routine to turn values into codes given the specified categories
[ "utility", "routine", "to", "turn", "values", "into", "codes", "given", "the", "specified", "categories" ]
python
train
ronaldguillen/wave
wave/views.py
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L355-L367
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), authenticators=self.get_authenticators()...
[ "def", "initialize_request", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser_context", "=", "self", ".", "get_parser_context", "(", "request", ")", "return", "Request", "(", "request", ",", "parsers", "=", "self", ...
Returns the initial request object.
[ "Returns", "the", "initial", "request", "object", "." ]
python
train
SetBased/py-etlt
etlt/condition/InListCondition.py
https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/condition/InListCondition.py#L73-L88
def match(self, row): """ Returns True if the field is in the list of conditions. Returns False otherwise. :param dict row: The row. :rtype: bool """ if row[self._field] in self._values: return True for condition in self._conditions: if ...
[ "def", "match", "(", "self", ",", "row", ")", ":", "if", "row", "[", "self", ".", "_field", "]", "in", "self", ".", "_values", ":", "return", "True", "for", "condition", "in", "self", ".", "_conditions", ":", "if", "condition", ".", "match", "(", "...
Returns True if the field is in the list of conditions. Returns False otherwise. :param dict row: The row. :rtype: bool
[ "Returns", "True", "if", "the", "field", "is", "in", "the", "list", "of", "conditions", ".", "Returns", "False", "otherwise", "." ]
python
train
belbio/bel
bel/lang/bel_utils.py
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L450-L457
def _dump_spec(spec): """Dump bel specification dictionary using YAML Formats this with an extra indentation for lists to make it easier to use cold folding on the YAML version of the spec dictionary. """ with open("spec.yaml", "w") as f: yaml.dump(spec, f, Dumper=MyDumper, default_flow_sty...
[ "def", "_dump_spec", "(", "spec", ")", ":", "with", "open", "(", "\"spec.yaml\"", ",", "\"w\"", ")", "as", "f", ":", "yaml", ".", "dump", "(", "spec", ",", "f", ",", "Dumper", "=", "MyDumper", ",", "default_flow_style", "=", "False", ")" ]
Dump bel specification dictionary using YAML Formats this with an extra indentation for lists to make it easier to use cold folding on the YAML version of the spec dictionary.
[ "Dump", "bel", "specification", "dictionary", "using", "YAML" ]
python
train
bwohlberg/sporco
sporco/admm/tvl2.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/tvl2.py#L319-L324
def cnst_c(self): r"""Compute constant component :math:`\mathbf{c}` of ADMM problem constraint. In this case :math:`\mathbf{c} = \mathbf{0}`. """ return np.zeros(self.S.shape + (len(self.axes),), self.dtype)
[ "def", "cnst_c", "(", "self", ")", ":", "return", "np", ".", "zeros", "(", "self", ".", "S", ".", "shape", "+", "(", "len", "(", "self", ".", "axes", ")", ",", ")", ",", "self", ".", "dtype", ")" ]
r"""Compute constant component :math:`\mathbf{c}` of ADMM problem constraint. In this case :math:`\mathbf{c} = \mathbf{0}`.
[ "r", "Compute", "constant", "component", ":", "math", ":", "\\", "mathbf", "{", "c", "}", "of", "ADMM", "problem", "constraint", ".", "In", "this", "case", ":", "math", ":", "\\", "mathbf", "{", "c", "}", "=", "\\", "mathbf", "{", "0", "}", "." ]
python
train
miyakogi/wdom
wdom/element.py
https://github.com/miyakogi/wdom/blob/a21bcd23e94baceee71161829f6897bee3fd39c1/wdom/element.py#L276-L286
def removeNamedItem(self, item: Attr) -> Optional[Attr]: """Set ``Attr`` object and return it (if exists).""" from wdom.web_node import WdomElement if not isinstance(item, Attr): raise TypeError('item must be an instance of Attr') if isinstance(self._owner, WdomElement): ...
[ "def", "removeNamedItem", "(", "self", ",", "item", ":", "Attr", ")", "->", "Optional", "[", "Attr", "]", ":", "from", "wdom", ".", "web_node", "import", "WdomElement", "if", "not", "isinstance", "(", "item", ",", "Attr", ")", ":", "raise", "TypeError", ...
Set ``Attr`` object and return it (if exists).
[ "Set", "Attr", "object", "and", "return", "it", "(", "if", "exists", ")", "." ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/platformfunc.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/platformfunc.py#L293-L307
def contains_unquoted_target(x: str, quote: str = '"', target: str = '&') -> bool: """ Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`. """ in_quote = False ...
[ "def", "contains_unquoted_target", "(", "x", ":", "str", ",", "quote", ":", "str", "=", "'\"'", ",", "target", ":", "str", "=", "'&'", ")", "->", "bool", ":", "in_quote", "=", "False", "for", "c", "in", "x", ":", "if", "c", "==", "quote", ":", "i...
Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`.
[ "Checks", "if", "target", "exists", "in", "x", "outside", "quotes", "(", "as", "defined", "by", "quote", ")", ".", "Principal", "use", ":", "from", ":", "func", ":", "contains_unquoted_ampersand_dangerous_to_windows", "." ]
python
train
EntilZha/PyFunctional
functional/transformations.py
https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/transformations.py#L634-L647
def sliding_impl(wrap, size, step, sequence): """ Implementation for sliding_t :param wrap: wrap children values with this :param size: size of window :param step: step size :param sequence: sequence to create sliding windows from :return: sequence of sliding windows """ i = 0 n ...
[ "def", "sliding_impl", "(", "wrap", ",", "size", ",", "step", ",", "sequence", ")", ":", "i", "=", "0", "n", "=", "len", "(", "sequence", ")", "while", "i", "+", "size", "<=", "n", "or", "(", "step", "!=", "1", "and", "i", "<", "n", ")", ":",...
Implementation for sliding_t :param wrap: wrap children values with this :param size: size of window :param step: step size :param sequence: sequence to create sliding windows from :return: sequence of sliding windows
[ "Implementation", "for", "sliding_t", ":", "param", "wrap", ":", "wrap", "children", "values", "with", "this", ":", "param", "size", ":", "size", "of", "window", ":", "param", "step", ":", "step", "size", ":", "param", "sequence", ":", "sequence", "to", ...
python
train
cloudendpoints/endpoints-python
endpoints/users_id_token.py
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/users_id_token.py#L365-L375
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes): """Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from...
[ "def", "_are_scopes_sufficient", "(", "authorized_scopes", ",", "sufficient_scopes", ")", ":", "for", "sufficient_scope_set", "in", "sufficient_scopes", ":", "if", "sufficient_scope_set", ".", "issubset", "(", "authorized_scopes", ")", ":", "return", "True", "return", ...
Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from _process_scopes
[ "Check", "if", "a", "list", "of", "authorized", "scopes", "satisfies", "any", "set", "of", "sufficient", "scopes", "." ]
python
train
saltstack/salt
salt/utils/stringutils.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L594-L609
def camel_to_snake_case(camel_input): ''' Converts camelCase (or CamelCase) to snake_case. From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case :param str camel_input: The camelcase or CamelCase string to convert to snake_case :return str ...
[ "def", "camel_to_snake_case", "(", "camel_input", ")", ":", "res", "=", "camel_input", "[", "0", "]", ".", "lower", "(", ")", "for", "i", ",", "letter", "in", "enumerate", "(", "camel_input", "[", "1", ":", "]", ",", "1", ")", ":", "if", "letter", ...
Converts camelCase (or CamelCase) to snake_case. From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case :param str camel_input: The camelcase or CamelCase string to convert to snake_case :return str
[ "Converts", "camelCase", "(", "or", "CamelCase", ")", "to", "snake_case", ".", "From", "https", ":", "//", "codereview", ".", "stackexchange", ".", "com", "/", "questions", "/", "185966", "/", "functions", "-", "to", "-", "convert", "-", "camelcase", "-", ...
python
train
thefab/tornadis
tornadis/client.py
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L218-L259
def async_call(self, *args, **kwargs): """Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis command itself): - callback Function called (with the result as argument) when the result is available. If no...
[ "def", "async_call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "after_autoconnect_callback", "(", "future", ")", ":", "if", "self", ".", "is_connected", "(", ")", ":", "self", ".", "_call", "(", "*", "args", ",", "*", ...
Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis command itself): - callback Function called (with the result as argument) when the result is available. If not set, the reply is silently discarded. In ...
[ "Calls", "a", "redis", "command", "waits", "for", "the", "reply", "and", "call", "a", "callback", "." ]
python
train
not-na/peng3d
peng3d/keybind.py
https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/keybind.py#L144-L152
def mod_is_held(self,modname,modifiers): """ Helper method to simplify checking if a modifier is held. :param str modname: Name of the modifier, see :py:data:`MODNAME2MODIFIER` :param int modifiers: Bitmask to check in, same as the modifiers argument of the on_key_press etc. han...
[ "def", "mod_is_held", "(", "self", ",", "modname", ",", "modifiers", ")", ":", "modifier", "=", "MODNAME2MODIFIER", "[", "modname", ".", "lower", "(", ")", "]", "return", "modifiers", "&", "modifier" ]
Helper method to simplify checking if a modifier is held. :param str modname: Name of the modifier, see :py:data:`MODNAME2MODIFIER` :param int modifiers: Bitmask to check in, same as the modifiers argument of the on_key_press etc. handlers
[ "Helper", "method", "to", "simplify", "checking", "if", "a", "modifier", "is", "held", ".", ":", "param", "str", "modname", ":", "Name", "of", "the", "modifier", "see", ":", "py", ":", "data", ":", "MODNAME2MODIFIER", ":", "param", "int", "modifiers", ":...
python
test
jrief/django-angular
djng/forms/fields.py
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/fields.py#L355-L364
def implode_multi_values(self, name, data): """ Due to the way Angular organizes it model, when Form data is sent via a POST request, then for this kind of widget, the posted data must to be converted into a format suitable for Django's Form validation. """ mkeys = [k for...
[ "def", "implode_multi_values", "(", "self", ",", "name", ",", "data", ")", ":", "mkeys", "=", "[", "k", "for", "k", "in", "data", ".", "keys", "(", ")", "if", "k", ".", "startswith", "(", "name", "+", "'.'", ")", "]", "mvls", "=", "[", "data", ...
Due to the way Angular organizes it model, when Form data is sent via a POST request, then for this kind of widget, the posted data must to be converted into a format suitable for Django's Form validation.
[ "Due", "to", "the", "way", "Angular", "organizes", "it", "model", "when", "Form", "data", "is", "sent", "via", "a", "POST", "request", "then", "for", "this", "kind", "of", "widget", "the", "posted", "data", "must", "to", "be", "converted", "into", "a", ...
python
train
ioam/lancet
lancet/core.py
https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L35-L43
def to_table(args, vdims=[]): "Helper function to convet an Args object to a HoloViews Table" if not Table: return "HoloViews Table not available" kdims = [dim for dim in args.constant_keys + args.varying_keys if dim not in vdims] items = [tuple([spec[k] for k in kdims+vdims]) ...
[ "def", "to_table", "(", "args", ",", "vdims", "=", "[", "]", ")", ":", "if", "not", "Table", ":", "return", "\"HoloViews Table not available\"", "kdims", "=", "[", "dim", "for", "dim", "in", "args", ".", "constant_keys", "+", "args", ".", "varying_keys", ...
Helper function to convet an Args object to a HoloViews Table
[ "Helper", "function", "to", "convet", "an", "Args", "object", "to", "a", "HoloViews", "Table" ]
python
valid
ml31415/numpy-groupies
numpy_groupies/benchmarks/generic.py
https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/benchmarks/generic.py#L13-L23
def aggregate_grouploop(*args, **kwargs): """wraps func in lambda which prevents aggregate_numpy from recognising and optimising it. Instead it groups and loops.""" extrafuncs = {'allnan': allnan, 'anynan': anynan, 'first': itemgetter(0), 'last': itemgetter(-1), 'nanfirst...
[ "def", "aggregate_grouploop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "extrafuncs", "=", "{", "'allnan'", ":", "allnan", ",", "'anynan'", ":", "anynan", ",", "'first'", ":", "itemgetter", "(", "0", ")", ",", "'last'", ":", "itemgetter", "(...
wraps func in lambda which prevents aggregate_numpy from recognising and optimising it. Instead it groups and loops.
[ "wraps", "func", "in", "lambda", "which", "prevents", "aggregate_numpy", "from", "recognising", "and", "optimising", "it", ".", "Instead", "it", "groups", "and", "loops", "." ]
python
train
Dallinger/Dallinger
dallinger/registration.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/registration.py#L50-L64
def _upload_assets_to_OSF(dlgr_id, osf_id, provider="osfstorage"): """Upload experimental assets to the OSF.""" root = "https://files.osf.io/v1" snapshot_filename = "{}-code.zip".format(dlgr_id) snapshot_path = os.path.join("snapshots", snapshot_filename) r = requests.put( "{}/resources/{}/p...
[ "def", "_upload_assets_to_OSF", "(", "dlgr_id", ",", "osf_id", ",", "provider", "=", "\"osfstorage\"", ")", ":", "root", "=", "\"https://files.osf.io/v1\"", "snapshot_filename", "=", "\"{}-code.zip\"", ".", "format", "(", "dlgr_id", ")", "snapshot_path", "=", "os", ...
Upload experimental assets to the OSF.
[ "Upload", "experimental", "assets", "to", "the", "OSF", "." ]
python
train
AshleySetter/optoanalysis
optoanalysis/optoanalysis/optoanalysis.py
https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/optoanalysis.py#L3966-L3988
def calc_mass_from_fit_and_conv_factor(A, Damping, ConvFactor): """ Calculates mass from the A parameter from fitting, the damping from fitting in angular units and the Conversion factor calculated from comparing the ratio of the z signal and first harmonic of z. Parameters ---------- A :...
[ "def", "calc_mass_from_fit_and_conv_factor", "(", "A", ",", "Damping", ",", "ConvFactor", ")", ":", "T0", "=", "300", "mFromA", "=", "2", "*", "Boltzmann", "*", "T0", "/", "(", "pi", "*", "A", ")", "*", "ConvFactor", "**", "2", "*", "Damping", "return"...
Calculates mass from the A parameter from fitting, the damping from fitting in angular units and the Conversion factor calculated from comparing the ratio of the z signal and first harmonic of z. Parameters ---------- A : float A factor calculated from fitting Damping : float ...
[ "Calculates", "mass", "from", "the", "A", "parameter", "from", "fitting", "the", "damping", "from", "fitting", "in", "angular", "units", "and", "the", "Conversion", "factor", "calculated", "from", "comparing", "the", "ratio", "of", "the", "z", "signal", "and",...
python
train
abourget/gevent-socketio
socketio/virtsocket.py
https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L477-L480
def _spawn_heartbeat(self): """This functions returns a list of jobs""" self.spawn(self._heartbeat) self.spawn(self._heartbeat_timeout)
[ "def", "_spawn_heartbeat", "(", "self", ")", ":", "self", ".", "spawn", "(", "self", ".", "_heartbeat", ")", "self", ".", "spawn", "(", "self", ".", "_heartbeat_timeout", ")" ]
This functions returns a list of jobs
[ "This", "functions", "returns", "a", "list", "of", "jobs" ]
python
valid