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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pip/_vendor/requests/utils.py | python | add_dict_to_cookiejar | (cj, cookie_dict) | return cookiejar_from_dict(cookie_dict, cj) | Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:rtype: CookieJar | Returns a CookieJar from a key/value dictionary. | [
"Returns",
"a",
"CookieJar",
"from",
"a",
"key",
"/",
"value",
"dictionary",
"."
] | def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:rtype: CookieJar
"""
return cookiejar_from_dict(cookie_dict, cj) | [
"def",
"add_dict_to_cookiejar",
"(",
"cj",
",",
"cookie_dict",
")",
":",
"return",
"cookiejar_from_dict",
"(",
"cookie_dict",
",",
"cj",
")"
] | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/requests/utils.py#L417-L425 | |
praw-dev/praw | d1280b132f509ad115f3941fb55f13f979068377 | praw/models/reddit/subreddit.py | python | Modmail.bulk_read | (
self,
other_subreddits: Optional[List[Union["praw.models.Subreddit", str]]] = None,
state: Optional[str] = None,
) | return [
self(conversation_id) for conversation_id in response["conversation_ids"]
] | Mark conversations for subreddit(s) as read.
Due to server-side restrictions, "all" is not a valid subreddit for this method.
Instead, use :meth:`~.Modmail.subreddits` to get a list of subreddits using the
new modmail.
:param other_subreddits: A list of :class:`.Subreddit` instances for which to
mark conversations (default: ``None``).
:param state: Can be one of: ``"all"``, ``"archived"``, or ``"highlighted"``,
``"inprogress"``, ``"join_requests"``, ``"mod"``, ``"new"``,
``"notifications"``, or ``"appeals"`` (default: ``"all"``). ``"all"`` does
not include internal, archived, or appeals conversations.
:returns: A list of :class:`.ModmailConversation` instances that were marked
read.
For example, to mark all notifications for a subreddit as read:
.. code-block:: python
subreddit = reddit.subreddit("test")
subreddit.modmail.bulk_read(state="notifications") | Mark conversations for subreddit(s) as read. | [
"Mark",
"conversations",
"for",
"subreddit",
"(",
"s",
")",
"as",
"read",
"."
] | def bulk_read(
self,
other_subreddits: Optional[List[Union["praw.models.Subreddit", str]]] = None,
state: Optional[str] = None,
) -> List[ModmailConversation]:
"""Mark conversations for subreddit(s) as read.
Due to server-side restrictions, "all" is not a valid subreddit for this method.
Instead, use :meth:`~.Modmail.subreddits` to get a list of subreddits using the
new modmail.
:param other_subreddits: A list of :class:`.Subreddit` instances for which to
mark conversations (default: ``None``).
:param state: Can be one of: ``"all"``, ``"archived"``, or ``"highlighted"``,
``"inprogress"``, ``"join_requests"``, ``"mod"``, ``"new"``,
``"notifications"``, or ``"appeals"`` (default: ``"all"``). ``"all"`` does
not include internal, archived, or appeals conversations.
:returns: A list of :class:`.ModmailConversation` instances that were marked
read.
For example, to mark all notifications for a subreddit as read:
.. code-block:: python
subreddit = reddit.subreddit("test")
subreddit.modmail.bulk_read(state="notifications")
"""
params = {"entity": self._build_subreddit_list(other_subreddits)}
if state:
params["state"] = state
response = self.subreddit._reddit.post(
API_PATH["modmail_bulk_read"], params=params
)
return [
self(conversation_id) for conversation_id in response["conversation_ids"]
] | [
"def",
"bulk_read",
"(",
"self",
",",
"other_subreddits",
":",
"Optional",
"[",
"List",
"[",
"Union",
"[",
"\"praw.models.Subreddit\"",
",",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"state",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",... | https://github.com/praw-dev/praw/blob/d1280b132f509ad115f3941fb55f13f979068377/praw/models/reddit/subreddit.py#L3215-L3252 | |
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | pypy/module/signal/interp_signal.py | python | getitimer | (space, which) | getitimer(which)
Returns current value of given itimer. | getitimer(which) | [
"getitimer",
"(",
"which",
")"
] | def getitimer(space, which):
"""getitimer(which)
Returns current value of given itimer.
"""
with lltype.scoped_alloc(itimervalP.TO, 1) as old:
c_getitimer(which, old)
return itimer_retval(space, old[0]) | [
"def",
"getitimer",
"(",
"space",
",",
"which",
")",
":",
"with",
"lltype",
".",
"scoped_alloc",
"(",
"itimervalP",
".",
"TO",
",",
"1",
")",
"as",
"old",
":",
"c_getitimer",
"(",
"which",
",",
"old",
")",
"return",
"itimer_retval",
"(",
"space",
",",
... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/signal/interp_signal.py#L343-L352 | ||
NVIDIA/DeepLearningExamples | 589604d49e016cd9ef4525f7abcc9c7b826cfc5e | TensorFlow/LanguageModeling/BERT/modeling.py | python | layer_norm_and_dropout | (input_tensor, dropout_prob, name=None) | return output_tensor | Runs layer normalization followed by dropout. | Runs layer normalization followed by dropout. | [
"Runs",
"layer",
"normalization",
"followed",
"by",
"dropout",
"."
] | def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor | [
"def",
"layer_norm_and_dropout",
"(",
"input_tensor",
",",
"dropout_prob",
",",
"name",
"=",
"None",
")",
":",
"output_tensor",
"=",
"layer_norm",
"(",
"input_tensor",
",",
"name",
")",
"output_tensor",
"=",
"dropout",
"(",
"output_tensor",
",",
"dropout_prob",
... | https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/LanguageModeling/BERT/modeling.py#L386-L390 | |
robclewley/pydstool | 939e3abc9dd1f180d35152bacbde57e24c85ff26 | PyDSTool/Toolbox/ParamEst.py | python | do_2Dstep | (fun, p, dirn, maxsteps, stepsize, atol, i0, orig_res, orig_dirn,
all_records) | return record | Residual vector continuation step in 2D parameter space.
orig_dirn corresponds to direction of positive dirn, in case when
re-calculating gradient the sign flips | Residual vector continuation step in 2D parameter space. | [
"Residual",
"vector",
"continuation",
"step",
"in",
"2D",
"parameter",
"space",
"."
] | def do_2Dstep(fun, p, dirn, maxsteps, stepsize, atol, i0, orig_res, orig_dirn,
all_records):
"""
Residual vector continuation step in 2D parameter space.
orig_dirn corresponds to direction of positive dirn, in case when
re-calculating gradient the sign flips"""
record = {}
print("Recalculating gradient")
grad = fun.gradient(p)
neut = np.array([grad[1], -grad[0]])
neut = neut/norm(neut)
if np.sign(dot(neut, orig_dirn)) != 1:
print("(neut was flipped for consistency with direction)")
neut = -neut
print("Neutral direction:", neut)
record['grad'] = grad
record['neut'] = neut
residuals = []
# inner loop - assumes curvature will be low (no adaptive step size)
print("\n****** INNER LOOP")
new_pars = copy(p)
i = 0
while True:
if i > maxsteps:
break
new_pars += dirn*stepsize*neut
res = fun(new_pars)
d = abs(res-orig_res)
if res > 100 or d > atol:
# fail
break
step_ok = d < atol/2.
if step_ok:
r = (copy(new_pars), res)
residuals.append(r)
all_records[i0+dirn*i] = r
num_dirn_steps = len([k for k in all_records.keys() if \
k*dirn >= abs(i0)])
i += 1
print(len(all_records), "total steps taken, ", num_dirn_steps, \
"in since grad re-calc: pars =", new_pars, " res=", res)
else:
# re-calc gradient
break
if len(residuals) > 0:
record['p_new'] = residuals[-1][0]
record['n'] = i
record['i0_new'] = i0+dirn*i
else:
record['p_new'] = p
record['n'] = 0
record['i0_new'] = i0
return record | [
"def",
"do_2Dstep",
"(",
"fun",
",",
"p",
",",
"dirn",
",",
"maxsteps",
",",
"stepsize",
",",
"atol",
",",
"i0",
",",
"orig_res",
",",
"orig_dirn",
",",
"all_records",
")",
":",
"record",
"=",
"{",
"}",
"print",
"(",
"\"Recalculating gradient\"",
")",
... | https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/Toolbox/ParamEst.py#L88-L141 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/accounting/views.py | python | EditSoftwarePlanView.page_url | (self) | return reverse(self.urlname, args=self.args) | [] | def page_url(self):
return reverse(self.urlname, args=self.args) | [
"def",
"page_url",
"(",
"self",
")",
":",
"return",
"reverse",
"(",
"self",
".",
"urlname",
",",
"args",
"=",
"self",
".",
"args",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/accounting/views.py#L644-L645 | |||
dmlc/dgl | 8d14a739bc9e446d6c92ef83eafe5782398118de | examples/pytorch/model_zoo/geometric/coarsening.py | python | compute_perm | (parents) | return indices[::-1] | Return a list of indices to reorder the adjacency and data matrices so
that the union of two neighbors from layer to layer forms a binary tree. | Return a list of indices to reorder the adjacency and data matrices so
that the union of two neighbors from layer to layer forms a binary tree. | [
"Return",
"a",
"list",
"of",
"indices",
"to",
"reorder",
"the",
"adjacency",
"and",
"data",
"matrices",
"so",
"that",
"the",
"union",
"of",
"two",
"neighbors",
"from",
"layer",
"to",
"layer",
"forms",
"a",
"binary",
"tree",
"."
] | def compute_perm(parents):
"""
Return a list of indices to reorder the adjacency and data matrices so
that the union of two neighbors from layer to layer forms a binary tree.
"""
# Order of last layer is random (chosen by the clustering algorithm).
indices = []
if len(parents) > 0:
M_last = max(parents[-1]) + 1
indices.append(list(range(M_last)))
for parent in parents[::-1]:
# Fake nodes go after real ones.
pool_singeltons = len(parent)
indices_layer = []
for i in indices[-1]:
indices_node = list(np.where(parent == i)[0])
assert 0 <= len(indices_node) <= 2
# Add a node to go with a singelton.
if len(indices_node) == 1:
indices_node.append(pool_singeltons)
pool_singeltons += 1
# Add two nodes as children of a singelton in the parent.
elif len(indices_node) == 0:
indices_node.append(pool_singeltons + 0)
indices_node.append(pool_singeltons + 1)
pool_singeltons += 2
indices_layer.extend(indices_node)
indices.append(indices_layer)
# Sanity checks.
for i, indices_layer in enumerate(indices):
M = M_last * 2 ** i
# Reduction by 2 at each layer (binary tree).
assert len(indices[0] == M)
# The new ordering does not omit an indice.
assert sorted(indices_layer) == list(range(M))
return indices[::-1] | [
"def",
"compute_perm",
"(",
"parents",
")",
":",
"# Order of last layer is random (chosen by the clustering algorithm).",
"indices",
"=",
"[",
"]",
"if",
"len",
"(",
"parents",
")",
">",
"0",
":",
"M_last",
"=",
"max",
"(",
"parents",
"[",
"-",
"1",
"]",
")",
... | https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/model_zoo/geometric/coarsening.py#L212-L256 | |
4shadoww/hakkuframework | 409a11fc3819d251f86faa3473439f8c19066a21 | lib/rarfile.py | python | RarFile.__init__ | (self, file, mode="r", charset=None, info_callback=None,
crc_check=True, errors="stop") | Open and parse a RAR archive.
Parameters:
file
archive file name or file-like object.
mode
only "r" is supported.
charset
fallback charset to use, if filenames are not already Unicode-enabled.
info_callback
debug callback, gets to see all archive entries.
crc_check
set to False to disable CRC checks
errors
Either "stop" to quietly stop parsing on errors,
or "strict" to raise errors. Default is "stop". | Open and parse a RAR archive. | [
"Open",
"and",
"parse",
"a",
"RAR",
"archive",
"."
] | def __init__(self, file, mode="r", charset=None, info_callback=None,
crc_check=True, errors="stop"):
"""Open and parse a RAR archive.
Parameters:
file
archive file name or file-like object.
mode
only "r" is supported.
charset
fallback charset to use, if filenames are not already Unicode-enabled.
info_callback
debug callback, gets to see all archive entries.
crc_check
set to False to disable CRC checks
errors
Either "stop" to quietly stop parsing on errors,
or "strict" to raise errors. Default is "stop".
"""
if is_filelike(file):
self.filename = getattr(file, "name", None)
else:
if isinstance(file, Path):
file = str(file)
self.filename = file
self._rarfile = file
self._charset = charset or DEFAULT_CHARSET
self._info_callback = info_callback
self._crc_check = crc_check
self._password = None
self._file_parser = None
if errors == "stop":
self._strict = False
elif errors == "strict":
self._strict = True
else:
raise ValueError("Invalid value for errors= parameter.")
if mode != "r":
raise NotImplementedError("RarFile supports only mode=r")
self._parse() | [
"def",
"__init__",
"(",
"self",
",",
"file",
",",
"mode",
"=",
"\"r\"",
",",
"charset",
"=",
"None",
",",
"info_callback",
"=",
"None",
",",
"crc_check",
"=",
"True",
",",
"errors",
"=",
"\"stop\"",
")",
":",
"if",
"is_filelike",
"(",
"file",
")",
":... | https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/rarfile.py#L645-L689 | ||
mnemosyne-proj/mnemosyne | e39e364e56343437f2e485e0b06ca714de2f2d2e | mnemosyne/libmnemosyne/scheduler.py | python | Scheduler.last_rep_to_interval_string | (self, last_rep, now=None) | Converts next_rep to a string like 'yesterday', '2 weeks ago', ... | Converts next_rep to a string like 'yesterday', '2 weeks ago', ... | [
"Converts",
"next_rep",
"to",
"a",
"string",
"like",
"yesterday",
"2",
"weeks",
"ago",
"..."
] | def last_rep_to_interval_string(self, last_rep, now=None):
"""Converts next_rep to a string like 'yesterday', '2 weeks ago', ...
"""
if now is None:
now = time.time()
# To perform the calculation, we need to 'snap' the two timestamps
# to midnight UTC before calculating the interval.
now = self.midnight_UTC(\
now - self.config()["day_starts_at"] * HOUR)
last_rep = self.midnight_UTC(\
last_rep - self.config()["day_starts_at"] * HOUR)
interval_days = (last_rep - now) / DAY
if interval_days > -1:
return _("today")
elif interval_days > -2:
return _("yesterday")
elif interval_days > -31:
return str(int(-interval_days)) + " " + _("days ago")
elif interval_days > -62:
return _("1 month ago")
elif interval_days > -365:
interval_months = int(-interval_days/31.)
return str(interval_months) + " " + _("months ago")
else:
interval_years = -interval_days/365.
return "%.1f " % interval_years + _("years ago") | [
"def",
"last_rep_to_interval_string",
"(",
"self",
",",
"last_rep",
",",
"now",
"=",
"None",
")",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# To perform the calculation, we need to 'snap' the two timestamps",
"# to midnight UTC... | https://github.com/mnemosyne-proj/mnemosyne/blob/e39e364e56343437f2e485e0b06ca714de2f2d2e/mnemosyne/libmnemosyne/scheduler.py#L234-L262 | ||
mikecrittenden/zen-coding-gedit | 49966219b1e9b7a1d0d8b4def6a32b6c386b8041 | zencoding/plugin.py | python | ZenCodingPlugin.merge_lines | (self, action) | [] | def merge_lines(self, action):
self.editor.merge_lines(self.window) | [
"def",
"merge_lines",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"editor",
".",
"merge_lines",
"(",
"self",
".",
"window",
")"
] | https://github.com/mikecrittenden/zen-coding-gedit/blob/49966219b1e9b7a1d0d8b4def6a32b6c386b8041/zencoding/plugin.py#L104-L105 | ||||
wordnik/wordnik-python | fd487d016852ce33cc651b94a1f5c5231f9be7a9 | wordnik/WordApi.py | python | WordApi.getScrabbleScore | (self, word, **kwargs) | return responseObject | Returns the Scrabble score for a word
Args:
word, str: Word to get scrabble score for. (required)
Returns: ScrabbleScoreResult | Returns the Scrabble score for a word | [
"Returns",
"the",
"Scrabble",
"score",
"for",
"a",
"word"
] | def getScrabbleScore(self, word, **kwargs):
"""Returns the Scrabble score for a word
Args:
word, str: Word to get scrabble score for. (required)
Returns: ScrabbleScoreResult
"""
allParams = ['word']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method getScrabbleScore" % key)
params[key] = val
del params['kwargs']
resourcePath = '/word.{format}/{word}/scrabbleScore'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('word' in params):
replacement = str(self.apiClient.toPathValue(params['word']))
resourcePath = resourcePath.replace('{' + 'word' + '}',
replacement)
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'ScrabbleScoreResult')
return responseObject | [
"def",
"getScrabbleScore",
"(",
"self",
",",
"word",
",",
"*",
"*",
"kwargs",
")",
":",
"allParams",
"=",
"[",
"'word'",
"]",
"params",
"=",
"locals",
"(",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"params",
"[",
"'kwargs'",
"]",
".",
"iterite... | https://github.com/wordnik/wordnik-python/blob/fd487d016852ce33cc651b94a1f5c5231f9be7a9/wordnik/WordApi.py#L579-L617 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/views/home.py | python | home | (request) | return render(request, "wagtailadmin/home.html", {
'root_page': root_page,
'root_site': root_site,
'site_name': real_site_name if real_site_name else settings.WAGTAIL_SITE_NAME,
'panels': sorted(panels, key=lambda p: p.order),
'user': request.user
}) | [] | def home(request):
panels = [
SiteSummaryPanel(request),
UpgradeNotificationPanel(request),
PagesForModerationPanel(request),
RecentEditsPanel(request),
]
for fn in hooks.get_hooks('construct_homepage_panels'):
fn(request, panels)
root_page = get_explorable_root_page(request.user)
if root_page:
root_site = root_page.get_site()
else:
root_site = None
real_site_name = None
if root_site:
real_site_name = root_site.site_name if root_site.site_name else root_site.hostname
return render(request, "wagtailadmin/home.html", {
'root_page': root_page,
'root_site': root_site,
'site_name': real_site_name if real_site_name else settings.WAGTAIL_SITE_NAME,
'panels': sorted(panels, key=lambda p: p.order),
'user': request.user
}) | [
"def",
"home",
"(",
"request",
")",
":",
"panels",
"=",
"[",
"SiteSummaryPanel",
"(",
"request",
")",
",",
"UpgradeNotificationPanel",
"(",
"request",
")",
",",
"PagesForModerationPanel",
"(",
"request",
")",
",",
"RecentEditsPanel",
"(",
"request",
")",
",",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/views/home.py#L93-L121 | |||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v2beta2_horizontal_pod_autoscaler_condition.py | python | V2beta2HorizontalPodAutoscalerCondition.reason | (self) | return self._reason | Gets the reason of this V2beta2HorizontalPodAutoscalerCondition. # noqa: E501
reason is the reason for the condition's last transition. # noqa: E501
:return: The reason of this V2beta2HorizontalPodAutoscalerCondition. # noqa: E501
:rtype: str | Gets the reason of this V2beta2HorizontalPodAutoscalerCondition. # noqa: E501 | [
"Gets",
"the",
"reason",
"of",
"this",
"V2beta2HorizontalPodAutoscalerCondition",
".",
"#",
"noqa",
":",
"E501"
] | def reason(self):
"""Gets the reason of this V2beta2HorizontalPodAutoscalerCondition. # noqa: E501
reason is the reason for the condition's last transition. # noqa: E501
:return: The reason of this V2beta2HorizontalPodAutoscalerCondition. # noqa: E501
:rtype: str
"""
return self._reason | [
"def",
"reason",
"(",
"self",
")",
":",
"return",
"self",
".",
"_reason"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v2beta2_horizontal_pod_autoscaler_condition.py#L120-L128 | |
lektor/lektor-archive | d2ab208c756b1e7092b2056108571719abd8d6cd | lektor/project.py | python | Project.make_env | (self, load_plugins=True) | return Environment(self, load_plugins=load_plugins) | Create a new environment for this project. | Create a new environment for this project. | [
"Create",
"a",
"new",
"environment",
"for",
"this",
"project",
"."
] | def make_env(self, load_plugins=True):
"""Create a new environment for this project."""
from lektor.environment import Environment
return Environment(self, load_plugins=load_plugins) | [
"def",
"make_env",
"(",
"self",
",",
"load_plugins",
"=",
"True",
")",
":",
"from",
"lektor",
".",
"environment",
"import",
"Environment",
"return",
"Environment",
"(",
"self",
",",
"load_plugins",
"=",
"load_plugins",
")"
] | https://github.com/lektor/lektor-archive/blob/d2ab208c756b1e7092b2056108571719abd8d6cd/lektor/project.py#L116-L119 | |
AIChallenger/AI_Challenger_2017 | 52014e0defbbdd85bf94ab05d308300d5764022f | Baselines/caption_baseline/im2txt/im2txt/inference_utils/caption_generator.py | python | CaptionGenerator.__init__ | (self,
model,
vocab,
beam_size=3,
max_caption_length=20,
length_normalization_factor=0.0) | Initializes the generator.
Args:
model: Object encapsulating a trained image-to-text model. Must have
methods feed_image() and inference_step(). For example, an instance of
InferenceWrapperBase.
vocab: A Vocabulary object.
beam_size: Beam size to use when generating captions.
max_caption_length: The maximum caption length before stopping the search.
length_normalization_factor: If != 0, a number x such that captions are
scored by logprob/length^x, rather than logprob. This changes the
relative scores of captions depending on their lengths. For example, if
x > 0 then longer captions will be favored. | Initializes the generator. | [
"Initializes",
"the",
"generator",
"."
] | def __init__(self,
model,
vocab,
beam_size=3,
max_caption_length=20,
length_normalization_factor=0.0):
"""Initializes the generator.
Args:
model: Object encapsulating a trained image-to-text model. Must have
methods feed_image() and inference_step(). For example, an instance of
InferenceWrapperBase.
vocab: A Vocabulary object.
beam_size: Beam size to use when generating captions.
max_caption_length: The maximum caption length before stopping the search.
length_normalization_factor: If != 0, a number x such that captions are
scored by logprob/length^x, rather than logprob. This changes the
relative scores of captions depending on their lengths. For example, if
x > 0 then longer captions will be favored.
"""
self.vocab = vocab
self.model = model
self.beam_size = beam_size
self.max_caption_length = max_caption_length
self.length_normalization_factor = length_normalization_factor | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"vocab",
",",
"beam_size",
"=",
"3",
",",
"max_caption_length",
"=",
"20",
",",
"length_normalization_factor",
"=",
"0.0",
")",
":",
"self",
".",
"vocab",
"=",
"vocab",
"self",
".",
"model",
"=",
"model"... | https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/caption_baseline/im2txt/im2txt/inference_utils/caption_generator.py#L114-L139 | ||
yulequan/UA-MT | 88ed29ad794f877122e542a7fa9505a76fa83515 | code/utils/losses.py | python | symmetric_mse_loss | (input1, input2) | return torch.mean((input1 - input2)**2) | Like F.mse_loss but sends gradients to both directions
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to both input1 and input2. | Like F.mse_loss but sends gradients to both directions | [
"Like",
"F",
".",
"mse_loss",
"but",
"sends",
"gradients",
"to",
"both",
"directions"
] | def symmetric_mse_loss(input1, input2):
"""Like F.mse_loss but sends gradients to both directions
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to both input1 and input2.
"""
assert input1.size() == input2.size()
return torch.mean((input1 - input2)**2) | [
"def",
"symmetric_mse_loss",
"(",
"input1",
",",
"input2",
")",
":",
"assert",
"input1",
".",
"size",
"(",
")",
"==",
"input2",
".",
"size",
"(",
")",
"return",
"torch",
".",
"mean",
"(",
"(",
"input1",
"-",
"input2",
")",
"**",
"2",
")"
] | https://github.com/yulequan/UA-MT/blob/88ed29ad794f877122e542a7fa9505a76fa83515/code/utils/losses.py#L88-L97 | |
microsoft/debugpy | be8dd607f6837244e0b565345e497aff7a0c08bf | src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py | python | ThreadingMixIn.process_request | (self, request, client_address) | Start a new thread to process the request. | Start a new thread to process the request. | [
"Start",
"a",
"new",
"thread",
"to",
"process",
"the",
"request",
"."
] | def process_request(self, request, client_address):
"""Start a new thread to process the request."""
t = threading.Thread(target = self.process_request_thread, # @UndefinedVariable
args = (request, client_address))
t.daemon = self.daemon_threads
t.start() | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"process_request_thread",
",",
"# @UndefinedVariable",
"args",
"=",
"(",
"request",
",",
"client_addr... | https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py#L588-L593 | ||
ShuangLI59/person_search | ef7d77a58a581825611e575010d9a3653b1ddf98 | lib/datasets/imdb.py | python | imdb.image_index | (self) | return self._image_index | [] | def image_index(self):
return self._image_index | [
"def",
"image_index",
"(",
"self",
")",
":",
"return",
"self",
".",
"_image_index"
] | https://github.com/ShuangLI59/person_search/blob/ef7d77a58a581825611e575010d9a3653b1ddf98/lib/datasets/imdb.py#L44-L45 | |||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v8/services/services/batch_job_service/client.py | python | BatchJobServiceClient.parse_batch_job_path | (path: str) | return m.groupdict() if m else {} | Parse a batch_job path into its component segments. | Parse a batch_job path into its component segments. | [
"Parse",
"a",
"batch_job",
"path",
"into",
"its",
"component",
"segments",
"."
] | def parse_batch_job_path(path: str) -> Dict[str, str]:
"""Parse a batch_job path into its component segments."""
m = re.match(
r"^customers/(?P<customer_id>.+?)/batchJobs/(?P<batch_job_id>.+?)$",
path,
)
return m.groupdict() if m else {} | [
"def",
"parse_batch_job_path",
"(",
"path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"^customers/(?P<customer_id>.+?)/batchJobs/(?P<batch_job_id>.+?)$\"",
",",
"path",
",",
")",
"return",
"m",
".",
... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/batch_job_service/client.py#L436-L442 | |
savio-code/fern-wifi-cracker | 0da03aba988c66dfa131a45824568abb84b7704a | Fern-Wifi-Cracker/core/toolbox/fern_cookie_hijacker.py | python | Fern_Cookie_Hijacker.kill_MITM_process | (self) | [] | def kill_MITM_process(self):
os.system("kill " + str(self.mitm_pid)) | [
"def",
"kill_MITM_process",
"(",
"self",
")",
":",
"os",
".",
"system",
"(",
"\"kill \"",
"+",
"str",
"(",
"self",
".",
"mitm_pid",
")",
")"
] | https://github.com/savio-code/fern-wifi-cracker/blob/0da03aba988c66dfa131a45824568abb84b7704a/Fern-Wifi-Cracker/core/toolbox/fern_cookie_hijacker.py#L649-L650 | ||||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/events_v1_event_list.py | python | EventsV1EventList.kind | (self, kind) | Sets the kind of this EventsV1EventList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this EventsV1EventList. # noqa: E501
:type: str | Sets the kind of this EventsV1EventList. | [
"Sets",
"the",
"kind",
"of",
"this",
"EventsV1EventList",
"."
] | def kind(self, kind):
"""Sets the kind of this EventsV1EventList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this EventsV1EventList. # noqa: E501
:type: str
"""
self._kind = kind | [
"def",
"kind",
"(",
"self",
",",
"kind",
")",
":",
"self",
".",
"_kind",
"=",
"kind"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/events_v1_event_list.py#L129-L138 | ||
MDAnalysis/mdanalysis | 3488df3cdb0c29ed41c4fb94efe334b541e31b21 | package/MDAnalysis/coordinates/base.py | python | Timestep.__getitem__ | (self, atoms) | Get a selection of coordinates
``ts[i]``
return coordinates for the i'th atom (0-based)
``ts[start:stop:skip]``
return an array of coordinates, where start, stop and skip
correspond to atom indices,
:attr:`MDAnalysis.core.groups.Atom.index` (0-based) | Get a selection of coordinates | [
"Get",
"a",
"selection",
"of",
"coordinates"
] | def __getitem__(self, atoms):
"""Get a selection of coordinates
``ts[i]``
return coordinates for the i'th atom (0-based)
``ts[start:stop:skip]``
return an array of coordinates, where start, stop and skip
correspond to atom indices,
:attr:`MDAnalysis.core.groups.Atom.index` (0-based)
"""
if isinstance(atoms, numbers.Integral):
return self._pos[atoms]
elif isinstance(atoms, (slice, np.ndarray)):
return self._pos[atoms]
else:
raise TypeError | [
"def",
"__getitem__",
"(",
"self",
",",
"atoms",
")",
":",
"if",
"isinstance",
"(",
"atoms",
",",
"numbers",
".",
"Integral",
")",
":",
"return",
"self",
".",
"_pos",
"[",
"atoms",
"]",
"elif",
"isinstance",
"(",
"atoms",
",",
"(",
"slice",
",",
"np"... | https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/coordinates/base.py#L456-L474 | ||
exaile/exaile | a7b58996c5c15b3aa7b9975ac13ee8f784ef4689 | plugins/ipconsole/ipython_view.py | python | IPythonView._processLine | (self) | Process current command line. | Process current command line. | [
"Process",
"current",
"command",
"line",
"."
] | def _processLine(self):
"""
Process current command line.
"""
self.history_pos = 0
self.execute()
returnvalue = self.cout.getvalue()
if returnvalue:
returnvalue = returnvalue.strip('\n')
self.showReturned(returnvalue)
self.cout.truncate(0)
self.cout.seek(0) | [
"def",
"_processLine",
"(",
"self",
")",
":",
"self",
".",
"history_pos",
"=",
"0",
"self",
".",
"execute",
"(",
")",
"returnvalue",
"=",
"self",
".",
"cout",
".",
"getvalue",
"(",
")",
"if",
"returnvalue",
":",
"returnvalue",
"=",
"returnvalue",
".",
... | https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/plugins/ipconsole/ipython_view.py#L707-L718 | ||
Ha0Tang/SelectionGAN | 80aa7ad9f79f643c28633c40c621f208f3fb0121 | selectiongan_v2/models/selectiongan_model.py | python | SelectionGANModel.initialize | (self, opt) | [] | def initialize(self, opt):
BaseModel.initialize(self, opt)
self.isTrain = opt.isTrain
# specify the training losses you want to print out. The program will call base_model.get_current_losses
self.loss_names = ['D_G', 'L1','G','D_real','D_fake', 'D_D']
# specify the images you want to save/display. The program will call base_model.get_current_visuals
if self.opt.saveDisk:
self.visual_names = ['real_A', 'fake_B', 'real_B','fake_D','real_D', 'A', 'I']
else:
self.visual_names = ['I1','I2','I3','I4','I5','I6','I7','I8','I9','I10','A1','A2','A3','A4','A5','A6','A7','A8','A9','A10',
'O1','O2', 'O3', 'O4', 'O5', 'O6', 'O7', 'O8', 'O9', 'O10',
'real_A', 'fake_B', 'real_B','fake_D','real_D', 'A', 'I']
# specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks
if self.isTrain:
self.model_names = ['Gi','Gs','Ga','D']
else:
self.model_names = ['Gi','Gs','Ga']
# load/define networks
self.netGi = networks.define_G(6, 3, opt.ngf,
opt.which_model_netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
self.netGs = networks.define_G(3, 3, 4,
opt.which_model_netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
# 10: the number of attention maps
self.netGa = networks.define_Ga(110, 10, opt.ngaf,
opt.which_model_netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
if self.isTrain:
use_sigmoid = opt.no_lsgan
self.netD = networks.define_D(6, opt.ndf,
opt.which_model_netD,
opt.n_layers_D, opt.norm, use_sigmoid, opt.init_type, opt.init_gain, self.gpu_ids)
if self.isTrain:
self.fake_AB_pool = ImagePool(opt.pool_size)
self.fake_DB_pool = ImagePool(opt.pool_size)
self.fake_D_pool = ImagePool(opt.pool_size)
# define loss functions
self.criterionGAN = networks.GANLoss(use_lsgan=not opt.no_lsgan).to(self.device)
self.criterionL1 = torch.nn.L1Loss()
# initialize optimizers
self.optimizers = []
self.optimizer_G = torch.optim.Adam(itertools.chain(self.netGi.parameters(), self.netGs.parameters(), self.netGa.parameters()),
lr=opt.lr, betas=(opt.beta1, 0.999))
self.optimizer_D = torch.optim.Adam(self.netD.parameters(),
lr=opt.lr, betas=(opt.beta1, 0.999))
self.optimizers.append(self.optimizer_G)
self.optimizers.append(self.optimizer_D) | [
"def",
"initialize",
"(",
"self",
",",
"opt",
")",
":",
"BaseModel",
".",
"initialize",
"(",
"self",
",",
"opt",
")",
"self",
".",
"isTrain",
"=",
"opt",
".",
"isTrain",
"# specify the training losses you want to print out. The program will call base_model.get_current_l... | https://github.com/Ha0Tang/SelectionGAN/blob/80aa7ad9f79f643c28633c40c621f208f3fb0121/selectiongan_v2/models/selectiongan_model.py#L22-L73 | ||||
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/rcsetup.py | python | validate_string_or_None | (s) | convert s to string or raise | convert s to string or raise | [
"convert",
"s",
"to",
"string",
"or",
"raise"
] | def validate_string_or_None(s):
"""convert s to string or raise"""
if s is None:
return None
try:
return validate_string(s)
except ValueError:
raise ValueError('Could not convert "%s" to string' % s) | [
"def",
"validate_string_or_None",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"try",
":",
"return",
"validate_string",
"(",
"s",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Could not convert \"%s\" to string'",
"%",
... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/rcsetup.py#L168-L175 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/turtle.py | python | TPen.fillcolor | (self, *args) | Return or set the fillcolor.
Arguments:
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- fillcolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- fillcolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- fillcolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
Example (for a Turtle instance named turtle):
>>> turtle.fillcolor('violet')
>>> col = turtle.pencolor()
>>> turtle.fillcolor(col)
>>> turtle.fillcolor(0, .5, 0) | Return or set the fillcolor. | [
"Return",
"or",
"set",
"the",
"fillcolor",
"."
] | def fillcolor(self, *args):
""" Return or set the fillcolor.
Arguments:
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- fillcolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- fillcolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- fillcolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
Example (for a Turtle instance named turtle):
>>> turtle.fillcolor('violet')
>>> col = turtle.pencolor()
>>> turtle.fillcolor(col)
>>> turtle.fillcolor(0, .5, 0)
"""
if args:
color = self._colorstr(args)
if color == self._fillcolor:
return
self.pen(fillcolor=color)
else:
return self._color(self._fillcolor) | [
"def",
"fillcolor",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"color",
"=",
"self",
".",
"_colorstr",
"(",
"args",
")",
"if",
"color",
"==",
"self",
".",
"_fillcolor",
":",
"return",
"self",
".",
"pen",
"(",
"fillcolor",
"=",
"col... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/turtle.py#L2259-L2293 | ||
googleapis/python-dialogflow | e48ea001b7c8a4a5c1fe4b162bad49ea397458e9 | google/cloud/dialogflow_v2/services/environments/client.py | python | EnvironmentsClient.__init__ | (
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, EnvironmentsTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) | Instantiates the environments client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, EnvironmentsTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason. | Instantiates the environments client. | [
"Instantiates",
"the",
"environments",
"client",
"."
] | def __init__(
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, EnvironmentsTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the environments client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, EnvironmentsTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
"true",
"false",
):
raise ValueError(
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
)
use_client_cert = (
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
)
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
if is_mtls:
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, EnvironmentsTransport):
# transport is a EnvironmentsTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, provide its scopes "
"directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=True,
) | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"credentials",
":",
"Optional",
"[",
"ga_credentials",
".",
"Credentials",
"]",
"=",
"None",
",",
"transport",
":",
"Union",
"[",
"str",
",",
"EnvironmentsTransport",
",",
"None",
"]",
"=",
"None",
",",
"cli... | https://github.com/googleapis/python-dialogflow/blob/e48ea001b7c8a4a5c1fe4b162bad49ea397458e9/google/cloud/dialogflow_v2/services/environments/client.py#L264-L386 | ||
10XGenomics/cellranger | a83c753ce641db6409a59ad817328354fbe7187e | lib/python/cellranger/matrix.py | python | CountMatrix.merge | (self, other) | Merge this matrix with another CountMatrix | Merge this matrix with another CountMatrix | [
"Merge",
"this",
"matrix",
"with",
"another",
"CountMatrix"
] | def merge(self, other):
'''Merge this matrix with another CountMatrix'''
assert self.features_dim == other.features_dim
self.m += other.m | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"assert",
"self",
".",
"features_dim",
"==",
"other",
".",
"features_dim",
"self",
".",
"m",
"+=",
"other",
".",
"m"
] | https://github.com/10XGenomics/cellranger/blob/a83c753ce641db6409a59ad817328354fbe7187e/lib/python/cellranger/matrix.py#L402-L405 | ||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/account_budget_proposal_service/transports/grpc.py | python | AccountBudgetProposalServiceGrpcTransport.mutate_account_budget_proposal | (
self,
) | return self._stubs["mutate_account_budget_proposal"] | r"""Return a callable for the mutate account budget proposal method over gRPC.
Creates, updates, or removes account budget proposals. Operation
statuses are returned.
List of thrown errors: `AccountBudgetProposalError <>`__
`AuthenticationError <>`__ `AuthorizationError <>`__
`DatabaseError <>`__ `DateError <>`__ `FieldError <>`__
`FieldMaskError <>`__ `HeaderError <>`__ `InternalError <>`__
`MutateError <>`__ `QuotaError <>`__ `RequestError <>`__
`StringLengthError <>`__
Returns:
Callable[[~.MutateAccountBudgetProposalRequest],
~.MutateAccountBudgetProposalResponse]:
A function that, when called, will call the underlying RPC
on the server. | r"""Return a callable for the mutate account budget proposal method over gRPC. | [
"r",
"Return",
"a",
"callable",
"for",
"the",
"mutate",
"account",
"budget",
"proposal",
"method",
"over",
"gRPC",
"."
] | def mutate_account_budget_proposal(
self,
) -> Callable[
[account_budget_proposal_service.MutateAccountBudgetProposalRequest],
account_budget_proposal_service.MutateAccountBudgetProposalResponse,
]:
r"""Return a callable for the mutate account budget proposal method over gRPC.
Creates, updates, or removes account budget proposals. Operation
statuses are returned.
List of thrown errors: `AccountBudgetProposalError <>`__
`AuthenticationError <>`__ `AuthorizationError <>`__
`DatabaseError <>`__ `DateError <>`__ `FieldError <>`__
`FieldMaskError <>`__ `HeaderError <>`__ `InternalError <>`__
`MutateError <>`__ `QuotaError <>`__ `RequestError <>`__
`StringLengthError <>`__
Returns:
Callable[[~.MutateAccountBudgetProposalRequest],
~.MutateAccountBudgetProposalResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "mutate_account_budget_proposal" not in self._stubs:
self._stubs[
"mutate_account_budget_proposal"
] = self.grpc_channel.unary_unary(
"/google.ads.googleads.v9.services.AccountBudgetProposalService/MutateAccountBudgetProposal",
request_serializer=account_budget_proposal_service.MutateAccountBudgetProposalRequest.serialize,
response_deserializer=account_budget_proposal_service.MutateAccountBudgetProposalResponse.deserialize,
)
return self._stubs["mutate_account_budget_proposal"] | [
"def",
"mutate_account_budget_proposal",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"account_budget_proposal_service",
".",
"MutateAccountBudgetProposalRequest",
"]",
",",
"account_budget_proposal_service",
".",
"MutateAccountBudgetProposalResponse",
",",
"]",
":",
... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/account_budget_proposal_service/transports/grpc.py#L267-L303 | |
dakrauth/django-swingtime | e32fba3f8eecfc291201b21776b9f130e152c1c3 | swingtime/views.py | python | _datetime_view | (
request,
template,
dt,
timeslot_factory=None,
items=None,
params=None
) | return render(request, template, {
'day': dt,
'next_day': dt + timedelta(days=+1),
'prev_day': dt + timedelta(days=-1),
'timeslots': timeslot_factory(dt, items, **params)
}) | Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
Context parameters:
``day``
the specified datetime value (dt)
``next_day``
day + 1 day
``prev_day``
day - 1 day
``timeslots``
time slot grid of (time, cells) rows | Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params. | [
"Build",
"a",
"time",
"slot",
"grid",
"representation",
"for",
"the",
"given",
"datetime",
"dt",
".",
"See",
"utils",
".",
"create_timeslot_table",
"documentation",
"for",
"items",
"and",
"params",
"."
] | def _datetime_view(
request,
template,
dt,
timeslot_factory=None,
items=None,
params=None
):
'''
Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
Context parameters:
``day``
the specified datetime value (dt)
``next_day``
day + 1 day
``prev_day``
day - 1 day
``timeslots``
time slot grid of (time, cells) rows
'''
timeslot_factory = timeslot_factory or utils.create_timeslot_table
params = params or {}
return render(request, template, {
'day': dt,
'next_day': dt + timedelta(days=+1),
'prev_day': dt + timedelta(days=-1),
'timeslots': timeslot_factory(dt, items, **params)
}) | [
"def",
"_datetime_view",
"(",
"request",
",",
"template",
",",
"dt",
",",
"timeslot_factory",
"=",
"None",
",",
"items",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"timeslot_factory",
"=",
"timeslot_factory",
"or",
"utils",
".",
"create_timeslot_table"... | https://github.com/dakrauth/django-swingtime/blob/e32fba3f8eecfc291201b21776b9f130e152c1c3/swingtime/views.py#L171-L206 | |
sunnyxiaohu/R-C3D.pytorch | e8731af7b95f1dc934f6604f9c09e3c4ead74db5 | lib/tf_model_zoo/models/slim/nets/resnet_v2.py | python | resnet_v2_101 | (inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
reuse=None,
scope='resnet_v2_101') | return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, reuse=reuse, scope=scope) | ResNet-101 model of [1]. See resnet_v2() for arg and return description. | ResNet-101 model of [1]. See resnet_v2() for arg and return description. | [
"ResNet",
"-",
"101",
"model",
"of",
"[",
"1",
"]",
".",
"See",
"resnet_v2",
"()",
"for",
"arg",
"and",
"return",
"description",
"."
] | def resnet_v2_101(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
reuse=None,
scope='resnet_v2_101'):
"""ResNet-101 model of [1]. See resnet_v2() for arg and return description."""
blocks = [
resnet_utils.Block(
'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),
resnet_utils.Block(
'block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]),
resnet_utils.Block(
'block3', bottleneck, [(1024, 256, 1)] * 22 + [(1024, 256, 2)]),
resnet_utils.Block(
'block4', bottleneck, [(2048, 512, 1)] * 3)]
return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, reuse=reuse, scope=scope) | [
"def",
"resnet_v2_101",
"(",
"inputs",
",",
"num_classes",
"=",
"None",
",",
"is_training",
"=",
"True",
",",
"global_pool",
"=",
"True",
",",
"output_stride",
"=",
"None",
",",
"reuse",
"=",
"None",
",",
"scope",
"=",
"'resnet_v2_101'",
")",
":",
"blocks"... | https://github.com/sunnyxiaohu/R-C3D.pytorch/blob/e8731af7b95f1dc934f6604f9c09e3c4ead74db5/lib/tf_model_zoo/models/slim/nets/resnet_v2.py#L239-L258 | |
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | tinfo_t.__eq__ | (self, *args) | return _idaapi.tinfo_t___eq__(self, *args) | __eq__(self, r) -> bool | __eq__(self, r) -> bool | [
"__eq__",
"(",
"self",
"r",
")",
"-",
">",
"bool"
] | def __eq__(self, *args):
"""
__eq__(self, r) -> bool
"""
return _idaapi.tinfo_t___eq__(self, *args) | [
"def",
"__eq__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"tinfo_t___eq__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L31006-L31010 | |
skylander86/lambda-text-extractor | 6da52d077a2fc571e38bfe29c33ae68f6443cd5a | lib-linux_x64/aiohttp/client_reqrep.py | python | ClientRequest.write_bytes | (self, writer, conn) | Support coroutines that yields bytes objects. | Support coroutines that yields bytes objects. | [
"Support",
"coroutines",
"that",
"yields",
"bytes",
"objects",
"."
] | def write_bytes(self, writer, conn):
"""Support coroutines that yields bytes objects."""
# 100 response
if self._continue is not None:
yield from writer.drain()
yield from self._continue
try:
if isinstance(self.body, payload.Payload):
yield from self.body.write(writer)
else:
if isinstance(self.body, (bytes, bytearray)):
self.body = (self.body,)
for chunk in self.body:
writer.write(chunk)
yield from writer.write_eof()
except OSError as exc:
new_exc = ClientOSError(
exc.errno,
'Can not write request body for %s' % self.url)
new_exc.__context__ = exc
new_exc.__cause__ = exc
conn.protocol.set_exception(new_exc)
except asyncio.CancelledError as exc:
if not conn.closed:
conn.protocol.set_exception(exc)
except Exception as exc:
conn.protocol.set_exception(exc)
finally:
self._writer = None | [
"def",
"write_bytes",
"(",
"self",
",",
"writer",
",",
"conn",
")",
":",
"# 100 response",
"if",
"self",
".",
"_continue",
"is",
"not",
"None",
":",
"yield",
"from",
"writer",
".",
"drain",
"(",
")",
"yield",
"from",
"self",
".",
"_continue",
"try",
":... | https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/aiohttp/client_reqrep.py#L324-L355 | ||
bdcht/amoco | dac8e00b862eb6d87cc88dddd1e5316c67c1d798 | amoco/cas/expressions.py | python | symbols_of | (e) | returns all symbols contained in expression e | returns all symbols contained in expression e | [
"returns",
"all",
"symbols",
"contained",
"in",
"expression",
"e"
] | def symbols_of(e):
"returns all symbols contained in expression e"
if e is None:
return []
if e._is_cst:
return []
if e._is_reg:
return [e]
if e._is_mem:
return symbols_of(e.a.base)
if e._is_ptr:
return symbols_of(e.base)
if e._is_eqn:
return symbols_of(e.l) + symbols_of(e.r)
if e._is_tst:
return sum([symbols_of(x) for x in (e.tst, e.l, e.r)], [])
if e._is_slc:
return symbols_of(e.x)
if e._is_cmp:
return sum([symbols_of(x) for x in e.parts.values()], [])
if e._is_vec:
return sum([symbols_of(x) for x in e.l], [])
if not e._is_def:
return []
raise ValueError(e) | [
"def",
"symbols_of",
"(",
"e",
")",
":",
"if",
"e",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"e",
".",
"_is_cst",
":",
"return",
"[",
"]",
"if",
"e",
".",
"_is_reg",
":",
"return",
"[",
"e",
"]",
"if",
"e",
".",
"_is_mem",
":",
"return",
... | https://github.com/bdcht/amoco/blob/dac8e00b862eb6d87cc88dddd1e5316c67c1d798/amoco/cas/expressions.py#L1998-L2022 | ||
Tencent/bk-sops | 2a6bd1573b7b42812cb8a5b00929e98ab916b18d | pipeline_web/wrapper.py | python | PipelineTemplateWebWrapper._kwargs_for_template_dict | (cls, template_dict, include_str_id) | return defaults | 根据模板数据字典返回创建模板所需的关键字参数
@param template_dict: 模板数据字典
@param include_str_id: 数据中是否包括模板 ID
@return: 关键字参数字典 | 根据模板数据字典返回创建模板所需的关键字参数 | [
"根据模板数据字典返回创建模板所需的关键字参数"
] | def _kwargs_for_template_dict(cls, template_dict, include_str_id):
"""
根据模板数据字典返回创建模板所需的关键字参数
@param template_dict: 模板数据字典
@param include_str_id: 数据中是否包括模板 ID
@return: 关键字参数字典
"""
snapshot = Snapshot.objects.create_snapshot(template_dict["tree"])
defaults = {
"name": template_dict["name"],
"create_time": datetime.datetime.strptime(template_dict["create_time"], cls.SERIALIZE_DATE_FORMAT),
"description": template_dict["description"],
"editor": template_dict["editor"],
"edit_time": datetime.datetime.strptime(template_dict["edit_time"], cls.SERIALIZE_DATE_FORMAT),
"snapshot": snapshot,
}
if include_str_id:
defaults["template_id"] = template_dict["template_id"]
return defaults | [
"def",
"_kwargs_for_template_dict",
"(",
"cls",
",",
"template_dict",
",",
"include_str_id",
")",
":",
"snapshot",
"=",
"Snapshot",
".",
"objects",
".",
"create_snapshot",
"(",
"template_dict",
"[",
"\"tree\"",
"]",
")",
"defaults",
"=",
"{",
"\"name\"",
":",
... | https://github.com/Tencent/bk-sops/blob/2a6bd1573b7b42812cb8a5b00929e98ab916b18d/pipeline_web/wrapper.py#L213-L232 | |
SINGROUP/dscribe | 79a13939d66bdc858865dc050b91be9debd3c06a | dscribe/descriptors/mbtr.py | python | MBTR.k3 | (self) | return self._k3 | [] | def k3(self):
return self._k3 | [
"def",
"k3",
"(",
"self",
")",
":",
"return",
"self",
".",
"_k3"
] | https://github.com/SINGROUP/dscribe/blob/79a13939d66bdc858865dc050b91be9debd3c06a/dscribe/descriptors/mbtr.py#L370-L371 | |||
CalebBell/thermo | 572a47d1b03d49fe609b8d5f826fa6a7cde00828 | thermo/eos_mix.py | python | GCEOSMIX._dfugacity_dn | (self, zi, i, phase) | [] | def _dfugacity_dn(self, zi, i, phase):
# obsolete, should be deleted
z_copy = list(self.zs)
z_copy.pop(i)
z_sum = sum(z_copy) + zi
z_copy = [j/z_sum if j else 0 for j in z_copy]
z_copy.insert(i, zi)
eos = self.to_TP_zs(self.T, self.P, z_copy)
if phase == 'g':
return eos.fugacities_g[i]
elif phase == 'l':
return eos.fugacities_l[i] | [
"def",
"_dfugacity_dn",
"(",
"self",
",",
"zi",
",",
"i",
",",
"phase",
")",
":",
"# obsolete, should be deleted",
"z_copy",
"=",
"list",
"(",
"self",
".",
"zs",
")",
"z_copy",
".",
"pop",
"(",
"i",
")",
"z_sum",
"=",
"sum",
"(",
"z_copy",
")",
"+",
... | https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/eos_mix.py#L1590-L1602 | ||||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py | python | PoolManager._new_pool | (self, scheme, host, port) | return pool_cls(host, port, **kwargs) | Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization. | Create a new :class:`ConnectionPool` based on host, port and scheme. | [
"Create",
"a",
"new",
":",
"class",
":",
"ConnectionPool",
"based",
"on",
"host",
"port",
"and",
"scheme",
"."
] | def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.
"""
pool_cls = self.pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs) | [
"def",
"_new_pool",
"(",
"self",
",",
"scheme",
",",
"host",
",",
"port",
")",
":",
"pool_cls",
"=",
"self",
".",
"pool_classes_by_scheme",
"[",
"scheme",
"]",
"kwargs",
"=",
"self",
".",
"connection_pool_kw",
"if",
"scheme",
"==",
"'http'",
":",
"kwargs",... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py#L136-L151 | |
asyml/texar | a23f021dae289a3d768dc099b220952111da04fd | examples/transformer/bleu_tool.py | python | _get_ngrams | (segment, max_order) | return ngram_counts | Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
The Counter containing all n-grams upto max_order in segment
with a count of how many times each n-gram occurred. | Extracts all n-grams upto a given maximum order from an input segment. | [
"Extracts",
"all",
"n",
"-",
"grams",
"upto",
"a",
"given",
"maximum",
"order",
"from",
"an",
"input",
"segment",
"."
] | def _get_ngrams(segment, max_order):
"""Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
The Counter containing all n-grams upto max_order in segment
with a count of how many times each n-gram occurred.
"""
ngram_counts = collections.Counter()
for order in xrange(1, max_order + 1):
for i in xrange(0, len(segment) - order + 1):
ngram = tuple(segment[i:i + order])
ngram_counts[ngram] += 1
return ngram_counts | [
"def",
"_get_ngrams",
"(",
"segment",
",",
"max_order",
")",
":",
"ngram_counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"order",
"in",
"xrange",
"(",
"1",
",",
"max_order",
"+",
"1",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",... | https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/examples/transformer/bleu_tool.py#L49-L66 | |
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3db/inv.py | python | inv_recv_attr | (status) | Set field attributes for inv_recv table | Set field attributes for inv_recv table | [
"Set",
"field",
"attributes",
"for",
"inv_recv",
"table"
] | def inv_recv_attr(status):
"""
Set field attributes for inv_recv table
"""
s3db = current.s3db
settings = current.deployment_settings
table = s3db.inv_recv
table.sender_id.readable = table.sender_id.writable = False
table.grn_status.readable = table.grn_status.writable = False
table.cert_status.readable = table.cert_status.writable = False
table.eta.readable = False
table.req_ref.writable = True
if status == SHIP_STATUS_IN_PROCESS:
if settings.get_inv_recv_ref_writable():
f = table.recv_ref
f.writable = True
f.widget = lambda f, v: \
StringWidget.widget(f, v, _placeholder = current.T("Leave blank to have this autogenerated"))
else:
table.recv_ref.readable = False
table.send_ref.writable = True
table.sender_id.readable = False
else:
# Make all fields writable False
for field in table.fields:
table[field].writable = False
if settings.get_inv_recv_req():
s3db.inv_recv_req.req_id.writable = False
if status == SHIP_STATUS_SENT:
table.date.writable = True
table.recipient_id.readable = table.recipient_id.writable = True
table.comments.writable = True | [
"def",
"inv_recv_attr",
"(",
"status",
")",
":",
"s3db",
"=",
"current",
".",
"s3db",
"settings",
"=",
"current",
".",
"deployment_settings",
"table",
"=",
"s3db",
".",
"inv_recv",
"table",
".",
"sender_id",
".",
"readable",
"=",
"table",
".",
"sender_id",
... | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3db/inv.py#L9084-L9119 | ||
ioflo/ioflo | 177ac656d7c4ff801aebb0d8b401db365a5248ce | ioflo/aid/odicting.py | python | Test | () | Self test | Self test | [
"Self",
"test"
] | def Test():
"""Self test
"""
seq = [('b', 1), ('c', 2), ('a', 3)]
dct = {}
for k,v in seq:
dct[k] = v
odct = odict()
for k,v in seq:
odct[k] = v
print("Intialized from sequence of duples 'seq' = %s" % seq)
x = odict(seq)
print(" odict(seq) = %s" % x)
print("Initialized from unordered dictionary 'dct' = %s" % dct)
x = odict(dct)
print(" odict(dct) = %s" % x)
print("Initialized from ordered dictionary 'odct' = %s" % odct)
x = odict(odct)
print(" odict(odct) = %s" % x)
print("Initialized from keyword arguments 'b = 1, c = 2, a = 3'")
x = odict(b = 1, c = 2, a = 3)
print(" odict(b = 1, c = 2, a = 3) = %s" % x)
print("Initialized from mixed arguments")
x = odict(odct, seq, [('e', 4)], d = 5)
print(" odict(odct, seq, d = 4) = %s" % x) | [
"def",
"Test",
"(",
")",
":",
"seq",
"=",
"[",
"(",
"'b'",
",",
"1",
")",
",",
"(",
"'c'",
",",
"2",
")",
",",
"(",
"'a'",
",",
"3",
")",
"]",
"dct",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"seq",
":",
"dct",
"[",
"k",
"]",
"=",
... | https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aid/odicting.py#L634-L666 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/psycopg2/psycopg1.py | python | connect | (*args, **kwargs) | return conn | connect(dsn, ...) -> new psycopg 1.1.x compatible connection object | connect(dsn, ...) -> new psycopg 1.1.x compatible connection object | [
"connect",
"(",
"dsn",
"...",
")",
"-",
">",
"new",
"psycopg",
"1",
".",
"1",
".",
"x",
"compatible",
"connection",
"object"
] | def connect(*args, **kwargs):
"""connect(dsn, ...) -> new psycopg 1.1.x compatible connection object"""
kwargs['connection_factory'] = connection
conn = _2connect(*args, **kwargs)
conn.set_isolation_level(_ext.ISOLATION_LEVEL_READ_COMMITTED)
return conn | [
"def",
"connect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'connection_factory'",
"]",
"=",
"connection",
"conn",
"=",
"_2connect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"conn",
".",
"set_isolation_level",
"(",
"_e... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/psycopg2/psycopg1.py#L39-L44 | |
wxGlade/wxGlade | 44ed0d1cba78f27c5c0a56918112a737653b7b27 | codegen/__init__.py | python | BaseLangCodeWriter.quote_path | (self, s) | return '"%s"' % s | Escapes all quotation marks and backslashes, thus making a path suitable to insert in a list source file | Escapes all quotation marks and backslashes, thus making a path suitable to insert in a list source file | [
"Escapes",
"all",
"quotation",
"marks",
"and",
"backslashes",
"thus",
"making",
"a",
"path",
"suitable",
"to",
"insert",
"in",
"a",
"list",
"source",
"file"
] | def quote_path(self, s):
"Escapes all quotation marks and backslashes, thus making a path suitable to insert in a list source file"
# You may overwrite this function in the derived class
s = s.replace('\\', '\\\\')
s = s.replace('"', r'\"')
s = s.replace('$', r'\$') # sigh
s = s.replace('@', r'\@')
return '"%s"' % s | [
"def",
"quote_path",
"(",
"self",
",",
"s",
")",
":",
"# You may overwrite this function in the derived class",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'\"'",
",",
"r'\\\"'",
")",
"s",
"=",... | https://github.com/wxGlade/wxGlade/blob/44ed0d1cba78f27c5c0a56918112a737653b7b27/codegen/__init__.py#L1036-L1043 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/logging/__init__.py | python | Handler.flush | (self) | Ensure all logging output has been flushed.
This version does nothing and is intended to be implemented by
subclasses. | Ensure all logging output has been flushed. | [
"Ensure",
"all",
"logging",
"output",
"has",
"been",
"flushed",
"."
] | def flush(self):
"""
Ensure all logging output has been flushed.
This version does nothing and is intended to be implemented by
subclasses.
"""
pass | [
"def",
"flush",
"(",
"self",
")",
":",
"pass"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/logging/__init__.py#L755-L762 | ||
SanPen/GridCal | d3f4566d2d72c11c7e910c9d162538ef0e60df31 | src/GridCal/Engine/Replacements/mpiserve.py | python | MPIWorker.finish_success | (self, record_id, value) | Indicate that a function evaluation completed successfully.
Args:
record_id: Identifier for the function evaluation
value: Value returned by the feval | Indicate that a function evaluation completed successfully. | [
"Indicate",
"that",
"a",
"function",
"evaluation",
"completed",
"successfully",
"."
] | def finish_success(self, record_id, value):
"""Indicate that a function evaluation completed successfully.
Args:
record_id: Identifier for the function evaluation
value: Value returned by the feval
"""
self.send('complete', record_id, value) | [
"def",
"finish_success",
"(",
"self",
",",
"record_id",
",",
"value",
")",
":",
"self",
".",
"send",
"(",
"'complete'",
",",
"record_id",
",",
"value",
")"
] | https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Engine/Replacements/mpiserve.py#L236-L243 | ||
HeinleinSupport/check_mk_extensions | aa7d7389b812ed00f91dad61d66fb676284897d8 | lsbrelease/lib/check_mk/base/cee/plugins/bakery/lsbrelease.py | python | get_lsbrelease_files | (conf: Dict[str, Any]) | [] | def get_lsbrelease_files(conf: Dict[str, Any]) -> FileGenerator:
yield Plugin(base_os=OS.LINUX,
source=Path("lsbrelease"),
interval=conf.get("interval")) | [
"def",
"get_lsbrelease_files",
"(",
"conf",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"FileGenerator",
":",
"yield",
"Plugin",
"(",
"base_os",
"=",
"OS",
".",
"LINUX",
",",
"source",
"=",
"Path",
"(",
"\"lsbrelease\"",
")",
",",
"interval",
... | https://github.com/HeinleinSupport/check_mk_extensions/blob/aa7d7389b812ed00f91dad61d66fb676284897d8/lsbrelease/lib/check_mk/base/cee/plugins/bakery/lsbrelease.py#L23-L26 | ||||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/wsgiref/headers.py | python | _formatparam | (param, value=None, quote=1) | Convenience function to format and return a key=value pair.
This will quote the value if needed or if quote is true. | Convenience function to format and return a key=value pair. | [
"Convenience",
"function",
"to",
"format",
"and",
"return",
"a",
"key",
"=",
"value",
"pair",
"."
] | def _formatparam(param, value=None, quote=1):
"""Convenience function to format and return a key=value pair.
This will quote the value if needed or if quote is true.
"""
if value is not None and len(value) > 0:
if quote or tspecials.search(value):
value = value.replace('\\', '\\\\').replace('"', r'\"')
return '%s="%s"' % (param, value)
else:
return '%s=%s' % (param, value)
else:
return param | [
"def",
"_formatparam",
"(",
"param",
",",
"value",
"=",
"None",
",",
"quote",
"=",
"1",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"0",
":",
"if",
"quote",
"or",
"tspecials",
".",
"search",
"(",
"value",
"... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/wsgiref/headers.py#L13-L25 | ||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/google/oauth2/credentials.py | python | Credentials.requires_scopes | (self) | return False | False: OAuth 2.0 credentials have their scopes set when
the initial token is requested and can not be changed. | False: OAuth 2.0 credentials have their scopes set when
the initial token is requested and can not be changed. | [
"False",
":",
"OAuth",
"2",
".",
"0",
"credentials",
"have",
"their",
"scopes",
"set",
"when",
"the",
"initial",
"token",
"is",
"requested",
"and",
"can",
"not",
"be",
"changed",
"."
] | def requires_scopes(self):
"""False: OAuth 2.0 credentials have their scopes set when
the initial token is requested and can not be changed."""
return False | [
"def",
"requires_scopes",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/google/oauth2/credentials.py#L107-L110 | |
html5lib/html5lib-python | f7cab6f019ce94a1ec0192b6ff29aaebaf10b50d | html5lib/filters/lint.py | python | Filter.__init__ | (self, source, require_matching_tags=True) | Creates a Filter
:arg source: the source token stream
:arg require_matching_tags: whether or not to require matching tags | Creates a Filter | [
"Creates",
"a",
"Filter"
] | def __init__(self, source, require_matching_tags=True):
"""Creates a Filter
:arg source: the source token stream
:arg require_matching_tags: whether or not to require matching tags
"""
super(Filter, self).__init__(source)
self.require_matching_tags = require_matching_tags | [
"def",
"__init__",
"(",
"self",
",",
"source",
",",
"require_matching_tags",
"=",
"True",
")",
":",
"super",
"(",
"Filter",
",",
"self",
")",
".",
"__init__",
"(",
"source",
")",
"self",
".",
"require_matching_tags",
"=",
"require_matching_tags"
] | https://github.com/html5lib/html5lib-python/blob/f7cab6f019ce94a1ec0192b6ff29aaebaf10b50d/html5lib/filters/lint.py#L18-L27 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/preview/sync/service/sync_list/sync_list_item.py | python | SyncListItemList.page | (self, order=values.unset, from_=values.unset, bounds=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset) | return SyncListItemPage(self._version, response, self._solution) | Retrieve a single page of SyncListItemInstance records from the API.
Request is executed immediately
:param SyncListItemInstance.QueryResultOrder order: The order
:param unicode from_: The from
:param SyncListItemInstance.QueryFromBoundType bounds: The bounds
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SyncListItemInstance
:rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage | Retrieve a single page of SyncListItemInstance records from the API.
Request is executed immediately | [
"Retrieve",
"a",
"single",
"page",
"of",
"SyncListItemInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | def page(self, order=values.unset, from_=values.unset, bounds=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of SyncListItemInstance records from the API.
Request is executed immediately
:param SyncListItemInstance.QueryResultOrder order: The order
:param unicode from_: The from
:param SyncListItemInstance.QueryFromBoundType bounds: The bounds
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of SyncListItemInstance
:rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage
"""
data = values.of({
'Order': order,
'From': from_,
'Bounds': bounds,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return SyncListItemPage(self._version, response, self._solution) | [
"def",
"page",
"(",
"self",
",",
"order",
"=",
"values",
".",
"unset",
",",
"from_",
"=",
"values",
".",
"unset",
",",
"bounds",
"=",
"values",
".",
"unset",
",",
"page_token",
"=",
"values",
".",
"unset",
",",
"page_number",
"=",
"values",
".",
"uns... | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/sync/service/sync_list/sync_list_item.py#L109-L137 | |
aws/sagemaker-python-sdk | 9d259b316f7f43838c16f35c10e98a110b56735b | src/sagemaker/cli/compatibility/v2/modifiers/renamed_params.py | python | ParamRenamer.old_param_name | (self) | The parameter name used in previous versions of the SageMaker Python SDK. | The parameter name used in previous versions of the SageMaker Python SDK. | [
"The",
"parameter",
"name",
"used",
"in",
"previous",
"versions",
"of",
"the",
"SageMaker",
"Python",
"SDK",
"."
] | def old_param_name(self):
"""The parameter name used in previous versions of the SageMaker Python SDK.""" | [
"def",
"old_param_name",
"(",
"self",
")",
":"
] | https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/cli/compatibility/v2/modifiers/renamed_params.py#L37-L38 | ||
janrueth/SiriServerCore | dcc028c1fdddcc362e484b9ad655420ce953c8d2 | biplist/__init__.py | python | PlistReader.__init__ | (self, fileOrStream) | Raises NotBinaryPlistException. | Raises NotBinaryPlistException. | [
"Raises",
"NotBinaryPlistException",
"."
] | def __init__(self, fileOrStream):
"""Raises NotBinaryPlistException."""
self.reset()
self.file = fileOrStream | [
"def",
"__init__",
"(",
"self",
",",
"fileOrStream",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"file",
"=",
"fileOrStream"
] | https://github.com/janrueth/SiriServerCore/blob/dcc028c1fdddcc362e484b9ad655420ce953c8d2/biplist/__init__.py#L146-L149 | ||
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-windows/x86/PIL/IcoImagePlugin.py | python | IcoImageFile.load_seek | (self) | [] | def load_seek(self):
# Flag the ImageFile.Parser so that it
# just does all the decode at the end.
pass | [
"def",
"load_seek",
"(",
"self",
")",
":",
"# Flag the ImageFile.Parser so that it",
"# just does all the decode at the end.",
"pass"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/IcoImagePlugin.py#L310-L313 | ||||
pulp/pulp | a0a28d804f997b6f81c391378aff2e4c90183df9 | server/pulp/plugins/config.py | python | PluginCallConfiguration.get_boolean | (self, key, default=None) | return default | Parses the given key as a boolean value. If the key is not present or
is not one of the acceptable values for representing a boolean, a default
value (defaulting to None) is returned.
:param key: key to look up in the configuration
:type key: str
:return: boolean representation of the value if it can be parsed; None otherwise
:rtype: bool, None | Parses the given key as a boolean value. If the key is not present or
is not one of the acceptable values for representing a boolean, a default
value (defaulting to None) is returned. | [
"Parses",
"the",
"given",
"key",
"as",
"a",
"boolean",
"value",
".",
"If",
"the",
"key",
"is",
"not",
"present",
"or",
"is",
"not",
"one",
"of",
"the",
"acceptable",
"values",
"for",
"representing",
"a",
"boolean",
"a",
"default",
"value",
"(",
"defaulti... | def get_boolean(self, key, default=None):
"""
Parses the given key as a boolean value. If the key is not present or
is not one of the acceptable values for representing a boolean, a default
value (defaulting to None) is returned.
:param key: key to look up in the configuration
:type key: str
:return: boolean representation of the value if it can be parsed; None otherwise
:rtype: bool, None
"""
str_bool = self.get(key)
# Handle the case where it's already a boolean
if isinstance(str_bool, bool):
return str_bool
# If we're here, need to parse the string version of a boolean
if str_bool is not None:
str_bool = str_bool.lower()
if str_bool == 'true':
return True
elif str_bool == 'false':
return False
return default | [
"def",
"get_boolean",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"str_bool",
"=",
"self",
".",
"get",
"(",
"key",
")",
"# Handle the case where it's already a boolean",
"if",
"isinstance",
"(",
"str_bool",
",",
"bool",
")",
":",
"return"... | https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/server/pulp/plugins/config.py#L89-L115 | |
NoGameNoLife00/mybolg | afe17ea5bfe405e33766e5682c43a4262232ee12 | libs/sqlalchemy/orm/relationships.py | python | JoinCondition._refers_to_parent_table | (self) | return result[0] | Return True if the join condition contains column
comparisons where both columns are in both tables. | Return True if the join condition contains column
comparisons where both columns are in both tables. | [
"Return",
"True",
"if",
"the",
"join",
"condition",
"contains",
"column",
"comparisons",
"where",
"both",
"columns",
"are",
"in",
"both",
"tables",
"."
] | def _refers_to_parent_table(self):
"""Return True if the join condition contains column
comparisons where both columns are in both tables.
"""
pt = self.parent_selectable
mt = self.child_selectable
result = [False]
def visit_binary(binary):
c, f = binary.left, binary.right
if (
isinstance(c, expression.ColumnClause) and
isinstance(f, expression.ColumnClause) and
pt.is_derived_from(c.table) and
pt.is_derived_from(f.table) and
mt.is_derived_from(c.table) and
mt.is_derived_from(f.table)
):
result[0] = True
visitors.traverse(
self.primaryjoin,
{},
{"binary": visit_binary}
)
return result[0] | [
"def",
"_refers_to_parent_table",
"(",
"self",
")",
":",
"pt",
"=",
"self",
".",
"parent_selectable",
"mt",
"=",
"self",
".",
"child_selectable",
"result",
"=",
"[",
"False",
"]",
"def",
"visit_binary",
"(",
"binary",
")",
":",
"c",
",",
"f",
"=",
"binar... | https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/orm/relationships.py#L2156-L2181 | |
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | examples/showoci/showoci_service.py | python | ShowOCIService.__load_core_compute_main | (self) | [] | def __load_core_compute_main(self):
try:
print("Compute...")
# BlockstorageClient
block_storage = oci.core.BlockstorageClient(self.config, signer=self.signer)
if self.flags.proxy:
block_storage.base_client.session.proxies = {'https': self.flags.proxy}
# ComputeManagementClient
compute_manage = oci.core.ComputeManagementClient(self.config, signer=self.signer)
if self.flags.proxy:
compute_manage.base_client.session.proxies = {'https': self.flags.proxy}
# ComputeClient
compute_client = oci.core.ComputeClient(self.config, signer=self.signer)
if self.flags.proxy:
compute_client.base_client.session.proxies = {'https': self.flags.proxy}
# virtual_network - for vnics
virtual_network = oci.core.VirtualNetworkClient(self.config, signer=self.signer)
if self.flags.proxy:
virtual_network.base_client.session.proxies = {'https': self.flags.proxy}
# auto scaling
auto_scaling = oci.autoscaling.AutoScalingClient(self.config, signer=self.signer)
if self.flags.proxy:
auto_scaling.base_client.session.proxies = {'https': self.flags.proxy}
# reference to compartments
compartments = self.get_compartment()
# add the key to the network if not exists
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_INST)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_IMAGES)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_BOOT_VOL_ATTACH)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_VOLUME_ATTACH)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_VNIC_ATTACH)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_INST_CONFIG)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_INST_POOL)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_AUTOSCALING)
self.__initialize_data_key(self.C_COMPUTE, self.C_COMPUTE_CAPACITY_RESERVATION)
self.__initialize_data_key(self.C_BLOCK, self.C_BLOCK_VOLGRP)
self.__initialize_data_key(self.C_BLOCK, self.C_BLOCK_BOOT)
self.__initialize_data_key(self.C_BLOCK, self.C_BLOCK_BOOTBACK)
self.__initialize_data_key(self.C_BLOCK, self.C_BLOCK_VOL)
self.__initialize_data_key(self.C_BLOCK, self.C_BLOCK_VOLBACK)
# reference to compute
compute = self.data[self.C_COMPUTE]
block = self.data[self.C_BLOCK]
# append the data
compute[self.C_COMPUTE_INST] += self.__load_core_compute_instances(compute_client, compartments)
compute[self.C_COMPUTE_IMAGES] += self.__load_core_compute_images(compute_client, compartments)
compute[self.C_COMPUTE_BOOT_VOL_ATTACH] += self.__load_core_compute_boot_vol_attach(compute_client, compartments)
compute[self.C_COMPUTE_VOLUME_ATTACH] += self.__load_core_compute_vol_attach(compute_client, compartments)
compute[self.C_COMPUTE_VNIC_ATTACH] += self.__load_core_compute_vnic_attach(compute_client, virtual_network, compartments)
compute[self.C_COMPUTE_INST_CONFIG] += self.__load_core_compute_inst_config(compute_client, compute_manage, block_storage, compartments)
compute[self.C_COMPUTE_CAPACITY_RESERVATION] += self.__load_core_compute_capacity_reservation(compute_client, compartments)
compute[self.C_COMPUTE_INST_POOL] += self.__load_core_compute_inst_pool(compute_manage, compartments)
compute[self.C_COMPUTE_AUTOSCALING] += self.__load_core_compute_autoscaling(auto_scaling, compute_manage, compartments)
print("")
print("Block Storage...")
block[self.C_BLOCK_VOLGRP] += self.__load_core_block_volume_group(block_storage, compartments)
block[self.C_BLOCK_BOOT] += self.__load_core_block_boot(block_storage, compartments)
block[self.C_BLOCK_VOL] += self.__load_core_block_volume(block_storage, compartments)
if not self.flags.skip_backups:
block[self.C_BLOCK_BOOTBACK] += self.__load_core_block_boot_backup(block_storage, compartments)
block[self.C_BLOCK_VOLBACK] += self.__load_core_block_volume_backup(block_storage, compartments)
print("")
except oci.exceptions.RequestException:
raise
except oci.exceptions.ServiceError as e:
if self.__check_service_error(e.code):
print("")
pass
raise
except Exception as e:
self.__print_error("__load_core_compute_main", e) | [
"def",
"__load_core_compute_main",
"(",
"self",
")",
":",
"try",
":",
"print",
"(",
"\"Compute...\"",
")",
"# BlockstorageClient",
"block_storage",
"=",
"oci",
".",
"core",
".",
"BlockstorageClient",
"(",
"self",
".",
"config",
",",
"signer",
"=",
"self",
".",... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/examples/showoci/showoci_service.py#L3800-L3886 | ||||
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/urllib3/connection.py | python | HTTPConnection.host | (self) | return self._dns_host.rstrip('.') | Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In addition, some
servers may not expect to receive the trailing dot when provided.
However, the hostname with trailing dot is critical to DNS resolution; doing a
lookup with the trailing dot will properly only resolve the appropriate FQDN,
whereas a lookup without a trailing dot will search the system's search domain
list. Thus, it's important to keep the original host around for use only in
those cases where it's appropriate (i.e., when doing DNS lookup to establish the
actual TCP connection across which we're going to send HTTP requests). | Getter method to remove any trailing dots that indicate the hostname is an FQDN. | [
"Getter",
"method",
"to",
"remove",
"any",
"trailing",
"dots",
"that",
"indicate",
"the",
"hostname",
"is",
"an",
"FQDN",
"."
] | def host(self):
"""
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In addition, some
servers may not expect to receive the trailing dot when provided.
However, the hostname with trailing dot is critical to DNS resolution; doing a
lookup with the trailing dot will properly only resolve the appropriate FQDN,
whereas a lookup without a trailing dot will search the system's search domain
list. Thus, it's important to keep the original host around for use only in
those cases where it's appropriate (i.e., when doing DNS lookup to establish the
actual TCP connection across which we're going to send HTTP requests).
"""
return self._dns_host.rstrip('.') | [
"def",
"host",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dns_host",
".",
"rstrip",
"(",
"'.'",
")"
] | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/urllib3/connection.py#L117-L133 | |
iGio90/Dwarf | bb3011cdffd209c7e3f5febe558053bf649ca69c | dwarf_debugger/ui/widgets/code_editor.py | python | DwarfCompleter.getSelected | (self) | return self.lastSelected | [] | def getSelected(self):
return self.lastSelected | [
"def",
"getSelected",
"(",
"self",
")",
":",
"return",
"self",
".",
"lastSelected"
] | https://github.com/iGio90/Dwarf/blob/bb3011cdffd209c7e3f5febe558053bf649ca69c/dwarf_debugger/ui/widgets/code_editor.py#L40-L41 | |||
openstack/swift | b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100 | swift/obj/diskfile.py | python | BaseDiskFile.__enter__ | (self) | return self | Context enter.
.. note::
An implementation shall raise `DiskFileNotOpen` when has not
previously invoked the :func:`swift.obj.diskfile.DiskFile.open`
method. | Context enter. | [
"Context",
"enter",
"."
] | def __enter__(self):
"""
Context enter.
.. note::
An implementation shall raise `DiskFileNotOpen` when has not
previously invoked the :func:`swift.obj.diskfile.DiskFile.open`
method.
"""
if self._metadata is None:
raise DiskFileNotOpen()
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"raise",
"DiskFileNotOpen",
"(",
")",
"return",
"self"
] | https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/obj/diskfile.py#L2549-L2561 | |
sdispater/pendulum | 4b79cb78c87ca8b7b0bbc4c31b8ba4ca1d754a86 | pendulum/period.py | python | Period.in_months | (self) | return self.years * MONTHS_PER_YEAR + self.months | Gives the duration of the Period in full months.
:rtype: int | Gives the duration of the Period in full months. | [
"Gives",
"the",
"duration",
"of",
"the",
"Period",
"in",
"full",
"months",
"."
] | def in_months(self):
"""
Gives the duration of the Period in full months.
:rtype: int
"""
return self.years * MONTHS_PER_YEAR + self.months | [
"def",
"in_months",
"(",
"self",
")",
":",
"return",
"self",
".",
"years",
"*",
"MONTHS_PER_YEAR",
"+",
"self",
".",
"months"
] | https://github.com/sdispater/pendulum/blob/4b79cb78c87ca8b7b0bbc4c31b8ba4ca1d754a86/pendulum/period.py#L215-L221 | |
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/wheel/metadata.py | python | convert_requirements | (requirements) | Yield Requires-Dist: strings for parsed requirements strings. | Yield Requires-Dist: strings for parsed requirements strings. | [
"Yield",
"Requires",
"-",
"Dist",
":",
"strings",
"for",
"parsed",
"requirements",
"strings",
"."
] | def convert_requirements(requirements):
"""Yield Requires-Dist: strings for parsed requirements strings."""
for req in requirements:
parsed_requirement = pkg_resources.Requirement.parse(req)
spec = requires_to_requires_dist(parsed_requirement)
extras = ",".join(parsed_requirement.extras)
if extras:
extras = "[%s]" % extras
yield (parsed_requirement.project_name + extras + spec) | [
"def",
"convert_requirements",
"(",
"requirements",
")",
":",
"for",
"req",
"in",
"requirements",
":",
"parsed_requirement",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"req",
")",
"spec",
"=",
"requires_to_requires_dist",
"(",
"parsed_requirement",... | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/wheel/metadata.py#L228-L236 | ||
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | find_extlang_by_name | (*args) | return _idaapi.find_extlang_by_name(*args) | find_extlang_by_name(name) -> extlang_t const * | find_extlang_by_name(name) -> extlang_t const * | [
"find_extlang_by_name",
"(",
"name",
")",
"-",
">",
"extlang_t",
"const",
"*"
] | def find_extlang_by_name(*args):
"""
find_extlang_by_name(name) -> extlang_t const *
"""
return _idaapi.find_extlang_by_name(*args) | [
"def",
"find_extlang_by_name",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"find_extlang_by_name",
"(",
"*",
"args",
")"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L26754-L26758 | |
rowanz/neural-motifs | d05a251b705cedaa51599bf2906cfa4653b7a761 | misc/motifs.py | python | id_to_str | (_id) | [] | def id_to_str(_id):
key = id_key[_id]
if len(key) == 2:
pair = key
l1, s1 = id_to_str(pair[0])
l2, s2 = id_to_str(pair[1])
return (l1 + l2, s1 + " & " + s2)
else:
return (1,"{}--{}-->{}".format(cids[key[0]], rids[key[1]], cids[key[2]])) | [
"def",
"id_to_str",
"(",
"_id",
")",
":",
"key",
"=",
"id_key",
"[",
"_id",
"]",
"if",
"len",
"(",
"key",
")",
"==",
"2",
":",
"pair",
"=",
"key",
"l1",
",",
"s1",
"=",
"id_to_str",
"(",
"pair",
"[",
"0",
"]",
")",
"l2",
",",
"s2",
"=",
"id... | https://github.com/rowanz/neural-motifs/blob/d05a251b705cedaa51599bf2906cfa4653b7a761/misc/motifs.py#L63-L71 | ||||
taokong/FoveaBox | 50ce41e5af9cfba562877a318231e53c3b3ce767 | mmdet/core/post_processing/merge_augs.py | python | merge_aug_bboxes | (aug_bboxes, aug_scores, img_metas, rcnn_test_cfg) | Merge augmented detection bboxes and scores.
Args:
aug_bboxes (list[Tensor]): shape (n, 4*#class)
aug_scores (list[Tensor] or None): shape (n, #class)
img_shapes (list[Tensor]): shape (3, ).
rcnn_test_cfg (dict): rcnn test config.
Returns:
tuple: (bboxes, scores) | Merge augmented detection bboxes and scores. | [
"Merge",
"augmented",
"detection",
"bboxes",
"and",
"scores",
"."
] | def merge_aug_bboxes(aug_bboxes, aug_scores, img_metas, rcnn_test_cfg):
"""Merge augmented detection bboxes and scores.
Args:
aug_bboxes (list[Tensor]): shape (n, 4*#class)
aug_scores (list[Tensor] or None): shape (n, #class)
img_shapes (list[Tensor]): shape (3, ).
rcnn_test_cfg (dict): rcnn test config.
Returns:
tuple: (bboxes, scores)
"""
recovered_bboxes = []
for bboxes, img_info in zip(aug_bboxes, img_metas):
img_shape = img_info[0]['img_shape']
scale_factor = img_info[0]['scale_factor']
flip = img_info[0]['flip']
bboxes = bbox_mapping_back(bboxes, img_shape, scale_factor, flip)
recovered_bboxes.append(bboxes)
bboxes = torch.stack(recovered_bboxes).mean(dim=0)
if aug_scores is None:
return bboxes
else:
scores = torch.stack(aug_scores).mean(dim=0)
return bboxes, scores | [
"def",
"merge_aug_bboxes",
"(",
"aug_bboxes",
",",
"aug_scores",
",",
"img_metas",
",",
"rcnn_test_cfg",
")",
":",
"recovered_bboxes",
"=",
"[",
"]",
"for",
"bboxes",
",",
"img_info",
"in",
"zip",
"(",
"aug_bboxes",
",",
"img_metas",
")",
":",
"img_shape",
"... | https://github.com/taokong/FoveaBox/blob/50ce41e5af9cfba562877a318231e53c3b3ce767/mmdet/core/post_processing/merge_augs.py#L40-L64 | ||
google/apis-client-generator | f09f0ba855c3845d315b811c6234fd3996f33172 | src/googleapis/codegen/data_types.py | python | ComplexDataType.className | (self) | return self.class_name or self.safeClassName | [] | def className(self): # pylint: disable=g-bad-name
return self.class_name or self.safeClassName | [
"def",
"className",
"(",
"self",
")",
":",
"# pylint: disable=g-bad-name",
"return",
"self",
".",
"class_name",
"or",
"self",
".",
"safeClassName"
] | https://github.com/google/apis-client-generator/blob/f09f0ba855c3845d315b811c6234fd3996f33172/src/googleapis/codegen/data_types.py#L223-L224 | |||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/mailbox.py | python | _mboxMMDF.get_bytes | (self, key, from_=False) | return string.replace(linesep, b'\n') | Return a string representation or raise a KeyError. | Return a string representation or raise a KeyError. | [
"Return",
"a",
"string",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_bytes(self, key, from_=False):
"""Return a string representation or raise a KeyError."""
start, stop = self._lookup(key)
self._file.seek(start)
if not from_:
self._file.readline()
string = self._file.read(stop - self._file.tell())
return string.replace(linesep, b'\n') | [
"def",
"get_bytes",
"(",
"self",
",",
"key",
",",
"from_",
"=",
"False",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"start",
")",
"if",
"not",
"from_",
":",
"self",
".",
... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/mailbox.py#L789-L796 | |
albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | mac/pyobjc-framework-Quartz/Examples/Core Image/CIMicroPaint/SampleCIView.py | python | SampleCIView.updateMatrices | (self) | [] | def updateMatrices(self):
r = self.bounds()
if r != self._lastBounds:
self.openGLContext().update()
# Install an orthographic projection matrix (no perspective)
# with the origin in the bottom left and one unit equal to one
# device pixel.
glViewport(0, 0, r.size.width, r.size.height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, r.size.width, 0, r.size.height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
self._lastBounds = r
self.viewBoundsDidChange_(r) | [
"def",
"updateMatrices",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"bounds",
"(",
")",
"if",
"r",
"!=",
"self",
".",
"_lastBounds",
":",
"self",
".",
"openGLContext",
"(",
")",
".",
"update",
"(",
")",
"# Install an orthographic projection matrix (no per... | https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Quartz/Examples/Core Image/CIMicroPaint/SampleCIView.py#L81-L102 | ||||
voc/voctomix | 3156f3546890e6ae8d379df17e5cc718eee14b15 | vocto/transitions.py | python | interpolate | (key_frames, num_frames, corner) | return animation | interpolate < num_frames > points of one corner defined by < corner >
between the rectangles given by < key_frames > | interpolate < num_frames > points of one corner defined by < corner >
between the rectangles given by < key_frames > | [
"interpolate",
"<",
"num_frames",
">",
"points",
"of",
"one",
"corner",
"defined",
"by",
"<",
"corner",
">",
"between",
"the",
"rectangles",
"given",
"by",
"<",
"key_frames",
">"
] | def interpolate(key_frames, num_frames, corner):
""" interpolate < num_frames > points of one corner defined by < corner >
between the rectangles given by < key_frames >
"""
# get corner points defined by index_x,index_y from rectangles
corners = np.array([i.corner(corner[X], corner[Y]) for i in key_frames])
# interpolate between corners and get the spline points and the indexes of
# those which are the nearest to the corner points
spline = bspline(corners)
# skip if we got no interpolation
if not spline:
return [], []
# find indices of the corner's nearest points within the spline
corner_indices = find_nearest(spline, corners)
# transpose point array
spline = np.transpose(spline)
# calulcate number of frames between every corner
num_frames_per_move = int(round(num_frames / (len(corner_indices) - 1)))
# measure the spline
positions = measure(spline)
# fill with point animation from corner to corner
animation = []
for i in range(1, len(corner_indices)):
# substitute indices of corner pair
begin = corner_indices[i - 1]
end = corner_indices[i]
# calculate range of X between 0.0 and 1.0 for these corners
_x0 = (i - 1) / (len(corner_indices) - 1)
_x1 = i / (len(corner_indices) - 1)
# create distribution of points between these corners
corner_animation = distribute(
spline, positions, begin, end, _x0, _x1, num_frames_per_move - 1)
# append first rectangle from parameters
animation.append(key_frames[i - 1])
# cound index
for j in range(len(corner_animation)):
# calculate current sinus wave acceleration
frame = morph(key_frames[i - 1], key_frames[i],
corner_animation[j], corner,
smooth(j / len(corner_animation)))
# append to resulting animation
animation.append(frame)
# append last rectangle from parameters
animation.append(key_frames[-1])
# return rectangle animation
return animation | [
"def",
"interpolate",
"(",
"key_frames",
",",
"num_frames",
",",
"corner",
")",
":",
"# get corner points defined by index_x,index_y from rectangles",
"corners",
"=",
"np",
".",
"array",
"(",
"[",
"i",
".",
"corner",
"(",
"corner",
"[",
"X",
"]",
",",
"corner",
... | https://github.com/voc/voctomix/blob/3156f3546890e6ae8d379df17e5cc718eee14b15/vocto/transitions.py#L488-L533 | |
CLUEbenchmark/CLUE | 5bd39732734afecb490cf18a5212e692dbf2c007 | baselines/models_pytorch/mrc_pytorch/tools/pytorch_optimization.py | python | BERTAdam.__init__ | (self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear',
b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01, cycle_step=None,
max_grad_norm=1.0) | [] | def __init__(self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear',
b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01, cycle_step=None,
max_grad_norm=1.0):
if lr is not None and not lr >= 0.0:
raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
if schedule not in SCHEDULES:
raise ValueError("Invalid schedule parameter: {}".format(schedule))
if not 0.0 <= warmup < 1.0 and not warmup == -1:
raise ValueError("Invalid warmup: {} - should be in [0.0, 1.0[ or -1".format(warmup))
if not 0.0 <= b1 < 1.0:
raise ValueError("Invalid b1 parameter: {} - should be in [0.0, 1.0[".format(b1))
if not 0.0 <= b2 < 1.0:
raise ValueError("Invalid b2 parameter: {} - should be in [0.0, 1.0[".format(b2))
if not e >= 0.0:
raise ValueError("Invalid epsilon value: {} - should be >= 0.0".format(e))
defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total,
b1=b1, b2=b2, e=e, weight_decay_rate=weight_decay_rate,
max_grad_norm=max_grad_norm, cycle_step=cycle_step)
super(BERTAdam, self).__init__(params, defaults) | [
"def",
"__init__",
"(",
"self",
",",
"params",
",",
"lr",
",",
"warmup",
"=",
"-",
"1",
",",
"t_total",
"=",
"-",
"1",
",",
"schedule",
"=",
"'warmup_linear'",
",",
"b1",
"=",
"0.9",
",",
"b2",
"=",
"0.999",
",",
"e",
"=",
"1e-6",
",",
"weight_de... | https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models_pytorch/mrc_pytorch/tools/pytorch_optimization.py#L69-L87 | ||||
tensorflow/lingvo | ce10019243d954c3c3ebe739f7589b5eebfdf907 | lingvo/trainer.py | python | RunnerManager.MaybeConfigCloudTpu | (self) | If given `FLAGS.tpu`, update flags for running on a Cloud TPU. | If given `FLAGS.tpu`, update flags for running on a Cloud TPU. | [
"If",
"given",
"FLAGS",
".",
"tpu",
"update",
"flags",
"for",
"running",
"on",
"a",
"Cloud",
"TPU",
"."
] | def MaybeConfigCloudTpu(self):
"""If given `FLAGS.tpu`, update flags for running on a Cloud TPU."""
if not FLAGS.tpu:
return
if not FLAGS.job:
FLAGS.job = 'trainer_client'
if FLAGS.job not in ('trainer_client', 'executor_tpu'):
raise ValueError('Only trainer_client and executor_tpu jobs are '
'supported on TPU.')
cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
tpu=FLAGS.tpu,
project=FLAGS.gcp_project,
zone=FLAGS.tpu_zone,
job_name=FLAGS.job)
cluster_spec_dict = cluster_resolver.cluster_spec().as_dict()
FLAGS.mode = 'sync'
FLAGS.tf_master = cluster_resolver.master()
FLAGS.worker_job = '/job:{}'.format(FLAGS.job)
FLAGS.worker_replicas = 1
FLAGS.worker_num_tpu_hosts = len(cluster_spec_dict[FLAGS.job])
FLAGS.worker_tpus = (
cluster_resolver.num_accelerators()['TPU'] * FLAGS.worker_num_tpu_hosts)
FLAGS.ps_job = FLAGS.worker_job
if FLAGS.job == 'trainer_client':
FLAGS.ps_replicas = FLAGS.worker_replicas
FLAGS.cluster_spec = ('@'.join('{}={}'.format(job, ','.join(hosts))
for job, hosts in cluster_spec_dict.items()))
FLAGS.xla_device = 'tpu'
FLAGS.enable_asserts = False
FLAGS.checkpoint_in_trainer_tpu = True | [
"def",
"MaybeConfigCloudTpu",
"(",
"self",
")",
":",
"if",
"not",
"FLAGS",
".",
"tpu",
":",
"return",
"if",
"not",
"FLAGS",
".",
"job",
":",
"FLAGS",
".",
"job",
"=",
"'trainer_client'",
"if",
"FLAGS",
".",
"job",
"not",
"in",
"(",
"'trainer_client'",
... | https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/trainer.py#L341-L377 | ||
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v6_0/task_agent/task_agent_client.py | python | TaskAgentClient.add_agent_cloud | (self, agent_cloud) | return self._deserialize('TaskAgentCloud', response) | AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>` | AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>` | [
"AddAgentCloud",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
":",
"class",
":",
"<TaskAgentCloud",
">",
"<azure",
".",
"devops",
".",
"v6_0",
".",
"task_agent",
".",
"models",
".",
"TaskAgentCloud",
">",
"agent_cloud",
":",
":",
"rtype",
":",
":",
"cl... | def add_agent_cloud(self, agent_cloud):
"""AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v6_0.task_agent.models.TaskAgentCloud>`
"""
content = self._serialize.body(agent_cloud, 'TaskAgentCloud')
response = self._send(http_method='POST',
location_id='bfa72b3d-0fc6-43fb-932b-a7f6559f93b9',
version='6.0-preview.1',
content=content)
return self._deserialize('TaskAgentCloud', response) | [
"def",
"add_agent_cloud",
"(",
"self",
",",
"agent_cloud",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"agent_cloud",
",",
"'TaskAgentCloud'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'POST'",
",",
"l... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/task_agent/task_agent_client.py#L28-L39 | |
Azure/azure-cli | 6c1b085a0910c6c2139006fcbd8ade44006eb6dd | src/azure-cli/azure/cli/command_modules/acs/custom.py | python | acs_browse | (cmd, client, resource_group_name, name, disable_browser=False, ssh_key_file=None) | Opens a browser to the web interface for the cluster orchestrator
:param name: Name of the target Azure container service instance.
:type name: String
:param resource_group_name: Name of Azure container service's resource group.
:type resource_group_name: String
:param disable_browser: If true, don't launch a web browser after estabilishing the proxy
:type disable_browser: bool
:param ssh_key_file: If set a path to an SSH key to use, only applies to DCOS
:type ssh_key_file: string | Opens a browser to the web interface for the cluster orchestrator | [
"Opens",
"a",
"browser",
"to",
"the",
"web",
"interface",
"for",
"the",
"cluster",
"orchestrator"
] | def acs_browse(cmd, client, resource_group_name, name, disable_browser=False, ssh_key_file=None):
"""
Opens a browser to the web interface for the cluster orchestrator
:param name: Name of the target Azure container service instance.
:type name: String
:param resource_group_name: Name of Azure container service's resource group.
:type resource_group_name: String
:param disable_browser: If true, don't launch a web browser after estabilishing the proxy
:type disable_browser: bool
:param ssh_key_file: If set a path to an SSH key to use, only applies to DCOS
:type ssh_key_file: string
"""
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
_acs_browse_internal(
cmd, client, acs_info, resource_group_name, name, disable_browser, ssh_key_file) | [
"def",
"acs_browse",
"(",
"cmd",
",",
"client",
",",
"resource_group_name",
",",
"name",
",",
"disable_browser",
"=",
"False",
",",
"ssh_key_file",
"=",
"None",
")",
":",
"acs_info",
"=",
"_get_acs_info",
"(",
"cmd",
".",
"cli_ctx",
",",
"name",
",",
"reso... | https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/acs/custom.py#L167-L182 | ||
nosmokingbandit/Watcher3 | 0217e75158b563bdefc8e01c3be7620008cf3977 | lib/infi/pkg_resources/_vendor/pyparsing.py | python | ParserElement.validate | ( self, validateTrace=[] ) | Check defined expressions for valid structure, check for infinite recursive definitions. | Check defined expressions for valid structure, check for infinite recursive definitions. | [
"Check",
"defined",
"expressions",
"for",
"valid",
"structure",
"check",
"for",
"infinite",
"recursive",
"definitions",
"."
] | def validate( self, validateTrace=[] ):
"""
Check defined expressions for valid structure, check for infinite recursive definitions.
"""
self.checkRecursion( [] ) | [
"def",
"validate",
"(",
"self",
",",
"validateTrace",
"=",
"[",
"]",
")",
":",
"self",
".",
"checkRecursion",
"(",
"[",
"]",
")"
] | https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/infi/pkg_resources/_vendor/pyparsing.py#L2126-L2130 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/asymptotic/term_monoid.py | python | TermWithCoefficientMonoid._default_kwds_construction_ | (self) | return defaults | r"""
Return the default keyword arguments for the construction of a term.
INPUT:
Nothing.
OUTPUT:
A dictionary.
TESTS::
sage: from sage.rings.asymptotic.term_monoid import DefaultTermMonoidFactory as TermMonoid
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: G = GrowthGroup('x^ZZ')
sage: T = TermMonoid('exact', G, ZZ)
sage: T._default_kwds_construction_()
{'coefficient': 1}
sage: T.from_construction((None, {'growth': G.gen()})) # indirect doctest
x | r"""
Return the default keyword arguments for the construction of a term. | [
"r",
"Return",
"the",
"default",
"keyword",
"arguments",
"for",
"the",
"construction",
"of",
"a",
"term",
"."
] | def _default_kwds_construction_(self):
r"""
Return the default keyword arguments for the construction of a term.
INPUT:
Nothing.
OUTPUT:
A dictionary.
TESTS::
sage: from sage.rings.asymptotic.term_monoid import DefaultTermMonoidFactory as TermMonoid
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: G = GrowthGroup('x^ZZ')
sage: T = TermMonoid('exact', G, ZZ)
sage: T._default_kwds_construction_()
{'coefficient': 1}
sage: T.from_construction((None, {'growth': G.gen()})) # indirect doctest
x
"""
defaults = {}
defaults.update(super()._default_kwds_construction_())
defaults.update({'coefficient': self.coefficient_ring.one()})
return defaults | [
"def",
"_default_kwds_construction_",
"(",
"self",
")",
":",
"defaults",
"=",
"{",
"}",
"defaults",
".",
"update",
"(",
"super",
"(",
")",
".",
"_default_kwds_construction_",
"(",
")",
")",
"defaults",
".",
"update",
"(",
"{",
"'coefficient'",
":",
"self",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/term_monoid.py#L3640-L3666 | |
mrlesmithjr/Ansible | d44f0dc0d942bdf3bf7334b307e6048f0ee16e36 | roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pkg_resources/__init__.py | python | WorkingSet.iter_entry_points | (self, group, name=None) | Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order). | Yield entry point objects from `group` matching `name` | [
"Yield",
"entry",
"point",
"objects",
"from",
"group",
"matching",
"name"
] | def iter_entry_points(self, group, name=None):
"""Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).
"""
for dist in self:
entries = dist.get_entry_map(group)
if name is None:
for ep in entries.values():
yield ep
elif name in entries:
yield entries[name] | [
"def",
"iter_entry_points",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
")",
":",
"for",
"dist",
"in",
"self",
":",
"entries",
"=",
"dist",
".",
"get_entry_map",
"(",
"group",
")",
"if",
"name",
"is",
"None",
":",
"for",
"ep",
"in",
"entries... | https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pkg_resources/__init__.py#L727-L740 | ||
ratschlab/RGAN | f41731b965348259dcd94b0dcb1374d3e1c4ca7d | differential_privacy/privacy_accountant/tf/accountant.py | python | AmortizedAccountant.accumulate_privacy_spending | (self, eps_delta, unused_sigma,
num_examples) | Accumulate the privacy spending.
Currently only support approximate privacy. Here we assume we use Gaussian
noise on randomly sampled batch so we get better composition: 1. the per
batch privacy is computed using privacy amplication via sampling bound;
2. the composition is done using the composition with Gaussian noise.
TODO(liqzhang) Add a link to a document that describes the bounds used.
Args:
eps_delta: EpsDelta pair which can be tensors.
unused_sigma: the noise sigma. Unused for this accountant.
num_examples: the number of examples involved.
Returns:
a TensorFlow operation for updating the privacy spending. | Accumulate the privacy spending. | [
"Accumulate",
"the",
"privacy",
"spending",
"."
] | def accumulate_privacy_spending(self, eps_delta, unused_sigma,
num_examples):
"""Accumulate the privacy spending.
Currently only support approximate privacy. Here we assume we use Gaussian
noise on randomly sampled batch so we get better composition: 1. the per
batch privacy is computed using privacy amplication via sampling bound;
2. the composition is done using the composition with Gaussian noise.
TODO(liqzhang) Add a link to a document that describes the bounds used.
Args:
eps_delta: EpsDelta pair which can be tensors.
unused_sigma: the noise sigma. Unused for this accountant.
num_examples: the number of examples involved.
Returns:
a TensorFlow operation for updating the privacy spending.
"""
eps, delta = eps_delta
with tf.control_dependencies(
[tf.Assert(tf.greater(delta, 0),
["delta needs to be greater than 0"])]):
amortize_ratio = (tf.cast(num_examples, tf.float32) * 1.0 /
self._total_examples)
# Use privacy amplification via sampling bound.
# See Lemma 2.2 in http://arxiv.org/pdf/1405.7085v2.pdf
# TODO(liqzhang) Add a link to a document with formal statement
# and proof.
amortize_eps = tf.reshape(tf.log(1.0 + amortize_ratio * (
tf.exp(eps) - 1.0)), [1])
amortize_delta = tf.reshape(amortize_ratio * delta, [1])
return tf.group(*[tf.assign_add(self._eps_squared_sum,
tf.square(amortize_eps)),
tf.assign_add(self._delta_sum, amortize_delta)]) | [
"def",
"accumulate_privacy_spending",
"(",
"self",
",",
"eps_delta",
",",
"unused_sigma",
",",
"num_examples",
")",
":",
"eps",
",",
"delta",
"=",
"eps_delta",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"tf",
".",
"Assert",
"(",
"tf",
".",
"greater... | https://github.com/ratschlab/RGAN/blob/f41731b965348259dcd94b0dcb1374d3e1c4ca7d/differential_privacy/privacy_accountant/tf/accountant.py#L73-L106 | ||
sideeffects/SideFXLabs | 956bc1eef6710882ae8d3a31b4a33dd631a56d5f | viewer_states/ruler.py | python | MeasurementContainer.current | (self) | return self.measurements[-1] | [] | def current(self):
if self.count() < 1:
raise hou.Error("No measurements available!") #this check is for debugging. we should never be in this place if things work correctly.
return self.measurements[-1] | [
"def",
"current",
"(",
"self",
")",
":",
"if",
"self",
".",
"count",
"(",
")",
"<",
"1",
":",
"raise",
"hou",
".",
"Error",
"(",
"\"No measurements available!\"",
")",
"#this check is for debugging. we should never be in this place if things work correctly.",
"return",
... | https://github.com/sideeffects/SideFXLabs/blob/956bc1eef6710882ae8d3a31b4a33dd631a56d5f/viewer_states/ruler.py#L457-L460 | |||
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/plugins/grep/cross_domain_js.py | python | cross_domain_js._analyze_domain | (self, response, script_full_url, script_tag) | Checks if the domain is the same, or if it's considered secure. | Checks if the domain is the same, or if it's considered secure. | [
"Checks",
"if",
"the",
"domain",
"is",
"the",
"same",
"or",
"if",
"it",
"s",
"considered",
"secure",
"."
] | def _analyze_domain(self, response, script_full_url, script_tag):
"""
Checks if the domain is the same, or if it's considered secure.
"""
response_url = response.get_url()
script_domain = script_full_url.get_domain()
if script_domain == response_url.get_domain():
return
for _ in self._secure_domain_multi_in.query(script_domain):
# Query the multi in to check if any if the domains we loaded
# previously match against the script domain we found in the
# HTML.
#
# It's a third party that we trust
return
to_highlight = script_tag.attrib.get('src')
desc = ('The URL: "%s" has a script tag with a source that points'
' to a third party site ("%s"). This practice is not'
' recommended, the security of the current site is being'
' delegated to the external entity.')
desc %= (smart_str_ignore(response_url),
smart_str_ignore(script_domain))
i = Info('Cross-domain javascript source', desc,
response.id, self.get_name())
i.set_url(response_url)
i.add_to_highlight(to_highlight)
i[CrossDomainInfoSet.ITAG] = script_domain
self.kb_append_uniq_group(self, 'cross_domain_js', i,
group_klass=CrossDomainInfoSet) | [
"def",
"_analyze_domain",
"(",
"self",
",",
"response",
",",
"script_full_url",
",",
"script_tag",
")",
":",
"response_url",
"=",
"response",
".",
"get_url",
"(",
")",
"script_domain",
"=",
"script_full_url",
".",
"get_domain",
"(",
")",
"if",
"script_domain",
... | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/grep/cross_domain_js.py#L91-L124 | ||
treigerm/WaterNet | 5f30e796b03519b1d79be2ac1f148b873bf9e877 | waterNet/geo_util.py | python | visualise_labels | (labels, tile_size, out_path) | Given the labels of a satellite image as tiles. Overlay the source image with the labels
to check if labels are roughly correct. | Given the labels of a satellite image as tiles. Overlay the source image with the labels
to check if labels are roughly correct. | [
"Given",
"the",
"labels",
"of",
"a",
"satellite",
"image",
"as",
"tiles",
".",
"Overlay",
"the",
"source",
"image",
"with",
"the",
"labels",
"to",
"check",
"if",
"labels",
"are",
"roughly",
"correct",
"."
] | def visualise_labels(labels, tile_size, out_path):
"""Given the labels of a satellite image as tiles. Overlay the source image with the labels
to check if labels are roughly correct."""
# The tiles might come from different satellite images so we have to
# group them according to their source image.
get_path = lambda (tiles, pos, path): path
sorted_by_path = sorted(labels, key=get_path)
for path, predictions in itertools.groupby(sorted_by_path, get_path):
raster_dataset = rasterio.open(path)
bitmap_shape = (raster_dataset.shape[0], raster_dataset.shape[1])
bitmap = image_from_tiles(predictions, tile_size, bitmap_shape)
satellite_img_name = get_file_name(path)
out_file_name = "{}.tif".format(satellite_img_name)
out = os.path.join(out_path, out_file_name)
overlay_bitmap(bitmap, raster_dataset, out) | [
"def",
"visualise_labels",
"(",
"labels",
",",
"tile_size",
",",
"out_path",
")",
":",
"# The tiles might come from different satellite images so we have to",
"# group them according to their source image.",
"get_path",
"=",
"lambda",
"(",
"tiles",
",",
"pos",
",",
"path",
... | https://github.com/treigerm/WaterNet/blob/5f30e796b03519b1d79be2ac1f148b873bf9e877/waterNet/geo_util.py#L125-L142 | ||
niosus/EasyClangComplete | 3b16eb17735aaa3f56bb295fc5481b269ee9f2ef | plugin/clang/cindex50.py | python | Cursor.get_template_argument_type | (self, num) | return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) | Returns the CXType for the indicated template argument. | Returns the CXType for the indicated template argument. | [
"Returns",
"the",
"CXType",
"for",
"the",
"indicated",
"template",
"argument",
"."
] | def get_template_argument_type(self, num):
"""Returns the CXType for the indicated template argument."""
return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) | [
"def",
"get_template_argument_type",
"(",
"self",
",",
"num",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getTemplateArgumentType",
"(",
"self",
",",
"num",
")"
] | https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex50.py#L1758-L1760 | |
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gui/views/navigationview.py | python | NavigationView.navigation_group | (self) | return self.nav_group | Return the navigation group. | Return the navigation group. | [
"Return",
"the",
"navigation",
"group",
"."
] | def navigation_group(self):
"""
Return the navigation group.
"""
return self.nav_group | [
"def",
"navigation_group",
"(",
"self",
")",
":",
"return",
"self",
".",
"nav_group"
] | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/views/navigationview.py#L175-L179 | |
jiangsir404/POC-S | eb06d3f54b1698362ad0b62f1b26d22ecafa5624 | pocs/thirdparty/httplib2/__init__.py | python | WsseAuthentication.request | (self, method, request_uri, headers, content) | Modify the request headers to add the appropriate
Authorization header. | Modify the request headers to add the appropriate
Authorization header. | [
"Modify",
"the",
"request",
"headers",
"to",
"add",
"the",
"appropriate",
"Authorization",
"header",
"."
] | def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"request_uri",
",",
"headers",
",",
"content",
")",
":",
"headers",
"[",
"'authorization'",
"]",
"=",
"'WSSE profile=\"UsernameToken\"'",
"iso_now",
"=",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%SZ\"",
"... | https://github.com/jiangsir404/POC-S/blob/eb06d3f54b1698362ad0b62f1b26d22ecafa5624/pocs/thirdparty/httplib2/__init__.py#L639-L650 | ||
s-leger/archipack | 5a6243bf1edf08a6b429661ce291dacb551e5f8a | pygeos/op_linemerge.py | python | LineMerger.add | (self, geoms) | * Adds a collection of Geometries to be processed.
* May be called multiple times.
*
* Any dimension of Geometry may be added; the constituent
* linework will be extracted. | * Adds a collection of Geometries to be processed.
* May be called multiple times.
*
* Any dimension of Geometry may be added; the constituent
* linework will be extracted. | [
"*",
"Adds",
"a",
"collection",
"of",
"Geometries",
"to",
"be",
"processed",
".",
"*",
"May",
"be",
"called",
"multiple",
"times",
".",
"*",
"*",
"Any",
"dimension",
"of",
"Geometry",
"may",
"be",
"added",
";",
"the",
"constituent",
"*",
"linework",
"wil... | def add(self, geoms):
"""
* Adds a collection of Geometries to be processed.
* May be called multiple times.
*
* Any dimension of Geometry may be added; the constituent
* linework will be extracted.
"""
try:
iter(geoms)
except TypeError:
return self.addGeometry(geoms)
pass
for geom in geoms:
self.addGeometry(geom) | [
"def",
"add",
"(",
"self",
",",
"geoms",
")",
":",
"try",
":",
"iter",
"(",
"geoms",
")",
"except",
"TypeError",
":",
"return",
"self",
".",
"addGeometry",
"(",
"geoms",
")",
"pass",
"for",
"geom",
"in",
"geoms",
":",
"self",
".",
"addGeometry",
"(",... | https://github.com/s-leger/archipack/blob/5a6243bf1edf08a6b429661ce291dacb551e5f8a/pygeos/op_linemerge.py#L697-L712 | ||
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/setuptools/command/py36compat.py | python | sdist_add_defaults._add_defaults_c_libs | (self) | [] | def _add_defaults_c_libs(self):
if self.distribution.has_c_libraries():
build_clib = self.get_finalized_command('build_clib')
self.filelist.extend(build_clib.get_source_files()) | [
"def",
"_add_defaults_c_libs",
"(",
"self",
")",
":",
"if",
"self",
".",
"distribution",
".",
"has_c_libraries",
"(",
")",
":",
"build_clib",
"=",
"self",
".",
"get_finalized_command",
"(",
"'build_clib'",
")",
"self",
".",
"filelist",
".",
"extend",
"(",
"b... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/setuptools/command/py36compat.py#L122-L125 | ||||
GoogleCloudPlatform/ml-on-gcp | ffd88931674e08ef6b0b20de27700ed1da61772c | example_zoo/tensorflow/probability/vq_vae/trainer/vq_vae.py | python | build_input_pipeline | (data_dir, batch_size, heldout_size, mnist_type) | return images, labels, handle, training_iterator, heldout_iterator | Builds an Iterator switching between train and heldout data. | Builds an Iterator switching between train and heldout data. | [
"Builds",
"an",
"Iterator",
"switching",
"between",
"train",
"and",
"heldout",
"data",
"."
] | def build_input_pipeline(data_dir, batch_size, heldout_size, mnist_type):
"""Builds an Iterator switching between train and heldout data."""
# Build an iterator over training batches.
if mnist_type in [MnistType.FAKE_DATA, MnistType.THRESHOLD]:
if mnist_type == MnistType.FAKE_DATA:
mnist_data = build_fake_data()
else:
mnist_data = mnist.read_data_sets(data_dir)
training_dataset = tf.data.Dataset.from_tensor_slices(
(mnist_data.train.images, np.int32(mnist_data.train.labels)))
heldout_dataset = tf.data.Dataset.from_tensor_slices(
(mnist_data.validation.images,
np.int32(mnist_data.validation.labels)))
elif mnist_type == MnistType.BERNOULLI:
training_dataset = load_bernoulli_mnist_dataset(data_dir, "train")
heldout_dataset = load_bernoulli_mnist_dataset(data_dir, "valid")
else:
raise ValueError("Unknown MNIST type.")
training_batches = training_dataset.repeat().batch(batch_size)
training_iterator = tf.compat.v1.data.make_one_shot_iterator(training_batches)
# Build a iterator over the heldout set with batch_size=heldout_size,
# i.e., return the entire heldout set as a constant.
heldout_frozen = (heldout_dataset.take(heldout_size).
repeat().batch(heldout_size))
heldout_iterator = tf.compat.v1.data.make_one_shot_iterator(heldout_frozen)
# Combine these into a feedable iterator that can switch between training
# and validation inputs.
handle = tf.compat.v1.placeholder(tf.string, shape=[])
feedable_iterator = tf.compat.v1.data.Iterator.from_string_handle(
handle, training_batches.output_types, training_batches.output_shapes)
images, labels = feedable_iterator.get_next()
# Reshape as a pixel image and binarize pixels.
images = tf.reshape(images, shape=[-1] + IMAGE_SHAPE)
if mnist_type in [MnistType.FAKE_DATA, MnistType.THRESHOLD]:
images = tf.cast(images > 0.5, dtype=tf.int32)
return images, labels, handle, training_iterator, heldout_iterator | [
"def",
"build_input_pipeline",
"(",
"data_dir",
",",
"batch_size",
",",
"heldout_size",
",",
"mnist_type",
")",
":",
"# Build an iterator over training batches.",
"if",
"mnist_type",
"in",
"[",
"MnistType",
".",
"FAKE_DATA",
",",
"MnistType",
".",
"THRESHOLD",
"]",
... | https://github.com/GoogleCloudPlatform/ml-on-gcp/blob/ffd88931674e08ef6b0b20de27700ed1da61772c/example_zoo/tensorflow/probability/vq_vae/trainer/vq_vae.py#L406-L445 | |
YudeWang/deeplabv3plus-pytorch | 64843da0d9cb14dbb0cd2775afda9c9ea8fffe53 | lib/datasets/COCODataset.py | python | COCODataset._preprocess | (self, ids, ids_file) | return new_ids | [] | def _preprocess(self, ids, ids_file):
tbar = trange(len(ids))
new_ids = []
for i in tbar:
img_id = ids[i]
cocotarget = self.coco.loadAnns(self.coco.getAnnIds(imgIds=img_id))
img_metadata = self.coco.loadImgs(img_id)[0]
mask = self._gen_seg_mask(cocotarget, img_metadata['height'],
img_metadata['width'])
if(mask > 0).sum() > 1000:
new_ids.append(img_id)
tbar.set_description('Doing: {}/{}, got {} qualified images'.\
format(i, len(ids), len(new_ids)))
print('Found number of qualified images: ', len(new_ids))
with open(ids_file, 'wb') as f:
pickle.dump(new_ids, f)
return new_ids | [
"def",
"_preprocess",
"(",
"self",
",",
"ids",
",",
"ids_file",
")",
":",
"tbar",
"=",
"trange",
"(",
"len",
"(",
"ids",
")",
")",
"new_ids",
"=",
"[",
"]",
"for",
"i",
"in",
"tbar",
":",
"img_id",
"=",
"ids",
"[",
"i",
"]",
"cocotarget",
"=",
... | https://github.com/YudeWang/deeplabv3plus-pytorch/blob/64843da0d9cb14dbb0cd2775afda9c9ea8fffe53/lib/datasets/COCODataset.py#L174-L190 | |||
minio/minio-py | b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3 | minio/select.py | python | CSVInputSerialization.toxml | (self, element) | Convert to XML. | Convert to XML. | [
"Convert",
"to",
"XML",
"."
] | def toxml(self, element):
"""Convert to XML."""
super().toxml(element)
element = SubElement(element, "CSV")
if self._allow_quoted_record_delimiter is not None:
SubElement(
element,
"AllowQuotedRecordDelimiter",
self._allow_quoted_record_delimiter,
)
if self._comments is not None:
SubElement(element, "Comments", self._comments)
if self._field_delimiter is not None:
SubElement(element, "FieldDelimiter", self._field_delimiter)
if self._file_header_info is not None:
SubElement(element, "FileHeaderInfo", self._file_header_info)
if self._quote_character is not None:
SubElement(element, "QuoteCharacter", self._quote_character)
if self._quote_escape_character is not None:
SubElement(
element,
"QuoteEscapeCharacter",
self._quote_escape_character,
)
if self._record_delimiter is not None:
SubElement(element, "RecordDelimiter", self._record_delimiter) | [
"def",
"toxml",
"(",
"self",
",",
"element",
")",
":",
"super",
"(",
")",
".",
"toxml",
"(",
"element",
")",
"element",
"=",
"SubElement",
"(",
"element",
",",
"\"CSV\"",
")",
"if",
"self",
".",
"_allow_quoted_record_delimiter",
"is",
"not",
"None",
":",... | https://github.com/minio/minio-py/blob/b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3/minio/select.py#L100-L125 | ||
facebookresearch/mmf | fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f | mmf/datasets/builders/visual_entailment/dataset.py | python | VisualEntailmentDataset.load_item | (self, idx) | return current_sample | [] | def load_item(self, idx):
sample_info = self.annotation_db[idx]
current_sample = Sample()
processed_sentence = self.text_processor({"text": sample_info["sentence2"]})
current_sample.text = processed_sentence["text"]
if "input_ids" in processed_sentence:
current_sample.update(processed_sentence)
if self._use_features is True:
# Remove sentence id from end
identifier = sample_info["Flikr30kID"].split(".")[0]
# Load img0 and img1 features
sample_info["feature_path"] = "{}.npy".format(identifier)
features = self.features_db[idx]
if hasattr(self, "transformer_bbox_processor"):
features["image_info_0"] = self.transformer_bbox_processor(
features["image_info_0"]
)
current_sample.update(features)
else:
image_path = sample_info["Flikr30kID"]
current_sample.image = self.image_db.from_path(image_path)["images"][0]
label = LABEL_TO_INT_MAPPING[sample_info["gold_label"]]
current_sample.targets = torch.tensor(label, dtype=torch.long)
return current_sample | [
"def",
"load_item",
"(",
"self",
",",
"idx",
")",
":",
"sample_info",
"=",
"self",
".",
"annotation_db",
"[",
"idx",
"]",
"current_sample",
"=",
"Sample",
"(",
")",
"processed_sentence",
"=",
"self",
".",
"text_processor",
"(",
"{",
"\"text\"",
":",
"sampl... | https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/datasets/builders/visual_entailment/dataset.py#L23-L51 | |||
tribe29/checkmk | 6260f2512e159e311f426e16b84b19d0b8e9ad0c | cmk/gui/plugins/dashboard/utils.py | python | Dashlet._get_refresh_url | (self) | return makeuri_contextless(
request,
[
("name", self._dashboard_name),
("id", self._dashlet_id),
("mtime", self._dashboard["mtime"]),
],
filename="dashboard_dashlet.py",
) | Returns the URL to be used for loading the dashlet contents | Returns the URL to be used for loading the dashlet contents | [
"Returns",
"the",
"URL",
"to",
"be",
"used",
"for",
"loading",
"the",
"dashlet",
"contents"
] | def _get_refresh_url(self) -> str:
"""Returns the URL to be used for loading the dashlet contents"""
dashlet_url = self._get_dashlet_url_from_urlfunc()
if dashlet_url is not None:
return dashlet_url
if self._dashlet_spec.get("url"):
return self._dashlet_spec["url"]
return makeuri_contextless(
request,
[
("name", self._dashboard_name),
("id", self._dashlet_id),
("mtime", self._dashboard["mtime"]),
],
filename="dashboard_dashlet.py",
) | [
"def",
"_get_refresh_url",
"(",
"self",
")",
"->",
"str",
":",
"dashlet_url",
"=",
"self",
".",
"_get_dashlet_url_from_urlfunc",
"(",
")",
"if",
"dashlet_url",
"is",
"not",
"None",
":",
"return",
"dashlet_url",
"if",
"self",
".",
"_dashlet_spec",
".",
"get",
... | https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/plugins/dashboard/utils.py#L430-L447 | |
biocore/qiime | 76d633c0389671e93febbe1338b5ded658eba31f | qiime/relatedness_library.py | python | reduce_mtx | (distmat, indices) | return distmat.take(indices, 0).take(indices, 1) | Returns rows,cols of distmat where rows,cols=indices. | Returns rows,cols of distmat where rows,cols=indices. | [
"Returns",
"rows",
"cols",
"of",
"distmat",
"where",
"rows",
"cols",
"=",
"indices",
"."
] | def reduce_mtx(distmat, indices):
"""Returns rows,cols of distmat where rows,cols=indices."""
return distmat.take(indices, 0).take(indices, 1) | [
"def",
"reduce_mtx",
"(",
"distmat",
",",
"indices",
")",
":",
"return",
"distmat",
".",
"take",
"(",
"indices",
",",
"0",
")",
".",
"take",
"(",
"indices",
",",
"1",
")"
] | https://github.com/biocore/qiime/blob/76d633c0389671e93febbe1338b5ded658eba31f/qiime/relatedness_library.py#L66-L68 | |
QuantFans/quantdigger | 8b6c436509e7dfe63798300c0e31ea04eace9779 | quantdigger/event/eventengine.py | python | QueueEventEngine.start | (self) | 引擎启动 | 引擎启动 | [
"引擎启动"
] | def start(self):
"""引擎启动"""
EventEngine.start(self)
self._thrd.start() | [
"def",
"start",
"(",
"self",
")",
":",
"EventEngine",
".",
"start",
"(",
"self",
")",
"self",
".",
"_thrd",
".",
"start",
"(",
")"
] | https://github.com/QuantFans/quantdigger/blob/8b6c436509e7dfe63798300c0e31ea04eace9779/quantdigger/event/eventengine.py#L148-L151 | ||
eladhoffer/quantized.pytorch | e09c447a50a6a4c7dabf6176f20c931422aefd67 | models/resnet_quantized_float_bn.py | python | conv3x3 | (in_planes, out_planes, stride=1) | return QConv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False, num_bits=NUM_BITS, num_bits_weight=NUM_BITS_WEIGHT, num_bits_grad=NUM_BITS_GRAD) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return QConv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False, num_bits=NUM_BITS, num_bits_weight=NUM_BITS_WEIGHT, num_bits_grad=NUM_BITS_GRAD) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"QConv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
... | https://github.com/eladhoffer/quantized.pytorch/blob/e09c447a50a6a4c7dabf6176f20c931422aefd67/models/resnet_quantized_float_bn.py#L12-L15 | |
Yelp/mysql_streamer | 568b807458ef93f1adce56f89665bce5a6e3f8f5 | replication_handler/config.py | python | EnvConfig.schema_tracker_cluster | (self) | return staticconf.get('schema_tracker_cluster').value | serves as the key to identify the tracker database in topology.yaml | serves as the key to identify the tracker database in topology.yaml | [
"serves",
"as",
"the",
"key",
"to",
"identify",
"the",
"tracker",
"database",
"in",
"topology",
".",
"yaml"
] | def schema_tracker_cluster(self):
"""serves as the key to identify the tracker database in topology.yaml
"""
return staticconf.get('schema_tracker_cluster').value | [
"def",
"schema_tracker_cluster",
"(",
"self",
")",
":",
"return",
"staticconf",
".",
"get",
"(",
"'schema_tracker_cluster'",
")",
".",
"value"
] | https://github.com/Yelp/mysql_streamer/blob/568b807458ef93f1adce56f89665bce5a6e3f8f5/replication_handler/config.py#L98-L101 | |
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/waas/waas_client_composite_operations.py | python | WaasClientCompositeOperations.update_custom_protection_rule_and_wait_for_state | (self, custom_protection_rule_id, update_custom_protection_rule_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}) | Calls :py:func:`~oci.waas.WaasClient.update_custom_protection_rule` and waits for the :py:class:`~oci.waas.models.CustomProtectionRule` acted upon
to enter the given state(s).
:param str custom_protection_rule_id: (required)
The `OCID`__ of the custom protection rule. This number is generated when the custom protection rule is added to the compartment.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param oci.waas.models.UpdateCustomProtectionRuleDetails update_custom_protection_rule_details: (required)
The details of the custom protection rule to update.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.waas.models.CustomProtectionRule.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.waas.WaasClient.update_custom_protection_rule`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait | Calls :py:func:`~oci.waas.WaasClient.update_custom_protection_rule` and waits for the :py:class:`~oci.waas.models.CustomProtectionRule` acted upon
to enter the given state(s). | [
"Calls",
":",
"py",
":",
"func",
":",
"~oci",
".",
"waas",
".",
"WaasClient",
".",
"update_custom_protection_rule",
"and",
"waits",
"for",
"the",
":",
"py",
":",
"class",
":",
"~oci",
".",
"waas",
".",
"models",
".",
"CustomProtectionRule",
"acted",
"upon"... | def update_custom_protection_rule_and_wait_for_state(self, custom_protection_rule_id, update_custom_protection_rule_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.waas.WaasClient.update_custom_protection_rule` and waits for the :py:class:`~oci.waas.models.CustomProtectionRule` acted upon
to enter the given state(s).
:param str custom_protection_rule_id: (required)
The `OCID`__ of the custom protection rule. This number is generated when the custom protection rule is added to the compartment.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param oci.waas.models.UpdateCustomProtectionRuleDetails update_custom_protection_rule_details: (required)
The details of the custom protection rule to update.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.waas.models.CustomProtectionRule.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.waas.WaasClient.update_custom_protection_rule`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_custom_protection_rule(custom_protection_rule_id, update_custom_protection_rule_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_custom_protection_rule(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) | [
"def",
"update_custom_protection_rule_and_wait_for_state",
"(",
"self",
",",
"custom_protection_rule_id",
",",
"update_custom_protection_rule_details",
",",
"wait_for_states",
"=",
"[",
"]",
",",
"operation_kwargs",
"=",
"{",
"}",
",",
"waiter_kwargs",
"=",
"{",
"}",
")... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/waas/waas_client_composite_operations.py#L662-L703 | ||
shahar603/SpaceXtract | fe8a30b9f5cf1d2bee83fa1df214081c34aeb283 | src/Plotting scripts/plot_analysed_telemetry.py | python | potential_energy | (altitude) | return 4*10**14/(6.375*10**6) - 4*10**14/(1000*altitude+6.375*10**6) | [] | def potential_energy(altitude):
return 4*10**14/(6.375*10**6) - 4*10**14/(1000*altitude+6.375*10**6) | [
"def",
"potential_energy",
"(",
"altitude",
")",
":",
"return",
"4",
"*",
"10",
"**",
"14",
"/",
"(",
"6.375",
"*",
"10",
"**",
"6",
")",
"-",
"4",
"*",
"10",
"**",
"14",
"/",
"(",
"1000",
"*",
"altitude",
"+",
"6.375",
"*",
"10",
"**",
"6",
... | https://github.com/shahar603/SpaceXtract/blob/fe8a30b9f5cf1d2bee83fa1df214081c34aeb283/src/Plotting scripts/plot_analysed_telemetry.py#L96-L97 | |||
owid/covid-19-data | 936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92 | scripts/src/cowidev/vax/incremental/united_arab_emirates.py | python | UnitedArabEmirates.pipeline | (self, ds: pd.Series) | return (
ds.pipe(self.pipe_calculate_boosters)
.pipe(self.pipe_location)
.pipe(self.pipe_vaccine)
.pipe(self.pipe_source)
) | [] | def pipeline(self, ds: pd.Series) -> pd.Series:
return (
ds.pipe(self.pipe_calculate_boosters)
.pipe(self.pipe_location)
.pipe(self.pipe_vaccine)
.pipe(self.pipe_source)
) | [
"def",
"pipeline",
"(",
"self",
",",
"ds",
":",
"pd",
".",
"Series",
")",
"->",
"pd",
".",
"Series",
":",
"return",
"(",
"ds",
".",
"pipe",
"(",
"self",
".",
"pipe_calculate_boosters",
")",
".",
"pipe",
"(",
"self",
".",
"pipe_location",
")",
".",
... | https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/incremental/united_arab_emirates.py#L88-L94 | |||
jeffkit/wechat | 95510106605e3870e81d7b2ea08ef7868b01d3bf | wechat/models.py | python | WxEmptyResponse.as_xml | (self) | return '' | [] | def as_xml(self):
return '' | [
"def",
"as_xml",
"(",
"self",
")",
":",
"return",
"''"
] | https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/models.py#L91-L92 | |||
NervanaSystems/ngraph-python | ac032c83c7152b615a9ad129d54d350f9d6a2986 | ngraph/frontends/caffe2/c2_importer/ops_unary.py | python | OpsUnary.NHWC2NCHW | (self, c2_op, inputs) | return Y | Returns data in NHWC format. | Returns data in NHWC format. | [
"Returns",
"data",
"in",
"NHWC",
"format",
"."
] | def NHWC2NCHW(self, c2_op, inputs):
""" Returns data in NHWC format. """
assert 1 == len(inputs)
X = inputs[0]
order = X.order if hasattr(X, 'order') else 'NHWC'
if 'NHWC' != order:
raise ValueError("NHWC2NCHW accepts only NHWC input format.")
Y = ng.axes_with_order(X, axes=ng.make_axes([X.axes[0], X.axes[3], X.axes[1], X.axes[2]]))
Y.order = 'NCHW'
return Y | [
"def",
"NHWC2NCHW",
"(",
"self",
",",
"c2_op",
",",
"inputs",
")",
":",
"assert",
"1",
"==",
"len",
"(",
"inputs",
")",
"X",
"=",
"inputs",
"[",
"0",
"]",
"order",
"=",
"X",
".",
"order",
"if",
"hasattr",
"(",
"X",
",",
"'order'",
")",
"else",
... | https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/frontends/caffe2/c2_importer/ops_unary.py#L127-L138 | |
DLR-RM/BlenderProc | e04e03f34b66702bbca45d1ac701599b6d764609 | blenderproc/python/modules/provider/getter/Texture.py | python | Texture.perform_and_condition_check | (and_condition, textures, used_textures_to_check=None) | return new_textures | Checks for all textures and if all given conditions are true, collects them in the return list.
:param and_condition: Given conditions. Type: dict.
:param textures: Textures, that are already in the return list. Type: list.
:param used_textures_to_check: Textures to perform the check on. Type: list. Default: all materials
:return: Textures that comply with given conditions. Type: list. | Checks for all textures and if all given conditions are true, collects them in the return list. | [
"Checks",
"for",
"all",
"textures",
"and",
"if",
"all",
"given",
"conditions",
"are",
"true",
"collects",
"them",
"in",
"the",
"return",
"list",
"."
] | def perform_and_condition_check(and_condition, textures, used_textures_to_check=None):
""" Checks for all textures and if all given conditions are true, collects them in the return list.
:param and_condition: Given conditions. Type: dict.
:param textures: Textures, that are already in the return list. Type: list.
:param used_textures_to_check: Textures to perform the check on. Type: list. Default: all materials
:return: Textures that comply with given conditions. Type: list.
"""
new_textures = []
if used_textures_to_check is None:
used_textures_to_check = get_all_textures()
for texture in used_textures_to_check:
if texture in new_textures or texture in textures:
continue
select_texture = True
for key, value in and_condition.items():
# check if the key is a requested custom property
requested_custom_property = False
#requested_custom_function = False
if key.startswith('cp_'):
requested_custom_property = True
key = key[3:]
if key.startswith('cf_'):
#requested_custom_function = True
#key = key[3:]
raise RuntimeError("Custom functions for texture objects are yet to be implemented!")
if hasattr(texture, key) and not requested_custom_property:
# check if the type of the value of attribute matches desired
if isinstance(getattr(texture, key), type(value)):
new_value = value
# if not, try to enforce some mathutils-specific type
else:
if isinstance(getattr(texture, key), mathutils.Vector):
new_value = mathutils.Vector(value)
elif isinstance(getattr(texture, key), mathutils.Euler):
new_value = mathutils.Euler(value)
elif isinstance(getattr(texture, key), mathutils.Color):
new_value = mathutils.Color(value)
# raise an exception if it is none of them
else:
raise Exception("Types are not matching: %s and %s !"
% (type(getattr(texture, key)), type(value)))
# or check for equality
if not ((isinstance(getattr(texture, key), str) and
re.fullmatch(value, getattr(texture, key)) is not None)
or getattr(texture, key) == new_value):
select_texture = False
break
# check if a custom property with this name exists
elif key in texture and requested_custom_property:
# check if the type of the value of such custom property matches desired
if isinstance(texture[key], type(value)) or (
isinstance(texture[key], int) and isinstance(value, bool)):
# if it is a string and if the whole string matches the given pattern
if not ((isinstance(texture[key], str) and re.fullmatch(value, texture[key]) is not None) or
texture[key] == value):
select_texture = False
break
else:
# raise an exception if not
raise Exception("Types are not matching: {} and {} !".format(type(texture[key]), type(value)))
else:
select_texture = False
break
if select_texture:
new_textures.append(texture)
return new_textures | [
"def",
"perform_and_condition_check",
"(",
"and_condition",
",",
"textures",
",",
"used_textures_to_check",
"=",
"None",
")",
":",
"new_textures",
"=",
"[",
"]",
"if",
"used_textures_to_check",
"is",
"None",
":",
"used_textures_to_check",
"=",
"get_all_textures",
"(",... | https://github.com/DLR-RM/BlenderProc/blob/e04e03f34b66702bbca45d1ac701599b6d764609/blenderproc/python/modules/provider/getter/Texture.py#L139-L209 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/widgets.py | python | LockDraw.available | (self, o) | return not self.locked() or self.isowner(o) | Return whether drawing is available to *o*. | Return whether drawing is available to *o*. | [
"Return",
"whether",
"drawing",
"is",
"available",
"to",
"*",
"o",
"*",
"."
] | def available(self, o):
"""Return whether drawing is available to *o*."""
return not self.locked() or self.isowner(o) | [
"def",
"available",
"(",
"self",
",",
"o",
")",
":",
"return",
"not",
"self",
".",
"locked",
"(",
")",
"or",
"self",
".",
"isowner",
"(",
"o",
")"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/widgets.py#L48-L50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.