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
biocore/scikit-bio
ecdfc7941d8c21eb2559ff1ab313d6e9348781da
skbio/tree/_tree.py
python
TreeNode.lowest_common_ancestor
(self, tipnames)
return curr
r"""Lowest common ancestor for a list of tips Parameters ---------- tipnames : list of TreeNode or str The nodes of interest Returns ------- TreeNode The lowest common ancestor of the passed in nodes Raises ------ ValueError If no tips could be found in the tree, or if not all tips were found. Examples -------- >>> from skbio import TreeNode >>> tree = TreeNode.read(["((a,b)c,(d,e)f)root;"]) >>> nodes = [tree.find('a'), tree.find('b')] >>> lca = tree.lowest_common_ancestor(nodes) >>> print(lca.name) c >>> nodes = [tree.find('a'), tree.find('e')] >>> lca = tree.lca(nodes) # lca is an alias for convience >>> print(lca.name) root
r"""Lowest common ancestor for a list of tips
[ "r", "Lowest", "common", "ancestor", "for", "a", "list", "of", "tips" ]
def lowest_common_ancestor(self, tipnames): r"""Lowest common ancestor for a list of tips Parameters ---------- tipnames : list of TreeNode or str The nodes of interest Returns ------- TreeNode The lowest common ancestor of the passed in nodes Raises ------ ValueError If no tips could be found in the tree, or if not all tips were found. Examples -------- >>> from skbio import TreeNode >>> tree = TreeNode.read(["((a,b)c,(d,e)f)root;"]) >>> nodes = [tree.find('a'), tree.find('b')] >>> lca = tree.lowest_common_ancestor(nodes) >>> print(lca.name) c >>> nodes = [tree.find('a'), tree.find('e')] >>> lca = tree.lca(nodes) # lca is an alias for convience >>> print(lca.name) root """ if len(tipnames) == 1: return self.find(tipnames[0]) tips = [self.find(name) for name in tipnames] if len(tips) == 0: raise ValueError("No tips found.") nodes_to_scrub = [] for t in tips: if t.is_root(): # has to be the LCA... return t prev = t curr = t.parent while curr and not hasattr(curr, 'black'): setattr(curr, 'black', [prev]) nodes_to_scrub.append(curr) prev = curr curr = curr.parent # increase black count, multiple children lead to here if curr: curr.black.append(prev) curr = self while len(curr.black) == 1: curr = curr.black[0] # clean up tree for n in nodes_to_scrub: delattr(n, 'black') return curr
[ "def", "lowest_common_ancestor", "(", "self", ",", "tipnames", ")", ":", "if", "len", "(", "tipnames", ")", "==", "1", ":", "return", "self", ".", "find", "(", "tipnames", "[", "0", "]", ")", "tips", "=", "[", "self", ".", "find", "(", "name", ")", "for", "name", "in", "tipnames", "]", "if", "len", "(", "tips", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No tips found.\"", ")", "nodes_to_scrub", "=", "[", "]", "for", "t", "in", "tips", ":", "if", "t", ".", "is_root", "(", ")", ":", "# has to be the LCA...", "return", "t", "prev", "=", "t", "curr", "=", "t", ".", "parent", "while", "curr", "and", "not", "hasattr", "(", "curr", ",", "'black'", ")", ":", "setattr", "(", "curr", ",", "'black'", ",", "[", "prev", "]", ")", "nodes_to_scrub", ".", "append", "(", "curr", ")", "prev", "=", "curr", "curr", "=", "curr", ".", "parent", "# increase black count, multiple children lead to here", "if", "curr", ":", "curr", ".", "black", ".", "append", "(", "prev", ")", "curr", "=", "self", "while", "len", "(", "curr", ".", "black", ")", "==", "1", ":", "curr", "=", "curr", ".", "black", "[", "0", "]", "# clean up tree", "for", "n", "in", "nodes_to_scrub", ":", "delattr", "(", "n", ",", "'black'", ")", "return", "curr" ]
https://github.com/biocore/scikit-bio/blob/ecdfc7941d8c21eb2559ff1ab313d6e9348781da/skbio/tree/_tree.py#L1771-L1840
ondyari/FaceForensics
b952e41cba017eb37593c39e12bd884a934791e1
dataset/DeepFakes/faceswap-master/tools/sort.py
python
Sort.estimate_blur
(image)
return score
Estimate the amount of blur an image has
Estimate the amount of blur an image has
[ "Estimate", "the", "amount", "of", "blur", "an", "image", "has" ]
def estimate_blur(image): """ Estimate the amount of blur an image has """ if image.ndim == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur_map = cv2.Laplacian(image, cv2.CV_64F) score = np.var(blur_map) return score
[ "def", "estimate_blur", "(", "image", ")", ":", "if", "image", ".", "ndim", "==", "3", ":", "image", "=", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_BGR2GRAY", ")", "blur_map", "=", "cv2", ".", "Laplacian", "(", "image", ",", "cv2", ".", "CV_64F", ")", "score", "=", "np", ".", "var", "(", "blur_map", ")", "return", "score" ]
https://github.com/ondyari/FaceForensics/blob/b952e41cba017eb37593c39e12bd884a934791e1/dataset/DeepFakes/faceswap-master/tools/sort.py#L710-L717
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/network/lib/transports/websocket.py
python
PupyWebSocketServer.bad_request
(self, msg)
[]
def bad_request(self, msg): if __debug__: logger.debug(msg) self.downstream.write(error_response) self.close()
[ "def", "bad_request", "(", "self", ",", "msg", ")", ":", "if", "__debug__", ":", "logger", ".", "debug", "(", "msg", ")", "self", ".", "downstream", ".", "write", "(", "error_response", ")", "self", ".", "close", "(", ")" ]
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/network/lib/transports/websocket.py#L375-L380
fbchat-dev/fbchat
916a14062d31f3624dfe8dd4ab672648a3e508c0
fbchat/_threads/_abc.py
python
ThreadABC.id
(self)
The unique identifier of the thread.
The unique identifier of the thread.
[ "The", "unique", "identifier", "of", "the", "thread", "." ]
def id(self) -> str: """The unique identifier of the thread.""" raise NotImplementedError
[ "def", "id", "(", "self", ")", "->", "str", ":", "raise", "NotImplementedError" ]
https://github.com/fbchat-dev/fbchat/blob/916a14062d31f3624dfe8dd4ab672648a3e508c0/fbchat/_threads/_abc.py#L49-L51
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/suite_xml/post_process/workflow.py
python
EndOfFormNavigationWorkflow.form_workflow_frames
(self, module, form)
return stack_frames
post_form_workflow = 'module': * Add stack frame and a command with value = "module command" post_form_workflow = 'previous_screen': * Add stack frame and a command with value = "module command" * Find longest list of common datums between form entries for the module and add datums to the stack frame for each. * Add a command to the frame with value = "form command" * Add datums to the frame for any remaining datums for that form. * Remove any autoselect items from the end of the stack frame. * Finally remove the last item from the stack frame.
post_form_workflow = 'module': * Add stack frame and a command with value = "module command"
[ "post_form_workflow", "=", "module", ":", "*", "Add", "stack", "frame", "and", "a", "command", "with", "value", "=", "module", "command" ]
def form_workflow_frames(self, module, form): """ post_form_workflow = 'module': * Add stack frame and a command with value = "module command" post_form_workflow = 'previous_screen': * Add stack frame and a command with value = "module command" * Find longest list of common datums between form entries for the module and add datums to the stack frame for each. * Add a command to the frame with value = "form command" * Add datums to the frame for any remaining datums for that form. * Remove any autoselect items from the end of the stack frame. * Finally remove the last item from the stack frame. """ if form.post_form_workflow != WORKFLOW_FORM: static_stack_frame = self._get_static_stack_frame(form.post_form_workflow, form, module) return [static_stack_frame] if static_stack_frame else [] stack_frames = [] for link in form.form_links: stack_frames.append(self._get_link_frame(link, form, module)) fallback_frame = self._get_fallback_frame(form, module) if fallback_frame: stack_frames.append(fallback_frame) return stack_frames
[ "def", "form_workflow_frames", "(", "self", ",", "module", ",", "form", ")", ":", "if", "form", ".", "post_form_workflow", "!=", "WORKFLOW_FORM", ":", "static_stack_frame", "=", "self", ".", "_get_static_stack_frame", "(", "form", ".", "post_form_workflow", ",", "form", ",", "module", ")", "return", "[", "static_stack_frame", "]", "if", "static_stack_frame", "else", "[", "]", "stack_frames", "=", "[", "]", "for", "link", "in", "form", ".", "form_links", ":", "stack_frames", ".", "append", "(", "self", ".", "_get_link_frame", "(", "link", ",", "form", ",", "module", ")", ")", "fallback_frame", "=", "self", ".", "_get_fallback_frame", "(", "form", ",", "module", ")", "if", "fallback_frame", ":", "stack_frames", ".", "append", "(", "fallback_frame", ")", "return", "stack_frames" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/suite_xml/post_process/workflow.py#L292-L318
hhursev/recipe-scrapers
478b9ddb0dda02b17b14f299eea729bef8131aa9
recipe_scrapers/motherthyme.py
python
MotherThyme.total_time
(self)
return get_minutes( self.soup.find("span", {"class": "wprm-recipe-total_time"}).parent )
[]
def total_time(self): return get_minutes( self.soup.find("span", {"class": "wprm-recipe-total_time"}).parent )
[ "def", "total_time", "(", "self", ")", ":", "return", "get_minutes", "(", "self", ".", "soup", ".", "find", "(", "\"span\"", ",", "{", "\"class\"", ":", "\"wprm-recipe-total_time\"", "}", ")", ".", "parent", ")" ]
https://github.com/hhursev/recipe-scrapers/blob/478b9ddb0dda02b17b14f299eea729bef8131aa9/recipe_scrapers/motherthyme.py#L13-L16
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/__init__.py
python
TriggerView.list
(self, gid, sid, did, scid, tid)
return ajax_response( response=res['rows'], status=200 )
This function is used to list all the trigger nodes within that collection. Args: gid: Server group ID sid: Server ID did: Database ID scid: Schema ID tid: Table ID Returns: JSON of available trigger nodes
This function is used to list all the trigger nodes within that collection.
[ "This", "function", "is", "used", "to", "list", "all", "the", "trigger", "nodes", "within", "that", "collection", "." ]
def list(self, gid, sid, did, scid, tid): """ This function is used to list all the trigger nodes within that collection. Args: gid: Server group ID sid: Server ID did: Database ID scid: Schema ID tid: Table ID Returns: JSON of available trigger nodes """ SQL = render_template("/".join([self.template_path, self._PROPERTIES_SQL]), tid=tid) status, res = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=res) return ajax_response( response=res['rows'], status=200 )
[ "def", "list", "(", "self", ",", "gid", ",", "sid", ",", "did", ",", "scid", ",", "tid", ")", ":", "SQL", "=", "render_template", "(", "\"/\"", ".", "join", "(", "[", "self", ".", "template_path", ",", "self", ".", "_PROPERTIES_SQL", "]", ")", ",", "tid", "=", "tid", ")", "status", ",", "res", "=", "self", ".", "conn", ".", "execute_dict", "(", "SQL", ")", "if", "not", "status", ":", "return", "internal_server_error", "(", "errormsg", "=", "res", ")", "return", "ajax_response", "(", "response", "=", "res", "[", "'rows'", "]", ",", "status", "=", "200", ")" ]
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/triggers/__init__.py#L401-L426
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/scripts/genes2genes.py
python
main
(argv=None)
script main. parses command line options in sys.argv, unless *argv* is given.
script main.
[ "script", "main", "." ]
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv # setup command line parser parser = E.OptionParser(version="%prog version: $Id$", usage=globals()["__doc__"]) parser.add_option( "-q", "--query-species", dest="query_species", type="string", help="query species [%default]") parser.add_option( "-t", "--target-species", dest="target_species", type="string", help="target species [%default]") parser.add_option( "-c", "--column", dest="column", type="string", help="column number or name with gene name to map [%default]") parser.set_defaults( query_species="hsapiens", target_species=None, column=1) # add common options (-h/--help, ...) and parse command line (options, args) = E.Start(parser, argv=argv) if options.target_species: map_orthologs = buildOrthologyMap( options.query_species, options.target_species) else: map_orthologs = None E.info("orthology map: %i -> %i (%i unique)" % (len(map_orthologs), len(list(map_orthologs.values())), len(set(map_orthologs.values())))) map_identifiers = buildIdentifierMap( options.query_species) E.info("identifier map: %i -> %i" % (len(map_identifiers), len(list(map_identifiers.values())))) first = True outfile = options.stdout c = E.Counter() for line in options.stdin: if line.startswith("#"): continue data = line[:-1].split("\t") if first: try: column = data.index(options.column) data[column] = "gene_id" except ValueError: column = int(options.column) - 1 outfile.write("\t".join(data) + "\n") first = False orig_id = data[column] gene_id = data[column].upper() c.input += 1 if gene_id in map_identifiers: m = map_identifiers[gene_id] if len(m) > 1: c.skipped_multiple_identifiers += 1 E.warn("skipped: %s - multiple identifiers: %s" % (gene_id, m)) continue new_id, method = m[0] c[method] += 1 gene_id = new_id else: c.skipped_no_identifiers += 1 continue if map_orthologs: if gene_id in map_orthologs: c.has_ortholog += 1 gene_id = map_orthologs[gene_id] else: c.skipped_no_orthologs += 1 E.warn("skipped: no ortholog %s->%s" % (orig_id, gene_id)) continue c.output += 1 data[column] = gene_id outfile.write("\t".join(data) + "\n") E.info(c) # write footer and output benchmark information. E.Stop()
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "# setup command line parser", "parser", "=", "E", ".", "OptionParser", "(", "version", "=", "\"%prog version: $Id$\"", ",", "usage", "=", "globals", "(", ")", "[", "\"__doc__\"", "]", ")", "parser", ".", "add_option", "(", "\"-q\"", ",", "\"--query-species\"", ",", "dest", "=", "\"query_species\"", ",", "type", "=", "\"string\"", ",", "help", "=", "\"query species [%default]\"", ")", "parser", ".", "add_option", "(", "\"-t\"", ",", "\"--target-species\"", ",", "dest", "=", "\"target_species\"", ",", "type", "=", "\"string\"", ",", "help", "=", "\"target species [%default]\"", ")", "parser", ".", "add_option", "(", "\"-c\"", ",", "\"--column\"", ",", "dest", "=", "\"column\"", ",", "type", "=", "\"string\"", ",", "help", "=", "\"column number or name with gene name to map [%default]\"", ")", "parser", ".", "set_defaults", "(", "query_species", "=", "\"hsapiens\"", ",", "target_species", "=", "None", ",", "column", "=", "1", ")", "# add common options (-h/--help, ...) and parse command line", "(", "options", ",", "args", ")", "=", "E", ".", "Start", "(", "parser", ",", "argv", "=", "argv", ")", "if", "options", ".", "target_species", ":", "map_orthologs", "=", "buildOrthologyMap", "(", "options", ".", "query_species", ",", "options", ".", "target_species", ")", "else", ":", "map_orthologs", "=", "None", "E", ".", "info", "(", "\"orthology map: %i -> %i (%i unique)\"", "%", "(", "len", "(", "map_orthologs", ")", ",", "len", "(", "list", "(", "map_orthologs", ".", "values", "(", ")", ")", ")", ",", "len", "(", "set", "(", "map_orthologs", ".", "values", "(", ")", ")", ")", ")", ")", "map_identifiers", "=", "buildIdentifierMap", "(", "options", ".", "query_species", ")", "E", ".", "info", "(", "\"identifier map: %i -> %i\"", "%", "(", "len", "(", "map_identifiers", ")", ",", "len", "(", "list", "(", "map_identifiers", ".", "values", "(", ")", ")", ")", ")", ")", "first", "=", "True", "outfile", "=", "options", ".", "stdout", "c", "=", "E", ".", "Counter", "(", ")", "for", "line", "in", "options", ".", "stdin", ":", "if", "line", ".", "startswith", "(", "\"#\"", ")", ":", "continue", "data", "=", "line", "[", ":", "-", "1", "]", ".", "split", "(", "\"\\t\"", ")", "if", "first", ":", "try", ":", "column", "=", "data", ".", "index", "(", "options", ".", "column", ")", "data", "[", "column", "]", "=", "\"gene_id\"", "except", "ValueError", ":", "column", "=", "int", "(", "options", ".", "column", ")", "-", "1", "outfile", ".", "write", "(", "\"\\t\"", ".", "join", "(", "data", ")", "+", "\"\\n\"", ")", "first", "=", "False", "orig_id", "=", "data", "[", "column", "]", "gene_id", "=", "data", "[", "column", "]", ".", "upper", "(", ")", "c", ".", "input", "+=", "1", "if", "gene_id", "in", "map_identifiers", ":", "m", "=", "map_identifiers", "[", "gene_id", "]", "if", "len", "(", "m", ")", ">", "1", ":", "c", ".", "skipped_multiple_identifiers", "+=", "1", "E", ".", "warn", "(", "\"skipped: %s - multiple identifiers: %s\"", "%", "(", "gene_id", ",", "m", ")", ")", "continue", "new_id", ",", "method", "=", "m", "[", "0", "]", "c", "[", "method", "]", "+=", "1", "gene_id", "=", "new_id", "else", ":", "c", ".", "skipped_no_identifiers", "+=", "1", "continue", "if", "map_orthologs", ":", "if", "gene_id", "in", "map_orthologs", ":", "c", ".", "has_ortholog", "+=", "1", "gene_id", "=", "map_orthologs", "[", "gene_id", "]", "else", ":", "c", ".", "skipped_no_orthologs", "+=", "1", "E", ".", "warn", "(", "\"skipped: no ortholog %s->%s\"", "%", "(", "orig_id", ",", "gene_id", ")", ")", "continue", "c", ".", "output", "+=", "1", "data", "[", "column", "]", "=", "gene_id", "outfile", ".", "write", "(", "\"\\t\"", ".", "join", "(", "data", ")", "+", "\"\\n\"", ")", "E", ".", "info", "(", "c", ")", "# write footer and output benchmark information.", "E", ".", "Stop", "(", ")" ]
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/scripts/genes2genes.py#L94-L203
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
transwarp/web.py
python
_quote
(s, encoding='utf-8')
return urllib.quote(s)
Url quote as str. >>> _quote('http://example/test?a=1+') 'http%3A//example/test%3Fa%3D1%2B' >>> _quote(u'hello world!') 'hello%20world%21'
Url quote as str.
[ "Url", "quote", "as", "str", "." ]
def _quote(s, encoding='utf-8'): ''' Url quote as str. >>> _quote('http://example/test?a=1+') 'http%3A//example/test%3Fa%3D1%2B' >>> _quote(u'hello world!') 'hello%20world%21' ''' if isinstance(s, unicode): s = s.encode(encoding) return urllib.quote(s)
[ "def", "_quote", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "s", "=", "s", ".", "encode", "(", "encoding", ")", "return", "urllib", ".", "quote", "(", "s", ")" ]
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/transwarp/web.py#L369-L380
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/chat/v1/service/channel/member.py
python
MemberList.get
(self, sid)
return MemberContext( self._version, service_sid=self._solution['service_sid'], channel_sid=self._solution['channel_sid'], sid=sid, )
Constructs a MemberContext :param sid: The unique string that identifies the resource :returns: twilio.rest.chat.v1.service.channel.member.MemberContext :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext
Constructs a MemberContext
[ "Constructs", "a", "MemberContext" ]
def get(self, sid): """ Constructs a MemberContext :param sid: The unique string that identifies the resource :returns: twilio.rest.chat.v1.service.channel.member.MemberContext :rtype: twilio.rest.chat.v1.service.channel.member.MemberContext """ return MemberContext( self._version, service_sid=self._solution['service_sid'], channel_sid=self._solution['channel_sid'], sid=sid, )
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "MemberContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "channel_sid", "=", "self", ".", "_solution", "[", "'channel_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v1/service/channel/member.py#L143-L157
CloudBotIRC/CloudBot
6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea
plugins/core_tracker.py
python
on_join
(conn, chan, target)
:type conn: cloudbot.client.Client :type chan: str :type nick: str
:type conn: cloudbot.client.Client :type chan: str :type nick: str
[ ":", "type", "conn", ":", "cloudbot", ".", "client", ".", "Client", ":", "type", "chan", ":", "str", ":", "type", "nick", ":", "str" ]
def on_join(conn, chan, target): """ :type conn: cloudbot.client.Client :type chan: str :type nick: str """ if target == conn.nick: bot_joined_channel(conn, chan)
[ "def", "on_join", "(", "conn", ",", "chan", ",", "target", ")", ":", "if", "target", "==", "conn", ".", "nick", ":", "bot_joined_channel", "(", "conn", ",", "chan", ")" ]
https://github.com/CloudBotIRC/CloudBot/blob/6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea/plugins/core_tracker.py#L84-L91
openstack/neutron
fb229fb527ac8b95526412f7762d90826ac41428
neutron/extensions/metering.py
python
MeteringPluginBase.get_metering_label_rule
(self, context, rule_id, fields=None)
Get a metering label rule.
Get a metering label rule.
[ "Get", "a", "metering", "label", "rule", "." ]
def get_metering_label_rule(self, context, rule_id, fields=None): """Get a metering label rule.""" pass
[ "def", "get_metering_label_rule", "(", "self", ",", "context", ",", "rule_id", ",", "fields", "=", "None", ")", ":", "pass" ]
https://github.com/openstack/neutron/blob/fb229fb527ac8b95526412f7762d90826ac41428/neutron/extensions/metering.py#L90-L92
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/dev/bdf_vectorized/bdf_interface2/attributes.py
python
BDFAttributes.object_methods
(self, mode='public', keys_to_skip=None)
return object_methods(self, mode=mode, keys_to_skip=keys_to_skip+my_keys_to_skip)
List the names of methods of a class as strings. Returns public methods as default. Parameters ---------- obj : instance the object for checking mode : str defines what kind of methods will be listed * "public" - names that do not begin with underscore * "private" - names that begin with single underscore * "both" - private and public * "all" - all methods that are defined for the object keys_to_skip : List[str]; default=None -> [] names to not consider to avoid deprecation warnings Returns ------- method : List[str] sorted list of the names of methods of a given type or None if the mode is wrong
List the names of methods of a class as strings. Returns public methods as default.
[ "List", "the", "names", "of", "methods", "of", "a", "class", "as", "strings", ".", "Returns", "public", "methods", "as", "default", "." ]
def object_methods(self, mode='public', keys_to_skip=None): """ List the names of methods of a class as strings. Returns public methods as default. Parameters ---------- obj : instance the object for checking mode : str defines what kind of methods will be listed * "public" - names that do not begin with underscore * "private" - names that begin with single underscore * "both" - private and public * "all" - all methods that are defined for the object keys_to_skip : List[str]; default=None -> [] names to not consider to avoid deprecation warnings Returns ------- method : List[str] sorted list of the names of methods of a given type or None if the mode is wrong """ if keys_to_skip is None: keys_to_skip = [] my_keys_to_skip = [] my_keys_to_skip = [ #'case_control_deck', 'log', #'mpcObject', 'spcObject', 'node_ids', 'coord_ids', 'element_ids', 'property_ids', 'material_ids', 'caero_ids', 'is_long_ids', 'nnodes', 'ncoords', 'nelements', 'nproperties', 'nmaterials', 'ncaeros', 'point_ids', 'subcases', '_card_parser', '_card_parser_b', 'object_methods', 'object_attributes', ] return object_methods(self, mode=mode, keys_to_skip=keys_to_skip+my_keys_to_skip)
[ "def", "object_methods", "(", "self", ",", "mode", "=", "'public'", ",", "keys_to_skip", "=", "None", ")", ":", "if", "keys_to_skip", "is", "None", ":", "keys_to_skip", "=", "[", "]", "my_keys_to_skip", "=", "[", "]", "my_keys_to_skip", "=", "[", "#'case_control_deck',", "'log'", ",", "#'mpcObject', 'spcObject',", "'node_ids'", ",", "'coord_ids'", ",", "'element_ids'", ",", "'property_ids'", ",", "'material_ids'", ",", "'caero_ids'", ",", "'is_long_ids'", ",", "'nnodes'", ",", "'ncoords'", ",", "'nelements'", ",", "'nproperties'", ",", "'nmaterials'", ",", "'ncaeros'", ",", "'point_ids'", ",", "'subcases'", ",", "'_card_parser'", ",", "'_card_parser_b'", ",", "'object_methods'", ",", "'object_attributes'", ",", "]", "return", "object_methods", "(", "self", ",", "mode", "=", "mode", ",", "keys_to_skip", "=", "keys_to_skip", "+", "my_keys_to_skip", ")" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/bdf_interface2/attributes.py#L654-L694
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/papylib/papyon/papyon/media/message.py
python
MediaSessionMessage.descriptions
(self)
return self._descriptions
Media stream descriptions
Media stream descriptions
[ "Media", "stream", "descriptions" ]
def descriptions(self): """Media stream descriptions""" return self._descriptions
[ "def", "descriptions", "(", "self", ")", ":", "return", "self", ".", "_descriptions" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/papylib/papyon/papyon/media/message.py#L38-L40
ucbdrive/3d-vehicle-tracking
8ee189f6792897651bb56bb2950ce07c9629a89d
3d-tracking/lib/model/rpn/proposal_layer.py
python
_ProposalLayer._filter_boxes
(self, boxes, min_size)
return keep
Remove all boxes with any side smaller than min_size.
Remove all boxes with any side smaller than min_size.
[ "Remove", "all", "boxes", "with", "any", "side", "smaller", "than", "min_size", "." ]
def _filter_boxes(self, boxes, min_size): """Remove all boxes with any side smaller than min_size.""" ws = boxes[:, :, 2] - boxes[:, :, 0] + 1 hs = boxes[:, :, 3] - boxes[:, :, 1] + 1 keep = ((ws >= min_size.view(-1,1).expand_as(ws)) & (hs >= min_size.view(-1,1).expand_as(hs))) return keep
[ "def", "_filter_boxes", "(", "self", ",", "boxes", ",", "min_size", ")", ":", "ws", "=", "boxes", "[", ":", ",", ":", ",", "2", "]", "-", "boxes", "[", ":", ",", ":", ",", "0", "]", "+", "1", "hs", "=", "boxes", "[", ":", ",", ":", ",", "3", "]", "-", "boxes", "[", ":", ",", ":", ",", "1", "]", "+", "1", "keep", "=", "(", "(", "ws", ">=", "min_size", ".", "view", "(", "-", "1", ",", "1", ")", ".", "expand_as", "(", "ws", ")", ")", "&", "(", "hs", ">=", "min_size", ".", "view", "(", "-", "1", ",", "1", ")", ".", "expand_as", "(", "hs", ")", ")", ")", "return", "keep" ]
https://github.com/ucbdrive/3d-vehicle-tracking/blob/8ee189f6792897651bb56bb2950ce07c9629a89d/3d-tracking/lib/model/rpn/proposal_layer.py#L170-L175
derek-zhang123/MxOnline
4e3de31164734792a978c6760f2e0f0d97f97a53
extra_apps/xadmin/plugins/importexport.py
python
ExportMixin.get_export_resource_class
(self)
return self.get_resource_class(usage='export')
Returns ResourceClass to use for export.
Returns ResourceClass to use for export.
[ "Returns", "ResourceClass", "to", "use", "for", "export", "." ]
def get_export_resource_class(self): """ Returns ResourceClass to use for export. """ return self.get_resource_class(usage='export')
[ "def", "get_export_resource_class", "(", "self", ")", ":", "return", "self", ".", "get_resource_class", "(", "usage", "=", "'export'", ")" ]
https://github.com/derek-zhang123/MxOnline/blob/4e3de31164734792a978c6760f2e0f0d97f97a53/extra_apps/xadmin/plugins/importexport.py#L348-L352
maurosoria/dirsearch
b83e68c8fdf360ab06be670d7b92b263262ee5b1
thirdparty/jinja2/lexer.py
python
compile_rules
(environment: "Environment")
return [x[1:] for x in sorted(rules, reverse=True)]
Compiles all the rules from the environment into a list of rules.
Compiles all the rules from the environment into a list of rules.
[ "Compiles", "all", "the", "rules", "from", "the", "environment", "into", "a", "list", "of", "rules", "." ]
def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]: """Compiles all the rules from the environment into a list of rules.""" e = re.escape rules = [ ( len(environment.comment_start_string), TOKEN_COMMENT_BEGIN, e(environment.comment_start_string), ), ( len(environment.block_start_string), TOKEN_BLOCK_BEGIN, e(environment.block_start_string), ), ( len(environment.variable_start_string), TOKEN_VARIABLE_BEGIN, e(environment.variable_start_string), ), ] if environment.line_statement_prefix is not None: rules.append( ( len(environment.line_statement_prefix), TOKEN_LINESTATEMENT_BEGIN, r"^[ \t\v]*" + e(environment.line_statement_prefix), ) ) if environment.line_comment_prefix is not None: rules.append( ( len(environment.line_comment_prefix), TOKEN_LINECOMMENT_BEGIN, r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix), ) ) return [x[1:] for x in sorted(rules, reverse=True)]
[ "def", "compile_rules", "(", "environment", ":", "\"Environment\"", ")", "->", "t", ".", "List", "[", "t", ".", "Tuple", "[", "str", ",", "str", "]", "]", ":", "e", "=", "re", ".", "escape", "rules", "=", "[", "(", "len", "(", "environment", ".", "comment_start_string", ")", ",", "TOKEN_COMMENT_BEGIN", ",", "e", "(", "environment", ".", "comment_start_string", ")", ",", ")", ",", "(", "len", "(", "environment", ".", "block_start_string", ")", ",", "TOKEN_BLOCK_BEGIN", ",", "e", "(", "environment", ".", "block_start_string", ")", ",", ")", ",", "(", "len", "(", "environment", ".", "variable_start_string", ")", ",", "TOKEN_VARIABLE_BEGIN", ",", "e", "(", "environment", ".", "variable_start_string", ")", ",", ")", ",", "]", "if", "environment", ".", "line_statement_prefix", "is", "not", "None", ":", "rules", ".", "append", "(", "(", "len", "(", "environment", ".", "line_statement_prefix", ")", ",", "TOKEN_LINESTATEMENT_BEGIN", ",", "r\"^[ \\t\\v]*\"", "+", "e", "(", "environment", ".", "line_statement_prefix", ")", ",", ")", ")", "if", "environment", ".", "line_comment_prefix", "is", "not", "None", ":", "rules", ".", "append", "(", "(", "len", "(", "environment", ".", "line_comment_prefix", ")", ",", "TOKEN_LINECOMMENT_BEGIN", ",", "r\"(?:^|(?<=\\S))[^\\S\\r\\n]*\"", "+", "e", "(", "environment", ".", "line_comment_prefix", ")", ",", ")", ")", "return", "[", "x", "[", "1", ":", "]", "for", "x", "in", "sorted", "(", "rules", ",", "reverse", "=", "True", ")", "]" ]
https://github.com/maurosoria/dirsearch/blob/b83e68c8fdf360ab06be670d7b92b263262ee5b1/thirdparty/jinja2/lexer.py#L211-L249
python-acoustics/python-acoustics
af72e7f88003f0bba06934ea38c98e8993c4a6c6
acoustics/_signal.py
python
Signal.plot_levels
(self, **kwargs)
return _base_plot(t, L_masked, params)
Plot sound pressure level as function of time. .. seealso:: :meth:`levels`
Plot sound pressure level as function of time.
[ "Plot", "sound", "pressure", "level", "as", "function", "of", "time", "." ]
def plot_levels(self, **kwargs): """Plot sound pressure level as function of time. .. seealso:: :meth:`levels` """ params = { 'xscale': 'linear', 'yscale': 'linear', 'xlabel': '$t$ in s', 'ylabel': '$L_{p,F}$ in dB', 'title': 'SPL', 'time': 0.125, 'method': 'average', 'labels': None, } params.update(kwargs) t, L = self.levels(params['time'], params['method']) L_masked = np.ma.masked_where(np.isinf(L), L) return _base_plot(t, L_masked, params)
[ "def", "plot_levels", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'xscale'", ":", "'linear'", ",", "'yscale'", ":", "'linear'", ",", "'xlabel'", ":", "'$t$ in s'", ",", "'ylabel'", ":", "'$L_{p,F}$ in dB'", ",", "'title'", ":", "'SPL'", ",", "'time'", ":", "0.125", ",", "'method'", ":", "'average'", ",", "'labels'", ":", "None", ",", "}", "params", ".", "update", "(", "kwargs", ")", "t", ",", "L", "=", "self", ".", "levels", "(", "params", "[", "'time'", "]", ",", "params", "[", "'method'", "]", ")", "L_masked", "=", "np", ".", "ma", ".", "masked_where", "(", "np", ".", "isinf", "(", "L", ")", ",", "L", ")", "return", "_base_plot", "(", "t", ",", "L_masked", ",", "params", ")" ]
https://github.com/python-acoustics/python-acoustics/blob/af72e7f88003f0bba06934ea38c98e8993c4a6c6/acoustics/_signal.py#L707-L726
TurboGears/tg2
f40a82d016d70ce560002593b4bb8f83b57f87b3
tg/i18n.py
python
_parse_locale
(identifier, sep='_')
return lang, territory, script, variant
Took from Babel, Parse a locale identifier into a tuple of the form:: ``(language, territory, script, variant)`` >>> parse_locale('zh_CN') ('zh', 'CN', None, None) >>> parse_locale('zh_Hans_CN') ('zh', 'CN', 'Hans', None) The default component separator is "_", but a different separator can be specified using the `sep` parameter: :see: `IETF RFC 4646 <http://www.ietf.org/rfc/rfc4646.txt>`_
Took from Babel, Parse a locale identifier into a tuple of the form::
[ "Took", "from", "Babel", "Parse", "a", "locale", "identifier", "into", "a", "tuple", "of", "the", "form", "::" ]
def _parse_locale(identifier, sep='_'): """ Took from Babel, Parse a locale identifier into a tuple of the form:: ``(language, territory, script, variant)`` >>> parse_locale('zh_CN') ('zh', 'CN', None, None) >>> parse_locale('zh_Hans_CN') ('zh', 'CN', 'Hans', None) The default component separator is "_", but a different separator can be specified using the `sep` parameter: :see: `IETF RFC 4646 <http://www.ietf.org/rfc/rfc4646.txt>`_ """ if '.' in identifier: # this is probably the charset/encoding, which we don't care about identifier = identifier.split('.', 1)[0] if '@' in identifier: # this is a locale modifier such as @euro, which we don't care about # either identifier = identifier.split('@', 1)[0] parts = identifier.split(sep) lang = parts.pop(0).lower() if not lang.isalpha(): raise ValueError('expected only letters, got %r' % lang) script = territory = variant = None if parts: if len(parts[0]) == 4 and parts[0].isalpha(): script = parts.pop(0).title() if parts: if len(parts[0]) == 2 and parts[0].isalpha(): territory = parts.pop(0).upper() elif len(parts[0]) == 3 and parts[0].isdigit(): territory = parts.pop(0) if parts: if len(parts[0]) == 4 and parts[0][0].isdigit() or\ len(parts[0]) >= 5 and parts[0][0].isalpha(): variant = parts.pop() if parts: raise ValueError('%r is not a valid locale identifier' % identifier) return lang, territory, script, variant
[ "def", "_parse_locale", "(", "identifier", ",", "sep", "=", "'_'", ")", ":", "if", "'.'", "in", "identifier", ":", "# this is probably the charset/encoding, which we don't care about", "identifier", "=", "identifier", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "'@'", "in", "identifier", ":", "# this is a locale modifier such as @euro, which we don't care about", "# either", "identifier", "=", "identifier", ".", "split", "(", "'@'", ",", "1", ")", "[", "0", "]", "parts", "=", "identifier", ".", "split", "(", "sep", ")", "lang", "=", "parts", ".", "pop", "(", "0", ")", ".", "lower", "(", ")", "if", "not", "lang", ".", "isalpha", "(", ")", ":", "raise", "ValueError", "(", "'expected only letters, got %r'", "%", "lang", ")", "script", "=", "territory", "=", "variant", "=", "None", "if", "parts", ":", "if", "len", "(", "parts", "[", "0", "]", ")", "==", "4", "and", "parts", "[", "0", "]", ".", "isalpha", "(", ")", ":", "script", "=", "parts", ".", "pop", "(", "0", ")", ".", "title", "(", ")", "if", "parts", ":", "if", "len", "(", "parts", "[", "0", "]", ")", "==", "2", "and", "parts", "[", "0", "]", ".", "isalpha", "(", ")", ":", "territory", "=", "parts", ".", "pop", "(", "0", ")", ".", "upper", "(", ")", "elif", "len", "(", "parts", "[", "0", "]", ")", "==", "3", "and", "parts", "[", "0", "]", ".", "isdigit", "(", ")", ":", "territory", "=", "parts", ".", "pop", "(", "0", ")", "if", "parts", ":", "if", "len", "(", "parts", "[", "0", "]", ")", "==", "4", "and", "parts", "[", "0", "]", "[", "0", "]", ".", "isdigit", "(", ")", "or", "len", "(", "parts", "[", "0", "]", ")", ">=", "5", "and", "parts", "[", "0", "]", "[", "0", "]", ".", "isalpha", "(", ")", ":", "variant", "=", "parts", ".", "pop", "(", ")", "if", "parts", ":", "raise", "ValueError", "(", "'%r is not a valid locale identifier'", "%", "identifier", ")", "return", "lang", ",", "territory", ",", "script", ",", "variant" ]
https://github.com/TurboGears/tg2/blob/f40a82d016d70ce560002593b4bb8f83b57f87b3/tg/i18n.py#L18-L67
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
acitoolkit/acisession.py
python
Subscriber.get_event
(self, url)
return event
Get an event for a particular APIC URL subscription. Used internally by the Class and Instance subscriptions. :param url: URL string to get pending event
Get an event for a particular APIC URL subscription. Used internally by the Class and Instance subscriptions.
[ "Get", "an", "event", "for", "a", "particular", "APIC", "URL", "subscription", ".", "Used", "internally", "by", "the", "Class", "and", "Instance", "subscriptions", "." ]
def get_event(self, url): """ Get an event for a particular APIC URL subscription. Used internally by the Class and Instance subscriptions. :param url: URL string to get pending event """ self._process_event_q() if url not in self._events: raise ValueError event = self._events[url].pop(0) log.debug('Event received %s', event) return event
[ "def", "get_event", "(", "self", ",", "url", ")", ":", "self", ".", "_process_event_q", "(", ")", "if", "url", "not", "in", "self", ".", "_events", ":", "raise", "ValueError", "event", "=", "self", ".", "_events", "[", "url", "]", ".", "pop", "(", "0", ")", "log", ".", "debug", "(", "'Event received %s'", ",", "event", ")", "return", "event" ]
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/acisession.py#L399-L411
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/apache2_module.py
python
create_apache_identifier
(name)
return name + '_module'
By convention if a module is loaded via name, it appears in apache2ctl -M as name_module. Some modules don't follow this convention and we use replacements for those.
By convention if a module is loaded via name, it appears in apache2ctl -M as name_module.
[ "By", "convention", "if", "a", "module", "is", "loaded", "via", "name", "it", "appears", "in", "apache2ctl", "-", "M", "as", "name_module", "." ]
def create_apache_identifier(name): """ By convention if a module is loaded via name, it appears in apache2ctl -M as name_module. Some modules don't follow this convention and we use replacements for those.""" # a2enmod name replacement to apache2ctl -M names text_workarounds = [ ('shib', 'mod_shib'), ('shib2', 'mod_shib'), ('evasive', 'evasive20_module'), ] # re expressions to extract subparts of names re_workarounds = [ ('php', re.compile(r'^(php\d)\.')), ] for a2enmod_spelling, module_name in text_workarounds: if a2enmod_spelling in name: return module_name for search, reexpr in re_workarounds: if search in name: try: rematch = reexpr.search(name) return rematch.group(1) + '_module' except AttributeError: pass return name + '_module'
[ "def", "create_apache_identifier", "(", "name", ")", ":", "# a2enmod name replacement to apache2ctl -M names", "text_workarounds", "=", "[", "(", "'shib'", ",", "'mod_shib'", ")", ",", "(", "'shib2'", ",", "'mod_shib'", ")", ",", "(", "'evasive'", ",", "'evasive20_module'", ")", ",", "]", "# re expressions to extract subparts of names", "re_workarounds", "=", "[", "(", "'php'", ",", "re", ".", "compile", "(", "r'^(php\\d)\\.'", ")", ")", ",", "]", "for", "a2enmod_spelling", ",", "module_name", "in", "text_workarounds", ":", "if", "a2enmod_spelling", "in", "name", ":", "return", "module_name", "for", "search", ",", "reexpr", "in", "re_workarounds", ":", "if", "search", "in", "name", ":", "try", ":", "rematch", "=", "reexpr", ".", "search", "(", "name", ")", "return", "rematch", ".", "group", "(", "1", ")", "+", "'_module'", "except", "AttributeError", ":", "pass", "return", "name", "+", "'_module'" ]
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/apache2_module.py#L156-L187
easylist/easylist
d9cd413870b79d3c95462e0a6ab4fe1ec0825cf8
FOP.py
python
start
()
Print a greeting message and run FOP in the directories specified via the command line, or the current working directory if no arguments have been passed.
Print a greeting message and run FOP in the directories specified via the command line, or the current working directory if no arguments have been passed.
[ "Print", "a", "greeting", "message", "and", "run", "FOP", "in", "the", "directories", "specified", "via", "the", "command", "line", "or", "the", "current", "working", "directory", "if", "no", "arguments", "have", "been", "passed", "." ]
def start (): """ Print a greeting message and run FOP in the directories specified via the command line, or the current working directory if no arguments have been passed.""" greeting = "FOP (Filter Orderer and Preener) version {version}".format(version = VERSION) characters = len(str(greeting)) print("=" * characters) print(greeting) print("=" * characters) # Convert the directory names to absolute references and visit each unique location places = sys.argv[1:] if places: places = [os.path.abspath(place) for place in places] for place in sorted(set(places)): main(place) print() else: main(os.getcwd())
[ "def", "start", "(", ")", ":", "greeting", "=", "\"FOP (Filter Orderer and Preener) version {version}\"", ".", "format", "(", "version", "=", "VERSION", ")", "characters", "=", "len", "(", "str", "(", "greeting", ")", ")", "print", "(", "\"=\"", "*", "characters", ")", "print", "(", "greeting", ")", "print", "(", "\"=\"", "*", "characters", ")", "# Convert the directory names to absolute references and visit each unique location", "places", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "places", ":", "places", "=", "[", "os", ".", "path", ".", "abspath", "(", "place", ")", "for", "place", "in", "places", "]", "for", "place", "in", "sorted", "(", "set", "(", "places", ")", ")", ":", "main", "(", "place", ")", "print", "(", ")", "else", ":", "main", "(", "os", ".", "getcwd", "(", ")", ")" ]
https://github.com/easylist/easylist/blob/d9cd413870b79d3c95462e0a6ab4fe1ec0825cf8/FOP.py#L74-L92
p2pool/p2pool
53c438bbada06b9d4a9a465bc13f7694a7a322b7
wstools/XMLSchema.py
python
AttributeGroupDefinition.getAttributeContent
(self)
return self.attr_content
[]
def getAttributeContent(self): return self.attr_content
[ "def", "getAttributeContent", "(", "self", ")", ":", "return", "self", ".", "attr_content" ]
https://github.com/p2pool/p2pool/blob/53c438bbada06b9d4a9a465bc13f7694a7a322b7/wstools/XMLSchema.py#L1627-L1628
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_user.py
python
SecurityContextConstraints.groups
(self)
return self._groups
groups property getter
groups property getter
[ "groups", "property", "getter" ]
def groups(self): ''' groups property getter ''' if self._groups is None: self._groups = self.get_groups() return self._groups
[ "def", "groups", "(", "self", ")", ":", "if", "self", ".", "_groups", "is", "None", ":", "self", ".", "_groups", "=", "self", ".", "get_groups", "(", ")", "return", "self", ".", "_groups" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_user.py#L1890-L1894
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/decimal.py
python
Context.Etop
(self)
return int(self.Emax - self.prec + 1)
Returns maximum exponent (= Emax - prec + 1)
Returns maximum exponent (= Emax - prec + 1)
[ "Returns", "maximum", "exponent", "(", "=", "Emax", "-", "prec", "+", "1", ")" ]
def Etop(self): """Returns maximum exponent (= Emax - prec + 1)""" return int(self.Emax - self.prec + 1)
[ "def", "Etop", "(", "self", ")", ":", "return", "int", "(", "self", ".", "Emax", "-", "self", ".", "prec", "+", "1", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/decimal.py#L3899-L3901
devstructure/blueprint
574a9fc0dd3031c66970387f1105d8c89e61218f
blueprint/frontend/chef.py
python
Resource.dumps
(self, inline=False)
Stringify differently depending on the number of options so the output always looks like Ruby code should look. Parentheses are always employed here due to grammatical inconsistencies when using braces surrounding a block.
Stringify differently depending on the number of options so the output always looks like Ruby code should look. Parentheses are always employed here due to grammatical inconsistencies when using braces surrounding a block.
[ "Stringify", "differently", "depending", "on", "the", "number", "of", "options", "so", "the", "output", "always", "looks", "like", "Ruby", "code", "should", "look", ".", "Parentheses", "are", "always", "employed", "here", "due", "to", "grammatical", "inconsistencies", "when", "using", "braces", "surrounding", "a", "block", "." ]
def dumps(self, inline=False): """ Stringify differently depending on the number of options so the output always looks like Ruby code should look. Parentheses are always employed here due to grammatical inconsistencies when using braces surrounding a block. """ if 0 == len(self): return u'{0}({1})\n'.format(self.type, self._dumps(self.name)) elif 1 == len(self): key, value = self.items()[0] return u'{0}({1}) {{ {2} {3} }}\n'.format(self.type, self._dumps(self.name), key, self._dumps(value)) else: out = [u'{0}({1}) do\n'.format(self.type, self._dumps(self.name))] for key, value in sorted(self.iteritems()): out.append(u' {0} {1}\n'.format(key, self._dumps(value))) out.append('end\n') return ''.join(out)
[ "def", "dumps", "(", "self", ",", "inline", "=", "False", ")", ":", "if", "0", "==", "len", "(", "self", ")", ":", "return", "u'{0}({1})\\n'", ".", "format", "(", "self", ".", "type", ",", "self", ".", "_dumps", "(", "self", ".", "name", ")", ")", "elif", "1", "==", "len", "(", "self", ")", ":", "key", ",", "value", "=", "self", ".", "items", "(", ")", "[", "0", "]", "return", "u'{0}({1}) {{ {2} {3} }}\\n'", ".", "format", "(", "self", ".", "type", ",", "self", ".", "_dumps", "(", "self", ".", "name", ")", ",", "key", ",", "self", ".", "_dumps", "(", "value", ")", ")", "else", ":", "out", "=", "[", "u'{0}({1}) do\\n'", ".", "format", "(", "self", ".", "type", ",", "self", ".", "_dumps", "(", "self", ".", "name", ")", ")", "]", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "iteritems", "(", ")", ")", ":", "out", ".", "append", "(", "u' {0} {1}\\n'", ".", "format", "(", "key", ",", "self", ".", "_dumps", "(", "value", ")", ")", ")", "out", ".", "append", "(", "'end\\n'", ")", "return", "''", ".", "join", "(", "out", ")" ]
https://github.com/devstructure/blueprint/blob/574a9fc0dd3031c66970387f1105d8c89e61218f/blueprint/frontend/chef.py#L389-L409
BlueBrain/BluePyOpt
6d4185479bc6dddb3daad84fa27e0b8457d69652
bluepyopt/ephys/objectives.py
python
SingletonObjective.calculate_score
(self, responses)
return self.calculate_feature_scores(responses)[0]
Objective score
Objective score
[ "Objective", "score" ]
def calculate_score(self, responses): """Objective score""" return self.calculate_feature_scores(responses)[0]
[ "def", "calculate_score", "(", "self", ",", "responses", ")", ":", "return", "self", ".", "calculate_feature_scores", "(", "responses", ")", "[", "0", "]" ]
https://github.com/BlueBrain/BluePyOpt/blob/6d4185479bc6dddb3daad84fa27e0b8457d69652/bluepyopt/ephys/objectives.py#L74-L77
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/site-geraldo/django/utils/datastructures.py
python
MultiValueDict.copy
(self)
return self.__deepcopy__()
Returns a copy of this object.
Returns a copy of this object.
[ "Returns", "a", "copy", "of", "this", "object", "." ]
def copy(self): """Returns a copy of this object.""" return self.__deepcopy__()
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__deepcopy__", "(", ")" ]
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/site-geraldo/django/utils/datastructures.py#L290-L292
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/data.py
python
Dim.__neg__
(self)
return -1 * self
:rtype: Dim
:rtype: Dim
[ ":", "rtype", ":", "Dim" ]
def __neg__(self): """ :rtype: Dim """ return -1 * self
[ "def", "__neg__", "(", "self", ")", ":", "return", "-", "1", "*", "self" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/data.py#L1116-L1120
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/webchecker/webchecker.py
python
Checker.note
(self, level, format, *args)
[]
def note(self, level, format, *args): if self.verbose > level: if args: format = format%args self.message(format)
[ "def", "note", "(", "self", ",", "level", ",", "format", ",", "*", "args", ")", ":", "if", "self", ".", "verbose", ">", "level", ":", "if", "args", ":", "format", "=", "format", "%", "args", "self", ".", "message", "(", "format", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/webchecker/webchecker.py#L291-L295
vispy/vispy
26256fdc2574259dd227022fbce0767cae4e244b
vispy/visuals/border.py
python
_BorderVisual.border_color
(self)
return self._border_color
The color of the border in pixels
The color of the border in pixels
[ "The", "color", "of", "the", "border", "in", "pixels" ]
def border_color(self): """The color of the border in pixels""" return self._border_color
[ "def", "border_color", "(", "self", ")", ":", "return", "self", ".", "_border_color" ]
https://github.com/vispy/vispy/blob/26256fdc2574259dd227022fbce0767cae4e244b/vispy/visuals/border.py#L181-L183
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/Tkinter.py
python
Wm.wm_iconwindow
(self, pathName=None)
return self.tk.call('wm', 'iconwindow', self._w, pathName)
Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.
Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.
[ "Set", "widget", "PATHNAME", "to", "be", "displayed", "instead", "of", "icon", ".", "Return", "the", "current", "value", "if", "None", "is", "given", "." ]
def wm_iconwindow(self, pathName=None): """Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.""" return self.tk.call('wm', 'iconwindow', self._w, pathName)
[ "def", "wm_iconwindow", "(", "self", ",", "pathName", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'iconwindow'", ",", "self", ".", "_w", ",", "pathName", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/Tkinter.py#L1726-L1729
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/api/models.py
python
ApiUser.username
(self)
[]
def username(self): if self.id.startswith("ApiUser-"): return self.id[len("ApiUser-"):] else: raise Exception("ApiUser _id has to be 'ApiUser-' + username")
[ "def", "username", "(", "self", ")", ":", "if", "self", ".", "id", ".", "startswith", "(", "\"ApiUser-\"", ")", ":", "return", "self", ".", "id", "[", "len", "(", "\"ApiUser-\"", ")", ":", "]", "else", ":", "raise", "Exception", "(", "\"ApiUser _id has to be 'ApiUser-' + username\"", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/api/models.py#L38-L42
iSECPartners/LibTech-Auditing-Cheatsheet
476feb58b5c6067a1aacfaf752c22f5b21179e93
markdown/inlinepatterns.py
python
Pattern.type
(self)
return self.__class__.__name__
Return class name, to define pattern type
Return class name, to define pattern type
[ "Return", "class", "name", "to", "define", "pattern", "type" ]
def type(self): """ Return class name, to define pattern type """ return self.__class__.__name__
[ "def", "type", "(", "self", ")", ":", "return", "self", ".", "__class__", ".", "__name__" ]
https://github.com/iSECPartners/LibTech-Auditing-Cheatsheet/blob/476feb58b5c6067a1aacfaf752c22f5b21179e93/markdown/inlinepatterns.py#L184-L186
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/browser/hints.py
python
HintManager._hint_scattered
(self, min_chars: int, chars: str, elems: _ElemsType)
return self._shuffle_hints(strings, len(chars))
Produce scattered hint labels with variable length (like Vimium). Args: min_chars: The minimum length of labels. chars: The alphabet to use for labels. elems: The elements to generate labels for.
Produce scattered hint labels with variable length (like Vimium).
[ "Produce", "scattered", "hint", "labels", "with", "variable", "length", "(", "like", "Vimium", ")", "." ]
def _hint_scattered(self, min_chars: int, chars: str, elems: _ElemsType) -> _HintStringsType: """Produce scattered hint labels with variable length (like Vimium). Args: min_chars: The minimum length of labels. chars: The alphabet to use for labels. elems: The elements to generate labels for. """ # Determine how many digits the link hints will require in the worst # case. Usually we do not need all of these digits for every link # single hint, so we can show shorter hints for a few of the links. needed = max(min_chars, utils.ceil_log(len(elems), len(chars))) # Short hints are the number of hints we can possibly show which are # (needed - 1) digits in length. if needed > min_chars and needed > 1: total_space = len(chars) ** needed # For each 1 short link being added, len(chars) long links are # removed, therefore the space removed is len(chars) - 1. short_count = (total_space - len(elems)) // (len(chars) - 1) else: short_count = 0 long_count = len(elems) - short_count strings = [] if needed > 1: for i in range(short_count): strings.append(self._number_to_hint_str(i, chars, needed - 1)) start = short_count * len(chars) for i in range(start, start + long_count): strings.append(self._number_to_hint_str(i, chars, needed)) return self._shuffle_hints(strings, len(chars))
[ "def", "_hint_scattered", "(", "self", ",", "min_chars", ":", "int", ",", "chars", ":", "str", ",", "elems", ":", "_ElemsType", ")", "->", "_HintStringsType", ":", "# Determine how many digits the link hints will require in the worst", "# case. Usually we do not need all of these digits for every link", "# single hint, so we can show shorter hints for a few of the links.", "needed", "=", "max", "(", "min_chars", ",", "utils", ".", "ceil_log", "(", "len", "(", "elems", ")", ",", "len", "(", "chars", ")", ")", ")", "# Short hints are the number of hints we can possibly show which are", "# (needed - 1) digits in length.", "if", "needed", ">", "min_chars", "and", "needed", ">", "1", ":", "total_space", "=", "len", "(", "chars", ")", "**", "needed", "# For each 1 short link being added, len(chars) long links are", "# removed, therefore the space removed is len(chars) - 1.", "short_count", "=", "(", "total_space", "-", "len", "(", "elems", ")", ")", "//", "(", "len", "(", "chars", ")", "-", "1", ")", "else", ":", "short_count", "=", "0", "long_count", "=", "len", "(", "elems", ")", "-", "short_count", "strings", "=", "[", "]", "if", "needed", ">", "1", ":", "for", "i", "in", "range", "(", "short_count", ")", ":", "strings", ".", "append", "(", "self", ".", "_number_to_hint_str", "(", "i", ",", "chars", ",", "needed", "-", "1", ")", ")", "start", "=", "short_count", "*", "len", "(", "chars", ")", "for", "i", "in", "range", "(", "start", ",", "start", "+", "long_count", ")", ":", "strings", ".", "append", "(", "self", ".", "_number_to_hint_str", "(", "i", ",", "chars", ",", "needed", ")", ")", "return", "self", ".", "_shuffle_hints", "(", "strings", ",", "len", "(", "chars", ")", ")" ]
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/browser/hints.py#L470-L507
adobe/brackets-shell
c180d7ea812759ba50d25ab0685434c345343008
gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetArch
(self, config)
return {'Win32': 'x86', 'x64': 'x64'}.get(platform, 'x86')
Get architecture based on msvs_configuration_platform and msvs_target_platform. Returns either 'x86' or 'x64'.
Get architecture based on msvs_configuration_platform and msvs_target_platform. Returns either 'x86' or 'x64'.
[ "Get", "architecture", "based", "on", "msvs_configuration_platform", "and", "msvs_target_platform", ".", "Returns", "either", "x86", "or", "x64", "." ]
def GetArch(self, config): """Get architecture based on msvs_configuration_platform and msvs_target_platform. Returns either 'x86' or 'x64'.""" configuration_platform = self.msvs_configuration_platform.get(config, '') platform = self.msvs_target_platform.get(config, '') if not platform: # If no specific override, use the configuration's. platform = configuration_platform # Map from platform to architecture. return {'Win32': 'x86', 'x64': 'x64'}.get(platform, 'x86')
[ "def", "GetArch", "(", "self", ",", "config", ")", ":", "configuration_platform", "=", "self", ".", "msvs_configuration_platform", ".", "get", "(", "config", ",", "''", ")", "platform", "=", "self", ".", "msvs_target_platform", ".", "get", "(", "config", ",", "''", ")", "if", "not", "platform", ":", "# If no specific override, use the configuration's.", "platform", "=", "configuration_platform", "# Map from platform to architecture.", "return", "{", "'Win32'", ":", "'x86'", ",", "'x64'", ":", "'x64'", "}", ".", "get", "(", "platform", ",", "'x86'", ")" ]
https://github.com/adobe/brackets-shell/blob/c180d7ea812759ba50d25ab0685434c345343008/gyp/pylib/gyp/msvs_emulation.py#L294-L302
PINTO0309/PINTO_model_zoo
2924acda7a7d541d8712efd7cc4fd1c61ef5bddd
023_yolov3-nano/core/common.py
python
upsample
(input_data, name, method="deconv")
return output
[]
def upsample(input_data, name, method="deconv"): assert method in ["resize", "deconv"] if method == "resize": with tf.variable_scope(name): input_shape = tf.shape(input_data) output = tf.image.resize_nearest_neighbor(input_data, (input_shape[1] * 2, input_shape[2] * 2)) if method == "deconv": # replace resize_nearest_neighbor with conv2d_transpose To support TensorRT optimization numm_filter = input_data.shape.as_list()[-1] output = tf.layers.conv2d_transpose(input_data, numm_filter, kernel_size=2, padding='same', strides=(2,2), kernel_initializer=tf.random_normal_initializer()) return output
[ "def", "upsample", "(", "input_data", ",", "name", ",", "method", "=", "\"deconv\"", ")", ":", "assert", "method", "in", "[", "\"resize\"", ",", "\"deconv\"", "]", "if", "method", "==", "\"resize\"", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "input_shape", "=", "tf", ".", "shape", "(", "input_data", ")", "output", "=", "tf", ".", "image", ".", "resize_nearest_neighbor", "(", "input_data", ",", "(", "input_shape", "[", "1", "]", "*", "2", ",", "input_shape", "[", "2", "]", "*", "2", ")", ")", "if", "method", "==", "\"deconv\"", ":", "# replace resize_nearest_neighbor with conv2d_transpose To support TensorRT optimization", "numm_filter", "=", "input_data", ".", "shape", ".", "as_list", "(", ")", "[", "-", "1", "]", "output", "=", "tf", ".", "layers", ".", "conv2d_transpose", "(", "input_data", ",", "numm_filter", ",", "kernel_size", "=", "2", ",", "padding", "=", "'same'", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "kernel_initializer", "=", "tf", ".", "random_normal_initializer", "(", ")", ")", "return", "output" ]
https://github.com/PINTO0309/PINTO_model_zoo/blob/2924acda7a7d541d8712efd7cc4fd1c61ef5bddd/023_yolov3-nano/core/common.py#L74-L88
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
geraldo/generators/base.py
python
ReportGenerator.set_stroke_color
(self, color)
Sets the current stroke on canvas
Sets the current stroke on canvas
[ "Sets", "the", "current", "stroke", "on", "canvas" ]
def set_stroke_color(self, color): """Sets the current stroke on canvas""" pass
[ "def", "set_stroke_color", "(", "self", ",", "color", ")", ":", "pass" ]
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/geraldo/generators/base.py#L711-L713
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/distlib/_backport/tarfile.py
python
TarFile.add
(self, name, arcname=None, recursive=True, exclude=None, filter=None)
Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that should return True for each filename to be excluded. `filter' is a function that expects a TarInfo object argument and returns the changed TarInfo object, if it returns None the TarInfo object will be excluded from the archive.
Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that should return True for each filename to be excluded. `filter' is a function that expects a TarInfo object argument and returns the changed TarInfo object, if it returns None the TarInfo object will be excluded from the archive.
[ "Add", "the", "file", "name", "to", "the", "archive", ".", "name", "may", "be", "any", "type", "of", "file", "(", "directory", "fifo", "symbolic", "link", "etc", ".", ")", ".", "If", "given", "arcname", "specifies", "an", "alternative", "name", "for", "the", "file", "in", "the", "archive", ".", "Directories", "are", "added", "recursively", "by", "default", ".", "This", "can", "be", "avoided", "by", "setting", "recursive", "to", "False", ".", "exclude", "is", "a", "function", "that", "should", "return", "True", "for", "each", "filename", "to", "be", "excluded", ".", "filter", "is", "a", "function", "that", "expects", "a", "TarInfo", "object", "argument", "and", "returns", "the", "changed", "TarInfo", "object", "if", "it", "returns", "None", "the", "TarInfo", "object", "will", "be", "excluded", "from", "the", "archive", "." ]
def add(self, name, arcname=None, recursive=True, exclude=None, filter=None): """Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that should return True for each filename to be excluded. `filter' is a function that expects a TarInfo object argument and returns the changed TarInfo object, if it returns None the TarInfo object will be excluded from the archive. """ self._check("aw") if arcname is None: arcname = name # Exclude pathnames. if exclude is not None: import warnings warnings.warn("use the filter argument instead", DeprecationWarning, 2) if exclude(name): self._dbg(2, "tarfile: Excluded %r" % name) return # Skip if somebody tries to archive the archive... if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return self._dbg(1, name) # Create a TarInfo object from the file. tarinfo = self.gettarinfo(name, arcname) if tarinfo is None: self._dbg(1, "tarfile: Unsupported type %r" % name) return # Change or exclude the TarInfo object. if filter is not None: tarinfo = filter(tarinfo) if tarinfo is None: self._dbg(2, "tarfile: Excluded %r" % name) return # Append the tar header and data to the archive. if tarinfo.isreg(): f = bltn_open(name, "rb") self.addfile(tarinfo, f) f.close() elif tarinfo.isdir(): self.addfile(tarinfo) if recursive: for f in os.listdir(name): self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude, filter=filter) else: self.addfile(tarinfo)
[ "def", "add", "(", "self", ",", "name", ",", "arcname", "=", "None", ",", "recursive", "=", "True", ",", "exclude", "=", "None", ",", "filter", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "if", "arcname", "is", "None", ":", "arcname", "=", "name", "# Exclude pathnames.", "if", "exclude", "is", "not", "None", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"use the filter argument instead\"", ",", "DeprecationWarning", ",", "2", ")", "if", "exclude", "(", "name", ")", ":", "self", ".", "_dbg", "(", "2", ",", "\"tarfile: Excluded %r\"", "%", "name", ")", "return", "# Skip if somebody tries to archive the archive...", "if", "self", ".", "name", "is", "not", "None", "and", "os", ".", "path", ".", "abspath", "(", "name", ")", "==", "self", ".", "name", ":", "self", ".", "_dbg", "(", "2", ",", "\"tarfile: Skipped %r\"", "%", "name", ")", "return", "self", ".", "_dbg", "(", "1", ",", "name", ")", "# Create a TarInfo object from the file.", "tarinfo", "=", "self", ".", "gettarinfo", "(", "name", ",", "arcname", ")", "if", "tarinfo", "is", "None", ":", "self", ".", "_dbg", "(", "1", ",", "\"tarfile: Unsupported type %r\"", "%", "name", ")", "return", "# Change or exclude the TarInfo object.", "if", "filter", "is", "not", "None", ":", "tarinfo", "=", "filter", "(", "tarinfo", ")", "if", "tarinfo", "is", "None", ":", "self", ".", "_dbg", "(", "2", ",", "\"tarfile: Excluded %r\"", "%", "name", ")", "return", "# Append the tar header and data to the archive.", "if", "tarinfo", ".", "isreg", "(", ")", ":", "f", "=", "bltn_open", "(", "name", ",", "\"rb\"", ")", "self", ".", "addfile", "(", "tarinfo", ",", "f", ")", "f", ".", "close", "(", ")", "elif", "tarinfo", ".", "isdir", "(", ")", ":", "self", ".", "addfile", "(", "tarinfo", ")", "if", "recursive", ":", "for", "f", "in", "os", ".", "listdir", "(", "name", ")", ":", "self", ".", "add", "(", "os", ".", "path", ".", "join", "(", "name", ",", "f", ")", ",", "os", ".", "path", ".", "join", "(", "arcname", ",", "f", ")", ",", "recursive", ",", "exclude", ",", "filter", "=", "filter", ")", "else", ":", "self", ".", "addfile", "(", "tarinfo", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/distlib/_backport/tarfile.py#L2038-L2098
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
Processor.process_get_current_notificationEventId
(self, seqid, iprot, oprot)
[]
def process_get_current_notificationEventId(self, seqid, iprot, oprot): args = get_current_notificationEventId_args() args.read(iprot) iprot.readMessageEnd() result = get_current_notificationEventId_result() try: result.success = self._handler.get_current_notificationEventId() msg_type = TMessageType.REPLY except TTransport.TTransportException: raise except TApplicationException as ex: logging.exception('TApplication exception in handler') msg_type = TMessageType.EXCEPTION result = ex except Exception: logging.exception('Unexpected exception in handler') msg_type = TMessageType.EXCEPTION result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error') oprot.writeMessageBegin("get_current_notificationEventId", msg_type, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()
[ "def", "process_get_current_notificationEventId", "(", "self", ",", "seqid", ",", "iprot", ",", "oprot", ")", ":", "args", "=", "get_current_notificationEventId_args", "(", ")", "args", ".", "read", "(", "iprot", ")", "iprot", ".", "readMessageEnd", "(", ")", "result", "=", "get_current_notificationEventId_result", "(", ")", "try", ":", "result", ".", "success", "=", "self", ".", "_handler", ".", "get_current_notificationEventId", "(", ")", "msg_type", "=", "TMessageType", ".", "REPLY", "except", "TTransport", ".", "TTransportException", ":", "raise", "except", "TApplicationException", "as", "ex", ":", "logging", ".", "exception", "(", "'TApplication exception in handler'", ")", "msg_type", "=", "TMessageType", ".", "EXCEPTION", "result", "=", "ex", "except", "Exception", ":", "logging", ".", "exception", "(", "'Unexpected exception in handler'", ")", "msg_type", "=", "TMessageType", ".", "EXCEPTION", "result", "=", "TApplicationException", "(", "TApplicationException", ".", "INTERNAL_ERROR", ",", "'Internal error'", ")", "oprot", ".", "writeMessageBegin", "(", "\"get_current_notificationEventId\"", ",", "msg_type", ",", "seqid", ")", "result", ".", "write", "(", "oprot", ")", "oprot", ".", "writeMessageEnd", "(", ")", "oprot", ".", "trans", ".", "flush", "(", ")" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L10904-L10925
simonmeister/pysc2-rl-agents
368a2227ee62148302bedc0065c023b332a51d8c
rl/util.py
python
safe_div
(numerator, denominator, name="value")
return tf.where( tf.greater(denominator, 0), tf.div(numerator, tf.where( tf.equal(denominator, 0), tf.ones_like(denominator), denominator)), tf.zeros_like(numerator), name=name)
Computes a safe divide which returns 0 if the denominator is zero. Note that the function contains an additional conditional check that is necessary for avoiding situations where the loss is zero causing NaNs to creep into the gradient computation. Args: numerator: An arbitrary `Tensor`. denominator: `Tensor` whose shape matches `numerator` and whose values are assumed to be non-negative. name: An optional name for the returned op. Returns: The element-wise value of the numerator divided by the denominator.
Computes a safe divide which returns 0 if the denominator is zero. Note that the function contains an additional conditional check that is necessary for avoiding situations where the loss is zero causing NaNs to creep into the gradient computation. Args: numerator: An arbitrary `Tensor`. denominator: `Tensor` whose shape matches `numerator` and whose values are assumed to be non-negative. name: An optional name for the returned op. Returns: The element-wise value of the numerator divided by the denominator.
[ "Computes", "a", "safe", "divide", "which", "returns", "0", "if", "the", "denominator", "is", "zero", ".", "Note", "that", "the", "function", "contains", "an", "additional", "conditional", "check", "that", "is", "necessary", "for", "avoiding", "situations", "where", "the", "loss", "is", "zero", "causing", "NaNs", "to", "creep", "into", "the", "gradient", "computation", ".", "Args", ":", "numerator", ":", "An", "arbitrary", "Tensor", ".", "denominator", ":", "Tensor", "whose", "shape", "matches", "numerator", "and", "whose", "values", "are", "assumed", "to", "be", "non", "-", "negative", ".", "name", ":", "An", "optional", "name", "for", "the", "returned", "op", ".", "Returns", ":", "The", "element", "-", "wise", "value", "of", "the", "numerator", "divided", "by", "the", "denominator", "." ]
def safe_div(numerator, denominator, name="value"): """Computes a safe divide which returns 0 if the denominator is zero. Note that the function contains an additional conditional check that is necessary for avoiding situations where the loss is zero causing NaNs to creep into the gradient computation. Args: numerator: An arbitrary `Tensor`. denominator: `Tensor` whose shape matches `numerator` and whose values are assumed to be non-negative. name: An optional name for the returned op. Returns: The element-wise value of the numerator divided by the denominator. """ return tf.where( tf.greater(denominator, 0), tf.div(numerator, tf.where( tf.equal(denominator, 0), tf.ones_like(denominator), denominator)), tf.zeros_like(numerator), name=name)
[ "def", "safe_div", "(", "numerator", ",", "denominator", ",", "name", "=", "\"value\"", ")", ":", "return", "tf", ".", "where", "(", "tf", ".", "greater", "(", "denominator", ",", "0", ")", ",", "tf", ".", "div", "(", "numerator", ",", "tf", ".", "where", "(", "tf", ".", "equal", "(", "denominator", ",", "0", ")", ",", "tf", ".", "ones_like", "(", "denominator", ")", ",", "denominator", ")", ")", ",", "tf", ".", "zeros_like", "(", "numerator", ")", ",", "name", "=", "name", ")" ]
https://github.com/simonmeister/pysc2-rl-agents/blob/368a2227ee62148302bedc0065c023b332a51d8c/rl/util.py#L4-L23
wakatime/legacy-python-cli
9b64548b16ab5ef16603d9a6c2620a16d0df8d46
wakatime/packages/urllib3/util/wait.py
python
wait_for_read
(socks, timeout=None)
return _wait_for_io_events(socks, EVENT_READ, timeout)
Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be read from immediately.
Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be read from immediately.
[ "Waits", "for", "reading", "to", "be", "available", "from", "a", "list", "of", "sockets", "or", "optionally", "a", "single", "socket", "if", "passed", "in", ".", "Returns", "a", "list", "of", "sockets", "that", "can", "be", "read", "from", "immediately", "." ]
def wait_for_read(socks, timeout=None): """ Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be read from immediately. """ return _wait_for_io_events(socks, EVENT_READ, timeout)
[ "def", "wait_for_read", "(", "socks", ",", "timeout", "=", "None", ")", ":", "return", "_wait_for_io_events", "(", "socks", ",", "EVENT_READ", ",", "timeout", ")" ]
https://github.com/wakatime/legacy-python-cli/blob/9b64548b16ab5ef16603d9a6c2620a16d0df8d46/wakatime/packages/urllib3/util/wait.py#L29-L33
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/train_pipeline.py
python
run_training
()
Train the model.
Train the model.
[ "Train", "the", "model", "." ]
def run_training() -> None: """Train the model.""" # read training data data = load_dataset(file_name=config.app_config.training_data_file) # divide train and test X_train, X_test, y_train, y_test = train_test_split( data[config.model_config.features], # predictors data[config.model_config.target], test_size=config.model_config.test_size, # we are setting the random seed here # for reproducibility random_state=config.model_config.random_state, ) y_train = np.log(y_train) # fit model price_pipe.fit(X_train, y_train) # persist trained model save_pipeline(pipeline_to_persist=price_pipe)
[ "def", "run_training", "(", ")", "->", "None", ":", "# read training data", "data", "=", "load_dataset", "(", "file_name", "=", "config", ".", "app_config", ".", "training_data_file", ")", "# divide train and test", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "data", "[", "config", ".", "model_config", ".", "features", "]", ",", "# predictors", "data", "[", "config", ".", "model_config", ".", "target", "]", ",", "test_size", "=", "config", ".", "model_config", ".", "test_size", ",", "# we are setting the random seed here", "# for reproducibility", "random_state", "=", "config", ".", "model_config", ".", "random_state", ",", ")", "y_train", "=", "np", ".", "log", "(", "y_train", ")", "# fit model", "price_pipe", ".", "fit", "(", "X_train", ",", "y_train", ")", "# persist trained model", "save_pipeline", "(", "pipeline_to_persist", "=", "price_pipe", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/train_pipeline.py#L8-L29
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/pyparsing.py
python
dictOf
( key, value )
return Dict( ZeroOrMore( Group ( key + value ) ) )
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields.
[ "Helper", "to", "easily", "and", "clearly", "define", "a", "dictionary", "by", "specifying", "the", "respective", "patterns", "for", "the", "key", "and", "value", ".", "Takes", "care", "of", "defining", "the", "C", "{", "L", "{", "Dict", "}}", "C", "{", "L", "{", "ZeroOrMore", "}}", "and", "C", "{", "L", "{", "Group", "}}", "tokens", "in", "the", "proper", "order", ".", "The", "key", "pattern", "can", "include", "delimiting", "markers", "or", "punctuation", "as", "long", "as", "they", "are", "suppressed", "thereby", "leaving", "the", "significant", "key", "text", ".", "The", "value", "pattern", "can", "include", "named", "results", "so", "that", "the", "C", "{", "Dict", "}", "results", "can", "include", "named", "token", "fields", "." ]
def dictOf( key, value ): """ Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} """ return Dict( ZeroOrMore( Group ( key + value ) ) )
[ "def", "dictOf", "(", "key", ",", "value", ")", ":", "return", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "key", "+", "value", ")", ")", ")" ]
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/pyparsing.py#L4624-L4657
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/urllib3/connectionpool.py
python
HTTPConnectionPool._raise_timeout
(self, err, url, timeout_value)
Is the error actually a timeout? Will raise a ReadTimeout or pass
Is the error actually a timeout? Will raise a ReadTimeout or pass
[ "Is", "the", "error", "actually", "a", "timeout?", "Will", "raise", "a", "ReadTimeout", "or", "pass" ]
def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, "errno") and err.errno in _blocking_errnos: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if "timed out" in str(err) or "did not complete (read)" in str( err ): # Python < 2.7.4 raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value )
[ "def", "_raise_timeout", "(", "self", ",", "err", ",", "url", ",", "timeout_value", ")", ":", "if", "isinstance", "(", "err", ",", "SocketTimeout", ")", ":", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")", "# See the above comment about EAGAIN in Python 3. In Python 2 we have", "# to specifically catch it and throw the timeout error", "if", "hasattr", "(", "err", ",", "\"errno\"", ")", "and", "err", ".", "errno", "in", "_blocking_errnos", ":", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")", "# Catch possible read timeouts thrown as SSL errors. If not the", "# case, rethrow the original. We need to do this because of:", "# http://bugs.python.org/issue10272", "if", "\"timed out\"", "in", "str", "(", "err", ")", "or", "\"did not complete (read)\"", "in", "str", "(", "err", ")", ":", "# Python < 2.7.4", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/urllib3/connectionpool.py#L332-L355
MTCloudVision/mxnet-dssd
6943428cd6e1c825fd63763317d8ec61b66f9430
tools/rand_sampler.py
python
RandCropper._check_satisfy
(self, rand_box, gt_boxes)
return ious
check if overlap with any gt box is larger than threshold
check if overlap with any gt box is larger than threshold
[ "check", "if", "overlap", "with", "any", "gt", "box", "is", "larger", "than", "threshold" ]
def _check_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """ l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt) * t rs = np.ones(num_gt) * r bs = np.ones(num_gt) * b mask = np.where(ls < gt_boxes[:, 1])[0] ls[mask] = gt_boxes[mask, 1] mask = np.where(ts < gt_boxes[:, 2])[0] ts[mask] = gt_boxes[mask, 2] mask = np.where(rs > gt_boxes[:, 3])[0] rs[mask] = gt_boxes[mask, 3] mask = np.where(bs > gt_boxes[:, 4])[0] bs[mask] = gt_boxes[mask, 4] w = rs - ls w[w < 0] = 0 h = bs - ts h[h < 0] = 0 inter_area = h * w union_area = np.ones(num_gt) * max(0, r - l) * max(0, b - t) union_area += (gt_boxes[:, 3] - gt_boxes[:, 1]) * (gt_boxes[:, 4] - gt_boxes[:, 2]) union_area -= inter_area ious = inter_area / union_area ious[union_area <= 0] = 0 max_iou = np.amax(ious) if max_iou < self.min_overlap: return None # check ground-truth constraint if self.config['gt_constraint'] == 'center': for i in range(ious.shape[0]): if ious[i] > 0: gt_x = (gt_boxes[i, 1] + gt_boxes[i, 3]) / 2.0 gt_y = (gt_boxes[i, 2] + gt_boxes[i, 4]) / 2.0 if gt_x < l or gt_x > r or gt_y < t or gt_y > b: return None elif self.config['gt_constraint'] == 'corner': for i in range(ious.shape[0]): if ious[i] > 0: if gt_boxes[i, 1] < l or gt_boxes[i, 3] > r \ or gt_boxes[i, 2] < t or gt_boxes[i, 4] > b: return None return ious
[ "def", "_check_satisfy", "(", "self", ",", "rand_box", ",", "gt_boxes", ")", ":", "l", ",", "t", ",", "r", ",", "b", "=", "rand_box", "num_gt", "=", "gt_boxes", ".", "shape", "[", "0", "]", "ls", "=", "np", ".", "ones", "(", "num_gt", ")", "*", "l", "ts", "=", "np", ".", "ones", "(", "num_gt", ")", "*", "t", "rs", "=", "np", ".", "ones", "(", "num_gt", ")", "*", "r", "bs", "=", "np", ".", "ones", "(", "num_gt", ")", "*", "b", "mask", "=", "np", ".", "where", "(", "ls", "<", "gt_boxes", "[", ":", ",", "1", "]", ")", "[", "0", "]", "ls", "[", "mask", "]", "=", "gt_boxes", "[", "mask", ",", "1", "]", "mask", "=", "np", ".", "where", "(", "ts", "<", "gt_boxes", "[", ":", ",", "2", "]", ")", "[", "0", "]", "ts", "[", "mask", "]", "=", "gt_boxes", "[", "mask", ",", "2", "]", "mask", "=", "np", ".", "where", "(", "rs", ">", "gt_boxes", "[", ":", ",", "3", "]", ")", "[", "0", "]", "rs", "[", "mask", "]", "=", "gt_boxes", "[", "mask", ",", "3", "]", "mask", "=", "np", ".", "where", "(", "bs", ">", "gt_boxes", "[", ":", ",", "4", "]", ")", "[", "0", "]", "bs", "[", "mask", "]", "=", "gt_boxes", "[", "mask", ",", "4", "]", "w", "=", "rs", "-", "ls", "w", "[", "w", "<", "0", "]", "=", "0", "h", "=", "bs", "-", "ts", "h", "[", "h", "<", "0", "]", "=", "0", "inter_area", "=", "h", "*", "w", "union_area", "=", "np", ".", "ones", "(", "num_gt", ")", "*", "max", "(", "0", ",", "r", "-", "l", ")", "*", "max", "(", "0", ",", "b", "-", "t", ")", "union_area", "+=", "(", "gt_boxes", "[", ":", ",", "3", "]", "-", "gt_boxes", "[", ":", ",", "1", "]", ")", "*", "(", "gt_boxes", "[", ":", ",", "4", "]", "-", "gt_boxes", "[", ":", ",", "2", "]", ")", "union_area", "-=", "inter_area", "ious", "=", "inter_area", "/", "union_area", "ious", "[", "union_area", "<=", "0", "]", "=", "0", "max_iou", "=", "np", ".", "amax", "(", "ious", ")", "if", "max_iou", "<", "self", ".", "min_overlap", ":", "return", "None", "# check ground-truth constraint", "if", "self", ".", "config", "[", "'gt_constraint'", "]", "==", "'center'", ":", "for", "i", "in", "range", "(", "ious", ".", "shape", "[", "0", "]", ")", ":", "if", "ious", "[", "i", "]", ">", "0", ":", "gt_x", "=", "(", "gt_boxes", "[", "i", ",", "1", "]", "+", "gt_boxes", "[", "i", ",", "3", "]", ")", "/", "2.0", "gt_y", "=", "(", "gt_boxes", "[", "i", ",", "2", "]", "+", "gt_boxes", "[", "i", ",", "4", "]", ")", "/", "2.0", "if", "gt_x", "<", "l", "or", "gt_x", ">", "r", "or", "gt_y", "<", "t", "or", "gt_y", ">", "b", ":", "return", "None", "elif", "self", ".", "config", "[", "'gt_constraint'", "]", "==", "'corner'", ":", "for", "i", "in", "range", "(", "ious", ".", "shape", "[", "0", "]", ")", ":", "if", "ious", "[", "i", "]", ">", "0", ":", "if", "gt_boxes", "[", "i", ",", "1", "]", "<", "l", "or", "gt_boxes", "[", "i", ",", "3", "]", ">", "r", "or", "gt_boxes", "[", "i", ",", "2", "]", "<", "t", "or", "gt_boxes", "[", "i", ",", "4", "]", ">", "b", ":", "return", "None", "return", "ious" ]
https://github.com/MTCloudVision/mxnet-dssd/blob/6943428cd6e1c825fd63763317d8ec61b66f9430/tools/rand_sampler.py#L130-L175
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/urls.py
python
BaseURL.raw_password
(self)
return self._split_auth()[1]
The password if it was part of the URL, `None` otherwise. Unlike :attr:`password` this one is not being decoded.
The password if it was part of the URL, `None` otherwise. Unlike :attr:`password` this one is not being decoded.
[ "The", "password", "if", "it", "was", "part", "of", "the", "URL", "None", "otherwise", ".", "Unlike", ":", "attr", ":", "password", "this", "one", "is", "not", "being", "decoded", "." ]
def raw_password(self): """The password if it was part of the URL, `None` otherwise. Unlike :attr:`password` this one is not being decoded. """ return self._split_auth()[1]
[ "def", "raw_password", "(", "self", ")", ":", "return", "self", ".", "_split_auth", "(", ")", "[", "1", "]" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/urls.py#L125-L129
rdnetto/YCM-Generator
7c0f5701130f4178cb63d10da88578b9b705fbb1
config_gen.py
python
generate_cc_conf
(flags, config_file)
Generates the .color_coded file flags: the list of flags config_file: the path to save the configuration file at
Generates the .color_coded file
[ "Generates", "the", ".", "color_coded", "file" ]
def generate_cc_conf(flags, config_file): '''Generates the .color_coded file flags: the list of flags config_file: the path to save the configuration file at''' with open(config_file, "w") as output: for flag in flags: if(isinstance(flag, basestring)): output.write(flag + "\n") else: # is tuple for f in flag: output.write(f + "\n")
[ "def", "generate_cc_conf", "(", "flags", ",", "config_file", ")", ":", "with", "open", "(", "config_file", ",", "\"w\"", ")", "as", "output", ":", "for", "flag", "in", "flags", ":", "if", "(", "isinstance", "(", "flag", ",", "basestring", ")", ")", ":", "output", ".", "write", "(", "flag", "+", "\"\\n\"", ")", "else", ":", "# is tuple", "for", "f", "in", "flag", ":", "output", ".", "write", "(", "f", "+", "\"\\n\"", ")" ]
https://github.com/rdnetto/YCM-Generator/blob/7c0f5701130f4178cb63d10da88578b9b705fbb1/config_gen.py#L423-L435
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/util/wine/dxvk_nvapi.py
python
DXVKNVAPIManager.disable
(self)
Disable DLLs for the current prefix
Disable DLLs for the current prefix
[ "Disable", "DLLs", "for", "the", "current", "prefix" ]
def disable(self): """Disable DLLs for the current prefix""" super().disable() windows_path = os.path.join(self.prefix, "drive_c/windows") system_dir = os.path.join(windows_path, "system32") for dll in self.dlss_dlls: self.disable_dll(system_dir, "x64", dll)
[ "def", "disable", "(", "self", ")", ":", "super", "(", ")", ".", "disable", "(", ")", "windows_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "prefix", ",", "\"drive_c/windows\"", ")", "system_dir", "=", "os", ".", "path", ".", "join", "(", "windows_path", ",", "\"system32\"", ")", "for", "dll", "in", "self", ".", "dlss_dlls", ":", "self", ".", "disable_dll", "(", "system_dir", ",", "\"x64\"", ",", "dll", ")" ]
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/util/wine/dxvk_nvapi.py#L36-L42
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py
python
_AssociationList.__delslice__
(self, start, end)
[]
def __delslice__(self, start, end): del self.col[start:end]
[ "def", "__delslice__", "(", "self", ",", "start", ",", "end", ")", ":", "del", "self", ".", "col", "[", "start", ":", "end", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py#L664-L665
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/factortools.py
python
dup_zz_diophantine
(F, m, p, K)
return result
Wang/EEZ: Solve univariate Diophantine equations.
Wang/EEZ: Solve univariate Diophantine equations.
[ "Wang", "/", "EEZ", ":", "Solve", "univariate", "Diophantine", "equations", "." ]
def dup_zz_diophantine(F, m, p, K): """Wang/EEZ: Solve univariate Diophantine equations. """ if len(F) == 2: a, b = F f = gf_from_int_poly(a, p) g = gf_from_int_poly(b, p) s, t, G = gf_gcdex(g, f, p, K) s = gf_lshift(s, m, K) t = gf_lshift(t, m, K) q, s = gf_div(s, f, p, K) t = gf_add_mul(t, q, g, p, K) s = gf_to_int_poly(s, p) t = gf_to_int_poly(t, p) result = [s, t] else: G = [F[-1]] for f in reversed(F[1:-1]): G.insert(0, dup_mul(f, G[0], K)) S, T = [], [[1]] for f, g in zip(F, G): t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K) T.append(t) S.append(s) result, S = [], S + [T[-1]] for s, f in zip(S, F): s = gf_from_int_poly(s, p) f = gf_from_int_poly(f, p) r = gf_rem(gf_lshift(s, m, K), f, p, K) s = gf_to_int_poly(r, p) result.append(s) return result
[ "def", "dup_zz_diophantine", "(", "F", ",", "m", ",", "p", ",", "K", ")", ":", "if", "len", "(", "F", ")", "==", "2", ":", "a", ",", "b", "=", "F", "f", "=", "gf_from_int_poly", "(", "a", ",", "p", ")", "g", "=", "gf_from_int_poly", "(", "b", ",", "p", ")", "s", ",", "t", ",", "G", "=", "gf_gcdex", "(", "g", ",", "f", ",", "p", ",", "K", ")", "s", "=", "gf_lshift", "(", "s", ",", "m", ",", "K", ")", "t", "=", "gf_lshift", "(", "t", ",", "m", ",", "K", ")", "q", ",", "s", "=", "gf_div", "(", "s", ",", "f", ",", "p", ",", "K", ")", "t", "=", "gf_add_mul", "(", "t", ",", "q", ",", "g", ",", "p", ",", "K", ")", "s", "=", "gf_to_int_poly", "(", "s", ",", "p", ")", "t", "=", "gf_to_int_poly", "(", "t", ",", "p", ")", "result", "=", "[", "s", ",", "t", "]", "else", ":", "G", "=", "[", "F", "[", "-", "1", "]", "]", "for", "f", "in", "reversed", "(", "F", "[", "1", ":", "-", "1", "]", ")", ":", "G", ".", "insert", "(", "0", ",", "dup_mul", "(", "f", ",", "G", "[", "0", "]", ",", "K", ")", ")", "S", ",", "T", "=", "[", "]", ",", "[", "[", "1", "]", "]", "for", "f", ",", "g", "in", "zip", "(", "F", ",", "G", ")", ":", "t", ",", "s", "=", "dmp_zz_diophantine", "(", "[", "g", ",", "f", "]", ",", "T", "[", "-", "1", "]", ",", "[", "]", ",", "0", ",", "p", ",", "1", ",", "K", ")", "T", ".", "append", "(", "t", ")", "S", ".", "append", "(", "s", ")", "result", ",", "S", "=", "[", "]", ",", "S", "+", "[", "T", "[", "-", "1", "]", "]", "for", "s", ",", "f", "in", "zip", "(", "S", ",", "F", ")", ":", "s", "=", "gf_from_int_poly", "(", "s", ",", "p", ")", "f", "=", "gf_from_int_poly", "(", "f", ",", "p", ")", "r", "=", "gf_rem", "(", "gf_lshift", "(", "s", ",", "m", ",", "K", ")", ",", "f", ",", "p", ",", "K", ")", "s", "=", "gf_to_int_poly", "(", "r", ",", "p", ")", "result", ".", "append", "(", "s", ")", "return", "result" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/factortools.py#L726-L771
pypa/cibuildwheel
5255155bc57eb6224354356df648dc42e31a0028
cibuildwheel/util.py
python
_parse_constraints_for_virtualenv
( dependency_constraint_flags: Sequence[PathOrStr], )
return constraints_dict
Parses the constraints file referenced by `dependency_constraint_flags` and returns a dict where the key is the package name, and the value is the constraint version. If a package version cannot be found, its value is "embed" meaning that virtualenv will install its bundled version, already available locally. The function does not try to be too smart and just handles basic constraints. If it can't get an exact version, the real constraint will be handled by the {macos|windows}.setup_python function.
Parses the constraints file referenced by `dependency_constraint_flags` and returns a dict where the key is the package name, and the value is the constraint version. If a package version cannot be found, its value is "embed" meaning that virtualenv will install its bundled version, already available locally. The function does not try to be too smart and just handles basic constraints. If it can't get an exact version, the real constraint will be handled by the {macos|windows}.setup_python function.
[ "Parses", "the", "constraints", "file", "referenced", "by", "dependency_constraint_flags", "and", "returns", "a", "dict", "where", "the", "key", "is", "the", "package", "name", "and", "the", "value", "is", "the", "constraint", "version", ".", "If", "a", "package", "version", "cannot", "be", "found", "its", "value", "is", "embed", "meaning", "that", "virtualenv", "will", "install", "its", "bundled", "version", "already", "available", "locally", ".", "The", "function", "does", "not", "try", "to", "be", "too", "smart", "and", "just", "handles", "basic", "constraints", ".", "If", "it", "can", "t", "get", "an", "exact", "version", "the", "real", "constraint", "will", "be", "handled", "by", "the", "{", "macos|windows", "}", ".", "setup_python", "function", "." ]
def _parse_constraints_for_virtualenv( dependency_constraint_flags: Sequence[PathOrStr], ) -> Dict[str, str]: """ Parses the constraints file referenced by `dependency_constraint_flags` and returns a dict where the key is the package name, and the value is the constraint version. If a package version cannot be found, its value is "embed" meaning that virtualenv will install its bundled version, already available locally. The function does not try to be too smart and just handles basic constraints. If it can't get an exact version, the real constraint will be handled by the {macos|windows}.setup_python function. """ assert len(dependency_constraint_flags) in {0, 2} packages = ["pip", "setuptools", "wheel"] constraints_dict = {package: "embed" for package in packages} if len(dependency_constraint_flags) == 2: assert dependency_constraint_flags[0] == "-c" constraint_path = Path(dependency_constraint_flags[1]) assert constraint_path.exists() with constraint_path.open() as constraint_file: for line in constraint_file: line = line.strip() if len(line) == 0: continue if line.startswith("#"): continue try: requirement = Requirement(line) package = requirement.name if ( package not in packages or requirement.url is not None or requirement.marker is not None or len(requirement.extras) != 0 or len(requirement.specifier) != 1 ): continue specifier = next(iter(requirement.specifier)) if specifier.operator != "==": continue constraints_dict[package] = specifier.version except InvalidRequirement: continue return constraints_dict
[ "def", "_parse_constraints_for_virtualenv", "(", "dependency_constraint_flags", ":", "Sequence", "[", "PathOrStr", "]", ",", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "assert", "len", "(", "dependency_constraint_flags", ")", "in", "{", "0", ",", "2", "}", "packages", "=", "[", "\"pip\"", ",", "\"setuptools\"", ",", "\"wheel\"", "]", "constraints_dict", "=", "{", "package", ":", "\"embed\"", "for", "package", "in", "packages", "}", "if", "len", "(", "dependency_constraint_flags", ")", "==", "2", ":", "assert", "dependency_constraint_flags", "[", "0", "]", "==", "\"-c\"", "constraint_path", "=", "Path", "(", "dependency_constraint_flags", "[", "1", "]", ")", "assert", "constraint_path", ".", "exists", "(", ")", "with", "constraint_path", ".", "open", "(", ")", "as", "constraint_file", ":", "for", "line", "in", "constraint_file", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", "==", "0", ":", "continue", "if", "line", ".", "startswith", "(", "\"#\"", ")", ":", "continue", "try", ":", "requirement", "=", "Requirement", "(", "line", ")", "package", "=", "requirement", ".", "name", "if", "(", "package", "not", "in", "packages", "or", "requirement", ".", "url", "is", "not", "None", "or", "requirement", ".", "marker", "is", "not", "None", "or", "len", "(", "requirement", ".", "extras", ")", "!=", "0", "or", "len", "(", "requirement", ".", "specifier", ")", "!=", "1", ")", ":", "continue", "specifier", "=", "next", "(", "iter", "(", "requirement", ".", "specifier", ")", ")", "if", "specifier", ".", "operator", "!=", "\"==\"", ":", "continue", "constraints_dict", "[", "package", "]", "=", "specifier", ".", "version", "except", "InvalidRequirement", ":", "continue", "return", "constraints_dict" ]
https://github.com/pypa/cibuildwheel/blob/5255155bc57eb6224354356df648dc42e31a0028/cibuildwheel/util.py#L478-L521
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/Iter2_v3_resv2_inresv2_random/nets/vgg.py
python
vgg_arg_scope
(weight_decay=0.0005)
Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope.
Defines the VGG arg scope.
[ "Defines", "the", "VGG", "arg", "scope", "." ]
def vgg_arg_scope(weight_decay=0.0005): """Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()): with slim.arg_scope([slim.conv2d], padding='SAME') as arg_sc: return arg_sc
[ "def", "vgg_arg_scope", "(", "weight_decay", "=", "0.0005", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "fully_connected", "]", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "weights_regularizer", "=", "slim", ".", "l2_regularizer", "(", "weight_decay", ")", ",", "biases_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", "]", ",", "padding", "=", "'SAME'", ")", "as", "arg_sc", ":", "return", "arg_sc" ]
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/Iter2_v3_resv2_inresv2_random/nets/vgg.py#L49-L63
glyph/automat
29a60958dc017af9bc70dc91fe2f628f2f5a7405
docs/examples/io_coffee_example.py
python
CoffeeBrewer._save_beans
(self, beans)
The beans are now in the machine; save them.
The beans are now in the machine; save them.
[ "The", "beans", "are", "now", "in", "the", "machine", ";", "save", "them", "." ]
def _save_beans(self, beans): "The beans are now in the machine; save them." self._beans = beans
[ "def", "_save_beans", "(", "self", ",", "beans", ")", ":", "self", ".", "_beans", "=", "beans" ]
https://github.com/glyph/automat/blob/29a60958dc017af9bc70dc91fe2f628f2f5a7405/docs/examples/io_coffee_example.py#L22-L24
hirofumi0810/tensorflow_end2end_speech_recognition
65b9728089d5e92b25b92384a67419d970399a64
models/attention/decoders/decoder_util.py
python
_flatten_dict
(dict_, parent_key="", sep=".")
return dict(items)
Flattens a nested dictionary. Namedtuples within the dictionary are converted to dicts. Args: dict_: The dictionary to flatten. parent_key: A prefix to prepend to each key. sep: Separator between parent and child keys, a string. For example { "a": { "b": 3 } } will become { "a.b": 3 } if the separator is ".". Returns: A new flattened dictionary.
Flattens a nested dictionary. Namedtuples within the dictionary are converted to dicts. Args: dict_: The dictionary to flatten. parent_key: A prefix to prepend to each key. sep: Separator between parent and child keys, a string. For example { "a": { "b": 3 } } will become { "a.b": 3 } if the separator is ".". Returns: A new flattened dictionary.
[ "Flattens", "a", "nested", "dictionary", ".", "Namedtuples", "within", "the", "dictionary", "are", "converted", "to", "dicts", ".", "Args", ":", "dict_", ":", "The", "dictionary", "to", "flatten", ".", "parent_key", ":", "A", "prefix", "to", "prepend", "to", "each", "key", ".", "sep", ":", "Separator", "between", "parent", "and", "child", "keys", "a", "string", ".", "For", "example", "{", "a", ":", "{", "b", ":", "3", "}", "}", "will", "become", "{", "a", ".", "b", ":", "3", "}", "if", "the", "separator", "is", ".", ".", "Returns", ":", "A", "new", "flattened", "dictionary", "." ]
def _flatten_dict(dict_, parent_key="", sep="."): """Flattens a nested dictionary. Namedtuples within the dictionary are converted to dicts. Args: dict_: The dictionary to flatten. parent_key: A prefix to prepend to each key. sep: Separator between parent and child keys, a string. For example { "a": { "b": 3 } } will become { "a.b": 3 } if the separator is ".". Returns: A new flattened dictionary. """ items = [] for key, value in dict_.items(): new_key = parent_key + sep + key if parent_key else key if isinstance(value, collections.MutableMapping): items.extend(_flatten_dict(value, new_key, sep=sep).items()) elif isinstance(value, tuple) and hasattr(value, "_asdict"): dict_items = collections.OrderedDict(zip(value._fields, value)) items.extend(_flatten_dict( dict_items, new_key, sep=sep).items()) else: items.append((new_key, value)) return dict(items)
[ "def", "_flatten_dict", "(", "dict_", ",", "parent_key", "=", "\"\"", ",", "sep", "=", "\".\"", ")", ":", "items", "=", "[", "]", "for", "key", ",", "value", "in", "dict_", ".", "items", "(", ")", ":", "new_key", "=", "parent_key", "+", "sep", "+", "key", "if", "parent_key", "else", "key", "if", "isinstance", "(", "value", ",", "collections", ".", "MutableMapping", ")", ":", "items", ".", "extend", "(", "_flatten_dict", "(", "value", ",", "new_key", ",", "sep", "=", "sep", ")", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "value", ",", "tuple", ")", "and", "hasattr", "(", "value", ",", "\"_asdict\"", ")", ":", "dict_items", "=", "collections", ".", "OrderedDict", "(", "zip", "(", "value", ".", "_fields", ",", "value", ")", ")", "items", ".", "extend", "(", "_flatten_dict", "(", "dict_items", ",", "new_key", ",", "sep", "=", "sep", ")", ".", "items", "(", ")", ")", "else", ":", "items", ".", "append", "(", "(", "new_key", ",", "value", ")", ")", "return", "dict", "(", "items", ")" ]
https://github.com/hirofumi0810/tensorflow_end2end_speech_recognition/blob/65b9728089d5e92b25b92384a67419d970399a64/models/attention/decoders/decoder_util.py#L7-L30
Harry24k/adversarial-attacks-pytorch
20d9783ef7033853eea59c2772aab17ccaf97f44
torchattacks/attacks/_differential_evolution.py
python
DifferentialEvolutionSolver._select_samples
(self, candidate, number_samples)
return idxs
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
[ "obtain", "random", "integers", "from", "range", "(", "self", ".", "num_population_members", ")", "without", "replacement", ".", "You", "can", "t", "have", "the", "original", "candidate", "either", "." ]
def _select_samples(self, candidate, number_samples): """ obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either. """ idxs = list(range(self.num_population_members)) idxs.remove(candidate) self.random_number_generator.shuffle(idxs) idxs = idxs[:number_samples] return idxs
[ "def", "_select_samples", "(", "self", ",", "candidate", ",", "number_samples", ")", ":", "idxs", "=", "list", "(", "range", "(", "self", ".", "num_population_members", ")", ")", "idxs", ".", "remove", "(", "candidate", ")", "self", ".", "random_number_generator", ".", "shuffle", "(", "idxs", ")", "idxs", "=", "idxs", "[", ":", "number_samples", "]", "return", "idxs" ]
https://github.com/Harry24k/adversarial-attacks-pytorch/blob/20d9783ef7033853eea59c2772aab17ccaf97f44/torchattacks/attacks/_differential_evolution.py#L876-L885
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.read_file
(self, fileob)
Read the metadata values from a file object.
Read the metadata values from a file object.
[ "Read", "the", "metadata", "values", "from", "a", "file", "object", "." ]
def read_file(self, fileob): """Read the metadata values from a file object.""" msg = message_from_file(fileob) self._fields['Metadata-Version'] = msg['metadata-version'] # When reading, get all the fields we can for field in _ALL_FIELDS: if field not in msg: continue if field in _LISTFIELDS: # we can have multiple lines values = msg.get_all(field) if field in _LISTTUPLEFIELDS and values is not None: values = [tuple(value.split(',')) for value in values] self.set(field, values) else: # single line value = msg[field] if value is not None and value != 'UNKNOWN': self.set(field, value)
[ "def", "read_file", "(", "self", ",", "fileob", ")", ":", "msg", "=", "message_from_file", "(", "fileob", ")", "self", ".", "_fields", "[", "'Metadata-Version'", "]", "=", "msg", "[", "'metadata-version'", "]", "# When reading, get all the fields we can", "for", "field", "in", "_ALL_FIELDS", ":", "if", "field", "not", "in", "msg", ":", "continue", "if", "field", "in", "_LISTFIELDS", ":", "# we can have multiple lines", "values", "=", "msg", ".", "get_all", "(", "field", ")", "if", "field", "in", "_LISTTUPLEFIELDS", "and", "values", "is", "not", "None", ":", "values", "=", "[", "tuple", "(", "value", ".", "split", "(", "','", ")", ")", "for", "value", "in", "values", "]", "self", ".", "set", "(", "field", ",", "values", ")", "else", ":", "# single line", "value", "=", "msg", "[", "field", "]", "if", "value", "is", "not", "None", "and", "value", "!=", "'UNKNOWN'", ":", "self", ".", "set", "(", "field", ",", "value", ")" ]
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/metadata.py#L362-L381
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/pickle.py
python
_Pickler.__init__
(self, file, protocol=None, *, fix_imports=True)
This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 3; a backward-incompatible protocol designed for Python 3. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.
This takes a binary file for writing a pickle data stream.
[ "This", "takes", "a", "binary", "file", "for", "writing", "a", "pickle", "data", "stream", "." ]
def __init__(self, file, protocol=None, *, fix_imports=True): """This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 3; a backward-incompatible protocol designed for Python 3. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. """ if protocol is None: protocol = DEFAULT_PROTOCOL if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) try: self._file_write = file.write except AttributeError: raise TypeError("file must have a 'write' attribute") self.framer = _Framer(self._file_write) self.write = self.framer.write self._write_large_bytes = self.framer.write_large_bytes self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0 self.fix_imports = fix_imports and protocol < 3
[ "def", "__init__", "(", "self", ",", "file", ",", "protocol", "=", "None", ",", "*", ",", "fix_imports", "=", "True", ")", ":", "if", "protocol", "is", "None", ":", "protocol", "=", "DEFAULT_PROTOCOL", "if", "protocol", "<", "0", ":", "protocol", "=", "HIGHEST_PROTOCOL", "elif", "not", "0", "<=", "protocol", "<=", "HIGHEST_PROTOCOL", ":", "raise", "ValueError", "(", "\"pickle protocol must be <= %d\"", "%", "HIGHEST_PROTOCOL", ")", "try", ":", "self", ".", "_file_write", "=", "file", ".", "write", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"file must have a 'write' attribute\"", ")", "self", ".", "framer", "=", "_Framer", "(", "self", ".", "_file_write", ")", "self", ".", "write", "=", "self", ".", "framer", ".", "write", "self", ".", "_write_large_bytes", "=", "self", ".", "framer", ".", "write_large_bytes", "self", ".", "memo", "=", "{", "}", "self", ".", "proto", "=", "int", "(", "protocol", ")", "self", ".", "bin", "=", "protocol", ">=", "1", "self", ".", "fast", "=", "0", "self", ".", "fix_imports", "=", "fix_imports", "and", "protocol", "<", "3" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/pickle.py#L374-L414
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
lib/align/alignments.py
python
Alignments.mask_summary
(self)
return masks
dict: The mask type names stored in the alignments :attr:`data` as key with the number of faces which possess the mask type as value.
dict: The mask type names stored in the alignments :attr:`data` as key with the number of faces which possess the mask type as value.
[ "dict", ":", "The", "mask", "type", "names", "stored", "in", "the", "alignments", ":", "attr", ":", "data", "as", "key", "with", "the", "number", "of", "faces", "which", "possess", "the", "mask", "type", "as", "value", "." ]
def mask_summary(self): """ dict: The mask type names stored in the alignments :attr:`data` as key with the number of faces which possess the mask type as value. """ masks = dict() for val in self._data.values(): for face in val["faces"]: if face.get("mask", None) is None: masks["none"] = masks.get("none", 0) + 1 for key in face.get("mask", dict()): masks[key] = masks.get(key, 0) + 1 return masks
[ "def", "mask_summary", "(", "self", ")", ":", "masks", "=", "dict", "(", ")", "for", "val", "in", "self", ".", "_data", ".", "values", "(", ")", ":", "for", "face", "in", "val", "[", "\"faces\"", "]", ":", "if", "face", ".", "get", "(", "\"mask\"", ",", "None", ")", "is", "None", ":", "masks", "[", "\"none\"", "]", "=", "masks", ".", "get", "(", "\"none\"", ",", "0", ")", "+", "1", "for", "key", "in", "face", ".", "get", "(", "\"mask\"", ",", "dict", "(", ")", ")", ":", "masks", "[", "key", "]", "=", "masks", ".", "get", "(", "key", ",", "0", ")", "+", "1", "return", "masks" ]
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/lib/align/alignments.py#L136-L146
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
vdui_t.refresh_view
(self, *args)
return _idaapi.vdui_t_refresh_view(self, *args)
refresh_view(self, redo_mba)
refresh_view(self, redo_mba)
[ "refresh_view", "(", "self", "redo_mba", ")" ]
def refresh_view(self, *args): """ refresh_view(self, redo_mba) """ return _idaapi.vdui_t_refresh_view(self, *args)
[ "def", "refresh_view", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "vdui_t_refresh_view", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L39468-L39472
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/config.py
python
LutrisConfig.merge_to_system_config
(self, config)
Merge a configuration to the system configuation
Merge a configuration to the system configuation
[ "Merge", "a", "configuration", "to", "the", "system", "configuation" ]
def merge_to_system_config(self, config): """Merge a configuration to the system configuation""" if not config: return existing_env = None if self.system_config.get("env") and "env" in config: existing_env = self.system_config["env"] self.system_config.update(config) if existing_env: self.system_config["env"] = existing_env self.system_config["env"].update(config["env"])
[ "def", "merge_to_system_config", "(", "self", ",", "config", ")", ":", "if", "not", "config", ":", "return", "existing_env", "=", "None", "if", "self", ".", "system_config", ".", "get", "(", "\"env\"", ")", "and", "\"env\"", "in", "config", ":", "existing_env", "=", "self", ".", "system_config", "[", "\"env\"", "]", "self", ".", "system_config", ".", "update", "(", "config", ")", "if", "existing_env", ":", "self", ".", "system_config", "[", "\"env\"", "]", "=", "existing_env", "self", ".", "system_config", "[", "\"env\"", "]", ".", "update", "(", "config", "[", "\"env\"", "]", ")" ]
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/config.py#L168-L178
jnhwkim/ban-vqa
54f044ce9020842b4cb69679e535f885bef57ca3
utils.py
python
weights_init
(m)
custom weights initialization.
custom weights initialization.
[ "custom", "weights", "initialization", "." ]
def weights_init(m): """custom weights initialization.""" cname = m.__class__ if cname == nn.Linear or cname == nn.Conv2d or cname == nn.ConvTranspose2d: m.weight.data.normal_(0.0, 0.02) elif cname == nn.BatchNorm2d: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) else: print('%s is not initialized.' % cname)
[ "def", "weights_init", "(", "m", ")", ":", "cname", "=", "m", ".", "__class__", "if", "cname", "==", "nn", ".", "Linear", "or", "cname", "==", "nn", ".", "Conv2d", "or", "cname", "==", "nn", ".", "ConvTranspose2d", ":", "m", ".", "weight", ".", "data", ".", "normal_", "(", "0.0", ",", "0.02", ")", "elif", "cname", "==", "nn", ".", "BatchNorm2d", ":", "m", ".", "weight", ".", "data", ".", "normal_", "(", "1.0", ",", "0.02", ")", "m", ".", "bias", ".", "data", ".", "fill_", "(", "0", ")", "else", ":", "print", "(", "'%s is not initialized.'", "%", "cname", ")" ]
https://github.com/jnhwkim/ban-vqa/blob/54f044ce9020842b4cb69679e535f885bef57ca3/utils.py#L61-L70
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
frontend/parse_lib.py
python
ParseContext.ParseProc
(self, lexer, out)
return last_token
proc f(x, y, @args) {
proc f(x, y,
[ "proc", "f", "(", "x", "y" ]
def ParseProc(self, lexer, out): # type: (Lexer, command__Proc) -> Token """ proc f(x, y, @args) { """ pnode, last_token = self._ParseOil(lexer, grammar_nt.oil_proc) if 0: self.p_printer.Print(pnode) out.sig = self.tr.Proc(pnode) return last_token
[ "def", "ParseProc", "(", "self", ",", "lexer", ",", "out", ")", ":", "# type: (Lexer, command__Proc) -> Token", "pnode", ",", "last_token", "=", "self", ".", "_ParseOil", "(", "lexer", ",", "grammar_nt", ".", "oil_proc", ")", "if", "0", ":", "self", ".", "p_printer", ".", "Print", "(", "pnode", ")", "out", ".", "sig", "=", "self", ".", "tr", ".", "Proc", "(", "pnode", ")", "return", "last_token" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/frontend/parse_lib.py#L374-L383
alexandre01/UltimateLabeling
590ceea62ff9ec97f8d5f001fc592a24c8182d78
ultimatelabeling/models/detector.py
python
SocketDetector.send_crop_area
(self, crop_area)
crop_area (Bbox)
crop_area (Bbox)
[ "crop_area", "(", "Bbox", ")" ]
def send_crop_area(self, crop_area): """ crop_area (Bbox) """ data = pickle.dumps(crop_area.to_json()) self.client_socket.send(data)
[ "def", "send_crop_area", "(", "self", ",", "crop_area", ")", ":", "data", "=", "pickle", ".", "dumps", "(", "crop_area", ".", "to_json", "(", ")", ")", "self", ".", "client_socket", ".", "send", "(", "data", ")" ]
https://github.com/alexandre01/UltimateLabeling/blob/590ceea62ff9ec97f8d5f001fc592a24c8182d78/ultimatelabeling/models/detector.py#L75-L80
yaohungt/Gated-Spatio-Temporal-Energy-Graph
bc8f44b3d95cbfe3032bb3612daa07b4d9cd4298
datasets/transforms.py
python
RandomResizedCrop.__call__
(self, img)
return [super(RandomResizedCrop, self).__call__(im) for im in img]
[]
def __call__(self, img): return [super(RandomResizedCrop, self).__call__(im) for im in img]
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "return", "[", "super", "(", "RandomResizedCrop", ",", "self", ")", ".", "__call__", "(", "im", ")", "for", "im", "in", "img", "]" ]
https://github.com/yaohungt/Gated-Spatio-Temporal-Energy-Graph/blob/bc8f44b3d95cbfe3032bb3612daa07b4d9cd4298/datasets/transforms.py#L22-L23
chenjiandongx/async-proxy-pool
b6869e39ab949700b90b84df58489c41f8d6e3e2
async_proxy_pool/utils.py
python
_get_page
(url, sleep)
获取并返回网页内容
获取并返回网页内容
[ "获取并返回网页内容" ]
async def _get_page(url, sleep): """ 获取并返回网页内容 """ async with aiohttp.ClientSession() as session: try: await asyncio.sleep(sleep) async with session.get( url, headers=HEADERS, timeout=REQUEST_TIMEOUT ) as resp: return await resp.text() except: return ""
[ "async", "def", "_get_page", "(", "url", ",", "sleep", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "try", ":", "await", "asyncio", ".", "sleep", "(", "sleep", ")", "async", "with", "session", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ",", "timeout", "=", "REQUEST_TIMEOUT", ")", "as", "resp", ":", "return", "await", "resp", ".", "text", "(", ")", "except", ":", "return", "\"\"" ]
https://github.com/chenjiandongx/async-proxy-pool/blob/b6869e39ab949700b90b84df58489c41f8d6e3e2/async_proxy_pool/utils.py#L14-L26
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/implementation/sqlalchemy/authinfos.py
python
SqlaAuthInfo.enabled
(self, enabled)
Set the enabled state :param enabled: boolean, True to enable the instance, False to disable it
Set the enabled state
[ "Set", "the", "enabled", "state" ]
def enabled(self, enabled): """Set the enabled state :param enabled: boolean, True to enable the instance, False to disable it """ self._dbmodel.enabled = enabled
[ "def", "enabled", "(", "self", ",", "enabled", ")", ":", "self", ".", "_dbmodel", ".", "enabled", "=", "enabled" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/implementation/sqlalchemy/authinfos.py#L59-L64
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/wallet/crypto.py
python
decrypt_plaintext
( ciphertext: bytes, recips_bin: bytes, nonce: bytes, key: bytes )
return output.decode("utf-8")
Decrypt the payload of a packed message. Args: ciphertext: recips_bin: nonce: key: Returns: The decrypted string
Decrypt the payload of a packed message.
[ "Decrypt", "the", "payload", "of", "a", "packed", "message", "." ]
def decrypt_plaintext( ciphertext: bytes, recips_bin: bytes, nonce: bytes, key: bytes ) -> str: """ Decrypt the payload of a packed message. Args: ciphertext: recips_bin: nonce: key: Returns: The decrypted string """ output = nacl.bindings.crypto_aead_chacha20poly1305_ietf_decrypt( ciphertext, recips_bin, nonce, key ) return output.decode("utf-8")
[ "def", "decrypt_plaintext", "(", "ciphertext", ":", "bytes", ",", "recips_bin", ":", "bytes", ",", "nonce", ":", "bytes", ",", "key", ":", "bytes", ")", "->", "str", ":", "output", "=", "nacl", ".", "bindings", ".", "crypto_aead_chacha20poly1305_ietf_decrypt", "(", "ciphertext", ",", "recips_bin", ",", "nonce", ",", "key", ")", "return", "output", ".", "decode", "(", "\"utf-8\"", ")" ]
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/wallet/crypto.py#L327-L346
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/logging.py
python
setBasicLogger
()
Use Basic Logger.
Use Basic Logger.
[ "Use", "Basic", "Logger", "." ]
def setBasicLogger(): '''Use Basic Logger. ''' setLoggerClass(BasicLogger) BasicLogger.setLevel(0)
[ "def", "setBasicLogger", "(", ")", ":", "setLoggerClass", "(", "BasicLogger", ")", "BasicLogger", ".", "setLevel", "(", "0", ")" ]
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/logging.py#L227-L231
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/Tool/applelink.py
python
_applelib_check_valid_version
(version_string)
return True, ""
Check that the version # is valid. X[.Y[.Z]] where X 0-65535 where Y either not specified or 0-255 where Z either not specified or 0-255 :param version_string: :return:
Check that the version # is valid. X[.Y[.Z]] where X 0-65535 where Y either not specified or 0-255 where Z either not specified or 0-255 :param version_string: :return:
[ "Check", "that", "the", "version", "#", "is", "valid", ".", "X", "[", ".", "Y", "[", ".", "Z", "]]", "where", "X", "0", "-", "65535", "where", "Y", "either", "not", "specified", "or", "0", "-", "255", "where", "Z", "either", "not", "specified", "or", "0", "-", "255", ":", "param", "version_string", ":", ":", "return", ":" ]
def _applelib_check_valid_version(version_string): """ Check that the version # is valid. X[.Y[.Z]] where X 0-65535 where Y either not specified or 0-255 where Z either not specified or 0-255 :param version_string: :return: """ parts = version_string.split('.') if len(parts) > 3: return False, "Version string has too many periods [%s]" % version_string if len(parts) <= 0: return False, "Version string unspecified [%s]" % version_string for (i, p) in enumerate(parts): try: p_i = int(p) except ValueError: return False, "Version component %s (from %s) is not a number" % (p, version_string) if p_i < 0 or p_i > _APPLELIB_MAX_VERSION_VALUES[i]: return False, "Version component %s (from %s) is not valid value should be between 0 and %d" % ( p, version_string, _APPLELIB_MAX_VERSION_VALUES[i]) return True, ""
[ "def", "_applelib_check_valid_version", "(", "version_string", ")", ":", "parts", "=", "version_string", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", ">", "3", ":", "return", "False", ",", "\"Version string has too many periods [%s]\"", "%", "version_string", "if", "len", "(", "parts", ")", "<=", "0", ":", "return", "False", ",", "\"Version string unspecified [%s]\"", "%", "version_string", "for", "(", "i", ",", "p", ")", "in", "enumerate", "(", "parts", ")", ":", "try", ":", "p_i", "=", "int", "(", "p", ")", "except", "ValueError", ":", "return", "False", ",", "\"Version component %s (from %s) is not a number\"", "%", "(", "p", ",", "version_string", ")", "if", "p_i", "<", "0", "or", "p_i", ">", "_APPLELIB_MAX_VERSION_VALUES", "[", "i", "]", ":", "return", "False", ",", "\"Version component %s (from %s) is not valid value should be between 0 and %d\"", "%", "(", "p", ",", "version_string", ",", "_APPLELIB_MAX_VERSION_VALUES", "[", "i", "]", ")", "return", "True", ",", "\"\"" ]
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/Tool/applelink.py#L54-L79
bigzhao/Keyword_Extraction
afac907856d46429806f051d75896ac111039b57
jieba/analyse/textrank.py
python
TextRank.__init__
(self)
[]
def __init__(self): self.tokenizer = self.postokenizer = jieba.posseg.dt self.stop_words = self.STOP_WORDS.copy() self.pos_filt = frozenset(('ns', 'n', 'vn', 'v')) self.span = 5
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "tokenizer", "=", "self", ".", "postokenizer", "=", "jieba", ".", "posseg", ".", "dt", "self", ".", "stop_words", "=", "self", ".", "STOP_WORDS", ".", "copy", "(", ")", "self", ".", "pos_filt", "=", "frozenset", "(", "(", "'ns'", ",", "'n'", ",", "'vn'", ",", "'v'", ")", ")", "self", ".", "span", "=", "5" ]
https://github.com/bigzhao/Keyword_Extraction/blob/afac907856d46429806f051d75896ac111039b57/jieba/analyse/textrank.py#L59-L63
httprunner/httprunner
16ee293273211b11c3efc3b3c659695be02cf045
examples/httpbin/debugtalk.py
python
alter_response
(response)
[]
def alter_response(response): response.status_code = 500 response.headers["Content-Type"] = "html/text" response.body["headers"]["Host"] = "127.0.0.1:8888" response.new_attribute = "new_attribute_value" response.new_attribute_dict = {"key": 123}
[ "def", "alter_response", "(", "response", ")", ":", "response", ".", "status_code", "=", "500", "response", ".", "headers", "[", "\"Content-Type\"", "]", "=", "\"html/text\"", "response", ".", "body", "[", "\"headers\"", "]", "[", "\"Host\"", "]", "=", "\"127.0.0.1:8888\"", "response", ".", "new_attribute", "=", "\"new_attribute_value\"", "response", ".", "new_attribute_dict", "=", "{", "\"key\"", ":", "123", "}" ]
https://github.com/httprunner/httprunner/blob/16ee293273211b11c3efc3b3c659695be02cf045/examples/httpbin/debugtalk.py#L126-L131
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/asyncore.py
python
dispatcher.__repr__
(self)
return '<%s at %#x>' % (' '.join(status), id(self))
[]
def __repr__(self): status = [self.__class__.__module__+"."+self.__class__.__qualname__] if self.accepting and self.addr: status.append('listening') elif self.connected: status.append('connected') if self.addr is not None: try: status.append('%s:%d' % self.addr) except TypeError: status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self))
[ "def", "__repr__", "(", "self", ")", ":", "status", "=", "[", "self", ".", "__class__", ".", "__module__", "+", "\".\"", "+", "self", ".", "__class__", ".", "__qualname__", "]", "if", "self", ".", "accepting", "and", "self", ".", "addr", ":", "status", ".", "append", "(", "'listening'", ")", "elif", "self", ".", "connected", ":", "status", ".", "append", "(", "'connected'", ")", "if", "self", ".", "addr", "is", "not", "None", ":", "try", ":", "status", ".", "append", "(", "'%s:%d'", "%", "self", ".", "addr", ")", "except", "TypeError", ":", "status", ".", "append", "(", "repr", "(", "self", ".", "addr", ")", ")", "return", "'<%s at %#x>'", "%", "(", "' '", ".", "join", "(", "status", ")", ",", "id", "(", "self", ")", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/asyncore.py#L259-L270
andrewekhalel/edafa
122da335fa3aada1e4df6b9bc88411f544a23c22
edafa/BasePredictor.py
python
BasePredictor._parse_conf
(self,conf)
Parse the configuration file :param conf: configuration (json string or file path)
Parse the configuration file
[ "Parse", "the", "configuration", "file" ]
def _parse_conf(self,conf): """ Parse the configuration file :param conf: configuration (json string or file path) """ loaded = conf_to_dict(conf) if loaded is None: raise ConfigurationUnrecognized("Unrecognized configuration!") if "augs" in loaded: self.augs = loaded["augs"] for aug in self.augs: if aug not in AUGS: raise AugmentationUnrecognized('Unrecognized augmentation: %s in configuration.'%aug) else: warnings.warn('No "augs" found in configuration file. No augmentations will be used.',SyntaxWarning) self.augs = ["NO"] if "mean" in loaded: self.mean = loaded["mean"] if self.mean not in MEANS: raise MeanUnrecognized('Unrecognized mean: %s in configuration.'%self.mean) else: warnings.warn('No "mean" found in configuration file. "ARITH" mean will be used.',SyntaxWarning) self.mean = "ARITH" if "bits" in loaded: self.bits = loaded["bits"] else: warnings.warn('No "bits" found in configuration file. 8-bits will be used.',SyntaxWarning) self.bits = 8
[ "def", "_parse_conf", "(", "self", ",", "conf", ")", ":", "loaded", "=", "conf_to_dict", "(", "conf", ")", "if", "loaded", "is", "None", ":", "raise", "ConfigurationUnrecognized", "(", "\"Unrecognized configuration!\"", ")", "if", "\"augs\"", "in", "loaded", ":", "self", ".", "augs", "=", "loaded", "[", "\"augs\"", "]", "for", "aug", "in", "self", ".", "augs", ":", "if", "aug", "not", "in", "AUGS", ":", "raise", "AugmentationUnrecognized", "(", "'Unrecognized augmentation: %s in configuration.'", "%", "aug", ")", "else", ":", "warnings", ".", "warn", "(", "'No \"augs\" found in configuration file. No augmentations will be used.'", ",", "SyntaxWarning", ")", "self", ".", "augs", "=", "[", "\"NO\"", "]", "if", "\"mean\"", "in", "loaded", ":", "self", ".", "mean", "=", "loaded", "[", "\"mean\"", "]", "if", "self", ".", "mean", "not", "in", "MEANS", ":", "raise", "MeanUnrecognized", "(", "'Unrecognized mean: %s in configuration.'", "%", "self", ".", "mean", ")", "else", ":", "warnings", ".", "warn", "(", "'No \"mean\" found in configuration file. \"ARITH\" mean will be used.'", ",", "SyntaxWarning", ")", "self", ".", "mean", "=", "\"ARITH\"", "if", "\"bits\"", "in", "loaded", ":", "self", ".", "bits", "=", "loaded", "[", "\"bits\"", "]", "else", ":", "warnings", ".", "warn", "(", "'No \"bits\" found in configuration file. 8-bits will be used.'", ",", "SyntaxWarning", ")", "self", ".", "bits", "=", "8" ]
https://github.com/andrewekhalel/edafa/blob/122da335fa3aada1e4df6b9bc88411f544a23c22/edafa/BasePredictor.py#L58-L90
googledatalab/pydatalab
1c86e26a0d24e3bc8097895ddeab4d0607be4c40
google/datalab/storage/_bucket.py
python
Bucket.__init__
(self, name, info=None, context=None)
Initializes an instance of a Bucket object. Args: name: the name of the bucket. info: the information about the bucket if available. context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones configured at the global level are used.
Initializes an instance of a Bucket object.
[ "Initializes", "an", "instance", "of", "a", "Bucket", "object", "." ]
def __init__(self, name, info=None, context=None): """Initializes an instance of a Bucket object. Args: name: the name of the bucket. info: the information about the bucket if available. context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones configured at the global level are used. """ if context is None: context = google.datalab.Context.default() self._context = context self._api = _api.Api(context) self._name = name self._info = info
[ "def", "__init__", "(", "self", ",", "name", ",", "info", "=", "None", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "self", ".", "_context", "=", "context", "self", ".", "_api", "=", "_api", ".", "Api", "(", "context", ")", "self", ".", "_name", "=", "name", "self", ".", "_info", "=", "info" ]
https://github.com/googledatalab/pydatalab/blob/1c86e26a0d24e3bc8097895ddeab4d0607be4c40/google/datalab/storage/_bucket.py#L90-L105
MenglinLu/Chinese-clinical-NER
9614593ee2e1ba38d0985c44e957d316e178b93c
bert_sklearn/bert_sklearn/utils.py
python
prepare_model_and_device
(model, config)
return model, device
Prepare model for training and get torch device Parameters ---------- model : BertPlusMLP BERT model plud mlp head len_train_data : int length of training data config : FinetuneConfig Parameters for finetuning BERT
Prepare model for training and get torch device
[ "Prepare", "model", "for", "training", "and", "get", "torch", "device" ]
def prepare_model_and_device(model, config): """ Prepare model for training and get torch device Parameters ---------- model : BertPlusMLP BERT model plud mlp head len_train_data : int length of training data config : FinetuneConfig Parameters for finetuning BERT """ device, n_gpu = get_device(config.local_rank, config.use_cuda) if config.fp16: model.half() model.to(device) if config.local_rank != -1: try: from apex.parallel import DistributedDataParallel as DDP except ImportError: raise ImportError("Please install apex from \ https://www.github.com/nvidia/apex to use distributed and fp16 training.") model = DDP(model) elif n_gpu > 1: model = torch.nn.DataParallel(model) return model, device
[ "def", "prepare_model_and_device", "(", "model", ",", "config", ")", ":", "device", ",", "n_gpu", "=", "get_device", "(", "config", ".", "local_rank", ",", "config", ".", "use_cuda", ")", "if", "config", ".", "fp16", ":", "model", ".", "half", "(", ")", "model", ".", "to", "(", "device", ")", "if", "config", ".", "local_rank", "!=", "-", "1", ":", "try", ":", "from", "apex", ".", "parallel", "import", "DistributedDataParallel", "as", "DDP", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Please install apex from \\\n https://www.github.com/nvidia/apex to use distributed and fp16 training.\"", ")", "model", "=", "DDP", "(", "model", ")", "elif", "n_gpu", ">", "1", ":", "model", "=", "torch", ".", "nn", ".", "DataParallel", "(", "model", ")", "return", "model", ",", "device" ]
https://github.com/MenglinLu/Chinese-clinical-NER/blob/9614593ee2e1ba38d0985c44e957d316e178b93c/bert_sklearn/bert_sklearn/utils.py#L102-L134
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/urllib/request.py
python
parse_keqv_list
(l)
return parsed
Parse list of key=value strings where keys are not duplicated.
Parse list of key=value strings where keys are not duplicated.
[ "Parse", "list", "of", "key", "=", "value", "strings", "where", "keys", "are", "not", "duplicated", "." ]
def parse_keqv_list(l): """Parse list of key=value strings where keys are not duplicated.""" parsed = {} for elt in l: k, v = elt.split('=', 1) if v[0] == '"' and v[-1] == '"': v = v[1:-1] parsed[k] = v return parsed
[ "def", "parse_keqv_list", "(", "l", ")", ":", "parsed", "=", "{", "}", "for", "elt", "in", "l", ":", "k", ",", "v", "=", "elt", ".", "split", "(", "'='", ",", "1", ")", "if", "v", "[", "0", "]", "==", "'\"'", "and", "v", "[", "-", "1", "]", "==", "'\"'", ":", "v", "=", "v", "[", "1", ":", "-", "1", "]", "parsed", "[", "k", "]", "=", "v", "return", "parsed" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/urllib/request.py#L1386-L1394
deanishe/alfred-reddit
2f7545e682fc1579489947baa679e19b4eb1900e
src/workflow/update.py
python
download_workflow
(url)
return local_path
Download workflow at ``url`` to a local temporary file. :param url: URL to .alfredworkflow file in GitHub repo :returns: path to downloaded file
Download workflow at ``url`` to a local temporary file.
[ "Download", "workflow", "at", "url", "to", "a", "local", "temporary", "file", "." ]
def download_workflow(url): """Download workflow at ``url`` to a local temporary file. :param url: URL to .alfredworkflow file in GitHub repo :returns: path to downloaded file """ filename = url.split('/')[-1] if (not filename.endswith('.alfredworkflow') and not filename.endswith('.alfred3workflow')): raise ValueError('attachment not a workflow: {0}'.format(filename)) local_path = os.path.join(tempfile.gettempdir(), filename) wf().logger.debug( 'downloading updated workflow from `%s` to `%s` ...', url, local_path) response = web.get(url) with open(local_path, 'wb') as output: output.write(response.content) return local_path
[ "def", "download_workflow", "(", "url", ")", ":", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "(", "not", "filename", ".", "endswith", "(", "'.alfredworkflow'", ")", "and", "not", "filename", ".", "endswith", "(", "'.alfred3workflow'", ")", ")", ":", "raise", "ValueError", "(", "'attachment not a workflow: {0}'", ".", "format", "(", "filename", ")", ")", "local_path", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "filename", ")", "wf", "(", ")", ".", "logger", ".", "debug", "(", "'downloading updated workflow from `%s` to `%s` ...'", ",", "url", ",", "local_path", ")", "response", "=", "web", ".", "get", "(", "url", ")", "with", "open", "(", "local_path", ",", "'wb'", ")", "as", "output", ":", "output", ".", "write", "(", "response", ".", "content", ")", "return", "local_path" ]
https://github.com/deanishe/alfred-reddit/blob/2f7545e682fc1579489947baa679e19b4eb1900e/src/workflow/update.py#L196-L219
sergioburdisso/pyss3
70c37853f3f56a60c3df9b94b678ca3f0db843de
pyss3/__init__.py
python
re_split_keep
(regex, string)
return re.split(regex, string)
Force the inclusion of unmatched items by re.split. This allows keeping the original content after splitting the input document for later use (e.g. for using it from the Live Test)
Force the inclusion of unmatched items by re.split.
[ "Force", "the", "inclusion", "of", "unmatched", "items", "by", "re", ".", "split", "." ]
def re_split_keep(regex, string): """ Force the inclusion of unmatched items by re.split. This allows keeping the original content after splitting the input document for later use (e.g. for using it from the Live Test) """ if not re.match(r"\(.*\)", regex): regex = "(%s)" % regex return re.split(regex, string)
[ "def", "re_split_keep", "(", "regex", ",", "string", ")", ":", "if", "not", "re", ".", "match", "(", "r\"\\(.*\\)\"", ",", "regex", ")", ":", "regex", "=", "\"(%s)\"", "%", "regex", "return", "re", ".", "split", "(", "regex", ",", "string", ")" ]
https://github.com/sergioburdisso/pyss3/blob/70c37853f3f56a60c3df9b94b678ca3f0db843de/pyss3/__init__.py#L2854-L2863
RaRe-Technologies/gensim
8b8203d8df354673732dff635283494a33d0d422
gensim/models/fasttext.py
python
ft_ngram_hashes
(word, minn, maxn, num_buckets)
return hashes
Calculate the ngrams of the word and hash them. Parameters ---------- word : str The word to calculate ngram hashes for. minn : int Minimum ngram length maxn : int Maximum ngram length num_buckets : int The number of buckets Returns ------- A list of hashes (integers), one per each detected ngram.
Calculate the ngrams of the word and hash them.
[ "Calculate", "the", "ngrams", "of", "the", "word", "and", "hash", "them", "." ]
def ft_ngram_hashes(word, minn, maxn, num_buckets): """Calculate the ngrams of the word and hash them. Parameters ---------- word : str The word to calculate ngram hashes for. minn : int Minimum ngram length maxn : int Maximum ngram length num_buckets : int The number of buckets Returns ------- A list of hashes (integers), one per each detected ngram. """ encoded_ngrams = compute_ngrams_bytes(word, minn, maxn) hashes = [ft_hash_bytes(n) % num_buckets for n in encoded_ngrams] return hashes
[ "def", "ft_ngram_hashes", "(", "word", ",", "minn", ",", "maxn", ",", "num_buckets", ")", ":", "encoded_ngrams", "=", "compute_ngrams_bytes", "(", "word", ",", "minn", ",", "maxn", ")", "hashes", "=", "[", "ft_hash_bytes", "(", "n", ")", "%", "num_buckets", "for", "n", "in", "encoded_ngrams", "]", "return", "hashes" ]
https://github.com/RaRe-Technologies/gensim/blob/8b8203d8df354673732dff635283494a33d0d422/gensim/models/fasttext.py#L1311-L1332
pyglet/pyglet
2833c1df902ca81aeeffa786c12e7e87d402434b
pyglet/graphics/vertexdomain.py
python
VertexList.delete
(self)
Delete this group.
Delete this group.
[ "Delete", "this", "group", "." ]
def delete(self): """Delete this group.""" self.domain.allocator.dealloc(self.start, self.count)
[ "def", "delete", "(", "self", ")", ":", "self", ".", "domain", ".", "allocator", ".", "dealloc", "(", "self", ".", "start", ",", "self", ".", "count", ")" ]
https://github.com/pyglet/pyglet/blob/2833c1df902ca81aeeffa786c12e7e87d402434b/pyglet/graphics/vertexdomain.py#L284-L286
TensorSpeech/TensorflowTTS
34358d82a4c91fd70344872f8ea8a405ea84aedb
tensorflow_tts/models/tacotron2.py
python
TFTacotronLocationSensitiveAttention.get_initial_context
(self, batch_size)
return tf.zeros( shape=[batch_size, self.config.encoder_lstm_units * 2], dtype=tf.float32 )
Get initial attention.
Get initial attention.
[ "Get", "initial", "attention", "." ]
def get_initial_context(self, batch_size): """Get initial attention.""" return tf.zeros( shape=[batch_size, self.config.encoder_lstm_units * 2], dtype=tf.float32 )
[ "def", "get_initial_context", "(", "self", ",", "batch_size", ")", ":", "return", "tf", ".", "zeros", "(", "shape", "=", "[", "batch_size", ",", "self", ".", "config", ".", "encoder_lstm_units", "*", "2", "]", ",", "dtype", "=", "tf", ".", "float32", ")" ]
https://github.com/TensorSpeech/TensorflowTTS/blob/34358d82a4c91fd70344872f8ea8a405ea84aedb/tensorflow_tts/models/tacotron2.py#L447-L451
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/pptx/shapes/placeholder.py
python
_InheritsDimensions._base_placeholder
(self)
Return the layout or master placeholder shape this placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily).
Return the layout or master placeholder shape this placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily).
[ "Return", "the", "layout", "or", "master", "placeholder", "shape", "this", "placeholder", "inherits", "from", ".", "Not", "to", "be", "confused", "with", "an", "instance", "of", "|BasePlaceholder|", "(", "necessarily", ")", "." ]
def _base_placeholder(self): """ Return the layout or master placeholder shape this placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily). """ raise NotImplementedError('Must be implemented by all subclasses.')
[ "def", "_base_placeholder", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Must be implemented by all subclasses.'", ")" ]
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/pptx/shapes/placeholder.py#L94-L100
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/smhi/weather.py
python
SmhiWeather.forecast
(self)
return data
Return the forecast.
Return the forecast.
[ "Return", "the", "forecast", "." ]
def forecast(self) -> list[Forecast] | None: """Return the forecast.""" if self._forecasts is None or len(self._forecasts) < 2: return None data: list[Forecast] = [] for forecast in self._forecasts[1:]: condition = next( (k for k, v in CONDITION_CLASSES.items() if forecast.symbol in v), None ) data.append( { ATTR_FORECAST_TIME: forecast.valid_time.isoformat(), ATTR_FORECAST_TEMP: forecast.temperature_max, ATTR_FORECAST_TEMP_LOW: forecast.temperature_min, ATTR_FORECAST_PRECIPITATION: round(forecast.total_precipitation, 1), ATTR_FORECAST_CONDITION: condition, } ) return data
[ "def", "forecast", "(", "self", ")", "->", "list", "[", "Forecast", "]", "|", "None", ":", "if", "self", ".", "_forecasts", "is", "None", "or", "len", "(", "self", ".", "_forecasts", ")", "<", "2", ":", "return", "None", "data", ":", "list", "[", "Forecast", "]", "=", "[", "]", "for", "forecast", "in", "self", ".", "_forecasts", "[", "1", ":", "]", ":", "condition", "=", "next", "(", "(", "k", "for", "k", ",", "v", "in", "CONDITION_CLASSES", ".", "items", "(", ")", "if", "forecast", ".", "symbol", "in", "v", ")", ",", "None", ")", "data", ".", "append", "(", "{", "ATTR_FORECAST_TIME", ":", "forecast", ".", "valid_time", ".", "isoformat", "(", ")", ",", "ATTR_FORECAST_TEMP", ":", "forecast", ".", "temperature_max", ",", "ATTR_FORECAST_TEMP_LOW", ":", "forecast", ".", "temperature_min", ",", "ATTR_FORECAST_PRECIPITATION", ":", "round", "(", "forecast", ".", "total_precipitation", ",", "1", ")", ",", "ATTR_FORECAST_CONDITION", ":", "condition", ",", "}", ")", "return", "data" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/smhi/weather.py#L250-L272
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/utils/__init__.py
python
CanvasRectangle.__init__
(self, scene, x=0, y=0, width=0, height=0, pen_color=QColor(128, 128, 128), brush_color=None, pen_width=1, z=0, pen_style=Qt.SolidLine, pen=None, tooltip=None, show=True, onclick=None)
[]
def __init__(self, scene, x=0, y=0, width=0, height=0, pen_color=QColor(128, 128, 128), brush_color=None, pen_width=1, z=0, pen_style=Qt.SolidLine, pen=None, tooltip=None, show=True, onclick=None): super().__init__(x, y, width, height, None) self.onclick = onclick if brush_color is not None: self.setBrush(QBrush(brush_color)) if pen: self.setPen(pen) else: self.setPen(QPen(QBrush(pen_color), pen_width, pen_style)) self.setZValue(z) if tooltip: self.setToolTip(tooltip) if show: self.show() else: self.hide() if scene is not None: scene.addItem(self)
[ "def", "__init__", "(", "self", ",", "scene", ",", "x", "=", "0", ",", "y", "=", "0", ",", "width", "=", "0", ",", "height", "=", "0", ",", "pen_color", "=", "QColor", "(", "128", ",", "128", ",", "128", ")", ",", "brush_color", "=", "None", ",", "pen_width", "=", "1", ",", "z", "=", "0", ",", "pen_style", "=", "Qt", ".", "SolidLine", ",", "pen", "=", "None", ",", "tooltip", "=", "None", ",", "show", "=", "True", ",", "onclick", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "x", ",", "y", ",", "width", ",", "height", ",", "None", ")", "self", ".", "onclick", "=", "onclick", "if", "brush_color", "is", "not", "None", ":", "self", ".", "setBrush", "(", "QBrush", "(", "brush_color", ")", ")", "if", "pen", ":", "self", ".", "setPen", "(", "pen", ")", "else", ":", "self", ".", "setPen", "(", "QPen", "(", "QBrush", "(", "pen_color", ")", ",", "pen_width", ",", "pen_style", ")", ")", "self", ".", "setZValue", "(", "z", ")", "if", "tooltip", ":", "self", ".", "setToolTip", "(", "tooltip", ")", "if", "show", ":", "self", ".", "show", "(", ")", "else", ":", "self", ".", "hide", "(", ")", "if", "scene", "is", "not", "None", ":", "scene", ".", "addItem", "(", "self", ")" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/utils/__init__.py#L674-L695
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/backports/csv.py
python
reader.parse_add_char
(self, c)
[]
def parse_add_char(self, c): if len(self.field) >= field_size_limit(): raise Error('field size limit exceeded') self.field.append(c)
[ "def", "parse_add_char", "(", "self", ",", "c", ")", ":", "if", "len", "(", "self", ".", "field", ")", ">=", "field_size_limit", "(", ")", ":", "raise", "Error", "(", "'field size limit exceeded'", ")", "self", ".", "field", ".", "append", "(", "c", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/backports/csv.py#L252-L255
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/languages.py
python
TranslatorFactory.params_substitution
(self, message, symbols)
return message
Substitutes parameters from symbols into message using %. also parse `%%{}` placeholders for plural-forms processing. Returns: string with parameters Note: *symbols* MUST BE OR tuple OR dict of parameters!
Substitutes parameters from symbols into message using %. also parse `%%{}` placeholders for plural-forms processing.
[ "Substitutes", "parameters", "from", "symbols", "into", "message", "using", "%", ".", "also", "parse", "%%", "{}", "placeholders", "for", "plural", "-", "forms", "processing", "." ]
def params_substitution(self, message, symbols): """ Substitutes parameters from symbols into message using %. also parse `%%{}` placeholders for plural-forms processing. Returns: string with parameters Note: *symbols* MUST BE OR tuple OR dict of parameters! """ def sub_plural(m): """String in `%{}` is transformed by this rules: If string starts with `!` or `?` such transformations take place: "!string of words" -> "String of word" (Capitalize) "!!string of words" -> "String Of Word" (Title) "!!!string of words" -> "STRING OF WORD" (Upper) "?word1?number" -> "word1" or "number" (return word1 if number == 1, return number otherwise) "??number" or "?number" -> "" or "number" (as above with word1 = "") "?word1?number?word0" -> "word1" or "number" or "word0" (return word1 if number == 1, return word0 if number == 0, return number otherwise) "?word1?number?" -> "word1" or "number" or "" (as above with word0 = "") "??number?word0" -> "number" or "word0" (as above with word1 = "") "??number?" -> "number" or "" (as above with word1 = word0 = "") "?word1?word[number]" -> "word1" or "word" (return word1 if symbols[number] == 1, return word otherwise) "?word1?[number]" -> "" or "word1" (as above with word = "") "??word[number]" or "?word[number]" -> "" or "word" (as above with word1 = "") "?word1?word?word0[number]" -> "word1" or "word" or "word0" (return word1 if symbols[number] == 1, return word0 if symbols[number] == 0, return word otherwise) "?word1?word?[number]" -> "word1" or "word" or "" (as above with word0 = "") "??word?word0[number]" -> "" or "word" or "word0" (as above with word1 = "") "??word?[number]" -> "" or "word" (as above with word1 = word0 = "") Other strings, (those not starting with `!` or `?`) are processed by self.plural """ def sub_tuple(m): """ word !word, !!word, !!!word ?word1?number ??number, ?number ?word1?number?word0 ?word1?number? ??number?word0 ??number? word[number] !word[number], !!word[number], !!!word[number] ?word1?word[number] ?word1?[number] ??word[number], ?word[number] ?word1?word?word0[number] ?word1?word?[number] ??word?word0[number] ??word?[number] """ w, i = m.group('w', 'i') c = w[0] if c not in '!?': return self.plural(w, symbols[int(i or 0)]) elif c == '?': (p1, sep, p2) = w[1:].partition("?") part1 = p1 if sep else "" (part2, sep, part3) = (p2 if sep else p1).partition("?") if not sep: part3 = part2 if i is None: # ?[word]?number[?number] or ?number if not part2: return m.group(0) num = int(part2) else: # ?[word1]?word[?word0][number] num = int(symbols[int(i or 0)]) return part1 if num == 1 else part3 if num == 0 else part2 elif w.startswith('!!!'): word = w[3:] fun = upper_fun elif w.startswith('!!'): word = w[2:] fun = title_fun else: word = w[1:] fun = cap_fun if i is not None: return to_native(fun(self.plural(word, symbols[int(i)]))) return to_native(fun(word)) def sub_dict(m): """ word(key or num) !word(key or num), !!word(key or num), !!!word(key or num) ?word1?word(key or num) ??word(key or num), ?word(key or num) ?word1?word?word0(key or num) ?word1?word?(key or num) ??word?word0(key or num) ?word1?word?(key or num) ??word?(key or num), ?word?(key or num) """ w, n = m.group('w', 'n') c = w[0] n = int(n) if n.isdigit() else symbols[n] if c not in '!?': return self.plural(w, n) elif c == '?': # ?[word1]?word[?word0](key or num), ?[word1]?word(key or num) or ?word(key or num) (p1, sep, p2) = w[1:].partition("?") part1 = p1 if sep else "" (part2, sep, part3) = (p2 if sep else p1).partition("?") if not sep: part3 = part2 num = int(n) return part1 if num == 1 else part3 if num == 0 else part2 elif w.startswith('!!!'): word = w[3:] fun = upper_fun elif w.startswith('!!'): word = w[2:] fun = title_fun else: word = w[1:] fun = cap_fun s = fun(self.plural(word, n)) return s if PY2 else to_unicode(s) s = m.group(1) part = regex_plural_tuple.sub(sub_tuple, s) if part == s: part = regex_plural_dict.sub(sub_dict, s) if part == s: return m.group(0) return part message = message % symbols message = regex_plural.sub(sub_plural, message) return message
[ "def", "params_substitution", "(", "self", ",", "message", ",", "symbols", ")", ":", "def", "sub_plural", "(", "m", ")", ":", "\"\"\"String in `%{}` is transformed by this rules:\n If string starts with `!` or `?` such transformations\n take place:\n\n \"!string of words\" -> \"String of word\" (Capitalize)\n \"!!string of words\" -> \"String Of Word\" (Title)\n \"!!!string of words\" -> \"STRING OF WORD\" (Upper)\n\n \"?word1?number\" -> \"word1\" or \"number\"\n (return word1 if number == 1,\n return number otherwise)\n \"??number\" or \"?number\" -> \"\" or \"number\"\n (as above with word1 = \"\")\n\n \"?word1?number?word0\" -> \"word1\" or \"number\" or \"word0\"\n (return word1 if number == 1,\n return word0 if number == 0,\n return number otherwise)\n \"?word1?number?\" -> \"word1\" or \"number\" or \"\"\n (as above with word0 = \"\")\n \"??number?word0\" -> \"number\" or \"word0\"\n (as above with word1 = \"\")\n \"??number?\" -> \"number\" or \"\"\n (as above with word1 = word0 = \"\")\n\n \"?word1?word[number]\" -> \"word1\" or \"word\"\n (return word1 if symbols[number] == 1,\n return word otherwise)\n \"?word1?[number]\" -> \"\" or \"word1\"\n (as above with word = \"\")\n \"??word[number]\" or \"?word[number]\" -> \"\" or \"word\"\n (as above with word1 = \"\")\n\n \"?word1?word?word0[number]\" -> \"word1\" or \"word\" or \"word0\"\n (return word1 if symbols[number] == 1,\n return word0 if symbols[number] == 0,\n return word otherwise)\n \"?word1?word?[number]\" -> \"word1\" or \"word\" or \"\"\n (as above with word0 = \"\")\n \"??word?word0[number]\" -> \"\" or \"word\" or \"word0\"\n (as above with word1 = \"\")\n \"??word?[number]\" -> \"\" or \"word\"\n (as above with word1 = word0 = \"\")\n\n Other strings, (those not starting with `!` or `?`)\n are processed by self.plural\n \"\"\"", "def", "sub_tuple", "(", "m", ")", ":", "\"\"\" word\n !word, !!word, !!!word\n ?word1?number\n ??number, ?number\n ?word1?number?word0\n ?word1?number?\n ??number?word0\n ??number?\n\n word[number]\n !word[number], !!word[number], !!!word[number]\n ?word1?word[number]\n ?word1?[number]\n ??word[number], ?word[number]\n ?word1?word?word0[number]\n ?word1?word?[number]\n ??word?word0[number]\n ??word?[number]\n \"\"\"", "w", ",", "i", "=", "m", ".", "group", "(", "'w'", ",", "'i'", ")", "c", "=", "w", "[", "0", "]", "if", "c", "not", "in", "'!?'", ":", "return", "self", ".", "plural", "(", "w", ",", "symbols", "[", "int", "(", "i", "or", "0", ")", "]", ")", "elif", "c", "==", "'?'", ":", "(", "p1", ",", "sep", ",", "p2", ")", "=", "w", "[", "1", ":", "]", ".", "partition", "(", "\"?\"", ")", "part1", "=", "p1", "if", "sep", "else", "\"\"", "(", "part2", ",", "sep", ",", "part3", ")", "=", "(", "p2", "if", "sep", "else", "p1", ")", ".", "partition", "(", "\"?\"", ")", "if", "not", "sep", ":", "part3", "=", "part2", "if", "i", "is", "None", ":", "# ?[word]?number[?number] or ?number", "if", "not", "part2", ":", "return", "m", ".", "group", "(", "0", ")", "num", "=", "int", "(", "part2", ")", "else", ":", "# ?[word1]?word[?word0][number]", "num", "=", "int", "(", "symbols", "[", "int", "(", "i", "or", "0", ")", "]", ")", "return", "part1", "if", "num", "==", "1", "else", "part3", "if", "num", "==", "0", "else", "part2", "elif", "w", ".", "startswith", "(", "'!!!'", ")", ":", "word", "=", "w", "[", "3", ":", "]", "fun", "=", "upper_fun", "elif", "w", ".", "startswith", "(", "'!!'", ")", ":", "word", "=", "w", "[", "2", ":", "]", "fun", "=", "title_fun", "else", ":", "word", "=", "w", "[", "1", ":", "]", "fun", "=", "cap_fun", "if", "i", "is", "not", "None", ":", "return", "to_native", "(", "fun", "(", "self", ".", "plural", "(", "word", ",", "symbols", "[", "int", "(", "i", ")", "]", ")", ")", ")", "return", "to_native", "(", "fun", "(", "word", ")", ")", "def", "sub_dict", "(", "m", ")", ":", "\"\"\" word(key or num)\n !word(key or num), !!word(key or num), !!!word(key or num)\n ?word1?word(key or num)\n ??word(key or num), ?word(key or num)\n ?word1?word?word0(key or num)\n ?word1?word?(key or num)\n ??word?word0(key or num)\n ?word1?word?(key or num)\n ??word?(key or num), ?word?(key or num)\n \"\"\"", "w", ",", "n", "=", "m", ".", "group", "(", "'w'", ",", "'n'", ")", "c", "=", "w", "[", "0", "]", "n", "=", "int", "(", "n", ")", "if", "n", ".", "isdigit", "(", ")", "else", "symbols", "[", "n", "]", "if", "c", "not", "in", "'!?'", ":", "return", "self", ".", "plural", "(", "w", ",", "n", ")", "elif", "c", "==", "'?'", ":", "# ?[word1]?word[?word0](key or num), ?[word1]?word(key or num) or ?word(key or num)", "(", "p1", ",", "sep", ",", "p2", ")", "=", "w", "[", "1", ":", "]", ".", "partition", "(", "\"?\"", ")", "part1", "=", "p1", "if", "sep", "else", "\"\"", "(", "part2", ",", "sep", ",", "part3", ")", "=", "(", "p2", "if", "sep", "else", "p1", ")", ".", "partition", "(", "\"?\"", ")", "if", "not", "sep", ":", "part3", "=", "part2", "num", "=", "int", "(", "n", ")", "return", "part1", "if", "num", "==", "1", "else", "part3", "if", "num", "==", "0", "else", "part2", "elif", "w", ".", "startswith", "(", "'!!!'", ")", ":", "word", "=", "w", "[", "3", ":", "]", "fun", "=", "upper_fun", "elif", "w", ".", "startswith", "(", "'!!'", ")", ":", "word", "=", "w", "[", "2", ":", "]", "fun", "=", "title_fun", "else", ":", "word", "=", "w", "[", "1", ":", "]", "fun", "=", "cap_fun", "s", "=", "fun", "(", "self", ".", "plural", "(", "word", ",", "n", ")", ")", "return", "s", "if", "PY2", "else", "to_unicode", "(", "s", ")", "s", "=", "m", ".", "group", "(", "1", ")", "part", "=", "regex_plural_tuple", ".", "sub", "(", "sub_tuple", ",", "s", ")", "if", "part", "==", "s", ":", "part", "=", "regex_plural_dict", ".", "sub", "(", "sub_dict", ",", "s", ")", "if", "part", "==", "s", ":", "return", "m", ".", "group", "(", "0", ")", "return", "part", "message", "=", "message", "%", "symbols", "message", "=", "regex_plural", ".", "sub", "(", "sub_plural", ",", "message", ")", "return", "message" ]
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/languages.py#L835-L992
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/layers/tftp.py
python
TFTP_RRQ_server.file_in_store
(self)
[]
def file_in_store(self): if self.data is not None: self.blknb = len(self.data)/self.blksize+1 raise self.SEND_FILE()
[ "def", "file_in_store", "(", "self", ")", ":", "if", "self", ".", "data", "is", "not", "None", ":", "self", ".", "blknb", "=", "len", "(", "self", ".", "data", ")", "/", "self", ".", "blksize", "+", "1", "raise", "self", ".", "SEND_FILE", "(", ")" ]
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/layers/tftp.py#L428-L431
google/diff-match-patch
62f2e689f498f9c92dbc588c58750addec9b1654
python3/diff_match_patch.py
python
diff_match_patch.diff_charsToLines
(self, diffs, lineArray)
Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings.
Rehydrate the text in a diff from a string of line hashes to real lines of text.
[ "Rehydrate", "the", "text", "in", "a", "diff", "from", "a", "string", "of", "line", "hashes", "to", "real", "lines", "of", "text", "." ]
def diff_charsToLines(self, diffs, lineArray): """Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings. """ for i in range(len(diffs)): text = [] for char in diffs[i][1]: text.append(lineArray[ord(char)]) diffs[i] = (diffs[i][0], "".join(text))
[ "def", "diff_charsToLines", "(", "self", ",", "diffs", ",", "lineArray", ")", ":", "for", "i", "in", "range", "(", "len", "(", "diffs", ")", ")", ":", "text", "=", "[", "]", "for", "char", "in", "diffs", "[", "i", "]", "[", "1", "]", ":", "text", ".", "append", "(", "lineArray", "[", "ord", "(", "char", ")", "]", ")", "diffs", "[", "i", "]", "=", "(", "diffs", "[", "i", "]", "[", "0", "]", ",", "\"\"", ".", "join", "(", "text", ")", ")" ]
https://github.com/google/diff-match-patch/blob/62f2e689f498f9c92dbc588c58750addec9b1654/python3/diff_match_patch.py#L444-L456
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/pages/wiki/parser/command.py
python
Command.removeQuotes
(text)
return text
Удалить начальные и конечные кавычки, которые остались после разбора параметров
Удалить начальные и конечные кавычки, которые остались после разбора параметров
[ "Удалить", "начальные", "и", "конечные", "кавычки", "которые", "остались", "после", "разбора", "параметров" ]
def removeQuotes(text): """ Удалить начальные и конечные кавычки, которые остались после разбора параметров """ if (len(text) > 0 and (text[0] == text[-1] == "'" or text[0] == text[-1] == '"')): return text[1:-1] return text
[ "def", "removeQuotes", "(", "text", ")", ":", "if", "(", "len", "(", "text", ")", ">", "0", "and", "(", "text", "[", "0", "]", "==", "text", "[", "-", "1", "]", "==", "\"'\"", "or", "text", "[", "0", "]", "==", "text", "[", "-", "1", "]", "==", "'\"'", ")", ")", ":", "return", "text", "[", "1", ":", "-", "1", "]", "return", "text" ]
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/pages/wiki/parser/command.py#L62-L71
Dash-Industry-Forum/dash-live-source-simulator
23cb15c35656a731d9f6d78a30f2713eff2ec20d
dashlivesim/dashlib/boxes.py
python
TRUNBox.__init__
(self, data_offset)
[]
def __init__(self, data_offset): self.samples = [] self.data_offset = data_offset self.use_comp_off = False
[ "def", "__init__", "(", "self", ",", "data_offset", ")", ":", "self", ".", "samples", "=", "[", "]", "self", ".", "data_offset", "=", "data_offset", "self", ".", "use_comp_off", "=", "False" ]
https://github.com/Dash-Industry-Forum/dash-live-source-simulator/blob/23cb15c35656a731d9f6d78a30f2713eff2ec20d/dashlivesim/dashlib/boxes.py#L947-L950
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Script/SConscript.py
python
BuildDefaultGlobals
()
return GlobalDict.copy()
Create a dictionary containing all the default globals for SConstruct and SConscript files.
Create a dictionary containing all the default globals for SConstruct and SConscript files.
[ "Create", "a", "dictionary", "containing", "all", "the", "default", "globals", "for", "SConstruct", "and", "SConscript", "files", "." ]
def BuildDefaultGlobals(): """ Create a dictionary containing all the default globals for SConstruct and SConscript files. """ global GlobalDict if GlobalDict is None: GlobalDict = {} import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] return GlobalDict.copy()
[ "def", "BuildDefaultGlobals", "(", ")", ":", "global", "GlobalDict", "if", "GlobalDict", "is", "None", ":", "GlobalDict", "=", "{", "}", "import", "SCons", ".", "Script", "d", "=", "SCons", ".", "Script", ".", "__dict__", "def", "not_a_module", "(", "m", ",", "d", "=", "d", ",", "mtype", "=", "type", "(", "SCons", ".", "Script", ")", ")", ":", "return", "not", "isinstance", "(", "d", "[", "m", "]", ",", "mtype", ")", "for", "m", "in", "filter", "(", "not_a_module", ",", "dir", "(", "SCons", ".", "Script", ")", ")", ":", "GlobalDict", "[", "m", "]", "=", "d", "[", "m", "]", "return", "GlobalDict", ".", "copy", "(", ")" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Script/SConscript.py#L663-L680
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/pycparser/c_parser.py
python
CParser.p_selection_statement_2
(self, p)
selection_statement : IF LPAREN expression RPAREN statement ELSE statement
selection_statement : IF LPAREN expression RPAREN statement ELSE statement
[ "selection_statement", ":", "IF", "LPAREN", "expression", "RPAREN", "statement", "ELSE", "statement" ]
def p_selection_statement_2(self, p): """ selection_statement : IF LPAREN expression RPAREN statement ELSE statement """ p[0] = c_ast.If(p[3], p[5], p[7], self._coord(p.lineno(1)))
[ "def", "p_selection_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "c_ast", ".", "If", "(", "p", "[", "3", "]", ",", "p", "[", "5", "]", ",", "p", "[", "7", "]", ",", "self", ".", "_coord", "(", "p", ".", "lineno", "(", "1", ")", ")", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/pycparser/c_parser.py#L1359-L1361
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/tagger.py
python
longversion
()
[]
def longversion(): print(versions.as_string())
[ "def", "longversion", "(", ")", ":", "print", "(", "versions", ".", "as_string", "(", ")", ")" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/tagger.py#L1002-L1003
HaoyuHu/bert-multi-gpu
66dc4ec8af70ec13e44749dae2ca8e5928f4b02e
modeling.py
python
embedding_lookup
(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False)
return (output, embedding_table)
Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.gather()`. Returns: float Tensor of shape [batch_size, seq_length, embedding_size].
Looks up words embeddings for id tensor.
[ "Looks", "up", "words", "embeddings", "for", "id", "tensor", "." ]
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.gather()`. Returns: float Tensor of shape [batch_size, seq_length, embedding_size]. """ # This function assumes that the input is of shape [batch_size, seq_length, # num_inputs]. # # If the input is a 2D tensor of shape [batch_size, seq_length], we # reshape to [batch_size, seq_length, 1]. if input_ids.shape.ndims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) flat_input_ids = tf.reshape(input_ids, [-1]) if use_one_hot_embeddings: one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output = tf.matmul(one_hot_input_ids, embedding_table) else: output = tf.gather(embedding_table, flat_input_ids) input_shape = get_shape_list(input_ids) output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) return (output, embedding_table)
[ "def", "embedding_lookup", "(", "input_ids", ",", "vocab_size", ",", "embedding_size", "=", "128", ",", "initializer_range", "=", "0.02", ",", "word_embedding_name", "=", "\"word_embeddings\"", ",", "use_one_hot_embeddings", "=", "False", ")", ":", "# This function assumes that the input is of shape [batch_size, seq_length,", "# num_inputs].", "#", "# If the input is a 2D tensor of shape [batch_size, seq_length], we", "# reshape to [batch_size, seq_length, 1].", "if", "input_ids", ".", "shape", ".", "ndims", "==", "2", ":", "input_ids", "=", "tf", ".", "expand_dims", "(", "input_ids", ",", "axis", "=", "[", "-", "1", "]", ")", "embedding_table", "=", "tf", ".", "get_variable", "(", "name", "=", "word_embedding_name", ",", "shape", "=", "[", "vocab_size", ",", "embedding_size", "]", ",", "initializer", "=", "create_initializer", "(", "initializer_range", ")", ")", "flat_input_ids", "=", "tf", ".", "reshape", "(", "input_ids", ",", "[", "-", "1", "]", ")", "if", "use_one_hot_embeddings", ":", "one_hot_input_ids", "=", "tf", ".", "one_hot", "(", "flat_input_ids", ",", "depth", "=", "vocab_size", ")", "output", "=", "tf", ".", "matmul", "(", "one_hot_input_ids", ",", "embedding_table", ")", "else", ":", "output", "=", "tf", ".", "gather", "(", "embedding_table", ",", "flat_input_ids", ")", "input_shape", "=", "get_shape_list", "(", "input_ids", ")", "output", "=", "tf", ".", "reshape", "(", "output", ",", "input_shape", "[", "0", ":", "-", "1", "]", "+", "[", "input_shape", "[", "-", "1", "]", "*", "embedding_size", "]", ")", "return", "(", "output", ",", "embedding_table", ")" ]
https://github.com/HaoyuHu/bert-multi-gpu/blob/66dc4ec8af70ec13e44749dae2ca8e5928f4b02e/modeling.py#L383-L428
nwojke/deep_sort
280b8bdb255f223813ff4a8679f3e1321b08cdfc
application_util/image_viewer.py
python
ImageViewer.annotate
(self, x, y, text)
Draws a text string at a given location. Parameters ---------- x : int | float Bottom-left corner of the text in the image (x-axis). y : int | float Bottom-left corner of the text in the image (y-axis). text : str The text to be drawn.
Draws a text string at a given location.
[ "Draws", "a", "text", "string", "at", "a", "given", "location", "." ]
def annotate(self, x, y, text): """Draws a text string at a given location. Parameters ---------- x : int | float Bottom-left corner of the text in the image (x-axis). y : int | float Bottom-left corner of the text in the image (y-axis). text : str The text to be drawn. """ cv2.putText(self.image, text, (int(x), int(y)), cv2.FONT_HERSHEY_PLAIN, 2, self.text_color, 2)
[ "def", "annotate", "(", "self", ",", "x", ",", "y", ",", "text", ")", ":", "cv2", ".", "putText", "(", "self", ".", "image", ",", "text", ",", "(", "int", "(", "x", ")", ",", "int", "(", "y", ")", ")", ",", "cv2", ".", "FONT_HERSHEY_PLAIN", ",", "2", ",", "self", ".", "text_color", ",", "2", ")" ]
https://github.com/nwojke/deep_sort/blob/280b8bdb255f223813ff4a8679f3e1321b08cdfc/application_util/image_viewer.py#L213-L227
treeio/treeio
bae3115f4015aad2cbc5ab45572232ceec990495
treeio/core/administration/forms.py
python
UserForm.clean_disabled
(self)
return self.cleaned_data['disabled']
Ensure the admin does not go over subscription limit by re-enabling users
Ensure the admin does not go over subscription limit by re-enabling users
[ "Ensure", "the", "admin", "does", "not", "go", "over", "subscription", "limit", "by", "re", "-", "enabling", "users" ]
def clean_disabled(self): "Ensure the admin does not go over subscription limit by re-enabling users" enable = not self.cleaned_data['disabled'] if self.instance and self.instance.id and enable and self.instance.disabled: user_limit = getattr( settings, 'HARDTREE_SUBSCRIPTION_USER_LIMIT', 0) if user_limit > 0: user_number = User.objects.filter(disabled=False).count() if user_number >= user_limit: raise forms.ValidationError( _("Sorry, but your subscription does not allow more than %d users. You're currently at your limit.") % (user_limit)) return self.cleaned_data['disabled']
[ "def", "clean_disabled", "(", "self", ")", ":", "enable", "=", "not", "self", ".", "cleaned_data", "[", "'disabled'", "]", "if", "self", ".", "instance", "and", "self", ".", "instance", ".", "id", "and", "enable", "and", "self", ".", "instance", ".", "disabled", ":", "user_limit", "=", "getattr", "(", "settings", ",", "'HARDTREE_SUBSCRIPTION_USER_LIMIT'", ",", "0", ")", "if", "user_limit", ">", "0", ":", "user_number", "=", "User", ".", "objects", ".", "filter", "(", "disabled", "=", "False", ")", ".", "count", "(", ")", "if", "user_number", ">=", "user_limit", ":", "raise", "forms", ".", "ValidationError", "(", "_", "(", "\"Sorry, but your subscription does not allow more than %d users. You're currently at your limit.\"", ")", "%", "(", "user_limit", ")", ")", "return", "self", ".", "cleaned_data", "[", "'disabled'", "]" ]
https://github.com/treeio/treeio/blob/bae3115f4015aad2cbc5ab45572232ceec990495/treeio/core/administration/forms.py#L275-L286
avocado-framework/avocado
1f9b3192e8ba47d029c33fe21266bd113d17811f
avocado/utils/multipath.py
python
get_multipath_wwid
(mpath)
Get the wwid binding for given mpath name :return: Multipath wwid :rtype: str
Get the wwid binding for given mpath name
[ "Get", "the", "wwid", "binding", "for", "given", "mpath", "name" ]
def get_multipath_wwid(mpath): """ Get the wwid binding for given mpath name :return: Multipath wwid :rtype: str """ cmd = "multipathd show maps format '%n %w'" try: wwids = process.run(cmd, ignore_status=True, sudo=True, shell=True).stdout_text except process.CmdError as ex: raise MPException("Multipathd Command Failed : %s " % ex) for wwid in wwids.splitlines(): if mpath in wwid: return wwid.split()[1]
[ "def", "get_multipath_wwid", "(", "mpath", ")", ":", "cmd", "=", "\"multipathd show maps format '%n %w'\"", "try", ":", "wwids", "=", "process", ".", "run", "(", "cmd", ",", "ignore_status", "=", "True", ",", "sudo", "=", "True", ",", "shell", "=", "True", ")", ".", "stdout_text", "except", "process", ".", "CmdError", "as", "ex", ":", "raise", "MPException", "(", "\"Multipathd Command Failed : %s \"", "%", "ex", ")", "for", "wwid", "in", "wwids", ".", "splitlines", "(", ")", ":", "if", "mpath", "in", "wwid", ":", "return", "wwid", ".", "split", "(", ")", "[", "1", "]" ]
https://github.com/avocado-framework/avocado/blob/1f9b3192e8ba47d029c33fe21266bd113d17811f/avocado/utils/multipath.py#L116-L131
interpretml/interpret-community
84d86b7514fd9812f1497329bf1c4c9fc864370e
python/interpret_community/explanation/explanation.py
python
_get_local_explanation_row
(explainer, evaluation_examples, i, batch_size)
return explainer.explain_local(rows)
Return the local explanation for the sliced evaluation_examples. :param explainer: The explainer used to create local explanations. :type explainer: BaseExplainer :param evaluation_examples: The evaluation examples. :type evaluation_examples: DatasetWrapper :param i: The index to slice from. :type i: int :param batch_size: If include_local is True, specifies the batch size for aggregating local explanations to global. :type batch_size: int :return: The local explanation for the slice of rows. :rtype: DynamicLocalExplanation
Return the local explanation for the sliced evaluation_examples.
[ "Return", "the", "local", "explanation", "for", "the", "sliced", "evaluation_examples", "." ]
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size): """Return the local explanation for the sliced evaluation_examples. :param explainer: The explainer used to create local explanations. :type explainer: BaseExplainer :param evaluation_examples: The evaluation examples. :type evaluation_examples: DatasetWrapper :param i: The index to slice from. :type i: int :param batch_size: If include_local is True, specifies the batch size for aggregating local explanations to global. :type batch_size: int :return: The local explanation for the slice of rows. :rtype: DynamicLocalExplanation """ rows = evaluation_examples.typed_wrapper_func(evaluation_examples.dataset[i:i + batch_size]) return explainer.explain_local(rows)
[ "def", "_get_local_explanation_row", "(", "explainer", ",", "evaluation_examples", ",", "i", ",", "batch_size", ")", ":", "rows", "=", "evaluation_examples", ".", "typed_wrapper_func", "(", "evaluation_examples", ".", "dataset", "[", "i", ":", "i", "+", "batch_size", "]", ")", "return", "explainer", ".", "explain_local", "(", "rows", ")" ]
https://github.com/interpretml/interpret-community/blob/84d86b7514fd9812f1497329bf1c4c9fc864370e/python/interpret_community/explanation/explanation.py#L1645-L1661
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/set/space.py
python
LinearSpaceElement.__cmp__
(self, other)
Comparsion not implemented.
Comparsion not implemented.
[ "Comparsion", "not", "implemented", "." ]
def __cmp__(self, other): """Comparsion not implemented.""" # Stops python 2 from allowing comparsion of arbitrary objects raise TypeError('unorderable types: {}, {}' ''.format(self.__class__.__name__, type(other)))
[ "def", "__cmp__", "(", "self", ",", "other", ")", ":", "# Stops python 2 from allowing comparsion of arbitrary objects", "raise", "TypeError", "(", "'unorderable types: {}, {}'", "''", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "type", "(", "other", ")", ")", ")" ]
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/set/space.py#L815-L819