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
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/lnchannel.py
python
AbstractChannel.sweep_address
(self)
return addr
[]
def sweep_address(self) -> str: # TODO: in case of unilateral close with pending HTLCs, this address will be reused addr = None if self.is_static_remotekey_enabled(): our_payment_pubkey = self.config[LOCAL].payment_basepoint.pubkey addr = make_commitment_output_to_remote_address(our_payment_pubkey) if addr is None: addr = self._fallback_sweep_address assert addr if self.lnworker: assert self.lnworker.wallet.is_mine(addr) return addr
[ "def", "sweep_address", "(", "self", ")", "->", "str", ":", "# TODO: in case of unilateral close with pending HTLCs, this address will be reused", "addr", "=", "None", "if", "self", ".", "is_static_remotekey_enabled", "(", ")", ":", "our_payment_pubkey", "=", "self", ".",...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/lnchannel.py#L323-L334
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/words/protocols/jabber/xmlstream.py
python
StreamManager.addHandler
(self, handler)
Add protocol handler. When an XML stream has already been established, the handler's C{connectionInitialized} will be called to get it up to speed.
Add protocol handler.
[ "Add", "protocol", "handler", "." ]
def addHandler(self, handler): """ Add protocol handler. When an XML stream has already been established, the handler's C{connectionInitialized} will be called to get it up to speed. """ XMPPHandlerCollection.addHandler(self, handler) # get protocol handler up to speed when a connection has already # been established if self.xmlstream and self._initialized: handler.makeConnection(self.xmlstream) handler.connectionInitialized()
[ "def", "addHandler", "(", "self", ",", "handler", ")", ":", "XMPPHandlerCollection", ".", "addHandler", "(", "self", ",", "handler", ")", "# get protocol handler up to speed when a connection has already", "# been established", "if", "self", ".", "xmlstream", "and", "se...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/words/protocols/jabber/xmlstream.py#L1020-L1033
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/docview.py
python
PathOnly
(path)
return os.path.split(path)[0]
Returns the path of a full path without the filename.
Returns the path of a full path without the filename.
[ "Returns", "the", "path", "of", "a", "full", "path", "without", "the", "filename", "." ]
def PathOnly(path): """ Returns the path of a full path without the filename. """ return os.path.split(path)[0]
[ "def", "PathOnly", "(", "path", ")", ":", "return", "os", ".", "path", ".", "split", "(", "path", ")", "[", "0", "]" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/docview.py#L66-L70
cms-dev/cms
0401c5336b34b1731736045da4877fef11889274
cms/server/jinja2_toolbox.py
python
today
(ctx, dt)
return dt.replace(tzinfo=utc).astimezone(timezone).date() \ == now.replace(tzinfo=utc).astimezone(timezone).date()
Returns whether the given datetime is today. ctx (Context): a Jinja2 context, needed to retrieve the current datetime and the timezone to use when comparing. dt (datetime): a datetime. return (bool): whether dt occurred today in the timezone.
Returns whether the given datetime is today.
[ "Returns", "whether", "the", "given", "datetime", "is", "today", "." ]
def today(ctx, dt): """Returns whether the given datetime is today. ctx (Context): a Jinja2 context, needed to retrieve the current datetime and the timezone to use when comparing. dt (datetime): a datetime. return (bool): whether dt occurred today in the timezone. """ now = ctx.get("now", make_datetime()) timezone = ctx.get("timezone", local_tz) return dt.replace(tzinfo=utc).astimezone(timezone).date() \ == now.replace(tzinfo=utc).astimezone(timezone).date()
[ "def", "today", "(", "ctx", ",", "dt", ")", ":", "now", "=", "ctx", ".", "get", "(", "\"now\"", ",", "make_datetime", "(", ")", ")", "timezone", "=", "ctx", ".", "get", "(", "\"timezone\"", ",", "local_tz", ")", "return", "dt", ".", "replace", "(",...
https://github.com/cms-dev/cms/blob/0401c5336b34b1731736045da4877fef11889274/cms/server/jinja2_toolbox.py#L119-L132
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/cookielib.py
python
CookieJar.clear_session_cookies
(self)
Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.
Discard all session cookies.
[ "Discard", "all", "session", "cookies", "." ]
def clear_session_cookies(self): """Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. """ self._cookies_lock.acquire() try: for cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
[ "def", "clear_session_cookies", "(", "self", ")", ":", "self", ".", "_cookies_lock", ".", "acquire", "(", ")", "try", ":", "for", "cookie", "in", "self", ":", "if", "cookie", ".", "discard", ":", "self", ".", "clear", "(", "cookie", ".", "domain", ",",...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/cookielib.py#L1676-L1689
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/plat-irix6/FILE.py
python
BBTOB
(bbs)
return ((bbs) << BBSHIFT)
[]
def BBTOB(bbs): return ((bbs) << BBSHIFT)
[ "def", "BBTOB", "(", "bbs", ")", ":", "return", "(", "(", "bbs", ")", "<<", "BBSHIFT", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-irix6/FILE.py#L441-L441
lzx1413/PytorchSSD
320fe34f394f40aaa3b8a34d1ceed46e7ffecd46
models/RFB_Net_vgg.py
python
BasicRFB_a.__init__
(self, in_planes, out_planes, stride=1, scale=0.1)
self.branch3 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=3, dilation=3, relu=False) )
self.branch3 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=3, dilation=3, relu=False) )
[ "self", ".", "branch3", "=", "nn", ".", "Sequential", "(", "BasicConv", "(", "in_planes", "inter_planes", "kernel_size", "=", "1", "stride", "=", "1", ")", "BasicConv", "(", "inter_planes", "inter_planes", "kernel_size", "=", "3", "stride", "=", "1", "paddin...
def __init__(self, in_planes, out_planes, stride=1, scale=0.1): super(BasicRFB_a, self).__init__() self.scale = scale self.out_channels = out_planes inter_planes = in_planes // 4 self.branch0 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=1, relu=False) ) self.branch1 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=(3, 1), stride=1, padding=(1, 0)), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=3, dilation=3, relu=False) ) self.branch2 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=(1, 3), stride=stride, padding=(0, 1)), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=3, dilation=3, relu=False) ) ''' self.branch3 = nn.Sequential( BasicConv(in_planes, inter_planes, kernel_size=1, stride=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=1), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=3, dilation=3, relu=False) ) ''' self.branch3 = nn.Sequential( BasicConv(in_planes, inter_planes // 2, kernel_size=1, stride=1), BasicConv(inter_planes // 2, (inter_planes // 4) * 3, kernel_size=(1, 3), stride=1, padding=(0, 1)), BasicConv((inter_planes // 4) * 3, inter_planes, kernel_size=(3, 1), stride=stride, padding=(1, 0)), BasicConv(inter_planes, inter_planes, kernel_size=3, stride=1, padding=5, dilation=5, relu=False) ) self.ConvLinear = BasicConv(4 * inter_planes, out_planes, kernel_size=1, stride=1, relu=False) self.shortcut = BasicConv(in_planes, out_planes, kernel_size=1, stride=stride, relu=False) self.relu = nn.ReLU(inplace=False)
[ "def", "__init__", "(", "self", ",", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ",", "scale", "=", "0.1", ")", ":", "super", "(", "BasicRFB_a", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "scale", "=", "scale", "self", "...
https://github.com/lzx1413/PytorchSSD/blob/320fe34f394f40aaa3b8a34d1ceed46e7ffecd46/models/RFB_Net_vgg.py#L69-L105
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/tkinter/__init__.py
python
PanedWindow.panecget
(self, child, option)
return self.tk.call( (self._w, 'panecget') + (child, '-'+option))
Query a management option for window. Option may be any value allowed by the paneconfigure subcommand
Query a management option for window.
[ "Query", "a", "management", "option", "for", "window", "." ]
def panecget(self, child, option): """Query a management option for window. Option may be any value allowed by the paneconfigure subcommand """ return self.tk.call( (self._w, 'panecget') + (child, '-'+option))
[ "def", "panecget", "(", "self", ",", "child", ",", "option", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'panecget'", ")", "+", "(", "child", ",", "'-'", "+", "option", ")", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/tkinter/__init__.py#L3740-L3746
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
var_ref_t.__ne__
(self, *args)
return _idaapi.var_ref_t___ne__(self, *args)
__ne__(self, r) -> bool
__ne__(self, r) -> bool
[ "__ne__", "(", "self", "r", ")", "-", ">", "bool" ]
def __ne__(self, *args): """ __ne__(self, r) -> bool """ return _idaapi.var_ref_t___ne__(self, *args)
[ "def", "__ne__", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "var_ref_t___ne__", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L36965-L36969
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/contrib/ethosu.py
python
qnn_maxpool2d_pattern
()
return pattern
This function creates the pattern for nn.max_pool2d with optional fused RELU activation.
This function creates the pattern for nn.max_pool2d with optional fused RELU activation.
[ "This", "function", "creates", "the", "pattern", "for", "nn", ".", "max_pool2d", "with", "optional", "fused", "RELU", "activation", "." ]
def qnn_maxpool2d_pattern() -> tvm.relay.dataflow_pattern.DFPattern: """ This function creates the pattern for nn.max_pool2d with optional fused RELU activation. """ pattern = is_op("nn.max_pool2d")(wildcard()) pattern = pattern.optional(is_op("clip")) return pattern
[ "def", "qnn_maxpool2d_pattern", "(", ")", "->", "tvm", ".", "relay", ".", "dataflow_pattern", ".", "DFPattern", ":", "pattern", "=", "is_op", "(", "\"nn.max_pool2d\"", ")", "(", "wildcard", "(", ")", ")", "pattern", "=", "pattern", ".", "optional", "(", "i...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/contrib/ethosu.py#L396-L402
e2nIEE/pandapower
12bd83d7c4e1bf3fa338dab2db649c3cd3db0cfb
pandapower/control/run_control.py
python
prepare_run_ctrl
(net, ctrl_variables, **kwargs)
return ctrl_variables
Prepares run control functions. Internal variables needed: **controller_order** (list) - Order in which controllers in net.controller will be called **runpp** (function) - the runpp function (for time series a faster version is possible) **initial_run** (bool) - some controllers need an initial run of the powerflow prior to the control step
Prepares run control functions. Internal variables needed:
[ "Prepares", "run", "control", "functions", ".", "Internal", "variables", "needed", ":" ]
def prepare_run_ctrl(net, ctrl_variables, **kwargs): """ Prepares run control functions. Internal variables needed: **controller_order** (list) - Order in which controllers in net.controller will be called **runpp** (function) - the runpp function (for time series a faster version is possible) **initial_run** (bool) - some controllers need an initial run of the powerflow prior to the control step """ # sort controller_order by order if not already done ctrl_var = ctrl_variables if ctrl_variables is None: ctrl_variables = ctrl_variables_default(net) if ('continue_on_divergence') in kwargs and (ctrl_var is None or 'continue_on_divergence' not in ctrl_var.keys()): div = kwargs.pop('continue_on_divergence') ctrl_variables['continue_on_divergence'] = div if ('check_each_level') in kwargs and (ctrl_var is None or 'continue_on_divergence' not in ctrl_var.keys()): check = kwargs.pop('check_each_level') ctrl_variables['check_each_level'] = check ctrl_variables["errors"] = (LoadflowNotConverged, OPFNotConverged, NetCalculationNotConverged) return ctrl_variables
[ "def", "prepare_run_ctrl", "(", "net", ",", "ctrl_variables", ",", "*", "*", "kwargs", ")", ":", "# sort controller_order by order if not already done", "ctrl_var", "=", "ctrl_variables", "if", "ctrl_variables", "is", "None", ":", "ctrl_variables", "=", "ctrl_variables_...
https://github.com/e2nIEE/pandapower/blob/12bd83d7c4e1bf3fa338dab2db649c3cd3db0cfb/pandapower/control/run_control.py#L107-L133
cdhigh/KindleEar
7c4ecf9625239f12a829210d1760b863ef5a23aa
lib/cssutils/tokenize2.py
python
Tokenizer.__init__
(self, macros=None, productions=None, doComments=True)
inits tokenizer with given macros and productions which default to cssutils own macros and productions
inits tokenizer with given macros and productions which default to cssutils own macros and productions
[ "inits", "tokenizer", "with", "given", "macros", "and", "productions", "which", "default", "to", "cssutils", "own", "macros", "and", "productions" ]
def __init__(self, macros=None, productions=None, doComments=True): """ inits tokenizer with given macros and productions which default to cssutils own macros and productions """ if isinstance(macros, dict): macros_hash_key = sorted(macros.items()) else: macros_hash_key = macros hash_key = str((macros_hash_key, productions)) if hash_key in _TOKENIZER_CACHE: (tokenmatches, commentmatcher, urimatcher) = _TOKENIZER_CACHE[hash_key] else: if not macros: macros = MACROS if not productions: productions = PRODUCTIONS tokenmatches = self._compile_productions(self._expand_macros(macros, productions)) commentmatcher = [x[1] for x in tokenmatches if x[0] == 'COMMENT'][0] urimatcher = [x[1] for x in tokenmatches if x[0] == 'URI'][0] _TOKENIZER_CACHE[hash_key] = (tokenmatches, commentmatcher, urimatcher) self.tokenmatches = tokenmatches self.commentmatcher = commentmatcher self.urimatcher = urimatcher self._doComments = doComments self._pushed = []
[ "def", "__init__", "(", "self", ",", "macros", "=", "None", ",", "productions", "=", "None", ",", "doComments", "=", "True", ")", ":", "if", "isinstance", "(", "macros", ",", "dict", ")", ":", "macros_hash_key", "=", "sorted", "(", "macros", ".", "item...
https://github.com/cdhigh/KindleEar/blob/7c4ecf9625239f12a829210d1760b863ef5a23aa/lib/cssutils/tokenize2.py#L34-L62
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
deepxde/data/fpde.py
python
FractionalTime.get_matrix_dynamic
(self, sparse)
return self.fracx.get_matrix(sparse)
[]
def get_matrix_dynamic(self, sparse): return self.fracx.get_matrix(sparse)
[ "def", "get_matrix_dynamic", "(", "self", ",", "sparse", ")", ":", "return", "self", ".", "fracx", ".", "get_matrix", "(", "sparse", ")" ]
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/deepxde/data/fpde.py#L651-L652
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/boto/datapipeline/layer1.py
python
DataPipelineConnection.report_task_runner_heartbeat
(self, taskrunner_id, worker_group=None, hostname=None)
return self.make_request(action='ReportTaskRunnerHeartbeat', body=json.dumps(params))
Task runners call ReportTaskRunnerHeartbeat every 15 minutes to indicate that they are operational. In the case of AWS Data Pipeline Task Runner launched on a resource managed by AWS Data Pipeline, the web service can use this call to detect when the task runner application has failed and restart a new instance. :type taskrunner_id: string :param taskrunner_id: The identifier of the task runner. This value should be unique across your AWS account. In the case of AWS Data Pipeline Task Runner launched on a resource managed by AWS Data Pipeline, the web service provides a unique identifier when it launches the application. If you have written a custom task runner, you should assign a unique identifier for the task runner. :type worker_group: string :param worker_group: Indicates the type of task the task runner is configured to accept and process. The worker group is set as a field on objects in the pipeline when they are created. You can only specify a single value for `workerGroup` in the call to ReportTaskRunnerHeartbeat. There are no wildcard values permitted in `workerGroup`, the string must be an exact, case-sensitive, match. :type hostname: string :param hostname: The public DNS name of the calling task runner.
Task runners call ReportTaskRunnerHeartbeat every 15 minutes to indicate that they are operational. In the case of AWS Data Pipeline Task Runner launched on a resource managed by AWS Data Pipeline, the web service can use this call to detect when the task runner application has failed and restart a new instance.
[ "Task", "runners", "call", "ReportTaskRunnerHeartbeat", "every", "15", "minutes", "to", "indicate", "that", "they", "are", "operational", ".", "In", "the", "case", "of", "AWS", "Data", "Pipeline", "Task", "Runner", "launched", "on", "a", "resource", "managed", ...
def report_task_runner_heartbeat(self, taskrunner_id, worker_group=None, hostname=None): """ Task runners call ReportTaskRunnerHeartbeat every 15 minutes to indicate that they are operational. In the case of AWS Data Pipeline Task Runner launched on a resource managed by AWS Data Pipeline, the web service can use this call to detect when the task runner application has failed and restart a new instance. :type taskrunner_id: string :param taskrunner_id: The identifier of the task runner. This value should be unique across your AWS account. In the case of AWS Data Pipeline Task Runner launched on a resource managed by AWS Data Pipeline, the web service provides a unique identifier when it launches the application. If you have written a custom task runner, you should assign a unique identifier for the task runner. :type worker_group: string :param worker_group: Indicates the type of task the task runner is configured to accept and process. The worker group is set as a field on objects in the pipeline when they are created. You can only specify a single value for `workerGroup` in the call to ReportTaskRunnerHeartbeat. There are no wildcard values permitted in `workerGroup`, the string must be an exact, case-sensitive, match. :type hostname: string :param hostname: The public DNS name of the calling task runner. """ params = {'taskrunnerId': taskrunner_id, } if worker_group is not None: params['workerGroup'] = worker_group if hostname is not None: params['hostname'] = hostname return self.make_request(action='ReportTaskRunnerHeartbeat', body=json.dumps(params))
[ "def", "report_task_runner_heartbeat", "(", "self", ",", "taskrunner_id", ",", "worker_group", "=", "None", ",", "hostname", "=", "None", ")", ":", "params", "=", "{", "'taskrunnerId'", ":", "taskrunner_id", ",", "}", "if", "worker_group", "is", "not", "None",...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/datapipeline/layer1.py#L476-L513
LoRexxar/Kunlun-M
06a68cf308f3d38be223d1d891465abcac9db88a
utils/file.py
python
File.lines
(self, line_rule)
return content
获取指定行内容 :param line_rule: :return:
获取指定行内容 :param line_rule: :return:
[ "获取指定行内容", ":", "param", "line_rule", ":", ":", "return", ":" ]
def lines(self, line_rule): """ 获取指定行内容 :param line_rule: :return: """ result = get_line(self.file_path, line_rule) result = "\n".join(result) if len(result): try: content = result.decode('utf-8') except AttributeError as e: content = result if content == '': content = False else: content = False return content
[ "def", "lines", "(", "self", ",", "line_rule", ")", ":", "result", "=", "get_line", "(", "self", ".", "file_path", ",", "line_rule", ")", "result", "=", "\"\\n\"", ".", "join", "(", "result", ")", "if", "len", "(", "result", ")", ":", "try", ":", "...
https://github.com/LoRexxar/Kunlun-M/blob/06a68cf308f3d38be223d1d891465abcac9db88a/utils/file.py#L747-L765
sagemath/sagenb
67a73cbade02639bc08265f28f3165442113ad4d
sagenb/notebook/cell.py
python
Cell.next_compute_id
(self)
r""" Returns the ID of the next compute cell in this compute cell's worksheet object. If this cell is *not* in the worksheet, it returns the ID of the worksheet's *first* compute cell. If this *is* the last compute cell, it returns its *own* ID. OUTPUT: - an integer or string EXAMPLES:: sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb')) sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True) sage: W = nb.create_new_worksheet('Test', 'sage') sage: W.edit_save('foo\n{{{\n2+3\n///\n5\n}}}bar\n{{{\n2+8\n///\n10\n}}}') sage: W.new_cell_after(1, "2^2") Cell 4: in=2^2, out= sage: [W.get_cell_with_id(i).next_compute_id() for i in [1, 4, 3]] [4, 3, 3]
r""" Returns the ID of the next compute cell in this compute cell's worksheet object. If this cell is *not* in the worksheet, it returns the ID of the worksheet's *first* compute cell. If this *is* the last compute cell, it returns its *own* ID.
[ "r", "Returns", "the", "ID", "of", "the", "next", "compute", "cell", "in", "this", "compute", "cell", "s", "worksheet", "object", ".", "If", "this", "cell", "is", "*", "not", "*", "in", "the", "worksheet", "it", "returns", "the", "ID", "of", "the", "...
def next_compute_id(self): r""" Returns the ID of the next compute cell in this compute cell's worksheet object. If this cell is *not* in the worksheet, it returns the ID of the worksheet's *first* compute cell. If this *is* the last compute cell, it returns its *own* ID. OUTPUT: - an integer or string EXAMPLES:: sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb')) sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True) sage: W = nb.create_new_worksheet('Test', 'sage') sage: W.edit_save('foo\n{{{\n2+3\n///\n5\n}}}bar\n{{{\n2+8\n///\n10\n}}}') sage: W.new_cell_after(1, "2^2") Cell 4: in=2^2, out= sage: [W.get_cell_with_id(i).next_compute_id() for i in [1, 4, 3]] [4, 3, 3] """ L = self.worksheet().compute_cell_list() try: k = L.index(self) except ValueError: print("Warning -- cell %s no longer exists" % self.id()) return L[0].id() try: return L[k + 1].id() except IndexError: return self.id()
[ "def", "next_compute_id", "(", "self", ")", ":", "L", "=", "self", ".", "worksheet", "(", ")", ".", "compute_cell_list", "(", ")", "try", ":", "k", "=", "L", ".", "index", "(", "self", ")", "except", "ValueError", ":", "print", "(", "\"Warning -- cell ...
https://github.com/sagemath/sagenb/blob/67a73cbade02639bc08265f28f3165442113ad4d/sagenb/notebook/cell.py#L1201-L1234
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/cluster/_spectral.py
python
cluster_qr
(vectors)
return vectors.argmax(axis=1)
Find the discrete partition closest to the eigenvector embedding. This implementation was proposed in [1]_. .. versionadded:: 1.1 Parameters ---------- vectors : array-like, shape: (n_samples, n_clusters) The embedding space of the samples. Returns ------- labels : array of integers, shape: n_samples The cluster labels of vectors. References ---------- .. [1] `Simple, direct, and efficient multi-way spectral clustering, 2019 Anil Damle, Victor Minden, Lexing Ying <:doi:`10.1093/imaiai/iay008`>`_
Find the discrete partition closest to the eigenvector embedding.
[ "Find", "the", "discrete", "partition", "closest", "to", "the", "eigenvector", "embedding", "." ]
def cluster_qr(vectors): """Find the discrete partition closest to the eigenvector embedding. This implementation was proposed in [1]_. .. versionadded:: 1.1 Parameters ---------- vectors : array-like, shape: (n_samples, n_clusters) The embedding space of the samples. Returns ------- labels : array of integers, shape: n_samples The cluster labels of vectors. References ---------- .. [1] `Simple, direct, and efficient multi-way spectral clustering, 2019 Anil Damle, Victor Minden, Lexing Ying <:doi:`10.1093/imaiai/iay008`>`_ """ k = vectors.shape[1] _, _, piv = qr(vectors.T, pivoting=True) ut, _, v = svd(vectors[piv[:k], :].T) vectors = abs(np.dot(vectors, np.dot(ut, v.conj()))) return vectors.argmax(axis=1)
[ "def", "cluster_qr", "(", "vectors", ")", ":", "k", "=", "vectors", ".", "shape", "[", "1", "]", "_", ",", "_", ",", "piv", "=", "qr", "(", "vectors", ".", "T", ",", "pivoting", "=", "True", ")", "ut", ",", "_", ",", "v", "=", "svd", "(", "...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/cluster/_spectral.py#L27-L56
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/managers/pluginmanager.py
python
PluginInfo._fix_classname
(self, plugin_class)
Protected method to update the class name if found during plugin load. (Assumes it's always valid, so no sanitization is performed). .. warning: This method is called internally by GoLismero, do not call it yourself! :param plugin_class: Plugin class name. :type plugin_class: str
Protected method to update the class name if found during plugin load. (Assumes it's always valid, so no sanitization is performed).
[ "Protected", "method", "to", "update", "the", "class", "name", "if", "found", "during", "plugin", "load", ".", "(", "Assumes", "it", "s", "always", "valid", "so", "no", "sanitization", "is", "performed", ")", "." ]
def _fix_classname(self, plugin_class): """ Protected method to update the class name if found during plugin load. (Assumes it's always valid, so no sanitization is performed). .. warning: This method is called internally by GoLismero, do not call it yourself! :param plugin_class: Plugin class name. :type plugin_class: str """ self.__plugin_class = plugin_class
[ "def", "_fix_classname", "(", "self", ",", "plugin_class", ")", ":", "self", ".", "__plugin_class", "=", "plugin_class" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/managers/pluginmanager.py#L634-L645
colour-science/colour
38782ac059e8ddd91939f3432bf06811c16667f0
colour/utilities/array.py
python
MixinDataclassArray.__array__
(self, *args, **kwargs)
return tstack([ value if value is not None else default for value in field_values.values() ], *args, **kwargs)
Implements support for *dataclass_like* conversion to :class:`ndarray` class. A field set to *None* will be filled with `np.nan` according to the shape of the first field not set with *None*. Other Parameters ---------------- \\*args : list, optional Arguments. \\**kwargs : dict, optional Keywords arguments. Returns ------- ndarray *dataclass_like* converted to `ndarray`.
Implements support for *dataclass_like* conversion to :class:`ndarray` class.
[ "Implements", "support", "for", "*", "dataclass_like", "*", "conversion", "to", ":", "class", ":", "ndarray", "class", "." ]
def __array__(self, *args, **kwargs): """ Implements support for *dataclass_like* conversion to :class:`ndarray` class. A field set to *None* will be filled with `np.nan` according to the shape of the first field not set with *None*. Other Parameters ---------------- \\*args : list, optional Arguments. \\**kwargs : dict, optional Keywords arguments. Returns ------- ndarray *dataclass_like* converted to `ndarray`. """ field_values = { field.name: getattr(self, field.name) for field in fields(self) } default = None for field, value in field_values.items(): if value is not None: default = full(as_float_array(value).shape, np.nan) break return tstack([ value if value is not None else default for value in field_values.values() ], *args, **kwargs)
[ "def", "__array__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "field_values", "=", "{", "field", ".", "name", ":", "getattr", "(", "self", ",", "field", ".", "name", ")", "for", "field", "in", "fields", "(", "self", ")", "...
https://github.com/colour-science/colour/blob/38782ac059e8ddd91939f3432bf06811c16667f0/colour/utilities/array.py#L89-L124
microsoft/SDNet
adef46911c4ef4161938e0dcc8a2b435cd680582
Models/Bert/modeling.py
python
PreTrainedBertModel.init_bert_weights
(self, module)
Initialize the weights.
Initialize the weights.
[ "Initialize", "the", "weights", "." ]
def init_bert_weights(self, module): """ Initialize the weights. """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, BertLayerNorm): module.beta.data.normal_(mean=0.0, std=self.config.initializer_range) module.gamma.data.normal_(mean=0.0, std=self.config.initializer_range) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_()
[ "def", "init_bert_weights", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "(", "nn", ".", "Linear", ",", "nn", ".", "Embedding", ")", ")", ":", "# Slightly different from the TF version which uses truncated_normal for initialization", ...
https://github.com/microsoft/SDNet/blob/adef46911c4ef4161938e0dcc8a2b435cd680582/Models/Bert/modeling.py#L433-L444
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/irc/irc/bot.py
python
SingleServerIRCBot._connect
(self)
Establish a connection to the server at the front of the server_list.
Establish a connection to the server at the front of the server_list.
[ "Establish", "a", "connection", "to", "the", "server", "at", "the", "front", "of", "the", "server_list", "." ]
def _connect(self): """ Establish a connection to the server at the front of the server_list. """ server = self.server_list[0] try: self.connect(server.host, server.port, self._nickname, server.password, ircname=self._realname, **self.__connect_params) except irc.client.ServerConnectionError: pass
[ "def", "_connect", "(", "self", ")", ":", "server", "=", "self", ".", "server_list", "[", "0", "]", "try", ":", "self", ".", "connect", "(", "server", ".", "host", ",", "server", ".", "port", ",", "self", ".", "_nickname", ",", "server", ".", "pass...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/irc/irc/bot.py#L107-L117
scrapinghub/spidermon
f2b21e45e70796f583bbb97f39b823c31d242b17
spidermon/results/monitor.py
python
MonitorResult.addFailure
(self, test, error)
[]
def addFailure(self, test, error): super().addFailure(test, error) self.step[test].status = settings.MONITOR.STATUS.FAILURE self.step[test].error = self._exc_info_to_string(error, test) self.step[test].reason = str(error[1])
[ "def", "addFailure", "(", "self", ",", "test", ",", "error", ")", ":", "super", "(", ")", ".", "addFailure", "(", "test", ",", "error", ")", "self", ".", "step", "[", "test", "]", ".", "status", "=", "settings", ".", "MONITOR", ".", "STATUS", ".", ...
https://github.com/scrapinghub/spidermon/blob/f2b21e45e70796f583bbb97f39b823c31d242b17/spidermon/results/monitor.py#L101-L105
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/AndroBugs/tools/modified/androguard/core/bytecodes/dvm.py
python
DCode.pretty_show
(self, m_a)
Display (with a pretty print) this object :param m_a: :class:`MethodAnalysis` object
Display (with a pretty print) this object
[ "Display", "(", "with", "a", "pretty", "print", ")", "this", "object" ]
def pretty_show(self, m_a): """ Display (with a pretty print) this object :param m_a: :class:`MethodAnalysis` object """ bytecode.PrettyShow(m_a, m_a.basic_blocks.gets(), self.notes) bytecode.PrettyShowEx(m_a.exceptions.gets())
[ "def", "pretty_show", "(", "self", ",", "m_a", ")", ":", "bytecode", ".", "PrettyShow", "(", "m_a", ",", "m_a", ".", "basic_blocks", ".", "gets", "(", ")", ",", "self", ".", "notes", ")", "bytecode", ".", "PrettyShowEx", "(", "m_a", ".", "exceptions", ...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/AndroBugs/tools/modified/androguard/core/bytecodes/dvm.py#L6390-L6397
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/syntaxnet/dragnn/python/digraph_ops.py
python
LabelPotentialsFromTokens
(tokens, weights)
return labels_bxnxl
r"""Computes label potentials from tokens and weights. For each batch of token activations, computes a scalar potential for each label as the product between the activations of the source token and the |weights|. Specifically, labels[b,t,l] = \sum_{i} weights[l,i] * tokens[b,t,i] Args: tokens: [B,N,T] tensor of batched token activations. weights: [L,T] matrix of weights. B,N may be dynamic, but L,T must be static. The dtype of all arguments must be compatible. Returns: [B,N,L] tensor of label potentials as defined above, with the same dtype as the arguments.
r"""Computes label potentials from tokens and weights.
[ "r", "Computes", "label", "potentials", "from", "tokens", "and", "weights", "." ]
def LabelPotentialsFromTokens(tokens, weights): r"""Computes label potentials from tokens and weights. For each batch of token activations, computes a scalar potential for each label as the product between the activations of the source token and the |weights|. Specifically, labels[b,t,l] = \sum_{i} weights[l,i] * tokens[b,t,i] Args: tokens: [B,N,T] tensor of batched token activations. weights: [L,T] matrix of weights. B,N may be dynamic, but L,T must be static. The dtype of all arguments must be compatible. Returns: [B,N,L] tensor of label potentials as defined above, with the same dtype as the arguments. """ check.Eq(tokens.get_shape().ndims, 3, 'tokens must be rank 3') check.Eq(weights.get_shape().ndims, 2, 'weights must be a matrix') num_labels = weights.get_shape().as_list()[0] num_activations = weights.get_shape().as_list()[1] check.NotNone(num_labels, 'unknown number of labels') check.NotNone(num_activations, 'unknown activation dimension') check.Eq(tokens.get_shape().as_list()[2], num_activations, 'activation mismatch between weights and tokens') tokens_shape = tf.shape(tokens) batch_size = tokens_shape[0] num_tokens = tokens_shape[1] check.Same([tokens.dtype.base_dtype, weights.dtype.base_dtype], 'dtype mismatch') # Flatten out the batch dimension so we can use one big matmul(). tokens_bnxt = tf.reshape(tokens, [-1, num_activations]) labels_bnxl = tf.matmul(tokens_bnxt, weights, transpose_b=True) # Restore the batch dimension in the output. labels_bxnxl = tf.reshape(labels_bnxl, [batch_size, num_tokens, num_labels]) return labels_bxnxl
[ "def", "LabelPotentialsFromTokens", "(", "tokens", ",", "weights", ")", ":", "check", ".", "Eq", "(", "tokens", ".", "get_shape", "(", ")", ".", "ndims", ",", "3", ",", "'tokens must be rank 3'", ")", "check", ".", "Eq", "(", "weights", ".", "get_shape", ...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/syntaxnet/dragnn/python/digraph_ops.py#L241-L284
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/hyperelliptic_curves/invariants.py
python
igusa_clebsch_invariants
(f)
return clebsch_to_igusa(*clebsch_invariants(f))
r""" Given a sextic form `f`, return the Igusa-Clebsch invariants `I_2, I_4, I_6, I_{10}` of Igusa and Clebsch [IJ1960]_. `f` may be homogeneous in two variables or inhomogeneous in one. EXAMPLES:: sage: from sage.schemes.hyperelliptic_curves.invariants import igusa_clebsch_invariants sage: R.<x, y> = QQ[] sage: igusa_clebsch_invariants(x^6 + y^6) (-240, 1620, -119880, -46656) sage: R.<x> = QQ[] sage: igusa_clebsch_invariants(x^6 + x^5 + x^4 + x^2 + 2) (-496, 6220, -955932, -1111784) sage: magma(x^6 + 1).IgusaClebschInvariants() # optional - magma [ -240, 1620, -119880, -46656 ] sage: magma(x^6 + x^5 + x^4 + x^2 + 2).IgusaClebschInvariants() # optional - magma [ -496, 6220, -955932, -1111784 ] TESTS: Let's check a symbolic example:: sage: R.<a, b, c, d, e> = QQ[] sage: S.<x> = R[] sage: igusa_clebsch_invariants(x^5 + a*x^4 + b*x^3 + c*x^2 + d*x + e)[0] 6*b^2 - 16*a*c + 40*d sage: absolute_igusa_invariants_wamelen(GF(5)['x'](x^6 - 2*x)) Traceback (most recent call last): ... NotImplementedError: Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5
r""" Given a sextic form `f`, return the Igusa-Clebsch invariants `I_2, I_4, I_6, I_{10}` of Igusa and Clebsch [IJ1960]_.
[ "r", "Given", "a", "sextic", "form", "f", "return", "the", "Igusa", "-", "Clebsch", "invariants", "I_2", "I_4", "I_6", "I_", "{", "10", "}", "of", "Igusa", "and", "Clebsch", "[", "IJ1960", "]", "_", "." ]
def igusa_clebsch_invariants(f): r""" Given a sextic form `f`, return the Igusa-Clebsch invariants `I_2, I_4, I_6, I_{10}` of Igusa and Clebsch [IJ1960]_. `f` may be homogeneous in two variables or inhomogeneous in one. EXAMPLES:: sage: from sage.schemes.hyperelliptic_curves.invariants import igusa_clebsch_invariants sage: R.<x, y> = QQ[] sage: igusa_clebsch_invariants(x^6 + y^6) (-240, 1620, -119880, -46656) sage: R.<x> = QQ[] sage: igusa_clebsch_invariants(x^6 + x^5 + x^4 + x^2 + 2) (-496, 6220, -955932, -1111784) sage: magma(x^6 + 1).IgusaClebschInvariants() # optional - magma [ -240, 1620, -119880, -46656 ] sage: magma(x^6 + x^5 + x^4 + x^2 + 2).IgusaClebschInvariants() # optional - magma [ -496, 6220, -955932, -1111784 ] TESTS: Let's check a symbolic example:: sage: R.<a, b, c, d, e> = QQ[] sage: S.<x> = R[] sage: igusa_clebsch_invariants(x^5 + a*x^4 + b*x^3 + c*x^2 + d*x + e)[0] 6*b^2 - 16*a*c + 40*d sage: absolute_igusa_invariants_wamelen(GF(5)['x'](x^6 - 2*x)) Traceback (most recent call last): ... NotImplementedError: Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5 """ return clebsch_to_igusa(*clebsch_invariants(f))
[ "def", "igusa_clebsch_invariants", "(", "f", ")", ":", "return", "clebsch_to_igusa", "(", "*", "clebsch_invariants", "(", "f", ")", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/hyperelliptic_curves/invariants.py#L293-L329
doraemonext/wechat-python-sdk
bf6f6f3d4a5440feb73a51937059d7feddc335a0
wechat_sdk/basic.py
python
WechatBasic.get_access_token
(self)
return self.conf.get_access_token()
获取 Access Token 及 Access Token 过期日期, 仅供缓存使用, 如果希望得到原生的 Access Token 请求数据请使用 :func:`grant_token` **仅为兼容 v0.6.0 以前版本使用, 自行维护 access_token 请使用 access_token_setfunc 和 access_token_getfunc 进行操作** :return: dict 对象, key 包括 `access_token` 及 `access_token_expires_at`
获取 Access Token 及 Access Token 过期日期, 仅供缓存使用, 如果希望得到原生的 Access Token 请求数据请使用 :func:`grant_token` **仅为兼容 v0.6.0 以前版本使用, 自行维护 access_token 请使用 access_token_setfunc 和 access_token_getfunc 进行操作** :return: dict 对象, key 包括 `access_token` 及 `access_token_expires_at`
[ "获取", "Access", "Token", "及", "Access", "Token", "过期日期", "仅供缓存使用", "如果希望得到原生的", "Access", "Token", "请求数据请使用", ":", "func", ":", "grant_token", "**", "仅为兼容", "v0", ".", "6", ".", "0", "以前版本使用", "自行维护", "access_token", "请使用", "access_token_setfunc", "和", "acce...
def get_access_token(self): """ 获取 Access Token 及 Access Token 过期日期, 仅供缓存使用, 如果希望得到原生的 Access Token 请求数据请使用 :func:`grant_token` **仅为兼容 v0.6.0 以前版本使用, 自行维护 access_token 请使用 access_token_setfunc 和 access_token_getfunc 进行操作** :return: dict 对象, key 包括 `access_token` 及 `access_token_expires_at` """ return self.conf.get_access_token()
[ "def", "get_access_token", "(", "self", ")", ":", "return", "self", ".", "conf", ".", "get_access_token", "(", ")" ]
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/basic.py#L183-L189
isl-org/MiDaS
b7fbf07a5d687653ec053757152f8f87efe49b4d
midas/midas_net.py
python
MidasNet.__init__
(self, path=None, features=256, non_negative=True)
Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50
Init.
[ "Init", "." ]
def __init__(self, path=None, features=256, non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50 """ print("Loading weights: ", path) super(MidasNet, self).__init__() use_pretrained = False if path is None else True self.pretrained, self.scratch = _make_encoder(backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained) self.scratch.refinenet4 = FeatureFusionBlock(features) self.scratch.refinenet3 = FeatureFusionBlock(features) self.scratch.refinenet2 = FeatureFusionBlock(features) self.scratch.refinenet1 = FeatureFusionBlock(features) self.scratch.output_conv = nn.Sequential( nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1), Interpolate(scale_factor=2, mode="bilinear"), nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), nn.ReLU(True) if non_negative else nn.Identity(), ) if path: self.load(path)
[ "def", "__init__", "(", "self", ",", "path", "=", "None", ",", "features", "=", "256", ",", "non_negative", "=", "True", ")", ":", "print", "(", "\"Loading weights: \"", ",", "path", ")", "super", "(", "MidasNet", ",", "self", ")", ".", "__init__", "("...
https://github.com/isl-org/MiDaS/blob/b7fbf07a5d687653ec053757152f8f87efe49b4d/midas/midas_net.py#L16-L47
kedro-org/kedro
e78990c6b606a27830f0d502afa0f639c0830950
kedro/versioning/journal.py
python
JournalFileHandler.emit
(self, record: logging.LogRecord)
Overriding emit function in logging.Handler, which will output the record to the filelog based on run id. Args: record: logging record.
Overriding emit function in logging.Handler, which will output the record to the filelog based on run id.
[ "Overriding", "emit", "function", "in", "logging", ".", "Handler", "which", "will", "output", "the", "record", "to", "the", "filelog", "based", "on", "run", "id", "." ]
def emit(self, record: logging.LogRecord) -> None: """Overriding emit function in logging.Handler, which will output the record to the filelog based on run id. Args: record: logging record. """ message = json.loads(record.getMessage()) handler = self._file_handlers.setdefault( message["run_id"], self._generate_handler(message["run_id"]) ) handler.emit(record)
[ "def", "emit", "(", "self", ",", "record", ":", "logging", ".", "LogRecord", ")", "->", "None", ":", "message", "=", "json", ".", "loads", "(", "record", ".", "getMessage", "(", ")", ")", "handler", "=", "self", ".", "_file_handlers", ".", "setdefault"...
https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/kedro/versioning/journal.py#L122-L136
tianzhi0549/FCOS
0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e
fcos_core/modeling/rpn/retinanet/loss.py
python
RetinaNetLossComputation.__call__
(self, anchors, box_cls, box_regression, targets)
return retinanet_cls_loss, retinanet_regression_loss
Arguments: anchors (list[BoxList]) box_cls (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList]) Returns: retinanet_cls_loss (Tensor) retinanet_regression_loss (Tensor
Arguments: anchors (list[BoxList]) box_cls (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList])
[ "Arguments", ":", "anchors", "(", "list", "[", "BoxList", "]", ")", "box_cls", "(", "list", "[", "Tensor", "]", ")", "box_regression", "(", "list", "[", "Tensor", "]", ")", "targets", "(", "list", "[", "BoxList", "]", ")" ]
def __call__(self, anchors, box_cls, box_regression, targets): """ Arguments: anchors (list[BoxList]) box_cls (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList]) Returns: retinanet_cls_loss (Tensor) retinanet_regression_loss (Tensor """ anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in anchors] labels, regression_targets = self.prepare_targets(anchors, targets) N = len(labels) box_cls, box_regression = \ concat_box_prediction_layers(box_cls, box_regression) labels = torch.cat(labels, dim=0) regression_targets = torch.cat(regression_targets, dim=0) pos_inds = torch.nonzero(labels > 0).squeeze(1) retinanet_regression_loss = smooth_l1_loss( box_regression[pos_inds], regression_targets[pos_inds], beta=self.bbox_reg_beta, size_average=False, ) / (max(1, pos_inds.numel() * self.regress_norm)) labels = labels.int() retinanet_cls_loss = self.box_cls_loss_func( box_cls, labels ) / (pos_inds.numel() + N) return retinanet_cls_loss, retinanet_regression_loss
[ "def", "__call__", "(", "self", ",", "anchors", ",", "box_cls", ",", "box_regression", ",", "targets", ")", ":", "anchors", "=", "[", "cat_boxlist", "(", "anchors_per_image", ")", "for", "anchors_per_image", "in", "anchors", "]", "labels", ",", "regression_tar...
https://github.com/tianzhi0549/FCOS/blob/0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e/fcos_core/modeling/rpn/retinanet/loss.py#L43-L80
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/beets/art.py
python
clear
(log, lib, query)
[]
def clear(log, lib, query): items = lib.items(query) log.info(u'Clearing album art from {0} items', len(items)) for item in items: log.debug(u'Clearing art for {0}', item) item.try_write(tags={'images': None})
[ "def", "clear", "(", "log", ",", "lib", ",", "query", ")", ":", "items", "=", "lib", ".", "items", "(", "query", ")", "log", ".", "info", "(", "u'Clearing album art from {0} items'", ",", "len", "(", "items", ")", ")", "for", "item", "in", "items", "...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/beets/art.py#L217-L222
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/volvooncall/lock.py
python
VolvoLock.async_lock
(self, **kwargs)
Lock the car.
Lock the car.
[ "Lock", "the", "car", "." ]
async def async_lock(self, **kwargs): """Lock the car.""" await self.instrument.lock()
[ "async", "def", "async_lock", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "instrument", ".", "lock", "(", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/volvooncall/lock.py#L33-L35
jupyterhub/kubespawner
81e6059a1481138d27d0d3c32f403ecd21d576d8
kubespawner/spawner.py
python
KubeSpawner._start_watching_pods
(self, replace=False)
return self._start_reflector( "pods", PodReflector, omit_namespace=self.enable_user_namespaces, replace=replace, )
Start the pod reflector If replace=False and the pod reflector is already running, do nothing. If replace=True, a running pod reflector will be stopped and a new one started (for recovering from possible errors).
Start the pod reflector
[ "Start", "the", "pod", "reflector" ]
def _start_watching_pods(self, replace=False): """Start the pod reflector If replace=False and the pod reflector is already running, do nothing. If replace=True, a running pod reflector will be stopped and a new one started (for recovering from possible errors). """ pod_reflector_class = PodReflector pod_reflector_class.labels.update({"component": self.component_label}) return self._start_reflector( "pods", PodReflector, omit_namespace=self.enable_user_namespaces, replace=replace, )
[ "def", "_start_watching_pods", "(", "self", ",", "replace", "=", "False", ")", ":", "pod_reflector_class", "=", "PodReflector", "pod_reflector_class", ".", "labels", ".", "update", "(", "{", "\"component\"", ":", "self", ".", "component_label", "}", ")", "return...
https://github.com/jupyterhub/kubespawner/blob/81e6059a1481138d27d0d3c32f403ecd21d576d8/kubespawner/spawner.py#L2287-L2303
vitruvianscience/OpenDeep
e96efc449101094354b615cf15afe6d03644fc36
opendeep/models/model.py
python
Model.get_loss
(self)
return None
Helper function for defining model-specific loss functions. Normally, you would pass an instance of :class:`opendeep.optimization.loss.Loss` to the optimizer. However, sometimes models or layers have specific, fixed loss functions that need to be implemented internally. If that is the case, implement this function. Returns ------- theano_expression or tuple(list(theano_variable), theano_expression) or None The loss expression, or a tuple containing the theano variables (i.e. matrix, tensor3, etc.) used as targets when calculating loss and the theano expression representing the loss function.
Helper function for defining model-specific loss functions. Normally, you would pass an instance of :class:`opendeep.optimization.loss.Loss` to the optimizer. However, sometimes models or layers have specific, fixed loss functions that need to be implemented internally. If that is the case, implement this function.
[ "Helper", "function", "for", "defining", "model", "-", "specific", "loss", "functions", ".", "Normally", "you", "would", "pass", "an", "instance", "of", ":", "class", ":", "opendeep", ".", "optimization", ".", "loss", ".", "Loss", "to", "the", "optimizer", ...
def get_loss(self): """ Helper function for defining model-specific loss functions. Normally, you would pass an instance of :class:`opendeep.optimization.loss.Loss` to the optimizer. However, sometimes models or layers have specific, fixed loss functions that need to be implemented internally. If that is the case, implement this function. Returns ------- theano_expression or tuple(list(theano_variable), theano_expression) or None The loss expression, or a tuple containing the theano variables (i.e. matrix, tensor3, etc.) used as targets when calculating loss and the theano expression representing the loss function. """ return None
[ "def", "get_loss", "(", "self", ")", ":", "return", "None" ]
https://github.com/vitruvianscience/OpenDeep/blob/e96efc449101094354b615cf15afe6d03644fc36/opendeep/models/model.py#L477-L490
xavierd/clang_complete
293a1062274a06be61797612034bd8d87851406e
plugin/clang/cindex.py
python
TranslationUnit.get_file
(self, filename)
return File.from_name(self, filename)
Obtain a File from this translation unit.
Obtain a File from this translation unit.
[ "Obtain", "a", "File", "from", "this", "translation", "unit", "." ]
def get_file(self, filename): """Obtain a File from this translation unit.""" return File.from_name(self, filename)
[ "def", "get_file", "(", "self", ",", "filename", ")", ":", "return", "File", ".", "from_name", "(", "self", ",", "filename", ")" ]
https://github.com/xavierd/clang_complete/blob/293a1062274a06be61797612034bd8d87851406e/plugin/clang/cindex.py#L2104-L2107
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/amqp/transport.py
python
TCPTransport._setup_transport
(self)
[]
def _setup_transport(self): # Setup to _write() directly to the socket, and # do our own buffered reads. self._write = self.sock.sendall self._read_buffer = EMPTY_BUFFER self._quick_recv = self.sock.recv
[ "def", "_setup_transport", "(", "self", ")", ":", "# Setup to _write() directly to the socket, and", "# do our own buffered reads.", "self", ".", "_write", "=", "self", ".", "sock", ".", "sendall", "self", ".", "_read_buffer", "=", "EMPTY_BUFFER", "self", ".", "_quick...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/amqp/transport.py#L363-L368
eltonlaw/impyute
b76a6b4bd3da36515d5f1fa87f35d0c3f4209c83
impyute/ops/wrapper.py
python
_shape_3d
(data)
return len(np.shape(data)) == 3
True if array is 3D
True if array is 3D
[ "True", "if", "array", "is", "3D" ]
def _shape_3d(data): """ True if array is 3D""" return len(np.shape(data)) == 3
[ "def", "_shape_3d", "(", "data", ")", ":", "return", "len", "(", "np", ".", "shape", "(", "data", ")", ")", "==", "3" ]
https://github.com/eltonlaw/impyute/blob/b76a6b4bd3da36515d5f1fa87f35d0c3f4209c83/impyute/ops/wrapper.py#L153-L155
ARISE-Initiative/robosuite
a5dfaf03cd769170881a1931d8f19c8eb72f531a
robosuite/utils/mjmod.py
python
CameraModder.get_pos
(self, name)
return self.model.cam_pos[camid]
Grabs position of a specific camera Args: name (str): Name of the camera Returns: np.array: (x,y,z) position of the camera Raises: AssertionError: Invalid camera name
Grabs position of a specific camera
[ "Grabs", "position", "of", "a", "specific", "camera" ]
def get_pos(self, name): """ Grabs position of a specific camera Args: name (str): Name of the camera Returns: np.array: (x,y,z) position of the camera Raises: AssertionError: Invalid camera name """ camid = self.get_camid(name) assert camid > -1, "Unknown camera %s" % name return self.model.cam_pos[camid]
[ "def", "get_pos", "(", "self", ",", "name", ")", ":", "camid", "=", "self", ".", "get_camid", "(", "name", ")", "assert", "camid", ">", "-", "1", ",", "\"Unknown camera %s\"", "%", "name", "return", "self", ".", "model", ".", "cam_pos", "[", "camid", ...
https://github.com/ARISE-Initiative/robosuite/blob/a5dfaf03cd769170881a1931d8f19c8eb72f531a/robosuite/utils/mjmod.py#L734-L749
elfgzp/wechat_mall
b2a39bcf7b3d459e594751ed3525d71fcb27acb8
weixin/pay.py
python
WeixinPay.order_query
(self, transaction_id='', out_trade_no='')
return self.make_request(method, url, kwargs)
订单查询接口 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 :param out_trade_no: 可选,商户订单号,默认自动生成 :param transaction_id: 可选,微信订单号 和out_trade_no 二选一 :return: 返回的结果数据 ----- trade_state 订单状态 SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销(刷卡支付) USERPAYING--用户支付中 PAYERROR--支付失败(其他原因,如银行返回失败)
订单查询接口 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 :param out_trade_no: 可选,商户订单号,默认自动生成 :param transaction_id: 可选,微信订单号 和out_trade_no 二选一 :return: 返回的结果数据 ----- trade_state 订单状态 SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销(刷卡支付) USERPAYING--用户支付中 PAYERROR--支付失败(其他原因,如银行返回失败)
[ "订单查询接口", "https", ":", "//", "pay", ".", "weixin", ".", "qq", ".", "com", "/", "wiki", "/", "doc", "/", "api", "/", "jsapi", ".", "php?chapter", "=", "9_2", ":", "param", "out_trade_no", ":", "可选,商户订单号,默认自动生成", ":", "param", "transaction_id", ":", "可选...
def order_query(self, transaction_id='', out_trade_no=''): """ 订单查询接口 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 :param out_trade_no: 可选,商户订单号,默认自动生成 :param transaction_id: 可选,微信订单号 和out_trade_no 二选一 :return: 返回的结果数据 ----- trade_state 订单状态 SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销(刷卡支付) USERPAYING--用户支付中 PAYERROR--支付失败(其他原因,如银行返回失败) """ path = 'pay/orderquery' params = dict( transaction_id=transaction_id, out_trade_no=out_trade_no ) method, url, kwargs = self.prepare_request('POST', path, params) return self.make_request(method, url, kwargs)
[ "def", "order_query", "(", "self", ",", "transaction_id", "=", "''", ",", "out_trade_no", "=", "''", ")", ":", "path", "=", "'pay/orderquery'", "params", "=", "dict", "(", "transaction_id", "=", "transaction_id", ",", "out_trade_no", "=", "out_trade_no", ")", ...
https://github.com/elfgzp/wechat_mall/blob/b2a39bcf7b3d459e594751ed3525d71fcb27acb8/weixin/pay.py#L169-L192
asyml/texar-pytorch
b83d3ec17e19da08fc5f81996d02f91176e55e54
texar/torch/utils/rnn.py
python
bidirectional_dynamic_rnn
( cell_fw: RNNCellBase[State], cell_bw: RNNCellBase[State], inputs: torch.Tensor, sequence_length: Optional[Union[torch.LongTensor, List[int]]] = None, initial_state_fw: Optional[State] = None, initial_state_bw: Optional[State] = None, time_major: bool = False)
return outputs, output_states
r"""Creates a dynamic version of bidirectional recurrent neural network. Takes input and builds independent forward and backward RNNs. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: The RNN inputs. If time_major == False (default), this must be a tensor of shape: ``[batch_size, max_time, ...]``, or a nested tuple of such elements. If time_major == True, this must be a tensor of shape: ``[max_time, batch_size, ...]``, or a nested tuple of such elements. sequence_length: (optional) An int32/int64 tensor, size ``[batch_size]``, containing the actual lengths for each of the sequences in the batch. If not provided, all batch entries are assumed to be full sequences; and time reversal is applied from time ``0`` to ``max_time`` for each sequence. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape ``[batch_size, cell_fw.state_size]``. If ``cell_fw.state_size`` is a tuple, this should be a tuple of tensors having shapes ``[batch_size, s]`` for ``s`` in ``cell_fw.state_size``. initial_state_bw: (optional) Same as for ``initial_state_fw``, but using the corresponding properties of ``cell_bw``. time_major: The shape format of the ``inputs`` and ``outputs`` Tensors. If true, these ``Tensors`` must be shaped ``[max_time, batch_size, depth]``. If false, these ``Tensors`` must be shaped ``[batch_size, max_time, depth]``. Using ``time_major = True`` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. Returns: A tuple (outputs, output_states) where: outputs: A tuple (output_fw, output_bw) containing the forward and the backward rnn output ``Tensor``. If time_major == False (default), output_fw will be a ``Tensor`` shaped: ``[batch_size, max_time, cell_fw.output_size]`` and output_bw will be a ``Tensor`` shaped: ``[batch_size, max_time, cell_bw.output_size]``. If time_major == True, output_fw will be a ``Tensor`` shaped: ``[max_time, batch_size, cell_fw.output_size]`` and output_bw will be a ``Tensor`` shaped: ``[max_time, batch_size, cell_bw.output_size]``. It returns a tuple instead of a single concatenated ``Tensor``, unlike in the ``bidirectional_rnn``. If the concatenated one is preferred, the forward and backward outputs can be concatenated as ``tf.concat(outputs, 2)``. output_states: A tuple (output_state_fw, output_state_bw) containing the forward and the backward final states of bidirectional rnn.
r"""Creates a dynamic version of bidirectional recurrent neural network.
[ "r", "Creates", "a", "dynamic", "version", "of", "bidirectional", "recurrent", "neural", "network", "." ]
def bidirectional_dynamic_rnn( cell_fw: RNNCellBase[State], cell_bw: RNNCellBase[State], inputs: torch.Tensor, sequence_length: Optional[Union[torch.LongTensor, List[int]]] = None, initial_state_fw: Optional[State] = None, initial_state_bw: Optional[State] = None, time_major: bool = False) -> Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[State, State]]: r"""Creates a dynamic version of bidirectional recurrent neural network. Takes input and builds independent forward and backward RNNs. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: The RNN inputs. If time_major == False (default), this must be a tensor of shape: ``[batch_size, max_time, ...]``, or a nested tuple of such elements. If time_major == True, this must be a tensor of shape: ``[max_time, batch_size, ...]``, or a nested tuple of such elements. sequence_length: (optional) An int32/int64 tensor, size ``[batch_size]``, containing the actual lengths for each of the sequences in the batch. If not provided, all batch entries are assumed to be full sequences; and time reversal is applied from time ``0`` to ``max_time`` for each sequence. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape ``[batch_size, cell_fw.state_size]``. If ``cell_fw.state_size`` is a tuple, this should be a tuple of tensors having shapes ``[batch_size, s]`` for ``s`` in ``cell_fw.state_size``. initial_state_bw: (optional) Same as for ``initial_state_fw``, but using the corresponding properties of ``cell_bw``. time_major: The shape format of the ``inputs`` and ``outputs`` Tensors. If true, these ``Tensors`` must be shaped ``[max_time, batch_size, depth]``. If false, these ``Tensors`` must be shaped ``[batch_size, max_time, depth]``. Using ``time_major = True`` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. Returns: A tuple (outputs, output_states) where: outputs: A tuple (output_fw, output_bw) containing the forward and the backward rnn output ``Tensor``. If time_major == False (default), output_fw will be a ``Tensor`` shaped: ``[batch_size, max_time, cell_fw.output_size]`` and output_bw will be a ``Tensor`` shaped: ``[batch_size, max_time, cell_bw.output_size]``. If time_major == True, output_fw will be a ``Tensor`` shaped: ``[max_time, batch_size, cell_fw.output_size]`` and output_bw will be a ``Tensor`` shaped: ``[max_time, batch_size, cell_bw.output_size]``. It returns a tuple instead of a single concatenated ``Tensor``, unlike in the ``bidirectional_rnn``. If the concatenated one is preferred, the forward and backward outputs can be concatenated as ``tf.concat(outputs, 2)``. output_states: A tuple (output_state_fw, output_state_bw) containing the forward and the backward final states of bidirectional rnn. """ output_fw, output_state_fw = dynamic_rnn(cell=cell_fw, inputs=inputs, sequence_length=sequence_length, initial_state=initial_state_fw, time_major=time_major) if time_major: time_steps = inputs.shape[0] batch_size = inputs.shape[1] else: time_steps = inputs.shape[1] batch_size = inputs.shape[0] if sequence_length is None: sequence_length = torch.tensor([time_steps] * batch_size, dtype=torch.int32, device=inputs.device) # Backward direction inputs_reverse = reverse_sequence(inputs=inputs, seq_lengths=sequence_length, time_major=time_major) tmp, output_state_bw = dynamic_rnn(cell=cell_bw, inputs=inputs_reverse, sequence_length=sequence_length, initial_state=initial_state_bw, time_major=time_major) output_bw = reverse_sequence(inputs=tmp, seq_lengths=sequence_length, time_major=time_major) outputs = (output_fw, output_bw) output_states = (output_state_fw, output_state_bw) return outputs, output_states
[ "def", "bidirectional_dynamic_rnn", "(", "cell_fw", ":", "RNNCellBase", "[", "State", "]", ",", "cell_bw", ":", "RNNCellBase", "[", "State", "]", ",", "inputs", ":", "torch", ".", "Tensor", ",", "sequence_length", ":", "Optional", "[", "Union", "[", "torch",...
https://github.com/asyml/texar-pytorch/blob/b83d3ec17e19da08fc5f81996d02f91176e55e54/texar/torch/utils/rnn.py#L82-L189
spectralpython/spectral
e1cd919f5f66abddc219b76926450240feaaed8f
spectral/graphics/spypylab.py
python
KeyParser.mods_are
(self, *args)
return True
Return True if modifiers are exactly the ones specified.
Return True if modifiers are exactly the ones specified.
[ "Return", "True", "if", "modifiers", "are", "exactly", "the", "ones", "specified", "." ]
def mods_are(self, *args): '''Return True if modifiers are exactly the ones specified.''' for a in args: if a not in self.modifiers: return False return True
[ "def", "mods_are", "(", "self", ",", "*", "args", ")", ":", "for", "a", "in", "args", ":", "if", "a", "not", "in", "self", ".", "modifiers", ":", "return", "False", "return", "True" ]
https://github.com/spectralpython/spectral/blob/e1cd919f5f66abddc219b76926450240feaaed8f/spectral/graphics/spypylab.py#L395-L400
avrae/avrae
6ebe46a1ec3d4dfaa2f9b18fac948325f39f87de
aliasing/api/statblock.py
python
AliasSkill.prof
(self)
return self._skill.prof
The proficiency multiplier in this skill. 0 = no proficiency, 0.5 = JoAT, 1 = proficiency, 2 = expertise. :rtype: float or int
The proficiency multiplier in this skill. 0 = no proficiency, 0.5 = JoAT, 1 = proficiency, 2 = expertise.
[ "The", "proficiency", "multiplier", "in", "this", "skill", ".", "0", "=", "no", "proficiency", "0", ".", "5", "=", "JoAT", "1", "=", "proficiency", "2", "=", "expertise", "." ]
def prof(self): """ The proficiency multiplier in this skill. 0 = no proficiency, 0.5 = JoAT, 1 = proficiency, 2 = expertise. :rtype: float or int """ return self._skill.prof
[ "def", "prof", "(", "self", ")", ":", "return", "self", ".", "_skill", ".", "prof" ]
https://github.com/avrae/avrae/blob/6ebe46a1ec3d4dfaa2f9b18fac948325f39f87de/aliasing/api/statblock.py#L443-L449
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iot/v20180123/models.py
python
AssociateSubDeviceToGatewayProductResponse.__init__
(self)
r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iot/v20180123/models.py#L1212-L1217
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_internal/req/req_install.py
python
InstallRequirement.__repr__
(self)
return '<{} object: {} editable={!r}>'.format( self.__class__.__name__, str(self), self.editable)
[]
def __repr__(self): # type: () -> str return '<{} object: {} editable={!r}>'.format( self.__class__.__name__, str(self), self.editable)
[ "def", "__repr__", "(", "self", ")", ":", "# type: () -> str", "return", "'<{} object: {} editable={!r}>'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "str", "(", "self", ")", ",", "self", ".", "editable", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_internal/req/req_install.py#L234-L237
pazz/alot
52f11f089df19cf336ad0983368e880dc5364149
alot/settings/theme.py
python
Theme.__init__
(self, path)
:param path: path to theme file :type path: str :raises: :class:`~alot.settings.errors.ConfigError`
:param path: path to theme file :type path: str :raises: :class:`~alot.settings.errors.ConfigError`
[ ":", "param", "path", ":", "path", "to", "theme", "file", ":", "type", "path", ":", "str", ":", "raises", ":", ":", "class", ":", "~alot", ".", "settings", ".", "errors", ".", "ConfigError" ]
def __init__(self, path): """ :param path: path to theme file :type path: str :raises: :class:`~alot.settings.errors.ConfigError` """ self._spec = os.path.join(DEFAULTSPATH, 'theme.spec') self._config = read_config(path, self._spec, report_extra=True, checks={'align': checks.align_mode, 'widthtuple': checks.width_tuple, 'force_list': checks.force_list, 'attrtriple': checks.attr_triple}) self._colours = [1, 16, 256] # make sure every entry in 'order' lists have their own subsections threadline = self._config['search']['threadline'] for sec in self._config['search']: if sec.startswith('threadline'): tline = self._config['search'][sec] if tline['parts'] is not None: listed = set(tline['parts']) here = set(tline.sections) indefault = set(threadline.sections) diff = listed.difference(here.union(indefault)) if diff: msg = 'missing threadline parts: %s' % ', '.join(diff) raise ConfigError(msg)
[ "def", "__init__", "(", "self", ",", "path", ")", ":", "self", ".", "_spec", "=", "os", ".", "path", ".", "join", "(", "DEFAULTSPATH", ",", "'theme.spec'", ")", "self", ".", "_config", "=", "read_config", "(", "path", ",", "self", ".", "_spec", ",", ...
https://github.com/pazz/alot/blob/52f11f089df19cf336ad0983368e880dc5364149/alot/settings/theme.py#L16-L41
googleapis/google-auth-library-python
87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b
google/oauth2/id_token.py
python
verify_oauth2_token
(id_token, request, audience=None, clock_skew_in_seconds=0)
return idinfo
Verifies an ID Token issued by Google's OAuth 2.0 authorization server. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The audience that this token is intended for. This is typically your application's OAuth 2.0 client ID. If None then the audience is not verified. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` validation. Returns: Mapping[str, Any]: The decoded token. Raises: exceptions.GoogleAuthError: If the issuer is invalid. ValueError: If token verification fails
Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
[ "Verifies", "an", "ID", "Token", "issued", "by", "Google", "s", "OAuth", "2", ".", "0", "authorization", "server", "." ]
def verify_oauth2_token(id_token, request, audience=None, clock_skew_in_seconds=0): """Verifies an ID Token issued by Google's OAuth 2.0 authorization server. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The audience that this token is intended for. This is typically your application's OAuth 2.0 client ID. If None then the audience is not verified. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` validation. Returns: Mapping[str, Any]: The decoded token. Raises: exceptions.GoogleAuthError: If the issuer is invalid. ValueError: If token verification fails """ idinfo = verify_token( id_token, request, audience=audience, certs_url=_GOOGLE_OAUTH2_CERTS_URL, clock_skew_in_seconds=clock_skew_in_seconds, ) if idinfo["iss"] not in _GOOGLE_ISSUERS: raise exceptions.GoogleAuthError( "Wrong issuer. 'iss' should be one of the following: {}".format( _GOOGLE_ISSUERS ) ) return idinfo
[ "def", "verify_oauth2_token", "(", "id_token", ",", "request", ",", "audience", "=", "None", ",", "clock_skew_in_seconds", "=", "0", ")", ":", "idinfo", "=", "verify_token", "(", "id_token", ",", "request", ",", "audience", "=", "audience", ",", "certs_url", ...
https://github.com/googleapis/google-auth-library-python/blob/87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b/google/oauth2/id_token.py#L143-L178
romanz/trezor-agent
23f8ef09a5b8eda2187b6883487d7ce0d9bd0b5e
libagent/gpg/keyring.py
python
parse
(s)
return parse_term(s)
Parse full s-expr from bytes.
Parse full s-expr from bytes.
[ "Parse", "full", "s", "-", "expr", "from", "bytes", "." ]
def parse(s): """Parse full s-expr from bytes.""" if s.startswith(b'('): s = s[1:] name, s = parse_term(s) values = [name] while not s.startswith(b')'): value, s = parse(s) values.append(value) return values, s[1:] return parse_term(s)
[ "def", "parse", "(", "s", ")", ":", "if", "s", ".", "startswith", "(", "b'('", ")", ":", "s", "=", "s", "[", "1", ":", "]", "name", ",", "s", "=", "parse_term", "(", "s", ")", "values", "=", "[", "name", "]", "while", "not", "s", ".", "star...
https://github.com/romanz/trezor-agent/blob/23f8ef09a5b8eda2187b6883487d7ce0d9bd0b5e/libagent/gpg/keyring.py#L107-L118
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/platform.py
python
pathbasename
(p)
return pathsplit(p)[-1]
This is a safe version of os.path.basename(), which does not work on input without a drive. This version does.
This is a safe version of os.path.basename(), which does not work on input without a drive. This version does.
[ "This", "is", "a", "safe", "version", "of", "os", ".", "path", ".", "basename", "()", "which", "does", "not", "work", "on", "input", "without", "a", "drive", ".", "This", "version", "does", "." ]
def pathbasename(p): """This is a safe version of os.path.basename(), which does not work on input without a drive. This version does. """ return pathsplit(p)[-1]
[ "def", "pathbasename", "(", "p", ")", ":", "return", "pathsplit", "(", "p", ")", "[", "-", "1", "]" ]
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/platform.py#L240-L244
chb/indivo_server
9826c67ab17d7fc0df935db327344fb0c7d237e5
indivo/views/documents/document_delete.py
python
_document_delete
(document_id, pha=None, record=None)
return DONE
Delete a document. **ARGUMENTS:** * *document_id*: The internal identifier of the document to delete. * *pha*: If the document to delete is scoped to an app, this :py:class:`~indivo.models.apps.PHA` instance refers to the app. * *record*: If the document to delete is scoped to a record, this :py:class:`~indivo.models.records_and_documents.Record` instance refers to the record. **RETURNS:** * :http:statuscode:`200` on success. **RAISES:** * :py:exc:`django.http.Http404` if the arguments don't identify an existing document.
Delete a document.
[ "Delete", "a", "document", "." ]
def _document_delete(document_id, pha=None, record=None): """ Delete a document. **ARGUMENTS:** * *document_id*: The internal identifier of the document to delete. * *pha*: If the document to delete is scoped to an app, this :py:class:`~indivo.models.apps.PHA` instance refers to the app. * *record*: If the document to delete is scoped to a record, this :py:class:`~indivo.models.records_and_documents.Record` instance refers to the record. **RETURNS:** * :http:statuscode:`200` on success. **RAISES:** * :py:exc:`django.http.Http404` if the arguments don't identify an existing document. """ document = _get_document(record=record, pha=pha, document_id=document_id) if not document: raise Http404 document.delete() return DONE
[ "def", "_document_delete", "(", "document_id", ",", "pha", "=", "None", ",", "record", "=", "None", ")", ":", "document", "=", "_get_document", "(", "record", "=", "record", ",", "pha", "=", "pha", ",", "document_id", "=", "document_id", ")", "if", "not"...
https://github.com/chb/indivo_server/blob/9826c67ab17d7fc0df935db327344fb0c7d237e5/indivo/views/documents/document_delete.py#L38-L68
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/dynamics/plotting.py
python
showContactMap
(enm, **kwargs)
return show
Show contact map using :func:`showAtomicMatrix`. *enm* can be either a :class:`.GNM` or :class:`.Atomic` object.
Show contact map using :func:`showAtomicMatrix`. *enm* can be either a :class:`.GNM` or :class:`.Atomic` object.
[ "Show", "contact", "map", "using", ":", "func", ":", "showAtomicMatrix", ".", "*", "enm", "*", "can", "be", "either", "a", ":", "class", ":", ".", "GNM", "or", ":", "class", ":", ".", "Atomic", "object", "." ]
def showContactMap(enm, **kwargs): """Show contact map using :func:`showAtomicMatrix`. *enm* can be either a :class:`.GNM` or :class:`.Atomic` object.""" import matplotlib.pyplot as plt #if SETTINGS['auto_show']: # plt.figure() cmap = kwargs.pop('cmap', 'Greys') if isinstance(enm, GNMBase): K = enm.getKirchhoff() atoms = kwargs.pop('atoms', None) elif isinstance(enm, Atomic): gnm = GNM() gnm.buildKirchhoff(enm) K = gnm.getKirchhoff() atoms = kwargs.pop('atoms', enm) else: raise TypeError('model argument must be a GNM instance') if K is None: LOGGER.warning('kirchhoff matrix is not set') return None D = np.diag(np.diag(K) + 1.) A = -(K - D) show = showAtomicMatrix(A, atoms=atoms, cmap=cmap, **kwargs) plt.title('{0} contact map'.format(enm.getTitle())) plt.xlabel('Residue') plt.ylabel('Residue') #if SETTINGS['auto_show']: # showFigure() return show
[ "def", "showContactMap", "(", "enm", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "#if SETTINGS['auto_show']:", "# plt.figure()", "cmap", "=", "kwargs", ".", "pop", "(", "'cmap'", ",", "'Greys'", ")", "if", "isins...
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/dynamics/plotting.py#L817-L849
colour-science/colour
38782ac059e8ddd91939f3432bf06811c16667f0
colour/models/rgb/transfer_functions/filmic_pro.py
python
_log_decoding_FilmicPro6_interpolator
()
return _LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE
Returns the *FiLMiC Pro 6* log decoding curve / electro-optical transfer function interpolator and caches it if not existing. Returns ------- Extrapolator *FiLMiC Pro 6* log decoding curve / electro-optical transfer function interpolator.
Returns the *FiLMiC Pro 6* log decoding curve / electro-optical transfer function interpolator and caches it if not existing.
[ "Returns", "the", "*", "FiLMiC", "Pro", "6", "*", "log", "decoding", "curve", "/", "electro", "-", "optical", "transfer", "function", "interpolator", "and", "caches", "it", "if", "not", "existing", "." ]
def _log_decoding_FilmicPro6_interpolator(): """ Returns the *FiLMiC Pro 6* log decoding curve / electro-optical transfer function interpolator and caches it if not existing. Returns ------- Extrapolator *FiLMiC Pro 6* log decoding curve / electro-optical transfer function interpolator. """ global _LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE t = np.arange(0, 1, 0.0001) if _LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE is None: _LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE = Extrapolator( LinearInterpolator(log_encoding_FilmicPro6(t), t)) return _LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE
[ "def", "_log_decoding_FilmicPro6_interpolator", "(", ")", ":", "global", "_LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE", "t", "=", "np", ".", "arange", "(", "0", ",", "1", ",", "0.0001", ")", "if", "_LOG_DECODING_FILMICPRO_INTERPOLATOR_CACHE", "is", "None", ":", "_LOG_D...
https://github.com/colour-science/colour/blob/38782ac059e8ddd91939f3432bf06811c16667f0/colour/models/rgb/transfer_functions/filmic_pro.py#L95-L114
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/web/vhost.py
python
NameVirtualHost._getResourceForRequest
(self, request)
return self.hosts.get(host, self.default) or resource.NoResource( "host %s not in vhost map" % repr(host) )
(Internal) Get the appropriate resource for the given host.
(Internal) Get the appropriate resource for the given host.
[ "(", "Internal", ")", "Get", "the", "appropriate", "resource", "for", "the", "given", "host", "." ]
def _getResourceForRequest(self, request): """(Internal) Get the appropriate resource for the given host.""" hostHeader = request.getHeader(b"host") if hostHeader == None: return self.default or resource.NoResource() else: host = hostHeader.lower().split(b":", 1)[0] return self.hosts.get(host, self.default) or resource.NoResource( "host %s not in vhost map" % repr(host) )
[ "def", "_getResourceForRequest", "(", "self", ",", "request", ")", ":", "hostHeader", "=", "request", ".", "getHeader", "(", "b\"host\"", ")", "if", "hostHeader", "==", "None", ":", "return", "self", ".", "default", "or", "resource", ".", "NoResource", "(", ...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/web/vhost.py#L77-L86
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/stringold.py
python
rfind
(s, *args)
return _apply(s.rfind, args)
rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
rfind(s, sub [,start [,end]]) -> int
[ "rfind", "(", "s", "sub", "[", "start", "[", "end", "]]", ")", "-", ">", "int" ]
def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return _apply(s.rfind, args)
[ "def", "rfind", "(", "s", ",", "*", "args", ")", ":", "return", "_apply", "(", "s", ".", "rfind", ",", "args", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/stringold.py#L178-L188
twitter/zktraffic
82db04d9aafa13f694d4f5c7265069db42c0307c
zktraffic/zab/quorum_packet.py
python
AckEpoch.__init__
(self, timestamp, src, dst, ptype, zxid, length, epoch)
[]
def __init__(self, timestamp, src, dst, ptype, zxid, length, epoch): super(AckEpoch, self).__init__(timestamp, src, dst, ptype, zxid, length) self.epoch = epoch
[ "def", "__init__", "(", "self", ",", "timestamp", ",", "src", ",", "dst", ",", "ptype", ",", "zxid", ",", "length", ",", "epoch", ")", ":", "super", "(", "AckEpoch", ",", "self", ")", ".", "__init__", "(", "timestamp", ",", "src", ",", "dst", ",", ...
https://github.com/twitter/zktraffic/blob/82db04d9aafa13f694d4f5c7265069db42c0307c/zktraffic/zab/quorum_packet.py#L349-L351
NTMC-Community/MatchZoo
8a487ee5a574356fc91e4f48e219253dc11bcff2
matchzoo/utils/bert_utils.py
python
whitespace_tokenize
(text)
return tokens
Runs basic whitespace cleaning and splitting on a piece of text.
Runs basic whitespace cleaning and splitting on a piece of text.
[ "Runs", "basic", "whitespace", "cleaning", "and", "splitting", "on", "a", "piece", "of", "text", "." ]
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() tokens = text.split() return tokens
[ "def", "whitespace_tokenize", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "tokens", "=", "text", ".", "split", "(", ")", "return", "tokens" ]
https://github.com/NTMC-Community/MatchZoo/blob/8a487ee5a574356fc91e4f48e219253dc11bcff2/matchzoo/utils/bert_utils.py#L90-L94
oxwhirl/smac
456d133f40030e60f27bc7a85d2c5bdf96f6ad56
smac/examples/rllib/env.py
python
RLlibStarCraft2Env.reset
(self)
return return_obs
Resets the env and returns observations from ready agents. Returns: obs (dict): New observations for each ready agent.
Resets the env and returns observations from ready agents.
[ "Resets", "the", "env", "and", "returns", "observations", "from", "ready", "agents", "." ]
def reset(self): """Resets the env and returns observations from ready agents. Returns: obs (dict): New observations for each ready agent. """ obs_list, state_list = self._env.reset() return_obs = {} for i, obs in enumerate(obs_list): return_obs[i] = { "action_mask": np.array(self._env.get_avail_agent_actions(i)), "obs": obs, } self._ready_agents = list(range(len(obs_list))) return return_obs
[ "def", "reset", "(", "self", ")", ":", "obs_list", ",", "state_list", "=", "self", ".", "_env", ".", "reset", "(", ")", "return_obs", "=", "{", "}", "for", "i", ",", "obs", "in", "enumerate", "(", "obs_list", ")", ":", "return_obs", "[", "i", "]", ...
https://github.com/oxwhirl/smac/blob/456d133f40030e60f27bc7a85d2c5bdf96f6ad56/smac/examples/rllib/env.py#L44-L60
OpenAgricultureFoundation/openag-device-software
a51d2de399c0a6781ae51d0dcfaae1583d75f346
device/utilities/logger.py
python
Logger.exception
(self, message: str)
Reports standard logging exception message if in normal runtime environment. If in test environment, prepends message with logger name.
Reports standard logging exception message if in normal runtime environment. If in test environment, prepends message with logger name.
[ "Reports", "standard", "logging", "exception", "message", "if", "in", "normal", "runtime", "environment", ".", "If", "in", "test", "environment", "prepends", "message", "with", "logger", "name", "." ]
def exception(self, message: str) -> None: """ Reports standard logging exception message if in normal runtime environment. If in test environment, prepends message with logger name. """ if "pytest" in sys.modules: self.logger.exception(self.name + ": " + str(message)) else: self.logger.exception(message)
[ "def", "exception", "(", "self", ",", "message", ":", "str", ")", "->", "None", ":", "if", "\"pytest\"", "in", "sys", ".", "modules", ":", "self", ".", "logger", ".", "exception", "(", "self", ".", "name", "+", "\": \"", "+", "str", "(", "message", ...
https://github.com/OpenAgricultureFoundation/openag-device-software/blob/a51d2de399c0a6781ae51d0dcfaae1583d75f346/device/utilities/logger.py#L65-L72
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/lib-tk/tkFont.py
python
Font.actual
(self, option=None)
Return actual font attributes
Return actual font attributes
[ "Return", "actual", "font", "attributes" ]
def actual(self, option=None): "Return actual font attributes" if option: return self._call("font", "actual", self.name, "-"+option) else: return self._mkdict( self._split(self._call("font", "actual", self.name)) )
[ "def", "actual", "(", "self", ",", "option", "=", "None", ")", ":", "if", "option", ":", "return", "self", ".", "_call", "(", "\"font\"", ",", "\"actual\"", ",", "self", ".", "name", ",", "\"-\"", "+", "option", ")", "else", ":", "return", "self", ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/lib-tk/tkFont.py#L122-L129
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/utilities/parameter_file_storage.py
python
ParameterFileStore.insert_ds
(self, ds)
This will insert a new *ds* and flush the database to disk.
This will insert a new *ds* and flush the database to disk.
[ "This", "will", "insert", "a", "new", "*", "ds", "*", "and", "flush", "the", "database", "to", "disk", "." ]
def insert_ds(self, ds): """This will insert a new *ds* and flush the database to disk.""" self._records[ds._hash()] = self._adapt_ds(ds) self.flush_db()
[ "def", "insert_ds", "(", "self", ",", "ds", ")", ":", "self", ".", "_records", "[", "ds", ".", "_hash", "(", ")", "]", "=", "self", ".", "_adapt_ds", "(", "ds", ")", "self", ".", "flush_db", "(", ")" ]
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/utilities/parameter_file_storage.py#L145-L148
Ultimaker/Uranium
66da853cd9a04edd3a8a03526fac81e83c03f5aa
UM/VersionUpgrade.py
python
FormatException.__str__
(self)
return "Exception parsing " + self._file + ": " + self._message
Gives a human-readable representation of this exception. :return: A human-readable representation of this exception.
Gives a human-readable representation of this exception.
[ "Gives", "a", "human", "-", "readable", "representation", "of", "this", "exception", "." ]
def __str__(self): """Gives a human-readable representation of this exception. :return: A human-readable representation of this exception. """ return "Exception parsing " + self._file + ": " + self._message
[ "def", "__str__", "(", "self", ")", ":", "return", "\"Exception parsing \"", "+", "self", ".", "_file", "+", "\": \"", "+", "self", ".", "_message" ]
https://github.com/Ultimaker/Uranium/blob/66da853cd9a04edd3a8a03526fac81e83c03f5aa/UM/VersionUpgrade.py#L62-L68
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/dc/utils/token.py
python
DataToken.__str__
(self)
return smart_str(self._value, errors='ignore')
[]
def __str__(self): return smart_str(self._value, errors='ignore')
[ "def", "__str__", "(", "self", ")", ":", "return", "smart_str", "(", "self", ".", "_value", ",", "errors", "=", "'ignore'", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/dc/utils/token.py#L73-L74
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/_pydecimal.py
python
Decimal.logical_or
(self, other, context=None)
return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Applies an 'or' operation between self and other's digits.
Applies an 'or' operation between self and other's digits.
[ "Applies", "an", "or", "operation", "between", "self", "and", "other", "s", "digits", "." ]
def logical_or(self, other, context=None): """Applies an 'or' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
[ "def", "logical_or", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "if", "...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/_pydecimal.py#L3404-L3419
calmevtime/DCTNet
bd7c669b478e47fde230119045133d10e135de97
classification/datasets/cvtransforms.py
python
RandomPerspective.get_params
(fov_range, anglex_ranges, angley_ranges, anglez_ranges, shear_ranges, translate, scale_ranges, img_size)
return fov, anglex, angley, anglez, shear, translations, scale
Get parameters for perspective transformation Returns: sequence: params to be passed to the perspective transformation
Get parameters for perspective transformation
[ "Get", "parameters", "for", "perspective", "transformation" ]
def get_params(fov_range, anglex_ranges, angley_ranges, anglez_ranges, shear_ranges, translate, scale_ranges, img_size): """Get parameters for perspective transformation Returns: sequence: params to be passed to the perspective transformation """ fov = 90 + random.uniform(-fov_range, fov_range) anglex = random.uniform(anglex_ranges[0], anglex_ranges[1]) angley = random.uniform(angley_ranges[0], angley_ranges[1]) anglez = random.uniform(anglez_ranges[0], anglez_ranges[1]) shear = random.uniform(shear_ranges[0], shear_ranges[1]) max_dx = translate[0] * img_size[1] max_dy = translate[1] * img_size[0] translations = (np.round(random.uniform(-max_dx, max_dx)), np.round(random.uniform(-max_dy, max_dy))) scale = (random.uniform(1 / scale_ranges[0], scale_ranges[0]), random.uniform(1 / scale_ranges[1], scale_ranges[1])) return fov, anglex, angley, anglez, shear, translations, scale
[ "def", "get_params", "(", "fov_range", ",", "anglex_ranges", ",", "angley_ranges", ",", "anglez_ranges", ",", "shear_ranges", ",", "translate", ",", "scale_ranges", ",", "img_size", ")", ":", "fov", "=", "90", "+", "random", ".", "uniform", "(", "-", "fov_ra...
https://github.com/calmevtime/DCTNet/blob/bd7c669b478e47fde230119045133d10e135de97/classification/datasets/cvtransforms.py#L1200-L1221
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/legacy/image_classification/resnet/resnet_runnable.py
python
ResnetRunnable.train_step
(self, iterator)
See base class.
See base class.
[ "See", "base", "class", "." ]
def train_step(self, iterator): """See base class.""" def step_fn(inputs): """Function to run on the device.""" images, labels = inputs with tf.GradientTape() as tape: logits = self.model(images, training=True) prediction_loss = tf.keras.losses.sparse_categorical_crossentropy( labels, logits) loss = tf.reduce_sum(prediction_loss) * (1.0 / self.flags_obj.batch_size) num_replicas = self.strategy.num_replicas_in_sync l2_weight_decay = 1e-4 if self.flags_obj.single_l2_loss_op: l2_loss = l2_weight_decay * 2 * tf.add_n([ tf.nn.l2_loss(v) for v in self.model.trainable_variables if 'bn' not in v.name ]) loss += (l2_loss / num_replicas) else: loss += (tf.reduce_sum(self.model.losses) / num_replicas) grad_utils.minimize_using_explicit_allreduce( tape, self.optimizer, loss, self.model.trainable_variables) self.train_loss.update_state(loss) self.train_accuracy.update_state(labels, logits) if self.flags_obj.enable_xla: step_fn = tf.function(step_fn, jit_compile=True) self.strategy.run(step_fn, args=(next(iterator),))
[ "def", "train_step", "(", "self", ",", "iterator", ")", ":", "def", "step_fn", "(", "inputs", ")", ":", "\"\"\"Function to run on the device.\"\"\"", "images", ",", "labels", "=", "inputs", "with", "tf", ".", "GradientTape", "(", ")", "as", "tape", ":", "log...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/legacy/image_classification/resnet/resnet_runnable.py#L134-L166
KenT2/pipresents-gapless
31a347bb8b45898a3fe08b1daf765e31d47b7a87
remi/gui.py
python
TextInput.onenter
(self, new_value)
return self.eventManager.propagate(self.EVENT_ONENTER, (new_value,))
Called when the user types an ENTER into the TextInput. Note: This event can't be registered together with Widget.onkeydown. Args: new_value (str): the new string content of the TextInput.
Called when the user types an ENTER into the TextInput. Note: This event can't be registered together with Widget.onkeydown.
[ "Called", "when", "the", "user", "types", "an", "ENTER", "into", "the", "TextInput", ".", "Note", ":", "This", "event", "can", "t", "be", "registered", "together", "with", "Widget", ".", "onkeydown", "." ]
def onenter(self, new_value): """Called when the user types an ENTER into the TextInput. Note: This event can't be registered together with Widget.onkeydown. Args: new_value (str): the new string content of the TextInput. """ self.set_value(new_value) return self.eventManager.propagate(self.EVENT_ONENTER, (new_value,))
[ "def", "onenter", "(", "self", ",", "new_value", ")", ":", "self", ".", "set_value", "(", "new_value", ")", "return", "self", ".", "eventManager", ".", "propagate", "(", "self", ".", "EVENT_ONENTER", ",", "(", "new_value", ",", ")", ")" ]
https://github.com/KenT2/pipresents-gapless/blob/31a347bb8b45898a3fe08b1daf765e31d47b7a87/remi/gui.py#L1135-L1143
rkhleics/wagtailmodeladmin
7fddc853bab2ff3868b8c7a03329308c55f16358
wagtailmodeladmin/options.py
python
ModelAdmin.get_extra_attrs_for_field_col
(self, obj, field_name)
return {}
Return a dictionary of additional HTML attributes to be added to a table cell when rendering the output of `field_name` for `obj` in `index_view`. Must always return a dictionary.
Return a dictionary of additional HTML attributes to be added to a table cell when rendering the output of `field_name` for `obj` in `index_view`.
[ "Return", "a", "dictionary", "of", "additional", "HTML", "attributes", "to", "be", "added", "to", "a", "table", "cell", "when", "rendering", "the", "output", "of", "field_name", "for", "obj", "in", "index_view", "." ]
def get_extra_attrs_for_field_col(self, obj, field_name): """ Return a dictionary of additional HTML attributes to be added to a table cell when rendering the output of `field_name` for `obj` in `index_view`. Must always return a dictionary. """ return {}
[ "def", "get_extra_attrs_for_field_col", "(", "self", ",", "obj", ",", "field_name", ")", ":", "return", "{", "}" ]
https://github.com/rkhleics/wagtailmodeladmin/blob/7fddc853bab2ff3868b8c7a03329308c55f16358/wagtailmodeladmin/options.py#L286-L294
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/tarfile.py
python
TarFile.makedir
(self, tarinfo, targetpath)
Make a directory called targetpath.
Make a directory called targetpath.
[ "Make", "a", "directory", "called", "targetpath", "." ]
def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except FileExistsError: pass
[ "def", "makedir", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "try", ":", "# Use a safe mode for the directory, the real mode is set", "# later in _extract_member().", "os", ".", "mkdir", "(", "targetpath", ",", "0o700", ")", "except", "FileExistsError", ...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tarfile.py#L2136-L2144
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/phonon/dos.py
python
plot_partial_dos
( ax, frequency_points, partial_dos, indices=None, legend=None, xlabel=None, ylabel=None, draw_grid=True, flip_xy=False, )
Plot partial DOS.
Plot partial DOS.
[ "Plot", "partial", "DOS", "." ]
def plot_partial_dos( ax, frequency_points, partial_dos, indices=None, legend=None, xlabel=None, ylabel=None, draw_grid=True, flip_xy=False, ): """Plot partial DOS.""" warnings.warn( "plot_partial_dos() is deprecated. Use plot_projected_dos() instead.", DeprecationWarning, ) plot_projected_dos( ax, frequency_points, partial_dos, indices=indices, legend=legend, xlabel=xlabel, ylabel=ylabel, draw_grid=draw_grid, flip_xy=flip_xy, )
[ "def", "plot_partial_dos", "(", "ax", ",", "frequency_points", ",", "partial_dos", ",", "indices", "=", "None", ",", "legend", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "draw_grid", "=", "True", ",", "flip_xy", "=", "False...
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/phonon/dos.py#L577-L603
gleeda/memtriage
c24f4859995cccb9d88ccc0118d90693019cc1d5
volatility/volatility/renderers/html.py
python
JSONRenderer.render
(self, outfd, data)
return outfd.write(json.dumps(json_input,ensure_ascii=False))
Renderers a treegrid as columns/row items in JSON format
Renderers a treegrid as columns/row items in JSON format
[ "Renderers", "a", "treegrid", "as", "columns", "/", "row", "items", "in", "JSON", "format" ]
def render(self, outfd, data): """Renderers a treegrid as columns/row items in JSON format""" # TODO: Implement tree structure in JSON if data.max_depth() > 1: raise NotImplementedError("JSON output for trees has not yet been implemented") # TODO: Output (basic) type information in JSON json_input = {"columns": [column.name for column in data.columns], "rows": data.visit(None, self.render_row, [])} return outfd.write(json.dumps(json_input,ensure_ascii=False))
[ "def", "render", "(", "self", ",", "outfd", ",", "data", ")", ":", "# TODO: Implement tree structure in JSON", "if", "data", ".", "max_depth", "(", ")", ">", "1", ":", "raise", "NotImplementedError", "(", "\"JSON output for trees has not yet been implemented\"", ")", ...
https://github.com/gleeda/memtriage/blob/c24f4859995cccb9d88ccc0118d90693019cc1d5/volatility/volatility/renderers/html.py#L44-L51
mikedh/trimesh
6b1e05616b44e6dd708d9bc748b211656ebb27ec
trimesh/scene/scene.py
python
Scene.rezero
(self)
Move the current scene so that the AABB of the whole scene is centered at the origin. Does this by changing the base frame to a new, offset base frame.
Move the current scene so that the AABB of the whole scene is centered at the origin.
[ "Move", "the", "current", "scene", "so", "that", "the", "AABB", "of", "the", "whole", "scene", "is", "centered", "at", "the", "origin", "." ]
def rezero(self): """ Move the current scene so that the AABB of the whole scene is centered at the origin. Does this by changing the base frame to a new, offset base frame. """ if self.is_empty or np.allclose(self.centroid, 0.0): # early exit since what we want already exists return # the transformation to move the overall scene to AABB centroid matrix = np.eye(4) matrix[:3, 3] = -self.centroid # we are going to change the base frame new_base = str(self.graph.base_frame) + '_I' self.graph.update(frame_from=new_base, frame_to=self.graph.base_frame, matrix=matrix) self.graph.base_frame = new_base
[ "def", "rezero", "(", "self", ")", ":", "if", "self", ".", "is_empty", "or", "np", ".", "allclose", "(", "self", ".", "centroid", ",", "0.0", ")", ":", "# early exit since what we want already exists", "return", "# the transformation to move the overall scene to AABB ...
https://github.com/mikedh/trimesh/blob/6b1e05616b44e6dd708d9bc748b211656ebb27ec/trimesh/scene/scene.py#L725-L746
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/gui/wsgi/applications/utils.py
python
load_single_global_wato_setting
(varname: str, deflt: Any = None)
return settings.get(varname, deflt)
Load a single config option from WATO globals (Only for special use) This is a small hack to get access to the current configuration without the need to load the whole GUI config. The problem is: The profiling setting is needed before the GUI config is loaded regularly. This is needed, because we want to be able to profile our whole WSGI app, including the config loading logic. We only process the WATO written global settings file to get the WATO settings. Which should be enough for the most cases.
Load a single config option from WATO globals (Only for special use)
[ "Load", "a", "single", "config", "option", "from", "WATO", "globals", "(", "Only", "for", "special", "use", ")" ]
def load_single_global_wato_setting(varname: str, deflt: Any = None) -> Any: """Load a single config option from WATO globals (Only for special use) This is a small hack to get access to the current configuration without the need to load the whole GUI config. The problem is: The profiling setting is needed before the GUI config is loaded regularly. This is needed, because we want to be able to profile our whole WSGI app, including the config loading logic. We only process the WATO written global settings file to get the WATO settings. Which should be enough for the most cases. """ settings = cmk.utils.store.load_mk_file( cmk.utils.paths.default_config_dir + "/multisite.d/wato/global.mk", default={} ) return settings.get(varname, deflt)
[ "def", "load_single_global_wato_setting", "(", "varname", ":", "str", ",", "deflt", ":", "Any", "=", "None", ")", "->", "Any", ":", "settings", "=", "cmk", ".", "utils", ".", "store", ".", "load_mk_file", "(", "cmk", ".", "utils", ".", "paths", ".", "d...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/wsgi/applications/utils.py#L159-L175
CalebBell/fluids
dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80
fluids/core.py
python
C2K
(C)
return C + zero_Celsius
Convert Celsius to Kelvin. Parameters ---------- C : float Celsius temperature to be converted, [degC] Returns ------- K : float Equivalent Kelvin temperature, [K] Notes ----- Computes ``K = C + zero_Celsius`` where `zero_Celsius` = 273.15, i.e., (the absolute value of) temperature "absolute zero" as measured in Celsius. Examples -------- >>> C2K(-40) 233.14999999999998
Convert Celsius to Kelvin.
[ "Convert", "Celsius", "to", "Kelvin", "." ]
def C2K(C): """Convert Celsius to Kelvin. Parameters ---------- C : float Celsius temperature to be converted, [degC] Returns ------- K : float Equivalent Kelvin temperature, [K] Notes ----- Computes ``K = C + zero_Celsius`` where `zero_Celsius` = 273.15, i.e., (the absolute value of) temperature "absolute zero" as measured in Celsius. Examples -------- >>> C2K(-40) 233.14999999999998 """ return C + zero_Celsius
[ "def", "C2K", "(", "C", ")", ":", "return", "C", "+", "zero_Celsius" ]
https://github.com/CalebBell/fluids/blob/dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80/fluids/core.py#L2687-L2710
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/functions/min_max.py
python
MinMax_base.__call__
(self, *args, **kwds)
EXAMPLES:: sage: max_symbolic(3, 5, x) max(x, 5) sage: max_symbolic(3, 5, x, hold=True) max(3, 5, x) sage: max_symbolic([3, 5, x]) max(x, 5) :: sage: min_symbolic(3, 5, x) min(x, 3) sage: min_symbolic(3, 5, x, hold=True) min(3, 5, x) sage: min_symbolic([3, 5, x]) min(x, 3) TESTS: We get an exception if no arguments are given:: sage: max_symbolic() Traceback (most recent call last): ... ValueError: number of arguments must be > 0 Check if a single argument which is not iterable works:: sage: max_symbolic(None) Traceback (most recent call last): ... TypeError: 'NoneType' object is not iterable sage: max_symbolic(5) Traceback (most recent call last): ... TypeError: 'sage.rings.integer.Integer' object is not iterable sage: max_symbolic(x) Traceback (most recent call last): ... TypeError: 'sage.symbolic.expression.Expression' object is not iterable sage: min_symbolic(5) Traceback (most recent call last): ... TypeError: 'sage.rings.integer.Integer' object is not iterable sage: min_symbolic(x) Traceback (most recent call last): ... TypeError: 'sage.symbolic.expression.Expression' object is not iterable
EXAMPLES::
[ "EXAMPLES", "::" ]
def __call__(self, *args, **kwds): """ EXAMPLES:: sage: max_symbolic(3, 5, x) max(x, 5) sage: max_symbolic(3, 5, x, hold=True) max(3, 5, x) sage: max_symbolic([3, 5, x]) max(x, 5) :: sage: min_symbolic(3, 5, x) min(x, 3) sage: min_symbolic(3, 5, x, hold=True) min(3, 5, x) sage: min_symbolic([3, 5, x]) min(x, 3) TESTS: We get an exception if no arguments are given:: sage: max_symbolic() Traceback (most recent call last): ... ValueError: number of arguments must be > 0 Check if a single argument which is not iterable works:: sage: max_symbolic(None) Traceback (most recent call last): ... TypeError: 'NoneType' object is not iterable sage: max_symbolic(5) Traceback (most recent call last): ... TypeError: 'sage.rings.integer.Integer' object is not iterable sage: max_symbolic(x) Traceback (most recent call last): ... TypeError: 'sage.symbolic.expression.Expression' object is not iterable sage: min_symbolic(5) Traceback (most recent call last): ... TypeError: 'sage.rings.integer.Integer' object is not iterable sage: min_symbolic(x) Traceback (most recent call last): ... TypeError: 'sage.symbolic.expression.Expression' object is not iterable """ if len(args) == 0: raise ValueError("number of arguments must be > 0") if len(args) == 1: try: args = (SR._force_pyobject(iter(args[0])),) except TypeError: raise try: return BuiltinFunction.__call__(self, *args, **kwds) except ValueError: pass
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "raise", "ValueError", "(", "\"number of arguments must be > 0\"", ")", "if", "len", "(", "args", ")", "==", "1", ":", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/functions/min_max.py#L89-L152
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/ipaddress.py
python
IPv6Address.sixtofour
(self)
return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address.
Return the IPv4 6to4 embedded address.
[ "Return", "the", "IPv4", "6to4", "embedded", "address", "." ]
def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
[ "def", "sixtofour", "(", "self", ")", ":", "if", "(", "self", ".", "_ip", ">>", "112", ")", "!=", "0x2002", ":", "return", "None", "return", "IPv4Address", "(", "(", "self", ".", "_ip", ">>", "80", ")", "&", "0xFFFFFFFF", ")" ]
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/ipaddress.py#L2156-L2166
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/pagerank/pagerank.py
python
int_str
(string_, integer, factor)
return integer
[]
def int_str(string_, integer, factor): for i in xrange(len(string_)) : integer *= factor integer &= 0xFFFFFFFF integer += ord(string_[i]) return integer
[ "def", "int_str", "(", "string_", ",", "integer", ",", "factor", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "string_", ")", ")", ":", "integer", "*=", "factor", "integer", "&=", "0xFFFFFFFF", "integer", "+=", "ord", "(", "string_", "[", "...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/pagerank/pagerank.py#L29-L35
eggnogdb/eggnog-mapper
d6e6cdf0a829f2bd85480f3f3f16e38c213cd091
eggnogmapper/annotation/orthologs.py
python
__load_orthology
(member, orthology)
return all_orthologs
[]
def __load_orthology(member, orthology): all_orthologs = { "one2one": set(), "one2many": set(), "many2many": set(), "many2one": set(), "all": set(), } # each set contains a list of taxa.sequence items # member # e.g. 1041607.K0KSN3 # orthology # k: (species, (tuple_of_co-orthologs)) # v: set of species with orthologs: set((species1, list_orths), (species2, list_orths), ...) # e.g. of many2one relationship # { # ('1041607', ('1041607.K0KPV8', '1041607.K0KSN3')): { # ('27289', ('27289.XP_003672691.1',)), # ('4956', ('4956.XP_002498479.1',)), # ('381046', ('381046.XP_002553862.1',)), # ('28985', ('28985.XP_453001.1',)), # ('113608', ('113608.XP_003687705.1',)), # ('588726', ('588726.J7S748',)), # ('27288', ('27288.XP_003673468.1',)), # ('36033', ('36033.XP_001645185.1',)), # ('4932', ('4932.YGR015C',)), # ('5478', ('5478.XP_446354.1',)), # ('432096', ('432096.XP_003958079.1',)), # ('4950', ('4950.XP_003681095.1',)) # } # } for k, v in orthology.items(): all_orthologs['all'].update(k[1]) if len(k[1]) == 1: otype_prefix = "one2" else: otype_prefix = "many2" for t2, co2 in v: all_orthologs['all'].update(co2) if len(co2) == 1: otype = otype_prefix + "one" else: otype = otype_prefix + "many" all_orthologs[otype].update(k[1]) all_orthologs[otype].update(co2) return all_orthologs
[ "def", "__load_orthology", "(", "member", ",", "orthology", ")", ":", "all_orthologs", "=", "{", "\"one2one\"", ":", "set", "(", ")", ",", "\"one2many\"", ":", "set", "(", ")", ",", "\"many2many\"", ":", "set", "(", ")", ",", "\"many2one\"", ":", "set", ...
https://github.com/eggnogdb/eggnog-mapper/blob/d6e6cdf0a829f2bd85480f3f3f16e38c213cd091/eggnogmapper/annotation/orthologs.py#L55-L110
cea-sec/Sibyl
14866eb8ef3a65fcc4535faaf76eb42faf64d313
sibyl/learn/learn.py
python
TestCreator.create_test
(self)
return self.create_test_from_trace()
Main function of the trace that is in charge of calling other methods in the right order Return a string that correspong to the code of the test class
Main function of the trace that is in charge of calling other methods in the right order Return a string that correspong to the code of the test class
[ "Main", "function", "of", "the", "trace", "that", "is", "in", "charge", "of", "calling", "other", "methods", "in", "the", "right", "order", "Return", "a", "string", "that", "correspong", "to", "the", "code", "of", "the", "test", "class" ]
def create_test(self): """ Main function of the trace that is in charge of calling other methods in the right order Return a string that correspong to the code of the test class """ self.parse_types() self.create_trace() self.prune_snapshots() self.clean_trace() self.test_trace() assert len(self.trace) > 0 self.extract_refs() return self.create_test_from_trace()
[ "def", "create_test", "(", "self", ")", ":", "self", ".", "parse_types", "(", ")", "self", ".", "create_trace", "(", ")", "self", ".", "prune_snapshots", "(", ")", "self", ".", "clean_trace", "(", ")", "self", ".", "test_trace", "(", ")", "assert", "le...
https://github.com/cea-sec/Sibyl/blob/14866eb8ef3a65fcc4535faaf76eb42faf64d313/sibyl/learn/learn.py#L171-L191
ssokolow/quicktile
ca8105dcdd08c26de0ce6b987958c15a88489de2
quicktile/util.py
python
Rectangle.to_relative
(self, other_rect: 'Rectangle')
return self._replace(x=self.x - other_rect.x, y=self.y - other_rect.y)
Interpret self as absolute and make it relative to ``other_rect``. (eg. Convert a window position that's relative to the top-left corner of the desktop as a whole into one that's relative to a single monitor) This assumes top-left gravity. :param other_rect: The reference frame to make this rectangle's x and y coordinates relative to. :returns: A relative-coordinates version of this rectangle.
Interpret self as absolute and make it relative to ``other_rect``.
[ "Interpret", "self", "as", "absolute", "and", "make", "it", "relative", "to", "other_rect", "." ]
def to_relative(self, other_rect: 'Rectangle') -> 'Rectangle': """Interpret self as absolute and make it relative to ``other_rect``. (eg. Convert a window position that's relative to the top-left corner of the desktop as a whole into one that's relative to a single monitor) This assumes top-left gravity. :param other_rect: The reference frame to make this rectangle's x and y coordinates relative to. :returns: A relative-coordinates version of this rectangle. """ return self._replace(x=self.x - other_rect.x, y=self.y - other_rect.y)
[ "def", "to_relative", "(", "self", ",", "other_rect", ":", "'Rectangle'", ")", "->", "'Rectangle'", ":", "return", "self", ".", "_replace", "(", "x", "=", "self", ".", "x", "-", "other_rect", ".", "x", ",", "y", "=", "self", ".", "y", "-", "other_rec...
https://github.com/ssokolow/quicktile/blob/ca8105dcdd08c26de0ce6b987958c15a88489de2/quicktile/util.py#L681-L694
Pylons/webob
259230aa2b8b9cf675c996e157c5cf021c256059
src/webob/acceptparse.py
python
AcceptLanguageInvalidHeader.__str__
(self)
return "<invalid header value>"
Return the ``str`` ``'<invalid header value>'``.
Return the ``str`` ``'<invalid header value>'``.
[ "Return", "the", "str", "<invalid", "header", "value", ">", "." ]
def __str__(self): """Return the ``str`` ``'<invalid header value>'``.""" return "<invalid header value>"
[ "def", "__str__", "(", "self", ")", ":", "return", "\"<invalid header value>\"" ]
https://github.com/Pylons/webob/blob/259230aa2b8b9cf675c996e157c5cf021c256059/src/webob/acceptparse.py#L5297-L5300
lanmaster53/recon-ng
9e907dfe09fce2997f0301d746796408e01a60b7
recon/core/framework.py
python
Framework._do_script_status
(self, params)
Provides the status of command recording
Provides the status of command recording
[ "Provides", "the", "status", "of", "command", "recording" ]
def _do_script_status(self, params): '''Provides the status of command recording''' status = 'started' if Framework._record else 'stopped' self.output(f"Command recording is {status}.")
[ "def", "_do_script_status", "(", "self", ",", "params", ")", ":", "status", "=", "'started'", "if", "Framework", ".", "_record", "else", "'stopped'", "self", ".", "output", "(", "f\"Command recording is {status}.\"", ")" ]
https://github.com/lanmaster53/recon-ng/blob/9e907dfe09fce2997f0301d746796408e01a60b7/recon/core/framework.py#L1200-L1203
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
deep-learning/CapsNET/TensorFlow_Implementation/capsLayer.py
python
conv2d
(inputs, filters, vec_len, kernel_size, strides=(1, 1), with_routing=False, reuse=None)
return(layer(inputs, kernel_size=kernel_size, stride=strides))
A capsule convolutional layer.(Note: not tested yet) Args: inputs: A tensor. Returns: ... Raises: ...
A capsule convolutional layer.(Note: not tested yet) Args: inputs: A tensor. Returns: ... Raises: ...
[ "A", "capsule", "convolutional", "layer", ".", "(", "Note", ":", "not", "tested", "yet", ")", "Args", ":", "inputs", ":", "A", "tensor", ".", "Returns", ":", "...", "Raises", ":", "..." ]
def conv2d(inputs, filters, vec_len, kernel_size, strides=(1, 1), with_routing=False, reuse=None): '''A capsule convolutional layer.(Note: not tested yet) Args: inputs: A tensor. Returns: ... Raises: ... ''' layer = CapsLayer(num_outputs=filters, vec_len=vec_len, with_routing=with_routing, layer_type='CONV') return(layer(inputs, kernel_size=kernel_size, stride=strides))
[ "def", "conv2d", "(", "inputs", ",", "filters", ",", "vec_len", ",", "kernel_size", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "with_routing", "=", "False", ",", "reuse", "=", "None", ")", ":", "layer", "=", "CapsLayer", "(", "num_outputs", "...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/CapsNET/TensorFlow_Implementation/capsLayer.py#L195-L214
pytrainer/pytrainer
66f3e2b30b48c66e03111248faffc43b8e31c583
extensions/gpx2garmin/gpx2garmin.py
python
gpx2garmin.exportGPX
(self)
return subprocess.call(cmd)
export the GPX file using gpsbabel
export the GPX file using gpsbabel
[ "export", "the", "GPX", "file", "using", "gpsbabel" ]
def exportGPX(self): ' export the GPX file using gpsbabel ' cmd = ["gpsbabel", "-t", "-i", "gpx", "-f", self.tmpgpxfile, "-o", "garmin"] if self.limit is not None: cmd = cmd + ["-x", "simplify,count=%s" % self.limit] cmd = cmd + ["-F", self.device] return subprocess.call(cmd)
[ "def", "exportGPX", "(", "self", ")", ":", "cmd", "=", "[", "\"gpsbabel\"", ",", "\"-t\"", ",", "\"-i\"", ",", "\"gpx\"", ",", "\"-f\"", ",", "self", ".", "tmpgpxfile", ",", "\"-o\"", ",", "\"garmin\"", "]", "if", "self", ".", "limit", "is", "not", "...
https://github.com/pytrainer/pytrainer/blob/66f3e2b30b48c66e03111248faffc43b8e31c583/extensions/gpx2garmin/gpx2garmin.py#L26-L32
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/future/src/future/types/newstr.py
python
newstr.encode
(self, encoding='utf-8', errors='strict')
return newbytes(super(newstr, self).encode(encoding, errors))
Returns bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
Returns bytes
[ "Returns", "bytes" ]
def encode(self, encoding='utf-8', errors='strict'): """ Returns bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ from future.types.newbytes import newbytes # Py2 unicode.encode() takes encoding and errors as optional parameter, # not keyword arguments as in Python 3 str. # For the surrogateescape error handling mechanism, the # codecs.register_error() function seems to be inadequate for an # implementation of it when encoding. (Decoding seems fine, however.) # For example, in the case of # u'\udcc3'.encode('ascii', 'surrogateescape_handler') # after registering the ``surrogateescape_handler`` function in # future.utils.surrogateescape, both Python 2.x and 3.x raise an # exception anyway after the function is called because the unicode # string it has to return isn't encodable strictly as ASCII. if errors == 'surrogateescape': if encoding == 'utf-16': # Known to fail here. See test_encoding_works_normally() raise NotImplementedError('FIXME: surrogateescape handling is ' 'not yet implemented properly') # Encode char by char, building up list of byte-strings mybytes = [] for c in self: code = ord(c) if 0xD800 <= code <= 0xDCFF: mybytes.append(newbytes([code - 0xDC00])) else: mybytes.append(c.encode(encoding=encoding)) return newbytes(b'').join(mybytes) return newbytes(super(newstr, self).encode(encoding, errors))
[ "def", "encode", "(", "self", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "from", "future", ".", "types", ".", "newbytes", "import", "newbytes", "# Py2 unicode.encode() takes encoding and errors as optional parameter,", "# not keyword argu...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/future/src/future/types/newstr.py#L179-L218
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_asa.py
python
BaseASAIntfLine.__repr__
(self)
[]
def __repr__(self): if not self.is_switchport: if self.ipv4_addr_object == self.default_ipv4_addr_object: addr = "No IPv4" else: addr = self.ipv4_addr_object return "<%s # %s '%s' info: '%s'>" % ( self.classname, self.linenum, self.name, addr, ) else: return "<%s # %s '%s' info: 'switchport'>" % ( self.classname, self.linenum, self.name, )
[ "def", "__repr__", "(", "self", ")", ":", "if", "not", "self", ".", "is_switchport", ":", "if", "self", ".", "ipv4_addr_object", "==", "self", ".", "default_ipv4_addr_object", ":", "addr", "=", "\"No IPv4\"", "else", ":", "addr", "=", "self", ".", "ipv4_ad...
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_asa.py#L150-L167
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
sensorClientWeatherService/lib/client/core.py
python
Connection.recv
(self, buffsize: int, timeout: Optional[float] = 20.0)
Receives data on the connection. :param buffsize: how much data at max is received :param timeout: timeout of the receiving call
Receives data on the connection. :param buffsize: how much data at max is received :param timeout: timeout of the receiving call
[ "Receives", "data", "on", "the", "connection", ".", ":", "param", "buffsize", ":", "how", "much", "data", "at", "max", "is", "received", ":", "param", "timeout", ":", "timeout", "of", "the", "receiving", "call" ]
def recv(self, buffsize: int, timeout: Optional[float] = 20.0) -> bytes: """ Receives data on the connection. :param buffsize: how much data at max is received :param timeout: timeout of the receiving call """ raise NotImplementedError("Abstract class.")
[ "def", "recv", "(", "self", ",", "buffsize", ":", "int", ",", "timeout", ":", "Optional", "[", "float", "]", "=", "20.0", ")", "->", "bytes", ":", "raise", "NotImplementedError", "(", "\"Abstract class.\"", ")" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/sensorClientWeatherService/lib/client/core.py#L37-L45
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
py2manager/gluon/highlight.py
python
Highlighter.highlight
(self, data)
return ''.join(self.output).expandtabs(4)
Syntax highlight some python code. Returns html version of code.
Syntax highlight some python code. Returns html version of code.
[ "Syntax", "highlight", "some", "python", "code", ".", "Returns", "html", "version", "of", "code", "." ]
def highlight(self, data): """ Syntax highlight some python code. Returns html version of code. """ i = 0 mode = self.mode while i < len(data): for (token, o_re, style) in Highlighter.all_styles[mode][1]: if not token in self.suppress_tokens: match = o_re.match(data, i) if match: if style: new_mode = \ Highlighter.all_styles[mode][0](self, token, match, style % dict(link=self.link)) else: new_mode = \ Highlighter.all_styles[mode][0](self, token, match, style) if not new_mode is None: mode = new_mode i += max(1, len(match.group())) break else: self.change_style(None, None) self.output.append(data[i]) i += 1 self.change_style(None, None) return ''.join(self.output).expandtabs(4)
[ "def", "highlight", "(", "self", ",", "data", ")", ":", "i", "=", "0", "mode", "=", "self", ".", "mode", "while", "i", "<", "len", "(", "data", ")", ":", "for", "(", "token", ",", "o_re", ",", "style", ")", "in", "Highlighter", ".", "all_styles",...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/highlight.py#L201-L232
django-oscar/django-oscar-accounts
8a6dc3b42306979779f048b4d3ed0a9fd4a2f794
src/oscar_accounts/api/views.py
python
TransferRefundsView.valid_payload
(self, payload)
return self.created( reverse('oscar_accounts_api:transfer', kwargs={'reference': transfer.reference}), transfer.as_dict())
[]
def valid_payload(self, payload): to_refund = get_object_or_404(Transfer, reference=self.kwargs['reference']) amount = payload['amount'] max_refund = to_refund.max_refund() if amount > max_refund: return self.forbidden( ("Refund not permitted: maximum refund permitted " "is %.2f") % max_refund) if not to_refund.source.is_active(): raise ValidationError(errors.ACCOUNT_INACTIVE) try: transfer = facade.transfer( to_refund.destination, to_refund.source, payload['amount'], parent=to_refund, merchant_reference=payload.get('merchant_reference', None)) except exceptions.AccountException as e: return self.forbidden( code=errors.CANNOT_CREATE_TRANSFER, msg=e.message) return self.created( reverse('oscar_accounts_api:transfer', kwargs={'reference': transfer.reference}), transfer.as_dict())
[ "def", "valid_payload", "(", "self", ",", "payload", ")", ":", "to_refund", "=", "get_object_or_404", "(", "Transfer", ",", "reference", "=", "self", ".", "kwargs", "[", "'reference'", "]", ")", "amount", "=", "payload", "[", "'amount'", "]", "max_refund", ...
https://github.com/django-oscar/django-oscar-accounts/blob/8a6dc3b42306979779f048b4d3ed0a9fd4a2f794/src/oscar_accounts/api/views.py#L304-L326
explosion/thinc
95d418925b25277a92291005318710b86b2bbb41
thinc/model.py
python
Model.__truediv__
(self, other: Any)
return self._context_operators.get()["/"](self, other)
Apply the function bound to the '/' operator.
Apply the function bound to the '/' operator.
[ "Apply", "the", "function", "bound", "to", "the", "/", "operator", "." ]
def __truediv__(self, other: Any) -> "Model": """Apply the function bound to the '/' operator.""" if "/" not in self._context_operators.get(): raise TypeError("Undefined operator: /") return self._context_operators.get()["/"](self, other)
[ "def", "__truediv__", "(", "self", ",", "other", ":", "Any", ")", "->", "\"Model\"", ":", "if", "\"/\"", "not", "in", "self", ".", "_context_operators", ".", "get", "(", ")", ":", "raise", "TypeError", "(", "\"Undefined operator: /\"", ")", "return", "self...
https://github.com/explosion/thinc/blob/95d418925b25277a92291005318710b86b2bbb41/thinc/model.py#L734-L738
avatartwo/avatar2
21ba70e1aec71dc87cf948dc5f3644c96fe437c0
avatar2/avatar2.py
python
Avatar.stop
(self)
Stop the thread which manages the asynchronous messages.
Stop the thread which manages the asynchronous messages.
[ "Stop", "the", "thread", "which", "manages", "the", "asynchronous", "messages", "." ]
def stop(self): """ Stop the thread which manages the asynchronous messages. """ self._close.set() self.join()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_close", ".", "set", "(", ")", "self", ".", "join", "(", ")" ]
https://github.com/avatartwo/avatar2/blob/21ba70e1aec71dc87cf948dc5f3644c96fe437c0/avatar2/avatar2.py#L524-L529
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/combinatorics/rewritingsystem_fsm.py
python
StateMachine.add_state
(self, state_name, state_type=None, rh_rule=None)
Instantiate a state object and stores it in the 'states' dictionary. Arguments: state_name (instance of FreeGroupElement or string) -- name of the new states. state_type (string) -- Denotes the type (accept/start/dead) of the state added. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
Instantiate a state object and stores it in the 'states' dictionary.
[ "Instantiate", "a", "state", "object", "and", "stores", "it", "in", "the", "states", "dictionary", "." ]
def add_state(self, state_name, state_type=None, rh_rule=None): ''' Instantiate a state object and stores it in the 'states' dictionary. Arguments: state_name (instance of FreeGroupElement or string) -- name of the new states. state_type (string) -- Denotes the type (accept/start/dead) of the state added. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state. ''' new_state = State(state_name, self, state_type, rh_rule) self.states[state_name] = new_state
[ "def", "add_state", "(", "self", ",", "state_name", ",", "state_type", "=", "None", ",", "rh_rule", "=", "None", ")", ":", "new_state", "=", "State", "(", "state_name", ",", "self", ",", "state_type", ",", "rh_rule", ")", "self", ".", "states", "[", "s...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/rewritingsystem_fsm.py#L46-L57
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/facility/views.py
python
facility_user_signup
(request)
return _facility_user(request, new_user=True, title=title)
Anyone can sign up, unless we have set the restricted flag
Anyone can sign up, unless we have set the restricted flag
[ "Anyone", "can", "sign", "up", "unless", "we", "have", "set", "the", "restricted", "flag" ]
def facility_user_signup(request): """ Anyone can sign up, unless we have set the restricted flag """ if getattr(request, "is_logged_in", False): return HttpResponseRedirect(reverse("homepage")) if settings.DISABLE_SELF_ADMIN: # Users cannot create/edit their own data when UserRestricted raise PermissionDenied(_("Please contact a coach or administrator to receive login information to this installation.")) if settings.CENTRAL_SERVER: raise Http404(_("You may not sign up as a facility user on the central server.")) title = _("Sign up for an account") return _facility_user(request, new_user=True, title=title)
[ "def", "facility_user_signup", "(", "request", ")", ":", "if", "getattr", "(", "request", ",", "\"is_logged_in\"", ",", "False", ")", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "\"homepage\"", ")", ")", "if", "settings", ".", "DISABLE_SELF_ADMIN...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/facility/views.py#L51-L65
openstack/trove
be86b79119d16ee77f596172f43b0c97cb2617bd
trove/cluster/models.py
python
validate_volume_size
(size)
Verify the volume size is within the maximum limit for Trove volumes.
Verify the volume size is within the maximum limit for Trove volumes.
[ "Verify", "the", "volume", "size", "is", "within", "the", "maximum", "limit", "for", "Trove", "volumes", "." ]
def validate_volume_size(size): """Verify the volume size is within the maximum limit for Trove volumes.""" if size is None: raise exception.VolumeSizeNotSpecified() max_size = CONF.max_accepted_volume_size if int(size) > max_size: msg = ("Volume 'size' cannot exceed maximum " "of %d Gb, %s cannot be accepted." % (max_size, size)) raise exception.VolumeQuotaExceeded(msg)
[ "def", "validate_volume_size", "(", "size", ")", ":", "if", "size", "is", "None", ":", "raise", "exception", ".", "VolumeSizeNotSpecified", "(", ")", "max_size", "=", "CONF", ".", "max_accepted_volume_size", "if", "int", "(", "size", ")", ">", "max_size", ":...
https://github.com/openstack/trove/blob/be86b79119d16ee77f596172f43b0c97cb2617bd/trove/cluster/models.py#L646-L655
PyThaiNLP/pythainlp
de38b8507bf0934540aa5094e5f7f57d7f67e2dc
pythainlp/augment/word2vec/thai2fit.py
python
Thai2fitAug.augment
( self, sentence: str, n_sent: int = 1, p: float = 0.7 )
return self.aug.augment(sentence, n_sent, p)
Text Augment using word2vec from Thai2Fit :param str sentence: thai sentence :param int n_sent: number sentence :param float p: Probability of word :return: list of text augment :rtype: List[Tuple[str]] :Example: :: from pythainlp.augment.word2vec import Thai2fitAug aug = Thai2fitAug() aug.augment("ผมเรียน", n_sent=2, p=0.5) # output: [('พวกเรา', 'เรียน'), ('ฉัน', 'เรียน')]
Text Augment using word2vec from Thai2Fit
[ "Text", "Augment", "using", "word2vec", "from", "Thai2Fit" ]
def augment( self, sentence: str, n_sent: int = 1, p: float = 0.7 ) -> List[Tuple[str]]: """ Text Augment using word2vec from Thai2Fit :param str sentence: thai sentence :param int n_sent: number sentence :param float p: Probability of word :return: list of text augment :rtype: List[Tuple[str]] :Example: :: from pythainlp.augment.word2vec import Thai2fitAug aug = Thai2fitAug() aug.augment("ผมเรียน", n_sent=2, p=0.5) # output: [('พวกเรา', 'เรียน'), ('ฉัน', 'เรียน')] """ return self.aug.augment(sentence, n_sent, p)
[ "def", "augment", "(", "self", ",", "sentence", ":", "str", ",", "n_sent", ":", "int", "=", "1", ",", "p", ":", "float", "=", "0.7", ")", "->", "List", "[", "Tuple", "[", "str", "]", "]", ":", "return", "self", ".", "aug", ".", "augment", "(", ...
https://github.com/PyThaiNLP/pythainlp/blob/de38b8507bf0934540aa5094e5f7f57d7f67e2dc/pythainlp/augment/word2vec/thai2fit.py#L32-L57
elastic/elasticsearch-py
6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb
elasticsearch/_sync/client/security.py
python
SecurityClient.clear_cached_roles
( self, *, name: Any, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, )
return self._perform_request("POST", __target, headers=__headers)
Evicts roles from the native role cache. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :param name: Role name
Evicts roles from the native role cache.
[ "Evicts", "roles", "from", "the", "native", "role", "cache", "." ]
def clear_cached_roles( self, *, name: Any, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, ) -> ObjectApiResponse[Any]: """ Evicts roles from the native role cache. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :param name: Role name """ if name in SKIP_IN_PATH: raise ValueError("Empty value passed for parameter 'name'") __path = f"/_security/role/{_quote(name)}/_clear_cache" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if __query: __target = f"{__path}?{_quote_query(__query)}" else: __target = __path __headers = {"accept": "application/json"} return self._perform_request("POST", __target, headers=__headers)
[ "def", "clear_cached_roles", "(", "self", ",", "*", ",", "name", ":", "Any", ",", "error_trace", ":", "Optional", "[", "bool", "]", "=", "None", ",", "filter_path", ":", "Optional", "[", "Union", "[", "List", "[", "str", "]", ",", "str", "]", "]", ...
https://github.com/elastic/elasticsearch-py/blob/6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb/elasticsearch/_sync/client/security.py#L232-L265
SiCKRAGE/SiCKRAGE
45fb67c0c730fc22a34c695b5a62b11970621c53
sickrage/libs/adba/aniDBmaper.py
python
AniDBMaper._getBitChain
(self, map, wanted)
return bit
Return an hex string with the correct bit set corresponding to the wanted fields in the map
Return an hex string with the correct bit set corresponding to the wanted fields in the map
[ "Return", "an", "hex", "string", "with", "the", "correct", "bit", "set", "corresponding", "to", "the", "wanted", "fields", "in", "the", "map" ]
def _getBitChain(self, map, wanted): """Return an hex string with the correct bit set corresponding to the wanted fields in the map """ bit = 0 for index, field in enumerate(map): if field in wanted and field not in self.blacklist: bit ^= 1 << len(map) - index - 1 bit = str(hex(bit)).lstrip("0x").rstrip("L") bit = ''.join(["0" for unused in range(int(len(map) / 4) - len(bit))]) + bit return bit
[ "def", "_getBitChain", "(", "self", ",", "map", ",", "wanted", ")", ":", "bit", "=", "0", "for", "index", ",", "field", "in", "enumerate", "(", "map", ")", ":", "if", "field", "in", "wanted", "and", "field", "not", "in", "self", ".", "blacklist", "...
https://github.com/SiCKRAGE/SiCKRAGE/blob/45fb67c0c730fc22a34c695b5a62b11970621c53/sickrage/libs/adba/aniDBmaper.py#L48-L58
simpeg/simpeg
d93145d768b5512621cdd75566b4a8175fee9ed3
SimPEG/electromagnetics/natural_source/fields.py
python
Fields3DPrimarySecondary._e_px
(self, e_pxSolution, source_list)
return self._e_pxPrimary(e_pxSolution, source_list) + self._e_pxSecondary( e_pxSolution, source_list )
px polarization of electric field from source :param numpy.ndarray e_pxSolution: px polarization that was solved for :param list source_list: list of sources :rtype: numpy.ndarray :return: electric field as defined by the sources
px polarization of electric field from source
[ "px", "polarization", "of", "electric", "field", "from", "source" ]
def _e_px(self, e_pxSolution, source_list): """ px polarization of electric field from source :param numpy.ndarray e_pxSolution: px polarization that was solved for :param list source_list: list of sources :rtype: numpy.ndarray :return: electric field as defined by the sources """ return self._e_pxPrimary(e_pxSolution, source_list) + self._e_pxSecondary( e_pxSolution, source_list )
[ "def", "_e_px", "(", "self", ",", "e_pxSolution", ",", "source_list", ")", ":", "return", "self", ".", "_e_pxPrimary", "(", "e_pxSolution", ",", "source_list", ")", "+", "self", ".", "_e_pxSecondary", "(", "e_pxSolution", ",", "source_list", ")" ]
https://github.com/simpeg/simpeg/blob/d93145d768b5512621cdd75566b4a8175fee9ed3/SimPEG/electromagnetics/natural_source/fields.py#L307-L318
IntelLabs/coach
dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d
rl_coach/architectures/network_wrapper.py
python
NetworkWrapper.update_target_network
(self, rate=1.0)
Copy weights: online network >>> target network :param rate: the rate of copying the weights - 1 for copying exactly
Copy weights: online network >>> target network
[ "Copy", "weights", ":", "online", "network", ">>>", "target", "network" ]
def update_target_network(self, rate=1.0): """ Copy weights: online network >>> target network :param rate: the rate of copying the weights - 1 for copying exactly """ if self.target_network: self.target_network.set_weights(self.online_network.get_weights(), rate)
[ "def", "update_target_network", "(", "self", ",", "rate", "=", "1.0", ")", ":", "if", "self", ".", "target_network", ":", "self", ".", "target_network", ".", "set_weights", "(", "self", ".", "online_network", ".", "get_weights", "(", ")", ",", "rate", ")" ...
https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/architectures/network_wrapper.py#L109-L116
jwkvam/bowtie
220cd41367a70f2e206db846278cb7b6fd3649eb
bowtie/_component.py
python
Event.__init__
(self, name: str, uuid: int, getter: Optional[str] = None)
Create an event. Parameters ---------- name : str uuid : int getter : str, optional
Create an event.
[ "Create", "an", "event", "." ]
def __init__(self, name: str, uuid: int, getter: Optional[str] = None) -> None: """Create an event. Parameters ---------- name : str uuid : int getter : str, optional """ self.name = name self.uuid = uuid self.getter = getter
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "uuid", ":", "int", ",", "getter", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "self", ".", "name", "=", "name", "self", ".", "uuid", "=", "uuid", "self", ...
https://github.com/jwkvam/bowtie/blob/220cd41367a70f2e206db846278cb7b6fd3649eb/bowtie/_component.py#L30-L42
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/bulkloader.py
python
RestoreLoader._translate_entity_proto
(self, entity_proto)
return entity_proto
Transform the ReferenceProperties of the given entity to fix app_id.
Transform the ReferenceProperties of the given entity to fix app_id.
[ "Transform", "the", "ReferenceProperties", "of", "the", "given", "entity", "to", "fix", "app_id", "." ]
def _translate_entity_proto(self, entity_proto): """Transform the ReferenceProperties of the given entity to fix app_id.""" entity_key = entity_proto.mutable_key() entity_key.set_app(self.app_id) original_entity_namespace = entity_key.name_space() if self.namespace: entity_key.set_name_space(self.namespace) else: entity_key.clear_name_space() for prop in entity_proto.property_list(): prop_value = prop.mutable_value() if prop_value.has_referencevalue(): self.rewrite_reference_proto(original_entity_namespace, prop_value.mutable_referencevalue()) for prop in entity_proto.raw_property_list(): prop_value = prop.mutable_value() if prop_value.has_referencevalue(): self.rewrite_reference_proto(original_entity_namespace, prop_value.mutable_referencevalue()) return entity_proto
[ "def", "_translate_entity_proto", "(", "self", ",", "entity_proto", ")", ":", "entity_key", "=", "entity_proto", ".", "mutable_key", "(", ")", "entity_key", ".", "set_app", "(", "self", ".", "app_id", ")", "original_entity_namespace", "=", "entity_key", ".", "na...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/bulkloader.py#L2925-L2947
TEag1e/BurpCollector
3ab69c472c3f74828eda5f6f9ad7c7a15cf2c179
pymysql/protocol.py
python
MysqlPacket.read
(self, size)
return result
Read the first 'size' bytes in packet and advance cursor past them.
Read the first 'size' bytes in packet and advance cursor past them.
[ "Read", "the", "first", "size", "bytes", "in", "packet", "and", "advance", "cursor", "past", "them", "." ]
def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position: %s. Data Length: %s' % (size, len(result), self._position, len(self._data))) if DEBUG: print(error) self.dump() raise AssertionError(error) self._position += size return result
[ "def", "read", "(", "self", ",", "size", ")", ":", "result", "=", "self", ".", "_data", "[", "self", ".", "_position", ":", "(", "self", ".", "_position", "+", "size", ")", "]", "if", "len", "(", "result", ")", "!=", "size", ":", "error", "=", ...
https://github.com/TEag1e/BurpCollector/blob/3ab69c472c3f74828eda5f6f9ad7c7a15cf2c179/pymysql/protocol.py#L63-L75
OctoPrint/OctoPrint
4b12b0e6f06c3abfb31b1840a0605e2de8e911d2
src/octoprint/_version.py
python
git_pieces_from_lookup
(lookup, root, verbose, run_command=run_command)
Extract version information based on provided lookup data.
Extract version information based on provided lookup data.
[ "Extract", "version", "information", "based", "on", "provided", "lookup", "data", "." ]
def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): """Extract version information based on provided lookup data.""" GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed") current_branch = stdout.strip() if current_branch == "HEAD": raise NotThisMethod("not on a branch") for matcher, render, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: raise NotThisMethod("tag or ref_commit is unset for " "this branch") stdout = run_command( GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root ) if stdout is None: raise NotThisMethod( "git rev-list %s..HEAD " "--count failed" % ref_commit ) try: num_commits = int(stdout.strip()) except ValueError: raise NotThisMethod( "git rev-list %s..HEAD --count didn't " "return a valid number" % ref_commit ) stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) if stdout is None: raise NotThisMethod("git describe rev-parse " "--short HEAD failed") short_hash = stdout.strip() stdout = run_command( GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root ) if stdout is None: raise NotThisMethod("git describe --tags --dirty " "--always failed") dirty = stdout.strip().endswith("-dirty") stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: raise NotThisMethod("git rev-parse HEAD failed") full = stdout.strip() return { "long": full, "short": short_hash, "dirty": dirty, "branch": current_branch, "closest-tag": tag, "distance": num_commits, "error": None, "render": render, } raise NotThisMethod("no matching lookup definition found")
[ "def", "git_pieces_from_lookup", "(", "lookup", ",", "root", ",", "verbose", ",", "run_command", "=", "run_command", ")", ":", "GITS", "=", "[", "\"git\"", "]", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "GITS", "=", "[", "\"git.cmd\"", ",", "...
https://github.com/OctoPrint/OctoPrint/blob/4b12b0e6f06c3abfb31b1840a0605e2de8e911d2/src/octoprint/_version.py#L377-L439