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
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/dataclasses.py
python
is_dataclass
(obj)
return hasattr(cls, _FIELDS)
Returns True if obj is a dataclass or an instance of a dataclass.
Returns True if obj is a dataclass or an instance of a dataclass.
[ "Returns", "True", "if", "obj", "is", "a", "dataclass", "or", "an", "instance", "of", "a", "dataclass", "." ]
def is_dataclass(obj): """Returns True if obj is a dataclass or an instance of a dataclass.""" cls = obj if isinstance(obj, type) and not isinstance(obj, GenericAlias) else type(obj) return hasattr(cls, _FIELDS)
[ "def", "is_dataclass", "(", "obj", ")", ":", "cls", "=", "obj", "if", "isinstance", "(", "obj", ",", "type", ")", "and", "not", "isinstance", "(", "obj", ",", "GenericAlias", ")", "else", "type", "(", "obj", ")", "return", "hasattr", "(", "cls", ",",...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/dataclasses.py#L1213-L1217
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/tkinter/colorchooser.py
python
Chooser._fixresult
(self, widget, result)
return (r//256, g//256, b//256), str(result)
Adjust result returned from call to tk_chooseColor. Return both an RGB tuple of ints in the range (0, 255) and the tk color string in the form #rrggbb.
Adjust result returned from call to tk_chooseColor.
[ "Adjust", "result", "returned", "from", "call", "to", "tk_chooseColor", "." ]
def _fixresult(self, widget, result): """Adjust result returned from call to tk_chooseColor. Return both an RGB tuple of ints in the range (0, 255) and the tk color string in the form #rrggbb. """ # Result can be many things: an empty tuple, an empty string, or # a _tkinter.Tcl_Obj, so this somewhat weird check handles that. if not result or not str(result): return None, None # canceled # To simplify application code, the color chooser returns # an RGB tuple together with the Tk color string. r, g, b = widget.winfo_rgb(result) return (r//256, g//256, b//256), str(result)
[ "def", "_fixresult", "(", "self", ",", "widget", ",", "result", ")", ":", "# Result can be many things: an empty tuple, an empty string, or", "# a _tkinter.Tcl_Obj, so this somewhat weird check handles that.", "if", "not", "result", "or", "not", "str", "(", "result", ")", "...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/tkinter/colorchooser.py#L48-L62
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/setuptools/command/build_py.py
python
build_py.check_package
(self, package, package_dir)
return init_py
Check namespace packages' __init__ for declare_namespace
Check namespace packages' __init__ for declare_namespace
[ "Check", "namespace", "packages", "__init__", "for", "declare_namespace" ]
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if not init_py or not self.distribution.namespace_packages: return init_py for pkg in self.distribution.namespace_packages: if pkg == package or pkg.startswith(package + '.'): break else: return init_py with io.open(init_py, 'rb') as f: contents = f.read() if b'declare_namespace' not in contents: raise distutils.errors.DistutilsError( "Namespace package problem: %s is a namespace package, but " "its\n__init__.py does not call declare_namespace()! Please " 'fix it.\n(See the setuptools manual under ' '"Namespace Packages" for details.)\n"' % (package,) ) return init_py
[ "def", "check_package", "(", "self", ",", "package", ",", "package_dir", ")", ":", "try", ":", "return", "self", ".", "packages_checked", "[", "package", "]", "except", "KeyError", ":", "pass", "init_py", "=", "orig", ".", "build_py", ".", "check_package", ...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/setuptools/command/build_py.py#L156-L184
wbenbihi/hourglasstensorlfow
356e0638a1bf28ecc92a121812e74d3fd0e353f5
hourglass_tiny.py
python
HourglassModel._accur
(self, pred, gtMap, num_image)
return tf.subtract(tf.to_float(1), err/num_image)
Given a Prediction batch (pred) and a Ground Truth batch (gtMaps), returns one minus the mean distance. Args: pred : Prediction Batch (shape = num_image x 64 x 64) gtMaps : Ground Truth Batch (shape = num_image x 64 x 64) num_image : (int) Number of images in batch Returns: (float)
Given a Prediction batch (pred) and a Ground Truth batch (gtMaps), returns one minus the mean distance. Args: pred : Prediction Batch (shape = num_image x 64 x 64) gtMaps : Ground Truth Batch (shape = num_image x 64 x 64) num_image : (int) Number of images in batch Returns: (float)
[ "Given", "a", "Prediction", "batch", "(", "pred", ")", "and", "a", "Ground", "Truth", "batch", "(", "gtMaps", ")", "returns", "one", "minus", "the", "mean", "distance", ".", "Args", ":", "pred", ":", "Prediction", "Batch", "(", "shape", "=", "num_image",...
def _accur(self, pred, gtMap, num_image): """ Given a Prediction batch (pred) and a Ground Truth batch (gtMaps), returns one minus the mean distance. Args: pred : Prediction Batch (shape = num_image x 64 x 64) gtMaps : Ground Truth Batch (shape = num_image x 64 x 64) num_image : (int) Number of images in batch Returns: (float) """ err = tf.to_float(0) for i in range(num_image): err = tf.add(err, self._compute_err(pred[i], gtMap[i])) return tf.subtract(tf.to_float(1), err/num_image)
[ "def", "_accur", "(", "self", ",", "pred", ",", "gtMap", ",", "num_image", ")", ":", "err", "=", "tf", ".", "to_float", "(", "0", ")", "for", "i", "in", "range", "(", "num_image", ")", ":", "err", "=", "tf", ".", "add", "(", "err", ",", "self",...
https://github.com/wbenbihi/hourglasstensorlfow/blob/356e0638a1bf28ecc92a121812e74d3fd0e353f5/hourglass_tiny.py#L640-L653
pydata/pandas-datareader
3f1d590e6e67cf30aa516d3b1f1921b5c45ccc4b
pandas_datareader/av/__init__.py
python
AlphaVantage.__init__
( self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None, api_key=None, )
[]
def __init__( self, symbols=None, start=None, end=None, retry_count=3, pause=0.1, session=None, api_key=None, ): super(AlphaVantage, self).__init__( symbols=symbols, start=start, end=end, retry_count=retry_count, pause=pause, session=session, ) if api_key is None: api_key = os.getenv("ALPHAVANTAGE_API_KEY") if not api_key or not isinstance(api_key, str): raise ValueError( "The AlphaVantage API key must be provided " "either through the api_key variable or " "through the environment variable " "ALPHAVANTAGE_API_KEY" ) self.api_key = api_key
[ "def", "__init__", "(", "self", ",", "symbols", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "retry_count", "=", "3", ",", "pause", "=", "0.1", ",", "session", "=", "None", ",", "api_key", "=", "None", ",", ")", ":", "sup...
https://github.com/pydata/pandas-datareader/blob/3f1d590e6e67cf30aa516d3b1f1921b5c45ccc4b/pandas_datareader/av/__init__.py#L22-L49
cortex-lab/phy
9a330b9437a3d0b40a37a201d147224e6e7fb462
phy/apps/base.py
python
TemplateMixin.get_mean_spike_template_amplitudes
(self, cluster_id)
return np.mean(self.get_spike_template_amplitudes(spike_ids))
Return the average of the spike template amplitudes.
Return the average of the spike template amplitudes.
[ "Return", "the", "average", "of", "the", "spike", "template", "amplitudes", "." ]
def get_mean_spike_template_amplitudes(self, cluster_id): """Return the average of the spike template amplitudes.""" spike_ids = self._get_amplitude_spike_ids(cluster_id) return np.mean(self.get_spike_template_amplitudes(spike_ids))
[ "def", "get_mean_spike_template_amplitudes", "(", "self", ",", "cluster_id", ")", ":", "spike_ids", "=", "self", ".", "_get_amplitude_spike_ids", "(", "cluster_id", ")", "return", "np", ".", "mean", "(", "self", ".", "get_spike_template_amplitudes", "(", "spike_ids"...
https://github.com/cortex-lab/phy/blob/9a330b9437a3d0b40a37a201d147224e6e7fb462/phy/apps/base.py#L540-L543
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/api/data/information/dns.py
python
DnsRegisterLOC.longitude
(self)
return self.__longitude
:return: tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. :rtype: (int, int, int, int)
:return: tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. :rtype: (int, int, int, int)
[ ":", "return", ":", "tuple", "specifying", "the", "degrees", "minutes", "seconds", "and", "milliseconds", "of", "the", "coordinate", ".", ":", "rtype", ":", "(", "int", "int", "int", "int", ")" ]
def longitude(self): """ :return: tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. :rtype: (int, int, int, int) """ return self.__longitude
[ "def", "longitude", "(", "self", ")", ":", "return", "self", ".", "__longitude" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/api/data/information/dns.py#L1144-L1149
deepmipt/DeepPavlov
08555428388fed3c7b036c0a82a70a25efcabcff
deeppavlov/utils/connector/conversation.py
python
BaseConversation._rearm_self_destruct
(self)
Rearms self-destruct timer.
Rearms self-destruct timer.
[ "Rearms", "self", "-", "destruct", "timer", "." ]
def _rearm_self_destruct(self) -> None: """Rearms self-destruct timer.""" self._timer.cancel() self._start_timer()
[ "def", "_rearm_self_destruct", "(", "self", ")", "->", "None", ":", "self", ".", "_timer", ".", "cancel", "(", ")", "self", ".", "_start_timer", "(", ")" ]
https://github.com/deepmipt/DeepPavlov/blob/08555428388fed3c7b036c0a82a70a25efcabcff/deeppavlov/utils/connector/conversation.py#L93-L96
spywhere/Javatar
e273ec40c209658247a71b109bb90cd126984a29
core/java_utils.py
python
JavaClassPath.get_package
(self)
return self.package
Returns a package within class path
Returns a package within class path
[ "Returns", "a", "package", "within", "class", "path" ]
def get_package(self): """ Returns a package within class path """ return self.package
[ "def", "get_package", "(", "self", ")", ":", "return", "self", ".", "package" ]
https://github.com/spywhere/Javatar/blob/e273ec40c209658247a71b109bb90cd126984a29/core/java_utils.py#L103-L107
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/rewritings.py
python
CNFizer.walk_function
(self, formula, **kwargs)
[]
def walk_function(self, formula, **kwargs): ty = formula.function_symbol().symbol_type() if ty.return_type.is_bool_type(): return formula, CNFizer.TRUE_CNF else: return CNFizer.THEORY_PLACEHOLDER
[ "def", "walk_function", "(", "self", ",", "formula", ",", "*", "*", "kwargs", ")", ":", "ty", "=", "formula", ".", "function_symbol", "(", ")", ".", "symbol_type", "(", ")", "if", "ty", ".", "return_type", ".", "is_bool_type", "(", ")", ":", "return", ...
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/rewritings.py#L164-L169
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/sql/querymodel.py
python
createView
(title, model)
[]
def createView(title, model): global offset, views view = QTableView() views.append(view) view.setModel(model) view.setWindowTitle(title) view.move(100 + offset, 100 + offset) offset += 20 view.show()
[ "def", "createView", "(", "title", ",", "model", ")", ":", "global", "offset", ",", "views", "view", "=", "QTableView", "(", ")", "views", ".", "append", "(", "view", ")", "view", ".", "setModel", "(", "model", ")", "view", ".", "setWindowTitle", "(", ...
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/sql/querymodel.py#L125-L134
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/spatial/distance.py
python
cosine
(u, v)
return dist
Computes the Cosine distance between 1-D arrays. The Cosine distance between `u` and `v`, is defined as .. math:: 1 - \\frac{u \\cdot v} {||u||_2 ||v||_2}. where :math:`u \\cdot v` is the dot product of :math:`u` and :math:`v`. Parameters ---------- u : (N,) array_like Input array. v : (N,) array_like Input array. Returns ------- cosine : double The Cosine distance between vectors `u` and `v`.
Computes the Cosine distance between 1-D arrays.
[ "Computes", "the", "Cosine", "distance", "between", "1", "-", "D", "arrays", "." ]
def cosine(u, v): """ Computes the Cosine distance between 1-D arrays. The Cosine distance between `u` and `v`, is defined as .. math:: 1 - \\frac{u \\cdot v} {||u||_2 ||v||_2}. where :math:`u \\cdot v` is the dot product of :math:`u` and :math:`v`. Parameters ---------- u : (N,) array_like Input array. v : (N,) array_like Input array. Returns ------- cosine : double The Cosine distance between vectors `u` and `v`. """ u = _validate_vector(u) v = _validate_vector(v) dist = 1.0 - np.dot(u, v) / (norm(u) * norm(v)) return dist
[ "def", "cosine", "(", "u", ",", "v", ")", ":", "u", "=", "_validate_vector", "(", "u", ")", "v", "=", "_validate_vector", "(", "v", ")", "dist", "=", "1.0", "-", "np", ".", "dot", "(", "u", ",", "v", ")", "/", "(", "norm", "(", "u", ")", "*...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/spatial/distance.py#L297-L327
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/tools/burnin.py
python
FeedbackAccumulator.GetFeedbackBuf
(self)
return self._feed_buf.getvalue()
Return the contents of the buffer.
Return the contents of the buffer.
[ "Return", "the", "contents", "of", "the", "buffer", "." ]
def GetFeedbackBuf(self): """Return the contents of the buffer.""" return self._feed_buf.getvalue()
[ "def", "GetFeedbackBuf", "(", "self", ")", ":", "return", "self", ".", "_feed_buf", ".", "getvalue", "(", ")" ]
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/tools/burnin.py#L335-L337
merenlab/anvio
9b792e2cedc49ecb7c0bed768261595a0d87c012
anvio/trnaseq.py
python
TRNASeqDataset.report_sub_stats
(self)
Report to terminal stats on potential modification-induced substitutions.
Report to terminal stats on potential modification-induced substitutions.
[ "Report", "to", "terminal", "stats", "on", "potential", "modification", "-", "induced", "substitutions", "." ]
def report_sub_stats(self): """Report to terminal stats on potential modification-induced substitutions.""" count_M = len(self.dict_M) dict_Nf = self.dict_Nf total_sub_count = 0 total_length_M = 0 for seq_M in self.dict_M.values(): length_M = len(dict_Nf[seq_M.name].string) total_sub_count += len(seq_M.sub_positions) total_length_M += length_M mean_sub_per_seq = total_sub_count / count_M mean_sub_per_nt = total_sub_count / total_length_M warning = self.run.warning info = self.run.info warning(None, "SUBSTITUTION SEARCH RESULTS", lc='green', nl_before=1) info("Modified seqs", count_M) info("Mean (*potential*) subs per modified seq", round(mean_sub_per_seq, 1)) info("Mean subs per nt in modified seq", round(mean_sub_per_nt, 3), nl_after=2)
[ "def", "report_sub_stats", "(", "self", ")", ":", "count_M", "=", "len", "(", "self", ".", "dict_M", ")", "dict_Nf", "=", "self", ".", "dict_Nf", "total_sub_count", "=", "0", "total_length_M", "=", "0", "for", "seq_M", "in", "self", ".", "dict_M", ".", ...
https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/trnaseq.py#L3683-L3702
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/sqlalchemy/orm/session.py
python
_state_session
(state)
return None
Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any.
Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any.
[ "Given", "an", ":", "class", ":", ".", "InstanceState", "return", "the", ":", "class", ":", ".", "Session", "associated", "if", "any", "." ]
def _state_session(state): """Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. """ if state.session_id: try: return _sessions[state.session_id] except KeyError: pass return None
[ "def", "_state_session", "(", "state", ")", ":", "if", "state", ".", "session_id", ":", "try", ":", "return", "_sessions", "[", "state", ".", "session_id", "]", "except", "KeyError", ":", "pass", "return", "None" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/orm/session.py#L37-L46
bnpy/bnpy
d5b311e8f58ccd98477f4a0c8a4d4982e3fca424
bnpy/suffstats/ParamBag.py
python
ParamBag.setAllFieldsToZero
(self)
Update every field to be an array of all zeros.
Update every field to be an array of all zeros.
[ "Update", "every", "field", "to", "be", "an", "array", "of", "all", "zeros", "." ]
def setAllFieldsToZero(self): ''' Update every field to be an array of all zeros. ''' for key, dims in list(self._FieldDims.items()): curShape = getattr(self, key).shape self.setField(key, np.zeros(curShape), dims=dims)
[ "def", "setAllFieldsToZero", "(", "self", ")", ":", "for", "key", ",", "dims", "in", "list", "(", "self", ".", "_FieldDims", ".", "items", "(", ")", ")", ":", "curShape", "=", "getattr", "(", "self", ",", "key", ")", ".", "shape", "self", ".", "set...
https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/suffstats/ParamBag.py#L82-L87
gnes-ai/gnes
b4d2c8cf863664a9322f866a72eab8246175ebef
gnes/proto/gnes_pb2_grpc.py
python
GnesRPCStub.__init__
(self, channel)
Constructor. Args: channel: A grpc.Channel.
Constructor.
[ "Constructor", "." ]
def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Train = channel.unary_unary( '/gnes.GnesRPC/Train', request_serializer=gnes__pb2.Request.SerializeToString, response_deserializer=gnes__pb2.Response.FromString, ) self.Index = channel.unary_unary( '/gnes.GnesRPC/Index', request_serializer=gnes__pb2.Request.SerializeToString, response_deserializer=gnes__pb2.Response.FromString, ) self.Query = channel.unary_unary( '/gnes.GnesRPC/Query', request_serializer=gnes__pb2.Request.SerializeToString, response_deserializer=gnes__pb2.Response.FromString, ) self.Call = channel.unary_unary( '/gnes.GnesRPC/Call', request_serializer=gnes__pb2.Request.SerializeToString, response_deserializer=gnes__pb2.Response.FromString, ) self.StreamCall = channel.stream_stream( '/gnes.GnesRPC/StreamCall', request_serializer=gnes__pb2.Request.SerializeToString, response_deserializer=gnes__pb2.Response.FromString, )
[ "def", "__init__", "(", "self", ",", "channel", ")", ":", "self", ".", "Train", "=", "channel", ".", "unary_unary", "(", "'/gnes.GnesRPC/Train'", ",", "request_serializer", "=", "gnes__pb2", ".", "Request", ".", "SerializeToString", ",", "response_deserializer", ...
https://github.com/gnes-ai/gnes/blob/b4d2c8cf863664a9322f866a72eab8246175ebef/gnes/proto/gnes_pb2_grpc.py#L11-L41
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/monitoring/nagios.py
python
Nagios.disable_servicegroup_svc_notifications
(self, servicegroup)
This command is used to prevent notifications from being sent out for all services in the specified servicegroup. Note that this does not prevent notifications from being sent out about the hosts in this servicegroup. Syntax: DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name>
This command is used to prevent notifications from being sent out for all services in the specified servicegroup.
[ "This", "command", "is", "used", "to", "prevent", "notifications", "from", "being", "sent", "out", "for", "all", "services", "in", "the", "specified", "servicegroup", "." ]
def disable_servicegroup_svc_notifications(self, servicegroup): """ This command is used to prevent notifications from being sent out for all services in the specified servicegroup. Note that this does not prevent notifications from being sent out about the hosts in this servicegroup. Syntax: DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name> """ cmd = "DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS" notif_str = self._fmt_notif_str(cmd, servicegroup) self._write_command(notif_str)
[ "def", "disable_servicegroup_svc_notifications", "(", "self", ",", "servicegroup", ")", ":", "cmd", "=", "\"DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS\"", "notif_str", "=", "self", ".", "_fmt_notif_str", "(", "cmd", ",", "servicegroup", ")", "self", ".", "_write_command", ...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/monitoring/nagios.py#L937-L950
ashdnazg/pyreshark
77a84ef1d7858defe8a5bb4579d10f3dc254f82d
python/cal/cal_types.py
python
PyFunctionItem.generate_filter_name
(self, prefix)
@summary: See ItemBase.
[]
def generate_filter_name(self, prefix): ''' @summary: See ItemBase. ''' for subitem in getattr(self, "_subitems", []): subitem.generate_filter_name(prefix)
[ "def", "generate_filter_name", "(", "self", ",", "prefix", ")", ":", "for", "subitem", "in", "getattr", "(", "self", ",", "\"_subitems\"", ",", "[", "]", ")", ":", "subitem", ".", "generate_filter_name", "(", "prefix", ")" ]
https://github.com/ashdnazg/pyreshark/blob/77a84ef1d7858defe8a5bb4579d10f3dc254f82d/python/cal/cal_types.py#L509-L514
zalando/patroni
3e1076a5746b4d7f313eaba0ff374824644c8ab1
patroni/ctl.py
python
set_defaults
(config, cluster_name)
fill-in some basic configuration parameters if config file is not set
fill-in some basic configuration parameters if config file is not set
[ "fill", "-", "in", "some", "basic", "configuration", "parameters", "if", "config", "file", "is", "not", "set" ]
def set_defaults(config, cluster_name): """fill-in some basic configuration parameters if config file is not set """ config['postgresql'].setdefault('name', cluster_name) config['postgresql'].setdefault('scope', cluster_name) config['postgresql'].setdefault('listen', '127.0.0.1') config['postgresql']['authentication'] = {'replication': None} config['restapi']['listen'] = ':' in config['restapi']['listen'] and config['restapi']['listen'] or '127.0.0.1:8008'
[ "def", "set_defaults", "(", "config", ",", "cluster_name", ")", ":", "config", "[", "'postgresql'", "]", ".", "setdefault", "(", "'name'", ",", "cluster_name", ")", "config", "[", "'postgresql'", "]", ".", "setdefault", "(", "'scope'", ",", "cluster_name", "...
https://github.com/zalando/patroni/blob/3e1076a5746b4d7f313eaba0ff374824644c8ab1/patroni/ctl.py#L919-L925
AlessandroZ/LaZagne
30623c9138e2387d10f6631007f954f2a4ead06d
Windows/lazagne/config/DPAPI/masterkey.py
python
MasterKeyFile.jhash
(self, sid=None, context='local')
return '$DPAPImk${version}*{context}*{sid}*{cipher_algo}*{hmac_algo}*{rounds}*{iv}*{size}*{ciphertext}'.format( version=version, context=context_int, sid=sid, cipher_algo=cipher_algo, hmac_algo=hmac_algo, rounds=self.masterkey.rounds, iv=self.masterkey.iv.encode("hex"), size=len(self.masterkey.ciphertext.encode("hex")), ciphertext=self.masterkey.ciphertext.encode("hex") )
Compute the hash used to be bruteforced. From the masterkey field of the mk file => mk variable.
Compute the hash used to be bruteforced. From the masterkey field of the mk file => mk variable.
[ "Compute", "the", "hash", "used", "to", "be", "bruteforced", ".", "From", "the", "masterkey", "field", "of", "the", "mk", "file", "=", ">", "mk", "variable", "." ]
def jhash(self, sid=None, context='local'): """ Compute the hash used to be bruteforced. From the masterkey field of the mk file => mk variable. """ if 'des3' in str(self.masterkey.cipherAlgo).lower() and 'hmac' in str(self.masterkey.hashAlgo).lower(): version = 1 hmac_algo = 'sha1' cipher_algo = 'des3' elif 'aes-256' in str(self.masterkey.cipherAlgo).lower() and 'sha512' in str(self.masterkey.hashAlgo).lower(): version = 2 hmac_algo = 'sha512' cipher_algo = 'aes256' else: return 'Unsupported combination of cipher {cipher_algo} and hash algorithm {algo} found!'.format( cipher_algo=self.masterkey.cipherAlgo, algo=self.masterkey.hashAlgo) context_int = 0 if context == "domain": context_int = 2 elif context == "local": context_int = 1 return '$DPAPImk${version}*{context}*{sid}*{cipher_algo}*{hmac_algo}*{rounds}*{iv}*{size}*{ciphertext}'.format( version=version, context=context_int, sid=sid, cipher_algo=cipher_algo, hmac_algo=hmac_algo, rounds=self.masterkey.rounds, iv=self.masterkey.iv.encode("hex"), size=len(self.masterkey.ciphertext.encode("hex")), ciphertext=self.masterkey.ciphertext.encode("hex") )
[ "def", "jhash", "(", "self", ",", "sid", "=", "None", ",", "context", "=", "'local'", ")", ":", "if", "'des3'", "in", "str", "(", "self", ".", "masterkey", ".", "cipherAlgo", ")", ".", "lower", "(", ")", "and", "'hmac'", "in", "str", "(", "self", ...
https://github.com/AlessandroZ/LaZagne/blob/30623c9138e2387d10f6631007f954f2a4ead06d/Windows/lazagne/config/DPAPI/masterkey.py#L186-L221
CalebBell/fluids
dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80
fluids/friction.py
python
Round_1980
(Re, eD)
return 4*ff
r'''Calculates Darcy friction factor using the method in Round (1980) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_f}} = -3.6\log_{10}\left[\frac{Re}{0.135Re \frac{\epsilon}{D}+6.5}\right] Parameters ---------- Re : float Reynolds number, [-] eD : float Relative roughness, [-] Returns ------- fd : float Darcy friction factor [-] Notes ----- Range is 4E3 <= Re <= 4E8; 0 <= eD <= 5E-2. Examples -------- >>> Round_1980(1E5, 1E-4) 0.01831475391244354 References ---------- .. [1] Winning, H. and T. Coole. "Explicit Friction Factor Accuracy and Computational Efficiency for Turbulent Flow in Pipes." Flow, Turbulence and Combustion 90, no. 1 (January 1, 2013): 1-27. doi:10.1007/s10494-012-9419-7 .. [2] Round, G. F."An Explicit Approximation for the Friction Factor-Reynolds Number Relation for Rough and Smooth Pipes." The Canadian Journal of Chemical Engineering 58, no. 1 (February 1, 1980): 122-23. doi:10.1002/cjce.5450580119.
r'''Calculates Darcy friction factor using the method in Round (1980) [2]_ as shown in [1]_.
[ "r", "Calculates", "Darcy", "friction", "factor", "using", "the", "method", "in", "Round", "(", "1980", ")", "[", "2", "]", "_", "as", "shown", "in", "[", "1", "]", "_", "." ]
def Round_1980(Re, eD): r'''Calculates Darcy friction factor using the method in Round (1980) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_f}} = -3.6\log_{10}\left[\frac{Re}{0.135Re \frac{\epsilon}{D}+6.5}\right] Parameters ---------- Re : float Reynolds number, [-] eD : float Relative roughness, [-] Returns ------- fd : float Darcy friction factor [-] Notes ----- Range is 4E3 <= Re <= 4E8; 0 <= eD <= 5E-2. Examples -------- >>> Round_1980(1E5, 1E-4) 0.01831475391244354 References ---------- .. [1] Winning, H. and T. Coole. "Explicit Friction Factor Accuracy and Computational Efficiency for Turbulent Flow in Pipes." Flow, Turbulence and Combustion 90, no. 1 (January 1, 2013): 1-27. doi:10.1007/s10494-012-9419-7 .. [2] Round, G. F."An Explicit Approximation for the Friction Factor-Reynolds Number Relation for Rough and Smooth Pipes." The Canadian Journal of Chemical Engineering 58, no. 1 (February 1, 1980): 122-23. doi:10.1002/cjce.5450580119. ''' ff = (-3.6*log10(Re/(0.135*Re*eD+6.5)))**-2 return 4*ff
[ "def", "Round_1980", "(", "Re", ",", "eD", ")", ":", "ff", "=", "(", "-", "3.6", "*", "log10", "(", "Re", "/", "(", "0.135", "*", "Re", "*", "eD", "+", "6.5", ")", ")", ")", "**", "-", "2", "return", "4", "*", "ff" ]
https://github.com/CalebBell/fluids/blob/dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80/fluids/friction.py#L902-L943
felipecode/coiltraine
29060ab5fd2ea5531686e72c621aaaca3b23f4fb
carla08/image_converter.py
python
depth_to_logarithmic_grayscale
(image)
return numpy.repeat(logdepth[:, :, numpy.newaxis], 3, axis=2)
Convert an image containing CARLA encoded depth-map to a logarithmic grayscale image array. "max_depth" is used to omit the points that are far enough.
Convert an image containing CARLA encoded depth-map to a logarithmic grayscale image array. "max_depth" is used to omit the points that are far enough.
[ "Convert", "an", "image", "containing", "CARLA", "encoded", "depth", "-", "map", "to", "a", "logarithmic", "grayscale", "image", "array", ".", "max_depth", "is", "used", "to", "omit", "the", "points", "that", "are", "far", "enough", "." ]
def depth_to_logarithmic_grayscale(image): """ Convert an image containing CARLA encoded depth-map to a logarithmic grayscale image array. "max_depth" is used to omit the points that are far enough. """ normalized_depth = depth_to_array(image) # Convert to logarithmic depth. logdepth = numpy.ones(normalized_depth.shape) + \ (numpy.log(normalized_depth) / 5.70378) logdepth = numpy.clip(logdepth, 0.0, 1.0) logdepth *= 255.0 # Expand to three colors. return numpy.repeat(logdepth[:, :, numpy.newaxis], 3, axis=2)
[ "def", "depth_to_logarithmic_grayscale", "(", "image", ")", ":", "normalized_depth", "=", "depth_to_array", "(", "image", ")", "# Convert to logarithmic depth.", "logdepth", "=", "numpy", ".", "ones", "(", "normalized_depth", ".", "shape", ")", "+", "(", "numpy", ...
https://github.com/felipecode/coiltraine/blob/29060ab5fd2ea5531686e72c621aaaca3b23f4fb/carla08/image_converter.py#L94-L107
wakatime/legacy-python-cli
9b64548b16ab5ef16603d9a6c2620a16d0df8d46
wakatime/packages/py26/pygments/lexer.py
python
RegexLexerMeta._process_new_state
(cls, new_state, unprocessed, processed)
Preprocess the state transition action of a token definition.
Preprocess the state transition action of a token definition.
[ "Preprocess", "the", "state", "transition", "action", "of", "a", "token", "definition", "." ]
def _process_new_state(cls, new_state, unprocessed, processed): """Preprocess the state transition action of a token definition.""" if isinstance(new_state, str): # an existing state if new_state == '#pop': return -1 elif new_state in unprocessed: return (new_state,) elif new_state == '#push': return new_state elif new_state[:5] == '#pop:': return -int(new_state[5:]) else: assert False, 'unknown new state %r' % new_state elif isinstance(new_state, combined): # combine a new state from existing ones tmp_state = '_tmp_%d' % cls._tmpname cls._tmpname += 1 itokens = [] for istate in new_state: assert istate != new_state, 'circular state ref %r' % istate itokens.extend(cls._process_state(unprocessed, processed, istate)) processed[tmp_state] = itokens return (tmp_state,) elif isinstance(new_state, tuple): # push more than one state for istate in new_state: assert (istate in unprocessed or istate in ('#pop', '#push')), \ 'unknown new state ' + istate return new_state else: assert False, 'unknown new state def %r' % new_state
[ "def", "_process_new_state", "(", "cls", ",", "new_state", ",", "unprocessed", ",", "processed", ")", ":", "if", "isinstance", "(", "new_state", ",", "str", ")", ":", "# an existing state", "if", "new_state", "==", "'#pop'", ":", "return", "-", "1", "elif", ...
https://github.com/wakatime/legacy-python-cli/blob/9b64548b16ab5ef16603d9a6c2620a16d0df8d46/wakatime/packages/py26/pygments/lexer.py#L435-L468
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/runpy.py
python
run_module
(mod_name, init_globals=None, run_name=None, alter_sys=False)
Execute a module's code without importing it Returns the resulting top level namespace dictionary
Execute a module's code without importing it
[ "Execute", "a", "module", "s", "code", "without", "importing", "it" ]
def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, loader, code, fname = _get_module_details(mod_name) if run_name is None: run_name = mod_name pkg_name = mod_name.rpartition('.')[0] if alter_sys: return _run_module_code(code, init_globals, run_name, fname, loader, pkg_name) else: # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, fname, loader, pkg_name)
[ "def", "run_module", "(", "mod_name", ",", "init_globals", "=", "None", ",", "run_name", "=", "None", ",", "alter_sys", "=", "False", ")", ":", "mod_name", ",", "loader", ",", "code", ",", "fname", "=", "_get_module_details", "(", "mod_name", ")", "if", ...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/runpy.py#L164-L180
trigger/trigger
c089f761a150f537f7e3201422a3964ec52ff245
trigger/twister.py
python
TriggerSSHJunoscriptChannel._send_next
(self)
Send the next command in the stack.
Send the next command in the stack.
[ "Send", "the", "next", "command", "in", "the", "stack", "." ]
def _send_next(self): """Send the next command in the stack.""" self.resetTimeout() if self.incremental: self.incremental(self.results) try: next_command = self.commanditer.next() log.msg('[%s] COMMAND: next command %s' % (self.device, next_command)) except StopIteration: log.msg('[%s] CHANNEL: out of commands, closing connection...' % self.device) self.loseConnection() return None if next_command is None: self.results.append(None) self._send_next() else: rpc = Element('rpc') rpc.append(next_command) ElementTree(rpc).write(self)
[ "def", "_send_next", "(", "self", ")", ":", "self", ".", "resetTimeout", "(", ")", "if", "self", ".", "incremental", ":", "self", ".", "incremental", "(", "self", ".", "results", ")", "try", ":", "next_command", "=", "self", ".", "commanditer", ".", "n...
https://github.com/trigger/trigger/blob/c089f761a150f537f7e3201422a3964ec52ff245/trigger/twister.py#L1566-L1590
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/parsers/rst/states.py
python
RSTState.inline_text
(self, text, lineno)
return self.inliner.parse(text, lineno, self.memo, self.parent)
Return 2 lists: nodes (text and inline elements), and system_messages.
Return 2 lists: nodes (text and inline elements), and system_messages.
[ "Return", "2", "lists", ":", "nodes", "(", "text", "and", "inline", "elements", ")", "and", "system_messages", "." ]
def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent)
[ "def", "inline_text", "(", "self", ",", "text", ",", "lineno", ")", ":", "return", "self", ".", "inliner", ".", "parse", "(", "text", ",", "lineno", ",", "self", ".", "memo", ",", "self", ".", "parent", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/parsers/rst/states.py#L404-L408
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/relocate.py
python
_patchelf
()
return patchelf.path
Return the full path to the patchelf binary, if available, else None.
Return the full path to the patchelf binary, if available, else None.
[ "Return", "the", "full", "path", "to", "the", "patchelf", "binary", "if", "available", "else", "None", "." ]
def _patchelf(): """Return the full path to the patchelf binary, if available, else None.""" if is_macos: return None patchelf = executable.which('patchelf') if patchelf is None: with spack.bootstrap.ensure_bootstrap_configuration(): patchelf = spack.bootstrap.ensure_patchelf_in_path_or_raise() return patchelf.path
[ "def", "_patchelf", "(", ")", ":", "if", "is_macos", ":", "return", "None", "patchelf", "=", "executable", ".", "which", "(", "'patchelf'", ")", "if", "patchelf", "is", "None", ":", "with", "spack", ".", "bootstrap", ".", "ensure_bootstrap_configuration", "(...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/relocate.py#L78-L88
wikilinks/neleval
68f68414f6a82e3d86761b8d3083e537582bfa7f
neleval/summary.py
python
PlotSystems._plot1d
(self, ax, data, group_sizes, tick_labels, score_label, sys_label=None)
[]
def _plot1d(self, ax, data, group_sizes, tick_labels, score_label, sys_label=None): small_font = make_small_font() ordinate = np.repeat(np.arange(len(group_sizes)), group_sizes) for scores, kwargs in data: if kwargs.pop('score_only', False): try: scores = scores['score'] except Exception: pass if self.secondary == 'rows': self._plot(ax, scores, ordinate[::-1], **kwargs) #, marker=marker, color=color, label=self._t(label), markeredgecolor=color) else: self._plot(ax, ordinate, scores, **kwargs) ticks = np.arange(len(tick_labels)) tick_labels = [self._t(label) for label in tick_labels] score_label = self._t(score_label) if self.secondary == 'rows': plt.yticks(ticks[::-1], tick_labels, fontproperties=small_font) self._set_lim(plt.xlim) plt.ylim(-.5, len(tick_labels) - .5) plt.xlabel(score_label) if sys_label is not None: plt.ylabel(self._t(sys_label)) elif self.secondary == 'columns': plt.xticks(ticks, tick_labels, fontproperties=small_font, **XTICK_ROTATION) plt.xlim(-.5, len(tick_labels) - .5) self._set_lim(plt.ylim) plt.ylabel(score_label) if sys_label is not None: plt.xlabel(self._t(sys_label)) else: raise ValueError('Unexpected secondary: {!r}'.format(self.secondary)) plt.tight_layout() if len(data) > 1: plt.legend(loc='best', prop=small_font, ncol=self._ncol(len(data)))
[ "def", "_plot1d", "(", "self", ",", "ax", ",", "data", ",", "group_sizes", ",", "tick_labels", ",", "score_label", ",", "sys_label", "=", "None", ")", ":", "small_font", "=", "make_small_font", "(", ")", "ordinate", "=", "np", ".", "repeat", "(", "np", ...
https://github.com/wikilinks/neleval/blob/68f68414f6a82e3d86761b8d3083e537582bfa7f/neleval/summary.py#L242-L278
elastic/eland
72856e2c3f827a0b71d140323009a7a9a3df6e1d
eland/ndframe.py
python
NDFrame.dtypes
(self)
return self._query_compiler.dtypes
Return the pandas dtypes in the DataFrame. Elasticsearch types are mapped to pandas dtypes via Mappings._es_dtype_to_pd_dtype.__doc__ Returns ------- pandas.Series The data type of each column. See Also -------- :pandas_api_docs:`pandas.DataFrame.dtypes` Examples -------- >>> df = ed.DataFrame('http://localhost:9200', 'flights', columns=['Origin', 'AvgTicketPrice', 'timestamp', 'dayOfWeek']) >>> df.dtypes Origin object AvgTicketPrice float64 timestamp datetime64[ns] dayOfWeek int64 dtype: object
Return the pandas dtypes in the DataFrame. Elasticsearch types are mapped to pandas dtypes via Mappings._es_dtype_to_pd_dtype.__doc__
[ "Return", "the", "pandas", "dtypes", "in", "the", "DataFrame", ".", "Elasticsearch", "types", "are", "mapped", "to", "pandas", "dtypes", "via", "Mappings", ".", "_es_dtype_to_pd_dtype", ".", "__doc__" ]
def dtypes(self) -> pd.Series: """ Return the pandas dtypes in the DataFrame. Elasticsearch types are mapped to pandas dtypes via Mappings._es_dtype_to_pd_dtype.__doc__ Returns ------- pandas.Series The data type of each column. See Also -------- :pandas_api_docs:`pandas.DataFrame.dtypes` Examples -------- >>> df = ed.DataFrame('http://localhost:9200', 'flights', columns=['Origin', 'AvgTicketPrice', 'timestamp', 'dayOfWeek']) >>> df.dtypes Origin object AvgTicketPrice float64 timestamp datetime64[ns] dayOfWeek int64 dtype: object """ return self._query_compiler.dtypes
[ "def", "dtypes", "(", "self", ")", "->", "pd", ".", "Series", ":", "return", "self", ".", "_query_compiler", ".", "dtypes" ]
https://github.com/elastic/eland/blob/72856e2c3f827a0b71d140323009a7a9a3df6e1d/eland/ndframe.py#L114-L138
autotest/autotest
4614ae5f550cc888267b9a419e4b90deb54f8fae
client/setup.py
python
_get_files
(path)
return flist
Given a path, return all the files in there to package
Given a path, return all the files in there to package
[ "Given", "a", "path", "return", "all", "the", "files", "in", "there", "to", "package" ]
def _get_files(path): ''' Given a path, return all the files in there to package ''' flist = [] for root, _, files in sorted(os.walk(path)): for name in files: fullname = os.path.join(root, name) flist.append(fullname) return flist
[ "def", "_get_files", "(", "path", ")", ":", "flist", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "sorted", "(", "os", ".", "walk", "(", "path", ")", ")", ":", "for", "name", "in", "files", ":", "fullname", "=", "os", ".", "path"...
https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/client/setup.py#L21-L30
pathak22/noreward-rl
3e220c2177fc253916f12d980957fc40579d577a
src/a3c.py
python
A3C.__init__
(self, env, task, visualise, unsupType, envWrap=False, designHead='universe', noReward=False)
An implementation of the A3C algorithm that is reasonably well-tuned for the VNC environments. Below, we will have a modest amount of complexity due to the way TensorFlow handles data parallelism. But overall, we'll define the model, specify its inputs, and describe how the policy gradients step should be computed.
An implementation of the A3C algorithm that is reasonably well-tuned for the VNC environments. Below, we will have a modest amount of complexity due to the way TensorFlow handles data parallelism. But overall, we'll define the model, specify its inputs, and describe how the policy gradients step should be computed.
[ "An", "implementation", "of", "the", "A3C", "algorithm", "that", "is", "reasonably", "well", "-", "tuned", "for", "the", "VNC", "environments", ".", "Below", "we", "will", "have", "a", "modest", "amount", "of", "complexity", "due", "to", "the", "way", "Ten...
def __init__(self, env, task, visualise, unsupType, envWrap=False, designHead='universe', noReward=False): """ An implementation of the A3C algorithm that is reasonably well-tuned for the VNC environments. Below, we will have a modest amount of complexity due to the way TensorFlow handles data parallelism. But overall, we'll define the model, specify its inputs, and describe how the policy gradients step should be computed. """ self.task = task self.unsup = unsupType is not None self.envWrap = envWrap self.env = env predictor = None numaction = env.action_space.n worker_device = "/job:worker/task:{}/cpu:0".format(task) with tf.device(tf.train.replica_device_setter(1, worker_device=worker_device)): with tf.variable_scope("global"): self.network = LSTMPolicy(env.observation_space.shape, numaction, designHead) self.global_step = tf.get_variable("global_step", [], tf.int32, initializer=tf.constant_initializer(0, dtype=tf.int32), trainable=False) if self.unsup: with tf.variable_scope("predictor"): if 'state' in unsupType: self.ap_network = StatePredictor(env.observation_space.shape, numaction, designHead, unsupType) else: self.ap_network = StateActionPredictor(env.observation_space.shape, numaction, designHead) with tf.device(worker_device): with tf.variable_scope("local"): self.local_network = pi = LSTMPolicy(env.observation_space.shape, numaction, designHead) pi.global_step = self.global_step if self.unsup: with tf.variable_scope("predictor"): if 'state' in unsupType: self.local_ap_network = predictor = StatePredictor(env.observation_space.shape, numaction, designHead, unsupType) else: self.local_ap_network = predictor = StateActionPredictor(env.observation_space.shape, numaction, designHead) # Computing a3c loss: https://arxiv.org/abs/1506.02438 self.ac = tf.placeholder(tf.float32, [None, numaction], name="ac") self.adv = tf.placeholder(tf.float32, [None], name="adv") self.r = tf.placeholder(tf.float32, [None], name="r") log_prob_tf = tf.nn.log_softmax(pi.logits) prob_tf = tf.nn.softmax(pi.logits) # 1) the "policy gradients" loss: its derivative is precisely the policy gradient # notice that self.ac is a placeholder that is provided externally. # adv will contain the advantages, as calculated in process_rollout pi_loss = - tf.reduce_mean(tf.reduce_sum(log_prob_tf * self.ac, 1) * self.adv) # Eq (19) # 2) loss of value function: l2_loss = (x-y)^2/2 vf_loss = 0.5 * tf.reduce_mean(tf.square(pi.vf - self.r)) # Eq (28) # 3) entropy to ensure randomness entropy = - tf.reduce_mean(tf.reduce_sum(prob_tf * log_prob_tf, 1)) # final a3c loss: lr of critic is half of actor self.loss = pi_loss + 0.5 * vf_loss - entropy * constants['ENTROPY_BETA'] # compute gradients grads = tf.gradients(self.loss * 20.0, pi.var_list) # batchsize=20. Factored out to make hyperparams not depend on it. # computing predictor loss if self.unsup: if 'state' in unsupType: self.predloss = constants['PREDICTION_LR_SCALE'] * predictor.forwardloss else: self.predloss = constants['PREDICTION_LR_SCALE'] * (predictor.invloss * (1-constants['FORWARD_LOSS_WT']) + predictor.forwardloss * constants['FORWARD_LOSS_WT']) predgrads = tf.gradients(self.predloss * 20.0, predictor.var_list) # batchsize=20. Factored out to make hyperparams not depend on it. # do not backprop to policy if constants['POLICY_NO_BACKPROP_STEPS'] > 0: grads = [tf.scalar_mul(tf.to_float(tf.greater(self.global_step, constants['POLICY_NO_BACKPROP_STEPS'])), grads_i) for grads_i in grads] self.runner = RunnerThread(env, pi, constants['ROLLOUT_MAXLEN'], visualise, predictor, envWrap, noReward) # storing summaries bs = tf.to_float(tf.shape(pi.x)[0]) if use_tf12_api: tf.summary.scalar("model/policy_loss", pi_loss) tf.summary.scalar("model/value_loss", vf_loss) tf.summary.scalar("model/entropy", entropy) tf.summary.image("model/state", pi.x) # max_outputs=10 tf.summary.scalar("model/grad_global_norm", tf.global_norm(grads)) tf.summary.scalar("model/var_global_norm", tf.global_norm(pi.var_list)) if self.unsup: tf.summary.scalar("model/predloss", self.predloss) if 'action' in unsupType: tf.summary.scalar("model/inv_loss", predictor.invloss) tf.summary.scalar("model/forward_loss", predictor.forwardloss) tf.summary.scalar("model/predgrad_global_norm", tf.global_norm(predgrads)) tf.summary.scalar("model/predvar_global_norm", tf.global_norm(predictor.var_list)) self.summary_op = tf.summary.merge_all() else: tf.scalar_summary("model/policy_loss", pi_loss) tf.scalar_summary("model/value_loss", vf_loss) tf.scalar_summary("model/entropy", entropy) tf.image_summary("model/state", pi.x) tf.scalar_summary("model/grad_global_norm", tf.global_norm(grads)) tf.scalar_summary("model/var_global_norm", tf.global_norm(pi.var_list)) if self.unsup: tf.scalar_summary("model/predloss", self.predloss) if 'action' in unsupType: tf.scalar_summary("model/inv_loss", predictor.invloss) tf.scalar_summary("model/forward_loss", predictor.forwardloss) tf.scalar_summary("model/predgrad_global_norm", tf.global_norm(predgrads)) tf.scalar_summary("model/predvar_global_norm", tf.global_norm(predictor.var_list)) self.summary_op = tf.merge_all_summaries() # clip gradients grads, _ = tf.clip_by_global_norm(grads, constants['GRAD_NORM_CLIP']) grads_and_vars = list(zip(grads, self.network.var_list)) if self.unsup: predgrads, _ = tf.clip_by_global_norm(predgrads, constants['GRAD_NORM_CLIP']) pred_grads_and_vars = list(zip(predgrads, self.ap_network.var_list)) grads_and_vars = grads_and_vars + pred_grads_and_vars # update global step by batch size inc_step = self.global_step.assign_add(tf.shape(pi.x)[0]) # each worker has a different set of adam optimizer parameters # TODO: make optimizer global shared, if needed print("Optimizer: ADAM with lr: %f" % (constants['LEARNING_RATE'])) print("Input observation shape: ",env.observation_space.shape) opt = tf.train.AdamOptimizer(constants['LEARNING_RATE']) self.train_op = tf.group(opt.apply_gradients(grads_and_vars), inc_step) # copy weights from the parameter server to the local model sync_var_list = [v1.assign(v2) for v1, v2 in zip(pi.var_list, self.network.var_list)] if self.unsup: sync_var_list += [v1.assign(v2) for v1, v2 in zip(predictor.var_list, self.ap_network.var_list)] self.sync = tf.group(*sync_var_list) # initialize extras self.summary_writer = None self.local_steps = 0
[ "def", "__init__", "(", "self", ",", "env", ",", "task", ",", "visualise", ",", "unsupType", ",", "envWrap", "=", "False", ",", "designHead", "=", "'universe'", ",", "noReward", "=", "False", ")", ":", "self", ".", "task", "=", "task", "self", ".", "...
https://github.com/pathak22/noreward-rl/blob/3e220c2177fc253916f12d980957fc40579d577a/src/a3c.py#L242-L378
Chandlercjy/OnePy
9bd43b721d3f7352495b6ccab76bd533a3d2e8f2
OnePy/sys_module/models/base_series.py
python
SeriesBase.get_barly_cur_price
(self, ticker: str, order_executed: bool)
若是订单执行,则返回成交价,否则只是更新信息,返回开盘价
若是订单执行,则返回成交价,否则只是更新信息,返回开盘价
[ "若是订单执行,则返回成交价,否则只是更新信息,返回开盘价" ]
def get_barly_cur_price(self, ticker: str, order_executed: bool) -> float: """若是订单执行,则返回成交价,否则只是更新信息,返回开盘价""" if order_executed: return self.env.feeds[ticker].execute_price else: return self.env.feeds[ticker].open
[ "def", "get_barly_cur_price", "(", "self", ",", "ticker", ":", "str", ",", "order_executed", ":", "bool", ")", "->", "float", ":", "if", "order_executed", ":", "return", "self", ".", "env", ".", "feeds", "[", "ticker", "]", ".", "execute_price", "else", ...
https://github.com/Chandlercjy/OnePy/blob/9bd43b721d3f7352495b6ccab76bd533a3d2e8f2/OnePy/sys_module/models/base_series.py#L108-L114
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/conversion/nnef_to_tf.py
python
Converter._is_nxc
(self, format)
return format[0] == 'N' and format[-1] == 'C' and len(format) > 2
[]
def _is_nxc(self, format): return format[0] == 'N' and format[-1] == 'C' and len(format) > 2
[ "def", "_is_nxc", "(", "self", ",", "format", ")", ":", "return", "format", "[", "0", "]", "==", "'N'", "and", "format", "[", "-", "1", "]", "==", "'C'", "and", "len", "(", "format", ")", ">", "2" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/conversion/nnef_to_tf.py#L135-L136
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/devices/ball_device/ball_count_handler.py
python
BallCountHandler.entrance_during_eject
(self)
Received an entrance during eject.
Received an entrance during eject.
[ "Received", "an", "entrance", "during", "eject", "." ]
async def entrance_during_eject(self): """Received an entrance during eject.""" await self.ball_device.incoming_balls_handler.ball_arrived() self._set_ball_count(self._ball_count + 1)
[ "async", "def", "entrance_during_eject", "(", "self", ")", ":", "await", "self", ".", "ball_device", ".", "incoming_balls_handler", ".", "ball_arrived", "(", ")", "self", ".", "_set_ball_count", "(", "self", ".", "_ball_count", "+", "1", ")" ]
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/devices/ball_device/ball_count_handler.py#L294-L297
BasioMeusPuga/Lector
1b1d87739a8c14e0e22009435350b155fc3e3b77
lector/rarfile/rarfile.py
python
CommonParser.parse
(self)
Process file.
Process file.
[ "Process", "file", "." ]
def parse(self): """Process file.""" self._fd = None try: self._parse_real() finally: if self._fd: self._fd.close() self._fd = None
[ "def", "parse", "(", "self", ")", ":", "self", ".", "_fd", "=", "None", "try", ":", "self", ".", "_parse_real", "(", ")", "finally", ":", "if", "self", ".", "_fd", ":", "self", ".", "_fd", ".", "close", "(", ")", "self", ".", "_fd", "=", "None"...
https://github.com/BasioMeusPuga/Lector/blob/1b1d87739a8c14e0e22009435350b155fc3e3b77/lector/rarfile/rarfile.py#L978-L986
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/geometry/solids/trianglemesh.py
python
getIsPathEntirelyOutsideTriangle
(begin, center, end, vector3Path)
return True
Determine if a path is entirely outside another loop.
Determine if a path is entirely outside another loop.
[ "Determine", "if", "a", "path", "is", "entirely", "outside", "another", "loop", "." ]
def getIsPathEntirelyOutsideTriangle(begin, center, end, vector3Path): "Determine if a path is entirely outside another loop." loop = [begin.dropAxis(), center.dropAxis(), end.dropAxis()] for vector3 in vector3Path: point = vector3.dropAxis() if euclidean.isPointInsideLoop(loop, point): return False return True
[ "def", "getIsPathEntirelyOutsideTriangle", "(", "begin", ",", "center", ",", "end", ",", "vector3Path", ")", ":", "loop", "=", "[", "begin", ".", "dropAxis", "(", ")", ",", "center", ".", "dropAxis", "(", ")", ",", "end", ".", "dropAxis", "(", ")", "]"...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/solids/trianglemesh.py#L366-L373
django-haystack/django-haystack
b6dd72e6b5c97b782f5436b7bb4e8227ba6e3b06
haystack/backends/solr_backend.py
python
SolrSearchBackend.build_search_kwargs
( self, query_string, sort_by=None, start_offset=0, end_offset=None, fields="", highlight=False, facets=None, date_facets=None, query_facets=None, narrow_queries=None, spelling_query=None, within=None, dwithin=None, distance_point=None, models=None, limit_to_registered_models=None, result_class=None, stats=None, collate=None, **extra_kwargs )
return kwargs
[]
def build_search_kwargs( self, query_string, sort_by=None, start_offset=0, end_offset=None, fields="", highlight=False, facets=None, date_facets=None, query_facets=None, narrow_queries=None, spelling_query=None, within=None, dwithin=None, distance_point=None, models=None, limit_to_registered_models=None, result_class=None, stats=None, collate=None, **extra_kwargs ): index = haystack.connections[self.connection_alias].get_unified_index() kwargs = {"fl": "* score", "df": index.document_field} if fields: if isinstance(fields, (list, set)): fields = " ".join(fields) kwargs["fl"] = fields if sort_by is not None: if sort_by in ["distance asc", "distance desc"] and distance_point: # Do the geo-enabled sort. lng, lat = distance_point["point"].coords kwargs["sfield"] = distance_point["field"] kwargs["pt"] = "%s,%s" % (lat, lng) if sort_by == "distance asc": kwargs["sort"] = "geodist() asc" else: kwargs["sort"] = "geodist() desc" else: if sort_by.startswith("distance "): warnings.warn( "In order to sort by distance, you must call the '.distance(...)' method." ) # Regular sorting. kwargs["sort"] = sort_by if start_offset is not None: kwargs["start"] = start_offset if end_offset is not None: kwargs["rows"] = end_offset - start_offset if highlight: # `highlight` can either be True or a dictionary containing custom parameters # which will be passed to the backend and may override our default settings: kwargs["hl"] = "true" kwargs["hl.fragsize"] = "200" if isinstance(highlight, dict): # autoprefix highlighter options with 'hl.', all of them start with it anyway # this makes option dicts shorter: {'maxAnalyzedChars': 42} # and lets some of options be used as keyword arguments: `.highlight(preserveMulti=False)` kwargs.update( { key if key.startswith("hl.") else ("hl." + key): highlight[key] for key in highlight.keys() } ) if collate is None: collate = self.collate if self.include_spelling is True: kwargs["spellcheck"] = "true" kwargs["spellcheck.collate"] = str(collate).lower() kwargs["spellcheck.count"] = 1 if spelling_query: kwargs["spellcheck.q"] = spelling_query if facets is not None: kwargs["facet"] = "on" kwargs["facet.field"] = facets.keys() for facet_field, options in facets.items(): for key, value in options.items(): kwargs[ "f.%s.facet.%s" % (facet_field, key) ] = self.conn._from_python(value) if date_facets is not None: kwargs["facet"] = "on" kwargs["facet.%s" % self.date_facet_field] = date_facets.keys() kwargs["facet.%s.other" % self.date_facet_field] = "none" for key, value in date_facets.items(): kwargs[ "f.%s.facet.%s.start" % (key, self.date_facet_field) ] = self.conn._from_python(value.get("start_date")) kwargs[ "f.%s.facet.%s.end" % (key, self.date_facet_field) ] = self.conn._from_python(value.get("end_date")) gap_by_string = value.get("gap_by").upper() gap_string = "%d%s" % (value.get("gap_amount"), gap_by_string) if value.get("gap_amount") != 1: gap_string += "S" kwargs[ "f.%s.facet.%s.gap" % (key, self.date_facet_field) ] = "+%s/%s" % ( gap_string, gap_by_string, ) if query_facets is not None: kwargs["facet"] = "on" kwargs["facet.query"] = [ "%s:%s" % (field, value) for field, value in query_facets ] if limit_to_registered_models is None: limit_to_registered_models = getattr( settings, "HAYSTACK_LIMIT_TO_REGISTERED_MODELS", True ) if models and len(models): model_choices = sorted(get_model_ct(model) for model in models) elif limit_to_registered_models: # Using narrow queries, limit the results to only models handled # with the current routers. model_choices = self.build_models_list() else: model_choices = [] if len(model_choices) > 0: if narrow_queries is None: narrow_queries = set() narrow_queries.add("%s:(%s)" % (DJANGO_CT, " OR ".join(model_choices))) if narrow_queries is not None: kwargs["fq"] = list(narrow_queries) if stats: kwargs["stats"] = "true" for k in stats.keys(): kwargs["stats.field"] = k for facet in stats[k]: kwargs["f.%s.stats.facet" % k] = facet if within is not None: from haystack.utils.geo import generate_bounding_box kwargs.setdefault("fq", []) ((min_lat, min_lng), (max_lat, max_lng)) = generate_bounding_box( within["point_1"], within["point_2"] ) # Bounding boxes are min, min TO max, max. Solr's wiki was *NOT* # very clear on this. bbox = "%s:[%s,%s TO %s,%s]" % ( within["field"], min_lat, min_lng, max_lat, max_lng, ) kwargs["fq"].append(bbox) if dwithin is not None: kwargs.setdefault("fq", []) lng, lat = dwithin["point"].coords geofilt = "{!geofilt pt=%s,%s sfield=%s d=%s}" % ( lat, lng, dwithin["field"], dwithin["distance"].km, ) kwargs["fq"].append(geofilt) # Check to see if the backend should try to include distances # (Solr 4.X+) in the results. if self.distance_available and distance_point: # In early testing, you can't just hand Solr 4.X a proper bounding box # & request distances. To enable native distance would take calculating # a center point & a radius off the user-provided box, which kinda # sucks. We'll avoid it for now, since Solr 4.x's release will be some # time yet. # kwargs['fl'] += ' _dist_:geodist()' pass if extra_kwargs: kwargs.update(extra_kwargs) return kwargs
[ "def", "build_search_kwargs", "(", "self", ",", "query_string", ",", "sort_by", "=", "None", ",", "start_offset", "=", "0", ",", "end_offset", "=", "None", ",", "fields", "=", "\"\"", ",", "highlight", "=", "False", ",", "facets", "=", "None", ",", "date...
https://github.com/django-haystack/django-haystack/blob/b6dd72e6b5c97b782f5436b7bb4e8227ba6e3b06/haystack/backends/solr_backend.py#L184-L388
jwlodek/py_cui
bc2de6a30cfc894348306531db94d7edbdbf17f3
py_cui/ui.py
python
UIElement.update_height_width
(self)
Function that refreshes position and dimensons on resize. If necessary, make sure required widget attributes updated here as well.
Function that refreshes position and dimensons on resize.
[ "Function", "that", "refreshes", "position", "and", "dimensons", "on", "resize", "." ]
def update_height_width(self) -> None: """Function that refreshes position and dimensons on resize. If necessary, make sure required widget attributes updated here as well. """ self._start_x, self._start_y = self.get_absolute_start_pos() self._stop_x, self._stop_y = self.get_absolute_stop_pos() self._height, self._width = self.get_absolute_dimensions()
[ "def", "update_height_width", "(", "self", ")", "->", "None", ":", "self", ".", "_start_x", ",", "self", ".", "_start_y", "=", "self", ".", "get_absolute_start_pos", "(", ")", "self", ".", "_stop_x", ",", "self", ".", "_stop_y", "=", "self", ".", "get_ab...
https://github.com/jwlodek/py_cui/blob/bc2de6a30cfc894348306531db94d7edbdbf17f3/py_cui/ui.py#L106-L114
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/sqlalchemy/orm/collections.py
python
CollectionAdapter.__iter__
(self)
return iter(self._data()._sa_iterator())
Iterate over entities in the collection.
Iterate over entities in the collection.
[ "Iterate", "over", "entities", "in", "the", "collection", "." ]
def __iter__(self): """Iterate over entities in the collection.""" return iter(self._data()._sa_iterator())
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_data", "(", ")", ".", "_sa_iterator", "(", ")", ")" ]
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/sqlalchemy/orm/collections.py#L685-L688
chen3feng/blade-build
360b4c9ddb9087fb811af3aef2830301cf48805e
src/blade/pathlib.py
python
PurePath.parents
(self)
return _PathParents(self)
A sequence of this path's logical parents.
A sequence of this path's logical parents.
[ "A", "sequence", "of", "this", "path", "s", "logical", "parents", "." ]
def parents(self): """A sequence of this path's logical parents.""" return _PathParents(self)
[ "def", "parents", "(", "self", ")", ":", "return", "_PathParents", "(", "self", ")" ]
https://github.com/chen3feng/blade-build/blob/360b4c9ddb9087fb811af3aef2830301cf48805e/src/blade/pathlib.py#L886-L888
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_mutating_webhook.py
python
V1MutatingWebhook.object_selector
(self)
return self._object_selector
Gets the object_selector of this V1MutatingWebhook. # noqa: E501 :return: The object_selector of this V1MutatingWebhook. # noqa: E501 :rtype: V1LabelSelector
Gets the object_selector of this V1MutatingWebhook. # noqa: E501
[ "Gets", "the", "object_selector", "of", "this", "V1MutatingWebhook", ".", "#", "noqa", ":", "E501" ]
def object_selector(self): """Gets the object_selector of this V1MutatingWebhook. # noqa: E501 :return: The object_selector of this V1MutatingWebhook. # noqa: E501 :rtype: V1LabelSelector """ return self._object_selector
[ "def", "object_selector", "(", "self", ")", ":", "return", "self", ".", "_object_selector" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_mutating_webhook.py#L242-L249
and3rson/clay
c271cecf6b6ea6465abcdd2444171b1a565a60a3
clay/vlc.py
python
libvlc_audio_equalizer_get_preset_count
()
return f()
Get the number of equalizer presets. @return: number of presets. @version: LibVLC 2.2.0 or later.
Get the number of equalizer presets.
[ "Get", "the", "number", "of", "equalizer", "presets", "." ]
def libvlc_audio_equalizer_get_preset_count(): '''Get the number of equalizer presets. @return: number of presets. @version: LibVLC 2.2.0 or later. ''' f = _Cfunctions.get('libvlc_audio_equalizer_get_preset_count', None) or \ _Cfunction('libvlc_audio_equalizer_get_preset_count', (), None, ctypes.c_uint) return f()
[ "def", "libvlc_audio_equalizer_get_preset_count", "(", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_audio_equalizer_get_preset_count'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_equalizer_get_preset_count'", ",", "(", ")", ",", "None", ...
https://github.com/and3rson/clay/blob/c271cecf6b6ea6465abcdd2444171b1a565a60a3/clay/vlc.py#L6515-L6523
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/models/deletion.py
python
ProtectedError.__init__
(self, msg, protected_objects)
[]
def __init__(self, msg, protected_objects): self.protected_objects = protected_objects super(ProtectedError, self).__init__(msg, protected_objects)
[ "def", "__init__", "(", "self", ",", "msg", ",", "protected_objects", ")", ":", "self", ".", "protected_objects", "=", "protected_objects", "super", "(", "ProtectedError", ",", "self", ")", ".", "__init__", "(", "msg", ",", "protected_objects", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/models/deletion.py#L10-L12
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/botocore/credentials.py
python
AssumeRoleCredentialFetcher._get_credentials
(self)
return client.assume_role(**kwargs)
Get credentials by calling assume role.
Get credentials by calling assume role.
[ "Get", "credentials", "by", "calling", "assume", "role", "." ]
def _get_credentials(self): """Get credentials by calling assume role.""" kwargs = self._assume_role_kwargs() client = self._create_client() return client.assume_role(**kwargs)
[ "def", "_get_credentials", "(", "self", ")", ":", "kwargs", "=", "self", ".", "_assume_role_kwargs", "(", ")", "client", "=", "self", ".", "_create_client", "(", ")", "return", "client", ".", "assume_role", "(", "*", "*", "kwargs", ")" ]
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/botocore/credentials.py#L694-L698
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppcls/arch/backbone/model_zoo/mixnet.py
python
MixNet.forward
(self, x)
return x
[]
def forward(self, x): x = self.features(x) reshape_dim = reduce(lambda x, y: x * y, x.shape[1:]) x = x.reshape(shape=[x.shape[0], reshape_dim]) x = self.output(x) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "features", "(", "x", ")", "reshape_dim", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "x", ".", "shape", "[", "1", ":", "]", ")", "x", "=", ...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppcls/arch/backbone/model_zoo/mixnet.py#L697-L702
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/difflib.py
python
SequenceMatcher.__init__
(self, isjunk=None, a='', b='', autojunk=True)
Construct a SequenceMatcher. Optional arg isjunk is None (the default), or a one-argument function that takes a sequence element and returns true iff the element is junk. None is equivalent to passing "lambda x: 0", i.e. no elements are considered to be junk. For example, pass lambda x: x in " \\t" if you're comparing lines as sequences of characters, and don't want to synch up on blanks or hard tabs. Optional arg a is the first of two sequences to be compared. By default, an empty string. The elements of a must be hashable. See also .set_seqs() and .set_seq1(). Optional arg b is the second of two sequences to be compared. By default, an empty string. The elements of b must be hashable. See also .set_seqs() and .set_seq2(). Optional arg autojunk should be set to False to disable the "automatic junk heuristic" that treats popular elements as junk (see module documentation for more information).
Construct a SequenceMatcher.
[ "Construct", "a", "SequenceMatcher", "." ]
def __init__(self, isjunk=None, a='', b='', autojunk=True): """Construct a SequenceMatcher. Optional arg isjunk is None (the default), or a one-argument function that takes a sequence element and returns true iff the element is junk. None is equivalent to passing "lambda x: 0", i.e. no elements are considered to be junk. For example, pass lambda x: x in " \\t" if you're comparing lines as sequences of characters, and don't want to synch up on blanks or hard tabs. Optional arg a is the first of two sequences to be compared. By default, an empty string. The elements of a must be hashable. See also .set_seqs() and .set_seq1(). Optional arg b is the second of two sequences to be compared. By default, an empty string. The elements of b must be hashable. See also .set_seqs() and .set_seq2(). Optional arg autojunk should be set to False to disable the "automatic junk heuristic" that treats popular elements as junk (see module documentation for more information). """ # Members: # a # first sequence # b # second sequence; differences are computed as "what do # we need to do to 'a' to change it into 'b'?" # b2j # for x in b, b2j[x] is a list of the indices (into b) # at which x appears; junk elements do not appear # fullbcount # for x in b, fullbcount[x] == the number of times x # appears in b; only materialized if really needed (used # only for computing quick_ratio()) # matching_blocks # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k]; # ascending & non-overlapping in i and in j; terminated by # a dummy (len(a), len(b), 0) sentinel # opcodes # a list of (tag, i1, i2, j1, j2) tuples, where tag is # one of # 'replace' a[i1:i2] should be replaced by b[j1:j2] # 'delete' a[i1:i2] should be deleted # 'insert' b[j1:j2] should be inserted # 'equal' a[i1:i2] == b[j1:j2] # isjunk # a user-supplied function taking a sequence element and # returning true iff the element is "junk" -- this has # subtle but helpful effects on the algorithm, which I'll # get around to writing up someday <0.9 wink>. # DON'T USE! Only __chain_b uses this. Use isbjunk. # isbjunk # for x in b, isbjunk(x) == isjunk(x) but much faster; # it's really the __contains__ method of a hidden dict. # DOES NOT WORK for x in a! # isbpopular # for x in b, isbpopular(x) is true iff b is reasonably long # (at least 200 elements) and x accounts for more than 1 + 1% of # its elements (when autojunk is enabled). # DOES NOT WORK for x in a! self.isjunk = isjunk self.a = self.b = None self.autojunk = autojunk self.set_seqs(a, b)
[ "def", "__init__", "(", "self", ",", "isjunk", "=", "None", ",", "a", "=", "''", ",", "b", "=", "''", ",", "autojunk", "=", "True", ")", ":", "# Members:", "# a", "# first sequence", "# b", "# second sequence; differences are computed as \"what do", "#...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/difflib.py#L152-L219
facebookresearch/ClassyVision
309d4f12431c6b4d8540010a781dc2aa25fe88e7
classy_vision/generic/distributed_util.py
python
all_reduce_sum
(tensor: torch.Tensor)
return all_reduce_op(tensor, torch.distributed.ReduceOp.SUM)
Wrapper over torch.distributed.all_reduce for performing sum reduction of tensor over all processes in both distributed / non-distributed scenarios.
Wrapper over torch.distributed.all_reduce for performing sum reduction of tensor over all processes in both distributed / non-distributed scenarios.
[ "Wrapper", "over", "torch", ".", "distributed", ".", "all_reduce", "for", "performing", "sum", "reduction", "of", "tensor", "over", "all", "processes", "in", "both", "distributed", "/", "non", "-", "distributed", "scenarios", "." ]
def all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor: """ Wrapper over torch.distributed.all_reduce for performing sum reduction of tensor over all processes in both distributed / non-distributed scenarios. """ return all_reduce_op(tensor, torch.distributed.ReduceOp.SUM)
[ "def", "all_reduce_sum", "(", "tensor", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "return", "all_reduce_op", "(", "tensor", ",", "torch", ".", "distributed", ".", "ReduceOp", ".", "SUM", ")" ]
https://github.com/facebookresearch/ClassyVision/blob/309d4f12431c6b4d8540010a781dc2aa25fe88e7/classy_vision/generic/distributed_util.py#L76-L82
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/site-packages/setuptools/glob.py
python
iglob
(pathname, recursive=False)
return it
Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories.
Return an iterator which yields the paths matching a pathname pattern.
[ "Return", "an", "iterator", "which", "yields", "the", "paths", "matching", "a", "pathname", "pattern", "." ]
def iglob(pathname, recursive=False): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. """ it = _iglob(pathname, recursive) if recursive and _isrecursive(pathname): s = next(it) # skip empty string assert not s return it
[ "def", "iglob", "(", "pathname", ",", "recursive", "=", "False", ")", ":", "it", "=", "_iglob", "(", "pathname", ",", "recursive", ")", "if", "recursive", "and", "_isrecursive", "(", "pathname", ")", ":", "s", "=", "next", "(", "it", ")", "# skip empty...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/setuptools/glob.py#L30-L45
beancount/fava
69614956d3c01074403af0a07ddbaa986cf602a0
src/fava/core/__init__.py
python
FavaLedger.load_file
(self)
Load the main file and all included files and set attributes.
Load the main file and all included files and set attributes.
[ "Load", "the", "main", "file", "and", "all", "included", "files", "and", "set", "attributes", "." ]
def load_file(self) -> None: """Load the main file and all included files and set attributes.""" # use the internal function to disable cache if not self._is_encrypted: # pylint: disable=protected-access self.all_entries, self.errors, self.options = loader._load( [(self.beancount_file_path, True)], None, None, None ) else: self.all_entries, self.errors, self.options = loader.load_file( self.beancount_file_path ) self.account_types = get_account_types(self.options) self.price_map = build_price_map(self.all_entries) self.all_root_account = realization.realize( self.all_entries, self.account_types ) self.all_entries_by_type = group_entries_by_type(self.all_entries) self.accounts = AccountDict() for open_entry in self.all_entries_by_type.Open: self.accounts.setdefault(open_entry.account).meta = open_entry.meta for close in self.all_entries_by_type.Close: self.accounts.setdefault(close.account).close_date = close.date self.commodities = {} for commodity in self.all_entries_by_type.Commodity: self.commodities[commodity.currency] = commodity self.fava_options, errors = parse_options( self.all_entries_by_type.Custom ) self.errors.extend(errors) if not self._is_encrypted: self._watcher.update(*self.paths_to_watch()) for mod in MODULES: getattr(self, mod).load_file() self.filters = Filters(self.options, self.fava_options) self.filter(True)
[ "def", "load_file", "(", "self", ")", "->", "None", ":", "# use the internal function to disable cache", "if", "not", "self", ".", "_is_encrypted", ":", "# pylint: disable=protected-access", "self", ".", "all_entries", ",", "self", ".", "errors", ",", "self", ".", ...
https://github.com/beancount/fava/blob/69614956d3c01074403af0a07ddbaa986cf602a0/src/fava/core/__init__.py#L220-L264
eliostvs/tomate-gtk
29e4db6b1e9bad34eee87bb64932c397eb2dffc0
tomate/pomodoro/config.py
python
remove_duplicates
(original: List[str])
return list(set(original))
[]
def remove_duplicates(original: List[str]) -> List[str]: return list(set(original))
[ "def", "remove_duplicates", "(", "original", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "list", "(", "set", "(", "original", ")", ")" ]
https://github.com/eliostvs/tomate-gtk/blob/29e4db6b1e9bad34eee87bb64932c397eb2dffc0/tomate/pomodoro/config.py#L129-L130
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/ext/importlib_metadata/__init__.py
python
distributions
(**kwargs)
return Distribution.discover(**kwargs)
Get all ``Distribution`` instances in the current environment. :return: An iterable of ``Distribution`` instances.
Get all ``Distribution`` instances in the current environment.
[ "Get", "all", "Distribution", "instances", "in", "the", "current", "environment", "." ]
def distributions(**kwargs): """Get all ``Distribution`` instances in the current environment. :return: An iterable of ``Distribution`` instances. """ return Distribution.discover(**kwargs)
[ "def", "distributions", "(", "*", "*", "kwargs", ")", ":", "return", "Distribution", ".", "discover", "(", "*", "*", "kwargs", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/ext/importlib_metadata/__init__.py#L675-L680
LexPredict/lexpredict-contraxsuite
1d5a2540d31f8f3f1adc442cfa13a7c007319899
sdk/python/sdk/openapi_client/model/project_document_similarity.py
python
ProjectDocumentSimilarity.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/LexPredict/lexpredict-contraxsuite/blob/1d5a2540d31f8f3f1adc442cfa13a7c007319899/sdk/python/sdk/openapi_client/model/project_document_similarity.py#L66-L71
unsky/focal-loss
f238924eabc566e98d3c72ad1c9c40f72922bc3f
faster_rcnn_mxnet/faster_rcnn/core/module.py
python
Module.get_params
(self)
return (self._arg_params, self._aux_params)
Get current parameters. Returns ------- `(arg_params, aux_params)`, each a dictionary of name to parameters (in `NDArray`) mapping.
Get current parameters. Returns ------- `(arg_params, aux_params)`, each a dictionary of name to parameters (in `NDArray`) mapping.
[ "Get", "current", "parameters", ".", "Returns", "-------", "(", "arg_params", "aux_params", ")", "each", "a", "dictionary", "of", "name", "to", "parameters", "(", "in", "NDArray", ")", "mapping", "." ]
def get_params(self): """Get current parameters. Returns ------- `(arg_params, aux_params)`, each a dictionary of name to parameters (in `NDArray`) mapping. """ assert self.binded and self.params_initialized if self._params_dirty: self._sync_params_from_devices() return (self._arg_params, self._aux_params)
[ "def", "get_params", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "if", "self", ".", "_params_dirty", ":", "self", ".", "_sync_params_from_devices", "(", ")", "return", "(", "self", ".", "_arg_params", ","...
https://github.com/unsky/focal-loss/blob/f238924eabc566e98d3c72ad1c9c40f72922bc3f/faster_rcnn_mxnet/faster_rcnn/core/module.py#L218-L229
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/google_assistant/helpers.py
python
_get_entity_and_device
( hass: HomeAssistant, entity_id: str )
return entity_entry, device_entry
Fetch the entity and device entries for a entity_id.
Fetch the entity and device entries for a entity_id.
[ "Fetch", "the", "entity", "and", "device", "entries", "for", "a", "entity_id", "." ]
async def _get_entity_and_device( hass: HomeAssistant, entity_id: str ) -> tuple[RegistryEntry, DeviceEntry] | None: """Fetch the entity and device entries for a entity_id.""" dev_reg, ent_reg = await gather( hass.helpers.device_registry.async_get_registry(), hass.helpers.entity_registry.async_get_registry(), ) if not (entity_entry := ent_reg.async_get(entity_id)): return None, None device_entry = dev_reg.devices.get(entity_entry.device_id) return entity_entry, device_entry
[ "async", "def", "_get_entity_and_device", "(", "hass", ":", "HomeAssistant", ",", "entity_id", ":", "str", ")", "->", "tuple", "[", "RegistryEntry", ",", "DeviceEntry", "]", "|", "None", ":", "dev_reg", ",", "ent_reg", "=", "await", "gather", "(", "hass", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/google_assistant/helpers.py#L49-L61
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/gui/menus/legend/animation.py
python
AnimationWindow.on_update_min_max_defaults
(self)
When the icase is changed, the min/max value default message is changed
When the icase is changed, the min/max value default message is changed
[ "When", "the", "icase", "is", "changed", "the", "min", "/", "max", "value", "default", "message", "is", "changed" ]
def on_update_min_max_defaults(self): """ When the icase is changed, the min/max value default message is changed """ icase = self.icase_disp_start_edit.value() min_value, max_value = self.get_min_max(icase) self.min_value_button.setToolTip('Sets the min value to %g' % min_value) self.max_value_button.setToolTip('Sets the max value to %g' % max_value)
[ "def", "on_update_min_max_defaults", "(", "self", ")", ":", "icase", "=", "self", ".", "icase_disp_start_edit", ".", "value", "(", ")", "min_value", ",", "max_value", "=", "self", ".", "get_min_max", "(", "icase", ")", "self", ".", "min_value_button", ".", "...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/gui/menus/legend/animation.py#L807-L814
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
data/setData.py
python
SetData.rebuild
(self,mode='add',forceMembership=True)
return result
Rebuild the set from the stored setData. @param mode: Membership mode if the specified set already exists. Accepted values are "add" and "replace". @type mode: str @param forceMembership: Forces addition of items to the set. If items are in another set which is in the same partition as the given set, the items will be removed from the other set in order to keep the sets in the partition mutually exclusive with respect to membership. @type forceMembership: bool
Rebuild the set from the stored setData.
[ "Rebuild", "the", "set", "from", "the", "stored", "setData", "." ]
def rebuild(self,mode='add',forceMembership=True): ''' Rebuild the set from the stored setData. @param mode: Membership mode if the specified set already exists. Accepted values are "add" and "replace". @type mode: str @param forceMembership: Forces addition of items to the set. If items are in another set which is in the same partition as the given set, the items will be removed from the other set in order to keep the sets in the partition mutually exclusive with respect to membership. @type forceMembership: bool ''' # ========== # - Checks - # ========== # Set Name if not self._data['name']: raise Exception('SetData has not been initialized!') # Member Items memberList = self._data['membership'] or [] for obj in memberList: if not mc.objExists(obj): print('Set member item "'+obj+'" does not exist! Unable to add to set...') memberList.remove(obj) # Flatten Membership List memberList = mc.ls(memberList,fl=True) or [] # Mode if not mode in self.mode: raise Exception('Invalid set membership mode "'+mode+'"! Use "add" or "replace"!') # =============== # - Rebuild Set - # =============== # Start timer timer = mc.timerX() # Create Set setName = self._data['name'] # Delete Set (REPLACE only) if mc.objExists(setName) and mode == 'replace': mc.delete(setName) # Create Set if not mc.objExists(setName): setName = mc.sets(n=setName) # Add Members if memberList: if forceMembership: for obj in memberList: try: mc.sets(obj,e=True,fe=setName) except Exception, e: print('Error adding item "'+obj+'" to set "'+setName+'"! Skipping') print(str(e)) else: for obj in memberList: try: mc.sets(obj,e=True,add=setName) except Exception, e: print('Error adding item "'+obj+'" to set "'+setName+'"! Skipping') print(str(e)) # Print Timer Result buildTime = mc.timerX(st=timer) print('SetData: Rebuild time for set "'+setName+'": '+str(buildTime)) # ================= # - Return Result - # ================= self.setName = setName result = {} result['set'] = setName result['membership'] = memberList return result
[ "def", "rebuild", "(", "self", ",", "mode", "=", "'add'", ",", "forceMembership", "=", "True", ")", ":", "# ==========", "# - Checks -", "# ==========", "# Set Name", "if", "not", "self", ".", "_data", "[", "'name'", "]", ":", "raise", "Exception", "(", "'...
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/data/setData.py#L80-L154
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v6_0/pipelines_checks/pipelines_checks_client.py
python
PipelinesChecksClient.delete_check_configuration
(self, project, id)
DeleteCheckConfiguration. [Preview API] :param str project: Project ID or project name :param int id:
DeleteCheckConfiguration. [Preview API] :param str project: Project ID or project name :param int id:
[ "DeleteCheckConfiguration", ".", "[", "Preview", "API", "]", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", "int", "id", ":" ]
def delete_check_configuration(self, project, id): """DeleteCheckConfiguration. [Preview API] :param str project: Project ID or project name :param int id: """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if id is not None: route_values['id'] = self._serialize.url('id', id, 'int') self._send(http_method='DELETE', location_id='86c8381e-5aee-4cde-8ae4-25c0c7f5eaea', version='6.0-preview.1', route_values=route_values)
[ "def", "delete_check_configuration", "(", "self", ",", "project", ",", "id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'pro...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/pipelines_checks/pipelines_checks_client.py#L46-L60
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/oda/oda_client_composite_operations.py
python
OdaClientCompositeOperations.__init__
(self, client, **kwargs)
Creates a new OdaClientCompositeOperations object :param OdaClient client: The service client which will be wrapped by this object
Creates a new OdaClientCompositeOperations object
[ "Creates", "a", "new", "OdaClientCompositeOperations", "object" ]
def __init__(self, client, **kwargs): """ Creates a new OdaClientCompositeOperations object :param OdaClient client: The service client which will be wrapped by this object """ self.client = client
[ "def", "__init__", "(", "self", ",", "client", ",", "*", "*", "kwargs", ")", ":", "self", ".", "client", "=", "client" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/oda/oda_client_composite_operations.py#L17-L24
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
Lib/xml/sax/handler.py
python
ContentHandler.processingInstruction
(self, target, data)
Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.
Receive notification of a processing instruction.
[ "Receive", "notification", "of", "a", "processing", "instruction", "." ]
def processingInstruction(self, target, data): """Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method."""
[ "def", "processingInstruction", "(", "self", ",", "target", ",", "data", ")", ":" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/Lib/xml/sax/handler.py#L185-L194
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/parser/statements.py
python
Parser._parse_palette_using
(self, ins)
Parse PALETTE USING syntax.
Parse PALETTE USING syntax.
[ "Parse", "PALETTE", "USING", "syntax", "." ]
def _parse_palette_using(self, ins): """Parse PALETTE USING syntax.""" ins.require_read((tk.USING,)) array_name, start_indices = self._parse_variable(ins) yield array_name, start_indices # brackets are not optional error.throw_if(not start_indices, error.STX)
[ "def", "_parse_palette_using", "(", "self", ",", "ins", ")", ":", "ins", ".", "require_read", "(", "(", "tk", ".", "USING", ",", ")", ")", "array_name", ",", "start_indices", "=", "self", ".", "_parse_variable", "(", "ins", ")", "yield", "array_name", ",...
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/parser/statements.py#L1325-L1331
google-research/morph-net
be4d79dea816c473007c5967d45ab4036306c21c
morph_net/network_regularizers/resource_function.py
python
_calculate_bilinear_regularization
( op, coeff, num_alive_inputs, num_alive_outputs, reg_inputs, reg_outputs, batch_size)
Calculates bilinear regularization term for an op. Args: op: A tf.Operation. coeff: A float coefficient for the bilinear function. num_alive_inputs: Scalar Tensor indicating how many input channels are considered alive. num_alive_outputs: Scalar Tensor indicating how many output channels are considered alive. reg_inputs: Scalar Tensor which is the sum over the input regularization vector. reg_outputs: Scalar Tensor which is the sum over the output regularization vector. batch_size: Integer batch size to calculate cost/loss for. Returns: Tensor with the regularization loss of the op.
Calculates bilinear regularization term for an op.
[ "Calculates", "bilinear", "regularization", "term", "for", "an", "op", "." ]
def _calculate_bilinear_regularization( op, coeff, num_alive_inputs, num_alive_outputs, reg_inputs, reg_outputs, batch_size): """Calculates bilinear regularization term for an op. Args: op: A tf.Operation. coeff: A float coefficient for the bilinear function. num_alive_inputs: Scalar Tensor indicating how many input channels are considered alive. num_alive_outputs: Scalar Tensor indicating how many output channels are considered alive. reg_inputs: Scalar Tensor which is the sum over the input regularization vector. reg_outputs: Scalar Tensor which is the sum over the output regularization vector. batch_size: Integer batch size to calculate cost/loss for. Returns: Tensor with the regularization loss of the op. """ if op.type == 'DepthwiseConv2dNative': # reg_inputs and reg_outputs are often identical since they should # come from the same regularizer. Duplicate them for symmetry. # When the input doesn't have a regularizer (e.g. input), only the # second term is used. # TODO(b1): revisit this expression after experiments. return batch_size * coeff * (reg_inputs + reg_outputs) else: # Handle normal ops. return batch_size * coeff * ( num_alive_inputs * reg_outputs + num_alive_outputs * reg_inputs)
[ "def", "_calculate_bilinear_regularization", "(", "op", ",", "coeff", ",", "num_alive_inputs", ",", "num_alive_outputs", ",", "reg_inputs", ",", "reg_outputs", ",", "batch_size", ")", ":", "if", "op", ".", "type", "==", "'DepthwiseConv2dNative'", ":", "# reg_inputs ...
https://github.com/google-research/morph-net/blob/be4d79dea816c473007c5967d45ab4036306c21c/morph_net/network_regularizers/resource_function.py#L446-L477
intohole/moodstyle
1d06fc565c0df4bf07196854f3efb94bbefd1bfb
moodstyle/classifier/Bp1.py
python
Neroun.update
(self , target, predict)
return error
[]
def update(self , target, predict): error = target - predict for i in self.weight_range: self.weights[i] += self.rate * error return error
[ "def", "update", "(", "self", ",", "target", ",", "predict", ")", ":", "error", "=", "target", "-", "predict", "for", "i", "in", "self", ".", "weight_range", ":", "self", ".", "weights", "[", "i", "]", "+=", "self", ".", "rate", "*", "error", "retu...
https://github.com/intohole/moodstyle/blob/1d06fc565c0df4bf07196854f3efb94bbefd1bfb/moodstyle/classifier/Bp1.py#L38-L42
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/build/build_client.py
python
BuildClient.delete_folder
(self, project, path)
DeleteFolder. [Preview API] Deletes a definition folder. Definitions and their corresponding builds will also be deleted. :param str project: Project ID or project name :param str path: The full path to the folder.
DeleteFolder. [Preview API] Deletes a definition folder. Definitions and their corresponding builds will also be deleted. :param str project: Project ID or project name :param str path: The full path to the folder.
[ "DeleteFolder", ".", "[", "Preview", "API", "]", "Deletes", "a", "definition", "folder", ".", "Definitions", "and", "their", "corresponding", "builds", "will", "also", "be", "deleted", ".", ":", "param", "str", "project", ":", "Project", "ID", "or", "project...
def delete_folder(self, project, path): """DeleteFolder. [Preview API] Deletes a definition folder. Definitions and their corresponding builds will also be deleted. :param str project: Project ID or project name :param str path: The full path to the folder. """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') query_parameters = {} if path is not None: query_parameters['path'] = self._serialize.query('path', path, 'str') self._send(http_method='DELETE', location_id='a906531b-d2da-4f55-bda7-f3e676cc50d9', version='5.1-preview.2', route_values=route_values, query_parameters=query_parameters)
[ "def", "delete_folder", "(", "self", ",", "project", ",", "path", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'project'", "...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/build/build_client.py#L907-L923
kozec/sc-controller
ce92c773b8b26f6404882e9209aff212c4053170
scc/gui/ring_editor.py
python
RingEditor.on_btCustomActionEditor_clicked
(self, *a)
Handler for 'Custom Editor' button
Handler for 'Custom Editor' button
[ "Handler", "for", "Custom", "Editor", "button" ]
def on_btCustomActionEditor_clicked(self, *a): """ Handler for 'Custom Editor' button """ from scc.gui.action_editor import ActionEditor # Can't be imported on top e = ActionEditor(self.app, self.ac_callback) e.set_input(self.id, self._make_action(), mode = self.mode) e.hide_action_buttons() e.hide_advanced_settings() e.set_title(_("Custom Action")) e.force_page(e.load_component("custom"), True) self.send_added_widget(e) self.close() e.show(self.get_transient_for())
[ "def", "on_btCustomActionEditor_clicked", "(", "self", ",", "*", "a", ")", ":", "from", "scc", ".", "gui", ".", "action_editor", "import", "ActionEditor", "# Can't be imported on top", "e", "=", "ActionEditor", "(", "self", ".", "app", ",", "self", ".", "ac_ca...
https://github.com/kozec/sc-controller/blob/ce92c773b8b26f6404882e9209aff212c4053170/scc/gui/ring_editor.py#L144-L155
JasperSnoek/spearmint
b37a541be1ea035f82c7c82bbd93f5b4320e7d91
spearmint/spearmint/chooser/cma.py
python
DerivedDictBase.__getitem__
(self, key)
return self.data[key]
defines self[key]
defines self[key]
[ "defines", "self", "[", "key", "]" ]
def __getitem__(self, key): """defines self[key]""" return self.data[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "data", "[", "key", "]" ]
https://github.com/JasperSnoek/spearmint/blob/b37a541be1ea035f82c7c82bbd93f5b4320e7d91/spearmint/spearmint/chooser/cma.py#L354-L356
euphrat1ca/fuzzdb-collect
f32552a4d5d84350552c68801aed281ca1f48e66
ScriptShare/pacemake/pacemaker.py
python
PacemakerServer.serve_forever
(self)
[]
def serve_forever(self): self.stopped = False while not self.stopped: self.handle_request()
[ "def", "serve_forever", "(", "self", ")", ":", "self", ".", "stopped", "=", "False", "while", "not", "self", ".", "stopped", ":", "self", ".", "handle_request", "(", ")" ]
https://github.com/euphrat1ca/fuzzdb-collect/blob/f32552a4d5d84350552c68801aed281ca1f48e66/ScriptShare/pacemake/pacemaker.py#L431-L434
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/addons/addon.py
python
Addon.ingress_entry
(self)
return None
Return ingress external URL.
Return ingress external URL.
[ "Return", "ingress", "external", "URL", "." ]
def ingress_entry(self) -> Optional[str]: """Return ingress external URL.""" if self.with_ingress: return f"/api/hassio_ingress/{self.ingress_token}" return None
[ "def", "ingress_entry", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "with_ingress", ":", "return", "f\"/api/hassio_ingress/{self.ingress_token}\"", "return", "None" ]
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/addons/addon.py#L264-L268
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/messaging/scheduling/forms.py
python
ScheduleForm.is_valid
(self)
[]
def is_valid(self): # Make sure .is_valid() is called on all appropriate forms before returning. # Don't let the result of one short-circuit the expression and prevent calling the others. schedule_form_is_valid = super(ScheduleForm, self).is_valid() custom_event_formset_is_valid = self.custom_event_formset.is_valid() standalone_content_form_is_valid = self.standalone_content_form.is_valid() if self.cleaned_data_uses_custom_event_definitions(): return schedule_form_is_valid and custom_event_formset_is_valid else: return schedule_form_is_valid and standalone_content_form_is_valid
[ "def", "is_valid", "(", "self", ")", ":", "# Make sure .is_valid() is called on all appropriate forms before returning.", "# Don't let the result of one short-circuit the expression and prevent calling the others.", "schedule_form_is_valid", "=", "super", "(", "ScheduleForm", ",", "self"...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/messaging/scheduling/forms.py#L1161-L1172
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1beta1_volume_attachment_list.py
python
V1beta1VolumeAttachmentList.__eq__
(self, other)
return self.to_dict() == other.to_dict()
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1VolumeAttachmentList): return False return self.to_dict() == other.to_dict()
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1beta1VolumeAttachmentList", ")", ":", "return", "False", "return", "self", ".", "to_dict", "(", ")", "==", "other", ".", "to_dict", "(", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_volume_attachment_list.py#L193-L198
Unidata/MetPy
1153590f397ae23adfea66c4adb0a206872fa0ad
tools/flake8-metpy/flake8_metpy.py
python
MetPyVisitor.error
(self, lineno, col, code)
Add an error to our output list.
Add an error to our output list.
[ "Add", "an", "error", "to", "our", "output", "list", "." ]
def error(self, lineno, col, code): """Add an error to our output list.""" self.errors.append(Error(lineno, col, code))
[ "def", "error", "(", "self", ",", "lineno", ",", "col", ",", "code", ")", ":", "self", ".", "errors", ".", "append", "(", "Error", "(", "lineno", ",", "col", ",", "code", ")", ")" ]
https://github.com/Unidata/MetPy/blob/1153590f397ae23adfea66c4adb0a206872fa0ad/tools/flake8-metpy/flake8_metpy.py#L46-L48
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Style.py
python
add_palette_colour
(colour_str, colour_index)
[]
def add_palette_colour(colour_str, colour_index): if not (8 <= colour_index <= 63): raise Exception("add_palette_colour: colour_index (%d) not in range(8, 64)" % (colour_index)) colour_map[colour_str] = colour_index
[ "def", "add_palette_colour", "(", "colour_str", ",", "colour_index", ")", ":", "if", "not", "(", "8", "<=", "colour_index", "<=", "63", ")", ":", "raise", "Exception", "(", "\"add_palette_colour: colour_index (%d) not in range(8, 64)\"", "%", "(", "colour_index", ")...
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Style.py#L376-L380
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/events/registration/formsets.py
python
RegistrantBaseFormSet.get_user_list
(self)
return users
returns a list of user registrants
returns a list of user registrants
[ "returns", "a", "list", "of", "user", "registrants" ]
def get_user_list(self): """returns a list of user registrants""" users = [] for i in range(0, self.total_form_count()): form = self.forms[i] user = form.get_user() if not user.is_anonymous: users.append(user) return users
[ "def", "get_user_list", "(", "self", ")", ":", "users", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "total_form_count", "(", ")", ")", ":", "form", "=", "self", ".", "forms", "[", "i", "]", "user", "=", "form", ".", "g...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/events/registration/formsets.py#L98-L106
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster/config/cluster_config.py
python
HeadNode.is_ebs_optimized
(self)
return self.instance_type_info.is_ebs_optimized()
Return True if the instance has optimized EBS support.
Return True if the instance has optimized EBS support.
[ "Return", "True", "if", "the", "instance", "has", "optimized", "EBS", "support", "." ]
def is_ebs_optimized(self) -> bool: """Return True if the instance has optimized EBS support.""" return self.instance_type_info.is_ebs_optimized()
[ "def", "is_ebs_optimized", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "instance_type_info", ".", "is_ebs_optimized", "(", ")" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster/config/cluster_config.py#L889-L891
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/auth.py
python
OAuthTokenFromHttpBody
(http_body)
return oauth_token
Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token.
Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token.
[ "Parses", "the", "HTTP", "response", "body", "and", "returns", "an", "OAuth", "token", ".", "The", "returned", "OAuth", "token", "will", "just", "have", "key", "and", "secret", "parameters", "set", ".", "It", "won", "t", "have", "any", "knowledge", "about"...
def OAuthTokenFromHttpBody(http_body): """Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token. """ token = oauth.OAuthToken.from_string(http_body) oauth_token = OAuthToken(key=token.key, secret=token.secret) return oauth_token
[ "def", "OAuthTokenFromHttpBody", "(", "http_body", ")", ":", "token", "=", "oauth", ".", "OAuthToken", ".", "from_string", "(", "http_body", ")", "oauth_token", "=", "OAuthToken", "(", "key", "=", "token", ".", "key", ",", "secret", "=", "token", ".", "sec...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/auth.py#L572-L584
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
24-class-metaprog/bulkfood/model_v8.py
python
AutoStorage.__get__
(self, instance, owner)
[]
def __get__(self, instance, owner): if instance is None: return self else: return getattr(instance, self.storage_name)
[ "def", "__get__", "(", "self", ",", "instance", ",", "owner", ")", ":", "if", "instance", "is", "None", ":", "return", "self", "else", ":", "return", "getattr", "(", "instance", ",", "self", ".", "storage_name", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/24-class-metaprog/bulkfood/model_v8.py#L15-L19
zzw922cn/Automatic_Speech_Recognition
3fe0514d1377a16170923ff1ada6f808e907fcba
speechvalley/pipeline/big_input.py
python
_bytes_feature
(value)
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
[]
def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
[ "def", "_bytes_feature", "(", "value", ")", ":", "return", "tf", ".", "train", ".", "Feature", "(", "bytes_list", "=", "tf", ".", "train", ".", "BytesList", "(", "value", "=", "[", "value", "]", ")", ")" ]
https://github.com/zzw922cn/Automatic_Speech_Recognition/blob/3fe0514d1377a16170923ff1ada6f808e907fcba/speechvalley/pipeline/big_input.py#L26-L27
pwnieexpress/raspberry_pwn
86f80e781cfb9f130a21a7ff41ef3d5c0340f287
src/pexpect-2.3/pexpect.py
python
searcher_re.__str__
(self)
return '\n'.join(ss)
This returns a human-readable string that represents the state of the object.
This returns a human-readable string that represents the state of the object.
[ "This", "returns", "a", "human", "-", "readable", "string", "that", "represents", "the", "state", "of", "the", "object", "." ]
def __str__(self): """This returns a human-readable string that represents the state of the object.""" ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches] ss.append((-1,'searcher_re:')) if self.eof_index >= 0: ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) if self.timeout_index >= 0: ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) ss.sort() ss = zip(*ss)[1] return '\n'.join(ss)
[ "def", "__str__", "(", "self", ")", ":", "ss", "=", "[", "(", "n", ",", "' %d: re.compile(\"%s\")'", "%", "(", "n", ",", "str", "(", "s", ".", "pattern", ")", ")", ")", "for", "n", ",", "s", "in", "self", ".", "_searches", "]", "ss", ".", "a...
https://github.com/pwnieexpress/raspberry_pwn/blob/86f80e781cfb9f130a21a7ff41ef3d5c0340f287/src/pexpect-2.3/pexpect.py#L1713-L1726
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/algo/hyperband.py
python
Hyperband.state_dict
(self)
return { "rng_state": self.rng.get_state(), "seed": self.seed, "_trials_info": copy.deepcopy(dict(self._trials_info)), "trial_to_brackets": copy.deepcopy(dict(self.trial_to_brackets)), "brackets": [bracket.state_dict for bracket in self.brackets], }
Return a state dict that can be used to reset the state of the algorithm.
Return a state dict that can be used to reset the state of the algorithm.
[ "Return", "a", "state", "dict", "that", "can", "be", "used", "to", "reset", "the", "state", "of", "the", "algorithm", "." ]
def state_dict(self): """Return a state dict that can be used to reset the state of the algorithm.""" return { "rng_state": self.rng.get_state(), "seed": self.seed, "_trials_info": copy.deepcopy(dict(self._trials_info)), "trial_to_brackets": copy.deepcopy(dict(self.trial_to_brackets)), "brackets": [bracket.state_dict for bracket in self.brackets], }
[ "def", "state_dict", "(", "self", ")", ":", "return", "{", "\"rng_state\"", ":", "self", ".", "rng", ".", "get_state", "(", ")", ",", "\"seed\"", ":", "self", ".", "seed", ",", "\"_trials_info\"", ":", "copy", ".", "deepcopy", "(", "dict", "(", "self",...
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/algo/hyperband.py#L236-L244
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/encodings/iso8859_8.py
python
Codec.encode
(self,input,errors='strict')
return codecs.charmap_encode(input,errors,encoding_table)
[]
def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table)
[ "def", "encode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "return", "codecs", ".", "charmap_encode", "(", "input", ",", "errors", ",", "encoding_table", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/encodings/iso8859_8.py#L11-L12
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/smtlib/script.py
python
SmtLibScript.to_file
(self, fname, daggify=True)
[]
def to_file(self, fname, daggify=True): with open(fname, "w") as outstream: self.serialize(outstream, daggify=daggify)
[ "def", "to_file", "(", "self", ",", "fname", ",", "daggify", "=", "True", ")", ":", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "outstream", ":", "self", ".", "serialize", "(", "outstream", ",", "daggify", "=", "daggify", ")" ]
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/smtlib/script.py#L223-L225
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/shlex.py
python
shlex.push_source
(self, newstream, newfile=None)
Push an input source onto the lexer's input source stack.
Push an input source onto the lexer's input source stack.
[ "Push", "an", "input", "source", "onto", "the", "lexer", "s", "input", "source", "stack", "." ]
def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if newfile is not None: print('shlex: pushing to file %s' % (self.infile,)) else: print('shlex: pushing to stream %s' % (self.instream,))
[ "def", "push_source", "(", "self", ",", "newstream", ",", "newfile", "=", "None", ")", ":", "if", "isinstance", "(", "newstream", ",", "str", ")", ":", "newstream", "=", "StringIO", "(", "newstream", ")", "self", ".", "filestack", ".", "appendleft", "(",...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/shlex.py#L78-L90
Anaconda-Platform/anaconda-project
df5ec33c12591e6512436d38d36c6132fa2e9618
anaconda_project/archiver.py
python
_unarchive_project
(archive_filename, project_dir, frontend, parent_dir=None)
Unpack an archive of files in the project. This takes care of several details, for example it deals with hostile archives containing files outside of the dest directory, and it handles both tar and zip. It does not load or validate the unpacked project. project_dir can be None to auto-choose one. If parent_dir is non-None, place the project_dir in it. This is most useful if project_dir is None. Args: archive_filename (str): the tar or zip archive file project_dir (str): the directory that will contain the project config file parent_dir (str): place project directory in here Returns: a ``Status``, if failed has ``errors``, on success has a ``project_dir`` property
Unpack an archive of files in the project.
[ "Unpack", "an", "archive", "of", "files", "in", "the", "project", "." ]
def _unarchive_project(archive_filename, project_dir, frontend, parent_dir=None): """Unpack an archive of files in the project. This takes care of several details, for example it deals with hostile archives containing files outside of the dest directory, and it handles both tar and zip. It does not load or validate the unpacked project. project_dir can be None to auto-choose one. If parent_dir is non-None, place the project_dir in it. This is most useful if project_dir is None. Args: archive_filename (str): the tar or zip archive file project_dir (str): the directory that will contain the project config file parent_dir (str): place project directory in here Returns: a ``Status``, if failed has ``errors``, on success has a ``project_dir`` property """ if project_dir is not None and os.path.isabs(project_dir) and parent_dir is not None: raise ValueError("If supplying parent_dir to unarchive, project_dir must be relative or None") frontend = _new_error_recorder(frontend) list_files = None extract_files = None if archive_filename.endswith(".zip"): list_files = _list_files_zip extract_files = _extract_files_zip elif any([archive_filename.endswith(suffix) for suffix in [".tar", ".tar.gz", ".tar.bz2"]]): list_files = _list_files_tar extract_files = _extract_files_tar else: frontend.error("Unsupported archive filename %s, must be a .zip, .tar.gz, or .tar.bz2" % (archive_filename)) return SimpleStatus(success=False, description=("Could not unpack archive %s" % archive_filename), errors=frontend.pop_errors()) try: result = _get_source_and_dest_files(archive_filename, list_files, project_dir, parent_dir, frontend) if result is None: return SimpleStatus(success=False, description=("Could not unpack archive %s" % archive_filename), errors=frontend.pop_errors()) (canonical_project_dir, src_and_dest) = result if len(src_and_dest) == 0: frontend.error("Archive does not contain a project directory or is empty.") return SimpleStatus(success=False, description=("Could not unpack archive %s" % archive_filename), errors=frontend.pop_errors()) if not os.path.exists(canonical_project_dir): os.makedirs(canonical_project_dir) try: extract_files(archive_filename, src_and_dest, frontend) except Exception as e: try: shutil.rmtree(canonical_project_dir) except (IOError, OSError): pass raise e return _UnarchiveStatus(success=True, description=("Project archive unpacked to %s." % canonical_project_dir), project_dir=canonical_project_dir) except (IOError, OSError, zipfile.error, tarfile.TarError) as e: frontend.error(str(e)) return SimpleStatus(success=False, description="Failed to read project archive.", errors=frontend.pop_errors())
[ "def", "_unarchive_project", "(", "archive_filename", ",", "project_dir", ",", "frontend", ",", "parent_dir", "=", "None", ")", ":", "if", "project_dir", "is", "not", "None", "and", "os", ".", "path", ".", "isabs", "(", "project_dir", ")", "and", "parent_dir...
https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/archiver.py#L584-L656
amimo/dcc
114326ab5a082a42c7728a375726489e4709ca29
androguard/core/bytecodes/dvm.py
python
EncodedArray.get_size
(self)
return self.size
Return the number of elements in the array :rtype: int
Return the number of elements in the array
[ "Return", "the", "number", "of", "elements", "in", "the", "array" ]
def get_size(self): """ Return the number of elements in the array :rtype: int """ return self.size
[ "def", "get_size", "(", "self", ")", ":", "return", "self", ".", "size" ]
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/core/bytecodes/dvm.py#L1417-L1423
idanr1986/cuckoo-droid
1350274639473d3d2b0ac740cae133ca53ab7444
analyzer/android/lib/api/androguard/dvm.py
python
Instruction.get_output
(self, idx=-1)
Return an additional output of the instruction :rtype: string
Return an additional output of the instruction
[ "Return", "an", "additional", "output", "of", "the", "instruction" ]
def get_output(self, idx=-1) : """ Return an additional output of the instruction :rtype: string """ raise("not implemented")
[ "def", "get_output", "(", "self", ",", "idx", "=", "-", "1", ")", ":", "raise", "(", "\"not implemented\"", ")" ]
https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android/lib/api/androguard/dvm.py#L3762-L3768
rll/rllab
ba78e4c16dc492982e648f117875b22af3965579
rllab/policies/base.py
python
Policy.recurrent
(self)
return False
Indicates whether the policy is recurrent. :return:
Indicates whether the policy is recurrent. :return:
[ "Indicates", "whether", "the", "policy", "is", "recurrent", ".", ":", "return", ":" ]
def recurrent(self): """ Indicates whether the policy is recurrent. :return: """ return False
[ "def", "recurrent", "(", "self", ")", ":", "return", "False" ]
https://github.com/rll/rllab/blob/ba78e4c16dc492982e648f117875b22af3965579/rllab/policies/base.py#L26-L31
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/autoscaler/_private/aliyun/utils.py
python
AcsClient.describe_instances
(self, tags=None, instance_ids=None)
return None
Query the details of one or more Elastic Compute Service (ECS) instances. :param tags: The tags of the instance. :param instance_ids: The IDs of ECS instances :return: ECS instance list
Query the details of one or more Elastic Compute Service (ECS) instances.
[ "Query", "the", "details", "of", "one", "or", "more", "Elastic", "Compute", "Service", "(", "ECS", ")", "instances", "." ]
def describe_instances(self, tags=None, instance_ids=None): """ Query the details of one or more Elastic Compute Service (ECS) instances. :param tags: The tags of the instance. :param instance_ids: The IDs of ECS instances :return: ECS instance list """ request = DescribeInstancesRequest() if tags is not None: request.set_Tags(tags) if instance_ids is not None: request.set_InstanceIds(instance_ids) response = self._send_request(request) if response is not None: instance_list = response.get("Instances").get("Instance") return instance_list return None
[ "def", "describe_instances", "(", "self", ",", "tags", "=", "None", ",", "instance_ids", "=", "None", ")", ":", "request", "=", "DescribeInstancesRequest", "(", ")", "if", "tags", "is", "not", "None", ":", "request", ".", "set_Tags", "(", "tags", ")", "i...
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/autoscaler/_private/aliyun/utils.py#L72-L88
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/req/req_set.py
python
RequirementSet.is_download
(self)
return False
[]
def is_download(self): if self.download_dir: self.download_dir = expanduser(self.download_dir) if os.path.exists(self.download_dir): return True else: logger.critical('Could not find download directory') raise InstallationError( "Could not find or access download directory '%s'" % display_path(self.download_dir)) return False
[ "def", "is_download", "(", "self", ")", ":", "if", "self", ".", "download_dir", ":", "self", ".", "download_dir", "=", "expanduser", "(", "self", ".", "download_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "download_dir", ")", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/req/req_set.py#L322-L332
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/idlelib/ColorDelegator.py
python
ColorDelegator.toggle_colorize_event
(self, event)
return "break"
[]
def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if DEBUG: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if DEBUG: print "stop colorizing" self.stop_colorizing = True self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if DEBUG: print "auto colorizing turned",\ self.allow_colorizing and "on" or "off" return "break"
[ "def", "toggle_colorize_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "after_id", ":", "after_id", "=", "self", ".", "after_id", "self", ".", "after_id", "=", "None", "if", "DEBUG", ":", "print", "\"cancel scheduled recolorizer\"", "self", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/idlelib/ColorDelegator.py#L123-L138
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/piglow/light.py
python
PiglowLight.brightness
(self)
return self._brightness
Return the brightness of the light.
Return the brightness of the light.
[ "Return", "the", "brightness", "of", "the", "light", "." ]
def brightness(self): """Return the brightness of the light.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/piglow/light.py#L75-L77
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/loaders/base.py
python
BaseLoader.import_from_cwd
(self, module, imp=None, package=None)
return import_from_cwd( module, self.import_module if imp is None else imp, package=package, )
[]
def import_from_cwd(self, module, imp=None, package=None): return import_from_cwd( module, self.import_module if imp is None else imp, package=package, )
[ "def", "import_from_cwd", "(", "self", ",", "module", ",", "imp", "=", "None", ",", "package", "=", "None", ")", ":", "return", "import_from_cwd", "(", "module", ",", "self", ".", "import_module", "if", "imp", "is", "None", "else", "imp", ",", "package",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/loaders/base.py#L102-L107
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/gevent/lock.py
python
RLock.release
(self)
[]
def release(self): if self._owner is not getcurrent(): raise RuntimeError("cannot release un-aquired lock") self._count = count = self._count - 1 if not count: self._owner = None self._block.release()
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "_owner", "is", "not", "getcurrent", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-aquired lock\"", ")", "self", ".", "_count", "=", "count", "=", "self", ".", "_count", "-", ...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/gevent/lock.py#L219-L225
deepmind/learning-to-learn
f3c1a8d176b8ea7cc60478bfcfdd10a7a52fd296
problems.py
python
simple_multi_optimizer
(num_dims=2)
return build
Multidimensional simple problem.
Multidimensional simple problem.
[ "Multidimensional", "simple", "problem", "." ]
def simple_multi_optimizer(num_dims=2): """Multidimensional simple problem.""" def get_coordinate(i): return tf.get_variable("x_{}".format(i), shape=[], dtype=tf.float32, initializer=tf.ones_initializer()) def build(): coordinates = [get_coordinate(i) for i in xrange(num_dims)] x = tf.concat([tf.expand_dims(c, 0) for c in coordinates], 0) return tf.reduce_sum(tf.square(x, name="x_squared")) return build
[ "def", "simple_multi_optimizer", "(", "num_dims", "=", "2", ")", ":", "def", "get_coordinate", "(", "i", ")", ":", "return", "tf", ".", "get_variable", "(", "\"x_{}\"", ".", "format", "(", "i", ")", ",", "shape", "=", "[", "]", ",", "dtype", "=", "tf...
https://github.com/deepmind/learning-to-learn/blob/f3c1a8d176b8ea7cc60478bfcfdd10a7a52fd296/problems.py#L54-L68
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/extra/dbgtool/dbgtool.py
python
main
(inputFile, outputFile)
[]
def main(inputFile, outputFile): if not os.path.isfile(inputFile): print "ERROR: the provided input file '%s' is not a regular file" % inputFile sys.exit(1) script = convert(inputFile) if outputFile: fpOut = open(outputFile, "w") sys.stdout = fpOut sys.stdout.write(script) sys.stdout.close() else: print script
[ "def", "main", "(", "inputFile", ",", "outputFile", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "inputFile", ")", ":", "print", "\"ERROR: the provided input file '%s' is not a regular file\"", "%", "inputFile", "sys", ".", "exit", "(", "1", "...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/extra/dbgtool/dbgtool.py#L60-L73
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/analysis/defects/defect_compatibility.py
python
DefectCompatibility.process_entry
(self, defect_entry, perform_corrections=True)
return defect_entry
Process a given DefectEntry with qualifiers given from initialization of class. Order of processing is: 1) perform all possible defect corrections with information given 2) consider delocalization analyses based on qualifier metrics given initialization of class. If delocalized, flag entry as delocalized 3) update corrections to defect entry and flag as delocalized Corrections are applied based on: i) if free charges are more than free_chg_cutoff then will not apply charge correction, because it no longer is applicable ii) use charge correction set by preferred_cc iii) only use BandFilling correction if use_bandfilling is set to True iv) only use BandEdgeShift correction if use_bandedgeshift is set to True
Process a given DefectEntry with qualifiers given from initialization of class. Order of processing is: 1) perform all possible defect corrections with information given 2) consider delocalization analyses based on qualifier metrics given initialization of class. If delocalized, flag entry as delocalized 3) update corrections to defect entry and flag as delocalized
[ "Process", "a", "given", "DefectEntry", "with", "qualifiers", "given", "from", "initialization", "of", "class", ".", "Order", "of", "processing", "is", ":", "1", ")", "perform", "all", "possible", "defect", "corrections", "with", "information", "given", "2", "...
def process_entry(self, defect_entry, perform_corrections=True): """ Process a given DefectEntry with qualifiers given from initialization of class. Order of processing is: 1) perform all possible defect corrections with information given 2) consider delocalization analyses based on qualifier metrics given initialization of class. If delocalized, flag entry as delocalized 3) update corrections to defect entry and flag as delocalized Corrections are applied based on: i) if free charges are more than free_chg_cutoff then will not apply charge correction, because it no longer is applicable ii) use charge correction set by preferred_cc iii) only use BandFilling correction if use_bandfilling is set to True iv) only use BandEdgeShift correction if use_bandedgeshift is set to True """ for struct_key in [ "bulk_sc_structure", "initial_defect_structure", "final_defect_structure", ]: if struct_key in defect_entry.parameters.keys() and isinstance(defect_entry.parameters[struct_key], dict): defect_entry.parameters[struct_key] = Structure.from_dict(defect_entry.parameters[struct_key]) if perform_corrections: self.perform_all_corrections(defect_entry) self.delocalization_analysis(defect_entry) # apply corrections based on delocalization analysis corrections = {} skip_charge_corrections = False if "num_hole_vbm" in defect_entry.parameters.keys(): if (self.free_chg_cutoff < defect_entry.parameters["num_hole_vbm"]) or ( self.free_chg_cutoff < defect_entry.parameters["num_elec_cbm"] ): logger.info("Will not use charge correction because too many free charges") skip_charge_corrections = True if skip_charge_corrections: corrections.update({"charge_correction": 0.0}) else: if ("freysoldt" in self.preferred_cc.lower()) and ("freysoldt_meta" in defect_entry.parameters.keys()): frey_meta = defect_entry.parameters["freysoldt_meta"] frey_corr = frey_meta["freysoldt_electrostatic"] + frey_meta["freysoldt_potential_alignment_correction"] corrections.update({"charge_correction": frey_corr}) elif "kumagai_meta" in defect_entry.parameters.keys(): kumagai_meta = defect_entry.parameters["kumagai_meta"] kumagai_corr = ( kumagai_meta["kumagai_electrostatic"] + kumagai_meta["kumagai_potential_alignment_correction"] ) corrections.update({"charge_correction": kumagai_corr}) else: logger.info("Could not use any charge correction because insufficient metadata was supplied.") if self.use_bandfilling: if "bandfilling_meta" in defect_entry.parameters.keys(): bfc_corr = defect_entry.parameters["bandfilling_meta"]["bandfilling_correction"] corrections.update({"bandfilling_correction": bfc_corr}) else: logger.info("Could not use band filling correction because insufficient metadata was supplied.") else: corrections.update({"bandfilling_correction": 0.0}) if self.use_bandedgeshift and ("bandshift_meta" in defect_entry.parameters.keys()): corrections.update( { "bandedgeshifting_correction": defect_entry.parameters["bandshift_meta"][ "bandedgeshifting_correction" ] } ) # also want to update relevant data for phase diagram defect_entry.parameters.update( { "phasediagram_meta": { "vbm": defect_entry.parameters["hybrid_vbm"], "gap": defect_entry.parameters["hybrid_cbm"] - defect_entry.parameters["hybrid_vbm"], } } ) else: corrections.update({"bandedgeshifting_correction": 0.0}) if isinstance(defect_entry.parameters["vbm"], float) and isinstance(defect_entry.parameters["cbm"], float): # still want to have vbm and gap ready for phase diagram defect_entry.parameters.update( { "phasediagram_meta": { "vbm": defect_entry.parameters["vbm"], "gap": defect_entry.parameters["cbm"] - defect_entry.parameters["vbm"], } } ) defect_entry.corrections.update(corrections) return defect_entry
[ "def", "process_entry", "(", "self", ",", "defect_entry", ",", "perform_corrections", "=", "True", ")", ":", "for", "struct_key", "in", "[", "\"bulk_sc_structure\"", ",", "\"initial_defect_structure\"", ",", "\"final_defect_structure\"", ",", "]", ":", "if", "struct...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/defects/defect_compatibility.py#L112-L209
WooYun/TangScan
f4fd60228ec09ad10bd3dd3ef3b67e58bcdd4aa5
tangscan/thirdparty/requests/utils.py
python
should_bypass_proxies
(url)
return False
Returns whether we should bypass proxies or not.
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy = get_proxy('no_proxy') netloc = urlparse(url).netloc if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the netloc, both with and without the port. no_proxy = no_proxy.replace(' ', '').split(',') ip = netloc.split(':')[0] if is_ipv4_address(ip): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True # If the system proxy settings indicate that this URL should be bypassed, # don't proxy. # The proxy_bypass function is incredibly buggy on OS X in early versions # of Python 2.6, so allow this call to fail. Only catch the specific # exceptions we've seen, though: this call failing in other ways can reveal # legitimate problems. try: bypass = proxy_bypass(netloc) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ")", ":", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ")", "or", "os", ".", "environ", ".", "get", "(", "k", ".", "upper", "(", ")", ")", "# First check whether no_proxy ...
https://github.com/WooYun/TangScan/blob/f4fd60228ec09ad10bd3dd3ef3b67e58bcdd4aa5/tangscan/thirdparty/requests/utils.py#L469-L512
LinuxCNC/linuxcnc
d42398ede7c839b3ef76298a5d2d753b50b6620c
src/emc/usr_intf/gscreen/gscreen.py
python
Gscreen.on_tool_touchoff_clicked
(self,widget)
This is a callback function for a press of the tool_touchoff button It calls tool_touchoff_checks()
This is a callback function for a press of the tool_touchoff button It calls tool_touchoff_checks()
[ "This", "is", "a", "callback", "function", "for", "a", "press", "of", "the", "tool_touchoff", "button", "It", "calls", "tool_touchoff_checks", "()" ]
def on_tool_touchoff_clicked(self,widget): """This is a callback function for a press of the tool_touchoff button It calls tool_touchoff_checks() """ print("touch") self.tool_touchoff_checks()
[ "def", "on_tool_touchoff_clicked", "(", "self", ",", "widget", ")", ":", "print", "(", "\"touch\"", ")", "self", ".", "tool_touchoff_checks", "(", ")" ]
https://github.com/LinuxCNC/linuxcnc/blob/d42398ede7c839b3ef76298a5d2d753b50b6620c/src/emc/usr_intf/gscreen/gscreen.py#L2513-L2518
merrychap/shellen
c0c5f8325dd3f0decf03e55d57c4714c797a2dea
shellen/opt/appearance.py
python
cprint
(text='', end='\n')
[]
def cprint(text='', end='\n'): colored_text = make_colors(text) print(colored_text, end=end)
[ "def", "cprint", "(", "text", "=", "''", ",", "end", "=", "'\\n'", ")", ":", "colored_text", "=", "make_colors", "(", "text", ")", "print", "(", "colored_text", ",", "end", "=", "end", ")" ]
https://github.com/merrychap/shellen/blob/c0c5f8325dd3f0decf03e55d57c4714c797a2dea/shellen/opt/appearance.py#L71-L73
LMFDB/lmfdb
6cf48a4c18a96e6298da6ae43f587f96845bcb43
lmfdb/backend/statstable.py
python
PostgresStatsTable._approx_most_common
(self, col, n)
return [tuple(x) for x in cur]
Returns the n most common values for ``col``. Counts are only approximate, but this functions should be quite fast. Note that the returned list may have length less than ``n`` if there are not many common values. Returns a list of pairs ``(value, count)`` where ``count`` is the number of rows where ``col`` takes on the value ``value``. INPUT: - ``col`` -- a column name - ``n`` -- an integer
Returns the n most common values for ``col``. Counts are only approximate, but this functions should be quite fast. Note that the returned list may have length less than ``n`` if there are not many common values.
[ "Returns", "the", "n", "most", "common", "values", "for", "col", ".", "Counts", "are", "only", "approximate", "but", "this", "functions", "should", "be", "quite", "fast", ".", "Note", "that", "the", "returned", "list", "may", "have", "length", "less", "tha...
def _approx_most_common(self, col, n): """ Returns the n most common values for ``col``. Counts are only approximate, but this functions should be quite fast. Note that the returned list may have length less than ``n`` if there are not many common values. Returns a list of pairs ``(value, count)`` where ``count`` is the number of rows where ``col`` takes on the value ``value``. INPUT: - ``col`` -- a column name - ``n`` -- an integer """ if col not in self.table.search_cols: raise ValueError("Column %s not a search column for %s" % (col, self.search_table)) selecter = SQL( """SELECT v.{0}, (c.reltuples * freq)::int as estimate_ct FROM pg_stats s CROSS JOIN LATERAL unnest(s.most_common_vals::text::""" + self.table.col_type[col] + """[] , s.most_common_freqs) WITH ORDINALITY v ({0}, freq, ord) CROSS JOIN ( SELECT reltuples FROM pg_class WHERE oid = regclass 'public.nf_fields') c WHERE schemaname = 'public' AND tablename = %s AND attname = %s ORDER BY v.ord LIMIT %s""" ).format(Identifier(col)) cur = self._execute(selecter, [self.search_table, col, n]) return [tuple(x) for x in cur]
[ "def", "_approx_most_common", "(", "self", ",", "col", ",", "n", ")", ":", "if", "col", "not", "in", "self", ".", "table", ".", "search_cols", ":", "raise", "ValueError", "(", "\"Column %s not a search column for %s\"", "%", "(", "col", ",", "self", ".", "...
https://github.com/LMFDB/lmfdb/blob/6cf48a4c18a96e6298da6ae43f587f96845bcb43/lmfdb/backend/statstable.py#L1345-L1376
zihangdai/xlnet
bbaa3a6fa0b3a2ee694e8cf66167434f9eca9660
modeling.py
python
rel_attn_core
(q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask, dropatt, is_training, scale)
return attn_vec
Core relative positional attention operations.
Core relative positional attention operations.
[ "Core", "relative", "positional", "attention", "operations", "." ]
def rel_attn_core(q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias, r_r_bias, r_s_bias, attn_mask, dropatt, is_training, scale): """Core relative positional attention operations.""" # content based attention score ac = tf.einsum('ibnd,jbnd->ijbn', q_head + r_w_bias, k_head_h) # position based attention score bd = tf.einsum('ibnd,jbnd->ijbn', q_head + r_r_bias, k_head_r) bd = rel_shift(bd, klen=tf.shape(ac)[1]) # segment based attention score if seg_mat is None: ef = 0 else: ef = tf.einsum('ibnd,snd->ibns', q_head + r_s_bias, seg_embed) ef = tf.einsum('ijbs,ibns->ijbn', seg_mat, ef) # merge attention scores and perform masking attn_score = (ac + bd + ef) * scale if attn_mask is not None: # attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask attn_score = attn_score - 1e30 * attn_mask # attention probability attn_prob = tf.nn.softmax(attn_score, 1) attn_prob = tf.layers.dropout(attn_prob, dropatt, training=is_training) # attention output attn_vec = tf.einsum('ijbn,jbnd->ibnd', attn_prob, v_head_h) return attn_vec
[ "def", "rel_attn_core", "(", "q_head", ",", "k_head_h", ",", "v_head_h", ",", "k_head_r", ",", "seg_embed", ",", "seg_mat", ",", "r_w_bias", ",", "r_r_bias", ",", "r_s_bias", ",", "attn_mask", ",", "dropatt", ",", "is_training", ",", "scale", ")", ":", "# ...
https://github.com/zihangdai/xlnet/blob/bbaa3a6fa0b3a2ee694e8cf66167434f9eca9660/modeling.py#L128-L160