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
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/core/featurizers/precomputation.py
python
MessageContainerForCoreFeaturization.derive_messages_from_domain_and_add
(self, domain: Domain)
Adds all lookup table entries that can be derived from the domain. That is, all action names, action texts, and intents defined in the domain will be turned into a (separate) messages and added to this lookup table. Args: domain: the domain from which we extract the substates
Adds all lookup table entries that can be derived from the domain.
[ "Adds", "all", "lookup", "table", "entries", "that", "can", "be", "derived", "from", "the", "domain", "." ]
def derive_messages_from_domain_and_add(self, domain: Domain) -> None: """Adds all lookup table entries that can be derived from the domain. That is, all action names, action texts, and intents defined in the domain will be turned into a (separate) messages and added to this lookup table. Args: domain: the domain from which we extract the substates """ if ( domain.action_texts and domain.action_names_or_texts[-len(domain.action_texts) :] != domain.action_texts ): raise NotImplementedError( "We assumed that domain's `action_names_or_texts` start with a list of " "all action names, followed by the action texts. " "Please update the code to grab the action_name and action_texts from " "the domain correctly." ) action_texts = domain.action_texts action_names = domain.action_names_or_texts[ slice(0, -len(domain.action_texts) if domain.action_texts else None) ] for key_attribute, actions in [ (ACTION_NAME, action_names), (ACTION_TEXT, action_texts), ]: for action in actions: self.add(Message({key_attribute: action})) for intent in domain.intent_properties.keys(): self.add(Message({INTENT: intent}))
[ "def", "derive_messages_from_domain_and_add", "(", "self", ",", "domain", ":", "Domain", ")", "->", "None", ":", "if", "(", "domain", ".", "action_texts", "and", "domain", ".", "action_names_or_texts", "[", "-", "len", "(", "domain", ".", "action_texts", ")", ...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/core/featurizers/precomputation.py#L248-L281
horazont/aioxmpp
c701e6399c90a6bb9bec0349018a03bd7b644cde
aioxmpp/xso/model.py
python
ChildList.from_events
(self, instance, ev_args, ctx)
return obj
Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list.
Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list.
[ "Like", ":", "meth", ":", ".", "Child", ".", "from_events", "but", "instead", "of", "replacing", "the", "attribute", "value", "the", "new", "object", "is", "appended", "to", "the", "list", "." ]
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list. """ obj = yield from self._process(instance, ev_args, ctx) self.__get__(instance, type(instance)).append(obj) return obj
[ "def", "from_events", "(", "self", ",", "instance", ",", "ev_args", ",", "ctx", ")", ":", "obj", "=", "yield", "from", "self", ".", "_process", "(", "instance", ",", "ev_args", ",", "ctx", ")", "self", ".", "__get__", "(", "instance", ",", "type", "(...
https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/xso/model.py#L637-L645
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/pandas/plotting/_misc.py
python
bootstrap_plot
(series, fig=None, size=50, samples=500, **kwds)
return fig
Bootstrap plot. Parameters: ----------- series: Time series fig: matplotlib figure object, optional size: number of data points to consider during each sampling samples: number of times the bootstrap procedure is performed kwds: optional keyword arguments for plotting commands, must be accepted by both hist and plot Returns: -------- fig: matplotlib figure
Bootstrap plot.
[ "Bootstrap", "plot", "." ]
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): """Bootstrap plot. Parameters: ----------- series: Time series fig: matplotlib figure object, optional size: number of data points to consider during each sampling samples: number of times the bootstrap procedure is performed kwds: optional keyword arguments for plotting commands, must be accepted by both hist and plot Returns: -------- fig: matplotlib figure """ import random import matplotlib.pyplot as plt # random.sample(ndarray, int) fails on python 3.3, sigh data = list(series.values) samplings = [random.sample(data, size) for _ in range(samples)] means = np.array([np.mean(sampling) for sampling in samplings]) medians = np.array([np.median(sampling) for sampling in samplings]) midranges = np.array([(min(sampling) + max(sampling)) * 0.5 for sampling in samplings]) if fig is None: fig = plt.figure() x = lrange(samples) axes = [] ax1 = fig.add_subplot(2, 3, 1) ax1.set_xlabel("Sample") axes.append(ax1) ax1.plot(x, means, **kwds) ax2 = fig.add_subplot(2, 3, 2) ax2.set_xlabel("Sample") axes.append(ax2) ax2.plot(x, medians, **kwds) ax3 = fig.add_subplot(2, 3, 3) ax3.set_xlabel("Sample") axes.append(ax3) ax3.plot(x, midranges, **kwds) ax4 = fig.add_subplot(2, 3, 4) ax4.set_xlabel("Mean") axes.append(ax4) ax4.hist(means, **kwds) ax5 = fig.add_subplot(2, 3, 5) ax5.set_xlabel("Median") axes.append(ax5) ax5.hist(medians, **kwds) ax6 = fig.add_subplot(2, 3, 6) ax6.set_xlabel("Midrange") axes.append(ax6) ax6.hist(midranges, **kwds) for axis in axes: plt.setp(axis.get_xticklabels(), fontsize=8) plt.setp(axis.get_yticklabels(), fontsize=8) return fig
[ "def", "bootstrap_plot", "(", "series", ",", "fig", "=", "None", ",", "size", "=", "50", ",", "samples", "=", "500", ",", "*", "*", "kwds", ")", ":", "import", "random", "import", "matplotlib", ".", "pyplot", "as", "plt", "# random.sample(ndarray, int) fai...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/plotting/_misc.py#L325-L383
joxeankoret/pyew
8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8
vtrace/__init__.py
python
Trace.release
(self)
Release resources for this tracer. This API should be called once you are done with the trace.
Release resources for this tracer. This API should be called once you are done with the trace.
[ "Release", "resources", "for", "this", "tracer", ".", "This", "API", "should", "be", "called", "once", "you", "are", "done", "with", "the", "trace", "." ]
def release(self): ''' Release resources for this tracer. This API should be called once you are done with the trace. ''' if not self._released: self._released = True if self.attached: self.detach() self._cleanupResources()
[ "def", "release", "(", "self", ")", ":", "if", "not", "self", ".", "_released", ":", "self", ".", "_released", "=", "True", "if", "self", ".", "attached", ":", "self", ".", "detach", "(", ")", "self", ".", "_cleanupResources", "(", ")" ]
https://github.com/joxeankoret/pyew/blob/8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8/vtrace/__init__.py#L324-L333
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/BaseHTTPServer.py
python
BaseHTTPRequestHandler.address_string
(self)
return socket.getfqdn(host)
Return the client address formatted for logging. This version looks up the full hostname using gethostbyaddr(), and tries to find a name that contains at least one dot.
Return the client address formatted for logging.
[ "Return", "the", "client", "address", "formatted", "for", "logging", "." ]
def address_string(self): """Return the client address formatted for logging. This version looks up the full hostname using gethostbyaddr(), and tries to find a name that contains at least one dot. """ host, port = self.client_address[:2] return socket.getfqdn(host)
[ "def", "address_string", "(", "self", ")", ":", "host", ",", "port", "=", "self", ".", "client_address", "[", ":", "2", "]", "return", "socket", ".", "getfqdn", "(", "host", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/BaseHTTPServer.py#L500-L509
xjsender/haoide
717dd706db1169bfc41e818ac6fc6cd9a0aef12d
util.py
python
list2csv
(file_path, records, NOT_INCLUDED_COLUMNS=["urls", "attributes"])
convert simple dict in list to csv Arguments: * records -- [{"1": 1}, {"2": 2}]
convert simple dict in list to csv
[ "convert", "simple", "dict", "in", "list", "to", "csv" ]
def list2csv(file_path, records, NOT_INCLUDED_COLUMNS=["urls", "attributes"]): """convert simple dict in list to csv Arguments: * records -- [{"1": 1}, {"2": 2}] """ # If records size is 0, just return if len(records) == 0: return "No Elements" headers = [k.encode('utf-8') for k in records[0] if k not in NOT_INCLUDED_COLUMNS] with open(file_path, "wb") as fp: fp.write(b",".join(headers) + b"\n") for record in records: values = [] for k in headers: strk = str(k, encoding="utf-8") if strk not in record: values.append(b"") else: values.append(('"%s"' % none_value(record[strk])).encode("utf-8")) fp.write(b",".join(values) + b"\n")
[ "def", "list2csv", "(", "file_path", ",", "records", ",", "NOT_INCLUDED_COLUMNS", "=", "[", "\"urls\"", ",", "\"attributes\"", "]", ")", ":", "# If records size is 0, just return", "if", "len", "(", "records", ")", "==", "0", ":", "return", "\"No Elements\"", "h...
https://github.com/xjsender/haoide/blob/717dd706db1169bfc41e818ac6fc6cd9a0aef12d/util.py#L2509-L2530
kivy/kivy-designer
20343184a28c2851faf0c1ab451d0286d147a441
designer/components/playground_size_selector.py
python
PlaygroundSizeSelector.on_playground
(self, *_)
Create a :class: `~designer.components.playground_size_selector.PlaygroundSizeView` for the current playground.
Create a :class: `~designer.components.playground_size_selector.PlaygroundSizeView` for the current playground.
[ "Create", "a", ":", "class", ":", "~designer", ".", "components", ".", "playground_size_selector", ".", "PlaygroundSizeView", "for", "the", "current", "playground", "." ]
def on_playground(self, *_): '''Create a :class: `~designer.components.playground_size_selector.PlaygroundSizeView` for the current playground. ''' self.view = PlaygroundSizeView(selected_size=self.playground.size) self.view.bind(selected_size=self._update_playground) self.view.bind(selected_size_name=self.setter('text')) self.text = self.view.selected_size_name
[ "def", "on_playground", "(", "self", ",", "*", "_", ")", ":", "self", ".", "view", "=", "PlaygroundSizeView", "(", "selected_size", "=", "self", ".", "playground", ".", "size", ")", "self", ".", "view", ".", "bind", "(", "selected_size", "=", "self", "...
https://github.com/kivy/kivy-designer/blob/20343184a28c2851faf0c1ab451d0286d147a441/designer/components/playground_size_selector.py#L28-L37
djblets/djblets
0496e1ec49e43d43d776768c9fc5b6f8af56ec2c
djblets/util/templatetags/djblets_email.py
python
condense
(context, nodelist, max_newlines=3)
return text
Condenses a block of text. This will ensure that there are never more than the given number of consecutive newlines. It's particularly useful when formatting plain text output, to avoid issues with template tags adding unwanted newlines.
Condenses a block of text.
[ "Condenses", "a", "block", "of", "text", "." ]
def condense(context, nodelist, max_newlines=3): """Condenses a block of text. This will ensure that there are never more than the given number of consecutive newlines. It's particularly useful when formatting plain text output, to avoid issues with template tags adding unwanted newlines. """ text = nodelist.render(context).strip() text = re.sub(r'\n{%d,}' % (max_newlines + 1), '\n' * max_newlines, text) return text
[ "def", "condense", "(", "context", ",", "nodelist", ",", "max_newlines", "=", "3", ")", ":", "text", "=", "nodelist", ".", "render", "(", "context", ")", ".", "strip", "(", ")", "text", "=", "re", ".", "sub", "(", "r'\\n{%d,}'", "%", "(", "max_newlin...
https://github.com/djblets/djblets/blob/0496e1ec49e43d43d776768c9fc5b6f8af56ec2c/djblets/util/templatetags/djblets_email.py#L50-L59
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op4/op4.py
python
OP4._read_real_sparse_ascii_new
(self, op4, iline, nrows, ncols, line_size, line, dtype, is_big_mat)
return A, iline
Reads a sparse real ASCII matrix
Reads a sparse real ASCII matrix
[ "Reads", "a", "sparse", "real", "ASCII", "matrix" ]
def _read_real_sparse_ascii_new(self, op4, iline, nrows, ncols, line_size, line, dtype, is_big_mat): """Reads a sparse real ASCII matrix""" self.log.debug('_read_real_sparse_ascii') rows = [] cols = [] entries = [] nloops = 0 was_broken = False while 1: if nloops > 0 and not was_broken: line = op4.readline().rstrip() iline += 1 was_broken = False icol, irow, nwords = line.split() icol = int(icol) if icol > ncols: break irow = int(irow) nwords = int(nwords) # This loop condition is overly complicated, but the first time # it will always execute. # Later if there is a sparse continuation line marker of # 1 (very large) integer, there will be no scientific notation value. # There also may be another sparse marker with 2 values. These are not large. # The scientific check prevents you from getting stuck in an infinite # loop b/c no lines are read if there was one float value. # The check for 1 (or 2) integers is to prevent the check for 3 integers # which starts a new column. We only want to continue a column. run_loop = True sline = line.strip().split() # next sparse entry jrow1 = len(rows) while (len(sline) == 1 or len(sline) == 2) and 'E' not in line or run_loop: if is_big_mat: irow, iline = self._get_irow_big_ascii(op4, iline, line, sline, irow) else: irow, iline = self._get_irow_small_ascii(op4, iline, line, sline, irow) run_loop = False #is_done_reading_row = False while nwords: line = op4.readline().rstrip() iline += 1 nwords_in_line = line.count('E') if nwords_in_line == 0: was_broken = True break irows = list(range(irow, irow + nwords_in_line)) n = 0 for unused_i in range(nwords_in_line): word = line[n:n + line_size] entries.append(word) n += line_size rows.extend(irows) #icols = [icol] * nwords_in_line #cols.extend(icols) irow += nwords_in_line #assert len(rows) == len(cols), 'rows=%s\ncols=%s' % (rows, cols) #assert len(rows) == len(entries) nwords -= nwords_in_line sline = line.strip().split() nloops += 1 jrow2 = len(rows) icols = [icol] * (jrow2 - jrow1) cols.append(icols) op4.readline() iline += 1 #if rows == []: # NULL matrix #raise NotImplementedError() cols = np.hstack(cols) rows = array(rows, dtype='int32') - 1 cols = array(cols, dtype='int32') - 1 A = coo_matrix((entries, (rows, cols)), shape=(nrows, ncols), dtype=dtype) #print("type = %s %s" % (type(A),type(A.toarray()))) #A = A.toarray() return A, iline
[ "def", "_read_real_sparse_ascii_new", "(", "self", ",", "op4", ",", "iline", ",", "nrows", ",", "ncols", ",", "line_size", ",", "line", ",", "dtype", ",", "is_big_mat", ")", ":", "self", ".", "log", ".", "debug", "(", "'_read_real_sparse_ascii'", ")", "row...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op4/op4.py#L288-L373
pyside/PySide
bcf6058e9d0e8513f58a0f1062b428ea7eb03f0c
doc/inheritance_diagram.py
python
InheritanceGraph._class_info
(self, classes, show_builtins, parts)
return all_classes.values()
Return name and bases for all classes that are ancestors of *classes*. *parts* gives the number of dotted name parts that is removed from the displayed node names.
Return name and bases for all classes that are ancestors of *classes*.
[ "Return", "name", "and", "bases", "for", "all", "classes", "that", "are", "ancestors", "of", "*", "classes", "*", "." ]
def _class_info(self, classes, show_builtins, parts): """Return name and bases for all classes that are ancestors of *classes*. *parts* gives the number of dotted name parts that is removed from the displayed node names. """ all_classes = {} builtins = __builtins__.values() def recurse(cls): if not show_builtins and cls in builtins: return nodename = self.class_name(cls, parts) fullname = self.class_name(cls, 0) baselist = [] all_classes[cls] = (nodename, fullname, baselist) for base in cls.__bases__: if not show_builtins and base in builtins: continue if base.__name__ == "Object" and base.__module__ == "Shiboken": continue baselist.append(self.class_name(base, parts)) if base not in all_classes: recurse(base) for cls in classes: recurse(cls) return all_classes.values()
[ "def", "_class_info", "(", "self", ",", "classes", ",", "show_builtins", ",", "parts", ")", ":", "all_classes", "=", "{", "}", "builtins", "=", "__builtins__", ".", "values", "(", ")", "def", "recurse", "(", "cls", ")", ":", "if", "not", "show_builtins",...
https://github.com/pyside/PySide/blob/bcf6058e9d0e8513f58a0f1062b428ea7eb03f0c/doc/inheritance_diagram.py#L139-L170
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Engine/IO/plexos.py
python
PlexosElement.__init__
(self, name)
Generic element constructor :param name: Name of the element
Generic element constructor :param name: Name of the element
[ "Generic", "element", "constructor", ":", "param", "name", ":", "Name", "of", "the", "element" ]
def __init__(self, name): """ Generic element constructor :param name: Name of the element """ self.name = name
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name" ]
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Engine/IO/plexos.py#L105-L110
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/util/versions.py
python
BaseVersion.__lt__
(self, other)
return self.tuple() < other.tuple()
[]
def __lt__(self, other): if not hasattr(other, "tuple"): raise ValueError("Can't compare %r with %r" % (self, other)) return self.tuple() < other.tuple()
[ "def", "__lt__", "(", "self", ",", "other", ")", ":", "if", "not", "hasattr", "(", "other", ",", "\"tuple\"", ")", ":", "raise", "ValueError", "(", "\"Can't compare %r with %r\"", "%", "(", "self", ",", "other", ")", ")", "return", "self", ".", "tuple", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/util/versions.py#L56-L59
geekori/pyqt5
49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c
src/table_tree/ColumnSort.py
python
ColumnSort.order
(self)
[]
def order(self): if self.orderType == Qt.DescendingOrder: self.orderType = Qt.AscendingOrder else: self.orderType = Qt.DescendingOrder self.tableWidget.sortItems(2,self.orderType)
[ "def", "order", "(", "self", ")", ":", "if", "self", ".", "orderType", "==", "Qt", ".", "DescendingOrder", ":", "self", ".", "orderType", "=", "Qt", ".", "AscendingOrder", "else", ":", "self", ".", "orderType", "=", "Qt", ".", "DescendingOrder", "self", ...
https://github.com/geekori/pyqt5/blob/49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c/src/table_tree/ColumnSort.py#L68-L73
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team.py
python
GroupMembersRemoveError.is_group_not_in_team
(self)
return self._tag == 'group_not_in_team'
Check if the union tag is ``group_not_in_team``. :rtype: bool
Check if the union tag is ``group_not_in_team``.
[ "Check", "if", "the", "union", "tag", "is", "group_not_in_team", "." ]
def is_group_not_in_team(self): """ Check if the union tag is ``group_not_in_team``. :rtype: bool """ return self._tag == 'group_not_in_team'
[ "def", "is_group_not_in_team", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'group_not_in_team'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team.py#L3326-L3332
salabim/salabim
e0de846b042daf2dc71aaf43d8adc6486b57f376
salabim.py
python
Environment.is_dark
(self, colorspec)
Arguments --------- colorspec : colorspec color to check Returns ------- : bool True, if the colorspec is dark (rather black than white) |n| False, if the colorspec is light (rather white than black |n| if colorspec has alpha=0 (total transparent), the background_color will be tested
Arguments --------- colorspec : colorspec color to check
[ "Arguments", "---------", "colorspec", ":", "colorspec", "color", "to", "check" ]
def is_dark(self, colorspec): """ Arguments --------- colorspec : colorspec color to check Returns ------- : bool True, if the colorspec is dark (rather black than white) |n| False, if the colorspec is light (rather white than black |n| if colorspec has alpha=0 (total transparent), the background_color will be tested """ rgba = self.colorspec_to_tuple(colorspec) if rgba[3] == 0: return self.is_dark(self.colorspec_to_tuple(("bg", 255))) luma = ((0.299 * rgba[0]) + (0.587 * rgba[1]) + (0.114 * rgba[2])) / 255 if luma > 0.5: return False else: return True
[ "def", "is_dark", "(", "self", ",", "colorspec", ")", ":", "rgba", "=", "self", ".", "colorspec_to_tuple", "(", "colorspec", ")", "if", "rgba", "[", "3", "]", "==", "0", ":", "return", "self", ".", "is_dark", "(", "self", ".", "colorspec_to_tuple", "("...
https://github.com/salabim/salabim/blob/e0de846b042daf2dc71aaf43d8adc6486b57f376/salabim.py#L7686-L7707
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/noarch/OpenSSL/SSL.py
python
Context.add_client_ca
(self, certificate_authority)
Add the CA certificate to the list of preferred signers for this context. The list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authority: certificate authority's X509 certificate. :return: None
Add the CA certificate to the list of preferred signers for this context.
[ "Add", "the", "CA", "certificate", "to", "the", "list", "of", "preferred", "signers", "for", "this", "context", "." ]
def add_client_ca(self, certificate_authority): """ Add the CA certificate to the list of preferred signers for this context. The list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authority: certificate authority's X509 certificate. :return: None """ if not isinstance(certificate_authority, X509): raise TypeError("certificate_authority must be an X509 instance") add_result = _lib.SSL_CTX_add_client_CA( self._context, certificate_authority._x509) if not add_result: # TODO: This is untested. _raise_current_error()
[ "def", "add_client_ca", "(", "self", ",", "certificate_authority", ")", ":", "if", "not", "isinstance", "(", "certificate_authority", ",", "X509", ")", ":", "raise", "TypeError", "(", "\"certificate_authority must be an X509 instance\"", ")", "add_result", "=", "_lib"...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/noarch/OpenSSL/SSL.py#L884-L902
fkie/multimaster_fkie
3d23df29d25d71a75c66bbd3cc6e9cbb255724d8
fkie_node_manager/src/fkie_node_manager/main_window.py
python
MainWindow.on_start_robot_clicked
(self)
Tries to start the master_discovery node on the machine requested by a dialog.
Tries to start the master_discovery node on the machine requested by a dialog.
[ "Tries", "to", "start", "the", "master_discovery", "node", "on", "the", "machine", "requested", "by", "a", "dialog", "." ]
def on_start_robot_clicked(self): ''' Tries to start the master_discovery node on the machine requested by a dialog. ''' # get the history list user_list = [self.userComboBox.itemText(i) for i in reversed(range(self.userComboBox.count()))] user_list.insert(0, 'last used') params_optional = {'Discovery type': {':type': 'string', ':value': ['master_discovery', 'zeroconf']}, 'ROS Master Name': {':type': 'string', ':value': 'autodetect'}, 'ROS Master URI': {':type': 'string', ':value': 'ROS_MASTER_URI'}, 'Robot hosts': {':type': 'string', ':value': ''}, 'Username': {':type': 'string', ':value': user_list}, 'MCast Group': {':type': 'string', ':value': '226.0.0.0'}, 'Heartbeat [Hz]': {':type': 'float', ':value': 0.5} } params = {'Host': {':type': 'string', ':value': 'localhost'}, 'Network(0..99)': {':type': 'int', ':value': str(self.mcast_port - 11511)}, 'Start sync': {':type': 'bool', ':value': nm.settings().start_sync_with_discovery}, 'Start daemon': {':type': 'bool', ':value': nm.settings().start_daemon_with_discovery}, 'Optional Parameter': params_optional } dia = ParameterDialog(params, sidebar_var='Host', store_geometry="start_robot_dialog") dia.setFilterVisible(False) dia.setWindowTitle('Start discovery') dia.setFocusField('Host') if dia.exec_(): try: params = dia.getKeywords(only_changed=False) hostnames = params['Host'] if isinstance(params['Host'], list) else [params['Host']] port = params['Network(0..99)'] start_sync = params['Start sync'] start_daemon = params['Start daemon'] discovery_type = params['Optional Parameter']['Discovery type'] mastername = 'autodetect' masteruri = 'ROS_MASTER_URI' if len(hostnames) < 2: mastername = params['Optional Parameter']['ROS Master Name'] masteruri = params['Optional Parameter']['ROS Master URI'] robot_hosts = params['Optional Parameter']['Robot hosts'] username = params['Optional Parameter']['Username'] mcast_group = params['Optional Parameter']['MCast Group'] heartbeat_hz = params['Optional Parameter']['Heartbeat [Hz]'] if robot_hosts: robot_hosts = robot_hosts.replace(' ', ',') robot_hosts = robot_hosts.replace(',,', ',') robot_hosts = robot_hosts.replace('[', '') robot_hosts = robot_hosts.replace(']', '') for hostname in hostnames: try: args = [] if port is not None and port and int(port) < 100 and int(port) >= 0: args.append('_mcast_port:=%s' % (11511 + int(port))) else: args.append('_mcast_port:=%s' % (11511)) if not mastername == 'autodetect': args.append('_name:=%s' % (mastername)) args.append('_mcast_group:=%s' % mcast_group) args.append('_robot_hosts:=[%s]' % robot_hosts) args.append('_heartbeat_hz:=%s' % heartbeat_hz) # TODO: remove the name parameter from the ROS parameter server usr = username if username == 'last used': usr = nm.settings().host_user(hostname) else: nm.settings().set_host_user(hostname, usr) muri = None if masteruri == 'ROS_MASTER_URI' else utf8(masteruri) # stop if master_discovery already running self._append_stop_for('/%s' % utf8(discovery_type), hostname, muri, self._progress_queue) self._progress_queue_sync.start() self._progress_queue.add2queue(utf8(uuid.uuid4()), 'start discovering on %s' % hostname, nm.starter().runNodeWithoutConfig, {'host': utf8(hostname), 'package': 'fkie_master_discovery', 'binary': utf8(discovery_type), 'name': utf8(discovery_type), 'args': args, 'masteruri': muri, 'use_nmd': False, 'auto_pw_request': False, 'user': usr }) # start the master sync with default settings if start_sync: if nm.is_local(hostname): default_sync_args = ["_interface_url:='.'", '_sync_topics_on_demand:=False', '_ignore_hosts:=[]', '_sync_hosts:=[]', '_ignore_nodes:=[]', '_sync_nodes:=[]', '_ignore_topics:=[]', '_sync_topics:=[]', '_ignore_services:=[]', '_sync_services:=[]', '_sync_remote_nodes:=False'] self._append_stop_for('/master_sync', hostname, muri, self._progress_queue_sync) self._progress_queue_sync.start() self._progress_queue.add2queue(utf8(uuid.uuid4()), 'start sync on %s' % hostname, nm.starter().runNodeWithoutConfig, {'host': utf8(hostname), 'package': 'fkie_master_sync', 'binary': 'master_sync', 'name': 'master_sync', 'args': default_sync_args, 'masteruri': muri, 'use_nmd': False, 'auto_pw_request': False, 'user': usr }) else: if hostname not in self._syncs_to_start: self._syncs_to_start.append(hostname) if start_daemon: # local daemon will be started anyway if not nm.is_local(hostname): if hostname not in self._daemons_to_start: self._daemons_to_start.append(hostname) except (Exception, nm.StartException) as e: import traceback print(traceback.format_exc(1)) rospy.logwarn("Error while start master_discovery for %s: %s" % (utf8(hostname), utf8(e))) MessageBox.warning(self, "Start error", 'Error while start master_discovery', utf8(e)) self._progress_queue.start() except Exception as e: MessageBox.warning(self, "Start error", 'Error while parse parameter', utf8(e))
[ "def", "on_start_robot_clicked", "(", "self", ")", ":", "# get the history list", "user_list", "=", "[", "self", ".", "userComboBox", ".", "itemText", "(", "i", ")", "for", "i", "in", "reversed", "(", "range", "(", "self", ".", "userComboBox", ".", "count", ...
https://github.com/fkie/multimaster_fkie/blob/3d23df29d25d71a75c66bbd3cc6e9cbb255724d8/fkie_node_manager/src/fkie_node_manager/main_window.py#L1669-L1796
rossant/galry
6201fa32fb5c9ef3cea700cc22caf52fb69ebe31
galry/glrenderer.py
python
ShaderManager.get_attribute_location
(self, name)
return gl.glGetAttribLocation(self.program, name)
Return the location of an attribute after the shaders have compiled.
Return the location of an attribute after the shaders have compiled.
[ "Return", "the", "location", "of", "an", "attribute", "after", "the", "shaders", "have", "compiled", "." ]
def get_attribute_location(self, name): """Return the location of an attribute after the shaders have compiled.""" return gl.glGetAttribLocation(self.program, name)
[ "def", "get_attribute_location", "(", "self", ",", "name", ")", ":", "return", "gl", ".", "glGetAttribLocation", "(", "self", ".", "program", ",", "name", ")" ]
https://github.com/rossant/galry/blob/6201fa32fb5c9ef3cea700cc22caf52fb69ebe31/galry/glrenderer.py#L437-L439
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/storage/database.py
python
DatabasePool.simple_search_list
( self, table: str, term: Optional[str], col: str, retcols: Collection[str], desc="simple_search_list", )
return await self.runInteraction( desc, self.simple_search_list_txn, table, term, col, retcols, db_autocommit=True, )
Executes a SELECT query on the named table, which may return zero or more rows, returning the result as a list of dicts. Args: table: the table name term: term for searching the table matched to a column. col: column to query term should be matched to retcols: the names of the columns to return Returns: A list of dictionaries or None.
Executes a SELECT query on the named table, which may return zero or more rows, returning the result as a list of dicts.
[ "Executes", "a", "SELECT", "query", "on", "the", "named", "table", "which", "may", "return", "zero", "or", "more", "rows", "returning", "the", "result", "as", "a", "list", "of", "dicts", "." ]
async def simple_search_list( self, table: str, term: Optional[str], col: str, retcols: Collection[str], desc="simple_search_list", ) -> Optional[List[Dict[str, Any]]]: """Executes a SELECT query on the named table, which may return zero or more rows, returning the result as a list of dicts. Args: table: the table name term: term for searching the table matched to a column. col: column to query term should be matched to retcols: the names of the columns to return Returns: A list of dictionaries or None. """ return await self.runInteraction( desc, self.simple_search_list_txn, table, term, col, retcols, db_autocommit=True, )
[ "async", "def", "simple_search_list", "(", "self", ",", "table", ":", "str", ",", "term", ":", "Optional", "[", "str", "]", ",", "col", ":", "str", ",", "retcols", ":", "Collection", "[", "str", "]", ",", "desc", "=", "\"simple_search_list\"", ",", ")"...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/storage/database.py#L2136-L2165
pyocd/pyOCD
7d164d99e816c4ef6c99f257014543188a0ca5a6
pyocd/trace/swv.py
python
SWVReader.__init__
(self, session, core_number=0, lock=None)
! @brief Constructor. @param self @param session The Session instance. @param core_number The number of the core being traced. Default is core 0.
!
[ "!" ]
def __init__(self, session, core_number=0, lock=None): """! @brief Constructor. @param self @param session The Session instance. @param core_number The number of the core being traced. Default is core 0. """ super(SWVReader, self).__init__() self.name = "SWVReader" self.daemon = True self._session = session self._core_number = core_number self._shutdown_event = threading.Event() self._swo_clock = 0 self._lock = lock self._session.subscribe(self._reset_handler, Target.Event.POST_RESET, self._session.target.cores[core_number])
[ "def", "__init__", "(", "self", ",", "session", ",", "core_number", "=", "0", ",", "lock", "=", "None", ")", ":", "super", "(", "SWVReader", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "name", "=", "\"SWVReader\"", "self", ".", "daemon"...
https://github.com/pyocd/pyOCD/blob/7d164d99e816c4ef6c99f257014543188a0ca5a6/pyocd/trace/swv.py#L71-L86
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/monitor/monitor/db/sqlalchemy/models.py
python
MonitorBase.update
(self, values)
Make the model object behave like a dict.
Make the model object behave like a dict.
[ "Make", "the", "model", "object", "behave", "like", "a", "dict", "." ]
def update(self, values): """Make the model object behave like a dict.""" for k, v in values.iteritems(): setattr(self, k, v)
[ "def", "update", "(", "self", ",", "values", ")", ":", "for", "k", ",", "v", "in", "values", ".", "iteritems", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/monitor/db/sqlalchemy/models.py#L91-L94
pyocd/pyOCD
7d164d99e816c4ef6c99f257014543188a0ca5a6
pyocd/flash/flash.py
python
Flash.get_page_info
(self, addr)
return info
! @brief Get info about the page that contains this address.
!
[ "!" ]
def get_page_info(self, addr): """! @brief Get info about the page that contains this address. """ assert self.region is not None if not self.region.contains_address(addr): return None info = PageInfo( program_weight=self.region.program_page_weight, size=self.region.page_size, base_addr=align_down(addr, self.region.page_size) ) return info
[ "def", "get_page_info", "(", "self", ",", "addr", ")", ":", "assert", "self", ".", "region", "is", "not", "None", "if", "not", "self", ".", "region", ".", "contains_address", "(", "addr", ")", ":", "return", "None", "info", "=", "PageInfo", "(", "progr...
https://github.com/pyocd/pyOCD/blob/7d164d99e816c4ef6c99f257014543188a0ca5a6/pyocd/flash/flash.py#L481-L494
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
ResourceCode/wswp-places-c573d29efa3a/web2py/gluon/contrib/memdb.py
python
Set.select
(self, *fields, **attributes)
Always returns a Rows object, even if it may be empty
Always returns a Rows object, even if it may be empty
[ "Always", "returns", "a", "Rows", "object", "even", "if", "it", "may", "be", "empty" ]
def select(self, *fields, **attributes): """ Always returns a Rows object, even if it may be empty """ if isinstance(self.where, QueryException): return self._select_except() else: raise SyntaxError('select arguments not supported')
[ "def", "select", "(", "self", ",", "*", "fields", ",", "*", "*", "attributes", ")", ":", "if", "isinstance", "(", "self", ".", "where", ",", "QueryException", ")", ":", "return", "self", ".", "_select_except", "(", ")", "else", ":", "raise", "SyntaxErr...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/ResourceCode/wswp-places-c573d29efa3a/web2py/gluon/contrib/memdb.py#L590-L598
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/io/cp2k/outputs.py
python
Cp2kOutput.is_metal
(self)
return False
Was a band gap found? i.e. is it a metal
Was a band gap found? i.e. is it a metal
[ "Was", "a", "band", "gap", "found?", "i", ".", "e", ".", "is", "it", "a", "metal" ]
def is_metal(self): """ Was a band gap found? i.e. is it a metal """ if self.band_gap is None: return True if self.band_gap <= 0: return True return False
[ "def", "is_metal", "(", "self", ")", ":", "if", "self", ".", "band_gap", "is", "None", ":", "return", "True", "if", "self", ".", "band_gap", "<=", "0", ":", "return", "True", "return", "False" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/cp2k/outputs.py#L162-L170
tflearn/tflearn
db5176773299b67a2a75c5889fb2aba7fd0fea8a
tflearn/estimators/cluster/kmeans.py
python
KMeansBase.all_distances_
(self)
return self.session.run(self._all_scores)
Distances of each point to each cluster center.
Distances of each point to each cluster center.
[ "Distances", "of", "each", "point", "to", "each", "cluster", "center", "." ]
def all_distances_(self): """ Distances of each point to each cluster center. """ return self.session.run(self._all_scores)
[ "def", "all_distances_", "(", "self", ")", ":", "return", "self", ".", "session", ".", "run", "(", "self", ".", "_all_scores", ")" ]
https://github.com/tflearn/tflearn/blob/db5176773299b67a2a75c5889fb2aba7fd0fea8a/tflearn/estimators/cluster/kmeans.py#L124-L126
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/core/base/block.py
python
PseudoMap.values
(self)
Generator returning the components defined on the Block
Generator returning the components defined on the Block
[ "Generator", "returning", "the", "components", "defined", "on", "the", "Block" ]
def values(self): """ Generator returning the components defined on the Block """ # Iterate over the PseudoMap values (the component objects) in # declaration order _active = self._active if self._ctypes is None: # If there is no ctype, then we will just iterate over # all components and return them all if _active is None: walker = (obj for obj, idx in self._block._decl_order if obj is not None) else: walker = (obj for obj, idx in self._block._decl_order if obj is not None and obj.active == _active) else: # The user specified a desired ctype; we will leverage # the _ctypewalker generator to walk the underlying linked # list and just return the desired objects (again, in # decl order) if _active is None: walker = (obj for obj in self._ctypewalker()) else: walker = (obj for obj in self._ctypewalker() if obj.active == _active) # If the user wants this sorted by name, then there is # nothing we can do to save memory: we must create the whole # list (so we can sort it) and then iterate over the sorted # temporary list if self._sorted: return (obj for obj in sorted(walker, key=lambda _x: _x.local_name)) else: return walker
[ "def", "values", "(", "self", ")", ":", "# Iterate over the PseudoMap values (the component objects) in", "# declaration order", "_active", "=", "self", ".", "_active", "if", "self", ".", "_ctypes", "is", "None", ":", "# If there is no ctype, then we will just iterate over", ...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/base/block.py#L374-L407
stevezheng23/xlnet_extension_tf
3efa272c4dcd126a0d3c79fb912b8cffae5ee572
run_nlu.py
python
NluProcessor.get_train_examples
(self)
return example_list
Gets a collection of `InputExample`s for the train set.
Gets a collection of `InputExample`s for the train set.
[ "Gets", "a", "collection", "of", "InputExample", "s", "for", "the", "train", "set", "." ]
def get_train_examples(self): """Gets a collection of `InputExample`s for the train set.""" data_path = os.path.join(self.data_dir, "train-{0}".format(self.task_name), "train-{0}.json".format(self.task_name)) data_list = self._read_json(data_path) example_list = self._get_example(data_list) return example_list
[ "def", "get_train_examples", "(", "self", ")", ":", "data_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_dir", ",", "\"train-{0}\"", ".", "format", "(", "self", ".", "task_name", ")", ",", "\"train-{0}.json\"", ".", "format", "(", "s...
https://github.com/stevezheng23/xlnet_extension_tf/blob/3efa272c4dcd126a0d3c79fb912b8cffae5ee572/run_nlu.py#L137-L142
mysql/mysql-connector-python
c5460bcbb0dff8e4e48bf4af7a971c89bf486d85
lib/mysqlx/statement.py
python
Statement.deallocate_prepare_execute
(self)
return self._deallocate_prepare_execute
bool: `True` to deallocate + prepare + execute statement.
bool: `True` to deallocate + prepare + execute statement.
[ "bool", ":", "True", "to", "deallocate", "+", "prepare", "+", "execute", "statement", "." ]
def deallocate_prepare_execute(self): """bool: `True` to deallocate + prepare + execute statement. """ return self._deallocate_prepare_execute
[ "def", "deallocate_prepare_execute", "(", "self", ")", ":", "return", "self", ".", "_deallocate_prepare_execute" ]
https://github.com/mysql/mysql-connector-python/blob/c5460bcbb0dff8e4e48bf4af7a971c89bf486d85/lib/mysqlx/statement.py#L196-L199
SigmaHQ/sigma
6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af
tools/sigma/backends/devo.py
python
DevoBackend.generateANDNode
(self, node)
[]
def generateANDNode(self, node): generated = [] for val in node: if self.requireFTS(val): generated.append(self.generateFTS(val)) else: generated.append(self.generateNode(val)) filtered = [g for g in generated if g is not None] if filtered: return self.andToken.join(filtered) else: return None
[ "def", "generateANDNode", "(", "self", ",", "node", ")", ":", "generated", "=", "[", "]", "for", "val", "in", "node", ":", "if", "self", ".", "requireFTS", "(", "val", ")", ":", "generated", ".", "append", "(", "self", ".", "generateFTS", "(", "val",...
https://github.com/SigmaHQ/sigma/blob/6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af/tools/sigma/backends/devo.py#L63-L75
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/lemmatize/processes.py
python
LatinLemmatizationProcess.algorithm
(self)
return LatinBackoffLemmatizer()
[]
def algorithm(self): return LatinBackoffLemmatizer()
[ "def", "algorithm", "(", "self", ")", ":", "return", "LatinBackoffLemmatizer", "(", ")" ]
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/lemmatize/processes.py#L79-L80
libvips/pyvips
a6d622957743f6f015a51e6b80fdbeccc85b44ae
doc/conf.py
python
setup
(app)
[]
def setup(app): app.connect('autodoc-skip-member', skip_deprecated) try: from sphinx.ext.autosummary import Autosummary from sphinx.ext.autosummary import get_documenter from docutils.parsers.rst import directives from sphinx.util.inspect import safe_getattr class AutoAutoSummary(Autosummary): option_spec = { 'methods': directives.unchanged, 'attributes': directives.unchanged } required_arguments = 1 @staticmethod def get_members(obj, typ, include_public=None): if not include_public: include_public = [] items = [] for name in dir(obj): try: documenter = get_documenter(safe_getattr(obj, name), obj) except AttributeError: continue if documenter.objtype == typ: items.append(name) public = [x for x in items if x in include_public or not x.startswith('_')] return public, items def run(self): clazz = str(self.arguments[0]) try: (module_name, class_name) = clazz.rsplit('.', 1) m = __import__(module_name, globals(), locals(), [class_name]) c = getattr(m, class_name) if 'methods' in self.options: _, methods = self.get_members(c, 'method', ['__init__']) self.content = ["~%s.%s" % (clazz, method) for method in methods if not method.startswith('_')] if 'attributes' in self.options: _, attribs = self.get_members(c, 'attribute') self.content = ["~%s.%s" % (clazz, attrib) for attrib in attribs if not attrib.startswith('_')] finally: return super(AutoAutoSummary, self).run() app.add_directive('autoautosummary', AutoAutoSummary) except BaseException as e: raise e
[ "def", "setup", "(", "app", ")", ":", "app", ".", "connect", "(", "'autodoc-skip-member'", ",", "skip_deprecated", ")", "try", ":", "from", "sphinx", ".", "ext", ".", "autosummary", "import", "Autosummary", "from", "sphinx", ".", "ext", ".", "autosummary", ...
https://github.com/libvips/pyvips/blob/a6d622957743f6f015a51e6b80fdbeccc85b44ae/doc/conf.py#L200-L258
miyuchina/mistletoe
8220f3568d566a033518fc3a2d71935112431be0
contrib/toc_renderer.py
python
TOCRenderer.toc
(self)
return items[0]
Returns table of contents as a block_token.List instance.
Returns table of contents as a block_token.List instance.
[ "Returns", "table", "of", "contents", "as", "a", "block_token", ".", "List", "instance", "." ]
def toc(self): """ Returns table of contents as a block_token.List instance. """ from mistletoe.block_token import List def get_indent(level): if self.omit_title: level -= 1 return ' ' * 4 * (level - 1) def build_list_item(heading): level, content = heading template = '{indent}- {content}\n' return template.format(indent=get_indent(level), content=content) lines = [build_list_item(heading) for heading in self._headings] items = block_token.tokenize(lines) return items[0]
[ "def", "toc", "(", "self", ")", ":", "from", "mistletoe", ".", "block_token", "import", "List", "def", "get_indent", "(", "level", ")", ":", "if", "self", ".", "omit_title", ":", "level", "-=", "1", "return", "' '", "*", "4", "*", "(", "level", "-", ...
https://github.com/miyuchina/mistletoe/blob/8220f3568d566a033518fc3a2d71935112431be0/contrib/toc_renderer.py#L30-L47
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/_abcoll.py
python
ItemsView.__contains__
(self, item)
[]
def __contains__(self, item): key, value = item try: v = self._mapping[key] except KeyError: return False else: return v == value
[ "def", "__contains__", "(", "self", ",", "item", ")", ":", "key", ",", "value", "=", "item", "try", ":", "v", "=", "self", ".", "_mapping", "[", "key", "]", "except", "KeyError", ":", "return", "False", "else", ":", "return", "v", "==", "value" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/_abcoll.py#L463-L470
plone/guillotina
57ad54988f797a93630e424fd4b6a75fa26410af
guillotina/db/interfaces.py
python
ITransaction.len
(oid: str)
Get size of children for object
Get size of children for object
[ "Get", "size", "of", "children", "for", "object" ]
async def len(oid: str) -> bool: """ Get size of children for object """
[ "async", "def", "len", "(", "oid", ":", "str", ")", "->", "bool", ":" ]
https://github.com/plone/guillotina/blob/57ad54988f797a93630e424fd4b6a75fa26410af/guillotina/db/interfaces.py#L93-L96
Zulko/easyAI
a5cbd0b600ebbeadc3730df9e7a211d7643cff8b
easyAI/games/TicTacToe-Flask.py
python
TicTacToe.unmake_move
(self, move)
[]
def unmake_move(self, move): # optional method (speeds up the AI) self.board[int(move) - 1] = 0
[ "def", "unmake_move", "(", "self", ",", "move", ")", ":", "# optional method (speeds up the AI)", "self", ".", "board", "[", "int", "(", "move", ")", "-", "1", "]", "=", "0" ]
https://github.com/Zulko/easyAI/blob/a5cbd0b600ebbeadc3730df9e7a211d7643cff8b/easyAI/games/TicTacToe-Flask.py#L23-L24
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
RagPreTrainedModel.from_pretrained
(cls, *args, **kwargs)
[]
def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"])
[ "def", "from_pretrained", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "cls", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L3951-L3952
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/console_widget.py
python
ConsoleWidget.can_copy
(self)
return self._control.textCursor().hasSelection()
Returns whether text can be copied to the clipboard.
Returns whether text can be copied to the clipboard.
[ "Returns", "whether", "text", "can", "be", "copied", "to", "the", "clipboard", "." ]
def can_copy(self): """ Returns whether text can be copied to the clipboard. """ return self._control.textCursor().hasSelection()
[ "def", "can_copy", "(", "self", ")", ":", "return", "self", ".", "_control", ".", "textCursor", "(", ")", ".", "hasSelection", "(", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/console_widget.py#L497-L500
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_manage_node.py
python
Utils.filter_versions
(stdout)
return version_dict
filter the oc version output
filter the oc version output
[ "filter", "the", "oc", "version", "output" ]
def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict
[ "def", "filter_versions", "(", "stdout", ")", ":", "version_dict", "=", "{", "}", "version_search", "=", "[", "'oc'", ",", "'openshift'", ",", "'kubernetes'", "]", "for", "line", "in", "stdout", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_manage_node.py#L1292-L1310
HCIILAB/DeRPN
21e6738ee1f7d3f159ee48d435c543e773f8ce99
lib/datasets/imdb.py
python
imdb.create_roidb_from_box_list
(self, box_list, gt_roidb)
return roidb
[]
def create_roidb_from_box_list(self, box_list, gt_roidb): assert len(box_list) == self.num_images, \ 'Number of boxes must match number of ground-truth images' roidb = [] for i in xrange(self.num_images): boxes = box_list[i] num_boxes = boxes.shape[0] overlaps = np.zeros((num_boxes, self.num_classes), dtype=np.float32) if gt_roidb is not None and gt_roidb[i]['boxes'].size > 0: gt_boxes = gt_roidb[i]['boxes'] gt_classes = gt_roidb[i]['gt_classes'] gt_overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) argmaxes = gt_overlaps.argmax(axis=1) maxes = gt_overlaps.max(axis=1) I = np.where(maxes > 0)[0] overlaps[I, gt_classes[argmaxes[I]]] = maxes[I] overlaps = scipy.sparse.csr_matrix(overlaps) roidb.append({ 'boxes' : boxes, 'gt_classes' : np.zeros((num_boxes,), dtype=np.int32), 'gt_overlaps' : overlaps, 'flipped' : False, 'seg_areas' : np.zeros((num_boxes,), dtype=np.float32), }) return roidb
[ "def", "create_roidb_from_box_list", "(", "self", ",", "box_list", ",", "gt_roidb", ")", ":", "assert", "len", "(", "box_list", ")", "==", "self", ".", "num_images", ",", "'Number of boxes must match number of ground-truth images'", "roidb", "=", "[", "]", "for", ...
https://github.com/HCIILAB/DeRPN/blob/21e6738ee1f7d3f159ee48d435c543e773f8ce99/lib/datasets/imdb.py#L209-L236
lunixbochs/ActualVim
1f555ce719e49d6584f0e35e9f0db2f216b98fa5
lib/neovim/msgpack_rpc/msgpack_stream.py
python
MsgpackStream.stop
(self)
Stop the event loop.
Stop the event loop.
[ "Stop", "the", "event", "loop", "." ]
def stop(self): """Stop the event loop.""" self._event_loop.stop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_event_loop", ".", "stop", "(", ")" ]
https://github.com/lunixbochs/ActualVim/blob/1f555ce719e49d6584f0e35e9f0db2f216b98fa5/lib/neovim/msgpack_rpc/msgpack_stream.py#L40-L42
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_webhook_conversion.py
python
V1WebhookConversion.__ne__
(self, other)
return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
Returns true if both objects are not equal
[ "Returns", "true", "if", "both", "objects", "are", "not", "equal" ]
def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1WebhookConversion): return True return self.to_dict() != other.to_dict()
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1WebhookConversion", ")", ":", "return", "True", "return", "self", ".", "to_dict", "(", ")", "!=", "other", ".", "to_dict", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_webhook_conversion.py#L144-L149
MasoniteFramework/masonite
faa448377916e9e0f618ea6bdc82330fa6604efc
src/masonite/helpers/urls.py
python
UrlsHelper.asset
(self, alias, filename)
return join(location, filename)
Generates a fully qualified URL for the given asset using the given disk Example: asset("local", "avatar.jpg") (take first pat) asset("s3.private", "doc.pdf") (when multiple paths are specified for the disk)
Generates a fully qualified URL for the given asset using the given disk Example: asset("local", "avatar.jpg") (take first pat) asset("s3.private", "doc.pdf") (when multiple paths are specified for the disk)
[ "Generates", "a", "fully", "qualified", "URL", "for", "the", "given", "asset", "using", "the", "given", "disk", "Example", ":", "asset", "(", "local", "avatar", ".", "jpg", ")", "(", "take", "first", "pat", ")", "asset", "(", "s3", ".", "private", "doc...
def asset(self, alias, filename): """Generates a fully qualified URL for the given asset using the given disk Example: asset("local", "avatar.jpg") (take first pat) asset("s3.private", "doc.pdf") (when multiple paths are specified for the disk) """ disks = config("filesystem.disks") # ensure that no slash is prefixing the relative filename path filename = filename.lstrip("/") if "." in alias: alias = alias.split(".") location = disks[alias[0]]["path"][alias[1]] else: location = disks[alias]["path"] # take first path if no path specified if isinstance(location, dict): location = list(location.values())[0] return join(location, filename)
[ "def", "asset", "(", "self", ",", "alias", ",", "filename", ")", ":", "disks", "=", "config", "(", "\"filesystem.disks\"", ")", "# ensure that no slash is prefixing the relative filename path", "filename", "=", "filename", ".", "lstrip", "(", "\"/\"", ")", "if", "...
https://github.com/MasoniteFramework/masonite/blob/faa448377916e9e0f618ea6bdc82330fa6604efc/src/masonite/helpers/urls.py#L18-L35
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotvideo/v20201215/iotvideo_client.py
python
IotvideoClient.DescribeModelDefinition
(self, request)
查询产品配置的数据模板信息 :param request: Request instance for DescribeModelDefinition. :type request: :class:`tencentcloud.iotvideo.v20201215.models.DescribeModelDefinitionRequest` :rtype: :class:`tencentcloud.iotvideo.v20201215.models.DescribeModelDefinitionResponse`
查询产品配置的数据模板信息
[ "查询产品配置的数据模板信息" ]
def DescribeModelDefinition(self, request): """查询产品配置的数据模板信息 :param request: Request instance for DescribeModelDefinition. :type request: :class:`tencentcloud.iotvideo.v20201215.models.DescribeModelDefinitionRequest` :rtype: :class:`tencentcloud.iotvideo.v20201215.models.DescribeModelDefinitionResponse` """ try: params = request._serialize() body = self.call("DescribeModelDefinition", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeModelDefinitionResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeModelDefinition", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeModelDefinition\"", ",", "params", ")", "response", "=", "json", "...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotvideo/v20201215/iotvideo_client.py#L1429-L1454
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/apis/storage_v1_api.py
python
StorageV1Api.delete_collection_storage_class_with_http_info
(self, **kwargs)
return self.api_client.call_api(resource_path, 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
delete collection of StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_collection_storage_class_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str pretty: If 'true', then the output is pretty printed. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread.
delete collection of StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_collection_storage_class_with_http_info(callback=callback_function)
[ "delete", "collection", "of", "StorageClass", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", ...
def delete_collection_storage_class_with_http_info(self, **kwargs): """ delete collection of StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_collection_storage_class_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str pretty: If 'true', then the output is pretty printed. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ all_params = ['pretty', 'field_selector', 'include_uninitialized', 'label_selector', 'resource_version', 'timeout_seconds', 'watch'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_storage_class" % key ) params[key] = val del params['kwargs'] collection_formats = {} resource_path = '/apis/storage.k8s.io/v1/storageclasses'.replace('{format}', 'json') path_params = {} query_params = {} if 'pretty' in params: query_params['pretty'] = params['pretty'] if 'field_selector' in params: query_params['fieldSelector'] = params['field_selector'] if 'include_uninitialized' in params: query_params['includeUninitialized'] = params['include_uninitialized'] if 'label_selector' in params: query_params['labelSelector'] = params['label_selector'] if 'resource_version' in params: query_params['resourceVersion'] = params['resource_version'] if 'timeout_seconds' in params: query_params['timeoutSeconds'] = params['timeout_seconds'] if 'watch' in params: query_params['watch'] = params['watch'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api(resource_path, 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "delete_collection_storage_class_with_http_info", "(", "self", ",", "*", "*", "kwargs", ")", ":", "all_params", "=", "[", "'pretty'", ",", "'field_selector'", ",", "'include_uninitialized'", ",", "'label_selector'", ",", "'resource_version'", ",", "'timeout_secon...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/apis/storage_v1_api.py#L183-L276
SciTools/iris
a12d0b15bab3377b23a148e891270b13a0419c38
lib/iris/coord_systems.py
python
GeogCS.__init__
( self, semi_major_axis=None, semi_minor_axis=None, inverse_flattening=None, longitude_of_prime_meridian=None, )
Creates a new GeogCS. Kwargs: * semi_major_axis, semi_minor_axis: Axes of ellipsoid, in metres. At least one must be given (see note below). * inverse_flattening: Can be omitted if both axes given (see note below). Defaults to 0.0 . * longitude_of_prime_meridian: Specifies the prime meridian on the ellipsoid, in degrees. Defaults to 0.0 . If just semi_major_axis is set, with no semi_minor_axis or inverse_flattening, then a perfect sphere is created from the given radius. If just two of semi_major_axis, semi_minor_axis, and inverse_flattening are given the missing element is calculated from the formula: :math:`flattening = (major - minor) / major` Currently, Iris will not allow over-specification (all three ellipsoid parameters). Examples:: cs = GeogCS(6371229) pp_cs = GeogCS(iris.fileformats.pp.EARTH_RADIUS) airy1830 = GeogCS(semi_major_axis=6377563.396, semi_minor_axis=6356256.909) airy1830 = GeogCS(semi_major_axis=6377563.396, inverse_flattening=299.3249646) custom_cs = GeogCS(6400000, 6300000)
Creates a new GeogCS.
[ "Creates", "a", "new", "GeogCS", "." ]
def __init__( self, semi_major_axis=None, semi_minor_axis=None, inverse_flattening=None, longitude_of_prime_meridian=None, ): """ Creates a new GeogCS. Kwargs: * semi_major_axis, semi_minor_axis: Axes of ellipsoid, in metres. At least one must be given (see note below). * inverse_flattening: Can be omitted if both axes given (see note below). Defaults to 0.0 . * longitude_of_prime_meridian: Specifies the prime meridian on the ellipsoid, in degrees. Defaults to 0.0 . If just semi_major_axis is set, with no semi_minor_axis or inverse_flattening, then a perfect sphere is created from the given radius. If just two of semi_major_axis, semi_minor_axis, and inverse_flattening are given the missing element is calculated from the formula: :math:`flattening = (major - minor) / major` Currently, Iris will not allow over-specification (all three ellipsoid parameters). Examples:: cs = GeogCS(6371229) pp_cs = GeogCS(iris.fileformats.pp.EARTH_RADIUS) airy1830 = GeogCS(semi_major_axis=6377563.396, semi_minor_axis=6356256.909) airy1830 = GeogCS(semi_major_axis=6377563.396, inverse_flattening=299.3249646) custom_cs = GeogCS(6400000, 6300000) """ # No ellipsoid specified? (0 0 0) if ( (semi_major_axis is None) and (semi_minor_axis is None) and (inverse_flattening is None) ): raise ValueError("No ellipsoid specified") # Ellipsoid over-specified? (1 1 1) if ( (semi_major_axis is not None) and (semi_minor_axis is not None) and (inverse_flattening is not None) ): raise ValueError("Ellipsoid is overspecified") # Perfect sphere (semi_major_axis only)? (1 0 0) elif semi_major_axis is not None and ( semi_minor_axis is None and not inverse_flattening ): semi_minor_axis = semi_major_axis inverse_flattening = 0.0 # Calculate semi_major_axis? (0 1 1) elif semi_major_axis is None and ( semi_minor_axis is not None and inverse_flattening is not None ): semi_major_axis = -semi_minor_axis / ( (1.0 - inverse_flattening) / inverse_flattening ) # Calculate semi_minor_axis? (1 0 1) elif semi_minor_axis is None and ( semi_major_axis is not None and inverse_flattening is not None ): semi_minor_axis = semi_major_axis - ( (1.0 / inverse_flattening) * semi_major_axis ) # Calculate inverse_flattening? (1 1 0) elif inverse_flattening is None and ( semi_major_axis is not None and semi_minor_axis is not None ): if semi_major_axis == semi_minor_axis: inverse_flattening = 0.0 else: inverse_flattening = 1.0 / ( (semi_major_axis - semi_minor_axis) / semi_major_axis ) # We didn't get enough to specify an ellipse. else: raise ValueError("Insufficient ellipsoid specification") #: Major radius of the ellipsoid in metres. self.semi_major_axis = float(semi_major_axis) #: Minor radius of the ellipsoid in metres. self.semi_minor_axis = float(semi_minor_axis) #: :math:`1/f` where :math:`f = (a-b)/a`. self.inverse_flattening = float(inverse_flattening) #: Describes 'zero' on the ellipsoid in degrees. self.longitude_of_prime_meridian = _arg_default( longitude_of_prime_meridian, 0 )
[ "def", "__init__", "(", "self", ",", "semi_major_axis", "=", "None", ",", "semi_minor_axis", "=", "None", ",", "inverse_flattening", "=", "None", ",", "longitude_of_prime_meridian", "=", "None", ",", ")", ":", "# No ellipsoid specified? (0 0 0)", "if", "(", "(", ...
https://github.com/SciTools/iris/blob/a12d0b15bab3377b23a148e891270b13a0419c38/lib/iris/coord_systems.py#L134-L247
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
gui/colors/bases.py
python
CachedBgWidgetMixin.paint_foreground_cb
(self, cr, w, h)
Paints the foreground over the background
Paints the foreground over the background
[ "Paints", "the", "foreground", "over", "the", "background" ]
def paint_foreground_cb(self, cr, w, h): """Paints the foreground over the background """ raise NotImplementedError
[ "def", "paint_foreground_cb", "(", "self", ",", "cr", ",", "w", ",", "h", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/gui/colors/bases.py#L85-L87
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/leoOPML.py
python
PutToOPML.tnodeListAttributes
(self, p)
return s
Put the tnodeList attribute of p.v
Put the tnodeList attribute of p.v
[ "Put", "the", "tnodeList", "attribute", "of", "p", ".", "v" ]
def tnodeListAttributes(self, p): """Put the tnodeList attribute of p.v""" # Remember: entries in the tnodeList correspond to @+node sentinels, _not_ to tnodes! if not hasattr(p.v, 'tnodeList') or not p.v.tnodeList: return None # Assign fileIndices. for v in p.v.tnodeList: try: # Will fail for None or any pre 4.1 file index. theId, time, n = p.v.fileIndex except Exception: g.trace("assigning gnx for ", p.v) gnx = g.app.nodeIndices.getNewIndex(p.v) p.v.setFileIndex(gnx) # Don't convert to string until the actual write. s = ','.join([g.app.nodeIndices.tupleToString(v.fileIndex) for v in p.v.tnodeList]) return s
[ "def", "tnodeListAttributes", "(", "self", ",", "p", ")", ":", "# Remember: entries in the tnodeList correspond to @+node sentinels, _not_ to tnodes!", "if", "not", "hasattr", "(", "p", ".", "v", ",", "'tnodeList'", ")", "or", "not", "p", ".", "v", ".", "tnodeList",...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/leoOPML.py#L557-L571
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/single_process/extraction_engine.py
python
SingleProcessEngine._ProcessSources
(self, source_configurations, parser_mediator)
Processes the sources. Args: source_configurations (list[SourceConfigurationArtifact]): configurations of the sources to process. parser_mediator (ParserMediator): parser mediator.
Processes the sources.
[ "Processes", "the", "sources", "." ]
def _ProcessSources(self, source_configurations, parser_mediator): """Processes the sources. Args: source_configurations (list[SourceConfigurationArtifact]): configurations of the sources to process. parser_mediator (ParserMediator): parser mediator. """ if self._processing_profiler: self._processing_profiler.StartTiming('process_sources') self._status = definitions.STATUS_INDICATOR_COLLECTING self._current_display_name = '' self._number_of_consumed_sources = 0 find_specs = None if self.collection_filters_helper: find_specs = ( self.collection_filters_helper.included_file_system_find_specs) source_path_specs = [ configuration.path_spec for configuration in source_configurations] path_spec_generator = self._path_spec_extractor.ExtractPathSpecs( source_path_specs, find_specs=find_specs, recurse_file_system=False, resolver_context=self._resolver_context) for path_spec in path_spec_generator: if self._abort: break self._status = definitions.STATUS_INDICATOR_COLLECTING self._current_display_name = parser_mediator.GetDisplayNameForPathSpec( path_spec) # TODO: determine if event sources should be DataStream or FileEntry # or both. event_source = event_sources.FileEntryEventSource(path_spec=path_spec) parser_mediator.ProduceEventSource(event_source) self._status = definitions.STATUS_INDICATOR_RUNNING if self._processing_profiler: self._processing_profiler.StartTiming('get_event_source') event_source = self._storage_writer.GetFirstWrittenEventSource() if self._processing_profiler: self._processing_profiler.StopTiming('get_event_source') while event_source: if self._abort: break self._ProcessPathSpec( self._extraction_worker, parser_mediator, event_source.path_spec) self._number_of_consumed_sources += 1 if self._processing_profiler: self._processing_profiler.StartTiming('get_event_source') event_source = self._storage_writer.GetNextWrittenEventSource() if self._processing_profiler: self._processing_profiler.StopTiming('get_event_source') if self._abort: self._status = definitions.STATUS_INDICATOR_ABORTED else: self._status = definitions.STATUS_INDICATOR_COMPLETED if self._processing_profiler: self._processing_profiler.StopTiming('process_sources')
[ "def", "_ProcessSources", "(", "self", ",", "source_configurations", ",", "parser_mediator", ")", ":", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StartTiming", "(", "'process_sources'", ")", "self", ".", "_status", "...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/single_process/extraction_engine.py#L134-L207
natea/django-deployer
5ce7d972db2f8500ec53ad89e7eb312d3360d074
django_deployer/helpers.py
python
_join
(*args)
return os.path.join(*args)
Convenience wrapper around os.path.join to make the rest of our functions more readable.
Convenience wrapper around os.path.join to make the rest of our functions more readable.
[ "Convenience", "wrapper", "around", "os", ".", "path", ".", "join", "to", "make", "the", "rest", "of", "our", "functions", "more", "readable", "." ]
def _join(*args): """ Convenience wrapper around os.path.join to make the rest of our functions more readable. """ return os.path.join(*args)
[ "def", "_join", "(", "*", "args", ")", ":", "return", "os", ".", "path", ".", "join", "(", "*", "args", ")" ]
https://github.com/natea/django-deployer/blob/5ce7d972db2f8500ec53ad89e7eb312d3360d074/django_deployer/helpers.py#L129-L134
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/wifitap/scapy.py
python
Dot11PacketList.toEthernet
(self)
return PacketList(r2,name="Ether from %s"%self.listname)
[]
def toEthernet(self): data = map(lambda x:x.getlayer(Dot11), filter(lambda x : x.haslayer(Dot11) and x.type == 2, self.res)) r2 = [] for p in data: q = p.copy() q.unwep() r2.append(Ether()/q.payload.payload.payload) #Dot11/LLC/SNAP/IP return PacketList(r2,name="Ether from %s"%self.listname)
[ "def", "toEthernet", "(", "self", ")", ":", "data", "=", "map", "(", "lambda", "x", ":", "x", ".", "getlayer", "(", "Dot11", ")", ",", "filter", "(", "lambda", "x", ":", "x", ".", "haslayer", "(", "Dot11", ")", "and", "x", ".", "type", "==", "2...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifitap/scapy.py#L3177-L3184
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/gis/db/models/sql/compiler.py
python
GeoSQLCompiler.get_field_select
(self, field, alias=None, column=None)
return field_sel
Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`.
Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`.
[ "Returns", "the", "SELECT", "SQL", "string", "for", "the", "given", "field", ".", "Figures", "out", "if", "any", "custom", "selection", "SQL", "is", "needed", "for", "the", "column", "The", "alias", "keyword", "may", "be", "used", "to", "manually", "specif...
def get_field_select(self, field, alias=None, column=None): """ Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`. """ sel_fmt = self.get_select_format(field) if field in self.query.custom_select: field_sel = sel_fmt % self.query.custom_select[field] else: field_sel = sel_fmt % self._field_column(field, alias, column) return field_sel
[ "def", "get_field_select", "(", "self", ",", "field", ",", "alias", "=", "None", ",", "column", "=", "None", ")", ":", "sel_fmt", "=", "self", ".", "get_select_format", "(", "field", ")", "if", "field", "in", "self", ".", "query", ".", "custom_select", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/gis/db/models/sql/compiler.py#L210-L224
jina-ai/jina
c77a492fcd5adba0fc3de5347bea83dd4e7d8087
docarray/simple/map.py
python
NamedScoreMap.__contains__
(self, key: str)
return key in self._pb_body
[]
def __contains__(self, key: str): return key in self._pb_body
[ "def", "__contains__", "(", "self", ",", "key", ":", "str", ")", ":", "return", "key", "in", "self", ".", "_pb_body" ]
https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/docarray/simple/map.py#L69-L70
PaddlePaddle/PARL
5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96
parl/utils/utils.py
python
kill_process
(regex_pattern)
kill process whose execution commnad is matched by regex pattern Args: regex_pattern(string): regex pattern used to filter the process to be killed NOTE: In windows, we will replace sep `/` with `\\\\`
kill process whose execution commnad is matched by regex pattern
[ "kill", "process", "whose", "execution", "commnad", "is", "matched", "by", "regex", "pattern" ]
def kill_process(regex_pattern): """kill process whose execution commnad is matched by regex pattern Args: regex_pattern(string): regex pattern used to filter the process to be killed NOTE: In windows, we will replace sep `/` with `\\\\` """ if _IS_WINDOWS: regex_pattern = regex_pattern.replace('/', '\\\\') command = r'''for /F "skip=2 tokens=2 delims=," %a in ('wmic process where "commandline like '%{}%'" get processid^,status /format:csv') do taskkill /F /T /pid %a'''.format( regex_pattern) with os.popen(command) as p: p.read() else: command = "ps aux | grep {} | awk '{{print $2}}' | xargs kill -9".format( regex_pattern) subprocess.call([command], shell=True)
[ "def", "kill_process", "(", "regex_pattern", ")", ":", "if", "_IS_WINDOWS", ":", "regex_pattern", "=", "regex_pattern", ".", "replace", "(", "'/'", ",", "'\\\\\\\\'", ")", "command", "=", "r'''for /F \"skip=2 tokens=2 delims=,\" %a in ('wmic process where \"commandline like...
https://github.com/PaddlePaddle/PARL/blob/5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96/parl/utils/utils.py#L97-L115
joxeankoret/diaphora
dcb5a25ac9fe23a285b657e5389cf770de7ac928
diaphora.py
python
CBinDiff.compare_graphs_pass
(self, bblocks1, bblocks2, colours1, colours2, is_second = False)
return colours1, colours2
[]
def compare_graphs_pass(self, bblocks1, bblocks2, colours1, colours2, is_second = False): dones1 = set() dones2 = set() # Now compare each basic block from the first function to all the # basic blocks in the 2nd function for key1 in bblocks1: if key1 in dones1: continue for key2 in bblocks2: if key2 in dones2: continue # Same number of instructions? if len(bblocks1[key1]) == len(bblocks2[key2]): mod = False partial = True i = 0 for ins1 in bblocks1[key1]: ins2 = bblocks2[key2][i] # Same mnemonic? The change can be only partial if ins1[1] != ins2[1]: partial = False # Try to compare the assembly after doing some cleaning cmp_asm1 = self.get_cmp_asm(ins1[2]) cmp_asm2 = self.get_cmp_asm(ins2[2]) if cmp_asm1 != cmp_asm2: mod = True if not partial: continue i += 1 if not mod: # Perfect match, we discovered a basic block equal in both # functions colours1[key1] = 0xffffff colours2[key2] = 0xffffff dones1.add(key1) dones2.add(key2) break elif not is_second and partial: # Partial match, we discovered a basic block with the same # mnemonics but something changed # # NOTE: # Do not add the partial matches to the dones lists, as we # can have complete matches after a partial match! colours1[key1] = 0xCCffff colours2[key2] = 0xCCffff break return colours1, colours2
[ "def", "compare_graphs_pass", "(", "self", ",", "bblocks1", ",", "bblocks2", ",", "colours1", ",", "colours2", ",", "is_second", "=", "False", ")", ":", "dones1", "=", "set", "(", ")", "dones2", "=", "set", "(", ")", "# Now compare each basic block from the fi...
https://github.com/joxeankoret/diaphora/blob/dcb5a25ac9fe23a285b657e5389cf770de7ac928/diaphora.py#L836-L888
andycasey/ads
7939be2650bfee85be13cd46cfa2e037381da7fc
ads/search.py
python
Article.bibtex
(self)
return ExportQuery(bibcodes=self.bibcode, format="bibtex").execute()
Return a BiBTeX entry for the current article.
Return a BiBTeX entry for the current article.
[ "Return", "a", "BiBTeX", "entry", "for", "the", "current", "article", "." ]
def bibtex(self): """Return a BiBTeX entry for the current article.""" warnings.warn("bibtex should be queried with ads.ExportQuery(); You will " "hit API ratelimits very quickly otherwise.", UserWarning) return ExportQuery(bibcodes=self.bibcode, format="bibtex").execute()
[ "def", "bibtex", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"bibtex should be queried with ads.ExportQuery(); You will \"", "\"hit API ratelimits very quickly otherwise.\"", ",", "UserWarning", ")", "return", "ExportQuery", "(", "bibcodes", "=", "self", ".", "...
https://github.com/andycasey/ads/blob/7939be2650bfee85be13cd46cfa2e037381da7fc/ads/search.py#L293-L297
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/series.py
python
Series.unstack
(self, level=-1)
return unstack(self, level)
Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. The level involved will automatically get sorted. Parameters ---------- level : int, string, or list of these, default last level Level(s) to unstack, can pass level name Examples -------- >>> s one a 1. one b 2. two a 3. two b 4. >>> s.unstack(level=-1) a b one 1. 2. two 3. 4. >>> s.unstack(level=0) one two a 1. 2. b 3. 4. Returns ------- unstacked : DataFrame
Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. The level involved will automatically get sorted.
[ "Unstack", "a", ".", "k", ".", "a", ".", "pivot", "Series", "with", "MultiIndex", "to", "produce", "DataFrame", ".", "The", "level", "involved", "will", "automatically", "get", "sorted", "." ]
def unstack(self, level=-1): """ Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. The level involved will automatically get sorted. Parameters ---------- level : int, string, or list of these, default last level Level(s) to unstack, can pass level name Examples -------- >>> s one a 1. one b 2. two a 3. two b 4. >>> s.unstack(level=-1) a b one 1. 2. two 3. 4. >>> s.unstack(level=0) one two a 1. 2. b 3. 4. Returns ------- unstacked : DataFrame """ from pandas.core.reshape import unstack return unstack(self, level)
[ "def", "unstack", "(", "self", ",", "level", "=", "-", "1", ")", ":", "from", "pandas", ".", "core", ".", "reshape", "import", "unstack", "return", "unstack", "(", "self", ",", "level", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/series.py#L1953-L1986
log2timeline/dfvfs
4ca7bf06b15cdc000297a7122a065f0ca71de544
dfvfs/vfs/cpio_file_entry.py
python
CPIOFileEntry.name
(self)
return self._file_system.BasenamePath(self._cpio_archive_file_entry.path)
str: name of the file entry, which does not include the full path.
str: name of the file entry, which does not include the full path.
[ "str", ":", "name", "of", "the", "file", "entry", "which", "does", "not", "include", "the", "full", "path", "." ]
def name(self): """str: name of the file entry, which does not include the full path.""" # Note that the root file entry is virtual and has no # cpio_archive_file_entry. if self._cpio_archive_file_entry is None: return '' return self._file_system.BasenamePath(self._cpio_archive_file_entry.path)
[ "def", "name", "(", "self", ")", ":", "# Note that the root file entry is virtual and has no", "# cpio_archive_file_entry.", "if", "self", ".", "_cpio_archive_file_entry", "is", "None", ":", "return", "''", "return", "self", ".", "_file_system", ".", "BasenamePath", "("...
https://github.com/log2timeline/dfvfs/blob/4ca7bf06b15cdc000297a7122a065f0ca71de544/dfvfs/vfs/cpio_file_entry.py#L161-L168
google-research/motion_imitation
d0e7b963c5a301984352d25a3ee0820266fa4218
motion_imitation/envs/sensors/environment_sensors.py
python
LastActionSensor.on_reset
(self, env)
From the callback, the sensor remembers the environment. Args: env: the environment who invokes this callback function.
From the callback, the sensor remembers the environment.
[ "From", "the", "callback", "the", "sensor", "remembers", "the", "environment", "." ]
def on_reset(self, env): """From the callback, the sensor remembers the environment. Args: env: the environment who invokes this callback function. """ self._env = env
[ "def", "on_reset", "(", "self", ",", "env", ")", ":", "self", ".", "_env", "=", "env" ]
https://github.com/google-research/motion_imitation/blob/d0e7b963c5a301984352d25a3ee0820266fa4218/motion_imitation/envs/sensors/environment_sensors.py#L65-L71
vanheeringen-lab/genomepy
4c10e69b6886cf52381caf6498395391834a675b
genomepy/providers/base.py
python
BaseProvider.head_annotation
(self, name: str, genomes_dir=None, n: int = 5, **kwargs)
Download the first n lines of the annotation. The first line of the GTF is printed for review (of the gene_name field, for instance). Parameters ---------- name : str genome name genomes_dir : str, optional genomes directory to install the annotation in. n : int, optional download the annotation for n genes.
Download the first n lines of the annotation.
[ "Download", "the", "first", "n", "lines", "of", "the", "annotation", "." ]
def head_annotation(self, name: str, genomes_dir=None, n: int = 5, **kwargs): """ Download the first n lines of the annotation. The first line of the GTF is printed for review (of the gene_name field, for instance). Parameters ---------- name : str genome name genomes_dir : str, optional genomes directory to install the annotation in. n : int, optional download the annotation for n genes. """ name = self._check_name(name) link = self.get_annotation_download_link(name, **kwargs) localname = f"{name}_head" genomes_dir = get_genomes_dir(genomes_dir, check_exist=False) fpath = os.path.join(genomes_dir, localname, f"{localname}.annotation.gtf") download_annotation(genomes_dir, link, localname, n=n) logger.info(self.name) m = 0 with open(fpath) as f: for line in f: line = line.strip() if line and line[0] != "#": print(line) m += 1 if m == n: break
[ "def", "head_annotation", "(", "self", ",", "name", ":", "str", ",", "genomes_dir", "=", "None", ",", "n", ":", "int", "=", "5", ",", "*", "*", "kwargs", ")", ":", "name", "=", "self", ".", "_check_name", "(", "name", ")", "link", "=", "self", "....
https://github.com/vanheeringen-lab/genomepy/blob/4c10e69b6886cf52381caf6498395391834a675b/genomepy/providers/base.py#L362-L396
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_linux/systrace/catapult/devil/devil/android/tools/system_app.py
python
_TemporarilyInstallApp
(device, apk)
A context manager that installs an app while in scope.
A context manager that installs an app while in scope.
[ "A", "context", "manager", "that", "installs", "an", "app", "while", "in", "scope", "." ]
def _TemporarilyInstallApp(device, apk): """A context manager that installs an app while in scope.""" device.Install(apk, reinstall=True) try: yield finally: device.Uninstall(apk_helper.GetPackageName(apk))
[ "def", "_TemporarilyInstallApp", "(", "device", ",", "apk", ")", ":", "device", ".", "Install", "(", "apk", ",", "reinstall", "=", "True", ")", "try", ":", "yield", "finally", ":", "device", ".", "Uninstall", "(", "apk_helper", ".", "GetPackageName", "(", ...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_linux/systrace/catapult/devil/devil/android/tools/system_app.py#L139-L145
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/abstract/mixer/trackgroup.py
python
AbstractTrackGroup.filters
(self)
return None
Returns a list of stringified names of enabled filters on the TrackGroup. Returns: list: A list of the string names of enabled filters.
Returns a list of stringified names of enabled filters on the TrackGroup.
[ "Returns", "a", "list", "of", "stringified", "names", "of", "enabled", "filters", "on", "the", "TrackGroup", "." ]
def filters(self): """Returns a list of stringified names of enabled filters on the TrackGroup. Returns: list: A list of the string names of enabled filters. """ return None
[ "def", "filters", "(", "self", ")", ":", "return", "None" ]
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/abstract/mixer/trackgroup.py#L167-L174
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
windows/SYNfulKnock/scapy-2.3.1/scapy/contrib/gsm_um.py
python
rrInitialisationRequest
()
return packet
RR Initialisation Request Section 9.1.28.a
RR Initialisation Request Section 9.1.28.a
[ "RR", "Initialisation", "Request", "Section", "9", ".", "1", ".", "28", ".", "a" ]
def rrInitialisationRequest(): """RR Initialisation Request Section 9.1.28.a""" a = TpPd(pd=0x6) b = MessageType(mesType=0x3c) # 00111100 c = CiphKeySeqNrAndMacModeAndChannelCodingRequest() e = MobileStationClassmark2() f = Tlli() g = ChannelRequestDescription() h = GprsMeasurementResults() packet = a / b / c / e / f / g / h return packet
[ "def", "rrInitialisationRequest", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x6", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x3c", ")", "# 00111100", "c", "=", "CiphKeySeqNrAndMacModeAndChannelCodingRequest", "(", ")", "e", "=", "MobileStat...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/windows/SYNfulKnock/scapy-2.3.1/scapy/contrib/gsm_um.py#L941-L951
astropy/photutils
3caa48e4e4d139976ed7457dc41583fb2c56ba20
photutils/segmentation/catalog.py
python
SourceCatalog.cxx
(self)
return ((np.cos(self.orientation) / self.semimajor_sigma)**2 + (np.sin(self.orientation) / self.semiminor_sigma)**2)
r""" `SourceExtractor`_'s CXX ellipse parameter in units of pixel**(-2). The ellipse is defined as .. math:: cxx (x - \bar{x})^2 + cxy (x - \bar{x}) (y - \bar{y}) + cyy (y - \bar{y})^2 = R^2 where :math:`R` is a parameter which scales the ellipse (in units of the axes lengths). `SourceExtractor`_ reports that the isophotal limit of a source is well represented by :math:`R \approx 3`.
r""" `SourceExtractor`_'s CXX ellipse parameter in units of pixel**(-2).
[ "r", "SourceExtractor", "_", "s", "CXX", "ellipse", "parameter", "in", "units", "of", "pixel", "**", "(", "-", "2", ")", "." ]
def cxx(self): r""" `SourceExtractor`_'s CXX ellipse parameter in units of pixel**(-2). The ellipse is defined as .. math:: cxx (x - \bar{x})^2 + cxy (x - \bar{x}) (y - \bar{y}) + cyy (y - \bar{y})^2 = R^2 where :math:`R` is a parameter which scales the ellipse (in units of the axes lengths). `SourceExtractor`_ reports that the isophotal limit of a source is well represented by :math:`R \approx 3`. """ return ((np.cos(self.orientation) / self.semimajor_sigma)**2 + (np.sin(self.orientation) / self.semiminor_sigma)**2)
[ "def", "cxx", "(", "self", ")", ":", "return", "(", "(", "np", ".", "cos", "(", "self", ".", "orientation", ")", "/", "self", ".", "semimajor_sigma", ")", "**", "2", "+", "(", "np", ".", "sin", "(", "self", ".", "orientation", ")", "/", "self", ...
https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/segmentation/catalog.py#L1885-L1902
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_tools/path_elements/cubic.py
python
getCubicPathByBeginEnd
(begin, controlPoints, end, xmlElement)
return svg_reader.getCubicPoints(begin, controlPoints, end, lineation.getNumberOfBezierPoints(begin, end, xmlElement))
Get the cubic path by begin and end.
Get the cubic path by begin and end.
[ "Get", "the", "cubic", "path", "by", "begin", "and", "end", "." ]
def getCubicPathByBeginEnd(begin, controlPoints, end, xmlElement): "Get the cubic path by begin and end." return svg_reader.getCubicPoints(begin, controlPoints, end, lineation.getNumberOfBezierPoints(begin, end, xmlElement))
[ "def", "getCubicPathByBeginEnd", "(", "begin", ",", "controlPoints", ",", "end", ",", "xmlElement", ")", ":", "return", "svg_reader", ".", "getCubicPoints", "(", "begin", ",", "controlPoints", ",", "end", ",", "lineation", ".", "getNumberOfBezierPoints", "(", "b...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/geometry_tools/path_elements/cubic.py#L52-L54
uqfoundation/klepto
a2b941fa2053ccbad731180d015bd39d3ee18c27
klepto/rounding.py
python
simple_round_factory
(tol)
return simple_round
helper function for simple_round (a factory for simple_round functions)
helper function for simple_round (a factory for simple_round functions)
[ "helper", "function", "for", "simple_round", "(", "a", "factory", "for", "simple_round", "functions", ")" ]
def simple_round_factory(tol): """helper function for simple_round (a factory for simple_round functions)""" def simple_round(*args, **kwds): argstype = type(args) _args = list(args) _kwds = kwds.copy() for i,j in enumerate(args): if isinstance(j, float): _args[i] = round(j, tol) # don't round int for i,j in kwds.items(): if isinstance(j, float): _kwds[i] = round(j, tol) return argstype(_args), _kwds return simple_round
[ "def", "simple_round_factory", "(", "tol", ")", ":", "def", "simple_round", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "argstype", "=", "type", "(", "args", ")", "_args", "=", "list", "(", "args", ")", "_kwds", "=", "kwds", ".", "copy", "("...
https://github.com/uqfoundation/klepto/blob/a2b941fa2053ccbad731180d015bd39d3ee18c27/klepto/rounding.py#L91-L102
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/platforms.py
python
check_privileges
(accept_content)
[]
def check_privileges(accept_content): uid = os.getuid() if hasattr(os, 'getuid') else 65535 gid = os.getgid() if hasattr(os, 'getgid') else 65535 euid = os.geteuid() if hasattr(os, 'geteuid') else 65535 egid = os.getegid() if hasattr(os, 'getegid') else 65535 if hasattr(os, 'fchown'): if not all(hasattr(os, attr) for attr in ['getuid', 'getgid', 'geteuid', 'getegid']): raise SecurityError('suspicious platform, contact support') if not uid or not gid or not euid or not egid: if ('pickle' in accept_content or 'application/x-python-serialize' in accept_content): if not C_FORCE_ROOT: try: print(ROOT_DISALLOWED.format( uid=uid, euid=euid, gid=gid, egid=egid, ), file=sys.stderr) finally: os._exit(1) warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( uid=uid, euid=euid, gid=gid, egid=egid, )))
[ "def", "check_privileges", "(", "accept_content", ")", ":", "uid", "=", "os", ".", "getuid", "(", ")", "if", "hasattr", "(", "os", ",", "'getuid'", ")", "else", "65535", "gid", "=", "os", ".", "getgid", "(", ")", "if", "hasattr", "(", "os", ",", "'...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/platforms.py#L771-L794
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/urllib3/util/selectors.py
python
BaseSelector._key_from_fd
(self, fd)
Return the key associated to a given file descriptor Return None if it is not found.
Return the key associated to a given file descriptor Return None if it is not found.
[ "Return", "the", "key", "associated", "to", "a", "given", "file", "descriptor", "Return", "None", "if", "it", "is", "not", "found", "." ]
def _key_from_fd(self, fd): """ Return the key associated to a given file descriptor Return None if it is not found. """ try: return self._fd_to_key[fd] except KeyError: return None
[ "def", "_key_from_fd", "(", "self", ",", "fd", ")", ":", "try", ":", "return", "self", ".", "_fd_to_key", "[", "fd", "]", "except", "KeyError", ":", "return", "None" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/urllib3/util/selectors.py#L270-L276
pyrocko/pyrocko
b6baefb7540fb7fce6ed9b856ec0c413961a4320
src/plot/dynamic_rupture.py
python
_save_grid
(lats, lons, data, filename)
Save lat-lon gridded data as gmt .grd file. :param lats: Grid latitude coordinates in [deg]. :type lats: iterable :param lons: Grid longitude coordinates in [deg]. :type lons: iterable :param data: Grid data of any kind. :type data: :py:class:`~numpy.ndarray`, ``(n_lons, n_lats)`` :param filename: Filename of the written grid file. :type filename: str
Save lat-lon gridded data as gmt .grd file.
[ "Save", "lat", "-", "lon", "gridded", "data", "as", "gmt", ".", "grd", "file", "." ]
def _save_grid(lats, lons, data, filename): ''' Save lat-lon gridded data as gmt .grd file. :param lats: Grid latitude coordinates in [deg]. :type lats: iterable :param lons: Grid longitude coordinates in [deg]. :type lons: iterable :param data: Grid data of any kind. :type data: :py:class:`~numpy.ndarray`, ``(n_lons, n_lats)`` :param filename: Filename of the written grid file. :type filename: str ''' gmtpy.savegrd(lons, lats, data, filename=filename, naming='lonlat')
[ "def", "_save_grid", "(", "lats", ",", "lons", ",", "data", ",", "filename", ")", ":", "gmtpy", ".", "savegrd", "(", "lons", ",", "lats", ",", "data", ",", "filename", "=", "filename", ",", "naming", "=", "'lonlat'", ")" ]
https://github.com/pyrocko/pyrocko/blob/b6baefb7540fb7fce6ed9b856ec0c413961a4320/src/plot/dynamic_rupture.py#L63-L88
romanz/trezor-agent
23f8ef09a5b8eda2187b6883487d7ce0d9bd0b5e
libagent/age/client.py
python
create_identity
(user_id)
return result
Create AGE identity for hardware device.
Create AGE identity for hardware device.
[ "Create", "AGE", "identity", "for", "hardware", "device", "." ]
def create_identity(user_id): """Create AGE identity for hardware device.""" result = interface.Identity(identity_str='age://', curve_name="ed25519") result.identity_dict['host'] = user_id return result
[ "def", "create_identity", "(", "user_id", ")", ":", "result", "=", "interface", ".", "Identity", "(", "identity_str", "=", "'age://'", ",", "curve_name", "=", "\"ed25519\"", ")", "result", ".", "identity_dict", "[", "'host'", "]", "=", "user_id", "return", "...
https://github.com/romanz/trezor-agent/blob/23f8ef09a5b8eda2187b6883487d7ce0d9bd0b5e/libagent/age/client.py#L13-L17
sripathikrishnan/redis-rdb-tools
548b11ec3c81a603f5b321228d07a61a0b940159
rdbtools/memprofiler.py
python
MemoryCallback.start_stream
(self, key, listpacks_count, expiry, info)
[]
def start_stream(self, key, listpacks_count, expiry, info): self._key_expiry = expiry self._current_encoding = info['encoding'] self._current_size = self.top_level_object_overhead(key, expiry) self._current_size += self.sizeof_pointer()*2 + 8 + 16 # stream struct self._current_size += self.sizeof_pointer() + 8*2 # rax struct self._listpacks_count = listpacks_count
[ "def", "start_stream", "(", "self", ",", "key", ",", "listpacks_count", ",", "expiry", ",", "info", ")", ":", "self", ".", "_key_expiry", "=", "expiry", "self", ".", "_current_encoding", "=", "info", "[", "'encoding'", "]", "self", ".", "_current_size", "=...
https://github.com/sripathikrishnan/redis-rdb-tools/blob/548b11ec3c81a603f5b321228d07a61a0b940159/rdbtools/memprofiler.py#L332-L338
BEEmod/BEE2.4
02767f3cf476581789425ab308ca1bea978f6a74
src/editoritems_props.py
python
UnknownProp.__getstate__
(self)
return (self.name, self.default, self.index, self.allow_user_default)
All the properties have the same attributes.
All the properties have the same attributes.
[ "All", "the", "properties", "have", "the", "same", "attributes", "." ]
def __getstate__(self): """All the properties have the same attributes.""" return (self.name, self.default, self.index, self.allow_user_default)
[ "def", "__getstate__", "(", "self", ")", ":", "return", "(", "self", ".", "name", ",", "self", ".", "default", ",", "self", ".", "index", ",", "self", ".", "allow_user_default", ")" ]
https://github.com/BEEmod/BEE2.4/blob/02767f3cf476581789425ab308ca1bea978f6a74/src/editoritems_props.py#L113-L115
houtianze/bypy
10fd0f18378174a775a05a366cc20ba6609f96c6
bypy/bypy.py
python
ByPy.__listrecycle_act
(self, r, args)
return const.ENoError
[]
def __listrecycle_act(self, r, args): print_pcs_list(r.json()) return const.ENoError
[ "def", "__listrecycle_act", "(", "self", ",", "r", ",", "args", ")", ":", "print_pcs_list", "(", "r", ".", "json", "(", ")", ")", "return", "const", ".", "ENoError" ]
https://github.com/houtianze/bypy/blob/10fd0f18378174a775a05a366cc20ba6609f96c6/bypy/bypy.py#L2587-L2589
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/transports/transport.py
python
Transport.copy
(self, remotesource, remotedestination, dereference=False, recursive=True)
Copy a file or a directory from remote source to remote destination (On the same remote machine) :param str remotesource: path of the remote source directory / file :param str remotedestination: path of the remote destination directory / file :param dereference: if True copy the contents of any symlinks found, otherwise copy the symlinks themselves :type dereference: bool :param recursive: if True copy directories recursively, otherwise only copy the specified file(s) :type recursive: bool :raises: IOError, if one of src or dst does not exist
Copy a file or a directory from remote source to remote destination (On the same remote machine)
[ "Copy", "a", "file", "or", "a", "directory", "from", "remote", "source", "to", "remote", "destination", "(", "On", "the", "same", "remote", "machine", ")" ]
def copy(self, remotesource, remotedestination, dereference=False, recursive=True): """ Copy a file or a directory from remote source to remote destination (On the same remote machine) :param str remotesource: path of the remote source directory / file :param str remotedestination: path of the remote destination directory / file :param dereference: if True copy the contents of any symlinks found, otherwise copy the symlinks themselves :type dereference: bool :param recursive: if True copy directories recursively, otherwise only copy the specified file(s) :type recursive: bool :raises: IOError, if one of src or dst does not exist """
[ "def", "copy", "(", "self", ",", "remotesource", ",", "remotedestination", ",", "dereference", "=", "False", ",", "recursive", "=", "True", ")", ":" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/transports/transport.py#L293-L306
dr-prodigy/python-holidays
57dd2ed2b8659c76f776f10207456e5231c82099
holidays/holiday_base.py
python
HolidayBase.pop_named
(self, name: str)
return to_pop
Remove (no longer treat at as holiday) all dates matching the provided holiday name. The match will be made case insensitively and partial matches will be removed. If default is not given and date is not a holiday, a KeyError is raised.
Remove (no longer treat at as holiday) all dates matching the provided holiday name. The match will be made case insensitively and partial matches will be removed. If default is not given and date is not a holiday, a KeyError is raised.
[ "Remove", "(", "no", "longer", "treat", "at", "as", "holiday", ")", "all", "dates", "matching", "the", "provided", "holiday", "name", ".", "The", "match", "will", "be", "made", "case", "insensitively", "and", "partial", "matches", "will", "be", "removed", ...
def pop_named(self, name: str) -> List[date]: """Remove (no longer treat at as holiday) all dates matching the provided holiday name. The match will be made case insensitively and partial matches will be removed. If default is not given and date is not a holiday, a KeyError is raised.""" to_pop = self.get_named(name) if not to_pop: raise KeyError(name) for key in to_pop: self.pop(key) return to_pop
[ "def", "pop_named", "(", "self", ",", "name", ":", "str", ")", "->", "List", "[", "date", "]", ":", "to_pop", "=", "self", ".", "get_named", "(", "name", ")", "if", "not", "to_pop", ":", "raise", "KeyError", "(", "name", ")", "for", "key", "in", ...
https://github.com/dr-prodigy/python-holidays/blob/57dd2ed2b8659c76f776f10207456e5231c82099/holidays/holiday_base.py#L354-L364
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/database.py
python
InstalledDistribution.__repr__
(self)
return '<InstalledDistribution %r %s at %r>' % ( self.name, self.version, self.path)
[]
def __repr__(self): return '<InstalledDistribution %r %s at %r>' % ( self.name, self.version, self.path)
[ "def", "__repr__", "(", "self", ")", ":", "return", "'<InstalledDistribution %r %s at %r>'", "%", "(", "self", ".", "name", ",", "self", ".", "version", ",", "self", ".", "path", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/database.py#L562-L564
bleakie/MaskInsightface
94511404eaa7912945fa087e6445a3608c46aaea
src/align/detect_face.py
python
Network.feed
(self, *args)
return self
Set the input(s) for the next operation by replacing the terminal nodes. The arguments can be either layer names or the actual layers.
Set the input(s) for the next operation by replacing the terminal nodes. The arguments can be either layer names or the actual layers.
[ "Set", "the", "input", "(", "s", ")", "for", "the", "next", "operation", "by", "replacing", "the", "terminal", "nodes", ".", "The", "arguments", "can", "be", "either", "layer", "names", "or", "the", "actual", "layers", "." ]
def feed(self, *args): '''Set the input(s) for the next operation by replacing the terminal nodes. The arguments can be either layer names or the actual layers. ''' assert len(args) != 0 self.terminals = [] for fed_layer in args: if isinstance(fed_layer, string_types): try: fed_layer = self.layers[fed_layer] except KeyError: raise KeyError('Unknown layer name fed: %s' % fed_layer) self.terminals.append(fed_layer) return self
[ "def", "feed", "(", "self", ",", "*", "args", ")", ":", "assert", "len", "(", "args", ")", "!=", "0", "self", ".", "terminals", "=", "[", "]", "for", "fed_layer", "in", "args", ":", "if", "isinstance", "(", "fed_layer", ",", "string_types", ")", ":...
https://github.com/bleakie/MaskInsightface/blob/94511404eaa7912945fa087e6445a3608c46aaea/src/align/detect_face.py#L97-L110
python-excel/xlrd
0c4e80b3d48dfe2250ac4e514c8231a742fee221
xlrd/book.py
python
Book.unload_sheet
(self, sheet_name_or_index)
:param sheet_name_or_index: Name or index of sheet to be unloaded. .. versionadded:: 0.7.1
:param sheet_name_or_index: Name or index of sheet to be unloaded.
[ ":", "param", "sheet_name_or_index", ":", "Name", "or", "index", "of", "sheet", "to", "be", "unloaded", "." ]
def unload_sheet(self, sheet_name_or_index): """ :param sheet_name_or_index: Name or index of sheet to be unloaded. .. versionadded:: 0.7.1 """ if isinstance(sheet_name_or_index, int): sheetx = sheet_name_or_index else: try: sheetx = self._sheet_names.index(sheet_name_or_index) except ValueError: raise XLRDError('No sheet named <%r>' % sheet_name_or_index) self._sheet_list[sheetx] = None
[ "def", "unload_sheet", "(", "self", ",", "sheet_name_or_index", ")", ":", "if", "isinstance", "(", "sheet_name_or_index", ",", "int", ")", ":", "sheetx", "=", "sheet_name_or_index", "else", ":", "try", ":", "sheetx", "=", "self", ".", "_sheet_names", ".", "i...
https://github.com/python-excel/xlrd/blob/0c4e80b3d48dfe2250ac4e514c8231a742fee221/xlrd/book.py#L507-L520
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/cross_validation.py
python
BaseShuffleSplit._iter_indices
(self)
Generate (train, test) indices
Generate (train, test) indices
[ "Generate", "(", "train", "test", ")", "indices" ]
def _iter_indices(self): """Generate (train, test) indices"""
[ "def", "_iter_indices", "(", "self", ")", ":" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/cross_validation.py#L786-L787
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xmlrpc/client.py
python
Unmarshaller.close
(self)
return tuple(self._stack)
[]
def close(self): # return response tuple and target method if self._type is None or self._marks: raise ResponseError() if self._type == "fault": raise Fault(**self._stack[0]) return tuple(self._stack)
[ "def", "close", "(", "self", ")", ":", "# return response tuple and target method", "if", "self", ".", "_type", "is", "None", "or", "self", ".", "_marks", ":", "raise", "ResponseError", "(", ")", "if", "self", ".", "_type", "==", "\"fault\"", ":", "raise", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xmlrpc/client.py#L643-L649
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/setuptools/dist.py
python
Distribution.get_command_class
(self, command)
Pluggable version of get_command_class()
Pluggable version of get_command_class()
[ "Pluggable", "version", "of", "get_command_class", "()" ]
def get_command_class(self, command): """Pluggable version of get_command_class()""" if command in self.cmdclass: return self.cmdclass[command] for ep in pkg_resources.iter_entry_points('distutils.commands', command): ep.require(installer=self.fetch_build_egg) self.cmdclass[command] = cmdclass = ep.load() return cmdclass else: return _Distribution.get_command_class(self, command)
[ "def", "get_command_class", "(", "self", ",", "command", ")", ":", "if", "command", "in", "self", ".", "cmdclass", ":", "return", "self", ".", "cmdclass", "[", "command", "]", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'distutils.com...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/setuptools/dist.py#L472-L482
wimleers/fileconveyor
4b2e21d9fde39152b28b41781013f6c0cff02c06
fileconveyor/fsmonitor_inotify.py
python
FSMonitorInotify.__process_pathscanner_updates
(self, update_list, callback)
[]
def __process_pathscanner_updates(self, update_list, callback): self.lock.acquire() if len(update_list) > 0: callback(update_list) del update_list[:] # Clear the list with updates. self.lock.release()
[ "def", "__process_pathscanner_updates", "(", "self", ",", "update_list", ",", "callback", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "if", "len", "(", "update_list", ")", ">", "0", ":", "callback", "(", "update_list", ")", "del", "update_list...
https://github.com/wimleers/fileconveyor/blob/4b2e21d9fde39152b28b41781013f6c0cff02c06/fileconveyor/fsmonitor_inotify.py#L141-L146
Fortran-FOSS-Programmers/ford
e93b27188c763a019713f64e2270ae98c8f226e1
ford/utils.py
python
split_path
(path)
return retlist
Splits the argument into its constituent directories and returns them as a list.
Splits the argument into its constituent directories and returns them as a list.
[ "Splits", "the", "argument", "into", "its", "constituent", "directories", "and", "returns", "them", "as", "a", "list", "." ]
def split_path(path): """ Splits the argument into its constituent directories and returns them as a list. """ def recurse_path(path, retlist): if len(retlist) > 100: fullpath = os.path.join( *( [ path, ] + retlist ) ) print("Directory '{}' contains too many levels".format(fullpath)) exit(1) head, tail = os.path.split(path) if len(tail) > 0: retlist.insert(0, tail) recurse_path(head, retlist) elif len(head) > 1: recurse_path(head, retlist) else: return retlist = [] path = os.path.realpath(os.path.normpath(path)) drive, path = os.path.splitdrive(path) if len(drive) > 0: retlist.append(drive) recurse_path(path, retlist) return retlist
[ "def", "split_path", "(", "path", ")", ":", "def", "recurse_path", "(", "path", ",", "retlist", ")", ":", "if", "len", "(", "retlist", ")", ">", "100", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "*", "(", "[", "path", ",", "]", ...
https://github.com/Fortran-FOSS-Programmers/ford/blob/e93b27188c763a019713f64e2270ae98c8f226e1/ford/utils.py#L179-L212
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/directory/addressbook.py
python
DirectoryAddressBookHomeTypeProvisioningResource.listChildren
(self)
[]
def listChildren(self): if config.EnablePrincipalListings: children = [] for record in ( yield self.directory.recordsWithRecordType(self.recordType) ): if getattr(record, "hasContacts", False): for shortName in record.shortNames: children.append(shortName) returnValue(children) else: # Not a listable collection raise HTTPError(responsecode.FORBIDDEN)
[ "def", "listChildren", "(", "self", ")", ":", "if", "config", ".", "EnablePrincipalListings", ":", "children", "=", "[", "]", "for", "record", "in", "(", "yield", "self", ".", "directory", ".", "recordsWithRecordType", "(", "self", ".", "recordType", ")", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/directory/addressbook.py#L192-L205
jiasenlu/NeuralBabyTalk
c351ae6ca59380eb4cf38384d3e66233b4d9e1b1
tools/pycider/pyciderevalcap/ciderD/ciderD_scorer.py
python
cook_refs
(refs, n=4)
return [precook(ref, n) for ref in refs]
Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. :param refs: list of string : reference sentences for some image :param n: int : number of ngrams for which (ngram) representation is calculated :return: result (list of dict)
Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. :param refs: list of string : reference sentences for some image :param n: int : number of ngrams for which (ngram) representation is calculated :return: result (list of dict)
[ "Takes", "a", "list", "of", "reference", "sentences", "for", "a", "single", "segment", "and", "returns", "an", "object", "that", "encapsulates", "everything", "that", "BLEU", "needs", "to", "know", "about", "them", ".", ":", "param", "refs", ":", "list", "...
def cook_refs(refs, n=4): ## lhuang: oracle will call with "average" '''Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. :param refs: list of string : reference sentences for some image :param n: int : number of ngrams for which (ngram) representation is calculated :return: result (list of dict) ''' return [precook(ref, n) for ref in refs]
[ "def", "cook_refs", "(", "refs", ",", "n", "=", "4", ")", ":", "## lhuang: oracle will call with \"average\"", "return", "[", "precook", "(", "ref", ",", "n", ")", "for", "ref", "in", "refs", "]" ]
https://github.com/jiasenlu/NeuralBabyTalk/blob/c351ae6ca59380eb4cf38384d3e66233b4d9e1b1/tools/pycider/pyciderevalcap/ciderD/ciderD_scorer.py#L34-L42
lonePatient/BERT-NER-Pytorch
bc9276185539c59bbd3d310ea808fea2b618fedf
processors/utils_ner.py
python
DataProcessor._read_text
(self,input_file)
return lines
[]
def _read_text(self,input_file): lines = [] with open(input_file,'r') as f: words = [] labels = [] for line in f: if line.startswith("-DOCSTART-") or line == "" or line == "\n": if words: lines.append({"words":words,"labels":labels}) words = [] labels = [] else: splits = line.split(" ") words.append(splits[0]) if len(splits) > 1: labels.append(splits[-1].replace("\n", "")) else: # Examples could have no label for mode = "test" labels.append("O") if words: lines.append({"words":words,"labels":labels}) return lines
[ "def", "_read_text", "(", "self", ",", "input_file", ")", ":", "lines", "=", "[", "]", "with", "open", "(", "input_file", ",", "'r'", ")", "as", "f", ":", "words", "=", "[", "]", "labels", "=", "[", "]", "for", "line", "in", "f", ":", "if", "li...
https://github.com/lonePatient/BERT-NER-Pytorch/blob/bc9276185539c59bbd3d310ea808fea2b618fedf/processors/utils_ner.py#L32-L53
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/core/configuration/system.py
python
SystemSection.can_initialize_system_clock
(self)
return self._is_boot_iso or self._is_live_os or self._is_booted_os
Can we initialize the System Clock? FIXME: This is a temporary workaround.
Can we initialize the System Clock?
[ "Can", "we", "initialize", "the", "System", "Clock?" ]
def can_initialize_system_clock(self): """Can we initialize the System Clock? FIXME: This is a temporary workaround. """ return self._is_boot_iso or self._is_live_os or self._is_booted_os
[ "def", "can_initialize_system_clock", "(", "self", ")", ":", "return", "self", ".", "_is_boot_iso", "or", "self", ".", "_is_live_os", "or", "self", ".", "_is_booted_os" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/core/configuration/system.py#L92-L97
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/appengine/handlers/performance_report/performance_analyzer.py
python
LibFuzzerPerformanceAnalyzer.analyzer_timeout
(self, stats)
return 0.0
Check if there is a libFuzzer timeout in the stats. Returns a number in range [0.0, 1.0].
Check if there is a libFuzzer timeout in the stats. Returns a number in range [0.0, 1.0].
[ "Check", "if", "there", "is", "a", "libFuzzer", "timeout", "in", "the", "stats", ".", "Returns", "a", "number", "in", "range", "[", "0", ".", "0", "1", ".", "0", "]", "." ]
def analyzer_timeout(self, stats): """Check if there is a libFuzzer timeout in the stats. Returns a number in range [0.0, 1.0].""" if stats['timeout_count']: return 1.0 return 0.0
[ "def", "analyzer_timeout", "(", "self", ",", "stats", ")", ":", "if", "stats", "[", "'timeout_count'", "]", ":", "return", "1.0", "return", "0.0" ]
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/appengine/handlers/performance_report/performance_analyzer.py#L346-L352
NeuromorphicProcessorProject/snn_toolbox
a85ada7b5d060500703285ef8a68f06ea1ffda65
snntoolbox/parsing/utils.py
python
AbstractModelParser.parse_concatenate
(self, layer, attributes)
Parse a concatenation layer. Parameters ---------- layer: Layer. attributes: dict The layer attributes as key-value pairs in a dict.
Parse a concatenation layer.
[ "Parse", "a", "concatenation", "layer", "." ]
def parse_concatenate(self, layer, attributes): """Parse a concatenation layer. Parameters ---------- layer: Layer. attributes: dict The layer attributes as key-value pairs in a dict. """ pass
[ "def", "parse_concatenate", "(", "self", ",", "layer", ",", "attributes", ")", ":", "pass" ]
https://github.com/NeuromorphicProcessorProject/snn_toolbox/blob/a85ada7b5d060500703285ef8a68f06ea1ffda65/snntoolbox/parsing/utils.py#L766-L778
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_internal/commands/wheel.py
python
WheelCommand.__init__
(self, *args, **kw)
[]
def __init__(self, *args, **kw): super(WheelCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-w', '--wheel-dir', dest='wheel_dir', metavar='dir', default=os.curdir, help=("Build wheels into <dir>, where the default is the " "current working directory."), ) cmd_opts.add_option(cmdoptions.no_binary()) cmd_opts.add_option(cmdoptions.only_binary()) cmd_opts.add_option(cmdoptions.prefer_binary()) cmd_opts.add_option( '--build-option', dest='build_options', metavar='options', action='append', help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", ) cmd_opts.add_option(cmdoptions.no_build_isolation()) cmd_opts.add_option(cmdoptions.constraints()) cmd_opts.add_option(cmdoptions.editable()) cmd_opts.add_option(cmdoptions.requirements()) cmd_opts.add_option(cmdoptions.src()) cmd_opts.add_option(cmdoptions.ignore_requires_python()) cmd_opts.add_option(cmdoptions.no_deps()) cmd_opts.add_option(cmdoptions.build_dir()) cmd_opts.add_option(cmdoptions.progress_bar()) cmd_opts.add_option( '--global-option', dest='global_options', action='append', metavar='options', help="Extra global options to be supplied to the setup.py " "call before the 'bdist_wheel' command.") cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option(cmdoptions.no_clean()) cmd_opts.add_option(cmdoptions.require_hashes()) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "super", "(", "WheelCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kw", ")", "cmd_opts", "=", "self", ".", "cmd_opts", "cmd_opts", "....
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/commands/wheel.py#L46-L104
obspy/obspy
0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f
obspy/clients/seishub/client.py
python
_BaseRESTClient.get_xml_resource
(self, resource_name, **kwargs)
return self.client._objectify(url, **kwargs)
Gets a XML resource. :type resource_name: str :param resource_name: Name of the resource. :return: Resource as :class:`lxml.objectify.ObjectifiedElement`
Gets a XML resource.
[ "Gets", "a", "XML", "resource", "." ]
def get_xml_resource(self, resource_name, **kwargs): """ Gets a XML resource. :type resource_name: str :param resource_name: Name of the resource. :return: Resource as :class:`lxml.objectify.ObjectifiedElement` """ url = '/xml/' + self.package + '/' + self.resourcetype + '/' + \ resource_name return self.client._objectify(url, **kwargs)
[ "def", "get_xml_resource", "(", "self", ",", "resource_name", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'/xml/'", "+", "self", ".", "package", "+", "'/'", "+", "self", ".", "resourcetype", "+", "'/'", "+", "resource_name", "return", "self", ".", ...
https://github.com/obspy/obspy/blob/0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f/obspy/clients/seishub/client.py#L267-L277
taigaio/taiga-ncurses
65312098f2d167762e0dbd1c16019754ab64d068
taiga_ncurses/api/client.py
python
TaigaClient.update_issue
(self, id, data_dict={}, params={})
return self._patch(url, data_dict, params)
[]
def update_issue(self, id, data_dict={}, params={}): url = urljoin(self._host, self.URLS.get("issue").format(id)) return self._patch(url, data_dict, params)
[ "def", "update_issue", "(", "self", ",", "id", ",", "data_dict", "=", "{", "}", ",", "params", "=", "{", "}", ")", ":", "url", "=", "urljoin", "(", "self", ".", "_host", ",", "self", ".", "URLS", ".", "get", "(", "\"issue\"", ")", ".", "format", ...
https://github.com/taigaio/taiga-ncurses/blob/65312098f2d167762e0dbd1c16019754ab64d068/taiga_ncurses/api/client.py#L293-L295
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/template.py
python
timestamp_custom
(value, date_format=DATE_STR_FORMAT, local=True, default=_SENTINEL)
Filter to convert given timestamp to format.
Filter to convert given timestamp to format.
[ "Filter", "to", "convert", "given", "timestamp", "to", "format", "." ]
def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True, default=_SENTINEL): """Filter to convert given timestamp to format.""" try: date = dt_util.utc_from_timestamp(value) if local: date = dt_util.as_local(date) return date.strftime(date_format) except (ValueError, TypeError): # If timestamp can't be converted if default is _SENTINEL: warn_no_default("timestamp_custom", value, value) return value return default
[ "def", "timestamp_custom", "(", "value", ",", "date_format", "=", "DATE_STR_FORMAT", ",", "local", "=", "True", ",", "default", "=", "_SENTINEL", ")", ":", "try", ":", "date", "=", "dt_util", ".", "utc_from_timestamp", "(", "value", ")", "if", "local", ":"...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/template.py#L1448-L1462
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cws/v20180312/models.py
python
DeleteMonitorsRequest.__init__
(self)
r""" :param MonitorIds: 监控任务ID列表 :type MonitorIds: list of int non-negative
r""" :param MonitorIds: 监控任务ID列表 :type MonitorIds: list of int non-negative
[ "r", ":", "param", "MonitorIds", ":", "监控任务ID列表", ":", "type", "MonitorIds", ":", "list", "of", "int", "non", "-", "negative" ]
def __init__(self): r""" :param MonitorIds: 监控任务ID列表 :type MonitorIds: list of int non-negative """ self.MonitorIds = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "MonitorIds", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cws/v20180312/models.py#L284-L289
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/objc/_convenience_nsset.py
python
nsset_symmetric_difference
(self, other)
return result
[]
def nsset_symmetric_difference(self, other): result = NSMutableSet() if not hasattr(other, '__contains__'): other = list(other) for item in iter(self): if item not in other: result.add(item) for item in other: if item not in self: result.add(item) return result
[ "def", "nsset_symmetric_difference", "(", "self", ",", "other", ")", ":", "result", "=", "NSMutableSet", "(", ")", "if", "not", "hasattr", "(", "other", ",", "'__contains__'", ")", ":", "other", "=", "list", "(", "other", ")", "for", "item", "in", "iter"...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/objc/_convenience_nsset.py#L67-L77
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment2/q2_NER.py
python
NERModel.add_training_op
(self, loss)
return train_op
Sets up the training Ops. Creates an optimizer and applies the gradients to all trainable variables. The Op returned by this function is what must be passed to the `sess.run()` call to cause the model to train. See https://www.tensorflow.org/versions/r0.7/api_docs/python/train.html#Optimizer for more information. Hint: Use tf.train.AdamOptimizer for this model. Calling optimizer.minimize() will return a train_op object. Args: loss: Loss tensor, from cross_entropy_loss. Returns: train_op: The Op for training.
Sets up the training Ops.
[ "Sets", "up", "the", "training", "Ops", "." ]
def add_training_op(self, loss): """Sets up the training Ops. Creates an optimizer and applies the gradients to all trainable variables. The Op returned by this function is what must be passed to the `sess.run()` call to cause the model to train. See https://www.tensorflow.org/versions/r0.7/api_docs/python/train.html#Optimizer for more information. Hint: Use tf.train.AdamOptimizer for this model. Calling optimizer.minimize() will return a train_op object. Args: loss: Loss tensor, from cross_entropy_loss. Returns: train_op: The Op for training. """ ### YOUR CODE HERE train_op = tf.train.AdamOptimizer(self.config.lr).minimize(loss) ### END YOUR CODE return train_op
[ "def", "add_training_op", "(", "self", ",", "loss", ")", ":", "### YOUR CODE HERE", "train_op", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "self", ".", "config", ".", "lr", ")", ".", "minimize", "(", "loss", ")", "### END YOUR CODE", "return", "tr...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment2/q2_NER.py#L220-L242
nanotube/supybot-bitcoin-marketmonitor
8cdcd6055b716fa9dbdba8f2311c44f836ba55ef
RatingSystem/plugin.py
python
RatingSystem._getrating
(self, nick)
return data
Get cumulative rating for user. For use from other plugins.
Get cumulative rating for user. For use from other plugins.
[ "Get", "cumulative", "rating", "for", "user", ".", "For", "use", "from", "other", "plugins", "." ]
def _getrating(self, nick): """Get cumulative rating for user. For use from other plugins.""" data = self.db.get(nick) if len(data) == 0: return None data = data[0] return data
[ "def", "_getrating", "(", "self", ",", "nick", ")", ":", "data", "=", "self", ".", "db", ".", "get", "(", "nick", ")", "if", "len", "(", "data", ")", "==", "0", ":", "return", "None", "data", "=", "data", "[", "0", "]", "return", "data" ]
https://github.com/nanotube/supybot-bitcoin-marketmonitor/blob/8cdcd6055b716fa9dbdba8f2311c44f836ba55ef/RatingSystem/plugin.py#L444-L450
richardaecn/class-balanced-loss
1d7857208a2abc03d84e35a9d5383af8225d4b4d
tpu/models/official/mobilenet/mobilenet.py
python
model_fn
(features, labels, mode, params)
return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_op=train_op, eval_metrics=eval_metrics)
Mobilenet v1 model using Estimator API.
Mobilenet v1 model using Estimator API.
[ "Mobilenet", "v1", "model", "using", "Estimator", "API", "." ]
def model_fn(features, labels, mode, params): """Mobilenet v1 model using Estimator API.""" num_classes = FLAGS.num_classes training_active = (mode == tf.estimator.ModeKeys.TRAIN) eval_active = (mode == tf.estimator.ModeKeys.EVAL) features = tensor_transform_fn(features, params['input_perm']) if FLAGS.clear_update_collections: # updates_collections must be set to None in order to use fused batchnorm with arg_scope(mobilenet_v1.mobilenet_v1_arg_scope()): logits, end_points = mobilenet_v1.mobilenet_v1( features, num_classes, is_training=training_active, depth_multiplier=FLAGS.depth_multiplier) else: with arg_scope(mobilenet_v1.mobilenet_v1_arg_scope()): logits, end_points = mobilenet_v1.mobilenet_v1( features, num_classes, is_training=training_active, depth_multiplier=FLAGS.depth_multiplier) predictions = { 'classes': tf.argmax(input=logits, axis=1), 'probabilities': tf.nn.softmax(logits, name='softmax_tensor') } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) if mode == tf.estimator.ModeKeys.EVAL and FLAGS.display_tensors and ( not FLAGS.use_tpu): with tf.control_dependencies([ tf.Print( predictions['classes'], [predictions['classes']], summarize=FLAGS.eval_batch_size, message='prediction: ') ]): labels = tf.Print( labels, [labels], summarize=FLAGS.eval_batch_size, message='label: ') one_hot_labels = tf.one_hot(labels, FLAGS.num_classes, dtype=tf.int32) tf.losses.softmax_cross_entropy( onehot_labels=one_hot_labels, logits=logits, weights=1.0, label_smoothing=0.1) loss = tf.losses.get_total_loss(add_regularization_losses=True) initial_learning_rate = FLAGS.learning_rate * FLAGS.train_batch_size / 256 final_learning_rate = 0.0001 * initial_learning_rate train_op = None if training_active: batches_per_epoch = _NUM_TRAIN_IMAGES // FLAGS.train_batch_size global_step = tf.train.get_or_create_global_step() learning_rate = tf.train.exponential_decay( learning_rate=initial_learning_rate, global_step=global_step, decay_steps=FLAGS.learning_rate_decay_epochs * batches_per_epoch, decay_rate=FLAGS.learning_rate_decay, staircase=True) # Set a minimum boundary for the learning rate. learning_rate = tf.maximum( learning_rate, final_learning_rate, name='learning_rate') if FLAGS.optimizer == 'sgd': tf.logging.info('Using SGD optimizer') optimizer = tf.train.GradientDescentOptimizer( learning_rate=learning_rate) elif FLAGS.optimizer == 'momentum': tf.logging.info('Using Momentum optimizer') optimizer = tf.train.MomentumOptimizer( learning_rate=learning_rate, momentum=0.9) elif FLAGS.optimizer == 'RMS': tf.logging.info('Using RMS optimizer') optimizer = tf.train.RMSPropOptimizer( learning_rate, RMSPROP_DECAY, momentum=RMSPROP_MOMENTUM, epsilon=RMSPROP_EPSILON) else: tf.logging.fatal('Unknown optimizer:', FLAGS.optimizer) if FLAGS.use_tpu: optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize(loss, global_step=global_step) if FLAGS.moving_average: ema = tf.train.ExponentialMovingAverage( decay=MOVING_AVERAGE_DECAY, num_updates=global_step) variables_to_average = (tf.trainable_variables() + tf.moving_average_variables()) with tf.control_dependencies([train_op]), tf.name_scope('moving_average'): train_op = ema.apply(variables_to_average) eval_metrics = None if eval_active: def metric_fn(labels, predictions): accuracy = tf.metrics.accuracy(labels, tf.argmax( input=predictions, axis=1)) return {'accuracy': accuracy} if FLAGS.use_logits: eval_predictions = logits else: eval_predictions = end_points['Predictions'] eval_metrics = (metric_fn, [labels, eval_predictions]) return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_op=train_op, eval_metrics=eval_metrics)
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "num_classes", "=", "FLAGS", ".", "num_classes", "training_active", "=", "(", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ")", "eval_active", ...
https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/official/mobilenet/mobilenet.py#L418-L536
nneonneo/eqgrp-free-file
49e457d7ac870d5e00f5a247b94476cd5643f3ba
Firewall/EXPLOITS/EXBA/scapy/utils6.py
python
in6_ctop
(addr)
return inet_ntop(socket.AF_INET6, "".join(res))
Convert an IPv6 address in Compact Representation Notation (RFC 1924) to printable representation ;-) Returns None on error.
Convert an IPv6 address in Compact Representation Notation (RFC 1924) to printable representation ;-) Returns None on error.
[ "Convert", "an", "IPv6", "address", "in", "Compact", "Representation", "Notation", "(", "RFC", "1924", ")", "to", "printable", "representation", ";", "-", ")", "Returns", "None", "on", "error", "." ]
def in6_ctop(addr): """ Convert an IPv6 address in Compact Representation Notation (RFC 1924) to printable representation ;-) Returns None on error. """ if len(addr) != 20 or not reduce(lambda x,y: x and y, map(lambda x: x in _rfc1924map, addr)): return None i = 0 for c in addr: j = _rfc1924map.index(c) i = 85*i + j res = [] for j in range(4): res.append(struct.pack("!I", i%2**32)) i = i/(2**32) res.reverse() return inet_ntop(socket.AF_INET6, "".join(res))
[ "def", "in6_ctop", "(", "addr", ")", ":", "if", "len", "(", "addr", ")", "!=", "20", "or", "not", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "and", "y", ",", "map", "(", "lambda", "x", ":", "x", "in", "_rfc1924map", ",", "addr", ")", "...
https://github.com/nneonneo/eqgrp-free-file/blob/49e457d7ac870d5e00f5a247b94476cd5643f3ba/Firewall/EXPLOITS/EXBA/scapy/utils6.py#L442-L460
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/skip_thoughts/skip_thoughts/vocabulary_expansion.py
python
_load_skip_thoughts_embeddings
(checkpoint_path)
return word_embedding
Loads the embedding matrix from a skip-thoughts model checkpoint. Args: checkpoint_path: Model checkpoint file or directory containing a checkpoint file. Returns: word_embedding: A numpy array of shape [vocab_size, embedding_dim]. Raises: ValueError: If no checkpoint file matches checkpoint_path.
Loads the embedding matrix from a skip-thoughts model checkpoint.
[ "Loads", "the", "embedding", "matrix", "from", "a", "skip", "-", "thoughts", "model", "checkpoint", "." ]
def _load_skip_thoughts_embeddings(checkpoint_path): """Loads the embedding matrix from a skip-thoughts model checkpoint. Args: checkpoint_path: Model checkpoint file or directory containing a checkpoint file. Returns: word_embedding: A numpy array of shape [vocab_size, embedding_dim]. Raises: ValueError: If no checkpoint file matches checkpoint_path. """ if tf.gfile.IsDirectory(checkpoint_path): checkpoint_file = tf.train.latest_checkpoint(checkpoint_path) if not checkpoint_file: raise ValueError("No checkpoint file found in %s" % checkpoint_path) else: checkpoint_file = checkpoint_path tf.logging.info("Loading skip-thoughts embedding matrix from %s", checkpoint_file) reader = tf.train.NewCheckpointReader(checkpoint_file) word_embedding = reader.get_tensor("word_embedding") tf.logging.info("Loaded skip-thoughts embedding matrix of shape %s", word_embedding.shape) return word_embedding
[ "def", "_load_skip_thoughts_embeddings", "(", "checkpoint_path", ")", ":", "if", "tf", ".", "gfile", ".", "IsDirectory", "(", "checkpoint_path", ")", ":", "checkpoint_file", "=", "tf", ".", "train", ".", "latest_checkpoint", "(", "checkpoint_path", ")", "if", "n...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/skip_thoughts/skip_thoughts/vocabulary_expansion.py#L69-L96
KhronosGroup/OpenXR-SDK-Source
76756e2e7849b15466d29bee7d80cada92865550
specification/scripts/validitygenerator.py
python
ValidityOutputGenerator.makeExternalTypeName
(self, name)
return self.conventions.makeExternalTypeName(name)
Prepend the appropriate format macro for an external type like uint32_t to a type name.
Prepend the appropriate format macro for an external type like uint32_t to a type name.
[ "Prepend", "the", "appropriate", "format", "macro", "for", "an", "external", "type", "like", "uint32_t", "to", "a", "type", "name", "." ]
def makeExternalTypeName(self, name): """Prepend the appropriate format macro for an external type like uint32_t to a type name.""" # delegate to conventions return self.conventions.makeExternalTypeName(name)
[ "def", "makeExternalTypeName", "(", "self", ",", "name", ")", ":", "# delegate to conventions", "return", "self", ".", "conventions", ".", "makeExternalTypeName", "(", "name", ")" ]
https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/76756e2e7849b15466d29bee7d80cada92865550/specification/scripts/validitygenerator.py#L320-L323