nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/gtk_extras/dialog_extras.py
python
ProgressDialog.__init__
(self, title="", okay=True, label="", sublabel=False, parent=None, cancel=False, stop=False, pause=False,modal=False)
stop,cancel,and pause will be given as callbacks to their prospective buttons.
stop,cancel,and pause will be given as callbacks to their prospective buttons.
[ "stop", "cancel", "and", "pause", "will", "be", "given", "as", "callbacks", "to", "their", "prospective", "buttons", "." ]
def __init__ (self, title="", okay=True, label="", sublabel=False, parent=None, cancel=False, stop=False, pause=False,modal=False): """stop,cancel,and pause will be given as callbacks to their prospective buttons.""" self.custom_pausecb=pause self.custom_cancelcb=cancel self.custom_pause_handlers = [] self.custom_stop_handlers = [] self.custom_stopcb=stop ModalDialog.__init__(self, title, okay=okay, label=label, sublabel=sublabel, parent=parent, cancel=cancel,modal=modal) self.set_title(label) self.progress_bar = Gtk.ProgressBar() self.vbox.add(self.progress_bar) self.detail_label = Gtk.Label() self.vbox.add(self.detail_label) self.detail_label.set_use_markup(True) self.detail_label.set_padding(H_PADDING,Y_PADDING) self.detail_label.set_line_wrap_mode(Pango.WrapMode.WORD) self.vbox.show_all() if okay: self.set_response_sensitive(Gtk.ResponseType.OK,False) # we're false by default! if not stop: self.stop.hide() if not pause: self.pause.hide()
[ "def", "__init__", "(", "self", ",", "title", "=", "\"\"", ",", "okay", "=", "True", ",", "label", "=", "\"\"", ",", "sublabel", "=", "False", ",", "parent", "=", "None", ",", "cancel", "=", "False", ",", "stop", "=", "False", ",", "pause", "=", ...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/gtk_extras/dialog_extras.py#L359-L380
pylava/pylava
c6834ca12f0c7c569cdab395afae416dcca61278
dummy.py
python
Message.__str__
(self)
return '%s:%s: %s' % (self.filename, self.lineno, self.message % self.message_args)
[]
def __str__(self): return '%s:%s: %s' % (self.filename, self.lineno, self.message % self.message_args)
[ "def", "__str__", "(", "self", ")", ":", "return", "'%s:%s: %s'", "%", "(", "self", ".", "filename", ",", "self", ".", "lineno", ",", "self", ".", "message", "%", "self", ".", "message_args", ")" ]
https://github.com/pylava/pylava/blob/c6834ca12f0c7c569cdab395afae416dcca61278/dummy.py#L23-L24
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/auth/generic.py
python
generic.__init__
(self)
[]
def __init__(self): AuthSessionPlugin.__init__(self) # User configuration self.username = '' self.password = '' self.username_field = '' self.password_field = '' self.auth_url = 'http://host.tld/' self.check_url = 'http://host.tld/' self.check_string = ''
[ "def", "__init__", "(", "self", ")", ":", "AuthSessionPlugin", ".", "__init__", "(", "self", ")", "# User configuration", "self", ".", "username", "=", "''", "self", ".", "password", "=", "''", "self", ".", "username_field", "=", "''", "self", ".", "passwo...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/auth/generic.py#L37-L47
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/bitbucket/__init__.py
python
Bitbucket.repo_grant_group_permissions
(self, project_key, repo_key, groupname, permission)
return self.put(url, params=params)
Grant the specified repository permission to an specific group Promote or demote a group's permission level for the specified repository. Available repository permissions are: REPO_READ REPO_WRITE REPO_ADMIN See the Bitbucket Server documentation for a detailed explanation of what each permission entails. The authenticated user must have REPO_ADMIN permission for the specified repository or a higher project or global permission to call this resource. In addition, a user may not demote a group's permission level if their own permission level would be reduced as a result. :param project_key: The project key :param repo_key: The repository key (slug) :param groupname: group to be granted :param permission: the repository permissions available are 'REPO_ADMIN', 'REPO_WRITE' and 'REPO_READ' :return:
Grant the specified repository permission to an specific group Promote or demote a group's permission level for the specified repository. Available repository permissions are: REPO_READ REPO_WRITE REPO_ADMIN See the Bitbucket Server documentation for a detailed explanation of what each permission entails. The authenticated user must have REPO_ADMIN permission for the specified repository or a higher project or global permission to call this resource. In addition, a user may not demote a group's permission level if their own permission level would be reduced as a result. :param project_key: The project key :param repo_key: The repository key (slug) :param groupname: group to be granted :param permission: the repository permissions available are 'REPO_ADMIN', 'REPO_WRITE' and 'REPO_READ' :return:
[ "Grant", "the", "specified", "repository", "permission", "to", "an", "specific", "group", "Promote", "or", "demote", "a", "group", "s", "permission", "level", "for", "the", "specified", "repository", ".", "Available", "repository", "permissions", "are", ":", "RE...
def repo_grant_group_permissions(self, project_key, repo_key, groupname, permission): """ Grant the specified repository permission to an specific group Promote or demote a group's permission level for the specified repository. Available repository permissions are: REPO_READ REPO_WRITE REPO_ADMIN See the Bitbucket Server documentation for a detailed explanation of what each permission entails. The authenticated user must have REPO_ADMIN permission for the specified repository or a higher project or global permission to call this resource. In addition, a user may not demote a group's permission level if their own permission level would be reduced as a result. :param project_key: The project key :param repo_key: The repository key (slug) :param groupname: group to be granted :param permission: the repository permissions available are 'REPO_ADMIN', 'REPO_WRITE' and 'REPO_READ' :return: """ url = self._url_repo_groups(project_key, repo_key) params = {"permission": permission, "name": groupname} return self.put(url, params=params)
[ "def", "repo_grant_group_permissions", "(", "self", ",", "project_key", ",", "repo_key", ",", "groupname", ",", "permission", ")", ":", "url", "=", "self", ".", "_url_repo_groups", "(", "project_key", ",", "repo_key", ")", "params", "=", "{", "\"permission\"", ...
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/bitbucket/__init__.py#L983-L1003
kedro-org/kedro
e78990c6b606a27830f0d502afa0f639c0830950
features/steps/cli_steps.py
python
check_message_not_printed
(context, msg)
Check that specified message is not printed to stdout.
Check that specified message is not printed to stdout.
[ "Check", "that", "specified", "message", "is", "not", "printed", "to", "stdout", "." ]
def check_message_not_printed(context, msg): """Check that specified message is not printed to stdout.""" if isinstance(context.result, ChildTerminatingPopen): stdout = context.result.stdout.read().decode() context.result.terminate() else: stdout = context.result.stdout assert msg not in stdout, ( "Expected the following message segment not to be printed on stdout: " f"{msg},\nbut got {stdout}" )
[ "def", "check_message_not_printed", "(", "context", ",", "msg", ")", ":", "if", "isinstance", "(", "context", ".", "result", ",", "ChildTerminatingPopen", ")", ":", "stdout", "=", "context", ".", "result", ".", "stdout", ".", "read", "(", ")", ".", "decode...
https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/features/steps/cli_steps.py#L584-L596
datastore/datastore
7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3
datastore/filesystem/__init__.py
python
FileSystemDatastore.contains
(self, key)
return os.path.exists(path) and os.path.isfile(path)
Returns whether the object named by `key` exists. Optimized to only check whether the file object exists. Args: key: Key naming the object to check. Returns: boalean whether the object exists
Returns whether the object named by `key` exists. Optimized to only check whether the file object exists.
[ "Returns", "whether", "the", "object", "named", "by", "key", "exists", ".", "Optimized", "to", "only", "check", "whether", "the", "file", "object", "exists", "." ]
def contains(self, key): '''Returns whether the object named by `key` exists. Optimized to only check whether the file object exists. Args: key: Key naming the object to check. Returns: boalean whether the object exists ''' path = self.object_path(key) return os.path.exists(path) and os.path.isfile(path)
[ "def", "contains", "(", "self", ",", "key", ")", ":", "path", "=", "self", ".", "object_path", "(", "key", ")", "return", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isfile", "(", "path", ")" ]
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L221-L232
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/lib2to3/pgen2/driver.py
python
_newer
(a, b)
return os.path.getmtime(a) >= os.path.getmtime(b)
Inquire whether file a was written since file b.
Inquire whether file a was written since file b.
[ "Inquire", "whether", "file", "a", "was", "written", "since", "file", "b", "." ]
def _newer(a, b): """Inquire whether file a was written since file b.""" if not os.path.exists(a): return False if not os.path.exists(b): return True return os.path.getmtime(a) >= os.path.getmtime(b)
[ "def", "_newer", "(", "a", ",", "b", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "a", ")", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "b", ")", ":", "return", "True", "return", "os", ".", "pa...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/lib2to3/pgen2/driver.py#L134-L140
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/optimize/_linprog_ip.py
python
_indicators
(A, b, c, c0, x, y, z, tau, kappa)
return rho_p, rho_d, rho_A, rho_g, rho_mu, obj
Implementation of several equations from [4] used as indicators of the status of optimization. References ---------- .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous algorithm." High performance optimization. Springer US, 2000. 197-232.
Implementation of several equations from [4] used as indicators of the status of optimization.
[ "Implementation", "of", "several", "equations", "from", "[", "4", "]", "used", "as", "indicators", "of", "the", "status", "of", "optimization", "." ]
def _indicators(A, b, c, c0, x, y, z, tau, kappa): """ Implementation of several equations from [4] used as indicators of the status of optimization. References ---------- .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous algorithm." High performance optimization. Springer US, 2000. 197-232. """ # residuals for termination are relative to initial values x0, y0, z0, tau0, kappa0 = _get_blind_start(A.shape) # See [4], Section 4 - The Homogeneous Algorithm, Equation 8.8 def r_p(x, tau): return b * tau - A.dot(x) def r_d(y, z, tau): return c * tau - A.T.dot(y) - z def r_g(x, y, kappa): return kappa + c.dot(x) - b.dot(y) # np.dot unpacks if they are arrays of size one def mu(x, tau, z, kappa): return (x.dot(z) + np.dot(tau, kappa)) / (len(x) + 1) obj = c.dot(x / tau) + c0 def norm(a): return np.linalg.norm(a) # See [4], Section 4.5 - The Stopping Criteria r_p0 = r_p(x0, tau0) r_d0 = r_d(y0, z0, tau0) r_g0 = r_g(x0, y0, kappa0) mu_0 = mu(x0, tau0, z0, kappa0) rho_A = norm(c.T.dot(x) - b.T.dot(y)) / (tau + norm(b.T.dot(y))) rho_p = norm(r_p(x, tau)) / max(1, norm(r_p0)) rho_d = norm(r_d(y, z, tau)) / max(1, norm(r_d0)) rho_g = norm(r_g(x, y, kappa)) / max(1, norm(r_g0)) rho_mu = mu(x, tau, z, kappa) / mu_0 return rho_p, rho_d, rho_A, rho_g, rho_mu, obj
[ "def", "_indicators", "(", "A", ",", "b", ",", "c", ",", "c0", ",", "x", ",", "y", ",", "z", ",", "tau", ",", "kappa", ")", ":", "# residuals for termination are relative to initial values", "x0", ",", "y0", ",", "z0", ",", "tau0", ",", "kappa0", "=", ...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/optimize/_linprog_ip.py#L454-L500
openstack/magnum
fa298eeab19b1d87070d72c7c4fb26cd75b0781e
magnum/common/rpc_service.py
python
API._call
(self, method, *args, **kwargs)
return self._client.call(self._context, method, *args, **kwargs)
[]
def _call(self, method, *args, **kwargs): return self._client.call(self._context, method, *args, **kwargs)
[ "def", "_call", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "call", "(", "self", ".", "_context", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/openstack/magnum/blob/fa298eeab19b1d87070d72c7c4fb26cd75b0781e/magnum/common/rpc_service.py#L78-L79
myano/jenni
d2e9f86b4d0826f43806bf6baf134147500027db
modules/wikipedia.py
python
wik
(jenni, input)
[]
def wik(jenni, input): origterm = input.groups()[1] if not origterm: return jenni.say('Perhaps you meant ".wik Zen"?') origterm = origterm.encode('utf-8') origterm = origterm.strip() term = urllib.unquote(origterm) language = 'en' if term.startswith(':') and (' ' in term): a, b = term.split(' ', 1) a = a.lstrip(':') if a.isalpha(): language, term = a, b term = term[0].upper() + term[1:] term = term.replace(' ', '_') try: result = wikipedia(term, language) except IOError: args = (language, wikiuri % (language, term)) error = "Can't connect to %s.wikipedia.org (%s)" % args return jenni.say(error) if result is not None: jenni.say(result) else: jenni.say('Can\'t find anything in Wikipedia for "%s".' % origterm)
[ "def", "wik", "(", "jenni", ",", "input", ")", ":", "origterm", "=", "input", ".", "groups", "(", ")", "[", "1", "]", "if", "not", "origterm", ":", "return", "jenni", ".", "say", "(", "'Perhaps you meant \".wik Zen\"?'", ")", "origterm", "=", "origterm",...
https://github.com/myano/jenni/blob/d2e9f86b4d0826f43806bf6baf134147500027db/modules/wikipedia.py#L159-L184
pymc-devs/pymc
38867dd19e96afb0ceccc8ccd74a9795f118dfe3
pymc/distributions/mixture.py
python
Mixture.random
(self, point=None, size=None)
Draw random values from defined Mixture distribution. Parameters ---------- point: dict, optional Dict of variable values on which random values are to be conditioned (uses default point if not specified). size: int, optional Desired size of random sample (returns one sample if not specified). Returns ------- array
Draw random values from defined Mixture distribution.
[ "Draw", "random", "values", "from", "defined", "Mixture", "distribution", "." ]
def random(self, point=None, size=None): """ Draw random values from defined Mixture distribution. Parameters ---------- point: dict, optional Dict of variable values on which random values are to be conditioned (uses default point if not specified). size: int, optional Desired size of random sample (returns one sample if not specified). Returns ------- array """
[ "def", "random", "(", "self", ",", "point", "=", "None", ",", "size", "=", "None", ")", ":" ]
https://github.com/pymc-devs/pymc/blob/38867dd19e96afb0ceccc8ccd74a9795f118dfe3/pymc/distributions/mixture.py#L427-L443
WangYueFt/rfs
f8c837ba93c62dd0ac68a2f4019c619aa86b8421
models/resnet.py
python
resnet101
(keep_prob=1.0, avg_pool=False, **kwargs)
return model
Constructs a ResNet-101 model. indeed, only (3 + 4 + 23 + 3) * 3 + 1 = 100 layers
Constructs a ResNet-101 model. indeed, only (3 + 4 + 23 + 3) * 3 + 1 = 100 layers
[ "Constructs", "a", "ResNet", "-", "101", "model", ".", "indeed", "only", "(", "3", "+", "4", "+", "23", "+", "3", ")", "*", "3", "+", "1", "=", "100", "layers" ]
def resnet101(keep_prob=1.0, avg_pool=False, **kwargs): """Constructs a ResNet-101 model. indeed, only (3 + 4 + 23 + 3) * 3 + 1 = 100 layers """ model = ResNet(BasicBlock, [3, 4, 23, 3], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs) return model
[ "def", "resnet101", "(", "keep_prob", "=", "1.0", ",", "avg_pool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "keep_prob", "=", "keep_prob", ...
https://github.com/WangYueFt/rfs/blob/f8c837ba93c62dd0ac68a2f4019c619aa86b8421/models/resnet.py#L262-L267
twitterdev/twitter-for-bigquery
8dcbcd28f813587e8f53e4436ad3e7e61f1c0a37
libs/requests/cookies.py
python
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "...
https://github.com/twitterdev/twitter-for-bigquery/blob/8dcbcd28f813587e8f53e4436ad3e7e61f1c0a37/libs/requests/cookies.py#L223-L229
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/tcl/tkinter/tix.py
python
HList.dragsite_set
(self, index)
[]
def dragsite_set(self, index): self.tk.call(self._w, 'dragsite', 'set', index)
[ "def", "dragsite_set", "(", "self", ",", "index", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'dragsite'", ",", "'set'", ",", "index", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/tcl/tkinter/tix.py#L902-L903
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/dell_emc/powermax/common.py
python
PowerMaxCommon._cleanup_device_snapvx
( self, array, device_id, extra_specs)
Perform any snapvx cleanup before creating clones or snapshots :param array: the array serial :param device_id: the device ID of the volume :param extra_specs: extra specifications
Perform any snapvx cleanup before creating clones or snapshots
[ "Perform", "any", "snapvx", "cleanup", "before", "creating", "clones", "or", "snapshots" ]
def _cleanup_device_snapvx( self, array, device_id, extra_specs): """Perform any snapvx cleanup before creating clones or snapshots :param array: the array serial :param device_id: the device ID of the volume :param extra_specs: extra specifications """ snapvx_tgt, snapvx_src, __ = self.rest.is_vol_in_rep_session( array, device_id) if snapvx_src or snapvx_tgt: @coordination.synchronized("emc-source-{src_device_id}") def do_unlink_and_delete_snap(src_device_id): src_sessions, tgt_session = self.rest.find_snap_vx_sessions( array, src_device_id) if tgt_session: self._unlink_and_delete_temporary_snapshots( tgt_session, array, extra_specs) if src_sessions: if not self.rest.is_snap_id: src_sessions.sort( key=lambda k: k['snapid'], reverse=True) for src_session in src_sessions: self._unlink_and_delete_temporary_snapshots( src_session, array, extra_specs) do_unlink_and_delete_snap(device_id)
[ "def", "_cleanup_device_snapvx", "(", "self", ",", "array", ",", "device_id", ",", "extra_specs", ")", ":", "snapvx_tgt", ",", "snapvx_src", ",", "__", "=", "self", ".", "rest", ".", "is_vol_in_rep_session", "(", "array", ",", "device_id", ")", "if", "snapvx...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/powermax/common.py#L2957-L2983
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/ttLib/tables/otTables.py
python
splitPairPos
(oldSubTable, newSubTable, overflowRecord)
return ok
[]
def splitPairPos(oldSubTable, newSubTable, overflowRecord): st = oldSubTable ok = False newSubTable.Format = oldSubTable.Format if oldSubTable.Format == 1 and len(oldSubTable.PairSet) > 1: for name in 'ValueFormat1', 'ValueFormat2': setattr(newSubTable, name, getattr(oldSubTable, name)) # Move top half of coverage to new subtable newSubTable.Coverage = oldSubTable.Coverage.__class__() coverage = oldSubTable.Coverage.glyphs records = oldSubTable.PairSet oldCount = len(oldSubTable.PairSet) // 2 oldSubTable.Coverage.glyphs = coverage[:oldCount] oldSubTable.PairSet = records[:oldCount] newSubTable.Coverage.glyphs = coverage[oldCount:] newSubTable.PairSet = records[oldCount:] oldSubTable.PairSetCount = len(oldSubTable.PairSet) newSubTable.PairSetCount = len(newSubTable.PairSet) ok = True elif oldSubTable.Format == 2 and len(oldSubTable.Class1Record) > 1: if not hasattr(oldSubTable, 'Class2Count'): oldSubTable.Class2Count = len(oldSubTable.Class1Record[0].Class2Record) for name in 'Class2Count', 'ClassDef2', 'ValueFormat1', 'ValueFormat2': setattr(newSubTable, name, getattr(oldSubTable, name)) # The two subtables will still have the same ClassDef2 and the table # sharing will still cause the sharing to overflow. As such, disable # sharing on the one that is serialized second (that's oldSubTable). oldSubTable.DontShare = True # Move top half of class numbers to new subtable newSubTable.Coverage = oldSubTable.Coverage.__class__() newSubTable.ClassDef1 = oldSubTable.ClassDef1.__class__() coverage = oldSubTable.Coverage.glyphs classDefs = oldSubTable.ClassDef1.classDefs records = oldSubTable.Class1Record oldCount = len(oldSubTable.Class1Record) // 2 newGlyphs = set(k for k,v in classDefs.items() if v >= oldCount) oldSubTable.Coverage.glyphs = [g for g in coverage if g not in newGlyphs] oldSubTable.ClassDef1.classDefs = {k:v for k,v in classDefs.items() if v < oldCount} oldSubTable.Class1Record = records[:oldCount] newSubTable.Coverage.glyphs = [g for g in coverage if g in newGlyphs] newSubTable.ClassDef1.classDefs = {k:(v-oldCount) for k,v in classDefs.items() if v > oldCount} newSubTable.Class1Record = records[oldCount:] oldSubTable.Class1Count = len(oldSubTable.Class1Record) newSubTable.Class1Count = len(newSubTable.Class1Record) ok = True return ok
[ "def", "splitPairPos", "(", "oldSubTable", ",", "newSubTable", ",", "overflowRecord", ")", ":", "st", "=", "oldSubTable", "ok", "=", "False", "newSubTable", ".", "Format", "=", "oldSubTable", ".", "Format", "if", "oldSubTable", ".", "Format", "==", "1", "and...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ttLib/tables/otTables.py#L1731-L1795
timy90022/One-Shot-Object-Detection
26ca16238f2c4f17685ea57b646d58a2d7542fdb
lib/model/roi_align/modules/roi_align.py
python
RoIAlignAvg.forward
(self, features, rois)
return avg_pool2d(x, kernel_size=2, stride=1)
[]
def forward(self, features, rois): x = RoIAlignFunction(self.aligned_height+1, self.aligned_width+1, self.spatial_scale)(features, rois) return avg_pool2d(x, kernel_size=2, stride=1)
[ "def", "forward", "(", "self", ",", "features", ",", "rois", ")", ":", "x", "=", "RoIAlignFunction", "(", "self", ".", "aligned_height", "+", "1", ",", "self", ".", "aligned_width", "+", "1", ",", "self", ".", "spatial_scale", ")", "(", "features", ","...
https://github.com/timy90022/One-Shot-Object-Detection/blob/26ca16238f2c4f17685ea57b646d58a2d7542fdb/lib/model/roi_align/modules/roi_align.py#L26-L29
facebookresearch/mmf
fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f
mmf/datasets/concat_dataset.py
python
MMFConcatDataset.__init__
(self, datasets)
[]
def __init__(self, datasets): super().__init__(datasets) self._dir_representation = dir(self)
[ "def", "__init__", "(", "self", ",", "datasets", ")", ":", "super", "(", ")", ".", "__init__", "(", "datasets", ")", "self", ".", "_dir_representation", "=", "dir", "(", "self", ")" ]
https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/datasets/concat_dataset.py#L12-L14
uwdata/termite-data-server
1085571407c627bdbbd21c352e793fed65d09599
web2py/gluon/storage.py
python
List.__call__
(self, i, default=DEFAULT, cast=None, otherwise=None)
return value
request.args(0,default=0,cast=int,otherwise='http://error_url') request.args(0,default=0,cast=int,otherwise=lambda:...)
request.args(0,default=0,cast=int,otherwise='http://error_url') request.args(0,default=0,cast=int,otherwise=lambda:...)
[ "request", ".", "args", "(", "0", "default", "=", "0", "cast", "=", "int", "otherwise", "=", "http", ":", "//", "error_url", ")", "request", ".", "args", "(", "0", "default", "=", "0", "cast", "=", "int", "otherwise", "=", "lambda", ":", "...", ")"...
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None): """ request.args(0,default=0,cast=int,otherwise='http://error_url') request.args(0,default=0,cast=int,otherwise=lambda:...) """ n = len(self) if 0 <= i < n or -n <= i < 0: value = self[i] elif default is DEFAULT: value = None else: value, cast = default, False if cast: try: value = cast(value) except (ValueError, TypeError): from http import HTTP, redirect if otherwise is None: raise HTTP(404) elif isinstance(otherwise, str): redirect(otherwise) elif callable(otherwise): return otherwise() else: raise RuntimeError("invalid otherwise") return value
[ "def", "__call__", "(", "self", ",", "i", ",", "default", "=", "DEFAULT", ",", "cast", "=", "None", ",", "otherwise", "=", "None", ")", ":", "n", "=", "len", "(", "self", ")", "if", "0", "<=", "i", "<", "n", "or", "-", "n", "<=", "i", "<", ...
https://github.com/uwdata/termite-data-server/blob/1085571407c627bdbbd21c352e793fed65d09599/web2py/gluon/storage.py#L253-L278
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/mailbox.py
python
_create_carefully
(path)
Create a file if it doesn't exist and open for reading and writing.
Create a file if it doesn't exist and open for reading and writing.
[ "Create", "a", "file", "if", "it", "doesn", "t", "exist", "and", "open", "for", "reading", "and", "writing", "." ]
def _create_carefully(path): """Create a file if it doesn't exist and open for reading and writing.""" fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666) try: return open(path, 'rb+') finally: os.close(fd)
[ "def", "_create_carefully", "(", "path", ")", ":", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_EXCL", "|", "os", ".", "O_RDWR", ",", "0o666", ")", "try", ":", "return", "open", "(", "path", ",", "'rb+'...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/mailbox.py#L2057-L2063
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/jinja2-2.6/jinja2/filters.py
python
do_dictsort
(value, case_sensitive=False, by='key')
return sorted(value.items(), key=sort_func)
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dicsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by key, case insensitive, sorted normally and ordered by value.
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:
[ "Sort", "a", "dict", "and", "yield", "(", "key", "value", ")", "pairs", ".", "Because", "python", "dicts", "are", "unsorted", "you", "may", "want", "to", "use", "this", "function", "to", "order", "them", "by", "either", "key", "or", "value", ":" ]
def do_dictsort(value, case_sensitive=False, by='key'): """Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: .. sourcecode:: jinja {% for item in mydict|dictsort %} sort the dict by key, case insensitive {% for item in mydict|dicsort(true) %} sort the dict by key, case sensitive {% for item in mydict|dictsort(false, 'value') %} sort the dict by key, case insensitive, sorted normally and ordered by value. """ if by == 'key': pos = 0 elif by == 'value': pos = 1 else: raise FilterArgumentError('You can only sort by either ' '"key" or "value"') def sort_func(item): value = item[pos] if isinstance(value, basestring) and not case_sensitive: value = value.lower() return value return sorted(value.items(), key=sort_func)
[ "def", "do_dictsort", "(", "value", ",", "case_sensitive", "=", "False", ",", "by", "=", "'key'", ")", ":", "if", "by", "==", "'key'", ":", "pos", "=", "0", "elif", "by", "==", "'value'", ":", "pos", "=", "1", "else", ":", "raise", "FilterArgumentErr...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/jinja2-2.6/jinja2/filters.py#L161-L191
general03/flask-autoindex
424246242c9f40aeb9ac2c8c63f4d2234024256e
.eggs/Werkzeug-1.0.1-py3.7.egg/werkzeug/wrappers/etag.py
python
ETagResponseMixin._wrap_response
(self, start, length)
Wrap existing Response in case of Range Request context.
Wrap existing Response in case of Range Request context.
[ "Wrap", "existing", "Response", "in", "case", "of", "Range", "Request", "context", "." ]
def _wrap_response(self, start, length): """Wrap existing Response in case of Range Request context.""" if self.status_code == 206: self.response = _RangeWrapper(self.response, start, length)
[ "def", "_wrap_response", "(", "self", ",", "start", ",", "length", ")", ":", "if", "self", ".", "status_code", "==", "206", ":", "self", ".", "response", "=", "_RangeWrapper", "(", "self", ".", "response", ",", "start", ",", "length", ")" ]
https://github.com/general03/flask-autoindex/blob/424246242c9f40aeb9ac2c8c63f4d2234024256e/.eggs/Werkzeug-1.0.1-py3.7.egg/werkzeug/wrappers/etag.py#L112-L115
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/numpy/ma/core.py
python
MaskedArray.get_fill_value
(self)
return self._fill_value[()]
Return the filling value of the masked array. Returns ------- fill_value : scalar The filling value. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.get_fill_value() -inf
Return the filling value of the masked array.
[ "Return", "the", "filling", "value", "of", "the", "masked", "array", "." ]
def get_fill_value(self): """ Return the filling value of the masked array. Returns ------- fill_value : scalar The filling value. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.get_fill_value() -inf """ if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) return self._fill_value[()]
[ "def", "get_fill_value", "(", "self", ")", ":", "if", "self", ".", "_fill_value", "is", "None", ":", "self", ".", "_fill_value", "=", "_check_fill_value", "(", "None", ",", "self", ".", "dtype", ")", "return", "self", ".", "_fill_value", "[", "(", ")", ...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/ma/core.py#L3467-L3493
z411/trackma
2422c23228efc9b72872b69f22f7d25c1d337264
trackma/ui/qt/mainwindow.py
python
MainWindow.start
(self, account)
Start engine and everything
Start engine and everything
[ "Start", "engine", "and", "everything" ]
def start(self, account): """ Start engine and everything """ # Workers self.worker = EngineWorker() self.account = account # Get API specific configuration self.api_config = self._get_api_config(account['api']) # Timers self.image_timer = QtCore.QTimer() self.image_timer.setInterval(500) self.image_timer.setSingleShot(True) self.image_timer.timeout.connect(self.s_download_image) self.busy_timer = QtCore.QTimer() self.busy_timer.setInterval(100) self.busy_timer.setSingleShot(True) self.busy_timer.timeout.connect(self.s_busy) # Build menus self.action_play_next = QAction( getIcon('media-playback-start'), 'Play &Next', self) self.action_play_next.setStatusTip('Play the next unwatched episode.') self.action_play_next.setShortcut('Ctrl+N') self.action_play_next.triggered.connect(lambda: self.s_play(True)) self.action_play_dialog = QAction('Play Episode...', self) self.action_play_dialog.setStatusTip('Select an episode to play.') self.action_play_dialog.triggered.connect(self.s_play_number) self.action_details = QAction('Show &details...', self) self.action_details.setStatusTip( 'Show detailed information about the selected show.') self.action_details.triggered.connect(self.s_show_details) self.action_altname = QAction('Change &alternate name...', self) self.action_altname.setStatusTip( 'Set an alternate title for the tracker.') self.action_altname.triggered.connect(self.s_altname) action_play_random = QAction('Play &random show', self) action_play_random.setStatusTip( 'Pick a random show with a new episode and play it.') action_play_random.setShortcut('Ctrl+R') action_play_random.triggered.connect(self.s_play_random) self.action_add = QAction( getIcon('edit-find'), 'Search/Add from Remote', self) self.action_add.setShortcut('Ctrl+A') self.action_add.triggered.connect(self.s_add) self.action_delete = QAction(getIcon('edit-delete'), '&Delete', self) self.action_delete.setStatusTip('Remove this show from your list.') self.action_delete.setShortcut(QtCore.Qt.Key_Delete) self.action_delete.triggered.connect(self.s_delete) action_quit = QAction(getIcon('application-exit'), '&Quit', self) action_quit.setShortcut('Ctrl+Q') action_quit.setStatusTip('Exit Trackma.') action_quit.triggered.connect(self._exit) self.action_sync = QAction('&Sync', self) self.action_sync.setStatusTip( 'Send changes and then retrieve remote list') self.action_sync.setShortcut('Ctrl+S') self.action_sync.triggered.connect(lambda: self.s_send(True)) self.action_send = QAction('S&end changes', self) self.action_send.setShortcut('Ctrl+E') self.action_send.setStatusTip( 'Upload any changes made to the list immediately.') self.action_send.triggered.connect(self.s_send) self.action_retrieve = QAction('Re&download list', self) self.action_retrieve.setShortcut('Ctrl+D') self.action_retrieve.setStatusTip( 'Discard any changes made to the list and re-download it.') self.action_retrieve.triggered.connect(self.s_retrieve) action_scan_library = QAction('Rescan &Library (quick)', self) action_scan_library.setShortcut('Ctrl+L') action_scan_library.triggered.connect(self.s_scan_library) action_rescan_library = QAction('Rescan &Library (full)', self) action_rescan_library.triggered.connect(self.s_rescan_library) action_open_folder = QAction('Open containing folder', self) action_open_folder.triggered.connect(self.s_open_folder) self.action_reload = QAction('Switch &Account', self) self.action_reload.setStatusTip('Switch to a different account.') self.action_reload.triggered.connect(self.s_switch_account) action_settings = QAction('&Settings...', self) action_settings.triggered.connect(self.s_settings) action_about = QAction(getIcon('help-about'), 'About...', self) action_about.triggered.connect(self.s_about) action_about_qt = QAction('About Qt...', self) action_about_qt.triggered.connect(self.s_about_qt) menubar = self.menuBar() self.menu_show = menubar.addMenu('&Show') self.menu_show.addAction(self.action_play_next) self.menu_show.addAction(self.action_play_dialog) self.menu_show.addAction(self.action_details) self.menu_show.addAction(self.action_altname) self.menu_show.addSeparator() self.menu_show.addAction(action_play_random) self.menu_show.addSeparator() self.menu_show.addAction(self.action_add) self.menu_show.addAction(self.action_delete) self.menu_show.addSeparator() self.menu_show.addAction(action_quit) self.menu_play = QMenu('Play') # Context menu for right click on list item self.menu_show_context = QMenu() self.menu_show_context.addMenu(self.menu_play) self.menu_show_context.addAction(self.action_details) self.menu_show_context.addAction(action_open_folder) self.menu_show_context.addAction(self.action_altname) self.menu_show_context.addSeparator() self.menu_show_context.addAction(self.action_delete) # Make icons for viewed episodes rect = QtCore.QSize(16, 16) buffer = QtGui.QPixmap(rect) ep_icon_states = {'all': QStyle.State_On, 'part': QStyle.State_NoChange, 'none': QStyle.State_Off} self.ep_icons = {} for key, state in ep_icon_states.items(): buffer.fill(QtCore.Qt.transparent) painter = QtGui.QPainter(buffer) opt = QStyleOptionButton() opt.state = state self.style().drawPrimitive(QStyle.PE_IndicatorMenuCheckMark, opt, painter) self.ep_icons[key] = QtGui.QIcon(buffer) painter.end() menu_list = menubar.addMenu('&List') menu_list.addAction(self.action_sync) menu_list.addSeparator() menu_list.addAction(self.action_send) menu_list.addAction(self.action_retrieve) menu_list.addSeparator() menu_list.addAction(action_scan_library) menu_list.addAction(action_rescan_library) self.menu_mediatype = menubar.addMenu('&Mediatype') self.mediatype_actiongroup = QActionGroup(self) self.mediatype_actiongroup.setExclusive(True) self.mediatype_actiongroup.triggered.connect(self.s_mediatype) menu_options = menubar.addMenu('&Options') menu_options.addAction(self.action_reload) menu_options.addSeparator() menu_options.addAction(action_settings) menu_help = menubar.addMenu('&Help') menu_help.addAction(action_about) menu_help.addAction(action_about_qt) # Build layout main_layout = QVBoxLayout() top_hbox = QHBoxLayout() main_hbox = QHBoxLayout() self.list_box = QVBoxLayout() filter_bar_box_layout = QHBoxLayout() self.filter_bar_box = QWidget() left_box = QFormLayout() small_btns_hbox = QHBoxLayout() self.show_title = QLabel('Trackma-qt') show_title_font = QtGui.QFont() show_title_font.setBold(True) show_title_font.setPointSize(12) self.show_title.setFont(show_title_font) self.api_icon = QLabel('icon') self.api_user = QLabel('user') top_hbox.addWidget(self.show_title, 1) top_hbox.addWidget(self.api_icon) top_hbox.addWidget(self.api_user) # Create main models and view self.notebook = QTabBar() self.notebook.currentChanged.connect(self.s_tab_changed) self.view = ShowsTableView(palette=self.config['colors']) self.view.context_menu = self.menu_show_context self.view.horizontalHeader().customContextMenuRequested.connect( self.s_show_menu_columns) self.view.horizontalHeader().sortIndicatorChanged.connect(self.s_update_sort) self.view.selectionModel().currentRowChanged.connect(self.s_show_selected) self.view.itemDelegate().setBarStyle( self.config['episodebar_style'], self.config['episodebar_text']) self.view.middleClicked.connect(lambda: self.s_play(True)) self.view.doubleClicked.connect(self.s_show_details) self._apply_view() self.view.model().sourceModel().progressChanged.connect(self.s_set_episode) self.view.model().sourceModel().scoreChanged.connect(self.s_set_score) # Context menu for right click on list header self.menu_columns = QMenu() self.column_keys = {'id': 0, 'title': 1, 'progress': 2, 'score': 3, 'percent': 4, 'next_ep': 5, 'date_start': 6, 'date_end': 7, 'my_start': 8, 'my_end': 9, 'tag': 10} self.menu_columns_group = QActionGroup(self) self.menu_columns_group.triggered.connect(self.s_toggle_column) for i, column_name in enumerate(self.view.model().sourceModel().columns): action = QAction(column_name, self, checkable=True) action.setData(i) if column_name in self.api_config['visible_columns']: action.setChecked(True) self.menu_columns_group.addAction(action) self.menu_columns.addAction(action) # Create filter list self.show_filter = QLineEdit() self.show_filter.setClearButtonEnabled(True) self.show_filter.textChanged.connect(self.s_filter_changed) filter_tooltip = ( "General Search: All fields (columns) of each show will be matched against the search term." "\nAdvanced Searching: A field can be specified by using its key followed by a colon" " e.g. 'title:My_Show date_start:2016'." "\n Any field may be specified multiple times to match terms in any order e.g. 'tag:Battle+Shounen tag:Ecchi'. " "\n + and _ are replaced with spaces when searching specific fields." "\n If colon is used after something that is not a column key, it will treat it as a general term." "\n ALL terms not attached to a field will be combined into a single general search term" "\n - 'My date_end:2016 Show' will match shows that have 'My Show' in any field and 2016 in the End Date field." "\n Available field keys are: " ) colkeys = ', '.join(sorted(self.column_keys.keys())) self.show_filter.setToolTip(filter_tooltip + colkeys + '.') self.show_filter_invert = QCheckBox() self.show_filter_invert.stateChanged.connect(self.s_filter_changed) self.show_filter_casesens = QCheckBox() self.show_filter_casesens.stateChanged.connect(self.s_filter_changed) if self.config['remember_geometry']: self.resize(self.config['last_width'], self.config['last_height']) self.move(self.config['last_x'], self.config['last_y']) else: self.resize(740, 480) self.show_image = QLabel('Trackma-qt') self.show_image.setFixedHeight(149) self.show_image.setMinimumWidth(100) self.show_image.setAlignment(QtCore.Qt.AlignCenter) self.show_image.setStyleSheet( "border: 1px solid #777;background-color:#999;text-align:center") show_progress_label = QLabel('Progress:') self.show_progress = QSpinBox() self.show_progress_bar = QProgressBar() self.show_progress_btn = QPushButton('Update') self.show_progress_btn.setToolTip( 'Set number of episodes watched to the value entered above') self.show_progress_btn.clicked.connect(self.s_set_episode) self.show_play_btn = QToolButton() self.show_play_btn.setIcon(getIcon('media-playback-start')) self.show_play_btn.setToolTip( 'Play the next unwatched episode\nHold to play other episodes') self.show_play_btn.clicked.connect(lambda: self.s_play(True)) self.show_play_btn.setMenu(self.menu_play) self.show_inc_btn = QToolButton() self.show_inc_btn.setIcon(getIcon('list-add')) self.show_inc_btn.setShortcut('Ctrl+Right') self.show_inc_btn.setToolTip('Increment number of episodes watched') self.show_inc_btn.clicked.connect(self.s_plus_episode) self.show_dec_btn = QToolButton() self.show_dec_btn.setIcon(getIcon('list-remove')) self.show_dec_btn.clicked.connect(self.s_rem_episode) self.show_dec_btn.setShortcut('Ctrl+Left') self.show_dec_btn.setToolTip('Decrement number of episodes watched') show_score_label = QLabel('Score:') self.show_score = QDoubleSpinBox() self.show_score_btn = QPushButton('Set') self.show_score_btn.setToolTip('Set score to the value entered above') self.show_score_btn.clicked.connect(self.s_set_score) self.show_tags_btn = QPushButton('Edit Tags...') self.show_tags_btn.setToolTip( 'Open a dialog to edit your tags for this show') self.show_tags_btn.clicked.connect(self.s_set_tags) self.show_status = QComboBox() self.show_status.setToolTip('Change your watching status of this show') self.show_status.currentIndexChanged.connect(self.s_set_status) small_btns_hbox.addWidget(self.show_dec_btn) small_btns_hbox.addWidget(self.show_play_btn) small_btns_hbox.addWidget(self.show_inc_btn) small_btns_hbox.setAlignment(QtCore.Qt.AlignCenter) left_box.addRow(self.show_image) left_box.addRow(self.show_progress_bar) left_box.addRow(small_btns_hbox) left_box.addRow(show_progress_label) left_box.addRow(self.show_progress, self.show_progress_btn) left_box.addRow(show_score_label) left_box.addRow(self.show_score, self.show_score_btn) left_box.addRow(self.show_status) left_box.addRow(self.show_tags_btn) filter_bar_box_layout.addWidget(QLabel('Filter:')) filter_bar_box_layout.addWidget(self.show_filter) filter_bar_box_layout.addWidget(QLabel('Invert')) filter_bar_box_layout.addWidget(self.show_filter_invert) filter_bar_box_layout.addWidget(QLabel('Case Sensitive')) filter_bar_box_layout.addWidget(self.show_filter_casesens) self.filter_bar_box.setLayout(filter_bar_box_layout) if self.config['filter_bar_position'] is FilterBar.PositionHidden: self.list_box.addWidget(self.notebook) self.list_box.addWidget(self.view) self.filter_bar_box.hide() elif self.config['filter_bar_position'] is FilterBar.PositionAboveLists: self.list_box.addWidget(self.filter_bar_box) self.list_box.addWidget(self.notebook) self.list_box.addWidget(self.view) elif self.config['filter_bar_position'] is FilterBar.PositionBelowLists: self.list_box.addWidget(self.notebook) self.list_box.addWidget(self.view) self.list_box.addWidget(self.filter_bar_box) main_hbox.addLayout(left_box) main_hbox.addLayout(self.list_box, 1) main_layout.addLayout(top_hbox) main_layout.addLayout(main_hbox) self.main_widget = QWidget(self) self.main_widget.setLayout(main_layout) self.setCentralWidget(self.main_widget) # Statusbar self.status_text = QLabel('Trackma-qt') self.tracker_text = QLabel('Tracker: N/A') self.tracker_text.setMinimumWidth(120) self.queue_text = QLabel('Unsynced items: N/A') self.statusBar().addWidget(self.status_text, 1) self.statusBar().addPermanentWidget(self.tracker_text) self.statusBar().addPermanentWidget(self.queue_text) # Tray icon tray_menu = QMenu(self) action_hide = QAction('Show/Hide', self) action_hide.triggered.connect(self.s_hide) tray_menu.addAction(action_hide) tray_menu.addAction(action_quit) self.tray = QSystemTrayIcon(self.windowIcon()) self.tray.setContextMenu(tray_menu) self.tray.activated.connect(self.s_tray_clicked) self._apply_tray() # Connect worker signals self.worker.changed_status.connect(self.ws_changed_status) self.worker.raised_error.connect(self.error) self.worker.raised_fatal.connect(self.fatal) self.worker.changed_show.connect(self.ws_changed_show) self.worker.changed_show_status.connect(self.ws_changed_show_status) self.worker.changed_list.connect(self.ws_changed_list) self.worker.changed_queue.connect(self.ws_changed_queue) self.worker.tracker_state.connect(self.ws_tracker_state) self.worker.playing_show.connect(self.ws_changed_show) self.worker.prompt_for_update.connect(self.ws_prompt_update) self.worker.prompt_for_add.connect(self.ws_prompt_add) # Show main window if not (self.config['show_tray'] and self.config['start_in_tray']): self.show() # Start loading engine self.started = True self._busy(False) self.worker_call('start', self.r_engine_loaded, account)
[ "def", "start", "(", "self", ",", "account", ")", ":", "# Workers", "self", ".", "worker", "=", "EngineWorker", "(", ")", "self", ".", "account", "=", "account", "# Get API specific configuration", "self", ".", "api_config", "=", "self", ".", "_get_api_config"...
https://github.com/z411/trackma/blob/2422c23228efc9b72872b69f22f7d25c1d337264/trackma/ui/qt/mainwindow.py#L110-L488
CyanideCN/PyCINRAD
f4bcc1f05e1355987b04f192caec4927ecb8e247
cinrad/projection.py
python
get_coordinate
( distance: Boardcast_T, azimuth: Boardcast_T, elevation: Number_T, centerlon: Number_T, centerlat: Number_T, h_offset: bool = True, )
return actuallon, actuallat
r""" Convert polar coordinates to geographic coordinates with the given radar station position. Parameters ---------- distance: int or float or numpy.ndarray distance in kilometer in terms of polar coordinate azimuth: int or float or numpy.ndarray azimuth in radian in terms of polar coordinate elevation: int or float elevation angle in degree centerlon: int or float longitude of center point centerlat: int or float latitude of center point Returns ------- actuallon: float or numpy.ndarray longitude value actuallat: float or numpy.ndarray latitude value
r""" Convert polar coordinates to geographic coordinates with the given radar station position.
[ "r", "Convert", "polar", "coordinates", "to", "geographic", "coordinates", "with", "the", "given", "radar", "station", "position", "." ]
def get_coordinate( distance: Boardcast_T, azimuth: Boardcast_T, elevation: Number_T, centerlon: Number_T, centerlat: Number_T, h_offset: bool = True, ) -> tuple: r""" Convert polar coordinates to geographic coordinates with the given radar station position. Parameters ---------- distance: int or float or numpy.ndarray distance in kilometer in terms of polar coordinate azimuth: int or float or numpy.ndarray azimuth in radian in terms of polar coordinate elevation: int or float elevation angle in degree centerlon: int or float longitude of center point centerlat: int or float latitude of center point Returns ------- actuallon: float or numpy.ndarray longitude value actuallat: float or numpy.ndarray latitude value """ elev = elevation if h_offset else 0 if isinstance(azimuth, np.ndarray): deltav = np.cos(azimuth[:, np.newaxis]) * distance * np.cos(elev * deg2rad) deltah = np.sin(azimuth[:, np.newaxis]) * distance * np.cos(elev * deg2rad) else: deltav = np.cos(azimuth) * distance * np.cos(elev * deg2rad) deltah = np.sin(azimuth) * distance * np.cos(elev * deg2rad) deltalat = deltav / 111 actuallat = deltalat + centerlat deltalon = deltah / (111 * np.cos(actuallat * deg2rad)) actuallon = deltalon + centerlon return actuallon, actuallat
[ "def", "get_coordinate", "(", "distance", ":", "Boardcast_T", ",", "azimuth", ":", "Boardcast_T", ",", "elevation", ":", "Number_T", ",", "centerlon", ":", "Number_T", ",", "centerlat", ":", "Number_T", ",", "h_offset", ":", "bool", "=", "True", ",", ")", ...
https://github.com/CyanideCN/PyCINRAD/blob/f4bcc1f05e1355987b04f192caec4927ecb8e247/cinrad/projection.py#L37-L79
liqd/adhocracy
a143e7101f788f56c78e00bd30b2fe2e15bf3552
src/adhocracy/lib/helpers/__init__.py
python
sorted_flash_messages
()
return sorted_
Return the flash messages sorted by priority, keeping the order.
Return the flash messages sorted by priority, keeping the order.
[ "Return", "the", "flash", "messages", "sorted", "by", "priority", "keeping", "the", "order", "." ]
def sorted_flash_messages(): ''' Return the flash messages sorted by priority, keeping the order. ''' order = ['error', 'warning', 'success', 'notice'] sorted_ = [] unsorted = flash.pop_messages() for category in order: for message in unsorted: if message.category == category: sorted_.append(message) return sorted_
[ "def", "sorted_flash_messages", "(", ")", ":", "order", "=", "[", "'error'", ",", "'warning'", ",", "'success'", ",", "'notice'", "]", "sorted_", "=", "[", "]", "unsorted", "=", "flash", ".", "pop_messages", "(", ")", "for", "category", "in", "order", ":...
https://github.com/liqd/adhocracy/blob/a143e7101f788f56c78e00bd30b2fe2e15bf3552/src/adhocracy/lib/helpers/__init__.py#L80-L92
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractBearlytranslatingHomeBlog.py
python
extractBearlytranslatingHomeBlog
(item)
return False
Parser for 'bearlytranslating.home.blog'
Parser for 'bearlytranslating.home.blog'
[ "Parser", "for", "bearlytranslating", ".", "home", ".", "blog" ]
def extractBearlytranslatingHomeBlog(item): ''' Parser for 'bearlytranslating.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractBearlytranslatingHomeBlog", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", ...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractBearlytranslatingHomeBlog.py#L2-L21
smicallef/spiderfoot
fd4bf9394c9ab3ecc90adc3115c56349fb23165b
sflib.py
python
SpiderFoot.validIP6
(self, address: str)
return netaddr.valid_ipv6(address)
Check if the provided string is a valid IPv6 address. Args: address (str): The IPv6 address to check. Returns: bool: string is a valid IPv6 address
Check if the provided string is a valid IPv6 address.
[ "Check", "if", "the", "provided", "string", "is", "a", "valid", "IPv6", "address", "." ]
def validIP6(self, address: str) -> bool: """Check if the provided string is a valid IPv6 address. Args: address (str): The IPv6 address to check. Returns: bool: string is a valid IPv6 address """ if not address: return False return netaddr.valid_ipv6(address)
[ "def", "validIP6", "(", "self", ",", "address", ":", "str", ")", "->", "bool", ":", "if", "not", "address", ":", "return", "False", "return", "netaddr", ".", "valid_ipv6", "(", "address", ")" ]
https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/sflib.py#L847-L858
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/Iter2_v4_random/nets/lenet.py
python
lenet_arg_scope
(weight_decay=0.0)
Defines the default lenet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model.
Defines the default lenet argument scope.
[ "Defines", "the", "default", "lenet", "argument", "scope", "." ]
def lenet_arg_scope(weight_decay=0.0): """Defines the default lenet argument scope. Args: weight_decay: The weight decay to use for regularizing the model. Returns: An `arg_scope` to use for the inception v3 model. """ with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
[ "def", "lenet_arg_scope", "(", "weight_decay", "=", "0.0", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "fully_connected", "]", ",", "weights_regularizer", "=", "slim", ".", "l2_regularizer", "(", "weight_dec...
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/Iter2_v4_random/nets/lenet.py#L79-L93
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/lib/remote_service.py
python
RemoteService.on_failure
(self)
[]
def on_failure(self): self.failure_count += 1 if self.failure_count >= self.failure_threshold: self.last_unavailable = now() self.state = State.UNAVAILABLE
[ "def", "on_failure", "(", "self", ")", ":", "self", ".", "failure_count", "+=", "1", "if", "self", ".", "failure_count", ">=", "self", ".", "failure_threshold", ":", "self", ".", "last_unavailable", "=", "now", "(", ")", "self", ".", "state", "=", "State...
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/lib/remote_service.py#L97-L101
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/lib-tk/Tix.py
python
PanedWindow.__init__
(self, master, cnf={}, **kw)
[]
def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPanedWindow', ['orientation', 'options'], cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "TixWidget", ".", "__init__", "(", "self", ",", "master", ",", "'tixPanedWindow'", ",", "[", "'orientation'", ",", "'options'", "]", ",", "cnf", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/lib-tk/Tix.py#L1215-L1216
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/util/k8s/pods.py
python
K8SPod.delete
(self)
[]
def delete(self): config.load_kube_config() v1 = client.CoreV1Api() v1.delete_namespaced_pod(name=self.name, namespace=self._namespace, body=V1DeleteOptions())
[ "def", "delete", "(", "self", ")", ":", "config", ".", "load_kube_config", "(", ")", "v1", "=", "client", ".", "CoreV1Api", "(", ")", "v1", ".", "delete_namespaced_pod", "(", "name", "=", "self", ".", "name", ",", "namespace", "=", "self", ".", "_names...
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/util/k8s/pods.py#L33-L37
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tcr/v20190924/tcr_client.py
python
TcrClient.DeleteWebhookTrigger
(self, request)
删除触发器 :param request: Request instance for DeleteWebhookTrigger. :type request: :class:`tencentcloud.tcr.v20190924.models.DeleteWebhookTriggerRequest` :rtype: :class:`tencentcloud.tcr.v20190924.models.DeleteWebhookTriggerResponse`
删除触发器
[ "删除触发器" ]
def DeleteWebhookTrigger(self, request): """删除触发器 :param request: Request instance for DeleteWebhookTrigger. :type request: :class:`tencentcloud.tcr.v20190924.models.DeleteWebhookTriggerRequest` :rtype: :class:`tencentcloud.tcr.v20190924.models.DeleteWebhookTriggerResponse` """ try: params = request._serialize() body = self.call("DeleteWebhookTrigger", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteWebhookTriggerResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DeleteWebhookTrigger", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DeleteWebhookTrigger\"", ",", "params", ")", "response", "=", "json", ".", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tcr/v20190924/tcr_client.py#L1065-L1090
ubuntu/ubuntu-make
939668aad1f4c38ffb74cce55b3678f6fded5c71
umake/frameworks/swift.py
python
SwiftLang.parse_download_link
(self, line, in_download)
return (sig_url, in_download)
Parse Swift download link, expect to find a .sig file
Parse Swift download link, expect to find a .sig file
[ "Parse", "Swift", "download", "link", "expect", "to", "find", "a", ".", "sig", "file" ]
def parse_download_link(self, line, in_download): """Parse Swift download link, expect to find a .sig file""" sig_url = None in_download = False if '.tar.gz.sig' in line: in_download = True if in_download: p = re.search(r'href="(.*)" title="PGP Signature"', line) with suppress(AttributeError): sig_url = "https://swift.org" + p.group(1) logger.debug("Found signature link: {}".format(sig_url)) return (sig_url, in_download)
[ "def", "parse_download_link", "(", "self", ",", "line", ",", "in_download", ")", ":", "sig_url", "=", "None", "in_download", "=", "False", "if", "'.tar.gz.sig'", "in", "line", ":", "in_download", "=", "True", "if", "in_download", ":", "p", "=", "re", ".", ...
https://github.com/ubuntu/ubuntu-make/blob/939668aad1f4c38ffb74cce55b3678f6fded5c71/umake/frameworks/swift.py#L59-L70
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/transports/plugins/ssh.py
python
SshTransport._get_allow_agent_suggestion_string
(cls, computer)
return convert_to_bool(str(config.get('allow_agent', 'yes')))
Return a suggestion for the specific field.
Return a suggestion for the specific field.
[ "Return", "a", "suggestion", "for", "the", "specific", "field", "." ]
def _get_allow_agent_suggestion_string(cls, computer): """ Return a suggestion for the specific field. """ config = parse_sshconfig(computer.hostname) return convert_to_bool(str(config.get('allow_agent', 'yes')))
[ "def", "_get_allow_agent_suggestion_string", "(", "cls", ",", "computer", ")", ":", "config", "=", "parse_sshconfig", "(", "computer", ".", "hostname", ")", "return", "convert_to_bool", "(", "str", "(", "config", ".", "get", "(", "'allow_agent'", ",", "'yes'", ...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/transports/plugins/ssh.py#L293-L298
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
set_segm_end
(*args)
return _idaapi.set_segm_end(*args)
set_segm_end(ea, newend, flags) -> bool
set_segm_end(ea, newend, flags) -> bool
[ "set_segm_end", "(", "ea", "newend", "flags", ")", "-", ">", "bool" ]
def set_segm_end(*args): """ set_segm_end(ea, newend, flags) -> bool """ return _idaapi.set_segm_end(*args)
[ "def", "set_segm_end", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "set_segm_end", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L48083-L48087
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/models/fields/files.py
python
FileField.deconstruct
(self)
return name, path, args, kwargs
[]
def deconstruct(self): name, path, args, kwargs = super(FileField, self).deconstruct() if kwargs.get("max_length") == 100: del kwargs["max_length"] kwargs['upload_to'] = self.upload_to if self.storage is not default_storage: kwargs['storage'] = self.storage return name, path, args, kwargs
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "FileField", ",", "self", ")", ".", "deconstruct", "(", ")", "if", "kwargs", ".", "get", "(", "\"max_length\"", ")", "==", "100", ":", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/models/fields/files.py#L267-L274
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/rest/client/login.py
python
_load_sso_handlers
(hs: "HomeServer")
Ensure that the SSO handlers are loaded, if they are enabled by configuration. This is mostly useful to ensure that the CAS/SAML/OIDC handlers register themselves with the main SsoHandler. It's safe to call this multiple times.
Ensure that the SSO handlers are loaded, if they are enabled by configuration.
[ "Ensure", "that", "the", "SSO", "handlers", "are", "loaded", "if", "they", "are", "enabled", "by", "configuration", "." ]
def _load_sso_handlers(hs: "HomeServer") -> None: """Ensure that the SSO handlers are loaded, if they are enabled by configuration. This is mostly useful to ensure that the CAS/SAML/OIDC handlers register themselves with the main SsoHandler. It's safe to call this multiple times. """ if hs.config.cas.cas_enabled: hs.get_cas_handler() if hs.config.saml2.saml2_enabled: hs.get_saml_handler() if hs.config.oidc.oidc_enabled: hs.get_oidc_handler()
[ "def", "_load_sso_handlers", "(", "hs", ":", "\"HomeServer\"", ")", "->", "None", ":", "if", "hs", ".", "config", ".", "cas", ".", "cas_enabled", ":", "hs", ".", "get_cas_handler", "(", ")", "if", "hs", ".", "config", ".", "saml2", ".", "saml2_enabled", ...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/rest/client/login.py#L602-L615
williballenthin/INDXParse
454d70645b2d01f75ac4346bc2410fbe047d090c
carve_mft_records.py
python
sizeof_fmt
(num, suffix='B')
return "%.1f%s%s" % (num, 'Yi', suffix)
via: http://stackoverflow.com/a/1094933/87207
via: http://stackoverflow.com/a/1094933/87207
[ "via", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "1094933", "/", "87207" ]
def sizeof_fmt(num, suffix='B'): ''' via: http://stackoverflow.com/a/1094933/87207 ''' for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
[ "def", "sizeof_fmt", "(", "num", ",", "suffix", "=", "'B'", ")", ":", "for", "unit", "in", "[", "''", ",", "'Ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", ",", "'Pi'", ",", "'Ei'", ",", "'Zi'", "]", ":", "if", "abs", "(", "num", ")", "<", "102...
https://github.com/williballenthin/INDXParse/blob/454d70645b2d01f75ac4346bc2410fbe047d090c/carve_mft_records.py#L23-L32
DarLiner/Algorithm_Interview_Notes-Chinese
63c1fe158169f20921d8c418112129791732e562
_codes/my_tensorflow/src/utils/math_op.py
python
dot
(x, y)
Multiplies 2 tensors (and/or variables) and returns a *tensor*.
Multiplies 2 tensors (and/or variables) and returns a *tensor*.
[ "Multiplies", "2", "tensors", "(", "and", "/", "or", "variables", ")", "and", "returns", "a", "*", "tensor", "*", "." ]
def dot(x, y): """Multiplies 2 tensors (and/or variables) and returns a *tensor*. """ x_shape = list(x.get_shape()) y_shape = list(y.get_shape()) x_ndim = len(x_shape) y_ndim = len(y_shape) if x_ndim is not None and (x_ndim > 2 or y_ndim > 2): y_permute_dim = list(range(y_ndim)) y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim xt = tf.reshape(x, [-1, x_shape[-1]]) yt = tf.reshape(tf.transpose(y, perm=y_permute_dim), [y_shape[-2], -1]) return tf.reshape(tf.matmul(xt, yt), x_shape[:-1] + y_shape[:-2] + y_shape[-1:]) else: return tf.matmul(x, y)
[ "def", "dot", "(", "x", ",", "y", ")", ":", "x_shape", "=", "list", "(", "x", ".", "get_shape", "(", ")", ")", "y_shape", "=", "list", "(", "y", ".", "get_shape", "(", ")", ")", "x_ndim", "=", "len", "(", "x_shape", ")", "y_ndim", "=", "len", ...
https://github.com/DarLiner/Algorithm_Interview_Notes-Chinese/blob/63c1fe158169f20921d8c418112129791732e562/_codes/my_tensorflow/src/utils/math_op.py#L10-L26
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/bs4/element.py
python
PageElement.setup
(self, parent=None, previous_element=None, next_element=None, previous_sibling=None, next_sibling=None)
Sets up the initial relations between this element and other elements. :param parent: The parent of this element. :param previous_element: The element parsed immediately before this one. :param next_element: The element parsed immediately before this one. :param previous_sibling: The most recently encountered element on the same level of the parse tree as this one. :param previous_sibling: The next element to be encountered on the same level of the parse tree as this one.
Sets up the initial relations between this element and other elements.
[ "Sets", "up", "the", "initial", "relations", "between", "this", "element", "and", "other", "elements", "." ]
def setup(self, parent=None, previous_element=None, next_element=None, previous_sibling=None, next_sibling=None): """Sets up the initial relations between this element and other elements. :param parent: The parent of this element. :param previous_element: The element parsed immediately before this one. :param next_element: The element parsed immediately before this one. :param previous_sibling: The most recently encountered element on the same level of the parse tree as this one. :param previous_sibling: The next element to be encountered on the same level of the parse tree as this one. """ self.parent = parent self.previous_element = previous_element if previous_element is not None: self.previous_element.next_element = self self.next_element = next_element if self.next_element is not None: self.next_element.previous_element = self self.next_sibling = next_sibling if self.next_sibling is not None: self.next_sibling.previous_sibling = self if (previous_sibling is None and self.parent is not None and self.parent.contents): previous_sibling = self.parent.contents[-1] self.previous_sibling = previous_sibling if previous_sibling is not None: self.previous_sibling.next_sibling = self
[ "def", "setup", "(", "self", ",", "parent", "=", "None", ",", "previous_element", "=", "None", ",", "next_element", "=", "None", ",", "previous_sibling", "=", "None", ",", "next_sibling", "=", "None", ")", ":", "self", ".", "parent", "=", "parent", "self...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/bs4/element.py#L158-L197
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/users.py
python
UserCollection.get_or_create
(self, email: str, **kwargs)
Get the existing user with a given email address or create an unstored one :param kwargs: The properties of the user to get or create :return: The corresponding user object :raises: :class:`aiida.common.exceptions.MultipleObjectsError`, :class:`aiida.common.exceptions.NotExistent`
Get the existing user with a given email address or create an unstored one
[ "Get", "the", "existing", "user", "with", "a", "given", "email", "address", "or", "create", "an", "unstored", "one" ]
def get_or_create(self, email: str, **kwargs) -> Tuple[bool, 'User']: """Get the existing user with a given email address or create an unstored one :param kwargs: The properties of the user to get or create :return: The corresponding user object :raises: :class:`aiida.common.exceptions.MultipleObjectsError`, :class:`aiida.common.exceptions.NotExistent` """ try: return False, self.get(email=email) except exceptions.NotExistent: return True, User(backend=self.backend, email=email, **kwargs)
[ "def", "get_or_create", "(", "self", ",", "email", ":", "str", ",", "*", "*", "kwargs", ")", "->", "Tuple", "[", "bool", ",", "'User'", "]", ":", "try", ":", "return", "False", ",", "self", ".", "get", "(", "email", "=", "email", ")", "except", "...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/users.py#L39-L50
pycontribs/pyrax
a0c022981f76a4cba96a22ecc19bb52843ac4fbe
pyrax/object_storage.py
python
StorageObjectManager.set_metadata
(self, obj, metadata, clear=False, prefix=None)
Accepts a dictionary of metadata key/value pairs and updates the specified object metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Otherwise, the values passed here update the object's metadata. By default, the standard object metadata prefix ('X-Object-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must include a non-None prefix, such as an empty string.
Accepts a dictionary of metadata key/value pairs and updates the specified object metadata with them.
[ "Accepts", "a", "dictionary", "of", "metadata", "key", "/", "value", "pairs", "and", "updates", "the", "specified", "object", "metadata", "with", "them", "." ]
def set_metadata(self, obj, metadata, clear=False, prefix=None): """ Accepts a dictionary of metadata key/value pairs and updates the specified object metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Otherwise, the values passed here update the object's metadata. By default, the standard object metadata prefix ('X-Object-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must include a non-None prefix, such as an empty string. """ # Add the metadata prefix, if needed. if prefix is None: prefix = OBJECT_META_PREFIX massaged = _massage_metakeys(metadata, prefix) cname = utils.get_name(self.container) oname = utils.get_name(obj) new_meta = {} # Note that the API for object POST is the opposite of that for # container POST: for objects, all current metadata is deleted, # whereas for containers you need to set the values to an empty # string to delete them. if not clear: obj_meta = self.get_metadata(obj, prefix=prefix) new_meta = _massage_metakeys(obj_meta, prefix) utils.case_insensitive_update(new_meta, massaged) # Remove any empty values, since the object metadata API will # store them. to_pop = [] for key, val in six.iteritems(new_meta): if not val: to_pop.append(key) for key in to_pop: new_meta.pop(key) uri = "/%s/%s" % (cname, oname) resp, resp_body = self.api.method_post(uri, headers=new_meta)
[ "def", "set_metadata", "(", "self", ",", "obj", ",", "metadata", ",", "clear", "=", "False", ",", "prefix", "=", "None", ")", ":", "# Add the metadata prefix, if needed.", "if", "prefix", "is", "None", ":", "prefix", "=", "OBJECT_META_PREFIX", "massaged", "=",...
https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/object_storage.py#L2128-L2165
internetarchive/openlibrary
33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8
openlibrary/utils/__init__.py
python
dicthash
(d)
Dictionaries are not hashable. This function converts dictionary into nested tuples, so that it can hashed.
Dictionaries are not hashable. This function converts dictionary into nested tuples, so that it can hashed.
[ "Dictionaries", "are", "not", "hashable", ".", "This", "function", "converts", "dictionary", "into", "nested", "tuples", "so", "that", "it", "can", "hashed", "." ]
def dicthash(d): """Dictionaries are not hashable. This function converts dictionary into nested tuples, so that it can hashed. """ if isinstance(d, dict): return tuple((k, dicthash(d[k])) for k in sorted(d)) elif isinstance(d, list): return tuple(dicthash(v) for v in d) else: return d
[ "def", "dicthash", "(", "d", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "tuple", "(", "(", "k", ",", "dicthash", "(", "d", "[", "k", "]", ")", ")", "for", "k", "in", "sorted", "(", "d", ")", ")", "elif", "isinsta...
https://github.com/internetarchive/openlibrary/blob/33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8/openlibrary/utils/__init__.py#L118-L127
vshymanskyy/blynk-library-python
fee389f17e84b17e6655c571100f49688b453307
BlynkTimer.py
python
BlynkTimer._add
(self, func, **kwargs)
return timer
Inits Timer
Inits Timer
[ "Inits", "Timer" ]
def _add(self, func, **kwargs): '''Inits Timer''' timerId = next(self.ids) timer = Timer(timerId, func, **kwargs) self.timers.append(timer) return timer
[ "def", "_add", "(", "self", ",", "func", ",", "*", "*", "kwargs", ")", ":", "timerId", "=", "next", "(", "self", ".", "ids", ")", "timer", "=", "Timer", "(", "timerId", ",", "func", ",", "*", "*", "kwargs", ")", "self", ".", "timers", ".", "app...
https://github.com/vshymanskyy/blynk-library-python/blob/fee389f17e84b17e6655c571100f49688b453307/BlynkTimer.py#L28-L33
captainhammy/Houdini-Toolbox
a4e61c3c0296b3a3a153a8dd42297c316be1b0f3
python/houdini_toolbox/ui/paste/sources.py
python
HomeDirSource.copy_helper_widget
( self, *args, **kwargs )
return houdini_toolbox.ui.paste.helpers.HomeToolDirItemsCopyHelperWidget( self, *args, **kwargs )
Get the copy helper widget for this source. :return: The helper widget to copy items to this source.
Get the copy helper widget for this source.
[ "Get", "the", "copy", "helper", "widget", "for", "this", "source", "." ]
def copy_helper_widget( self, *args, **kwargs ) -> houdini_toolbox.ui.paste.helpers.HomeToolDirItemsCopyHelperWidget: # pylint: disable=arguments-differ """Get the copy helper widget for this source. :return: The helper widget to copy items to this source. """ return houdini_toolbox.ui.paste.helpers.HomeToolDirItemsCopyHelperWidget( self, *args, **kwargs )
[ "def", "copy_helper_widget", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "houdini_toolbox", ".", "ui", ".", "paste", ".", "helpers", ".", "HomeToolDirItemsCopyHelperWidget", ":", "# pylint: disable=arguments-differ", "return", "houdini_toolbox...
https://github.com/captainhammy/Houdini-Toolbox/blob/a4e61c3c0296b3a3a153a8dd42297c316be1b0f3/python/houdini_toolbox/ui/paste/sources.py#L233-L243
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/ObjectBrowser.py
python
ClassTreeItem.IsExpandable
(self)
return True
[]
def IsExpandable(self): return True
[ "def", "IsExpandable", "(", "self", ")", ":", "return", "True" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/ObjectBrowser.py#L61-L62
bashtage/linearmodels
9256269f01ff8c5f85e65342d66149a5636661b6
linearmodels/iv/absorbing.py
python
Interaction.sparse
(self)
r""" Construct a sparse interaction matrix Returns ------- csc_matrix Dummy interaction constructed from the cartesian product of the categories and each of the continuous variables. Notes ----- The number of columns in `dummy_interact` is .. math:: ncont \times \prod_{i=1}^{ncat} |c_i| where :math:`|c_i|` is the number distinct categories in column i.
r""" Construct a sparse interaction matrix
[ "r", "Construct", "a", "sparse", "interaction", "matrix" ]
def sparse(self) -> sp.csc_matrix: r""" Construct a sparse interaction matrix Returns ------- csc_matrix Dummy interaction constructed from the cartesian product of the categories and each of the continuous variables. Notes ----- The number of columns in `dummy_interact` is .. math:: ncont \times \prod_{i=1}^{ncat} |c_i| where :math:`|c_i|` is the number distinct categories in column i. """ if self.cat.shape[1] and self.cont.shape[1]: out = [] for col in self.cont: out.append( category_continuous_interaction( self.cat, self.cont[col], precondition=False ) ) return sp.hstack(out, format="csc") elif self.cat.shape[1]: return category_interaction(category_product(self.cat), precondition=False) elif self.cont.shape[1]: return sp.csc_matrix(self._cont_data.ndarray) else: # empty interaction return sp.csc_matrix(empty((self._cat_data.shape[0], 0)))
[ "def", "sparse", "(", "self", ")", "->", "sp", ".", "csc_matrix", ":", "if", "self", ".", "cat", ".", "shape", "[", "1", "]", "and", "self", ".", "cont", ".", "shape", "[", "1", "]", ":", "out", "=", "[", "]", "for", "col", "in", "self", ".",...
https://github.com/bashtage/linearmodels/blob/9256269f01ff8c5f85e65342d66149a5636661b6/linearmodels/iv/absorbing.py#L376-L410
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ttypes.py
python
TableMeta.__ne__
(self, other)
return not (self == other)
[]
def __ne__(self, other): return not (self == other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "(", "self", "==", "other", ")" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ttypes.py#L10838-L10839
meraki/dashboard-api-python
aef5e6fe5d23a40d435d5c64ff30580a28af07f1
meraki_v0/aio/api/licenses.py
python
AsyncLicenses.moveOrganizationLicenses
(self, organizationId: str, destOrganizationId: str, licenseIds: list)
return await self._session.post(metadata, resource, payload)
**Move licenses to another organization. This will also move any devices that the licenses are assigned to** https://developer.cisco.com/meraki/api/#!move-organization-licenses - organizationId (string) - destOrganizationId (string): The ID of the organization to move the licenses to - licenseIds (array): A list of IDs of licenses to move to the new organization
**Move licenses to another organization. This will also move any devices that the licenses are assigned to** https://developer.cisco.com/meraki/api/#!move-organization-licenses - organizationId (string) - destOrganizationId (string): The ID of the organization to move the licenses to - licenseIds (array): A list of IDs of licenses to move to the new organization
[ "**", "Move", "licenses", "to", "another", "organization", ".", "This", "will", "also", "move", "any", "devices", "that", "the", "licenses", "are", "assigned", "to", "**", "https", ":", "//", "developer", ".", "cisco", ".", "com", "/", "meraki", "/", "ap...
async def moveOrganizationLicenses(self, organizationId: str, destOrganizationId: str, licenseIds: list): """ **Move licenses to another organization. This will also move any devices that the licenses are assigned to** https://developer.cisco.com/meraki/api/#!move-organization-licenses - organizationId (string) - destOrganizationId (string): The ID of the organization to move the licenses to - licenseIds (array): A list of IDs of licenses to move to the new organization """ kwargs = locals() metadata = { 'tags': ['Licenses'], 'operation': 'moveOrganizationLicenses', } resource = f'/organizations/{organizationId}/licenses/move' body_params = ['destOrganizationId', 'licenseIds'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.post(metadata, resource, payload)
[ "async", "def", "moveOrganizationLicenses", "(", "self", ",", "organizationId", ":", "str", ",", "destOrganizationId", ":", "str", ",", "licenseIds", ":", "list", ")", ":", "kwargs", "=", "locals", "(", ")", "metadata", "=", "{", "'tags'", ":", "[", "'Lice...
https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki_v0/aio/api/licenses.py#L64-L85
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Convert/convertChemProt.py
python
openOutFile
(setName, outPath, fileType, fileTypes, outFiles, openFiles)
return None
[]
def openOutFile(setName, outPath, fileType, fileTypes, outFiles, openFiles): if fileType in fileTypes: if fileType not in outFiles[setName]: if outPath.endswith(".tsv"): filePath = outPath if not os.path.exists(os.path.dirname(outPath)): os.makedirs(os.path.dirname(outPath)) else: filePath = os.path.join(outPath, setName + "_" + fileType + ".tsv") if not os.path.exists(outPath): os.makedirs(outPath) if filePath not in openFiles: print >> sys.stderr, "Opening output file", filePath openFiles[filePath] = codecs.open(filePath, "wt", "utf-8") outFiles[setName][fileType] = openFiles[filePath] return outFiles[setName][fileType] return None
[ "def", "openOutFile", "(", "setName", ",", "outPath", ",", "fileType", ",", "fileTypes", ",", "outFiles", ",", "openFiles", ")", ":", "if", "fileType", "in", "fileTypes", ":", "if", "fileType", "not", "in", "outFiles", "[", "setName", "]", ":", "if", "ou...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Convert/convertChemProt.py#L167-L183
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/idserver.py
python
split
(string, separator="-")
return string.split(separator)
split a string on the given separator
split a string on the given separator
[ "split", "a", "string", "on", "the", "given", "separator" ]
def split(string, separator="-"): """ split a string on the given separator """ if not isinstance(string, basestring): return [] return string.split(separator)
[ "def", "split", "(", "string", ",", "separator", "=", "\"-\"", ")", ":", "if", "not", "isinstance", "(", "string", ",", "basestring", ")", ":", "return", "[", "]", "return", "string", ".", "split", "(", "separator", ")" ]
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/idserver.py#L172-L177
cornellius-gp/gpytorch
61f643eb8b487aef332c818f661fbcdb1df576ca
gpytorch/lazy/lazy_tensor.py
python
LazyTensor.numel
(self)
return self.shape.numel()
Returns the number of elements
Returns the number of elements
[ "Returns", "the", "number", "of", "elements" ]
def numel(self): """ Returns the number of elements """ return self.shape.numel()
[ "def", "numel", "(", "self", ")", ":", "return", "self", ".", "shape", ".", "numel", "(", ")" ]
https://github.com/cornellius-gp/gpytorch/blob/61f643eb8b487aef332c818f661fbcdb1df576ca/gpytorch/lazy/lazy_tensor.py#L1462-L1466
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py
python
Client.renew_delegation_token
(self, token_str_form)
return self.recv_renew_delegation_token()
Parameters: - token_str_form
Parameters: - token_str_form
[ "Parameters", ":", "-", "token_str_form" ]
def renew_delegation_token(self, token_str_form): """ Parameters: - token_str_form """ self.send_renew_delegation_token(token_str_form) return self.recv_renew_delegation_token()
[ "def", "renew_delegation_token", "(", "self", ",", "token_str_form", ")", ":", "self", ".", "send_renew_delegation_token", "(", "token_str_form", ")", "return", "self", ".", "recv_renew_delegation_token", "(", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py#L5816-L5823
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/markdown/__init__.py
python
markdownFromFile
(input = None, output = None, extensions = [], encoding = None, safe_mode = False, output_format = DEFAULT_OUTPUT_FORMAT)
Read markdown code from a file and write it to a file or a stream.
Read markdown code from a file and write it to a file or a stream.
[ "Read", "markdown", "code", "from", "a", "file", "and", "write", "it", "to", "a", "file", "or", "a", "stream", "." ]
def markdownFromFile(input = None, output = None, extensions = [], encoding = None, safe_mode = False, output_format = DEFAULT_OUTPUT_FORMAT): """Read markdown code from a file and write it to a file or a stream.""" md = Markdown(extensions=load_extensions(extensions), safe_mode=safe_mode, output_format=output_format) md.convertFile(input, output, encoding)
[ "def", "markdownFromFile", "(", "input", "=", "None", ",", "output", "=", "None", ",", "extensions", "=", "[", "]", ",", "encoding", "=", "None", ",", "safe_mode", "=", "False", ",", "output_format", "=", "DEFAULT_OUTPUT_FORMAT", ")", ":", "md", "=", "Ma...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/markdown/__init__.py#L601-L611
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/numbers.py
python
Integral.numerator
(self)
return +self
Integers are their own numerators.
Integers are their own numerators.
[ "Integers", "are", "their", "own", "numerators", "." ]
def numerator(self): """Integers are their own numerators.""" return +self
[ "def", "numerator", "(", "self", ")", ":", "return", "+", "self" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/numbers.py#L380-L382
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/campaign_service/client.py
python
CampaignServiceClient.common_folder_path
(folder: str,)
return "folders/{folder}".format(folder=folder,)
Return a fully-qualified folder string.
Return a fully-qualified folder string.
[ "Return", "a", "fully", "-", "qualified", "folder", "string", "." ]
def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,)
[ "def", "common_folder_path", "(", "folder", ":", "str", ",", ")", "->", "str", ":", "return", "\"folders/{folder}\"", ".", "format", "(", "folder", "=", "folder", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/campaign_service/client.py#L308-L310
yaohungt/Multimodal-Transformer
a670936824ee722c8494fd98d204977a1d663c7a
modules/transformer.py
python
TransformerEncoder.max_positions
(self)
return min(self.max_source_positions, self.embed_positions.max_positions())
Maximum input length supported by the encoder.
Maximum input length supported by the encoder.
[ "Maximum", "input", "length", "supported", "by", "the", "encoder", "." ]
def max_positions(self): """Maximum input length supported by the encoder.""" if self.embed_positions is None: return self.max_source_positions return min(self.max_source_positions, self.embed_positions.max_positions())
[ "def", "max_positions", "(", "self", ")", ":", "if", "self", ".", "embed_positions", "is", "None", ":", "return", "self", ".", "max_source_positions", "return", "min", "(", "self", ".", "max_source_positions", ",", "self", ".", "embed_positions", ".", "max_pos...
https://github.com/yaohungt/Multimodal-Transformer/blob/a670936824ee722c8494fd98d204977a1d663c7a/modules/transformer.py#L92-L96
karanchahal/distiller
a17ec06cbeafcdd2aea19d7c7663033c951392f5
distill_archive/research_seed/baselines/segmentation/utils.py
python
is_main_process
()
return get_rank() == 0
[]
def is_main_process(): return get_rank() == 0
[ "def", "is_main_process", "(", ")", ":", "return", "get_rank", "(", ")", "==", "0" ]
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/distill_archive/research_seed/baselines/segmentation/utils.py#L268-L269
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/site-packages/win32/lib/win32evtlogutil.py
python
ReportEvent
(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None)
Report an event for a previously added event source.
Report an event for a previously added event source.
[ "Report", "an", "event", "for", "a", "previously", "added", "event", "source", "." ]
def ReportEvent(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None): """Report an event for a previously added event source. """ # Get a handle to the Application event log hAppLog = win32evtlog.RegisterEventSource(None, appName) # Now report the event, which will add this event to the event log */ win32evtlog.ReportEvent(hAppLog, # event-log handle \ eventType, eventCategory, eventID, sid, strings, data) win32evtlog.DeregisterEventSource(hAppLog);
[ "def", "ReportEvent", "(", "appName", ",", "eventID", ",", "eventCategory", "=", "0", ",", "eventType", "=", "win32evtlog", ".", "EVENTLOG_ERROR_TYPE", ",", "strings", "=", "None", ",", "data", "=", "None", ",", "sid", "=", "None", ")", ":", "# Get a handl...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/site-packages/win32/lib/win32evtlogutil.py#L67-L82
pyamg/pyamg
e3fb6feaad2358e681f2f4affae3205bfe9a2350
pyamg/relaxation/smoothing.py
python
setup_schwarz
(lvl, iterations=DEFAULT_NITER, subdomain=None, subdomain_ptr=None, inv_subblock=None, inv_subblock_ptr=None, sweep=DEFAULT_SWEEP)
return smoother
Set up Schwarz.
Set up Schwarz.
[ "Set", "up", "Schwarz", "." ]
def setup_schwarz(lvl, iterations=DEFAULT_NITER, subdomain=None, subdomain_ptr=None, inv_subblock=None, inv_subblock_ptr=None, sweep=DEFAULT_SWEEP): """Set up Schwarz.""" matrix_asformat(lvl, 'A', 'csr') lvl.Acsr.sort_indices() subdomain, subdomain_ptr, inv_subblock, inv_subblock_ptr = \ relaxation.schwarz_parameters(lvl.Acsr, subdomain, subdomain_ptr, inv_subblock, inv_subblock_ptr) def smoother(A, x, b): relaxation.schwarz(lvl.Acsr, x, b, iterations=iterations, subdomain=subdomain, subdomain_ptr=subdomain_ptr, inv_subblock=inv_subblock, inv_subblock_ptr=inv_subblock_ptr, sweep=sweep) return smoother
[ "def", "setup_schwarz", "(", "lvl", ",", "iterations", "=", "DEFAULT_NITER", ",", "subdomain", "=", "None", ",", "subdomain_ptr", "=", "None", ",", "inv_subblock", "=", "None", ",", "inv_subblock_ptr", "=", "None", ",", "sweep", "=", "DEFAULT_SWEEP", ")", ":...
https://github.com/pyamg/pyamg/blob/e3fb6feaad2358e681f2f4affae3205bfe9a2350/pyamg/relaxation/smoothing.py#L461-L477
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/news/database.py
python
INewsStorage.listGroupRequest
(group)
Returns a deferred whose callback will be passed a two-tuple of (group name, [article indices])
Returns a deferred whose callback will be passed a two-tuple of (group name, [article indices])
[ "Returns", "a", "deferred", "whose", "callback", "will", "be", "passed", "a", "two", "-", "tuple", "of", "(", "group", "name", "[", "article", "indices", "]", ")" ]
def listGroupRequest(group): """ Returns a deferred whose callback will be passed a two-tuple of (group name, [article indices]) """
[ "def", "listGroupRequest", "(", "group", ")", ":" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/news/database.py#L145-L149
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/tlinerender.py
python
TimeLineRenderer.__init__
(self)
[]
def __init__(self): self.segments = [] self.press_frame = -1 self.release_frame = -1 self.drag_on = False
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "segments", "=", "[", "]", "self", ".", "press_frame", "=", "-", "1", "self", ".", "release_frame", "=", "-", "1", "self", ".", "drag_on", "=", "False" ]
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/tlinerender.py#L245-L251
AstusRush/AMaDiA
e2ad87318d9dd30bc24428e05c29cb32a29c83aa
External_Libraries/python_control_master/control/lti.py
python
isctime
(sys, strict=False)
return False
Check to see if a system is a continuous-time system Parameters ---------- sys : LTI system System to be checked strict: bool (default = False) If strict is True, make sure that timebase is not None
Check to see if a system is a continuous-time system
[ "Check", "to", "see", "if", "a", "system", "is", "a", "continuous", "-", "time", "system" ]
def isctime(sys, strict=False): """ Check to see if a system is a continuous-time system Parameters ---------- sys : LTI system System to be checked strict: bool (default = False) If strict is True, make sure that timebase is not None """ # Check to see if this is a constant if isinstance(sys, (int, float, complex, np.number)): # OK as long as strict checking is off return True if not strict else False # Check for a transfer function or state space object if isinstance(sys, LTI): return sys.isctime(strict) # Check to see if object has a dt object if hasattr(sys, 'dt'): # If no timebase is given, answer depends on strict flag if sys.dt is None: return True if not strict else False return sys.dt == 0 # Got passed something we don't recognize return False
[ "def", "isctime", "(", "sys", ",", "strict", "=", "False", ")", ":", "# Check to see if this is a constant", "if", "isinstance", "(", "sys", ",", "(", "int", ",", "float", ",", "complex", ",", "np", ".", "number", ")", ")", ":", "# OK as long as strict check...
https://github.com/AstusRush/AMaDiA/blob/e2ad87318d9dd30bc24428e05c29cb32a29c83aa/External_Libraries/python_control_master/control/lti.py#L238-L267
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/distutils/command/sdist.py
python
sdist.prune_file_list
(self)
Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
[ "Prune", "off", "branches", "that", "might", "slip", "into", "the", "file", "list", "as", "created", "by", "read_template", "()", "but", "really", "don", "t", "belong", "there", ":", "*", "the", "build", "tree", "(", "typically", "build", ")", "*", "the"...
def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
[ "def", "prune_file_list", "(", "self", ")", ":", "build", "=", "self", ".", "get_finalized_command", "(", "'build'", ")", "base_dir", "=", "self", ".", "distribution", ".", "get_fullname", "(", ")", "self", ".", "filelist", ".", "exclude_pattern", "(", "None...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/distutils/command/sdist.py#L353-L375
spytensor/detect_steel_bar
5ddcca2c4e4270cf06bd6b35af5f95e14dd9a335
retinanet/anchors.py
python
generate_anchors
(base_size=16, ratios=None, scales=None)
return anchors
Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window.
Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window.
[ "Generate", "anchor", "(", "reference", ")", "windows", "by", "enumerating", "aspect", "ratios", "X", "scales", "w", ".", "r", ".", "t", ".", "a", "reference", "window", "." ]
def generate_anchors(base_size=16, ratios=None, scales=None): """ Generate anchor (reference) windows by enumerating aspect ratios X scales w.r.t. a reference window. """ if ratios is None: ratios = np.array([0.5, 1, 2]) if scales is None: scales = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]) num_anchors = len(ratios) * len(scales) # initialize output anchors anchors = np.zeros((num_anchors, 4)) # scale base_size anchors[:, 2:] = base_size * np.tile(scales, (2, len(ratios))).T # compute areas of anchors areas = anchors[:, 2] * anchors[:, 3] # correct for ratios anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales))) anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales)) # transform from (x_ctr, y_ctr, w, h) -> (x1, y1, x2, y2) anchors[:, 0::2] -= np.tile(anchors[:, 2] * 0.5, (2, 1)).T anchors[:, 1::2] -= np.tile(anchors[:, 3] * 0.5, (2, 1)).T return anchors
[ "def", "generate_anchors", "(", "base_size", "=", "16", ",", "ratios", "=", "None", ",", "scales", "=", "None", ")", ":", "if", "ratios", "is", "None", ":", "ratios", "=", "np", ".", "array", "(", "[", "0.5", ",", "1", ",", "2", "]", ")", "if", ...
https://github.com/spytensor/detect_steel_bar/blob/5ddcca2c4e4270cf06bd6b35af5f95e14dd9a335/retinanet/anchors.py#L39-L70
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/tools/ete_build_lib/scheduler.py
python
background_job_launcher
(job_queue, run_detached, schedule_time, max_cores)
[]
def background_job_launcher(job_queue, run_detached, schedule_time, max_cores): running_jobs = {} visited_ids = set() # job_queue = [jid, cores, cmd, status_file] GLOBALS["myid"] = 'back_launcher' finished_states = set("ED") cores_used = 0 dups = set() pending_jobs = deque() try: while True: launched = 0 done_jobs = set() cores_used = 0 for jid, (cores, cmd, st_file, pid) in six.iteritems(running_jobs): process_done = pid.poll() if pid else None try: st = open(st_file).read(1) except IOError: st = "?" #print pid.poll(), pid.pid, st if st in finished_states: done_jobs.add(jid) elif process_done is not None and st == "R": # check if a running job is actually running print("LOST PROCESS", pid, jid) ST=open(st_file, "w"); ST.write("E"); ST.flush(); ST.close() done_jobs.add(jid) else: cores_used += cores for d in done_jobs: del running_jobs[d] cores_avail = max_cores - cores_used for i in range(cores_avail): try: jid, cores, cmd, st_file = job_queue.get(False) except QueueEmpty: pass else: pending_jobs.append([jid, cores, cmd, st_file]) if pending_jobs and pending_jobs[0][1] <= cores_avail: jid, cores, cmd, st_file = pending_jobs.popleft() if jid in visited_ids: dups.add(jid) print("DUPLICATED execution!!!!!!!!!!!! This should not occur!", jid) continue elif pending_jobs: log.log(28, "@@8:waiting for %s cores" %pending_jobs[0][1]) break else: break ST=open(st_file, "w"); ST.write("R"); ST.flush(); ST.close() try: if run_detached: cmd += " &" running_proc = None subprocess.call(cmd, shell=True) else: # create a process group, so I can kill the thread if necessary running_proc = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) except Exception as e: print(e) ST=open(st_file, "w"); ST.write("E"); ST.flush(); ST.close() else: launched += 1 running_jobs[jid] = [cores, cmd, st_file, running_proc] cores_avail -= cores cores_used += cores visited_ids.add(jid) try: waiting_jobs = job_queue.qsize() + len(pending_jobs) except NotImplementedError: # OSX does not support qsize waiting_jobs = len(pending_jobs) log.log(28, "@@8:Launched@@1: %s jobs. %d(R), %s(W). Cores usage: %s/%s", launched, len(running_jobs), waiting_jobs, cores_used, max_cores) for _d in dups: print("duplicate bug", _d) sleep(schedule_time) except: if len(running_jobs): print(' Killing %s running jobs...' %len(running_jobs), file=sys.stderr) for jid, (cores, cmd, st_file, pid) in six.iteritems(running_jobs): if pid: #print >>sys.stderr, ".", #sys.stderr.flush() try: os.killpg(pid.pid, signal.SIGTERM) except: print("Ooops, the process", pid.pid, "could not be terminated!") pass try: open(st_file, "w").write("E") except: print("Ooops,", st_file, "could not be labeled as Error task. Please remove file before resuming the analysis.") sys.exit(0)
[ "def", "background_job_launcher", "(", "job_queue", ",", "run_detached", ",", "schedule_time", ",", "max_cores", ")", ":", "running_jobs", "=", "{", "}", "visited_ids", "=", "set", "(", ")", "# job_queue = [jid, cores, cmd, status_file]", "GLOBALS", "[", "\"myid\"", ...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/tools/ete_build_lib/scheduler.py#L496-L598
Cog-Creators/Red-DiscordBot
b05933274a11fb097873ab0d1b246d37b06aa306
redbot/core/commands/commands.py
python
CogCommandMixin.set_default_rule
(self, rule: Optional[bool], guild_id: int)
Set the default rule for this cog or command. Parameters ---------- rule : Optional[bool] The rule to set as default. If ``True`` for allow, ``False`` for deny and ``None`` for normal. guild_id : int The guild to set the default rule in. When ``0``, this will set the global default rule.
Set the default rule for this cog or command.
[ "Set", "the", "default", "rule", "for", "this", "cog", "or", "command", "." ]
def set_default_rule(self, rule: Optional[bool], guild_id: int) -> None: """Set the default rule for this cog or command. Parameters ---------- rule : Optional[bool] The rule to set as default. If ``True`` for allow, ``False`` for deny and ``None`` for normal. guild_id : int The guild to set the default rule in. When ``0``, this will set the global default rule. """ if rule is None: self.clear_rule_for(Requires.DEFAULT, guild_id=guild_id) elif rule is True: self.allow_for(Requires.DEFAULT, guild_id=guild_id) elif rule is False: self.deny_to(Requires.DEFAULT, guild_id=guild_id)
[ "def", "set_default_rule", "(", "self", ",", "rule", ":", "Optional", "[", "bool", "]", ",", "guild_id", ":", "int", ")", "->", "None", ":", "if", "rule", "is", "None", ":", "self", ".", "clear_rule_for", "(", "Requires", ".", "DEFAULT", ",", "guild_id...
https://github.com/Cog-Creators/Red-DiscordBot/blob/b05933274a11fb097873ab0d1b246d37b06aa306/redbot/core/commands/commands.py#L234-L252
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/xmlrpclib.py
python
gzip_encode
(data)
return encoded
data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952
data -> gzip encoded data
[ "data", "-", ">", "gzip", "encoded", "data" ]
def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO() gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) gzf.write(data) gzf.close() encoded = f.getvalue() f.close() return encoded
[ "def", "gzip_encode", "(", "data", ")", ":", "if", "not", "gzip", ":", "raise", "NotImplementedError", "f", "=", "StringIO", ".", "StringIO", "(", ")", "gzf", "=", "gzip", ".", "GzipFile", "(", "mode", "=", "\"wb\"", ",", "fileobj", "=", "f", ",", "c...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/xmlrpclib.py#L1156-L1169
tweecode/twine
45e6350a2b813ec4282440b78f901cf377ead1a9
app.py
python
App.openOnStartup
(self)
return True
Opens any files that were passed via argv[1:]. Returns whether anything was opened.
Opens any files that were passed via argv[1:]. Returns whether anything was opened.
[ "Opens", "any", "files", "that", "were", "passed", "via", "argv", "[", "1", ":", "]", ".", "Returns", "whether", "anything", "was", "opened", "." ]
def openOnStartup(self): """ Opens any files that were passed via argv[1:]. Returns whether anything was opened. """ if len(sys.argv) is 1: return False for file in sys.argv[1:]: self.open(file) return True
[ "def", "openOnStartup", "(", "self", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "is", "1", ":", "return", "False", "for", "file", "in", "sys", ".", "argv", "[", "1", ":", "]", ":", "self", ".", "open", "(", "file", ")", "return", "Tru...
https://github.com/tweecode/twine/blob/45e6350a2b813ec4282440b78f901cf377ead1a9/app.py#L125-L136
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/google_maps/device_tracker.py
python
GoogleMapsScanner.__init__
(self, hass, config: ConfigType, see)
Initialize the scanner.
Initialize the scanner.
[ "Initialize", "the", "scanner", "." ]
def __init__(self, hass, config: ConfigType, see) -> None: """Initialize the scanner.""" self.see = see self.username = config[CONF_USERNAME] self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY] self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60) self._prev_seen: dict[str, str] = {} credfile = f"{hass.config.path(CREDENTIALS_FILE)}.{slugify(self.username)}" try: self.service = Service(credfile, self.username) self._update_info() track_time_interval(hass, self._update_info, self.scan_interval) self.success_init = True except InvalidCookies: _LOGGER.error( "The cookie file provided does not provide a valid session. Please create another one and try again" ) self.success_init = False
[ "def", "__init__", "(", "self", ",", "hass", ",", "config", ":", "ConfigType", ",", "see", ")", "->", "None", ":", "self", ".", "see", "=", "see", "self", ".", "username", "=", "config", "[", "CONF_USERNAME", "]", "self", ".", "max_gps_accuracy", "=", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/google_maps/device_tracker.py#L64-L85
canonical/cloud-init
dc1aabfca851e520693c05322f724bd102c76364
cloudinit/distros/gentoo.py
python
convert_resolv_conf
(settings)
return result
Returns a settings string formatted for resolv.conf.
Returns a settings string formatted for resolv.conf.
[ "Returns", "a", "settings", "string", "formatted", "for", "resolv", ".", "conf", "." ]
def convert_resolv_conf(settings): """Returns a settings string formatted for resolv.conf.""" result = "" if isinstance(settings, list): for ns in settings: result += "nameserver %s\n" % ns return result
[ "def", "convert_resolv_conf", "(", "settings", ")", ":", "result", "=", "\"\"", "if", "isinstance", "(", "settings", ",", "list", ")", ":", "for", "ns", "in", "settings", ":", "result", "+=", "\"nameserver %s\\n\"", "%", "ns", "return", "result" ]
https://github.com/canonical/cloud-init/blob/dc1aabfca851e520693c05322f724bd102c76364/cloudinit/distros/gentoo.py#L239-L245
openstack/glance
502fa0ffc8970c087c5924742231812c0da6a114
glance/db/sqlalchemy/api.py
python
metadef_property_get
(context, namespace_name, property_name, session=None)
return metadef_property_api.get( context, namespace_name, property_name, session)
Get a metadef property or raise if it does not exist.
Get a metadef property or raise if it does not exist.
[ "Get", "a", "metadef", "property", "or", "raise", "if", "it", "does", "not", "exist", "." ]
def metadef_property_get(context, namespace_name, property_name, session=None): """Get a metadef property or raise if it does not exist.""" session = session or get_session() return metadef_property_api.get( context, namespace_name, property_name, session)
[ "def", "metadef_property_get", "(", "context", ",", "namespace_name", ",", "property_name", ",", "session", "=", "None", ")", ":", "session", "=", "session", "or", "get_session", "(", ")", "return", "metadef_property_api", ".", "get", "(", "context", ",", "nam...
https://github.com/openstack/glance/blob/502fa0ffc8970c087c5924742231812c0da6a114/glance/db/sqlalchemy/api.py#L2056-L2061
DataBiosphere/toil
2e148eee2114ece8dcc3ec8a83f36333266ece0d
src/toil/lib/misc.py
python
CalledProcessErrorStderr.__str__
(self)
[]
def __str__(self) -> str: if (self.returncode < 0) or (self.stderr is None): return str(super()) else: err = self.stderr if isinstance(self.stderr, str) else self.stderr.decode("ascii", errors="replace") return "Command '%s' exit status %d: %s" % (self.cmd, self.returncode, err)
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "if", "(", "self", ".", "returncode", "<", "0", ")", "or", "(", "self", ".", "stderr", "is", "None", ")", ":", "return", "str", "(", "super", "(", ")", ")", "else", ":", "err", "=", "self", ...
https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/lib/misc.py#L80-L85
dropbox/stone
b7b64320631b3a4d2f10681dca64e0718ebe68ee
ez_setup.py
python
get_zip_class
()
return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \ ContextualZipFile
Supplement ZipFile class to support context manager for Python 2.6
Supplement ZipFile class to support context manager for Python 2.6
[ "Supplement", "ZipFile", "class", "to", "support", "context", "manager", "for", "Python", "2", ".", "6" ]
def get_zip_class(): """ Supplement ZipFile class to support context manager for Python 2.6 """ class ContextualZipFile(zipfile.ZipFile): def __enter__(self): return self def __exit__(self, type, value, traceback): self.close return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \ ContextualZipFile
[ "def", "get_zip_class", "(", ")", ":", "class", "ContextualZipFile", "(", "zipfile", ".", "ZipFile", ")", ":", "def", "__enter__", "(", "self", ")", ":", "return", "self", "def", "__exit__", "(", "self", ",", "type", ",", "value", ",", "traceback", ")", ...
https://github.com/dropbox/stone/blob/b7b64320631b3a4d2f10681dca64e0718ebe68ee/ez_setup.py#L67-L77
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/xml/sax/handler.py
python
ContentHandler.characters
(self, content)
Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.
Receive notification of character data.
[ "Receive", "notification", "of", "character", "data", "." ]
def characters(self, content): """Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information."""
[ "def", "characters", "(", "self", ",", "content", ")", ":" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/xml/sax/handler.py#L158-L166
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/nbformat/v4/convert.py
python
from_mime_key
(d)
return d2
convert dict with mime-type keys to v3 aliases
convert dict with mime-type keys to v3 aliases
[ "convert", "dict", "with", "mime", "-", "type", "keys", "to", "v3", "aliases" ]
def from_mime_key(d): """convert dict with mime-type keys to v3 aliases""" d2 = {} for alias, mime in _mime_map.items(): if mime in d: d2[alias] = d[mime] return d2
[ "def", "from_mime_key", "(", "d", ")", ":", "d2", "=", "{", "}", "for", "alias", ",", "mime", "in", "_mime_map", ".", "items", "(", ")", ":", "if", "mime", "in", "d", ":", "d2", "[", "alias", "]", "=", "d", "[", "mime", "]", "return", "d2" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/nbformat/v4/convert.py#L152-L158
moses-palmer/pynput
57504699b4b9a889bf6e15a0c0b9ed654a5677e1
tools/make-release.py
python
update_info
(version)
Updates the version information in ``._info.`` :param tuple version: The version to set.
Updates the version information in ``._info.``
[ "Updates", "the", "version", "information", "in", ".", "_info", "." ]
def update_info(version): """Updates the version information in ``._info.`` :param tuple version: The version to set. """ gsub( os.path.join(PACKAGE_DIR, '_info.py'), re.compile(r'__version__\s*=\s*(\([0-9]+(\s*,\s*[0-9]+)*\))'), 1, repr(version))
[ "def", "update_info", "(", "version", ")", ":", "gsub", "(", "os", ".", "path", ".", "join", "(", "PACKAGE_DIR", ",", "'_info.py'", ")", ",", "re", ".", "compile", "(", "r'__version__\\s*=\\s*(\\([0-9]+(\\s*,\\s*[0-9]+)*\\))'", ")", ",", "1", ",", "repr", "(...
https://github.com/moses-palmer/pynput/blob/57504699b4b9a889bf6e15a0c0b9ed654a5677e1/tools/make-release.py#L55-L64
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/flows/general/timeline.py
python
ProtoEntries
( client_id: Text, flow_id: Text, )
return timeline.DeserializeTimelineEntryProtoStream(blobs)
Retrieves timeline entries for the specified flow. Args: client_id: An identifier of a client of the flow to retrieve the blobs for. flow_id: An identifier of the flow to retrieve the blobs for. Returns: An iterator over timeline entries protos for the specified flow.
Retrieves timeline entries for the specified flow.
[ "Retrieves", "timeline", "entries", "for", "the", "specified", "flow", "." ]
def ProtoEntries( client_id: Text, flow_id: Text, ) -> Iterator[timeline_pb2.TimelineEntry]: """Retrieves timeline entries for the specified flow. Args: client_id: An identifier of a client of the flow to retrieve the blobs for. flow_id: An identifier of the flow to retrieve the blobs for. Returns: An iterator over timeline entries protos for the specified flow. """ blobs = Blobs(client_id, flow_id) return timeline.DeserializeTimelineEntryProtoStream(blobs)
[ "def", "ProtoEntries", "(", "client_id", ":", "Text", ",", "flow_id", ":", "Text", ",", ")", "->", "Iterator", "[", "timeline_pb2", ".", "TimelineEntry", "]", ":", "blobs", "=", "Blobs", "(", "client_id", ",", "flow_id", ")", "return", "timeline", ".", "...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/flows/general/timeline.py#L81-L95
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/PreferencesDialog.py
python
General.VideoTimestampChecked
( self )
[]
def VideoTimestampChecked ( self ): PreferencesDialog.VideoTimestamp = self.VideoTimestampVar.get()
[ "def", "VideoTimestampChecked", "(", "self", ")", ":", "PreferencesDialog", ".", "VideoTimestamp", "=", "self", ".", "VideoTimestampVar", ".", "get", "(", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/PreferencesDialog.py#L299-L300
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/edit.py
python
_ripple_trim_end_undo
(self)
[]
def _ripple_trim_end_undo(self): _remove_clip(self.track, self.index) _insert_clip(self.track, self.clip, self.index, self.clip.clip_in, self.clip.clip_out - self.edit_delta) _ripple_trim_blanks_undo(self)
[ "def", "_ripple_trim_end_undo", "(", "self", ")", ":", "_remove_clip", "(", "self", ".", "track", ",", "self", ".", "index", ")", "_insert_clip", "(", "self", ".", "track", ",", "self", ".", "clip", ",", "self", ".", "index", ",", "self", ".", "clip", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/edit.py#L1450-L1455
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
is_type_ptr_or_array
(*args)
return _idaapi.is_type_ptr_or_array(*args)
is_type_ptr_or_array(t) -> bool
is_type_ptr_or_array(t) -> bool
[ "is_type_ptr_or_array", "(", "t", ")", "-", ">", "bool" ]
def is_type_ptr_or_array(*args): """ is_type_ptr_or_array(t) -> bool """ return _idaapi.is_type_ptr_or_array(*args)
[ "def", "is_type_ptr_or_array", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "is_type_ptr_or_array", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L28418-L28422
intrig-unicamp/mininet-wifi
3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba
mn_wifi/sumo/traci/_vehicletype.py
python
VehicleTypeDomain.setDecel
(self, typeID, decel)
setDecel(string, double) -> None Sets the maximal comfortable deceleration in m/s^2 of vehicles of this type.
setDecel(string, double) -> None Sets the maximal comfortable deceleration in m/s^2 of vehicles of this type.
[ "setDecel", "(", "string", "double", ")", "-", ">", "None", "Sets", "the", "maximal", "comfortable", "deceleration", "in", "m", "/", "s^2", "of", "vehicles", "of", "this", "type", "." ]
def setDecel(self, typeID, decel): """setDecel(string, double) -> None Sets the maximal comfortable deceleration in m/s^2 of vehicles of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_DECEL, typeID, decel)
[ "def", "setDecel", "(", "self", ",", "typeID", ",", "decel", ")", ":", "self", ".", "_connection", ".", "_sendDoubleCmd", "(", "tc", ".", "CMD_SET_VEHICLETYPE_VARIABLE", ",", "tc", ".", "VAR_DECEL", ",", "typeID", ",", "decel", ")" ]
https://github.com/intrig-unicamp/mininet-wifi/blob/3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba/mn_wifi/sumo/traci/_vehicletype.py#L277-L282
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/setuptools/setuptools/dist.py
python
Distribution._feature_attrname
(self, name)
return 'with_' + name.replace('-', '_')
Convert feature name to corresponding option attribute name
Convert feature name to corresponding option attribute name
[ "Convert", "feature", "name", "to", "corresponding", "option", "attribute", "name" ]
def _feature_attrname(self, name): """Convert feature name to corresponding option attribute name""" return 'with_' + name.replace('-', '_')
[ "def", "_feature_attrname", "(", "self", ",", "name", ")", ":", "return", "'with_'", "+", "name", ".", "replace", "(", "'-'", ",", "'_'", ")" ]
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/setuptools/setuptools/dist.py#L352-L354
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/gp/kernel.py
python
CoordinateProductKernel.is_guaranteed_psd
(self)
return all([kern.is_guaranteed_psd() for kern in self.kernel_list])
The child class should implement this method to indicate whether it is guaranteed to be PSD. Returns True if each kernel is is_guaranteed_psd()
The child class should implement this method to indicate whether it is guaranteed to be PSD. Returns True if each kernel is is_guaranteed_psd()
[ "The", "child", "class", "should", "implement", "this", "method", "to", "indicate", "whether", "it", "is", "guaranteed", "to", "be", "PSD", ".", "Returns", "True", "if", "each", "kernel", "is", "is_guaranteed_psd", "()" ]
def is_guaranteed_psd(self): """ The child class should implement this method to indicate whether it is guaranteed to be PSD. Returns True if each kernel is is_guaranteed_psd()""" return all([kern.is_guaranteed_psd() for kern in self.kernel_list])
[ "def", "is_guaranteed_psd", "(", "self", ")", ":", "return", "all", "(", "[", "kern", ".", "is_guaranteed_psd", "(", ")", "for", "kern", "in", "self", ".", "kernel_list", "]", ")" ]
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/gp/kernel.py#L560-L563
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/benchmark/__init__.py
python
Benchmark.process
(self, n_workers=1)
Run studies experiment
Run studies experiment
[ "Run", "studies", "experiment" ]
def process(self, n_workers=1): """Run studies experiment""" for study in self.studies: study.execute(n_workers)
[ "def", "process", "(", "self", ",", "n_workers", "=", "1", ")", ":", "for", "study", "in", "self", ".", "studies", ":", "study", ".", "execute", "(", "n_workers", ")" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/benchmark/__init__.py#L87-L90
yueyoum/social-oauth
80600ea737355b20931c8a0b5223f5b68175d930
example/_bottle.py
python
path_shift
(script_name, path_info, shift=1)
return new_script_name, new_path_info
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
[ "Shift", "path", "fragments", "from", "PATH_INFO", "to", "SCRIPT_NAME", "and", "vice", "versa", "." ]
def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) ''' if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if shift > 0 and shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif shift < 0 and shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info
[ "def", "path_shift", "(", "script_name", ",", "path_info", ",", "shift", "=", "1", ")", ":", "if", "shift", "==", "0", ":", "return", "script_name", ",", "path_info", "pathlist", "=", "path_info", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'"...
https://github.com/yueyoum/social-oauth/blob/80600ea737355b20931c8a0b5223f5b68175d930/example/_bottle.py#L1994-L2022
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/polys/densebasic.py
python
dmp_permute
(f, P, u, K)
return dmp_from_dict(H, u, K)
Return a polynomial in ``K[x_{P(1)},..,x_{P(n)}]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_permute >>> f = ZZ.map([[[2], [1, 0]], []]) >>> dmp_permute(f, [1, 0, 2], 2, ZZ) [[[2], []], [[1, 0], []]] >>> dmp_permute(f, [1, 2, 0], 2, ZZ) [[[1], []], [[2, 0], []]]
Return a polynomial in ``K[x_{P(1)},..,x_{P(n)}]``.
[ "Return", "a", "polynomial", "in", "K", "[", "x_", "{", "P", "(", "1", ")", "}", "..", "x_", "{", "P", "(", "n", ")", "}", "]", "." ]
def dmp_permute(f, P, u, K): """ Return a polynomial in ``K[x_{P(1)},..,x_{P(n)}]``. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_permute >>> f = ZZ.map([[[2], [1, 0]], []]) >>> dmp_permute(f, [1, 0, 2], 2, ZZ) [[[2], []], [[1, 0], []]] >>> dmp_permute(f, [1, 2, 0], 2, ZZ) [[[1], []], [[2, 0], []]] """ F, H = dmp_to_dict(f, u), {} for exp, coeff in F.items(): new_exp = [0]*len(exp) for e, p in zip(exp, P): new_exp[p] = e H[tuple(new_exp)] = coeff return dmp_from_dict(H, u, K)
[ "def", "dmp_permute", "(", "f", ",", "P", ",", "u", ",", "K", ")", ":", "F", ",", "H", "=", "dmp_to_dict", "(", "f", ",", "u", ")", ",", "{", "}", "for", "exp", ",", "coeff", "in", "F", ".", "items", "(", ")", ":", "new_exp", "=", "[", "0...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/polys/densebasic.py#L1141-L1169
cszn/KAIR
72e93351bca41d1b1f6a4c3e1957f5bffccc7101
models/network_imdn.py
python
IMDN.__init__
(self, in_nc=3, out_nc=3, nc=64, nb=8, upscale=4, act_mode='L', upsample_mode='pixelshuffle', negative_slope=0.05)
in_nc: channel number of input out_nc: channel number of output nc: channel number nb: number of residual blocks upscale: up-scale factor act_mode: activation function upsample_mode: 'upconv' | 'pixelshuffle' | 'convtranspose'
in_nc: channel number of input out_nc: channel number of output nc: channel number nb: number of residual blocks upscale: up-scale factor act_mode: activation function upsample_mode: 'upconv' | 'pixelshuffle' | 'convtranspose'
[ "in_nc", ":", "channel", "number", "of", "input", "out_nc", ":", "channel", "number", "of", "output", "nc", ":", "channel", "number", "nb", ":", "number", "of", "residual", "blocks", "upscale", ":", "up", "-", "scale", "factor", "act_mode", ":", "activatio...
def __init__(self, in_nc=3, out_nc=3, nc=64, nb=8, upscale=4, act_mode='L', upsample_mode='pixelshuffle', negative_slope=0.05): """ in_nc: channel number of input out_nc: channel number of output nc: channel number nb: number of residual blocks upscale: up-scale factor act_mode: activation function upsample_mode: 'upconv' | 'pixelshuffle' | 'convtranspose' """ super(IMDN, self).__init__() assert 'R' in act_mode or 'L' in act_mode, 'Examples of activation function: R, L, BR, BL, IR, IL' m_head = B.conv(in_nc, nc, mode='C') m_body = [B.IMDBlock(nc, nc, mode='C'+act_mode, negative_slope=negative_slope) for _ in range(nb)] m_body.append(B.conv(nc, nc, mode='C')) if upsample_mode == 'upconv': upsample_block = B.upsample_upconv elif upsample_mode == 'pixelshuffle': upsample_block = B.upsample_pixelshuffle elif upsample_mode == 'convtranspose': upsample_block = B.upsample_convtranspose else: raise NotImplementedError('upsample mode [{:s}] is not found'.format(upsample_mode)) m_uper = upsample_block(nc, out_nc, mode=str(upscale)) self.model = B.sequential(m_head, B.ShortcutBlock(B.sequential(*m_body)), *m_uper)
[ "def", "__init__", "(", "self", ",", "in_nc", "=", "3", ",", "out_nc", "=", "3", ",", "nc", "=", "64", ",", "nb", "=", "8", ",", "upscale", "=", "4", ",", "act_mode", "=", "'L'", ",", "upsample_mode", "=", "'pixelshuffle'", ",", "negative_slope", "...
https://github.com/cszn/KAIR/blob/72e93351bca41d1b1f6a4c3e1957f5bffccc7101/models/network_imdn.py#L34-L62
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/properties/bars.py
python
PBEND.MassPerLength
(self)
return self.A * rho + self.nsm
m/L = rho*A + nsm
m/L = rho*A + nsm
[ "m", "/", "L", "=", "rho", "*", "A", "+", "nsm" ]
def MassPerLength(self) -> float: """m/L = rho*A + nsm""" rho = self.mid_ref.Rho() assert isinstance(self.A, float), self.get_stats() return self.A * rho + self.nsm
[ "def", "MassPerLength", "(", "self", ")", "->", "float", ":", "rho", "=", "self", ".", "mid_ref", ".", "Rho", "(", ")", "assert", "isinstance", "(", "self", ".", "A", ",", "float", ")", ",", "self", ".", "get_stats", "(", ")", "return", "self", "."...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/properties/bars.py#L3162-L3166
nopernik/mpDNS
b17dc39e7068406df82cb3431b3042e74e520cf9
dnslib/intercept.py
python
InterceptResolver.resolve
(self,request,handler)
return reply
[]
def resolve(self,request,handler): reply = request.reply() qname = request.q.qname qtype = QTYPE[request.q.qtype] # Try to resolve locally unless on skip list if not any([qname.matchGlob(s) for s in self.skip]): for name,rtype,rr in self.zone: if qname.matchGlob(name) and (qtype in (rtype,'ANY','CNAME')): a = copy.copy(rr) a.rname = qname reply.add_answer(a) # Check for NXDOMAIN if any([qname.matchGlob(s) for s in self.nxdomain]): reply.header.rcode = getattr(RCODE,'NXDOMAIN') return reply # Otherwise proxy if not reply.rr: try: if handler.protocol == 'udp': proxy_r = request.send(self.address,self.port, timeout=self.timeout) else: proxy_r = request.send(self.address,self.port, tcp=True,timeout=self.timeout) reply = DNSRecord.parse(proxy_r) except socket.timeout: reply.header.rcode = getattr(RCODE,'NXDOMAIN') return reply
[ "def", "resolve", "(", "self", ",", "request", ",", "handler", ")", ":", "reply", "=", "request", ".", "reply", "(", ")", "qname", "=", "request", ".", "q", ".", "qname", "qtype", "=", "QTYPE", "[", "request", ".", "q", ".", "qtype", "]", "# Try to...
https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/dnslib/intercept.py#L47-L75
ArchiveBox/ArchiveBox
663918a37298d6b7617d1f36d346f95947c5bab2
archivebox/parsers/pocket_api.py
python
parse_pocket_api_export
(input_buffer: IO[str], **_kwargs)
Parse bookmarks from the Pocket API
Parse bookmarks from the Pocket API
[ "Parse", "bookmarks", "from", "the", "Pocket", "API" ]
def parse_pocket_api_export(input_buffer: IO[str], **_kwargs) -> Iterable[Link]: """Parse bookmarks from the Pocket API""" input_buffer.seek(0) pattern = re.compile(r"^pocket:\/\/(\w+)") for line in input_buffer: if should_parse_as_pocket_api(line): username = pattern.search(line).group(1) api = Pocket(POCKET_CONSUMER_KEY, POCKET_ACCESS_TOKENS[username]) api.last_since = None for article in get_pocket_articles(api, since=read_since(username)): yield link_from_article(article, sources=[line]) write_since(username, api.last_since)
[ "def", "parse_pocket_api_export", "(", "input_buffer", ":", "IO", "[", "str", "]", ",", "*", "*", "_kwargs", ")", "->", "Iterable", "[", "Link", "]", ":", "input_buffer", ".", "seek", "(", "0", ")", "pattern", "=", "re", ".", "compile", "(", "r\"^pocke...
https://github.com/ArchiveBox/ArchiveBox/blob/663918a37298d6b7617d1f36d346f95947c5bab2/archivebox/parsers/pocket_api.py#L98-L113
spacetx/starfish
0e879d995d5c49b6f5a842e201e3be04c91afc7e
starfish/core/imagestack/parser/tilefetcher/_parser.py
python
TileFetcherData.extras
(self)
return {}
Returns the extras metadata for the TileSet.
Returns the extras metadata for the TileSet.
[ "Returns", "the", "extras", "metadata", "for", "the", "TileSet", "." ]
def extras(self) -> dict: """Returns the extras metadata for the TileSet.""" return {}
[ "def", "extras", "(", "self", ")", "->", "dict", ":", "return", "{", "}" ]
https://github.com/spacetx/starfish/blob/0e879d995d5c49b6f5a842e201e3be04c91afc7e/starfish/core/imagestack/parser/tilefetcher/_parser.py#L113-L115
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/pathlib.py
python
_PosixFlavour.is_reserved
(self, parts)
return False
[]
def is_reserved(self, parts): return False
[ "def", "is_reserved", "(", "self", ",", "parts", ")", ":", "return", "False" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/pathlib.py#L263-L264
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/demo/vacuum.py
python
StateDemoVacuum.stop
(self, **kwargs)
Stop the cleaning task, do not return to dock.
Stop the cleaning task, do not return to dock.
[ "Stop", "the", "cleaning", "task", "do", "not", "return", "to", "dock", "." ]
def stop(self, **kwargs): """Stop the cleaning task, do not return to dock.""" if self.supported_features & SUPPORT_STOP == 0: return self._state = STATE_IDLE self.schedule_update_ha_state()
[ "def", "stop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "supported_features", "&", "SUPPORT_STOP", "==", "0", ":", "return", "self", ".", "_state", "=", "STATE_IDLE", "self", ".", "schedule_update_ha_state", "(", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/demo/vacuum.py#L331-L337
fooof-tools/fooof
14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac
fooof/plts/utils.py
python
recursive_plot
(data, plot_function, ax, **kwargs)
A utility to recursively plot sets of data. Parameters ---------- data : list List of datasets to iteratively add to the plot. plot_function : callable Plot function to call to plot the data. ax : matplotlib.Axes Figure axes upon which to plot. **kwargs Keyword arguments to pass into the plot function. Inputs can be organized as: - a list of values corresponding to length of data, one for each plot call - a single value, such as an int, str or None, to be applied to all plot calls Notes ----- The `plot_function` argument must accept the `ax` parameter to specify a plot axis.
A utility to recursively plot sets of data.
[ "A", "utility", "to", "recursively", "plot", "sets", "of", "data", "." ]
def recursive_plot(data, plot_function, ax, **kwargs): """A utility to recursively plot sets of data. Parameters ---------- data : list List of datasets to iteratively add to the plot. plot_function : callable Plot function to call to plot the data. ax : matplotlib.Axes Figure axes upon which to plot. **kwargs Keyword arguments to pass into the plot function. Inputs can be organized as: - a list of values corresponding to length of data, one for each plot call - a single value, such as an int, str or None, to be applied to all plot calls Notes ----- The `plot_function` argument must accept the `ax` parameter to specify a plot axis. """ # Check and update all inputs to be iterators for key, val in kwargs.items(): # If an input is already an iterator, we can leave as is if isinstance(val, Iterator): kwargs[key] = val # If an input is a list, assume one element per call, and make iterator to do so elif isinstance(val, list): kwargs[key] = iter(val) # Otherwise, assume is a single value to pass to all plot calls, and make repeat to do so else: kwargs[key] = repeat(val) # Pass each array of data recursively into plot function # Each element of data is added to the same plot axis for cur_data in data: cur_kwargs = {key: next(val) for key, val in kwargs.items()} plot_function(cur_data, ax=ax, **cur_kwargs)
[ "def", "recursive_plot", "(", "data", ",", "plot_function", ",", "ax", ",", "*", "*", "kwargs", ")", ":", "# Check and update all inputs to be iterators", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "# If an input is already an iterator,...
https://github.com/fooof-tools/fooof/blob/14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac/fooof/plts/utils.py#L102-L145
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/werkzeug/datastructures.py
python
HeaderSet.add
(self, header)
Add a new header to the set.
Add a new header to the set.
[ "Add", "a", "new", "header", "to", "the", "set", "." ]
def add(self, header): """Add a new header to the set.""" self.update((header,))
[ "def", "add", "(", "self", ",", "header", ")", ":", "self", ".", "update", "(", "(", "header", ",", ")", ")" ]
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/werkzeug/datastructures.py#L1883-L1885
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility/plugins/getservicesids.py
python
GetServiceSids.render_text
(self, outfd, data)
output to Service SIDs as a dictionary for future use
output to Service SIDs as a dictionary for future use
[ "output", "to", "Service", "SIDs", "as", "a", "dictionary", "for", "future", "use" ]
def render_text(self, outfd, data): """ output to Service SIDs as a dictionary for future use""" outfd.write("servicesids = { \n") for sid, service in data: if not service: continue outfd.write(" '" + sid + "': '" + service + "',\n") outfd.write("}\n")
[ "def", "render_text", "(", "self", ",", "outfd", ",", "data", ")", ":", "outfd", ".", "write", "(", "\"servicesids = { \\n\"", ")", "for", "sid", ",", "service", "in", "data", ":", "if", "not", "service", ":", "continue", "outfd", ".", "write", "(", "\...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility/plugins/getservicesids.py#L540-L547
XKNX/xknx
1deeeb3dc0978aebacf14492a84e1f1eaf0970ed
xknx/io/gateway_scanner.py
python
GatewayScanner.scan
(self)
return self.found_gateways
Scan and return a list of GatewayDescriptors on success.
Scan and return a list of GatewayDescriptors on success.
[ "Scan", "and", "return", "a", "list", "of", "GatewayDescriptors", "on", "success", "." ]
async def scan(self) -> list[GatewayDescriptor]: """Scan and return a list of GatewayDescriptors on success.""" if self.stop_on_found is None: self._count_upper_bound = 0 else: self._count_upper_bound = max(0, self.stop_on_found) await self._send_search_requests() try: await asyncio.wait_for( self._response_received_event.wait(), timeout=self.timeout_in_seconds, ) except asyncio.TimeoutError: pass finally: await self._stop() return self.found_gateways
[ "async", "def", "scan", "(", "self", ")", "->", "list", "[", "GatewayDescriptor", "]", ":", "if", "self", ".", "stop_on_found", "is", "None", ":", "self", ".", "_count_upper_bound", "=", "0", "else", ":", "self", ".", "_count_upper_bound", "=", "max", "(...
https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/io/gateway_scanner.py#L133-L150
carlio/django-flows
326baa3e216a15bd7a8d13b2a09ba9752e250dbb
flows/components.py
python
FlowComponent.check_preconditions
(self, request)
Ensures that all of the preconditions for this flow component are satisfied. It will return the result of the first failing precondition, where order is defined by their position in the `preconditions` list.
Ensures that all of the preconditions for this flow component are satisfied. It will return the result of the first failing precondition, where order is defined by their position in the `preconditions` list.
[ "Ensures", "that", "all", "of", "the", "preconditions", "for", "this", "flow", "component", "are", "satisfied", ".", "It", "will", "return", "the", "result", "of", "the", "first", "failing", "precondition", "where", "order", "is", "defined", "by", "their", "...
def check_preconditions(self, request): """ Ensures that all of the preconditions for this flow component are satisfied. It will return the result of the first failing precondition, where order is defined by their position in the `preconditions` list. """ for prec in getattr(self, 'preconditions', []): ret = prec.process(request, self) if ret is not None: return ret
[ "def", "check_preconditions", "(", "self", ",", "request", ")", ":", "for", "prec", "in", "getattr", "(", "self", ",", "'preconditions'", ",", "[", "]", ")", ":", "ret", "=", "prec", ".", "process", "(", "request", ",", "self", ")", "if", "ret", "is"...
https://github.com/carlio/django-flows/blob/326baa3e216a15bd7a8d13b2a09ba9752e250dbb/flows/components.py#L86-L96