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
jeffzh3ng/fuxi
fadb1136b8896fe2a0f7783627bda867d5e6fd98
fuxi/common/libs/ip_handler.py
python
IPint.iptype
(self)
return "unknown"
Return a description of the IP type ('PRIVATE', 'RESERVED', etc). >>> print(IP('127.0.0.1').iptype()) LOOPBACK >>> print(IP('192.168.1.1').iptype()) PRIVATE >>> print(IP('195.185.1.2').iptype()) PUBLIC >>> print(IP('::1').iptype()) LOOPBACK >>> print(IP('2001:0658:022a:cafe:0200::1').iptype()) ALLOCATED RIPE NCC The type information for IPv6 is out of sync with reality.
Return a description of the IP type ('PRIVATE', 'RESERVED', etc).
[ "Return", "a", "description", "of", "the", "IP", "type", "(", "PRIVATE", "RESERVED", "etc", ")", "." ]
def iptype(self): """Return a description of the IP type ('PRIVATE', 'RESERVED', etc). >>> print(IP('127.0.0.1').iptype()) LOOPBACK >>> print(IP('192.168.1.1').iptype()) PRIVATE >>> print(IP('195.185.1.2').iptype()) PUBLIC >>> print(IP('::1').iptype()) LOOPBACK >>> print(IP('2001:0658:022a:cafe:0200::1').iptype()) ALLOCATED RIPE NCC The type information for IPv6 is out of sync with reality. """ # this could be greatly improved if self._ipversion == 4: iprange = IPv4ranges elif self._ipversion == 6: iprange = IPv6ranges else: raise ValueError("only IPv4 and IPv6 supported") bits = self.strBin() for i in xrange(len(bits), 0, -1): if bits[:i] in iprange: return iprange[bits[:i]] return "unknown"
[ "def", "iptype", "(", "self", ")", ":", "# this could be greatly improved", "if", "self", ".", "_ipversion", "==", "4", ":", "iprange", "=", "IPv4ranges", "elif", "self", ".", "_ipversion", "==", "6", ":", "iprange", "=", "IPv6ranges", "else", ":", "raise", ...
https://github.com/jeffzh3ng/fuxi/blob/fadb1136b8896fe2a0f7783627bda867d5e6fd98/fuxi/common/libs/ip_handler.py#L479-L509
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/Phylo/BaseTree.py
python
TreeMixin.depths
(self, unit_branch_lengths=False)
return depths
Create a mapping of tree clades to depths (by branch length). :Parameters: unit_branch_lengths : bool If True, count only the number of branches (levels in the tree). By default the distance is the cumulative branch length leading to the clade. :returns: dict of {clade: depth}, where keys are all of the Clade instances in the tree, and values are the distance from the root to each clade (including terminals).
Create a mapping of tree clades to depths (by branch length).
[ "Create", "a", "mapping", "of", "tree", "clades", "to", "depths", "(", "by", "branch", "length", ")", "." ]
def depths(self, unit_branch_lengths=False): # noqa: D402 """Create a mapping of tree clades to depths (by branch length). :Parameters: unit_branch_lengths : bool If True, count only the number of branches (levels in the tree). By default the distance is the cumulative branch length leading to the clade. :returns: dict of {clade: depth}, where keys are all of the Clade instances in the tree, and values are the distance from the root to each clade (including terminals). """ # noqa: D402 if unit_branch_lengths: depth_of = lambda c: 1 # noqa: E731 else: depth_of = lambda c: c.branch_length or 0 # noqa: E731 depths = {} def update_depths(node, curr_depth): depths[node] = curr_depth for child in node.clades: new_depth = curr_depth + depth_of(child) update_depths(child, new_depth) update_depths(self.root, self.root.branch_length or 0) return depths
[ "def", "depths", "(", "self", ",", "unit_branch_lengths", "=", "False", ")", ":", "# noqa: D402", "# noqa: D402", "if", "unit_branch_lengths", ":", "depth_of", "=", "lambda", "c", ":", "1", "# noqa: E731", "else", ":", "depth_of", "=", "lambda", "c", ":", "c...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/Phylo/BaseTree.py#L462-L489
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/vpc/__init__.py
python
VPCConnection.delete_customer_gateway
(self, customer_gateway_id, dry_run=False)
return self.get_status('DeleteCustomerGateway', params)
Delete a Customer Gateway. :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer_gateway to be deleted. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful
Delete a Customer Gateway.
[ "Delete", "a", "Customer", "Gateway", "." ]
def delete_customer_gateway(self, customer_gateway_id, dry_run=False): """ Delete a Customer Gateway. :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer_gateway to be deleted. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful """ params = {'CustomerGatewayId': customer_gateway_id} if dry_run: params['DryRun'] = 'true' return self.get_status('DeleteCustomerGateway', params)
[ "def", "delete_customer_gateway", "(", "self", ",", "customer_gateway_id", ",", "dry_run", "=", "False", ")", ":", "params", "=", "{", "'CustomerGatewayId'", ":", "customer_gateway_id", "}", "if", "dry_run", ":", "params", "[", "'DryRun'", "]", "=", "'true'", ...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/vpc/__init__.py#L957-L973
mutpy/mutpy
5c8b3ca0d365083a4da8333f7fce8783114371fa
mutpy/controller.py
python
MutationScore.inc_incompetent
(self)
[]
def inc_incompetent(self): self.incompetent_mutants += 1
[ "def", "inc_incompetent", "(", "self", ")", ":", "self", ".", "incompetent_mutants", "+=", "1" ]
https://github.com/mutpy/mutpy/blob/5c8b3ca0d365083a4da8333f7fce8783114371fa/mutpy/controller.py#L34-L35
nipy/nipy
d16d268938dcd5c15748ca051532c21f57cf8a22
nipy/labs/spatial_models/discrete_domain.py
python
grid_domain_from_shape
(shape, affine=None)
return NDGridDomain(dim, ijk, shape, affine, vol, topology)
Return a NDGridDomain from an n-d array Parameters ---------- shape: tuple the shape of a rectangular domain. affine: np.array, optional affine transform that maps the array coordinates to some embedding space. By default, this is np.eye(dim+1, dim+1)
Return a NDGridDomain from an n-d array
[ "Return", "a", "NDGridDomain", "from", "an", "n", "-", "d", "array" ]
def grid_domain_from_shape(shape, affine=None): """Return a NDGridDomain from an n-d array Parameters ---------- shape: tuple the shape of a rectangular domain. affine: np.array, optional affine transform that maps the array coordinates to some embedding space. By default, this is np.eye(dim+1, dim+1) """ dim = len(shape) if affine is None: affine = np.eye(dim + 1) rect = np.ones(shape) ijk = np.array(np.where(rect)).T vol = (np.absolute(np.linalg.det(affine[:3, 0:3])) * np.ones(int(np.sum(rect)))) topology = smatrix_from_nd_idx(ijk, 0) return NDGridDomain(dim, ijk, shape, affine, vol, topology)
[ "def", "grid_domain_from_shape", "(", "shape", ",", "affine", "=", "None", ")", ":", "dim", "=", "len", "(", "shape", ")", "if", "affine", "is", "None", ":", "affine", "=", "np", ".", "eye", "(", "dim", "+", "1", ")", "rect", "=", "np", ".", "one...
https://github.com/nipy/nipy/blob/d16d268938dcd5c15748ca051532c21f57cf8a22/nipy/labs/spatial_models/discrete_domain.py#L296-L318
CityOfZion/neo-python
99783bc8310982a5380081ec41a6ee07ba843f3f
neo/Core/TX/Transaction.py
python
TransactionOutput.Address
(self)
return Crypto.ToAddress(self.ScriptHash)
Get the public address of the transaction. Returns: str: base58 encoded string representing the address.
Get the public address of the transaction.
[ "Get", "the", "public", "address", "of", "the", "transaction", "." ]
def Address(self): """ Get the public address of the transaction. Returns: str: base58 encoded string representing the address. """ return Crypto.ToAddress(self.ScriptHash)
[ "def", "Address", "(", "self", ")", ":", "return", "Crypto", ".", "ToAddress", "(", "self", ".", "ScriptHash", ")" ]
https://github.com/CityOfZion/neo-python/blob/99783bc8310982a5380081ec41a6ee07ba843f3f/neo/Core/TX/Transaction.py#L102-L109
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/homogenization/coefs_base.py
python
MiniAppBase.init_solvers
(self, problem)
Setup solvers. Use local options if these are defined, otherwise use the global ones. For linear problems, assemble the matrix and try to presolve the linear system.
Setup solvers. Use local options if these are defined, otherwise use the global ones.
[ "Setup", "solvers", ".", "Use", "local", "options", "if", "these", "are", "defined", "otherwise", "use", "the", "global", "ones", "." ]
def init_solvers(self, problem): """ Setup solvers. Use local options if these are defined, otherwise use the global ones. For linear problems, assemble the matrix and try to presolve the linear system. """ if hasattr(self, 'solvers'): opts = self.solvers else: opts = problem.conf.options problem.set_conf_solvers(problem.conf.solvers, opts) problem.init_solvers() if self.is_linear: output('linear problem, trying to presolve...') timer = Timer(start=True) ev = problem.get_evaluator() state = problem.create_state() try: mtx_a = ev.eval_tangent_matrix(state(), is_full=True) except ValueError: output('matrix evaluation failed, giving up...') raise problem.set_linear(True) problem.try_presolve(mtx_a) output('...done in %.2f s' % timer.stop()) else: problem.set_linear(False)
[ "def", "init_solvers", "(", "self", ",", "problem", ")", ":", "if", "hasattr", "(", "self", ",", "'solvers'", ")", ":", "opts", "=", "self", ".", "solvers", "else", ":", "opts", "=", "problem", ".", "conf", ".", "options", "problem", ".", "set_conf_sol...
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/homogenization/coefs_base.py#L56-L93
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/preview/deployed_devices/fleet/key.py
python
KeyInstance.date_updated
(self)
return self._properties['date_updated']
:returns: The date this Key credential was updated. :rtype: datetime
:returns: The date this Key credential was updated. :rtype: datetime
[ ":", "returns", ":", "The", "date", "this", "Key", "credential", "was", "updated", ".", ":", "rtype", ":", "datetime" ]
def date_updated(self): """ :returns: The date this Key credential was updated. :rtype: datetime """ return self._properties['date_updated']
[ "def", "date_updated", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'date_updated'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/deployed_devices/fleet/key.py#L405-L410
EnigmaCurry/blogofile
f8503eb5a4e9f7962b799adfdc3afc2dd6fe91c9
blogofile/filter.py
python
preload_filters
(namespace=None, directory="_filters")
Find all the standalone .py files and modules in the directory specified and load them into namespace specified.
Find all the standalone .py files and modules in the directory specified and load them into namespace specified.
[ "Find", "all", "the", "standalone", ".", "py", "files", "and", "modules", "in", "the", "directory", "specified", "and", "load", "them", "into", "namespace", "specified", "." ]
def preload_filters(namespace=None, directory="_filters"): """Find all the standalone .py files and modules in the directory specified and load them into namespace specified. """ if namespace is None: namespace = bf.config.filters if(not os.path.isdir(directory)): return for fn in os.listdir(directory): p = os.path.join(directory, fn) if (os.path.isfile(p) and fn.endswith(".py")): # Load a single .py file: load_filter(fn[:-3], module_path=p, namespace=namespace) elif (os.path.isdir(p) and os.path.isfile(os.path.join(p, "__init__.py"))): # Load a package: load_filter(fn, module_path=p, namespace=namespace)
[ "def", "preload_filters", "(", "namespace", "=", "None", ",", "directory", "=", "\"_filters\"", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "bf", ".", "config", ".", "filters", "if", "(", "not", "os", ".", "path", ".", "isdir", "(...
https://github.com/EnigmaCurry/blogofile/blob/f8503eb5a4e9f7962b799adfdc3afc2dd6fe91c9/blogofile/filter.py#L64-L80
rhydlewis/search-omnifocus
8e872073be51b867440c4fa124f82433813fa73a
workflow/web.py
python
Response.save_to_path
(self, filepath)
Save retrieved data to file at ``filepath``. .. versionadded: 1.9.6 :param filepath: Path to save retrieved data.
Save retrieved data to file at ``filepath``.
[ "Save", "retrieved", "data", "to", "file", "at", "filepath", "." ]
def save_to_path(self, filepath): """Save retrieved data to file at ``filepath``. .. versionadded: 1.9.6 :param filepath: Path to save retrieved data. """ filepath = os.path.abspath(filepath) dirname = os.path.dirname(filepath) if not os.path.exists(dirname): os.makedirs(dirname) self.stream = True with open(filepath, 'wb') as fileobj: for data in self.iter_content(): fileobj.write(data)
[ "def", "save_to_path", "(", "self", ",", "filepath", ")", ":", "filepath", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "if", "not", "os", ".", "path", ".", "...
https://github.com/rhydlewis/search-omnifocus/blob/8e872073be51b867440c4fa124f82433813fa73a/workflow/web.py#L388-L405
nathanlopez/Stitch
8e22e91c94237959c02d521aab58dc7e3d994cea
Application/stitch_pyld_config.py
python
create_new_config
()
return confirm_config()
[]
def create_new_config(): BIND = False BHOST = "" BPORT = "" LISTEN = False LHOST = "" LPORT = "" KEYLOGGER_BOOT = False st_bind = '' while st_bind != "y" and st_bind != "yes" and st_bind != "n" and st_bind != "no": st_bind = raw_input('\nWould you like the payload to bind itself? [Y/N]: ').lower() if st_bind.startswith('y'): BIND = True elif st_bind.startswith('n'): BIND = False if BIND: st_bhost = raw_input('\nEnter the host IP you want the payload to bind to. (Leave empty to allow all IPs): ').lower() BHOST = st_bhost st_bport = raw_input('Enter the port you want the payload to bind itself to?: ').lower() while not check_int(st_bport): st_bport = raw_input('\nEnter the port you want the payload to bind itself to?: ').lower() BPORT = st_bport else: BHOST = "" BPORT = "" st_conn = '' while st_conn != "y" and st_conn != "yes" and st_conn != "n" and st_conn != "no": st_conn = raw_input('\nWould you like the payload to connect to a host? [Y/N]: ').lower() if st_conn.startswith('y'): LISTEN = True elif st_conn.startswith('n'): LISTEN = False if LISTEN: st_chost = raw_input('\nEnter the host IP you want the payload to connect to: ').lower() LHOST = st_chost st_cport = raw_input('Enter the port on "{}" that you want the payload to connect to: '.format(st_chost)).lower() while not check_int(st_cport): st_cport = raw_input('Enter the port on "{}" that you want the payload to connect to: '.format(st_chost)).lower() LPORT = st_cport else: LHOST = "" LPORT = "" st_email = '' while st_email != "y" and st_email != "yes" and st_email != "n" and st_email != "no": st_email = raw_input('\nWould you like the payload to email you on boot? [Y/N]: ').lower() if st_email.startswith('y'): EMAIL = True elif st_email.startswith('n'): EMAIL = False if EMAIL: while True: GMAIL_USER = raw_input('\nEnter a valid gmail address you want the payload to use: ').lower() if '@gmail.com' in GMAIL_USER: break GMAIL_PWD = base64.b64encode(getpass('Enter your email password for {}: '.format(GMAIL_USER))) else: GMAIL_USER = "None" GMAIL_PWD = "" st_klboot = '' while st_klboot != "y" and st_klboot != "yes" and st_klboot != "n" and st_klboot != "no": st_klboot = raw_input('\nWould you like the keylogger to start on boot? [Y/N]: ').lower() if st_klboot.startswith('y'): KEYLOGGER_BOOT = True elif st_klboot.startswith('n'): KEYLOGGER_BOOT = False stini = stitch_ini() stini.set_value('BIND', BIND) stini.set_value('BHOST',BHOST) stini.set_value('BPORT',BPORT) stini.set_value('LISTEN',LISTEN) stini.set_value('LHOST',LHOST) stini.set_value('LPORT',LPORT) stini.set_value('EMAIL',GMAIL_USER) stini.set_value('EMAIL_PWD',GMAIL_PWD) stini.set_value('KEYLOGGER_BOOT',KEYLOGGER_BOOT) return confirm_config()
[ "def", "create_new_config", "(", ")", ":", "BIND", "=", "False", "BHOST", "=", "\"\"", "BPORT", "=", "\"\"", "LISTEN", "=", "False", "LHOST", "=", "\"\"", "LPORT", "=", "\"\"", "KEYLOGGER_BOOT", "=", "False", "st_bind", "=", "''", "while", "st_bind", "!=...
https://github.com/nathanlopez/Stitch/blob/8e22e91c94237959c02d521aab58dc7e3d994cea/Application/stitch_pyld_config.py#L32-L120
horazont/aioxmpp
c701e6399c90a6bb9bec0349018a03bd7b644cde
aioxmpp/structs.py
python
LanguageMap.lookup
(self, language_ranges)
return self[key]
Perform an RFC4647 language range lookup on the keys in the dictionary. `language_ranges` must be a sequence of :class:`LanguageRange` instances. Return the entry in the dictionary with a key as produced by `lookup_language`. If `lookup_language` does not find a match and the mapping contains an entry with key :data:`None`, that entry is returned, otherwise :class:`KeyError` is raised.
Perform an RFC4647 language range lookup on the keys in the dictionary. `language_ranges` must be a sequence of :class:`LanguageRange` instances.
[ "Perform", "an", "RFC4647", "language", "range", "lookup", "on", "the", "keys", "in", "the", "dictionary", ".", "language_ranges", "must", "be", "a", "sequence", "of", ":", "class", ":", "LanguageRange", "instances", "." ]
def lookup(self, language_ranges): """ Perform an RFC4647 language range lookup on the keys in the dictionary. `language_ranges` must be a sequence of :class:`LanguageRange` instances. Return the entry in the dictionary with a key as produced by `lookup_language`. If `lookup_language` does not find a match and the mapping contains an entry with key :data:`None`, that entry is returned, otherwise :class:`KeyError` is raised. """ keys = list(self.keys()) try: keys.remove(None) except ValueError: pass keys.sort() key = lookup_language(keys, language_ranges) return self[key]
[ "def", "lookup", "(", "self", ",", "language_ranges", ")", ":", "keys", "=", "list", "(", "self", ".", "keys", "(", ")", ")", "try", ":", "keys", ".", "remove", "(", "None", ")", "except", "ValueError", ":", "pass", "keys", ".", "sort", "(", ")", ...
https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/structs.py#L1314-L1332
Arachnid/bloggart
ba2b60417102fe14a77b1bcd809b9b801d3a96e2
lib/docutils/parsers/rst/states.py
python
RSTState.no_match
(self, context, transitions)
return context, None, []
Override `StateWS.no_match` to generate a system message. This code should never be run.
Override `StateWS.no_match` to generate a system message.
[ "Override", "StateWS", ".", "no_match", "to", "generate", "a", "system", "message", "." ]
def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), line=self.state_machine.abs_line_number()) return context, None, []
[ "def", "no_match", "(", "self", ",", "context", ",", "transitions", ")", ":", "self", ".", "reporter", ".", "severe", "(", "'Internal error: no transition pattern match. State: \"%s\"; '", "'transitions: %s; context: %s; current line: %r.'", "%", "(", "self", ".", "__cla...
https://github.com/Arachnid/bloggart/blob/ba2b60417102fe14a77b1bcd809b9b801d3a96e2/lib/docutils/parsers/rst/states.py#L235-L247
ryankiros/layer-norm
7a9a1bf7c6553b5a89949c5c860bdfc0937af483
layers.py
python
lngru_layer
(tparams, state_below, init_state, options, prefix='lngru', mask=None, one_step=False, **kwargs)
return rval
Feedforward pass through GRU with LN
Feedforward pass through GRU with LN
[ "Feedforward", "pass", "through", "GRU", "with", "LN" ]
def lngru_layer(tparams, state_below, init_state, options, prefix='lngru', mask=None, one_step=False, **kwargs): """ Feedforward pass through GRU with LN """ nsteps = state_below.shape[0] if state_below.ndim == 3: n_samples = state_below.shape[1] else: n_samples = 1 dim = tparams[_p(prefix,'Ux')].shape[1] if init_state == None: init_state = tensor.alloc(0., n_samples, dim) if mask == None: mask = tensor.alloc(1., state_below.shape[0], 1) def _slice(_x, n, dim): if _x.ndim == 3: return _x[:, :, n*dim:(n+1)*dim] return _x[:, n*dim:(n+1)*dim] state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + tparams[_p(prefix, 'b')] state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + tparams[_p(prefix, 'bx')] U = tparams[_p(prefix, 'U')] Ux = tparams[_p(prefix, 'Ux')] def _step_slice(m_, x_, xx_, h_, U, Ux, b1, b2, b3, b4, s1, s2, s3, s4): x_ = ln(x_, b1, s1) xx_ = ln(xx_, b2, s2) preact = tensor.dot(h_, U) preact = ln(preact, b3, s3) preact += x_ r = tensor.nnet.sigmoid(_slice(preact, 0, dim)) u = tensor.nnet.sigmoid(_slice(preact, 1, dim)) preactx = tensor.dot(h_, Ux) preactx = ln(preactx, b4, s4) preactx = preactx * r preactx = preactx + xx_ h = tensor.tanh(preactx) h = u * h_ + (1. - u) * h h = m_[:,None] * h + (1. - m_)[:,None] * h_ return h seqs = [mask, state_below_, state_belowx] _step = _step_slice non_seqs = [tparams[_p(prefix, 'U')], tparams[_p(prefix, 'Ux')]] non_seqs += [tparams[_p(prefix, 'b1')], tparams[_p(prefix, 'b2')], tparams[_p(prefix, 'b3')], tparams[_p(prefix, 'b4')]] non_seqs += [tparams[_p(prefix, 's1')], tparams[_p(prefix, 's2')], tparams[_p(prefix, 's3')], tparams[_p(prefix, 's4')]] if one_step: rval = _step(*(seqs+[init_state, tparams[_p(prefix, 'U')], tparams[_p(prefix, 'Ux')]])) else: rval, updates = theano.scan(_step, sequences=seqs, outputs_info = [init_state], non_sequences = non_seqs, name=_p(prefix, '_layers'), n_steps=nsteps, profile=False, strict=True) rval = [rval] return rval
[ "def", "lngru_layer", "(", "tparams", ",", "state_below", ",", "init_state", ",", "options", ",", "prefix", "=", "'lngru'", ",", "mask", "=", "None", ",", "one_step", "=", "False", ",", "*", "*", "kwargs", ")", ":", "nsteps", "=", "state_below", ".", "...
https://github.com/ryankiros/layer-norm/blob/7a9a1bf7c6553b5a89949c5c860bdfc0937af483/layers.py#L174-L245
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/AndroBugs/tools/modified/androguard/patch/zipfile.py
python
ZipFile.testzip
(self)
Read all the files and check the CRC.
Read all the files and check the CRC.
[ "Read", "all", "the", "files", "and", "check", "the", "CRC", "." ]
def testzip(self): """Read all the files and check the CRC.""" chunk_size = 2 ** 20 for zinfo in self.filelist: try: # Read by chunks, to avoid an OverflowError or a # MemoryError with very large embedded files. f = self.open(zinfo.filename, "r") while f.read(chunk_size): # Check CRC-32 pass except BadZipfile: return zinfo.filename
[ "def", "testzip", "(", "self", ")", ":", "chunk_size", "=", "2", "**", "20", "for", "zinfo", "in", "self", ".", "filelist", ":", "try", ":", "# Read by chunks, to avoid an OverflowError or a", "# MemoryError with very large embedded files.", "f", "=", "self", ".", ...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/AndroBugs/tools/modified/androguard/patch/zipfile.py#L837-L848
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/traceback.py
python
_format_final_exc_line
(etype, value)
return line
Return a list of a single line -- normal case for format_exception_only
Return a list of a single line -- normal case for format_exception_only
[ "Return", "a", "list", "of", "a", "single", "line", "--", "normal", "case", "for", "format_exception_only" ]
def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" valuestr = _some_str(value) if value is None or not valuestr: line = "%s\n" % etype else: line = "%s: %s\n" % (etype, valuestr) return line
[ "def", "_format_final_exc_line", "(", "etype", ",", "value", ")", ":", "valuestr", "=", "_some_str", "(", "value", ")", "if", "value", "is", "None", "or", "not", "valuestr", ":", "line", "=", "\"%s\\n\"", "%", "etype", "else", ":", "line", "=", "\"%s: %s...
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/traceback.py#L203-L210
pytest-dev/pytest-xdist
5749a347b998448c55e5db94bcee7fa1d4378fa6
example/loadscope/epsilon/__init__.py
python
epsilon2
(arg1, arg2=1000)
return arg1 - arg2 - 10
Do epsilon2 Usage: >>> epsilon2(10, 20) -20 >>> epsilon2(30) -980
Do epsilon2
[ "Do", "epsilon2" ]
def epsilon2(arg1, arg2=1000): """Do epsilon2 Usage: >>> epsilon2(10, 20) -20 >>> epsilon2(30) -980 """ return arg1 - arg2 - 10
[ "def", "epsilon2", "(", "arg1", ",", "arg2", "=", "1000", ")", ":", "return", "arg1", "-", "arg2", "-", "10" ]
https://github.com/pytest-dev/pytest-xdist/blob/5749a347b998448c55e5db94bcee7fa1d4378fa6/example/loadscope/epsilon/__init__.py#L14-L24
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/feature/feature_scale/standard_scale.py
python
StandardScale.fit
(self, data)
return fit_data
Apply standard scale for input data Parameters ---------- data: data_instance, input data Returns ---------- data:data_instance, data after scale mean: list, each column mean value std: list, each column standard deviation
Apply standard scale for input data Parameters ---------- data: data_instance, input data
[ "Apply", "standard", "scale", "for", "input", "data", "Parameters", "----------", "data", ":", "data_instance", "input", "data" ]
def fit(self, data): """ Apply standard scale for input data Parameters ---------- data: data_instance, input data Returns ---------- data:data_instance, data after scale mean: list, each column mean value std: list, each column standard deviation """ self.column_min_value, self.column_max_value = self._get_min_max_value(data) self.scale_column_idx = self._get_scale_column_idx(data) self.header = self._get_header(data) self.data_shape = self._get_data_shape(data) # fit column value if larger than parameter upper or less than parameter lower data = self.fit_feature_range(data) if not self.with_mean and not self.with_std: self.mean = [0 for _ in range(self.data_shape)] self.std = [1 for _ in range(self.data_shape)] else: self.summary_obj = MultivariateStatisticalSummary(data, -1) if self.with_mean: self.mean = self.summary_obj.get_mean() self.mean = [self.mean[key] for key in self.header] else: self.mean = [0 for _ in range(self.data_shape)] if self.with_std: self.std = self.summary_obj.get_std_variance() self.std = [self.std[key] for key in self.header] for i, value in enumerate(self.std): if np.abs(value - 0) < 1e-6: self.std[i] = 1 else: self.std = [1 for _ in range(self.data_shape)] f = functools.partial(self.__scale, mean=self.mean, std=self.std, process_cols_list=self.scale_column_idx) fit_data = data.mapValues(f) return fit_data
[ "def", "fit", "(", "self", ",", "data", ")", ":", "self", ".", "column_min_value", ",", "self", ".", "column_max_value", "=", "self", ".", "_get_min_max_value", "(", "data", ")", "self", ".", "scale_column_idx", "=", "self", ".", "_get_scale_column_idx", "("...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/feature/feature_scale/standard_scale.py#L75-L121
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/reading.py
python
SegmentReader.all_stored_fields
(self)
return self._perdoc.all_stored_fields()
[]
def all_stored_fields(self): if self.is_closed: raise ReaderClosed return self._perdoc.all_stored_fields()
[ "def", "all_stored_fields", "(", "self", ")", ":", "if", "self", ".", "is_closed", ":", "raise", "ReaderClosed", "return", "self", ".", "_perdoc", ".", "all_stored_fields", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/reading.py#L702-L705
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_scale.py
python
Yedit.append
(self, path, value)
return (True, self.yaml_dict)
append value to a list
append value to a list
[ "append", "value", "to", "a", "list" ]
def append(self, path, value): '''append value to a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if entry is None: self.put(path, []) entry = Yedit.get_entry(self.yaml_dict, path, self.separator) if not isinstance(entry, list): return (False, self.yaml_dict) # AUDIT:maybe-no-member makes sense due to loading data from # a serialized format. # pylint: disable=maybe-no-member entry.append(value) return (True, self.yaml_dict)
[ "def", "append", "(", "self", ",", "path", ",", "value", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separator", ")", "except", "KeyError", ":", "entry", "=", "None", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_scale.py#L517-L534
minio/minio-py
b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3
minio/notificationconfig.py
python
QueueConfig.queue
(self)
return self._queue
Get queue ARN.
Get queue ARN.
[ "Get", "queue", "ARN", "." ]
def queue(self): """Get queue ARN.""" return self._queue
[ "def", "queue", "(", "self", ")", ":", "return", "self", ".", "_queue" ]
https://github.com/minio/minio-py/blob/b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3/minio/notificationconfig.py#L199-L201
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/OpenSSL/crypto.py
python
_new_mem_buf
(buffer=None)
return bio
Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out.
Allocate a new OpenSSL memory BIO.
[ "Allocate", "a", "new", "OpenSSL", "memory", "BIO", "." ]
def _new_mem_buf(buffer=None): """ Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out. """ if buffer is None: bio = _lib.BIO_new(_lib.BIO_s_mem()) free = _lib.BIO_free else: data = _ffi.new("char[]", buffer) bio = _lib.BIO_new_mem_buf(data, len(buffer)) # Keep the memory alive as long as the bio is alive! def free(bio, ref=data): return _lib.BIO_free(bio) _openssl_assert(bio != _ffi.NULL) bio = _ffi.gc(bio, free) return bio
[ "def", "_new_mem_buf", "(", "buffer", "=", "None", ")", ":", "if", "buffer", "is", "None", ":", "bio", "=", "_lib", ".", "BIO_new", "(", "_lib", ".", "BIO_s_mem", "(", ")", ")", "free", "=", "_lib", ".", "BIO_free", "else", ":", "data", "=", "_ffi"...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/OpenSSL/crypto.py#L67-L90
emcconville/wand
03682680c351645f16c3b8ea23bde79fbb270305
wand/image.py
python
BaseImage.solarize
(self, threshold=0.0, channel=None)
return r
Simulates extreme overexposure. :see: Example of :ref:`solarize`. :param threshold: between ``0.0`` and :attr:`quantum_range`. :type threshold: :class:`numbers.Real` :param channel: Optional color channel to target. See :const:`CHANNELS` :type channel: :class:`basestring` .. versionadded:: 0.5.3 .. versionchanged:: 0.5.5 Added ``channel`` argument.
Simulates extreme overexposure.
[ "Simulates", "extreme", "overexposure", "." ]
def solarize(self, threshold=0.0, channel=None): """Simulates extreme overexposure. :see: Example of :ref:`solarize`. :param threshold: between ``0.0`` and :attr:`quantum_range`. :type threshold: :class:`numbers.Real` :param channel: Optional color channel to target. See :const:`CHANNELS` :type channel: :class:`basestring` .. versionadded:: 0.5.3 .. versionchanged:: 0.5.5 Added ``channel`` argument. """ assertions.assert_real(threshold=threshold) if channel is None: r = library.MagickSolarizeImage(self.wand, threshold) else: channel_ch = self._channel_to_mask(channel) if MAGICK_VERSION_NUMBER < 0x700: r = library.MagickSolarizeImageChannel(self.wand, channel_ch, threshold) else: # pragma: no cover mask = library.MagickSetImageChannelMask(self.wand, channel_ch) r = library.MagickSolarizeImage(self.wand, threshold) library.MagickSetImageChannelMask(self.wand, mask) return r
[ "def", "solarize", "(", "self", ",", "threshold", "=", "0.0", ",", "channel", "=", "None", ")", ":", "assertions", ".", "assert_real", "(", "threshold", "=", "threshold", ")", "if", "channel", "is", "None", ":", "r", "=", "library", ".", "MagickSolarizeI...
https://github.com/emcconville/wand/blob/03682680c351645f16c3b8ea23bde79fbb270305/wand/image.py#L8070-L8099
jameskermode/f90wrap
6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e
f90wrap/fortran.py
python
f2py_type
(type, attributes=None)
return pytype
Convert string repr of Fortran type to equivalent Python type
Convert string repr of Fortran type to equivalent Python type
[ "Convert", "string", "repr", "of", "Fortran", "type", "to", "equivalent", "Python", "type" ]
def f2py_type(type, attributes=None): """ Convert string repr of Fortran type to equivalent Python type """ if attributes is None: attributes = [] if "real" in type: pytype = "float" elif "integer" in type: pytype = "int" elif "character" in type: pytype = 'str' elif "logical" in type: pytype = "bool" elif "complex" in type: pytype = 'complex' elif type.startswith("type"): pytype = strip_type(type).title() else: pytype = "unknown" dims = list(filter(lambda x: x.startswith("dimension"), attributes)) if len(dims) > 0: pytype += " array" return pytype
[ "def", "f2py_type", "(", "type", ",", "attributes", "=", "None", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "[", "]", "if", "\"real\"", "in", "type", ":", "pytype", "=", "\"float\"", "elif", "\"integer\"", "in", "type", ":", "p...
https://github.com/jameskermode/f90wrap/blob/6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e/f90wrap/fortran.py#L944-L968
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/recurring_payments/models.py
python
RecurringPayment.get_absolute_url
(self)
return reverse('recurring_payment.view_account', args=[self.id])
[]
def get_absolute_url(self): return reverse('recurring_payment.view_account', args=[self.id])
[ "def", "get_absolute_url", "(", "self", ")", ":", "return", "reverse", "(", "'recurring_payment.view_account'", ",", "args", "=", "[", "self", ".", "id", "]", ")" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/recurring_payments/models.py#L118-L119
mithril-global/GoAgentX
788fbd5e1c824c75cf98a9aef8a6d4ec8df25e95
GoAgentX.app/Contents/PlugIns/shadowsocks.gxbundle/Contents/Resources/bin/python/M2Crypto/SSL/Context.py
python
Context.set_verify
(self, mode, depth, callback=None)
Set verify options. Most applications will need to call this method with the right options to make a secure SSL connection. @param mode: The verification mode to use. Typically at least SSL.verify_peer is used. Clients would also typically add SSL.verify_fail_if_no_peer_cert. @type mode: int @param depth: The maximum allowed depth of the certificate chain returned by the peer. @type depth: int @param callback: Callable that can be used to specify custom verification checks.
Set verify options. Most applications will need to call this method with the right options to make a secure SSL connection.
[ "Set", "verify", "options", ".", "Most", "applications", "will", "need", "to", "call", "this", "method", "with", "the", "right", "options", "to", "make", "a", "secure", "SSL", "connection", "." ]
def set_verify(self, mode, depth, callback=None): """ Set verify options. Most applications will need to call this method with the right options to make a secure SSL connection. @param mode: The verification mode to use. Typically at least SSL.verify_peer is used. Clients would also typically add SSL.verify_fail_if_no_peer_cert. @type mode: int @param depth: The maximum allowed depth of the certificate chain returned by the peer. @type depth: int @param callback: Callable that can be used to specify custom verification checks. """ if callback is None: m2.ssl_ctx_set_verify_default(self.ctx, mode) else: m2.ssl_ctx_set_verify(self.ctx, mode, callback) m2.ssl_ctx_set_verify_depth(self.ctx, depth)
[ "def", "set_verify", "(", "self", ",", "mode", ",", "depth", ",", "callback", "=", "None", ")", ":", "if", "callback", "is", "None", ":", "m2", ".", "ssl_ctx_set_verify_default", "(", "self", ".", "ctx", ",", "mode", ")", "else", ":", "m2", ".", "ssl...
https://github.com/mithril-global/GoAgentX/blob/788fbd5e1c824c75cf98a9aef8a6d4ec8df25e95/GoAgentX.app/Contents/PlugIns/shadowsocks.gxbundle/Contents/Resources/bin/python/M2Crypto/SSL/Context.py#L156-L175
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/integrations/vacuum/viomi/viomivacuum.py
python
ViomiVacuum.set_sound_volume
(self, volume: int)
return self.send("set_voice", [enabled, volume])
Switch the voice on or off.
Switch the voice on or off.
[ "Switch", "the", "voice", "on", "or", "off", "." ]
def set_sound_volume(self, volume: int): """Switch the voice on or off.""" enabled = 1 if volume == 0: enabled = 0 return self.send("set_voice", [enabled, volume])
[ "def", "set_sound_volume", "(", "self", ",", "volume", ":", "int", ")", ":", "enabled", "=", "1", "if", "volume", "==", "0", ":", "enabled", "=", "0", "return", "self", ".", "send", "(", "\"set_voice\"", ",", "[", "enabled", ",", "volume", "]", ")" ]
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/integrations/vacuum/viomi/viomivacuum.py#L785-L790
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1alpha1_pod_preset_spec.py
python
V1alpha1PodPresetSpec.volumes
(self)
return self._volumes
Gets the volumes of this V1alpha1PodPresetSpec. Volumes defines the collection of Volume to inject into the pod. :return: The volumes of this V1alpha1PodPresetSpec. :rtype: list[V1Volume]
Gets the volumes of this V1alpha1PodPresetSpec. Volumes defines the collection of Volume to inject into the pod.
[ "Gets", "the", "volumes", "of", "this", "V1alpha1PodPresetSpec", ".", "Volumes", "defines", "the", "collection", "of", "Volume", "to", "inject", "into", "the", "pod", "." ]
def volumes(self): """ Gets the volumes of this V1alpha1PodPresetSpec. Volumes defines the collection of Volume to inject into the pod. :return: The volumes of this V1alpha1PodPresetSpec. :rtype: list[V1Volume] """ return self._volumes
[ "def", "volumes", "(", "self", ")", ":", "return", "self", ".", "_volumes" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1alpha1_pod_preset_spec.py#L148-L156
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cuda/libdevice.py
python
byte_perm
(x, y, z)
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_byte_perm.html :param x: Argument. :type x: int32 :param y: Argument. :type y: int32 :param z: Argument. :type z: int32 :rtype: int32
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_byte_perm.html
[ "See", "https", ":", "//", "docs", ".", "nvidia", ".", "com", "/", "cuda", "/", "libdevice", "-", "users", "-", "guide", "/", "__nv_byte_perm", ".", "html" ]
def byte_perm(x, y, z): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_byte_perm.html :param x: Argument. :type x: int32 :param y: Argument. :type y: int32 :param z: Argument. :type z: int32 :rtype: int32 """
[ "def", "byte_perm", "(", "x", ",", "y", ",", "z", ")", ":" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/libdevice.py#L175-L186
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/tenacity/__init__.py
python
retry
(*dargs: t.Any, **dkw: t.Any)
[]
def retry(*dargs: t.Any, **dkw: t.Any) -> t.Callable[[WrappedFn], WrappedFn]: # noqa pass
[ "def", "retry", "(", "*", "dargs", ":", "t", ".", "Any", ",", "*", "*", "dkw", ":", "t", ".", "Any", ")", "->", "t", ".", "Callable", "[", "[", "WrappedFn", "]", ",", "WrappedFn", "]", ":", "# noqa", "pass" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/tenacity/__init__.py#L103-L104
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/connection.py
python
_validate_algs
(config: SSHConfig, kex_algs_arg: _AlgsArg, enc_algs_arg: _AlgsArg, mac_algs_arg: _AlgsArg, cmp_algs_arg: _AlgsArg, sig_algs_arg: _AlgsArg, allow_x509: bool)
return kex_algs, enc_algs, mac_algs, cmp_algs, sig_algs
Validate requested algorithms
Validate requested algorithms
[ "Validate", "requested", "algorithms" ]
def _validate_algs(config: SSHConfig, kex_algs_arg: _AlgsArg, enc_algs_arg: _AlgsArg, mac_algs_arg: _AlgsArg, cmp_algs_arg: _AlgsArg, sig_algs_arg: _AlgsArg, allow_x509: bool) -> \ Tuple[Sequence[bytes], Sequence[bytes], Sequence[bytes], Sequence[bytes], Sequence[bytes]]: """Validate requested algorithms""" kex_algs = _select_algs('key exchange', kex_algs_arg, cast(_AlgsArg, config.get('KexAlgorithms', ())), get_kex_algs(), get_default_kex_algs()) enc_algs = _select_algs('encryption', enc_algs_arg, cast(_AlgsArg, config.get('Ciphers', ())), get_encryption_algs(), get_default_encryption_algs()) mac_algs = _select_algs('MAC', mac_algs_arg, cast(_AlgsArg, config.get('MACs', ())), get_mac_algs(), get_default_mac_algs()) cmp_algs = _select_algs('compression', cmp_algs_arg, cast(_AlgsArg, config.get_compression_algs()), get_compression_algs(), get_default_compression_algs(), b'none') allowed_sig_algs = get_x509_certificate_algs() if allow_x509 else [] allowed_sig_algs = allowed_sig_algs + get_public_key_algs() default_sig_algs = get_default_x509_certificate_algs() if allow_x509 else [] default_sig_algs = allowed_sig_algs + get_default_public_key_algs() sig_algs = _select_algs('signature', sig_algs_arg, cast(_AlgsArg, config.get('CASignatureAlgorithms', ())), allowed_sig_algs, default_sig_algs) return kex_algs, enc_algs, mac_algs, cmp_algs, sig_algs
[ "def", "_validate_algs", "(", "config", ":", "SSHConfig", ",", "kex_algs_arg", ":", "_AlgsArg", ",", "enc_algs_arg", ":", "_AlgsArg", ",", "mac_algs_arg", ":", "_AlgsArg", ",", "cmp_algs_arg", ":", "_AlgsArg", ",", "sig_algs_arg", ":", "_AlgsArg", ",", "allow_x5...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/connection.py#L601-L635
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/djangoapps/track/transformers.py
python
EventTransformer.transform
(self)
Transform the event with legacy fields and other necessary modifications.
Transform the event with legacy fields and other necessary modifications.
[ "Transform", "the", "event", "with", "legacy", "fields", "and", "other", "necessary", "modifications", "." ]
def transform(self): """ Transform the event with legacy fields and other necessary modifications. """ if self.is_legacy_event: self._set_legacy_event_type() self.process_legacy_fields() self.process_event() self.dump_payload()
[ "def", "transform", "(", "self", ")", ":", "if", "self", ".", "is_legacy_event", ":", "self", ".", "_set_legacy_event_type", "(", ")", "self", ".", "process_legacy_fields", "(", ")", "self", ".", "process_event", "(", ")", "self", ".", "dump_payload", "(", ...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/djangoapps/track/transformers.py#L241-L250
faucetsdn/ryu
537f35f4b2bc634ef05e3f28373eb5e24609f989
ryu/lib/stringify.py
python
StringifyMixin.from_jsondict
(cls, dict_, decode_string=base64.b64decode, **additional_args)
r"""Create an instance from a JSON style dict. Instantiate this class with parameters specified by the dict. This method takes the following arguments. .. tabularcolumns:: |l|L| =============== ===================================================== Argument Descrpition =============== ===================================================== dict\_ A dictionary which describes the parameters. For example, {"Param1": 100, "Param2": 200} decode_string (Optional) specify how to decode strings. The default is base64. This argument is used only for attributes which don't have explicit type annotations in _TYPE class attribute. additional_args (Optional) Additional kwargs for constructor. =============== =====================================================
r"""Create an instance from a JSON style dict.
[ "r", "Create", "an", "instance", "from", "a", "JSON", "style", "dict", "." ]
def from_jsondict(cls, dict_, decode_string=base64.b64decode, **additional_args): r"""Create an instance from a JSON style dict. Instantiate this class with parameters specified by the dict. This method takes the following arguments. .. tabularcolumns:: |l|L| =============== ===================================================== Argument Descrpition =============== ===================================================== dict\_ A dictionary which describes the parameters. For example, {"Param1": 100, "Param2": 200} decode_string (Optional) specify how to decode strings. The default is base64. This argument is used only for attributes which don't have explicit type annotations in _TYPE class attribute. additional_args (Optional) Additional kwargs for constructor. =============== ===================================================== """ decode = lambda k, x: cls._decode_value(k, x, decode_string, **additional_args) kwargs = cls._restore_args(_mapdict_kv(decode, dict_)) try: return cls(**dict(kwargs, **additional_args)) except TypeError: # debug print("CLS %s" % cls) print("ARG %s" % dict_) print("KWARG %s" % kwargs) raise
[ "def", "from_jsondict", "(", "cls", ",", "dict_", ",", "decode_string", "=", "base64", ".", "b64decode", ",", "*", "*", "additional_args", ")", ":", "decode", "=", "lambda", "k", ",", "x", ":", "cls", ".", "_decode_value", "(", "k", ",", "x", ",", "d...
https://github.com/faucetsdn/ryu/blob/537f35f4b2bc634ef05e3f28373eb5e24609f989/ryu/lib/stringify.py#L328-L361
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/plot/plotcanvas.py
python
PlotCanvas._getXCurrentRange
(self)
return self.last_draw[1]
Returns (minX, maxX) x-axis for currently displayed portion of graph
Returns (minX, maxX) x-axis for currently displayed portion of graph
[ "Returns", "(", "minX", "maxX", ")", "x", "-", "axis", "for", "currently", "displayed", "portion", "of", "graph" ]
def _getXCurrentRange(self): """Returns (minX, maxX) x-axis for currently displayed portion of graph""" return self.last_draw[1]
[ "def", "_getXCurrentRange", "(", "self", ")", ":", "return", "self", ".", "last_draw", "[", "1", "]" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/plot/plotcanvas.py#L1709-L1712
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/docview.py
python
CommandProcessor.Submit
(self, command, storeIt=True)
return done
Submits a new command to the command processor. The command processor calls :meth:`Command.Do` to execute the command; if it succeeds, the command is stored in the history list, and the associated edit menu (if any) updated appropriately. If it fails, the command is deleted immediately. Once Submit has been called, the passed command should not be deleted directly by the application. ``storeIt`` indicates whether the successful command should be stored in the history list.
Submits a new command to the command processor. The command processor calls :meth:`Command.Do` to execute the command; if it succeeds, the command is stored in the history list, and the associated edit menu (if any) updated appropriately. If it fails, the command is deleted immediately. Once Submit has been called, the passed command should not be deleted directly by the application.
[ "Submits", "a", "new", "command", "to", "the", "command", "processor", ".", "The", "command", "processor", "calls", ":", "meth", ":", "Command", ".", "Do", "to", "execute", "the", "command", ";", "if", "it", "succeeds", "the", "command", "is", "stored", ...
def Submit(self, command, storeIt=True): """ Submits a new command to the command processor. The command processor calls :meth:`Command.Do` to execute the command; if it succeeds, the command is stored in the history list, and the associated edit menu (if any) updated appropriately. If it fails, the command is deleted immediately. Once Submit has been called, the passed command should not be deleted directly by the application. ``storeIt`` indicates whether the successful command should be stored in the history list. """ done = command.Do() if done: del self._redoCommands[:] if storeIt: self._commands.append(command) if self._maxCommands > -1: if len(self._commands) > self._maxCommands: del self._commands[0] return done
[ "def", "Submit", "(", "self", ",", "command", ",", "storeIt", "=", "True", ")", ":", "done", "=", "command", ".", "Do", "(", ")", "if", "done", ":", "del", "self", ".", "_redoCommands", "[", ":", "]", "if", "storeIt", ":", "self", ".", "_commands",...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/docview.py#L3162-L3182
vsitzmann/siren
4df34baee3f0f9c8f351630992c1fe1f69114b5f
make_figures.py
python
glob_all_imgs
(trgt_dir)
return all_imgs
Returns list of all images in trgt_dir
Returns list of all images in trgt_dir
[ "Returns", "list", "of", "all", "images", "in", "trgt_dir" ]
def glob_all_imgs(trgt_dir): '''Returns list of all images in trgt_dir ''' all_imgs = [] for ending in ['*.png', '*.tiff', '*.tif', '*.jpeg', '*.JPEG', '*.jpg', '*.bmp']: all_imgs.extend(glob.glob(os.path.join(trgt_dir, ending))) return all_imgs
[ "def", "glob_all_imgs", "(", "trgt_dir", ")", ":", "all_imgs", "=", "[", "]", "for", "ending", "in", "[", "'*.png'", ",", "'*.tiff'", ",", "'*.tif'", ",", "'*.jpeg'", ",", "'*.JPEG'", ",", "'*.jpg'", ",", "'*.bmp'", "]", ":", "all_imgs", ".", "extend", ...
https://github.com/vsitzmann/siren/blob/4df34baee3f0f9c8f351630992c1fe1f69114b5f/make_figures.py#L197-L204
microsoft/debugpy
be8dd607f6837244e0b565345e497aff7a0c08bf
src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/defines.py
python
MakeWideVersion
(fn)
return wrapper
Decorator that generates a Unicode (wide) version of an ANSI only API call. @type fn: callable @param fn: ANSI version of the API function to call.
Decorator that generates a Unicode (wide) version of an ANSI only API call.
[ "Decorator", "that", "generates", "a", "Unicode", "(", "wide", ")", "version", "of", "an", "ANSI", "only", "API", "call", "." ]
def MakeWideVersion(fn): """ Decorator that generates a Unicode (wide) version of an ANSI only API call. @type fn: callable @param fn: ANSI version of the API function to call. """ @functools.wraps(fn) def wrapper(*argv, **argd): t_ansi = GuessStringType.t_ansi t_unicode = GuessStringType.t_unicode v_types = [ type(item) for item in argv ] v_types.extend( [ type(value) for (key, value) in compat.iteritems(argd) ] ) if t_unicode in v_types: argv = list(argv) for index in compat.xrange(len(argv)): if v_types[index] == t_unicode: argv[index] = t_ansi(argv[index]) for key, value in argd.items(): if type(value) == t_unicode: argd[key] = t_ansi(value) return fn(*argv, **argd) return wrapper
[ "def", "MakeWideVersion", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "argv", ",", "*", "*", "argd", ")", ":", "t_ansi", "=", "GuessStringType", ".", "t_ansi", "t_unicode", "=", "GuessStringType", "....
https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/defines.py#L328-L350
instrumenta/openapi2jsonschema
d697cbff8a25f520e125e3a5f79cb4e9b972e8ce
openapi2jsonschema/util.py
python
append_no_duplicates
(obj, key, value)
Given a dictionary, lookup the given key, if it doesn't exist create a new array. Then check if the given value already exists in the array, if it doesn't add it.
Given a dictionary, lookup the given key, if it doesn't exist create a new array. Then check if the given value already exists in the array, if it doesn't add it.
[ "Given", "a", "dictionary", "lookup", "the", "given", "key", "if", "it", "doesn", "t", "exist", "create", "a", "new", "array", ".", "Then", "check", "if", "the", "given", "value", "already", "exists", "in", "the", "array", "if", "it", "doesn", "t", "ad...
def append_no_duplicates(obj, key, value): """ Given a dictionary, lookup the given key, if it doesn't exist create a new array. Then check if the given value already exists in the array, if it doesn't add it. """ if key not in obj: obj[key] = [] if value not in obj[key]: obj[key].append(value)
[ "def", "append_no_duplicates", "(", "obj", ",", "key", ",", "value", ")", ":", "if", "key", "not", "in", "obj", ":", "obj", "[", "key", "]", "=", "[", "]", "if", "value", "not", "in", "obj", "[", "key", "]", ":", "obj", "[", "key", "]", ".", ...
https://github.com/instrumenta/openapi2jsonschema/blob/d697cbff8a25f520e125e3a5f79cb4e9b972e8ce/openapi2jsonschema/util.py#L102-L110
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/statistics.py
python
median_high
(data)
return data[n//2]
Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. >>> median_high([1, 3, 5]) 3 >>> median_high([1, 3, 5, 7]) 5
Return the high median of data.
[ "Return", "the", "high", "median", "of", "data", "." ]
def median_high(data): """Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. >>> median_high([1, 3, 5]) 3 >>> median_high([1, 3, 5, 7]) 5 """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") return data[n//2]
[ "def", "median_high", "(", "data", ")", ":", "data", "=", "sorted", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "==", "0", ":", "raise", "StatisticsError", "(", "\"no median for empty data\"", ")", "return", "data", "[", "n", "//", ...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/statistics.py#L410-L426
shapely/shapely
9258e6dd4dcca61699d69c2a5853a486b132ed86
shapely/io.py
python
from_geojson
(geometry, on_invalid="raise", **kwargs)
return lib.from_geojson(geometry, invalid_handler, **kwargs)
Creates geometries from GeoJSON representations (strings). If a GeoJSON is a FeatureCollection, it is read as a single geometry (with type GEOMETRYCOLLECTION). This may be unpacked using the ``pygeos.get_parts``. Properties are not read. The GeoJSON format is defined in `RFC 7946 <https://geojson.org/>`__. The following are currently unsupported: - Three-dimensional geometries: the third dimension is ignored. - Geometries having 'null' in the coordinates. Parameters ---------- geometry : str, bytes or array_like The GeoJSON string or byte object(s) to convert. on_invalid : {"raise", "warn", "ignore"}, default "raise" - raise: an exception will be raised if an input GeoJSON is invalid. - warn: a warning will be raised and invalid input geometries will be returned as ``None``. - ignore: invalid input geometries will be returned as ``None`` without a warning. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- get_parts Examples -------- >>> from_geojson('{"type": "Point","coordinates": [1, 2]}') <pygeos.Geometry POINT (1 2)>
Creates geometries from GeoJSON representations (strings).
[ "Creates", "geometries", "from", "GeoJSON", "representations", "(", "strings", ")", "." ]
def from_geojson(geometry, on_invalid="raise", **kwargs): """Creates geometries from GeoJSON representations (strings). If a GeoJSON is a FeatureCollection, it is read as a single geometry (with type GEOMETRYCOLLECTION). This may be unpacked using the ``pygeos.get_parts``. Properties are not read. The GeoJSON format is defined in `RFC 7946 <https://geojson.org/>`__. The following are currently unsupported: - Three-dimensional geometries: the third dimension is ignored. - Geometries having 'null' in the coordinates. Parameters ---------- geometry : str, bytes or array_like The GeoJSON string or byte object(s) to convert. on_invalid : {"raise", "warn", "ignore"}, default "raise" - raise: an exception will be raised if an input GeoJSON is invalid. - warn: a warning will be raised and invalid input geometries will be returned as ``None``. - ignore: invalid input geometries will be returned as ``None`` without a warning. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- get_parts Examples -------- >>> from_geojson('{"type": "Point","coordinates": [1, 2]}') <pygeos.Geometry POINT (1 2)> """ # GEOS Tickets: # - support 3D: https://trac.osgeo.org/geos/ticket/1141 # - handle null coordinates: https://trac.osgeo.org/geos/ticket/1142 if not np.isscalar(on_invalid): raise TypeError("on_invalid only accepts scalar values") invalid_handler = np.uint8(DecodingErrorOptions.get_value(on_invalid)) # ensure the input has object dtype, to avoid numpy inferring it as a # fixed-length string dtype (which removes trailing null bytes upon access # of array elements) geometry = np.asarray(geometry, dtype=object) return lib.from_geojson(geometry, invalid_handler, **kwargs)
[ "def", "from_geojson", "(", "geometry", ",", "on_invalid", "=", "\"raise\"", ",", "*", "*", "kwargs", ")", ":", "# GEOS Tickets:", "# - support 3D: https://trac.osgeo.org/geos/ticket/1141", "# - handle null coordinates: https://trac.osgeo.org/geos/ticket/1142", "if", "not", "np...
https://github.com/shapely/shapely/blob/9258e6dd4dcca61699d69c2a5853a486b132ed86/shapely/io.py#L293-L342
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/engine/processing_status.py
python
ProcessStatus.UpdateNumberOfEventReports
( self, number_of_consumed_reports, number_of_produced_reports)
Updates the number of event reports. Args: number_of_consumed_reports (int): total number of event reports consumed by the process. number_of_produced_reports (int): total number of event reports produced by the process. Raises: ValueError: if the consumed or produced number of event reports is smaller than the value of the previous update.
Updates the number of event reports.
[ "Updates", "the", "number", "of", "event", "reports", "." ]
def UpdateNumberOfEventReports( self, number_of_consumed_reports, number_of_produced_reports): """Updates the number of event reports. Args: number_of_consumed_reports (int): total number of event reports consumed by the process. number_of_produced_reports (int): total number of event reports produced by the process. Raises: ValueError: if the consumed or produced number of event reports is smaller than the value of the previous update. """ if number_of_consumed_reports is not None: if number_of_consumed_reports < self.number_of_consumed_reports: raise ValueError( 'Number of consumed reports smaller than previous update.') self.number_of_consumed_reports_delta = ( number_of_consumed_reports - self.number_of_consumed_reports) self.number_of_consumed_reports = number_of_consumed_reports if number_of_produced_reports is not None: if number_of_produced_reports < self.number_of_produced_reports: raise ValueError( 'Number of produced reports smaller than previous update.') self.number_of_produced_reports_delta = ( number_of_produced_reports - self.number_of_produced_reports) self.number_of_produced_reports = number_of_produced_reports
[ "def", "UpdateNumberOfEventReports", "(", "self", ",", "number_of_consumed_reports", ",", "number_of_produced_reports", ")", ":", "if", "number_of_consumed_reports", "is", "not", "None", ":", "if", "number_of_consumed_reports", "<", "self", ".", "number_of_consumed_reports"...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/engine/processing_status.py#L76-L106
Blizzard/s2protocol
4bfe857bb832eee12cc6307dd699e3b74bd7e1b2
s2protocol/versions/protocol32283.py
python
decode_replay_game_events
(contents)
Decodes and yields each game event from the contents byte string.
Decodes and yields each game event from the contents byte string.
[ "Decodes", "and", "yields", "each", "game", "event", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_game_events(contents): """Decodes and yields each game event from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) for event in _decode_event_stream(decoder, game_eventid_typeid, game_event_types, decode_user_id=True): yield event
[ "def", "decode_replay_game_events", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "for", "event", "in", "_decode_event_stream", "(", "decoder", ",", "game_eventid_typeid", ",", "game_event_types", ",", "decode...
https://github.com/Blizzard/s2protocol/blob/4bfe857bb832eee12cc6307dd699e3b74bd7e1b2/s2protocol/versions/protocol32283.py#L392-L399
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_policy_user.py
python
Yedit.remove_entry
(data, key, index=None, value=None, sep='.')
remove data at location key
remove data at location key
[ "remove", "data", "at", "location", "key" ]
def remove_entry(data, key, index=None, value=None, sep='.'): ''' remove data at location key ''' if key == '' and isinstance(data, dict): if value is not None: data.pop(value) elif index is not None: raise YeditException("remove_entry for a dictionary does not have an index {}".format(index)) else: data.clear() return True elif key == '' and isinstance(data, list): ind = None if value is not None: try: ind = data.index(value) except ValueError: return False elif index is not None: ind = index else: del data[:] if ind is not None: data.pop(ind) return True if not (key and Yedit.valid_key(key, sep)) and \ isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None # process last index for remove # expected list entry if key_indexes[-1][0]: if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501 del data[int(key_indexes[-1][0])] return True # expected dict entry elif key_indexes[-1][1]: if isinstance(data, dict): del data[key_indexes[-1][1]] return True
[ "def", "remove_entry", "(", "data", ",", "key", ",", "index", "=", "None", ",", "value", "=", "None", ",", "sep", "=", "'.'", ")", ":", "if", "key", "==", "''", "and", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "value", "is", "not", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_policy_user.py#L226-L280
google/Legilimency
02cd38fd82a90bca789b8bf61c88f4bc5dd1eb07
BCMClient.py
python
BCMClient.fw_check_range
(self, fw_addr, size)
Checks that the given address range falls within the firmware's TCM, and raises an exception otherwise.
Checks that the given address range falls within the firmware's TCM, and raises an exception otherwise.
[ "Checks", "that", "the", "given", "address", "range", "falls", "within", "the", "firmware", "s", "TCM", "and", "raises", "an", "exception", "otherwise", "." ]
def fw_check_range(self, fw_addr, size): """ Checks that the given address range falls within the firmware's TCM, and raises an exception otherwise. """ if not (self.ram_offset <= fw_addr <= (self.ram_offset + self.ram_size)) or \ not (self.ram_offset <= (fw_addr + size) <= (self.ram_offset + self.ram_size)): raise Exception("Illegal FW read range: [%08X,%08X]" % (fw_addr, fw_addr + size))
[ "def", "fw_check_range", "(", "self", ",", "fw_addr", ",", "size", ")", ":", "if", "not", "(", "self", ".", "ram_offset", "<=", "fw_addr", "<=", "(", "self", ".", "ram_offset", "+", "self", ".", "ram_size", ")", ")", "or", "not", "(", "self", ".", ...
https://github.com/google/Legilimency/blob/02cd38fd82a90bca789b8bf61c88f4bc5dd1eb07/BCMClient.py#L116-L124
johntruckenbrodt/pyroSAR
efac51134ba42d20120b259f968afe5a4ddcc46a
pyroSAR/gamma/parser_demo.py
python
par_ASF_91
(CEOS_leader, CEOS_trailer, SLC_par, logpath=None, outdir=None, shellscript=None)
| SLC parameter file for data data from theAlaska SAR Facility (1991-1996) | Copyright 2008, Gamma Remote Sensing, v3.3 25-Mar-2008 clw/uw Parameters ---------- CEOS_leader: (input) ASF CEOS leader file CEOS_trailer: (input) ASF CEOS trailer file SLC_par: (output) ISP SLC image parameter file logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format
| SLC parameter file for data data from theAlaska SAR Facility (1991-1996) | Copyright 2008, Gamma Remote Sensing, v3.3 25-Mar-2008 clw/uw
[ "|", "SLC", "parameter", "file", "for", "data", "data", "from", "theAlaska", "SAR", "Facility", "(", "1991", "-", "1996", ")", "|", "Copyright", "2008", "Gamma", "Remote", "Sensing", "v3", ".", "3", "25", "-", "Mar", "-", "2008", "clw", "/", "uw" ]
def par_ASF_91(CEOS_leader, CEOS_trailer, SLC_par, logpath=None, outdir=None, shellscript=None): """ | SLC parameter file for data data from theAlaska SAR Facility (1991-1996) | Copyright 2008, Gamma Remote Sensing, v3.3 25-Mar-2008 clw/uw Parameters ---------- CEOS_leader: (input) ASF CEOS leader file CEOS_trailer: (input) ASF CEOS trailer file SLC_par: (output) ISP SLC image parameter file logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format """ process(['/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/par_ASF_91', CEOS_leader, CEOS_trailer, SLC_par], logpath=logpath, outdir=outdir, shellscript=shellscript)
[ "def", "par_ASF_91", "(", "CEOS_leader", ",", "CEOS_trailer", ",", "SLC_par", ",", "logpath", "=", "None", ",", "outdir", "=", "None", ",", "shellscript", "=", "None", ")", ":", "process", "(", "[", "'/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/par_ASF_91'", ",", ...
https://github.com/johntruckenbrodt/pyroSAR/blob/efac51134ba42d20120b259f968afe5a4ddcc46a/pyroSAR/gamma/parser_demo.py#L2517-L2538
knipknap/exscript
a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83
Exscript/util/url.py
python
Url.to_string
(self)
return str(self)
Returns the URL, including all attributes, as a string. :rtype: str :return: A URL.
Returns the URL, including all attributes, as a string.
[ "Returns", "the", "URL", "including", "all", "attributes", "as", "a", "string", "." ]
def to_string(self): """ Returns the URL, including all attributes, as a string. :rtype: str :return: A URL. """ return str(self)
[ "def", "to_string", "(", "self", ")", ":", "return", "str", "(", "self", ")" ]
https://github.com/knipknap/exscript/blob/a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83/Exscript/util/url.py#L157-L164
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
plugins/autodock_plugin.py
python
DirDialogButtonClassFactory.get
(fn)
return DirDialogButton
This returns a FileDialogButton class that will call the specified function with the resulting file.
This returns a FileDialogButton class that will call the specified function with the resulting file.
[ "This", "returns", "a", "FileDialogButton", "class", "that", "will", "call", "the", "specified", "function", "with", "the", "resulting", "file", "." ]
def get(fn): """This returns a FileDialogButton class that will call the specified function with the resulting file. """ class DirDialogButton(Tkinter.Button): # This is just an ordinary button with special colors. def __init__(self, master=None, cnf={}, **kw): '''when we get a file, we call fn(filename)''' self.fn = fn self.__toggle = 0 Tkinter.Button.__init__(self, master, cnf, **kw) self.configure(command=self.set) def set(self): fd = PmwDirDialog(self.master) fd.title('Please choose a directory') n = fd.askfilename() if n is not None: self.fn(n) return DirDialogButton
[ "def", "get", "(", "fn", ")", ":", "class", "DirDialogButton", "(", "Tkinter", ".", "Button", ")", ":", "# This is just an ordinary button with special colors.", "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*",...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/plugins/autodock_plugin.py#L3050-L3070
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/solver/fastai_optim.py
python
FastAIMixedOptim.step
(self)
[]
def step(self): model_g2master_g(self.model_params, self.master_params, self.flat_master) for group in self.master_params: for param in group: param.grad.div_(self.loss_scale) super(FastAIMixedOptim, self).step() self.model.zero_grad() # Update the params from master to model. master2model(self.model_params, self.master_params, self.flat_master)
[ "def", "step", "(", "self", ")", ":", "model_g2master_g", "(", "self", ".", "model_params", ",", "self", ".", "master_params", ",", "self", ".", "flat_master", ")", "for", "group", "in", "self", ".", "master_params", ":", "for", "param", "in", "group", "...
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/solver/fastai_optim.py#L298-L306
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/path.py
python
Path.to_polygons
(self, transform=None, width=0, height=0)
return _path.convert_path_to_polygons(self, transform, width, height)
Convert this path to a list of polygons. Each polygon is an Nx2 array of vertices. In other words, each polygon has no ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK. If *width* and *height* are both non-zero then the lines will be simplified so that vertices outside of (0, 0), (width, height) will be clipped.
Convert this path to a list of polygons. Each polygon is an Nx2 array of vertices. In other words, each polygon has no ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK.
[ "Convert", "this", "path", "to", "a", "list", "of", "polygons", ".", "Each", "polygon", "is", "an", "Nx2", "array", "of", "vertices", ".", "In", "other", "words", "each", "polygon", "has", "no", "MOVETO", "instructions", "or", "curves", ".", "This", "is"...
def to_polygons(self, transform=None, width=0, height=0): """ Convert this path to a list of polygons. Each polygon is an Nx2 array of vertices. In other words, each polygon has no ``MOVETO`` instructions or curves. This is useful for displaying in backends that do not support compound paths or Bezier curves, such as GDK. If *width* and *height* are both non-zero then the lines will be simplified so that vertices outside of (0, 0), (width, height) will be clipped. """ if len(self.vertices) == 0: return [] if transform is not None: transform = transform.frozen() if self.codes is None and (width == 0 or height == 0): if transform is None: return [self.vertices] else: return [transform.transform(self.vertices)] # Deal with the case where there are curves and/or multiple # subpaths (using extension code) return _path.convert_path_to_polygons(self, transform, width, height)
[ "def", "to_polygons", "(", "self", ",", "transform", "=", "None", ",", "width", "=", "0", ",", "height", "=", "0", ")", ":", "if", "len", "(", "self", ".", "vertices", ")", "==", "0", ":", "return", "[", "]", "if", "transform", "is", "not", "None...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/path.py#L563-L589
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/ui/mainwindow.py
python
MainWindow.update_script_editor_example_files
(self)
Update the list of example files for the file naming script editor.
Update the list of example files for the file naming script editor.
[ "Update", "the", "list", "of", "example", "files", "for", "the", "file", "naming", "script", "editor", "." ]
def update_script_editor_example_files(self): """Update the list of example files for the file naming script editor. """ if self.examples: self.examples.update_sample_example_files() self.update_script_editor_examples()
[ "def", "update_script_editor_example_files", "(", "self", ")", ":", "if", "self", ".", "examples", ":", "self", ".", "examples", ".", "update_sample_example_files", "(", ")", "self", ".", "update_script_editor_examples", "(", ")" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/ui/mainwindow.py#L1699-L1704
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/plugins/generic/takeover.py
python
Takeover.osSmb
(self)
[]
def osSmb(self): self.checkDbmsOs() if not Backend.isOs(OS.WINDOWS): errMsg = "the back-end DBMS underlying operating system is " errMsg += "not Windows: it is not possible to perform the SMB " errMsg += "relay attack" raise SqlmapUnsupportedDBMSException(errMsg) if not isStackingAvailable() and not conf.direct: if Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.MSSQL): errMsg = "on this back-end DBMS it is only possible to " errMsg += "perform the SMB relay attack if stacked " errMsg += "queries are supported" raise SqlmapUnsupportedDBMSException(errMsg) elif Backend.isDbms(DBMS.MYSQL): debugMsg = "since stacked queries are not supported, " debugMsg += "sqlmap is going to perform the SMB relay " debugMsg += "attack via inference blind SQL injection" logger.debug(debugMsg) printWarn = True warnMsg = "it is unlikely that this attack will be successful " if Backend.isDbms(DBMS.MYSQL): warnMsg += "because by default MySQL on Windows runs as " warnMsg += "Local System which is not a real user, it does " warnMsg += "not send the NTLM session hash when connecting to " warnMsg += "a SMB service" elif Backend.isDbms(DBMS.PGSQL): warnMsg += "because by default PostgreSQL on Windows runs " warnMsg += "as postgres user which is a real user of the " warnMsg += "system, but not within the Administrators group" elif Backend.isDbms(DBMS.MSSQL) and Backend.isVersionWithin(("2005", "2008")): warnMsg += "because often Microsoft SQL Server %s " % Backend.getVersion() warnMsg += "runs as Network Service which is not a real user, " warnMsg += "it does not send the NTLM session hash when " warnMsg += "connecting to a SMB service" else: printWarn = False if printWarn: logger.warn(warnMsg) self.smb()
[ "def", "osSmb", "(", "self", ")", ":", "self", ".", "checkDbmsOs", "(", ")", "if", "not", "Backend", ".", "isOs", "(", "OS", ".", "WINDOWS", ")", ":", "errMsg", "=", "\"the back-end DBMS underlying operating system is \"", "errMsg", "+=", "\"not Windows: it is n...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/plugins/generic/takeover.py#L271-L319
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/pyparsing.py
python
Regex.sub
(self, repl)
return self.addParseAction(pa)
r""" Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") print(make_html.transformString("h1:main title:")) # prints "<h1>main title</h1>"
r""" Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
[ "r", "Return", "Regex", "with", "an", "attached", "parse", "action", "to", "transform", "the", "parsed", "result", "as", "if", "called", "using", "re", ".", "sub", "(", "expr", "repl", "string", ")", "<https", ":", "//", "docs", ".", "python", ".", "or...
def sub(self, repl): r""" Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") print(make_html.transformString("h1:main title:")) # prints "<h1>main title</h1>" """ if self.asGroupList: warnings.warn("cannot use sub() with Regex(asGroupList=True)", SyntaxWarning, stacklevel=2) raise SyntaxError() if self.asMatch and callable(repl): warnings.warn("cannot use sub() with a callable with Regex(asMatch=True)", SyntaxWarning, stacklevel=2) raise SyntaxError() if self.asMatch: def pa(tokens): return tokens[0].expand(repl) else: def pa(tokens): return self.re.sub(repl, tokens[0]) return self.addParseAction(pa)
[ "def", "sub", "(", "self", ",", "repl", ")", ":", "if", "self", ".", "asGroupList", ":", "warnings", ".", "warn", "(", "\"cannot use sub() with Regex(asGroupList=True)\"", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "raise", "SyntaxError", "(", ")"...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/pyparsing.py#L3381-L3408
nltk/nltk_contrib
c9da2c29777ca9df650740145f1f4a375ccac961
nltk_contrib/fst/draw_graph.py
python
GraphWidget.arrange
(self, arrange_algorithm=None, toplevel=None)
Set the node positions. This routine should attempt to minimize the number of crossing edges, in order to make the graph easier to read.
Set the node positions. This routine should attempt to minimize the number of crossing edges, in order to make the graph easier to read.
[ "Set", "the", "node", "positions", ".", "This", "routine", "should", "attempt", "to", "minimize", "the", "number", "of", "crossing", "edges", "in", "order", "to", "make", "the", "graph", "easier", "to", "read", "." ]
def arrange(self, arrange_algorithm=None, toplevel=None): """ Set the node positions. This routine should attempt to minimize the number of crossing edges, in order to make the graph easier to read. """ if arrange_algorithm is not None: self._arrange = arrange_algorithm self._arrange_into_levels(toplevel) self._arrange_levels() (old_left, old_top) = self.bbox()[:2] for node in self._nodes: (x1, y1) = node.bbox()[:2] node.move(-x1, -y1) # Now we want to minimize crossing edges.. how, again? :) for i in range(len(self._levels)): for j in range(len(self._levels[i])): if self._levels[i][j] is not None: node = self._levels[i][j] if self._orientation == 'horizontal': node.move(i*self._xspace, j*self._yspace) else: node.move(j*self._xspace, i*self._yspace) # If there is an edge from a node at the same # position within its level, but whose level is at # least 2 levels prior, then it's likely that that # edge goes through an intervening node; so if its # curve is zero, then increment it. for edge in self._inedges.get(node,[]): from_node = self._startnode[edge] from_levelnum = self._nodelevel[from_node] from_level = self._levels[from_levelnum] if (abs(i-from_levelnum)>1 and len(from_level) > j and from_node == from_level[j] and edge['curve'] == 0): edge['curve'] = -0.25 (left, top) = self.bbox()[:2] self.move(int(old_left-left), int(old_top-top))
[ "def", "arrange", "(", "self", ",", "arrange_algorithm", "=", "None", ",", "toplevel", "=", "None", ")", ":", "if", "arrange_algorithm", "is", "not", "None", ":", "self", ".", "_arrange", "=", "arrange_algorithm", "self", ".", "_arrange_into_levels", "(", "t...
https://github.com/nltk/nltk_contrib/blob/c9da2c29777ca9df650740145f1f4a375ccac961/nltk_contrib/fst/draw_graph.py#L377-L420
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/tamper/space2hash.py
python
dependencies
()
[]
def dependencies(): singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))
[ "def", "dependencies", "(", ")", ":", "singleTimeWarnMessage", "(", "\"tamper script '%s' is only meant to be run against %s\"", "%", "(", "os", ".", "path", ".", "basename", "(", "__file__", ")", ".", "split", "(", "\".\"", ")", "[", "0", "]", ",", "DBMS", "....
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/tamper/space2hash.py#L18-L19
eliben/code-for-blog
06d6887eccd84ca5703b792a85ab6c1ebfc5393e
2009/pygame_creeps_game/creeps.py
python
Creep.update
(self, time_passed)
Update the creep. time_passed: The time passed (in ms) since the previous update.
Update the creep. time_passed: The time passed (in ms) since the previous update.
[ "Update", "the", "creep", ".", "time_passed", ":", "The", "time", "passed", "(", "in", "ms", ")", "since", "the", "previous", "update", "." ]
def update(self, time_passed): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._compute_direction(time_passed) # Make the creep image point in the correct direction. # Note that two images are used, one for diagonals # and one for horizontals/verticals. # # round() on the angle is necessary, to make it # exact, despite small deviations that may result from # floating-point calculations # if int(round(self.direction.angle)) % 90 == 45: self.image = pygame.transform.rotate( self.base_image_45, -(self.direction.angle + 45)) elif int(round(self.direction.angle)) % 90 == 0: self.image = pygame.transform.rotate( self.base_image_0, -self.direction.angle) else: assert False # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.prev_pos = vec2d(self.pos) self.pos += displacement # When the image is rotated, its size is changed. self.image_w, self.image_h = self.image.get_size() elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self._die() elif self.state == Creep.DEAD: pass
[ "def", "update", "(", "self", ",", "time_passed", ")", ":", "if", "self", ".", "state", "==", "Creep", ".", "ALIVE", ":", "# Maybe it's time to change the direction ?", "#", "self", ".", "_compute_direction", "(", "time_passed", ")", "# Make the creep image point in...
https://github.com/eliben/code-for-blog/blob/06d6887eccd84ca5703b792a85ab6c1ebfc5393e/2009/pygame_creeps_game/creeps.py#L95-L145
fossasia/open-event-legacy
82b585d276efb894a48919bec4f3bff49077e2e8
app/models/ticket.py
python
Ticket.tags_csv
(self)
return ','.join(tag_names)
Return list of Tags in CSV.
Return list of Tags in CSV.
[ "Return", "list", "of", "Tags", "in", "CSV", "." ]
def tags_csv(self): """Return list of Tags in CSV. """ tag_names = [tag.name for tag in self.tags] return ','.join(tag_names)
[ "def", "tags_csv", "(", "self", ")", ":", "tag_names", "=", "[", "tag", ".", "name", "for", "tag", "in", "self", ".", "tags", "]", "return", "','", ".", "join", "(", "tag_names", ")" ]
https://github.com/fossasia/open-event-legacy/blob/82b585d276efb894a48919bec4f3bff49077e2e8/app/models/ticket.py#L96-L100
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/generic.py
python
NDFrame.get_values
(self)
return self.as_matrix()
same as values (but handles sparseness conversions)
same as values (but handles sparseness conversions)
[ "same", "as", "values", "(", "but", "handles", "sparseness", "conversions", ")" ]
def get_values(self): """same as values (but handles sparseness conversions)""" return self.as_matrix()
[ "def", "get_values", "(", "self", ")", ":", "return", "self", ".", "as_matrix", "(", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/generic.py#L2938-L2940
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/cookielib.py
python
request_path
(request)
return path
Path component of request-URI, as defined by RFC 2965.
Path component of request-URI, as defined by RFC 2965.
[ "Path", "component", "of", "request", "-", "URI", "as", "defined", "by", "RFC", "2965", "." ]
def request_path(request): """Path component of request-URI, as defined by RFC 2965.""" url = request.get_full_url() parts = urlparse.urlsplit(url) path = escape_path(parts.path) if not path.startswith("/"): # fix bad RFC 2396 absoluteURI path = "/" + path return path
[ "def", "request_path", "(", "request", ")", ":", "url", "=", "request", ".", "get_full_url", "(", ")", "parts", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "path", "=", "escape_path", "(", "parts", ".", "path", ")", "if", "not", "path", ".", "...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/cookielib.py#L609-L617
CastagnaIT/plugin.video.netflix
5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a
packages/httpcore/_sync/http.py
python
SyncBaseHTTPConnection.is_available
(self)
Return `True` if the connection is currently able to accept an outgoing request.
Return `True` if the connection is currently able to accept an outgoing request.
[ "Return", "True", "if", "the", "connection", "is", "currently", "able", "to", "accept", "an", "outgoing", "request", "." ]
def is_available(self) -> bool: """ Return `True` if the connection is currently able to accept an outgoing request. """ raise NotImplementedError()
[ "def", "is_available", "(", "self", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/CastagnaIT/plugin.video.netflix/blob/5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a/packages/httpcore/_sync/http.py#L30-L34
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/inspect.py
python
ismethoddescriptor
(object)
return (hasattr(object, "__get__") and not hasattr(object, "__set__") # else it's a data descriptor and not ismethod(object) # mutual exclusion and not isfunction(object) and not isclass(object))
Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod().
Return true if the object is a method descriptor.
[ "Return", "true", "if", "the", "object", "is", "a", "method", "descriptor", "." ]
def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod().""" return (hasattr(object, "__get__") and not hasattr(object, "__set__") # else it's a data descriptor and not ismethod(object) # mutual exclusion and not isfunction(object) and not isclass(object))
[ "def", "ismethoddescriptor", "(", "object", ")", ":", "return", "(", "hasattr", "(", "object", ",", "\"__get__\"", ")", "and", "not", "hasattr", "(", "object", ",", "\"__set__\"", ")", "# else it's a data descriptor", "and", "not", "ismethod", "(", "object", "...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/inspect.py#L78-L96
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/gdata/webmastertools/__init__.py
python
SitesFeed.__init__
(self, start_index=None, atom_id=None, title=None, entry=None, category=None, link=None, updated=None, extension_elements=None, extension_attributes=None, text=None)
Constructor for Source Args: category: list (optional) A list of Category instances id: Id (optional) The entry's Id element link: list (optional) A list of Link instances title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element.
Constructor for Source Args: category: list (optional) A list of Category instances id: Id (optional) The entry's Id element link: list (optional) A list of Link instances title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element.
[ "Constructor", "for", "Source", "Args", ":", "category", ":", "list", "(", "optional", ")", "A", "list", "of", "Category", "instances", "id", ":", "Id", "(", "optional", ")", "The", "entry", "s", "Id", "element", "link", ":", "list", "(", "optional", "...
def __init__(self, start_index=None, atom_id=None, title=None, entry=None, category=None, link=None, updated=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Source Args: category: list (optional) A list of Category instances id: Id (optional) The entry's Id element link: list (optional) A list of Link instances title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.start_index = start_index self.category = category or [] self.id = atom_id self.link = link or [] self.title = title self.updated = updated self.entry = entry or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {}
[ "def", "__init__", "(", "self", ",", "start_index", "=", "None", ",", "atom_id", "=", "None", ",", "title", "=", "None", ",", "entry", "=", "None", ",", "category", "=", "None", ",", "link", "=", "None", ",", "updated", "=", "None", ",", "extension_e...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/webmastertools/__init__.py#L401-L432
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/groupby/groupby.py
python
GroupBy._transform_with_numba
(self, data, func, *args, engine_kwargs=None, **kwargs)
return result.take(np.argsort(sorted_index), axis=0)
Perform groupby transform routine with the numba engine. This routine mimics the data splitting routine of the DataSplitter class to generate the indices of each group in the sorted data and then passes the data and indices into a Numba jitted function.
Perform groupby transform routine with the numba engine.
[ "Perform", "groupby", "transform", "routine", "with", "the", "numba", "engine", "." ]
def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): """ Perform groupby transform routine with the numba engine. This routine mimics the data splitting routine of the DataSplitter class to generate the indices of each group in the sorted data and then passes the data and indices into a Numba jitted function. """ starts, ends, sorted_index, sorted_data = self._numba_prep(func, data) numba_transform_func = numba_.generate_numba_transform_func( kwargs, func, engine_kwargs ) result = numba_transform_func( sorted_data, sorted_index, starts, ends, len(data.columns), *args, ) cache_key = (func, "groupby_transform") if cache_key not in NUMBA_FUNC_CACHE: NUMBA_FUNC_CACHE[cache_key] = numba_transform_func # result values needs to be resorted to their original positions since we # evaluated the data sorted by group return result.take(np.argsort(sorted_index), axis=0)
[ "def", "_transform_with_numba", "(", "self", ",", "data", ",", "func", ",", "*", "args", ",", "engine_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "starts", ",", "ends", ",", "sorted_index", ",", "sorted_data", "=", "self", ".", "_numba_prep"...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/groupby/groupby.py#L1310-L1338
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/xml/sax/xmlreader.py
python
XMLReader.getContentHandler
(self)
return self._cont_handler
Returns the current ContentHandler.
Returns the current ContentHandler.
[ "Returns", "the", "current", "ContentHandler", "." ]
def getContentHandler(self): "Returns the current ContentHandler." return self._cont_handler
[ "def", "getContentHandler", "(", "self", ")", ":", "return", "self", ".", "_cont_handler" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/xml/sax/xmlreader.py#L34-L36
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_vendor/requests/utils.py
python
get_unicode_from_response
(r)
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
Returns the requested content back in unicode.
[ "Returns", "the", "requested", "content", "back", "in", "unicode", "." ]
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
[ "def", "get_unicode_from_response", "(", "r", ")", ":", "warnings", ".", "warn", "(", "(", "'In requests 3.0, get_unicode_from_response will be removed. For '", "'more information, please see the discussion on issue #2266. (This'", "' warning should only appear once.)'", ")", ",", "D...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L524-L557
kvazis/homeassistant
aca227a780f806d861342e3611025a52a3bb4366
custom_components/hacs/helpers/classes/repository.py
python
HacsRepository.common_validate
(self, ignore_issues=False)
Common validation steps of the repository.
Common validation steps of the repository.
[ "Common", "validation", "steps", "of", "the", "repository", "." ]
async def common_validate(self, ignore_issues=False): """Common validation steps of the repository.""" await common_validate(self, ignore_issues)
[ "async", "def", "common_validate", "(", "self", ",", "ignore_issues", "=", "False", ")", ":", "await", "common_validate", "(", "self", ",", "ignore_issues", ")" ]
https://github.com/kvazis/homeassistant/blob/aca227a780f806d861342e3611025a52a3bb4366/custom_components/hacs/helpers/classes/repository.py#L219-L221
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/cherrypy/_cpreqbody.py
python
SizedReader.readlines
(self, sizehint=None)
return lines
Read lines from the request body and return them.
Read lines from the request body and return them.
[ "Read", "lines", "from", "the", "request", "body", "and", "return", "them", "." ]
def readlines(self, sizehint=None): """Read lines from the request body and return them.""" if self.length is not None: if sizehint is None: sizehint = self.length - self.bytes_read else: sizehint = min(sizehint, self.length - self.bytes_read) lines = [] seen = 0 while True: line = self.readline() if not line: break lines.append(line) seen += len(line) if seen >= sizehint: break return lines
[ "def", "readlines", "(", "self", ",", "sizehint", "=", "None", ")", ":", "if", "self", ".", "length", "is", "not", "None", ":", "if", "sizehint", "is", "None", ":", "sizehint", "=", "self", ".", "length", "-", "self", ".", "bytes_read", "else", ":", ...
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/cherrypy/_cpreqbody.py#L886-L904
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/dts/transfer_device_client.py
python
TransferDeviceClient.update_transfer_device
(self, id, transfer_device_label, update_transfer_device_details, **kwargs)
Updates a Transfer Device :param str id: (required) ID of the Transfer Job :param str transfer_device_label: (required) Label of the Transfer Device :param oci.dts.models.UpdateTransferDeviceDetails update_transfer_device_details: (required) fields to update :param str if_match: (optional) The entity tag to match. Optional, if set, the update will be successful only if the object's tag matches the tag specified in the request. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.dts.models.TransferDevice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/dts/update_transfer_device.py.html>`__ to see an example of how to use update_transfer_device API.
Updates a Transfer Device
[ "Updates", "a", "Transfer", "Device" ]
def update_transfer_device(self, id, transfer_device_label, update_transfer_device_details, **kwargs): """ Updates a Transfer Device :param str id: (required) ID of the Transfer Job :param str transfer_device_label: (required) Label of the Transfer Device :param oci.dts.models.UpdateTransferDeviceDetails update_transfer_device_details: (required) fields to update :param str if_match: (optional) The entity tag to match. Optional, if set, the update will be successful only if the object's tag matches the tag specified in the request. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.dts.models.TransferDevice` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/dts/update_transfer_device.py.html>`__ to see an example of how to use update_transfer_device API. """ resource_path = "/transferJobs/{id}/transferDevices/{transferDeviceLabel}" method = "PUT" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "update_transfer_device got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "id": id, "transferDeviceLabel": transfer_device_label } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "if-match": kwargs.get("if_match", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_transfer_device_details, response_type="TransferDevice") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_transfer_device_details, response_type="TransferDevice")
[ "def", "update_transfer_device", "(", "self", ",", "id", ",", "transfer_device_label", ",", "update_transfer_device_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/transferJobs/{id}/transferDevices/{transferDeviceLabel}\"", "method", "=", "\"PUT\"", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/dts/transfer_device_client.py#L429-L516
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/requests/packages/urllib3/packages/six.py
python
_SixMetaPathImporter.get_code
(self, fullname)
return None
Return None Required, if is_package is implemented
Return None
[ "Return", "None" ]
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/requests/packages/urllib3/packages/six.py#L218-L223
Walleclipse/ChineseAddress_OCR
ca7929c72cbac09c71501f06bf16c387f42f00cf
ctpn/lib/backup/fast_rcnn/bbox_transform.py
python
clip_boxes
(boxes, im_shape)
return boxes
Clip boxes to image boundaries.
Clip boxes to image boundaries.
[ "Clip", "boxes", "to", "image", "boundaries", "." ]
def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. """ # x1 >= 0 boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0) # x2 < im_shape[1] boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0) # y2 < im_shape[0] boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0) return boxes
[ "def", "clip_boxes", "(", "boxes", ",", "im_shape", ")", ":", "# x1 >= 0", "boxes", "[", ":", ",", "0", ":", ":", "4", "]", "=", "np", ".", "maximum", "(", "np", ".", "minimum", "(", "boxes", "[", ":", ",", "0", ":", ":", "4", "]", ",", "im_s...
https://github.com/Walleclipse/ChineseAddress_OCR/blob/ca7929c72cbac09c71501f06bf16c387f42f00cf/ctpn/lib/backup/fast_rcnn/bbox_transform.py#L67-L80
PyHDI/Pyverilog
2a42539bebd1b4587ee577d491ff002d0cc7295d
pyverilog/vparser/parser.py
python
VerilogParser.p_always_latch
(self, p)
always_latch : ALWAYS_LATCH senslist always_statement
always_latch : ALWAYS_LATCH senslist always_statement
[ "always_latch", ":", "ALWAYS_LATCH", "senslist", "always_statement" ]
def p_always_latch(self, p): 'always_latch : ALWAYS_LATCH senslist always_statement' p[0] = AlwaysLatch(p[2], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_always_latch", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "AlwaysLatch", "(", "p", "[", "2", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0"...
https://github.com/PyHDI/Pyverilog/blob/2a42539bebd1b4587ee577d491ff002d0cc7295d/pyverilog/vparser/parser.py#L1313-L1316
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/thirdparty/xdot/xdot.py
python
TextShape.draw
(self, cr, highlight=False)
[]
def draw(self, cr, highlight=False): try: layout = self.layout except AttributeError: layout = cr.create_layout() # set font options # see http://lists.freedesktop.org/archives/cairo/2007-February/009688.html context = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) fo.set_hint_style(cairo.HINT_STYLE_NONE) fo.set_hint_metrics(cairo.HINT_METRICS_OFF) try: pangocairo.context_set_font_options(context, fo) except TypeError: # XXX: Some broken pangocairo bindings show the error # 'TypeError: font_options must be a cairo.FontOptions or None' pass # set font font = pango.FontDescription() font.set_family(self.pen.fontname) font.set_absolute_size(self.pen.fontsize*pango.SCALE) layout.set_font_description(font) # set text layout.set_text(self.t) # cache it self.layout = layout else: cr.update_layout(layout) descent = 2 # XXX get descender from font metrics width, height = layout.get_size() width = float(width)/pango.SCALE height = float(height)/pango.SCALE # we know the width that dot thinks this text should have # we do not necessarily have a font with the same metrics # scale it so that the text fits inside its box if width > self.w: f = self.w / width width = self.w # equivalent to width *= f height *= f descent *= f else: f = 1.0 if self.j == self.LEFT: x = self.x elif self.j == self.CENTER: x = self.x - 0.5*width elif self.j == self.RIGHT: x = self.x - width else: assert 0 y = self.y - height + descent cr.move_to(x, y) cr.save() cr.scale(f, f) cr.set_source_rgba(*self.select_pen(highlight).color) cr.show_layout(layout) cr.restore() if 0: # DEBUG # show where dot thinks the text should appear cr.set_source_rgba(1, 0, 0, .9) if self.j == self.LEFT: x = self.x elif self.j == self.CENTER: x = self.x - 0.5*self.w elif self.j == self.RIGHT: x = self.x - self.w cr.move_to(x, self.y) cr.line_to(x+self.w, self.y) cr.stroke()
[ "def", "draw", "(", "self", ",", "cr", ",", "highlight", "=", "False", ")", ":", "try", ":", "layout", "=", "self", ".", "layout", "except", "AttributeError", ":", "layout", "=", "cr", ".", "create_layout", "(", ")", "# set font options", "# see http://lis...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/thirdparty/xdot/xdot.py#L111-L192
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/recipeIdentifier.py
python
format_ings
(rec, rd)
return format_ing_text(alist,rd)
[]
def format_ings (rec, rd): ings = rd.get_ings(rec) alist = rd.order_ings(ings) return format_ing_text(alist,rd)
[ "def", "format_ings", "(", "rec", ",", "rd", ")", ":", "ings", "=", "rd", ".", "get_ings", "(", "rec", ")", "alist", "=", "rd", ".", "order_ings", "(", "ings", ")", "return", "format_ing_text", "(", "alist", ",", "rd", ")" ]
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/recipeIdentifier.py#L102-L105
gmr/tinman
98f0acd15a228d752caa1864cdf02aaa3d492a9f
tinman/auth/mixins.py
python
OAuth2Mixin.authenticate_redirect
(self, callback_uri=None, cancel_uri=None, extended_permissions=None, callback=None)
Perform the authentication redirect to GitHub
Perform the authentication redirect to GitHub
[ "Perform", "the", "authentication", "redirect", "to", "GitHub" ]
def authenticate_redirect(self, callback_uri=None, cancel_uri=None, extended_permissions=None, callback=None): """Perform the authentication redirect to GitHub """ self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME) scope = self._BASE_SCOPE if extended_permissions: scope += extended_permissions args = {'client_id': self.settings[self._CLIENT_ID_SETTING], 'redirect_uri': self.oauth2_redirect_uri(callback_uri), 'scope': ','.join(scope)} # If cookie_secret is set, use it for GitHub's state value if not self.state and 'cookie_secret' in self.settings: sha1 = hashlib.sha1(self.settings['cookie_secret']) self.state = str(sha1.hexdigest()) # If state is set, add it to args if self.state: args['state'] = self.state LOGGER.info('Redirect args: %r', args) # Redirect the user to the proper URL self.redirect(self._OAUTH_AUTHORIZE_URL + auth.urllib_parse.urlencode(args)) callback()
[ "def", "authenticate_redirect", "(", "self", ",", "callback_uri", "=", "None", ",", "cancel_uri", "=", "None", ",", "extended_permissions", "=", "None", ",", "callback", "=", "None", ")", ":", "self", ".", "require_setting", "(", "self", ".", "_CLIENT_ID_SETTI...
https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/auth/mixins.py#L36-L66
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/html5lib/treebuilders/_base.py
python
TreeBuilder.createElement
(self, token)
return element
Create an element but don't insert it anywhere
Create an element but don't insert it anywhere
[ "Create", "an", "element", "but", "don", "t", "insert", "it", "anywhere" ]
def createElement(self, token): """Create an element but don't insert it anywhere""" name = token["name"] namespace = token.get("namespace", self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token["data"] return element
[ "def", "createElement", "(", "self", ",", "token", ")", ":", "name", "=", "token", "[", "\"name\"", "]", "namespace", "=", "token", ".", "get", "(", "\"namespace\"", ",", "self", ".", "defaultNamespace", ")", "element", "=", "self", ".", "elementClass", ...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/html5lib/treebuilders/_base.py#L264-L270
deanishe/alfred-vpn-manager
f5d0dd1433ea69b1517d4866a12b1118097057b9
src/docopt.py
python
parse_shorts
(tokens, options)
return parsed
shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;
shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;
[ "shorts", "::", "=", "-", "(", "chars", ")", "*", "[", "[", "]", "chars", "]", ";" ]
def parse_shorts(tokens, options): """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;""" token = tokens.move() assert token.startswith('-') and not token.startswith('--') left = token.lstrip('-') parsed = [] while left != '': short, left = '-' + left[0], left[1:] similar = [o for o in options if o.short == short] if len(similar) > 1: raise tokens.error('%s is specified ambiguously %d times' % (short, len(similar))) elif len(similar) < 1: o = Option(short, None, 0) options.append(o) if tokens.error is DocoptExit: o = Option(short, None, 0, True) else: # why copying is necessary here? o = Option(short, similar[0].long, similar[0].argcount, similar[0].value) value = None if o.argcount != 0: if left == '': if tokens.current() is None: raise tokens.error('%s requires argument' % short) value = tokens.move() else: value = left left = '' if tokens.error is DocoptExit: o.value = value if value is not None else True parsed.append(o) return parsed
[ "def", "parse_shorts", "(", "tokens", ",", "options", ")", ":", "token", "=", "tokens", ".", "move", "(", ")", "assert", "token", ".", "startswith", "(", "'-'", ")", "and", "not", "token", ".", "startswith", "(", "'--'", ")", "left", "=", "token", "....
https://github.com/deanishe/alfred-vpn-manager/blob/f5d0dd1433ea69b1517d4866a12b1118097057b9/src/docopt.py#L335-L367
PaddlePaddle/PGL
e48545f2814523c777b8a9a9188bf5a7f00d6e52
legacy/examples/pgl-ke/model/TransE.py
python
TransE.construct_train_program
(self)
return [loss]
Construct train program.
Construct train program.
[ "Construct", "train", "program", "." ]
def construct_train_program(self): """ Construct train program. """ entity_embedding, relation_embedding = self.creat_share_variables() pos_head = lookup_table(self.train_pos_input[:, 0], entity_embedding) pos_tail = lookup_table(self.train_pos_input[:, 2], entity_embedding) pos_rel = lookup_table(self.train_pos_input[:, 1], relation_embedding) neg_head = lookup_table(self.train_neg_input[:, 0], entity_embedding) neg_tail = lookup_table(self.train_neg_input[:, 2], entity_embedding) neg_rel = lookup_table(self.train_neg_input[:, 1], relation_embedding) pos_score = self.score_with_l2_normalize(pos_head, pos_rel, pos_tail) neg_score = self.score_with_l2_normalize(neg_head, neg_rel, neg_tail) pos = fluid.layers.reduce_sum( fluid.layers.abs(pos_score), 1, keep_dim=False) neg = fluid.layers.reduce_sum( fluid.layers.abs(neg_score), 1, keep_dim=False) neg = fluid.layers.reshape( neg, shape=[-1, self._neg_times], inplace=True) loss = fluid.layers.reduce_mean( fluid.layers.relu(pos - neg + self._margin)) return [loss]
[ "def", "construct_train_program", "(", "self", ")", ":", "entity_embedding", ",", "relation_embedding", "=", "self", ".", "creat_share_variables", "(", ")", "pos_head", "=", "lookup_table", "(", "self", ".", "train_pos_input", "[", ":", ",", "0", "]", ",", "en...
https://github.com/PaddlePaddle/PGL/blob/e48545f2814523c777b8a9a9188bf5a7f00d6e52/legacy/examples/pgl-ke/model/TransE.py#L69-L93
open-notify/Open-Notify-API
88c34b793c9b0b299c8e941fd477e12c0b974353
util.py
python
jsonp
(func)
return decorated_function
Wraps JSONified output for JSONP requests.
Wraps JSONified output for JSONP requests.
[ "Wraps", "JSONified", "output", "for", "JSONP", "requests", "." ]
def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs)[0].data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype), func(*args, **kwargs)[1] else: return func(*args, **kwargs) return decorated_function
[ "def", "jsonp", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "request", ".", "args", ".", "get", "(", "'callback'", ",", "False", ")", "if"...
https://github.com/open-notify/Open-Notify-API/blob/88c34b793c9b0b299c8e941fd477e12c0b974353/util.py#L30-L42
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/python/mxnet/gluon/block.py
python
Block.hybridize
(self, active=True, **kwargs)
Activates or deactivates :py:class:`HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. static_alloc : bool, default False Statically allocate memory to improve speed. Memory usage may increase. static_shape : bool, default False Optimize for invariant input shapes between iterations. Must also set static_alloc to True. Change of input shapes is still allowed but slower.
Activates or deactivates :py:class:`HybridBlock` s recursively. Has no effect on non-hybrid children.
[ "Activates", "or", "deactivates", ":", "py", ":", "class", ":", "HybridBlock", "s", "recursively", ".", "Has", "no", "effect", "on", "non", "-", "hybrid", "children", "." ]
def hybridize(self, active=True, **kwargs): """Activates or deactivates :py:class:`HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. static_alloc : bool, default False Statically allocate memory to improve speed. Memory usage may increase. static_shape : bool, default False Optimize for invariant input shapes between iterations. Must also set static_alloc to True. Change of input shapes is still allowed but slower. """ for cld in self._children.values(): cld.hybridize(active, **kwargs)
[ "def", "hybridize", "(", "self", ",", "active", "=", "True", ",", "*", "*", "kwargs", ")", ":", "for", "cld", "in", "self", ".", "_children", ".", "values", "(", ")", ":", "cld", ".", "hybridize", "(", "active", ",", "*", "*", "kwargs", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/python/mxnet/gluon/block.py#L504-L520
brainix/pottery
0a57ef51949e13f10ffbe5a8b499ea9cb1909ffc
pottery/counter.py
python
RedisCounter.__imath_op
(self, other: Counter[JSONTypes], *, sign: int = +1, )
[]
def __imath_op(self, other: Counter[JSONTypes], *, sign: int = +1, ) -> RedisCounter: with self._watch(other) as pipeline: try: other_items = cast('RedisCounter', other).to_counter().items() except AttributeError: other_items = other.items() to_set = {k: self[k] + sign * v for k, v in other_items} to_del = {k for k, v in to_set.items() if v <= 0} to_del.update( k for k, v in self.items() if k not in to_set and v <= 0 ) encoded_to_set = { self._encode(k): self._encode(v) for k, v in to_set.items() if v } encoded_to_del = {self._encode(k) for k in to_del} if encoded_to_set or encoded_to_del: pipeline.multi() # Available since Redis 1.2.0 if encoded_to_set: # Available since Redis 2.0.0: pipeline.hset(self.key, mapping=encoded_to_set) # type: ignore if encoded_to_del: pipeline.hdel(self.key, *encoded_to_del) # Available since Redis 2.0.0 return self
[ "def", "__imath_op", "(", "self", ",", "other", ":", "Counter", "[", "JSONTypes", "]", ",", "*", ",", "sign", ":", "int", "=", "+", "1", ",", ")", "->", "RedisCounter", ":", "with", "self", ".", "_watch", "(", "other", ")", "as", "pipeline", ":", ...
https://github.com/brainix/pottery/blob/0a57ef51949e13f10ffbe5a8b499ea9cb1909ffc/pottery/counter.py#L176-L202
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/storages/storage.py
python
ListStorage.__setitem__
(self, key, value)
Set the specified value at the specified key.
Set the specified value at the specified key.
[ "Set", "the", "specified", "value", "at", "the", "specified", "key", "." ]
def __setitem__(self, key, value): """Set the specified value at the specified key.""" super(ListStorage, self).__setitem__(key, self._to(value, device=self.device, dtype=self.dtype))
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "super", "(", "ListStorage", ",", "self", ")", ".", "__setitem__", "(", "key", ",", "self", ".", "_to", "(", "value", ",", "device", "=", "self", ".", "device", ",", "dtype", "=...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/storages/storage.py#L268-L270
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/computation/pytables.py
python
BinOp.conform
(self, rhs)
return rhs
inplace conform rhs
inplace conform rhs
[ "inplace", "conform", "rhs" ]
def conform(self, rhs): """ inplace conform rhs """ if not com.is_list_like(rhs): rhs = [rhs] if hasattr(self.rhs, 'ravel'): rhs = rhs.ravel() return rhs
[ "def", "conform", "(", "self", ",", "rhs", ")", ":", "if", "not", "com", ".", "is_list_like", "(", "rhs", ")", ":", "rhs", "=", "[", "rhs", "]", "if", "hasattr", "(", "self", ".", "rhs", ",", "'ravel'", ")", ":", "rhs", "=", "rhs", ".", "ravel"...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/computation/pytables.py#L128-L134
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/genericpath.py
python
exists
(path)
return True
Test whether a path exists. Returns False for broken symbolic links
Test whether a path exists. Returns False for broken symbolic links
[ "Test", "whether", "a", "path", "exists", ".", "Returns", "False", "for", "broken", "symbolic", "links" ]
def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" try: os.stat(path) except os.error: return False return True
[ "def", "exists", "(", "path", ")", ":", "try", ":", "os", ".", "stat", "(", "path", ")", "except", "os", ".", "error", ":", "return", "False", "return", "True" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/genericpath.py#L17-L24
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
datadog_checks_base/datadog_checks/base/checks/windows/perf_counters/base.py
python
PerfCountersBaseCheck.check
(self, _)
[]
def check(self, _): self.query_counters()
[ "def", "check", "(", "self", ",", "_", ")", ":", "self", ".", "query_counters", "(", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/datadog_checks_base/datadog_checks/base/checks/windows/perf_counters/base.py#L43-L44
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py
python
Manifest._translate_pattern
(self, pattern, anchor=True, prefix=None, is_regex=False)
return re.compile(pattern_re)
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
Translate a shell-like wildcard pattern to a compiled regular expression.
[ "Translate", "a", "shell", "-", "like", "wildcard", "pattern", "to", "a", "compiled", "regular", "expression", "." ]
def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). """ if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern if _PYTHON_VERSION > (3, 2): # ditch start and end characters start, _, end = self._glob_to_re('_').partition('_') if pattern: pattern_re = self._glob_to_re(pattern) if _PYTHON_VERSION > (3, 2): assert pattern_re.startswith(start) and pattern_re.endswith(end) else: pattern_re = '' base = re.escape(os.path.join(self.base, '')) if prefix is not None: # ditch end of pattern character if _PYTHON_VERSION <= (3, 2): empty_pattern = self._glob_to_re('') prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] else: prefix_re = self._glob_to_re(prefix) assert prefix_re.startswith(start) and prefix_re.endswith(end) prefix_re = prefix_re[len(start): len(prefix_re) - len(end)] sep = os.sep if os.sep == '\\': sep = r'\\' if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + sep.join((prefix_re, '.*' + pattern_re)) else: pattern_re = pattern_re[len(start): len(pattern_re) - len(end)] pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep, pattern_re, end) else: # no prefix -- respect anchor flag if anchor: if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + pattern_re else: pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):]) return re.compile(pattern_re)
[ "def", "_translate_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "if", "is_regex", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "re", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py#L317-L370
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0060/pubsub.py
python
XEP_0060.get_node_affiliations
(self, jid, node, ifrom=None, block=True, callback=None, timeout=None)
return iq.send(block=block, callback=callback, timeout=timeout)
Retrieve the affiliations associated with a given node. Arguments: jid -- The JID of the pubsub service. node -- The node to retrieve affiliations from. ifrom -- Specify the sender's JID. block -- Specify if the send call will block until a response is received, or a timeout occurs. Defaults to True. timeout -- The length of time (in seconds) to wait for a response before exiting the send call if blocking is used. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT callback -- Optional reference to a stream handler function. Will be executed when a reply stanza is received.
Retrieve the affiliations associated with a given node.
[ "Retrieve", "the", "affiliations", "associated", "with", "a", "given", "node", "." ]
def get_node_affiliations(self, jid, node, ifrom=None, block=True, callback=None, timeout=None): """ Retrieve the affiliations associated with a given node. Arguments: jid -- The JID of the pubsub service. node -- The node to retrieve affiliations from. ifrom -- Specify the sender's JID. block -- Specify if the send call will block until a response is received, or a timeout occurs. Defaults to True. timeout -- The length of time (in seconds) to wait for a response before exiting the send call if blocking is used. Defaults to sleekxmpp.xmlstream.RESPONSE_TIMEOUT callback -- Optional reference to a stream handler function. Will be executed when a reply stanza is received. """ iq = self.xmpp.Iq(sto=jid, sfrom=ifrom, stype='get') iq['pubsub_owner']['affiliations']['node'] = node return iq.send(block=block, callback=callback, timeout=timeout)
[ "def", "get_node_affiliations", "(", "self", ",", "jid", ",", "node", ",", "ifrom", "=", "None", ",", "block", "=", "True", ",", "callback", "=", "None", ",", "timeout", "=", "None", ")", ":", "iq", "=", "self", ".", "xmpp", ".", "Iq", "(", "sto", ...
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0060/pubsub.py#L380-L399
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/rfc822.py
python
Message.__getitem__
(self, name)
return self.dict[name.lower()]
Get a specific header, as from a dictionary.
Get a specific header, as from a dictionary.
[ "Get", "a", "specific", "header", "as", "from", "a", "dictionary", "." ]
def __getitem__(self, name): """Get a specific header, as from a dictionary.""" return self.dict[name.lower()]
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "dict", "[", "name", ".", "lower", "(", ")", "]" ]
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/rfc822.py#L382-L384
timothyb0912/pylogit
cffc9c523b5368966ef2481c7dc30f0a5d296de8
src/pylogit/conditional_logit.py
python
_mnl_transform_deriv_c
(*args, **kwargs)
return None
Returns None. This is a place holder function since the MNL model has no shape parameters.
Returns None.
[ "Returns", "None", "." ]
def _mnl_transform_deriv_c(*args, **kwargs): """ Returns None. This is a place holder function since the MNL model has no shape parameters. """ # This is a place holder function since the MNL model has no shape # parameters. return None
[ "def", "_mnl_transform_deriv_c", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# This is a place holder function since the MNL model has no shape", "# parameters.", "return", "None" ]
https://github.com/timothyb0912/pylogit/blob/cffc9c523b5368966ef2481c7dc30f0a5d296de8/src/pylogit/conditional_logit.py#L103-L112
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
plugins/convert/mask/mask_blend.py
python
Mask._get_erosion_kernel
(self, mask)
return erosion_kernel
Get the erosion kernel. Parameters ---------- mask: :class:`numpy.ndarray` The mask to be eroded or dilated Returns ------- :class:`numpy.ndarray` The erosion kernel to be used for erosion/dilation
Get the erosion kernel.
[ "Get", "the", "erosion", "kernel", "." ]
def _get_erosion_kernel(self, mask): """ Get the erosion kernel. Parameters ---------- mask: :class:`numpy.ndarray` The mask to be eroded or dilated Returns ------- :class:`numpy.ndarray` The erosion kernel to be used for erosion/dilation """ erosion_ratio = self.config["erosion"] / 100 mask_radius = np.sqrt(np.sum(mask)) / 2 kernel_size = max(1, int(abs(erosion_ratio * mask_radius))) erosion_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) logger.trace("erosion_kernel shape: %s", erosion_kernel.shape) return erosion_kernel
[ "def", "_get_erosion_kernel", "(", "self", ",", "mask", ")", ":", "erosion_ratio", "=", "self", ".", "config", "[", "\"erosion\"", "]", "/", "100", "mask_radius", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "mask", ")", ")", "/", "2", "kernel...
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/plugins/convert/mask/mask_blend.py#L154-L172
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/feedparser.py
python
_FeedParserMixin._isBase64
(self, attrsD, contentparams)
return 1
[]
def _isBase64(self, attrsD, contentparams): if attrsD.get('mode', '') == 'base64': return 1 if self.contentparams['type'].startswith('text/'): return 0 if self.contentparams['type'].endswith('+xml'): return 0 if self.contentparams['type'].endswith('/xml'): return 0 return 1
[ "def", "_isBase64", "(", "self", ",", "attrsD", ",", "contentparams", ")", ":", "if", "attrsD", ".", "get", "(", "'mode'", ",", "''", ")", "==", "'base64'", ":", "return", "1", "if", "self", ".", "contentparams", "[", "'type'", "]", ".", "startswith", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/feedparser.py#L1000-L1009
PytLab/VASPy
3650b3e07bcd722f9443ae1213ff4b8734c42ffa
vaspy/atomco.py
python
XyzFile.coordinate_transform
(self, bases=None)
return self.cart2dir(bases, self.data)
Use Ax=b to do coordinate transform cartesian to direct
Use Ax=b to do coordinate transform cartesian to direct
[ "Use", "Ax", "=", "b", "to", "do", "coordinate", "transform", "cartesian", "to", "direct" ]
def coordinate_transform(self, bases=None): "Use Ax=b to do coordinate transform cartesian to direct" if bases is None: bases = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) return self.cart2dir(bases, self.data)
[ "def", "coordinate_transform", "(", "self", ",", "bases", "=", "None", ")", ":", "if", "bases", "is", "None", ":", "bases", "=", "np", ".", "array", "(", "[", "[", "1.0", ",", "0.0", ",", "0.0", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", "]"...
https://github.com/PytLab/VASPy/blob/3650b3e07bcd722f9443ae1213ff4b8734c42ffa/vaspy/atomco.py#L410-L416
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/sysconfig.py
python
get_paths
(scheme=_get_default_scheme(), vars=None, expand=True)
Returns a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform.
Returns a mapping containing an install scheme.
[ "Returns", "a", "mapping", "containing", "an", "install", "scheme", "." ]
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Returns a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ if expand: return _expand_vars(scheme, vars) else: return _INSTALL_SCHEMES[scheme]
[ "def", "get_paths", "(", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "if", "expand", ":", "return", "_expand_vars", "(", "scheme", ",", "vars", ")", "else", ":", "return", "_INSTALL_SCHE...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/sysconfig.py#L427-L436
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/distutils/command/build_ext.py
python
build_ext.get_ext_fullname
(self, ext_name)
Returns the fullname of a given extension name. Adds the `package.` prefix
Returns the fullname of a given extension name.
[ "Returns", "the", "fullname", "of", "a", "given", "extension", "name", "." ]
def get_ext_fullname(self, ext_name): """Returns the fullname of a given extension name. Adds the `package.` prefix""" if self.package is None: return ext_name else: return self.package + '.' + ext_name
[ "def", "get_ext_fullname", "(", "self", ",", "ext_name", ")", ":", "if", "self", ".", "package", "is", "None", ":", "return", "ext_name", "else", ":", "return", "self", ".", "package", "+", "'.'", "+", "ext_name" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/distutils/command/build_ext.py#L659-L666
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
skeinforge_application/skeinforge_plugins/craft_plugins/dimension.py
python
DimensionSkein.getRetractionRatio
(self, lineIndex)
return (distanceToNextThread - self.minimumTravelForRetraction) / self.minimumTravelForRetraction
Get the retraction ratio.
Get the retraction ratio.
[ "Get", "the", "retraction", "ratio", "." ]
def getRetractionRatio(self, lineIndex): 'Get the retraction ratio.' distanceToNextThread = self.getDistanceToNextThread(lineIndex) if distanceToNextThread is None: return 1.0 if distanceToNextThread >= self.doubleMinimumTravelForRetraction: return 1.0 if distanceToNextThread <= self.minimumTravelForRetraction: return 0.0 return (distanceToNextThread - self.minimumTravelForRetraction) / self.minimumTravelForRetraction
[ "def", "getRetractionRatio", "(", "self", ",", "lineIndex", ")", ":", "distanceToNextThread", "=", "self", ".", "getDistanceToNextThread", "(", "lineIndex", ")", "if", "distanceToNextThread", "is", "None", ":", "return", "1.0", "if", "distanceToNextThread", ">=", ...
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/dimension.py#L318-L327
homles11/IGCV3
83aba2f34702836cc1b82350163909034cd9b553
detection/dataset/mscoco.py
python
Coco.label_from_index
(self, index)
return self.labels[index]
given image index, return preprocessed ground-truth Parameters: ---------- index: int index of a specific image Returns: ---------- ground-truths of this image
given image index, return preprocessed ground-truth
[ "given", "image", "index", "return", "preprocessed", "ground", "-", "truth" ]
def label_from_index(self, index): """ given image index, return preprocessed ground-truth Parameters: ---------- index: int index of a specific image Returns: ---------- ground-truths of this image """ assert self.labels is not None, "Labels not processed" return self.labels[index]
[ "def", "label_from_index", "(", "self", ",", "index", ")", ":", "assert", "self", ".", "labels", "is", "not", "None", ",", "\"Labels not processed\"", "return", "self", ".", "labels", "[", "index", "]" ]
https://github.com/homles11/IGCV3/blob/83aba2f34702836cc1b82350163909034cd9b553/detection/dataset/mscoco.py#L54-L67
novoid/lazyblorg
b71730770aba4fa58890d245f5f9ab30037f3931
lazyblorg.py
python
Lazyblorg.determine_changes
(self)
return generate, marked_for_feed, increment_version, stats_parsed_org_files, stats_parsed_org_lines
Parses input Org-mode files, reads in previous meta-data file, and determines which articles changed in which way. @param return: generate: list of IDs of articles in blog_data/metadata that should be build @param return: marked_for_feed: list of IDs of articles in blog_data/metadata that are modified/new @param return: increment_version: list of IDs of articles in blog_data/metadata that got a new version
[]
def determine_changes(self): """ Parses input Org-mode files, reads in previous meta-data file, and determines which articles changed in which way. @param return: generate: list of IDs of articles in blog_data/metadata that should be build @param return: marked_for_feed: list of IDs of articles in blog_data/metadata that are modified/new @param return: increment_version: list of IDs of articles in blog_data/metadata that got a new version """ options = self.options stats_parsed_org_files, stats_parsed_org_lines = 0, 0 logging.info("• Parsing Org mode files …") for filename in options.orgfiles: new_org_lines = 0 try: file_blog_data, new_org_lines = self._parse_orgmode_file( filename) # parsing one Org-mode file except OrgParserException as message: verbose_message = "Parsing error in file \"" + filename + \ "\" which is not good. Therefore, I stop here and hope you " + \ "can fix the issue in the Org-mode file. Reason: " + message.value Utils.error_exit_with_userlog( options.logfilename, 20, verbose_message) else: self.blog_data += file_blog_data stats_parsed_org_files += 1 stats_parsed_org_lines += new_org_lines # dump blogdata for debugging purpose ... if options.verbose: with open('2del-lazyblorg_dump_of_blogdata_from_previous_verbose_run.pk', 'wb') as output: # always use ASCII format: easier to debug from outside pickle.dump(self.blog_data, output) # FIXXME: debug with: [x['id'] for x in self.blog_data] # generate persistent data which is used to compare this status # with the status of the next invocation: self.metadata, self.entries_timeline_by_published = Utils.generate_metadata_from_blogdata( self.blog_data) # create path to new metadatafile if it does not exist: if not os.path.isdir(os.path.dirname(options.new_metadatafilename)): logging.debug( "path of new_metadatafilename \"" + options.new_metadatafilename + "\" does not exist. Creating …") os.makedirs(os.path.dirname(options.new_metadatafilename)) # write this status to the persistent data file: with open(options.new_metadatafilename, 'wb') as output: pickle.dump([self.metadata, self.entries_timeline_by_published], output) # load old metadata from file if os.path.isfile(options.previous_metadatafilename): logging.debug( "reading old \"" + options.previous_metadatafilename + "\" …") with open(options.previous_metadatafilename, 'rb') as input: [self.previous_metadata, self.entries_timeline_by_published] = pickle.load(input) # extract HTML templates and store in class var self.template_definitions = self._generate_template_definitions_from_template_data() # run comparing algorithm (last metadata, current metadata) generate, marked_for_feed, increment_version = self._compare_blogdata_to_metadata() return generate, marked_for_feed, increment_version, stats_parsed_org_files, stats_parsed_org_lines
[ "def", "determine_changes", "(", "self", ")", ":", "options", "=", "self", ".", "options", "stats_parsed_org_files", ",", "stats_parsed_org_lines", "=", "0", ",", "0", "logging", ".", "info", "(", "\"• Parsing Org mode files …\")", "", "for", "filename", "in", "...
https://github.com/novoid/lazyblorg/blob/b71730770aba4fa58890d245f5f9ab30037f3931/lazyblorg.py#L62-L136
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_linux/systrace/catapult/third_party/pyserial/serial/serialcli.py
python
IronSerial.getCD
(self)
return self._port_handle.CDHolding
Read terminal status line: Carrier Detect
Read terminal status line: Carrier Detect
[ "Read", "terminal", "status", "line", ":", "Carrier", "Detect" ]
def getCD(self): """Read terminal status line: Carrier Detect""" if not self._port_handle: raise portNotOpenError return self._port_handle.CDHolding
[ "def", "getCD", "(", "self", ")", ":", "if", "not", "self", ".", "_port_handle", ":", "raise", "portNotOpenError", "return", "self", ".", "_port_handle", ".", "CDHolding" ]
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_linux/systrace/catapult/third_party/pyserial/serial/serialcli.py#L232-L235
zim-desktop-wiki/zim-desktop-wiki
fe717d7ee64e5c06d90df90eb87758e5e72d25c5
zim/gui/uiactions.py
python
UIActions.delete_page
(self, path=None)
Delete a page by either trashing it, or permanent deletion after confirmation of a L{TrashPageDialog} or L{DeletePageDialog}. @param path: a L{Path} object, or C{None} for the current selected page
Delete a page by either trashing it, or permanent deletion after confirmation of a L{TrashPageDialog} or L{DeletePageDialog}.
[ "Delete", "a", "page", "by", "either", "trashing", "it", "or", "permanent", "deletion", "after", "confirmation", "of", "a", "L", "{", "TrashPageDialog", "}", "or", "L", "{", "DeletePageDialog", "}", "." ]
def delete_page(self, path=None): '''Delete a page by either trashing it, or permanent deletion after confirmation of a L{TrashPageDialog} or L{DeletePageDialog}. @param path: a L{Path} object, or C{None} for the current selected page ''' # Difficulty here is that we want to avoid unnecessary prompts. # So ideally we want to know whether trash is supported, but we only # know for sure when we try. Thus we risk prompting twice: once for # trash and once for deletion if trash fails. path = path or self.page assert path is not None if not self.ensure_index_uptodate(): return # TODO: if page is placeholder, present different dialog ? # explain no file is deleted, only links can be removed, which is not reversable if self.notebook.config['Notebook']['disable_trash']: return DeletePageDialog(self.widget, self.notebook, path).run() else: # Try to trash - if fail, go to delete anyway error = TrashPageDialog(self.widget, self.notebook, path).run() if error: if QuestionDialog( self.widget, _("Trash failed, do you want to permanently delete instead ?") # T: question in "delete page" action ).run(): return DeletePageDialog(self.widget, self.notebook, path).run()
[ "def", "delete_page", "(", "self", ",", "path", "=", "None", ")", ":", "# Difficulty here is that we want to avoid unnecessary prompts.", "# So ideally we want to know whether trash is supported, but we only", "# know for sure when we try. Thus we risk prompting twice: once for", "# trash ...
https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/gui/uiactions.py#L196-L227
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/opflow/gradients/natural_gradient.py
python
NaturalGradient.convert
( self, operator: OperatorBase, params: Optional[ Union[ParameterVector, ParameterExpression, List[ParameterExpression]] ] = None, )
return ListOp([grad, metric], combo_fn=combo_fn)
r""" Args: operator: The operator we are taking the gradient of. params: The parameters we are taking the gradient with respect to. If not explicitly passed, they are inferred from the operator and sorted by name. Returns: An operator whose evaluation yields the NaturalGradient. Raises: TypeError: If ``operator`` does not represent an expectation value or the quantum state is not ``CircuitStateFn``. ValueError: If ``params`` contains a parameter not present in ``operator``. ValueError: If ``operator`` is not parameterized.
r""" Args: operator: The operator we are taking the gradient of. params: The parameters we are taking the gradient with respect to. If not explicitly passed, they are inferred from the operator and sorted by name.
[ "r", "Args", ":", "operator", ":", "The", "operator", "we", "are", "taking", "the", "gradient", "of", ".", "params", ":", "The", "parameters", "we", "are", "taking", "the", "gradient", "with", "respect", "to", ".", "If", "not", "explicitly", "passed", "t...
def convert( self, operator: OperatorBase, params: Optional[ Union[ParameterVector, ParameterExpression, List[ParameterExpression]] ] = None, ) -> OperatorBase: r""" Args: operator: The operator we are taking the gradient of. params: The parameters we are taking the gradient with respect to. If not explicitly passed, they are inferred from the operator and sorted by name. Returns: An operator whose evaluation yields the NaturalGradient. Raises: TypeError: If ``operator`` does not represent an expectation value or the quantum state is not ``CircuitStateFn``. ValueError: If ``params`` contains a parameter not present in ``operator``. ValueError: If ``operator`` is not parameterized. """ if not isinstance(operator, ComposedOp): if not (isinstance(operator, ListOp) and len(operator.oplist) == 1): raise TypeError( "Please provide the operator either as ComposedOp or as ListOp of " "a CircuitStateFn potentially with a combo function." ) if not isinstance(operator[-1], CircuitStateFn): raise TypeError( "Please make sure that the operator for which you want to compute " "Quantum Fisher Information represents an expectation value or a " "loss function and that the quantum state is given as " "CircuitStateFn." ) if len(operator.parameters) == 0: raise ValueError("The operator we are taking the gradient of is not parameterized!") if params is None: params = sorted(operator.parameters, key=functools.cmp_to_key(_compare_parameters)) if not isinstance(params, Iterable): params = [params] # Instantiate the gradient grad = Gradient(self._grad_method, epsilon=self._epsilon).convert(operator, params) # Instantiate the QFI metric which is used to re-scale the gradient metric = self._qfi_method.convert(operator[-1], params) * 0.25 # Define the function which compute the natural gradient from the gradient and the QFI. def combo_fn(x): c = np.real(x[0]) a = np.real(x[1]) if self.regularization: # If a regularization method is chosen then use a regularized solver to # construct the natural gradient. nat_grad = NaturalGradient._regularized_sle_solver( a, c, regularization=self.regularization ) else: try: # Try to solve the system of linear equations Ax = C. nat_grad = np.linalg.solve(a, c) except np.linalg.LinAlgError: # singular matrix nat_grad = np.linalg.lstsq(a, c)[0] return np.real(nat_grad) # Define the ListOp which combines the gradient and the QFI according to the combination # function defined above. return ListOp([grad, metric], combo_fn=combo_fn)
[ "def", "convert", "(", "self", ",", "operator", ":", "OperatorBase", ",", "params", ":", "Optional", "[", "Union", "[", "ParameterVector", ",", "ParameterExpression", ",", "List", "[", "ParameterExpression", "]", "]", "]", "=", "None", ",", ")", "->", "Ope...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/opflow/gradients/natural_gradient.py#L76-L143
jcjohnson/pytorch-examples
0003fcdc606a79951e53bf8f46f8574fa4739f23
nn/two_layer_net_module.py
python
TwoLayerNet.__init__
(self, D_in, H, D_out)
In the constructor we instantiate two nn.Linear modules and assign them as member variables.
In the constructor we instantiate two nn.Linear modules and assign them as member variables.
[ "In", "the", "constructor", "we", "instantiate", "two", "nn", ".", "Linear", "modules", "and", "assign", "them", "as", "member", "variables", "." ]
def __init__(self, D_in, H, D_out): """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. """ super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out)
[ "def", "__init__", "(", "self", ",", "D_in", ",", "H", ",", "D_out", ")", ":", "super", "(", "TwoLayerNet", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "linear1", "=", "torch", ".", "nn", ".", "Linear", "(", "D_in", ",", "H", ")", ...
https://github.com/jcjohnson/pytorch-examples/blob/0003fcdc606a79951e53bf8f46f8574fa4739f23/nn/two_layer_net_module.py#L13-L20
pannous/tensorflow-ocr
52579ae55549429a1631193b2e6218087d0c60de
combine.py
python
Box.__init__
(self, **kwargs)
[]
def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value)
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
https://github.com/pannous/tensorflow-ocr/blob/52579ae55549429a1631193b2e6218087d0c60de/combine.py#L12-L14