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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
alisaifee/flask-limiter | fb47a0ad1af557af7274361226c2c3c04fc172f7 | versioneer.py | python | render | (pieces, style) | return {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
"date": pieces.get("date"),
} | Render the given version pieces into the requested style. | Render the given version pieces into the requested style. | [
"Render",
"the",
"given",
"version",
"pieces",
"into",
"the",
"requested",
"style",
"."
] | def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None,
}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
return {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
"date": pieces.get("date"),
} | [
"def",
"render",
"(",
"pieces",
",",
"style",
")",
":",
"if",
"pieces",
"[",
"\"error\"",
"]",
":",
"return",
"{",
"\"version\"",
":",
"\"unknown\"",
",",
"\"full-revisionid\"",
":",
"pieces",
".",
"get",
"(",
"\"long\"",
")",
",",
"\"dirty\"",
":",
"Non... | https://github.com/alisaifee/flask-limiter/blob/fb47a0ad1af557af7274361226c2c3c04fc172f7/versioneer.py#L1399-L1434 | |
Blizzard/heroprotocol | 3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c | heroprotocol/versions/protocol40322.py | python | decode_replay_attributes_events | (contents) | return attributes | Decodes and yields each attribute from the contents byte string. | Decodes and yields each attribute from the contents byte string. | [
"Decodes",
"and",
"yields",
"each",
"attribute",
"from",
"the",
"contents",
"byte",
"string",
"."
] | def decode_replay_attributes_events(contents):
"""Decodes and yields each attribute from the contents byte string."""
buffer = BitPackedBuffer(contents, 'little')
attributes = {}
if not buffer.done():
attributes['source'] = buffer.read_bits(8)
attributes['mapNamespace'] = buffer.read_bits(32)
_ = buffer.read_bits(32)
attributes['scopes'] = {}
while not buffer.done():
value = {}
value['namespace'] = buffer.read_bits(32)
value['attrid'] = attrid = buffer.read_bits(32)
scope = buffer.read_bits(8)
value['value'] = buffer.read_aligned_bytes(4)[::-1].strip(b'\x00')
if not scope in attributes['scopes']:
attributes['scopes'][scope] = {}
if not attrid in attributes['scopes'][scope]:
attributes['scopes'][scope][attrid] = []
attributes['scopes'][scope][attrid].append(value)
return attributes | [
"def",
"decode_replay_attributes_events",
"(",
"contents",
")",
":",
"buffer",
"=",
"BitPackedBuffer",
"(",
"contents",
",",
"'little'",
")",
"attributes",
"=",
"{",
"}",
"if",
"not",
"buffer",
".",
"done",
"(",
")",
":",
"attributes",
"[",
"'source'",
"]",
... | https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol40322.py#L464-L484 | |
radiac/django-tagulous | 90c6ee5ac54ef1127f2edcfac10c5ef3ab09e255 | tagulous/models/models.py | python | TagTreeModelQuerySet.with_ancestors | (self) | return self._clean().filter(path__in=set(paths)) | Add selected tags' ancestors to current queryset | Add selected tags' ancestors to current queryset | [
"Add",
"selected",
"tags",
"ancestors",
"to",
"current",
"queryset"
] | def with_ancestors(self):
"""
Add selected tags' ancestors to current queryset
"""
# Build list of all paths of all ancestors (and self)
paths = []
for path in self.values_list("path", flat=True):
parts = utils.split_tree_name(path)
paths += [path] + [
utils.join_tree_name(parts[:i]) # Join parts up to i (misses last)
for i in range(1, len(parts)) # Skip first (empty)
]
return self._clean().filter(path__in=set(paths)) | [
"def",
"with_ancestors",
"(",
"self",
")",
":",
"# Build list of all paths of all ancestors (and self)",
"paths",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"values_list",
"(",
"\"path\"",
",",
"flat",
"=",
"True",
")",
":",
"parts",
"=",
"utils",
".",
... | https://github.com/radiac/django-tagulous/blob/90c6ee5ac54ef1127f2edcfac10c5ef3ab09e255/tagulous/models/models.py#L497-L509 | |
tensorflow/model-analysis | e38c23ce76eff039548ce69e3160ed4d7984f2fc | tensorflow_model_analysis/metrics/metric_util.py | python | to_standard_metric_inputs | (
extracts: types.Extracts,
include_features: bool = False,
include_transformed_features: bool = False,
include_attributions: bool = False) | return metric_types.StandardMetricInputs(extracts) | Verifies extract keys and converts extracts to StandardMetricInputs. | Verifies extract keys and converts extracts to StandardMetricInputs. | [
"Verifies",
"extract",
"keys",
"and",
"converts",
"extracts",
"to",
"StandardMetricInputs",
"."
] | def to_standard_metric_inputs(
extracts: types.Extracts,
include_features: bool = False,
include_transformed_features: bool = False,
include_attributions: bool = False) -> metric_types.StandardMetricInputs:
"""Verifies extract keys and converts extracts to StandardMetricInputs."""
if constants.LABELS_KEY not in extracts:
raise ValueError(f'"{constants.LABELS_KEY}" key not found in extracts. '
'Check that the configuration is setup properly to '
'specify the name of label input and that the proper '
'extractor has been configured to extract the labels from '
'the inputs.')
if constants.PREDICTIONS_KEY not in extracts:
raise ValueError(f'"{constants.PREDICTIONS_KEY}" key not found in '
'extracts. Check that the proper extractor has been '
'configured to perform model inference.')
if include_features and constants.FEATURES_KEY not in extracts:
raise ValueError(f'"{constants.FEATURES_KEY}" key not found in extracts. '
'Check that the proper extractor has been configured to '
'extract the features from the inputs.')
if (include_transformed_features and
constants.TRANSFORMED_FEATURES_KEY not in extracts):
raise ValueError(f'"{constants.TRANSFORMED_FEATURES_KEY}" key not found in '
'extracts. Check that the proper extractor has been '
'configured to extract the transformed features from the '
'inputs.')
if (include_attributions and constants.ATTRIBUTIONS_KEY not in extracts):
raise ValueError(f'"{constants.ATTRIBUTIONS_KEY}" key not found in '
'extracts. Check that the proper extractor has been '
'configured to extract the attributions from the inputs.')
return metric_types.StandardMetricInputs(extracts) | [
"def",
"to_standard_metric_inputs",
"(",
"extracts",
":",
"types",
".",
"Extracts",
",",
"include_features",
":",
"bool",
"=",
"False",
",",
"include_transformed_features",
":",
"bool",
"=",
"False",
",",
"include_attributions",
":",
"bool",
"=",
"False",
")",
"... | https://github.com/tensorflow/model-analysis/blob/e38c23ce76eff039548ce69e3160ed4d7984f2fc/tensorflow_model_analysis/metrics/metric_util.py#L106-L136 | |
tox-dev/tox | 86a0383c0617ff1d1ea47a526211bedc415c9d95 | src/tox/config/__init__.py | python | ParseIni.handle_provision | (self, config, reader) | [] | def handle_provision(self, config, reader):
config.requires = reader.getlist("requires")
config.minversion = reader.getstring("minversion", None)
config.provision_tox_env = name = reader.getstring("provision_tox_env", ".tox")
min_version = "tox >= {}".format(config.minversion or Version(tox.__version__).public)
deps = self.ensure_requires_satisfied(config, config.requires, min_version)
if config.run_provision:
section_name = "testenv:{}".format(name)
if section_name not in self._cfg.sections:
self._cfg.sections[section_name] = {}
self._cfg.sections[section_name]["description"] = "meta tox"
env_config = self.make_envconfig(
name,
"{}{}".format(testenvprefix, name),
reader._subs,
config,
)
env_config.deps = deps
config.envconfigs[config.provision_tox_env] = env_config
raise tox.exception.MissingRequirement(config)
# if provisioning is not on, now we need do a strict argument evaluation
# raise on unknown args
self.config._parser.parse_cli(args=self.config.args, strict=True) | [
"def",
"handle_provision",
"(",
"self",
",",
"config",
",",
"reader",
")",
":",
"config",
".",
"requires",
"=",
"reader",
".",
"getlist",
"(",
"\"requires\"",
")",
"config",
".",
"minversion",
"=",
"reader",
".",
"getstring",
"(",
"\"minversion\"",
",",
"N... | https://github.com/tox-dev/tox/blob/86a0383c0617ff1d1ea47a526211bedc415c9d95/src/tox/config/__init__.py#L1318-L1340 | ||||
microsoft/nni | 31f11f51249660930824e888af0d4e022823285c | nni/retiarii/graph.py | python | Graph.fork | (self) | return self.model.fork().graphs[self.name] | Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model. | Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model. | [
"Fork",
"the",
"model",
"and",
"returns",
"corresponding",
"graph",
"in",
"new",
"model",
".",
"This",
"shortcut",
"might",
"be",
"helpful",
"because",
"many",
"algorithms",
"only",
"cares",
"about",
"stem",
"subgraph",
"instead",
"of",
"whole",
"model",
"."
] | def fork(self) -> 'Graph':
"""
Fork the model and returns corresponding graph in new model.
This shortcut might be helpful because many algorithms only cares about "stem" subgraph instead of whole model.
"""
return self.model.fork().graphs[self.name] | [
"def",
"fork",
"(",
"self",
")",
"->",
"'Graph'",
":",
"return",
"self",
".",
"model",
".",
"fork",
"(",
")",
".",
"graphs",
"[",
"self",
".",
"name",
"]"
] | https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/nni/retiarii/graph.py#L440-L445 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/networkx/algorithms/connectivity/connectivity.py | python | all_pairs_node_connectivity | (G, nbunch=None, flow_func=None) | return all_pairs | Compute node connectivity between all pairs of nodes of G.
Parameters
----------
G : NetworkX graph
Undirected graph
nbunch: container
Container of nodes. If provided node connectivity will be computed
only over pairs of nodes in nbunch.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
Returns
-------
all_pairs : dict
A dictionary with node connectivity between all pairs of nodes
in G, or in nbunch if provided.
See also
--------
:meth:`local_node_connectivity`
:meth:`edge_connectivity`
:meth:`local_edge_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path` | Compute node connectivity between all pairs of nodes of G. | [
"Compute",
"node",
"connectivity",
"between",
"all",
"pairs",
"of",
"nodes",
"of",
"G",
"."
] | def all_pairs_node_connectivity(G, nbunch=None, flow_func=None):
"""Compute node connectivity between all pairs of nodes of G.
Parameters
----------
G : NetworkX graph
Undirected graph
nbunch: container
Container of nodes. If provided node connectivity will be computed
only over pairs of nodes in nbunch.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
Returns
-------
all_pairs : dict
A dictionary with node connectivity between all pairs of nodes
in G, or in nbunch if provided.
See also
--------
:meth:`local_node_connectivity`
:meth:`edge_connectivity`
:meth:`local_edge_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
"""
if nbunch is None:
nbunch = G
else:
nbunch = set(nbunch)
directed = G.is_directed()
if directed:
iter_func = itertools.permutations
else:
iter_func = itertools.combinations
all_pairs = {n: {} for n in nbunch}
# Reuse auxiliary digraph and residual network
H = build_auxiliary_node_connectivity(G)
mapping = H.graph['mapping']
R = build_residual_network(H, 'capacity')
kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R)
for u, v in iter_func(nbunch, 2):
K = local_node_connectivity(G, u, v, **kwargs)
all_pairs[u][v] = K
if not directed:
all_pairs[v][u] = K
return all_pairs | [
"def",
"all_pairs_node_connectivity",
"(",
"G",
",",
"nbunch",
"=",
"None",
",",
"flow_func",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nbunch",
"=",
"G",
"else",
":",
"nbunch",
"=",
"set",
"(",
"nbunch",
")",
"directed",
"=",
"G",
"... | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/networkx/algorithms/connectivity/connectivity.py#L421-L485 | |
stephenmcd/mezzanine | e38ffc69f732000ce44b7ed5c9d0516d258b8af2 | mezzanine/core/models.py | python | Orderable.save | (self, *args, **kwargs) | Set the initial ordering value. | Set the initial ordering value. | [
"Set",
"the",
"initial",
"ordering",
"value",
"."
] | def save(self, *args, **kwargs):
"""
Set the initial ordering value.
"""
if self._order is None:
lookup = self.with_respect_to()
lookup["_order__isnull"] = False
concrete_model = base_concrete_model(Orderable, self)
self._order = concrete_model.objects.filter(**lookup).count()
super().save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_order",
"is",
"None",
":",
"lookup",
"=",
"self",
".",
"with_respect_to",
"(",
")",
"lookup",
"[",
"\"_order__isnull\"",
"]",
"=",
"False",
"concret... | https://github.com/stephenmcd/mezzanine/blob/e38ffc69f732000ce44b7ed5c9d0516d258b8af2/mezzanine/core/models.py#L478-L487 | ||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/cherrypy/lib/xmlrpcutil.py | python | _set_response | (body) | [] | def _set_response(body):
# The XML-RPC spec (http://www.xmlrpc.com/spec) says:
# "Unless there's a lower-level error, always return 200 OK."
# Since Python's xmlrpclib interprets a non-200 response
# as a "Protocol Error", we'll just return 200 every time.
response = cherrypy.response
response.status = '200 OK'
response.body = ntob(body, 'utf-8')
response.headers['Content-Type'] = 'text/xml'
response.headers['Content-Length'] = len(body) | [
"def",
"_set_response",
"(",
"body",
")",
":",
"# The XML-RPC spec (http://www.xmlrpc.com/spec) says:",
"# \"Unless there's a lower-level error, always return 200 OK.\"",
"# Since Python's xmlrpclib interprets a non-200 response",
"# as a \"Protocol Error\", we'll just return 200 every time.",
"... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/lib/xmlrpcutil.py#L33-L42 | ||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/setuptools/lib2to3_ex.py | python | Mixin2to3.run_2to3 | (self, files, doctests=False) | [] | def run_2to3(self, files, doctests=False):
# See of the distribution option has been set, otherwise check the
# setuptools default.
if self.distribution.use_2to3 is not True:
return
if not files:
return
log.info("Fixing " + " ".join(files))
self.__build_fixer_names()
self.__exclude_fixers()
if doctests:
if setuptools.run_2to3_on_doctests:
r = DistutilsRefactoringTool(self.fixer_names)
r.refactor(files, write=True, doctests_only=True)
else:
_Mixin2to3.run_2to3(self, files) | [
"def",
"run_2to3",
"(",
"self",
",",
"files",
",",
"doctests",
"=",
"False",
")",
":",
"# See of the distribution option has been set, otherwise check the",
"# setuptools default.",
"if",
"self",
".",
"distribution",
".",
"use_2to3",
"is",
"not",
"True",
":",
"return"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/setuptools/lib2to3_ex.py#L29-L44 | ||||
hacktoolkit/django-htk | 902f3780630f1308aa97a70b9b62a5682239ff2d | lib/fitbit/api.py | python | FitbitAPI.get_body_fat_logs_past_day | (self) | return fat_logs | Get Body Fat logs for the past day | Get Body Fat logs for the past day | [
"Get",
"Body",
"Fat",
"logs",
"for",
"the",
"past",
"day"
] | def get_body_fat_logs_past_day(self):
"""Get Body Fat logs for the past day
"""
resource_args = (
utcnow().strftime('%Y-%m-%d'),
'1d',
)
response = self.get('fat', resource_args=resource_args)
if response.status_code == 200:
fat_logs = response.json()['fat']
fat_logs = fat_logs[::-1]
else:
fat_logs = None
return fat_logs | [
"def",
"get_body_fat_logs_past_day",
"(",
"self",
")",
":",
"resource_args",
"=",
"(",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
",",
"'1d'",
",",
")",
"response",
"=",
"self",
".",
"get",
"(",
"'fat'",
",",
"resource_args",
"=",
"reso... | https://github.com/hacktoolkit/django-htk/blob/902f3780630f1308aa97a70b9b62a5682239ff2d/lib/fitbit/api.py#L180-L193 | |
netaddr/netaddr | e84688f7034b7a88ac00a676359be57eb7a78184 | netaddr/strategy/eui48.py | python | valid_str | (addr) | return False | :param addr: An IEEE EUI-48 (MAC) address in string form.
:return: ``True`` if MAC address string is valid, ``False`` otherwise. | :param addr: An IEEE EUI-48 (MAC) address in string form. | [
":",
"param",
"addr",
":",
"An",
"IEEE",
"EUI",
"-",
"48",
"(",
"MAC",
")",
"address",
"in",
"string",
"form",
"."
] | def valid_str(addr):
"""
:param addr: An IEEE EUI-48 (MAC) address in string form.
:return: ``True`` if MAC address string is valid, ``False`` otherwise.
"""
for regexp in RE_MAC_FORMATS:
try:
match_result = regexp.findall(addr)
if len(match_result) != 0:
return True
except TypeError:
pass
return False | [
"def",
"valid_str",
"(",
"addr",
")",
":",
"for",
"regexp",
"in",
"RE_MAC_FORMATS",
":",
"try",
":",
"match_result",
"=",
"regexp",
".",
"findall",
"(",
"addr",
")",
"if",
"len",
"(",
"match_result",
")",
"!=",
"0",
":",
"return",
"True",
"except",
"Ty... | https://github.com/netaddr/netaddr/blob/e84688f7034b7a88ac00a676359be57eb7a78184/netaddr/strategy/eui48.py#L138-L152 | |
chengzhengxin/groupsoftmax-simpledet | 3f63a00998c57fee25241cf43a2e8600893ea462 | core/detection_input.py | python | ConvertImageFromHwcToChw.__init__ | (self) | [] | def __init__(self):
super().__init__() | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")"
] | https://github.com/chengzhengxin/groupsoftmax-simpledet/blob/3f63a00998c57fee25241cf43a2e8600893ea462/core/detection_input.py#L364-L365 | ||||
PySimpleGUI/PySimpleGUI | 6c0d1fb54f493d45e90180b322fbbe70f7a5af3c | DemoPrograms/Demo_Desktop_Widget_Count_To_A_Goal.py | python | Gauge.add | (number1, number2) | return number1 + number1 | Add two number
: Parameter
number1 - number to add.
numeer2 - number to add.
: Return
Addition result for number1 and number2. | Add two number
: Parameter
number1 - number to add.
numeer2 - number to add.
: Return
Addition result for number1 and number2. | [
"Add",
"two",
"number",
":",
"Parameter",
"number1",
"-",
"number",
"to",
"add",
".",
"numeer2",
"-",
"number",
"to",
"add",
".",
":",
"Return",
"Addition",
"result",
"for",
"number1",
"and",
"number2",
"."
] | def add(number1, number2):
"""
Add two number
: Parameter
number1 - number to add.
numeer2 - number to add.
: Return
Addition result for number1 and number2.
"""
return number1 + number1 | [
"def",
"add",
"(",
"number1",
",",
"number2",
")",
":",
"return",
"number1",
"+",
"number1"
] | https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_Desktop_Widget_Count_To_A_Goal.py#L44-L53 | |
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/iohub/client/eyetracker/validation/posgrid.py | python | PositionGrid.__init__ | (self,
bounds=None,
shape=None, # Defines the number of columns and rows of
# positions needed. If shape is an array of
# two elements, it defines the col,row shape
# for position layout. Position count will
# equal rows*cols. If shape is a single
# int, the position grid col,row shape will
# be shape x shape.
posCount=None, # Defines the number of positions to create
# without any col,row position constraint.
leftMargin=None, # Specify the minimum valid horz position.
rightMargin=None, # Limit horz positions to be < max horz
# position minus rightMargin.
topMargin=None, # Limit vert positions to be < max vert
# position minus topMargin.
bottomMargin=None, # Specify the minimum valid vert position.
scale=1.0, # Scale can be one or two numbers, each
# between 0.0 and 1.0. If a tuple is
# provided, it represents the horz, vert
# scale to be applied to window width,
# height. If a single number is
# given, the same scale will be applied to
# both window width and height. The scaled
# window size is centered on the original
# window size to define valid position area.
posList=None, # Provide an existing list of (x,y)
# positions. If posList is provided, the
# shape, posCount, margin and scale arg's
# are ignored.
noiseStd=None, # Add a random shift to each position based
# on a normal distribution with mean = 0.0
# and sigma equal to noiseStd. Specify
# value based on units being used.
firstposindex=0, # Specify which position in the position
# list should be displayed first. This
# position is not effected by randomization.
repeatFirstPos=False # If the first position in the list should
# be provided as the last position as well,
# set to True. In this case, the number of
# positions returned will be position
# count + 1. False indicated the first
# position should not be repeated.
) | PositionGrid provides a flexible way to generate a set of x,y position
values within the boundaries of the psychopy window object provided.
The class provides a set of arguments that represent commonly needed
constraints when creating a target position list, supporting a
variety of position arrangements.
PositionGrid supports the len() function, and returns the number of
positions generated based on the supplied parameters. If repeatFirstPos
is true, len(posgrid) == number of unique positions + 1 (a repeat of the
first position value).
PositionGrid is a generator, so the normal way to access the positions from
the class is to use a for loop or with statement:
posgrid = PositionGrid(....)
for pos in posgrid:
# do something cool with the pos
print(pos)
:param bounds:
:param shape:
:param posCount:
:param leftMargin:
:param rightMargin:
:param topMargin:
:param bottomMargin:
:param scale:
:param posList:
:param noiseStd:
:param firstposindex:
:param repeatFirstPos: | PositionGrid provides a flexible way to generate a set of x,y position
values within the boundaries of the psychopy window object provided. | [
"PositionGrid",
"provides",
"a",
"flexible",
"way",
"to",
"generate",
"a",
"set",
"of",
"x",
"y",
"position",
"values",
"within",
"the",
"boundaries",
"of",
"the",
"psychopy",
"window",
"object",
"provided",
"."
] | def __init__(self,
bounds=None,
shape=None, # Defines the number of columns and rows of
# positions needed. If shape is an array of
# two elements, it defines the col,row shape
# for position layout. Position count will
# equal rows*cols. If shape is a single
# int, the position grid col,row shape will
# be shape x shape.
posCount=None, # Defines the number of positions to create
# without any col,row position constraint.
leftMargin=None, # Specify the minimum valid horz position.
rightMargin=None, # Limit horz positions to be < max horz
# position minus rightMargin.
topMargin=None, # Limit vert positions to be < max vert
# position minus topMargin.
bottomMargin=None, # Specify the minimum valid vert position.
scale=1.0, # Scale can be one or two numbers, each
# between 0.0 and 1.0. If a tuple is
# provided, it represents the horz, vert
# scale to be applied to window width,
# height. If a single number is
# given, the same scale will be applied to
# both window width and height. The scaled
# window size is centered on the original
# window size to define valid position area.
posList=None, # Provide an existing list of (x,y)
# positions. If posList is provided, the
# shape, posCount, margin and scale arg's
# are ignored.
noiseStd=None, # Add a random shift to each position based
# on a normal distribution with mean = 0.0
# and sigma equal to noiseStd. Specify
# value based on units being used.
firstposindex=0, # Specify which position in the position
# list should be displayed first. This
# position is not effected by randomization.
repeatFirstPos=False # If the first position in the list should
# be provided as the last position as well,
# set to True. In this case, the number of
# positions returned will be position
# count + 1. False indicated the first
# position should not be repeated.
):
"""
PositionGrid provides a flexible way to generate a set of x,y position
values within the boundaries of the psychopy window object provided.
The class provides a set of arguments that represent commonly needed
constraints when creating a target position list, supporting a
variety of position arrangements.
PositionGrid supports the len() function, and returns the number of
positions generated based on the supplied parameters. If repeatFirstPos
is true, len(posgrid) == number of unique positions + 1 (a repeat of the
first position value).
PositionGrid is a generator, so the normal way to access the positions from
the class is to use a for loop or with statement:
posgrid = PositionGrid(....)
for pos in posgrid:
# do something cool with the pos
print(pos)
:param bounds:
:param shape:
:param posCount:
:param leftMargin:
:param rightMargin:
:param topMargin:
:param bottomMargin:
:param scale:
:param posList:
:param noiseStd:
:param firstposindex:
:param repeatFirstPos:
"""
self.posIndex = 0
self.positions = None
self.posOffsets = None
self.bounds = bounds
if self.bounds is None:
self.bounds = ioHubConnection.getActiveConnection().devices.display.getCoordBounds()
winSize = self.bounds[2] - self.bounds[0], self.bounds[3] - self.bounds[1]
self.firstposindex = firstposindex
self.repeatfirstpos = repeatFirstPos
self.horzStd, self.vertStd = None, None
if noiseStd:
if hasattr(noiseStd, '__len__'):
self.horzStd, self.vertStd = noiseStd
else:
self.horzStd, self.vertStd = noiseStd, noiseStd
horzScale, vertScale = None, None
if scale:
if hasattr(scale, '__len__'):
horzScale, vertScale = scale
else:
horzScale, vertScale = scale, scale
rowCount, colCount = None, None
if shape:
if hasattr(shape, '__len__'):
colCount, rowCount = shape
else:
rowCount, colCount = shape, shape
if posList:
# User has provided the target positions, use posList to set
# self.positions as array of x,y pairs.
if len(posList) == 2 and len(posList[0]) != 2 and len(posList[0]) == len(posList[1]):
# positions were provided in ((x1,x2,..,xn),(y1,y2,..,yn))
# format
self.positions = np.column_stack((posList[0], posList[1]))
elif len(posList[0]) == 2:
self.positions = np.asarray(posList)
else:
raise ValueError('PositionGrid posList kwarg must be in ((x1,y1),(x2,y2),..,(xn,yn))'
' or ((x1,x2,..,xn),(y1,y2,..,yn)) format')
if self.positions is None and (posCount or (rowCount and colCount)):
# Auto generate position list based on criteria
# provided.
if winSize is not None:
pixw, pixh = winSize
xmin = 0.0
xmax = 1.0
ymin = 0.0
ymax = 1.0
if leftMargin:
if leftMargin < pixw:
xmin = leftMargin / pixw
else:
raise ValueError('PositionGrid leftMargin kwarg must be < winSize[0]')
if rightMargin:
if rightMargin < pixw:
xmax = 1.0 - rightMargin / pixw
else:
raise ValueError('PositionGrid rightMargin kwarg must be < winSize[0]')
if topMargin:
if topMargin < pixh:
ymax = 1.0 - topMargin / pixh
else:
raise ValueError('PositionGrid topMargin kwarg must be < winSize[1]')
if bottomMargin:
if bottomMargin < pixh:
ymin = bottomMargin / pixh
else:
raise ValueError('PositionGrid bottomMargin kwarg must be < winSize[1]')
if horzScale:
if 0.0 < horzScale <= 1.0:
xmin += (1.0 - horzScale) / 2.0
xmax -= (1.0 - horzScale) / 2.0
else:
raise ValueError('PositionGrid horzScale kwarg must be 0.0 > horzScale <= 1.0')
if vertScale:
if 0.0 < vertScale <= 1.0:
ymin += (1.0 - vertScale) / 2.0
ymax -= (1.0 - vertScale) / 2.0
else:
raise ValueError('PositionGrid vertScale kwarg must be 0.0 > vertScale <= 1.0')
if posCount:
colCount = int(np.sqrt(posCount))
rowCount = colCount
xps = np.random.uniform(xmin, xmax, colCount) * pixw - pixw / 2.0
yps = np.random.uniform(ymin, ymax, rowCount) * pixh - pixh / 2.0
else:
xps = np.linspace(xmin, xmax, colCount) * pixw - pixw / 2.0
yps = np.linspace(ymin, ymax, rowCount) * pixh - pixh / 2.0
xps, yps = np.meshgrid(xps, yps)
self.positions = np.column_stack((xps.flatten(), yps.flatten()))
else:
raise ValueError('PositionGrid posCount kwarg also requires winSize to be provided.')
if self.positions is None:
raise AttributeError('PositionGrid is unable to generate positions based on the provided kwargs.')
if self.firstposindex and self.firstposindex > 0:
fpos = self.positions[self.firstposindex]
self.positions = np.delete(self.positions, self.firstposindex, 0)
self.positions = np.insert(self.positions, 0, fpos, 0)
self._generatePosOffsets() | [
"def",
"__init__",
"(",
"self",
",",
"bounds",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"# Defines the number of columns and rows of",
"# positions needed. If shape is an array of",
"# two elements, it defines the col,row shape",
"# for position layout. Position count will",
"#... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/iohub/client/eyetracker/validation/posgrid.py#L11-L203 | ||
darkonhub/darkon | 5f35a12585f5edb43ab1da5edd8d05243da65a64 | darkon/influence/influence.py | python | Influence.upweighting_influence_batch | (self, sess, test_indices, test_batch_size, approx_params,
train_batch_size, train_iterations, subsamples=-1, force_refresh=False) | return score | Iteratively calculate influence scores for training data sampled by batch sampler
Negative value indicates bad effect on the test loss
Parameters
----------
sess: tf.Session
Tensorflow session
test_indices: list
Test samples to be used. Influence on these samples are calculated.
test_batch_size: int
batch size for test samples
approx_params: dict
Parameters for inverse hessian vector product approximation
Default:
{'scale': 1e4,
'damping': 0.01,
'num_repeats': 1,
'recursion_batch_size': 10,
'recursion_depth': 10000}
train_batch_size: int
Batch size of training samples
train_iterations: int
Number of iterations
subsamples: int
Number of training samples in a batch to be calculated.
If -1, all samples are calculated (no subsampling).
Default: -1
force_refresh: bool
If False, it calculates only when test samples and parameters are changed.
Default: False
Returns
-------
numpy.ndarray | Iteratively calculate influence scores for training data sampled by batch sampler
Negative value indicates bad effect on the test loss | [
"Iteratively",
"calculate",
"influence",
"scores",
"for",
"training",
"data",
"sampled",
"by",
"batch",
"sampler",
"Negative",
"value",
"indicates",
"bad",
"effect",
"on",
"the",
"test",
"loss"
] | def upweighting_influence_batch(self, sess, test_indices, test_batch_size, approx_params,
train_batch_size, train_iterations, subsamples=-1, force_refresh=False):
""" Iteratively calculate influence scores for training data sampled by batch sampler
Negative value indicates bad effect on the test loss
Parameters
----------
sess: tf.Session
Tensorflow session
test_indices: list
Test samples to be used. Influence on these samples are calculated.
test_batch_size: int
batch size for test samples
approx_params: dict
Parameters for inverse hessian vector product approximation
Default:
{'scale': 1e4,
'damping': 0.01,
'num_repeats': 1,
'recursion_batch_size': 10,
'recursion_depth': 10000}
train_batch_size: int
Batch size of training samples
train_iterations: int
Number of iterations
subsamples: int
Number of training samples in a batch to be calculated.
If -1, all samples are calculated (no subsampling).
Default: -1
force_refresh: bool
If False, it calculates only when test samples and parameters are changed.
Default: False
Returns
-------
numpy.ndarray
"""
self._prepare(sess, test_indices, test_batch_size, approx_params, force_refresh)
self.feeder.reset()
score = self._grad_diffs_all(sess, train_batch_size, train_iterations, subsamples)
logger.info('Multiplying by %s train examples' % score.size)
return score | [
"def",
"upweighting_influence_batch",
"(",
"self",
",",
"sess",
",",
"test_indices",
",",
"test_batch_size",
",",
"approx_params",
",",
"train_batch_size",
",",
"train_iterations",
",",
"subsamples",
"=",
"-",
"1",
",",
"force_refresh",
"=",
"False",
")",
":",
"... | https://github.com/darkonhub/darkon/blob/5f35a12585f5edb43ab1da5edd8d05243da65a64/darkon/influence/influence.py#L181-L224 | |
google/clusterfuzz | f358af24f414daa17a3649b143e71ea71871ef59 | src/appengine/handlers/cron/load_bigquery_stats.py | python | Handler._create_table_if_needed | (self, bigquery, dataset_id, table_id) | return self._execute_insert_request(table_insert) | Create a new table if needed. | Create a new table if needed. | [
"Create",
"a",
"new",
"table",
"if",
"needed",
"."
] | def _create_table_if_needed(self, bigquery, dataset_id, table_id):
"""Create a new table if needed."""
project_id = utils.get_application_id()
table_body = {
'tableReference': {
'datasetId': dataset_id,
'projectId': project_id,
'tableId': table_id,
},
'timePartitioning': {
'type': 'DAY',
},
}
table_insert = bigquery.tables().insert(
projectId=project_id, datasetId=dataset_id, body=table_body)
return self._execute_insert_request(table_insert) | [
"def",
"_create_table_if_needed",
"(",
"self",
",",
"bigquery",
",",
"dataset_id",
",",
"table_id",
")",
":",
"project_id",
"=",
"utils",
".",
"get_application_id",
"(",
")",
"table_body",
"=",
"{",
"'tableReference'",
":",
"{",
"'datasetId'",
":",
"dataset_id",... | https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/appengine/handlers/cron/load_bigquery_stats.py#L80-L96 | |
atlassian-api/atlassian-python-api | 6d8545a790c3aae10b75bdc225fb5c3a0aee44db | atlassian/jira.py | python | Jira.delete_version | (self, version, moved_fixed=None, move_affected=None) | return self.delete("rest/api/2/version/{}".format(version), data=payload) | Delete version from the project
:param int version: the version id to delete
:param int moved_fixed: The version to set fixVersion to on issues where the deleted version is the fix version.
If null then the fixVersion is removed.
:param int move_affected: The version to set affectedVersion to on issues where the deleted version is
the affected version, If null then the affectedVersion is removed.
:return: | Delete version from the project
:param int version: the version id to delete
:param int moved_fixed: The version to set fixVersion to on issues where the deleted version is the fix version.
If null then the fixVersion is removed.
:param int move_affected: The version to set affectedVersion to on issues where the deleted version is
the affected version, If null then the affectedVersion is removed.
:return: | [
"Delete",
"version",
"from",
"the",
"project",
":",
"param",
"int",
"version",
":",
"the",
"version",
"id",
"to",
"delete",
":",
"param",
"int",
"moved_fixed",
":",
"The",
"version",
"to",
"set",
"fixVersion",
"to",
"on",
"issues",
"where",
"the",
"deleted... | def delete_version(self, version, moved_fixed=None, move_affected=None):
"""
Delete version from the project
:param int version: the version id to delete
:param int moved_fixed: The version to set fixVersion to on issues where the deleted version is the fix version.
If null then the fixVersion is removed.
:param int move_affected: The version to set affectedVersion to on issues where the deleted version is
the affected version, If null then the affectedVersion is removed.
:return:
"""
payload = {"moveFixIssuesTo": moved_fixed, "moveAffectedIssuesTo": move_affected}
return self.delete("rest/api/2/version/{}".format(version), data=payload) | [
"def",
"delete_version",
"(",
"self",
",",
"version",
",",
"moved_fixed",
"=",
"None",
",",
"move_affected",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"moveFixIssuesTo\"",
":",
"moved_fixed",
",",
"\"moveAffectedIssuesTo\"",
":",
"move_affected",
"}",
"retur... | https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/jira.py#L1909-L1920 | |
rucio/rucio | 6d0d358e04f5431f0b9a98ae40f31af0ddff4833 | lib/rucio/core/replica.py | python | add_bad_pfns | (pfns, account, state, reason=None, expires_at=None, session=None) | return True | Add bad PFNs.
:param pfns: the list of new files.
:param account: The account who declared the bad replicas.
:param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILABLE.
:param reason: A string describing the reason of the loss.
:param expires_at: Specify a timeout for the TEMPORARY_UNAVAILABLE replicas. None for BAD files.
:param session: The database session in use.
:returns: True is successful. | Add bad PFNs. | [
"Add",
"bad",
"PFNs",
"."
] | def add_bad_pfns(pfns, account, state, reason=None, expires_at=None, session=None):
"""
Add bad PFNs.
:param pfns: the list of new files.
:param account: The account who declared the bad replicas.
:param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILABLE.
:param reason: A string describing the reason of the loss.
:param expires_at: Specify a timeout for the TEMPORARY_UNAVAILABLE replicas. None for BAD files.
:param session: The database session in use.
:returns: True is successful.
"""
if isinstance(state, string_types):
rep_state = BadPFNStatus[state]
else:
rep_state = state
if rep_state == BadPFNStatus.TEMPORARY_UNAVAILABLE and expires_at is None:
raise exception.InputValidationError("When adding a TEMPORARY UNAVAILABLE pfn the expires_at value should be set.")
elif rep_state == BadPFNStatus.BAD and expires_at is not None:
raise exception.InputValidationError("When adding a BAD pfn the expires_at value shouldn't be set.")
pfns = clean_surls(pfns)
for pfn in pfns:
new_pfn = models.BadPFNs(path=str(pfn), account=account, state=rep_state, reason=reason, expires_at=expires_at)
new_pfn = session.merge(new_pfn)
new_pfn.save(session=session, flush=False)
try:
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
except DatabaseError as error:
raise exception.RucioException(error.args)
except FlushError as error:
if match('New instance .* with identity key .* conflicts with persistent instance', error.args[0]):
raise exception.Duplicate('One PFN already exists!')
raise exception.RucioException(error.args)
return True | [
"def",
"add_bad_pfns",
"(",
"pfns",
",",
"account",
",",
"state",
",",
"reason",
"=",
"None",
",",
"expires_at",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"state",
",",
"string_types",
")",
":",
"rep_state",
"=",
"Bad... | https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/core/replica.py#L3106-L3146 | |
googleapis/google-auth-library-python | 87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b | google/auth/downscoped.py | python | AccessBoundaryRule.available_permissions | (self) | return tuple(self._available_permissions) | Returns the current available permissions.
Returns:
Tuple[str, ...]: The current available permissions. These are returned
as an immutable tuple to prevent modification. | Returns the current available permissions. | [
"Returns",
"the",
"current",
"available",
"permissions",
"."
] | def available_permissions(self):
"""Returns the current available permissions.
Returns:
Tuple[str, ...]: The current available permissions. These are returned
as an immutable tuple to prevent modification.
"""
return tuple(self._available_permissions) | [
"def",
"available_permissions",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"_available_permissions",
")"
] | https://github.com/googleapis/google-auth-library-python/blob/87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b/google/auth/downscoped.py#L231-L238 | |
munki/munki | 4b778f0e5a73ed3df9eb62d93c5227efb29eebe3 | code/client/munkilib/dmgutils.py | python | diskImageIsMounted | (dmgpath) | return isMounted | Returns true if the given disk image is currently mounted | Returns true if the given disk image is currently mounted | [
"Returns",
"true",
"if",
"the",
"given",
"disk",
"image",
"is",
"currently",
"mounted"
] | def diskImageIsMounted(dmgpath):
"""
Returns true if the given disk image is currently mounted
"""
isMounted = False
infoplist = hdiutil_info()
for imageProperties in infoplist.get('images'):
if 'image-path' in imageProperties:
imagepath = imageProperties['image-path']
if imagepath == dmgpath:
for entity in imageProperties.get('system-entities', []):
if entity.get('mount-point'):
isMounted = True
break
return isMounted | [
"def",
"diskImageIsMounted",
"(",
"dmgpath",
")",
":",
"isMounted",
"=",
"False",
"infoplist",
"=",
"hdiutil_info",
"(",
")",
"for",
"imageProperties",
"in",
"infoplist",
".",
"get",
"(",
"'images'",
")",
":",
"if",
"'image-path'",
"in",
"imageProperties",
":"... | https://github.com/munki/munki/blob/4b778f0e5a73ed3df9eb62d93c5227efb29eebe3/code/client/munkilib/dmgutils.py#L106-L120 | |
IsaacChanghau/neural_sequence_labeling | 10b5585235d5500b78bff81d4f8f3c818cd3af00 | utils/data_utils.py | python | dataset_batch_iter | (dataset, batch_size) | [] | def dataset_batch_iter(dataset, batch_size):
batch_words, batch_chars, batch_tags = [], [], []
for record in dataset:
batch_words.append(record["words"])
batch_chars.append(record["chars"])
batch_tags.append(record["tags"])
if len(batch_words) == batch_size:
yield process_batch_data(batch_words, batch_chars, batch_tags)
batch_words, batch_chars, batch_tags = [], [], []
if len(batch_words) > 0:
yield process_batch_data(batch_words, batch_chars, batch_tags) | [
"def",
"dataset_batch_iter",
"(",
"dataset",
",",
"batch_size",
")",
":",
"batch_words",
",",
"batch_chars",
",",
"batch_tags",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"record",
"in",
"dataset",
":",
"batch_words",
".",
"append",
"(",
"record... | https://github.com/IsaacChanghau/neural_sequence_labeling/blob/10b5585235d5500b78bff81d4f8f3c818cd3af00/utils/data_utils.py#L53-L63 | ||||
tcgoetz/GarminDB | 55796eb621df9f6ecd92f16b3a53393d23c0b4dc | garmindb/tcx.py | python | Tcx.get_lap_duration | (self, lap) | return conversions.secs_to_dt_time(super().get_lap_duration(lap)) | Return the recorded duration for the lap. | Return the recorded duration for the lap. | [
"Return",
"the",
"recorded",
"duration",
"for",
"the",
"lap",
"."
] | def get_lap_duration(self, lap):
"""Return the recorded duration for the lap."""
return conversions.secs_to_dt_time(super().get_lap_duration(lap)) | [
"def",
"get_lap_duration",
"(",
"self",
",",
"lap",
")",
":",
"return",
"conversions",
".",
"secs_to_dt_time",
"(",
"super",
"(",
")",
".",
"get_lap_duration",
"(",
"lap",
")",
")"
] | https://github.com/tcgoetz/GarminDB/blob/55796eb621df9f6ecd92f16b3a53393d23c0b4dc/garmindb/tcx.py#L110-L112 | |
git-cola/git-cola | b48b8028e0c3baf47faf7b074b9773737358163d | cola/widgets/diff.py | python | Options.set_options | (self) | Update diff options in response to UI events | Update diff options in response to UI events | [
"Update",
"diff",
"options",
"in",
"response",
"to",
"UI",
"events"
] | def set_options(self):
"""Update diff options in response to UI events"""
space_at_eol = get(self.ignore_space_at_eol)
space_change = get(self.ignore_space_change)
all_space = get(self.ignore_all_space)
function_context = get(self.function_context)
gitcmds.update_diff_overrides(
space_at_eol, space_change, all_space, function_context
)
self.widget.set_options() | [
"def",
"set_options",
"(",
"self",
")",
":",
"space_at_eol",
"=",
"get",
"(",
"self",
".",
"ignore_space_at_eol",
")",
"space_change",
"=",
"get",
"(",
"self",
".",
"ignore_space_change",
")",
"all_space",
"=",
"get",
"(",
"self",
".",
"ignore_all_space",
")... | https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/diff.py#L688-L697 | ||
songdejia/EAST | a74cbf03e661cdd83d756c5ef24bba44280ec2a0 | pyicdartools/evaluation.py | python | visulization | (img_dir, bbox_dir, visu_dir) | [] | def visulization(img_dir, bbox_dir, visu_dir):
for root, dirs, files in os.walk(img_dir):
for file in files:
# print(file)
# if file!='img_75.jpg':
# continue
print(file)
image_name = file
img_path = os.path.join(img_dir, image_name)
img = cv2.imread(img_path)
plt.clf()
plt.imshow(img)
currentAxis = plt.gca()
bbox_name = 'res_' + file[0:len(file) - 3] + 'txt'
bbox_path = os.path.join(bbox_dir, bbox_name)
if os.path.isfile(bbox_path):
with open(bbox_path, 'r') as f:
count = 1
for line in f.readlines():
line = line.strip()
x1 = line.split(',')[0]
y1 = line.split(',')[1]
x2 = line.split(',')[2]
y2 = line.split(',')[3]
x3 = line.split(',')[4]
y3 = line.split(',')[5]
x4 = line.split(',')[6]
y4 = line.split(',')[7]
rbox = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
color_rbox = 'r'
currentAxis.add_patch(plt.Polygon(rbox, fill=False, edgecolor=color_rbox, linewidth=1))
# currentAxis.text(int(x1), int(y1), str(count), bbox={'facecolor':'white', 'alpha':0.5})
count = count + 1
plt.axis('off')
plt.savefig(visu_dir + image_name, dpi=300) | [
"def",
"visulization",
"(",
"img_dir",
",",
"bbox_dir",
",",
"visu_dir",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"img_dir",
")",
":",
"for",
"file",
"in",
"files",
":",
"# print(file)",
"# if file!='img_75.jpg':",
... | https://github.com/songdejia/EAST/blob/a74cbf03e661cdd83d756c5ef24bba44280ec2a0/pyicdartools/evaluation.py#L329-L364 | ||||
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/platform.py | python | system | () | return uname()[0] | Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined. | Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. | [
"Returns",
"the",
"system",
"/",
"OS",
"name",
"e",
".",
"g",
".",
"Linux",
"Windows",
"or",
"Java",
"."
] | def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0] | [
"def",
"system",
"(",
")",
":",
"return",
"uname",
"(",
")",
"[",
"0",
"]"
] | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/platform.py#L1303-L1310 | |
paulproteus/python-scraping-code-samples | 4e5396d4e311ca66c784a2b5f859308285e511da | new/seleniumrc/selenium-remote-control-1.0-beta-2/selenium-python-client-driver-1.0-beta-2/selenium.py | python | selenium.set_context | (self,context) | Writes a message to the status bar and adds a note to the browser-side
log.
'context' is the message to be sent to the browser | Writes a message to the status bar and adds a note to the browser-side
log.
'context' is the message to be sent to the browser | [
"Writes",
"a",
"message",
"to",
"the",
"status",
"bar",
"and",
"adds",
"a",
"note",
"to",
"the",
"browser",
"-",
"side",
"log",
".",
"context",
"is",
"the",
"message",
"to",
"be",
"sent",
"to",
"the",
"browser"
] | def set_context(self,context):
"""
Writes a message to the status bar and adds a note to the browser-side
log.
'context' is the message to be sent to the browser
"""
self.do_command("setContext", [context,]) | [
"def",
"set_context",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"do_command",
"(",
"\"setContext\"",
",",
"[",
"context",
",",
"]",
")"
] | https://github.com/paulproteus/python-scraping-code-samples/blob/4e5396d4e311ca66c784a2b5f859308285e511da/new/seleniumrc/selenium-remote-control-1.0-beta-2/selenium-python-client-driver-1.0-beta-2/selenium.py#L1907-L1914 | ||
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/core/annotations/type_annotations.py | python | TypeAnnotation.annotate | (self) | [] | def annotate(self):
source = SourceLines(self.func_id.func)
# if not source.avail:
# return "Source code unavailable"
groupedinst = self.prepare_annotations()
# Format annotations
io = StringIO()
with closing(io):
if source.avail:
print("# File: %s" % self.filename, file=io)
for num in source:
srcline = source[num]
ind = _getindent(srcline)
print("%s# --- LINE %d --- " % (ind, num), file=io)
for inst in groupedinst[num]:
print('%s# %s' % (ind, inst), file=io)
print(file=io)
print(srcline, file=io)
print(file=io)
if self.lifted:
print("# The function contains lifted loops", file=io)
for loop in self.lifted:
print("# Loop at line %d" % loop.get_source_location(),
file=io)
print("# Has %d overloads" % len(loop.overloads),
file=io)
for cres in loop.overloads.values():
print(cres.type_annotation, file=io)
else:
print("# Source code unavailable", file=io)
for num in groupedinst:
for inst in groupedinst[num]:
print('%s' % (inst,), file=io)
print(file=io)
return io.getvalue() | [
"def",
"annotate",
"(",
"self",
")",
":",
"source",
"=",
"SourceLines",
"(",
"self",
".",
"func_id",
".",
"func",
")",
"# if not source.avail:",
"# return \"Source code unavailable\"",
"groupedinst",
"=",
"self",
".",
"prepare_annotations",
"(",
")",
"# Format a... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/annotations/type_annotations.py#L111-L148 | ||||
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/Cookie.py | python | BaseCookie.output | (self, attrs=None, header="Set-Cookie:", sep="\015\012") | return sep.join(result) | Return a string suitable for HTTP. | Return a string suitable for HTTP. | [
"Return",
"a",
"string",
"suitable",
"for",
"HTTP",
"."
] | def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP."""
result = []
items = self.items()
items.sort()
for K,V in items:
result.append( V.output(attrs, header) )
return sep.join(result) | [
"def",
"output",
"(",
"self",
",",
"attrs",
"=",
"None",
",",
"header",
"=",
"\"Set-Cookie:\"",
",",
"sep",
"=",
"\"\\015\\012\"",
")",
":",
"result",
"=",
"[",
"]",
"items",
"=",
"self",
".",
"items",
"(",
")",
"items",
".",
"sort",
"(",
")",
"for... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/Cookie.py#L595-L602 | |
Henryhaohao/Wenshu_Spider | 5b5ec14febb76a4867c4a257a3e498c85b02198a | Wenshu_Project/Wenshu/spiders/wenshu.py | python | WenshuSpider.get_docid | (self, response) | 计算出docid | 计算出docid | [
"计算出docid"
] | def get_docid(self, response):
'''计算出docid'''
html = response.text
result = eval(json.loads(html))
runeval = result[0]['RunEval']
content = result[1:]
for i in content:
casewenshuid = i.get('文书ID', '')
casejudgedate = i.get('裁判日期', '')
docid = self.js_2.call('getdocid', runeval, casewenshuid)
print('*************文书ID:' + docid)
url = 'http://wenshu.court.gov.cn/CreateContentJS/CreateContentJS.aspx?DocID={}'.format(docid)
yield scrapy.Request(url, callback=self.get_detail, meta={'casejudgedate':casejudgedate}, dont_filter=True) | [
"def",
"get_docid",
"(",
"self",
",",
"response",
")",
":",
"html",
"=",
"response",
".",
"text",
"result",
"=",
"eval",
"(",
"json",
".",
"loads",
"(",
"html",
")",
")",
"runeval",
"=",
"result",
"[",
"0",
"]",
"[",
"'RunEval'",
"]",
"content",
"=... | https://github.com/Henryhaohao/Wenshu_Spider/blob/5b5ec14febb76a4867c4a257a3e498c85b02198a/Wenshu_Project/Wenshu/spiders/wenshu.py#L91-L103 | ||
aiidateam/aiida-core | c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2 | aiida/orm/nodes/process/calculation/calcjob.py | python | CalcJobNode.set_retrieve_list | (self, retrieve_list: Sequence[Union[str, Tuple[str, str, str]]]) | Set the retrieve list.
This list of directives will instruct the daemon what files to retrieve after the calculation has completed.
list or tuple of files or paths that should be retrieved by the daemon.
:param retrieve_list: list or tuple of with filepath directives | Set the retrieve list. | [
"Set",
"the",
"retrieve",
"list",
"."
] | def set_retrieve_list(self, retrieve_list: Sequence[Union[str, Tuple[str, str, str]]]) -> None:
"""Set the retrieve list.
This list of directives will instruct the daemon what files to retrieve after the calculation has completed.
list or tuple of files or paths that should be retrieved by the daemon.
:param retrieve_list: list or tuple of with filepath directives
"""
self._validate_retrieval_directive(retrieve_list)
self.set_attribute(self.RETRIEVE_LIST_KEY, retrieve_list) | [
"def",
"set_retrieve_list",
"(",
"self",
",",
"retrieve_list",
":",
"Sequence",
"[",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
"]",
"]",
")",
"->",
"None",
":",
"self",
".",
"_validate_retrieval_directive",
"(",
"retriev... | https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/nodes/process/calculation/calcjob.py#L283-L292 | ||
weechat/scripts | 99ec0e7eceefabb9efb0f11ec26d45d6e8e84335 | python/minesweeper.py | python | minesweeper_init | () | Init minesweeper: create buffer, adjust zoom, new game. | Init minesweeper: create buffer, adjust zoom, new game. | [
"Init",
"minesweeper",
":",
"create",
"buffer",
"adjust",
"zoom",
"new",
"game",
"."
] | def minesweeper_init():
"""Init minesweeper: create buffer, adjust zoom, new game."""
global minesweeper
if minesweeper['buffer']:
return
minesweeper['buffer'] = weechat.buffer_search('python', 'minesweeper')
if not minesweeper['buffer']:
minesweeper['buffer'] = weechat.buffer_new('minesweeper', 'minesweeper_input_buffer', '', 'minesweeper_close_buffer', '')
if minesweeper['buffer']:
weechat.buffer_set(minesweeper['buffer'], 'type', 'free')
weechat.buffer_set(minesweeper['buffer'], 'title',
'Minesweeper! | alt-space or mouse-b1: explore, alt-f or mouse-b2: flag, alt-n: new game, '
'alt-+/-: adjust board zoom | '
'Command line: (n)ew, +/-: change size, (q)uit')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-A', '/minesweeper up')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-B', '/minesweeper down')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-D', '/minesweeper left')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-C', '/minesweeper right')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-f', '/minesweeper flag')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta- ', '/minesweeper explore')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-n', '/minesweeper new')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-+', '/minesweeper zoom')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta--', '/minesweeper dezoom')
weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-c', '/minesweeper cheat')
if minesweeper['buffer']:
minesweeper_adjust_zoom()
minesweeper_new_game() | [
"def",
"minesweeper_init",
"(",
")",
":",
"global",
"minesweeper",
"if",
"minesweeper",
"[",
"'buffer'",
"]",
":",
"return",
"minesweeper",
"[",
"'buffer'",
"]",
"=",
"weechat",
".",
"buffer_search",
"(",
"'python'",
",",
"'minesweeper'",
")",
"if",
"not",
"... | https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/minesweeper.py#L351-L377 | ||
srusskih/SublimeJEDI | 8a5054f0a053c8a8170c06c56216245240551d54 | dependencies/jedi/parser_utils.py | python | get_signature | (funcdef, width=72, call_string=None,
omit_first_param=False, omit_return_annotation=False) | return '\n'.join(textwrap.wrap(code, width)) | Generate a string signature of a function.
:param width: Fold lines if a line is longer than this value.
:type width: int
:arg func_name: Override function name when given.
:type func_name: str
:rtype: str | Generate a string signature of a function. | [
"Generate",
"a",
"string",
"signature",
"of",
"a",
"function",
"."
] | def get_signature(funcdef, width=72, call_string=None,
omit_first_param=False, omit_return_annotation=False):
"""
Generate a string signature of a function.
:param width: Fold lines if a line is longer than this value.
:type width: int
:arg func_name: Override function name when given.
:type func_name: str
:rtype: str
"""
# Lambdas have no name.
if call_string is None:
if funcdef.type == 'lambdef':
call_string = '<lambda>'
else:
call_string = funcdef.name.value
params = funcdef.get_params()
if omit_first_param:
params = params[1:]
p = '(' + ''.join(param.get_code() for param in params).strip() + ')'
# TODO this is pretty bad, we should probably just normalize.
p = re.sub(r'\s+', ' ', p)
if funcdef.annotation and not omit_return_annotation:
rtype = " ->" + funcdef.annotation.get_code()
else:
rtype = ""
code = call_string + p + rtype
return '\n'.join(textwrap.wrap(code, width)) | [
"def",
"get_signature",
"(",
"funcdef",
",",
"width",
"=",
"72",
",",
"call_string",
"=",
"None",
",",
"omit_first_param",
"=",
"False",
",",
"omit_return_annotation",
"=",
"False",
")",
":",
"# Lambdas have no name.",
"if",
"call_string",
"is",
"None",
":",
"... | https://github.com/srusskih/SublimeJEDI/blob/8a5054f0a053c8a8170c06c56216245240551d54/dependencies/jedi/parser_utils.py#L145-L175 | |
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/core/units.py | python | FloatWithUnit.supported_units | (self) | return tuple(ALL_UNITS[self._unit_type].keys()) | Supported units for specific unit type. | Supported units for specific unit type. | [
"Supported",
"units",
"for",
"specific",
"unit",
"type",
"."
] | def supported_units(self):
"""
Supported units for specific unit type.
"""
return tuple(ALL_UNITS[self._unit_type].keys()) | [
"def",
"supported_units",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"ALL_UNITS",
"[",
"self",
".",
"_unit_type",
"]",
".",
"keys",
"(",
")",
")"
] | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/core/units.py#L484-L488 | |
ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | digsby/src/oscar/OscarProtocol.py | python | OscarProtocol.send_folder | (self, buddy, filestorage) | Sends a folder to a buddy. | Sends a folder to a buddy. | [
"Sends",
"a",
"folder",
"to",
"a",
"buddy",
"."
] | def send_folder(self, buddy, filestorage):
'Sends a folder to a buddy.'
self.send_file(buddy, filestorage) | [
"def",
"send_folder",
"(",
"self",
",",
"buddy",
",",
"filestorage",
")",
":",
"self",
".",
"send_file",
"(",
"buddy",
",",
"filestorage",
")"
] | https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/oscar/OscarProtocol.py#L559-L562 | ||
google/aiyprojects-raspbian | 964f07f5b4bd2ec785cfda6f318e50e1b67d4758 | src/aiy/_buzzer.py | python | PWMController.close | (self) | Shuts down the PWMController and unexports the GPIO. | Shuts down the PWMController and unexports the GPIO. | [
"Shuts",
"down",
"the",
"PWMController",
"and",
"unexports",
"the",
"GPIO",
"."
] | def close(self):
"""Shuts down the PWMController and unexports the GPIO."""
self._unexport_pwm() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_unexport_pwm",
"(",
")"
] | https://github.com/google/aiyprojects-raspbian/blob/964f07f5b4bd2ec785cfda6f318e50e1b67d4758/src/aiy/_buzzer.py#L188-L190 | ||
devanshbatham/ParamSpider | e21624c068ac2227b73fbef7d6410682a1fec232 | core/extractor.py | python | param_extract | (response, level, black_list, placeholder) | return list(set(final_uris)) | Function to extract URLs with parameters (ignoring the black list extention)
regexp : r'.*?:\/\/.*\?.*\=[^$]' | Function to extract URLs with parameters (ignoring the black list extention)
regexp : r'.*?:\/\/.*\?.*\=[^$]' | [
"Function",
"to",
"extract",
"URLs",
"with",
"parameters",
"(",
"ignoring",
"the",
"black",
"list",
"extention",
")",
"regexp",
":",
"r",
".",
"*",
"?",
":",
"\\",
"/",
"\\",
"/",
".",
"*",
"\\",
"?",
".",
"*",
"\\",
"=",
"[",
"^$",
"]"
] | def param_extract(response, level, black_list, placeholder):
'''
Function to extract URLs with parameters (ignoring the black list extention)
regexp : r'.*?:\/\/.*\?.*\=[^$]'
'''
parsed = list(set(re.findall(r'.*?:\/\/.*\?.*\=[^$]' , response)))
final_uris = []
for i in parsed:
delim = i.find('=')
second_delim = i.find('=', i.find('=') + 1)
if len(black_list) > 0:
words_re = re.compile("|".join(black_list))
if not words_re.search(i):
final_uris.append((i[:delim+1] + placeholder))
if level == 'high':
final_uris.append(i[:second_delim+1] + placeholder)
else:
final_uris.append((i[:delim+1] + placeholder))
if level == 'high':
final_uris.append(i[:second_delim+1] + placeholder)
# for i in final_uris:
# k = [ele for ele in black_list if(ele in i)]
return list(set(final_uris)) | [
"def",
"param_extract",
"(",
"response",
",",
"level",
",",
"black_list",
",",
"placeholder",
")",
":",
"parsed",
"=",
"list",
"(",
"set",
"(",
"re",
".",
"findall",
"(",
"r'.*?:\\/\\/.*\\?.*\\=[^$]'",
",",
"response",
")",
")",
")",
"final_uris",
"=",
"["... | https://github.com/devanshbatham/ParamSpider/blob/e21624c068ac2227b73fbef7d6410682a1fec232/core/extractor.py#L4-L32 | |
ppizarror/pygame-menu | da5827a1ad0686e8ff2aa536b74bbfba73967bcf | pygame_menu/menu.py | python | Menu._copy_theme | (self) | Updates theme reference with a copied one.
:return: None | Updates theme reference with a copied one. | [
"Updates",
"theme",
"reference",
"with",
"a",
"copied",
"one",
"."
] | def _copy_theme(self) -> None:
"""
Updates theme reference with a copied one.
:return: None
"""
self._theme = self._theme.copy() | [
"def",
"_copy_theme",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_theme",
"=",
"self",
".",
"_theme",
".",
"copy",
"(",
")"
] | https://github.com/ppizarror/pygame-menu/blob/da5827a1ad0686e8ff2aa536b74bbfba73967bcf/pygame_menu/menu.py#L3887-L3893 | ||
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/gdata/src/gdata/contacts/client.py | python | ContactsClient.get_group | (self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs) | return self.get_entry(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) | Get a single groups details
Args:
uri: the group uri or id | Get a single groups details
Args:
uri: the group uri or id | [
"Get",
"a",
"single",
"groups",
"details",
"Args",
":",
"uri",
":",
"the",
"group",
"uri",
"or",
"id"
] | def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs):
""" Get a single groups details
Args:
uri: the group uri or id
"""
return self.get_entry(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) | [
"def",
"get_group",
"(",
"self",
",",
"uri",
"=",
"None",
",",
"desired_class",
"=",
"gdata",
".",
"contacts",
".",
"data",
".",
"GroupEntry",
",",
"auth_token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_entry",
"(",
... | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/gdata/contacts/client.py#L205-L211 | |
pysmt/pysmt | ade4dc2a825727615033a96d31c71e9f53ce4764 | pysmt/solvers/msat.py | python | MSatConverter.walk_ite | (self, formula, args, **kwargs) | [] | def walk_ite(self, formula, args, **kwargs):
i = args[0]
t = args[1]
e = args[2]
if self._get_type(formula).is_bool_type():
impl = self.mgr.Implies(formula.arg(0), formula.arg(1))
th = self.walk_implies(impl, [i,t])
nif = self.mgr.Not(formula.arg(0))
ni = self.walk_not(nif, [i])
el = self.walk_implies(self.mgr.Implies(nif, formula.arg(2)), [ni,e])
return mathsat.msat_make_and(self.msat_env(), th, el)
else:
return mathsat.msat_make_term_ite(self.msat_env(), i, t, e) | [
"def",
"walk_ite",
"(",
"self",
",",
"formula",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"i",
"=",
"args",
"[",
"0",
"]",
"t",
"=",
"args",
"[",
"1",
"]",
"e",
"=",
"args",
"[",
"2",
"]",
"if",
"self",
".",
"_get_type",
"(",
"formula",... | https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/solvers/msat.py#L799-L812 | ||||
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/flaskext/sqlalchemy.py | python | SQLAlchemy.metadata | (self) | return self.Model.metadata | Returns the metadata | Returns the metadata | [
"Returns",
"the",
"metadata"
] | def metadata(self):
"""Returns the metadata"""
return self.Model.metadata | [
"def",
"metadata",
"(",
"self",
")",
":",
"return",
"self",
".",
"Model",
".",
"metadata"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/flaskext/sqlalchemy.py#L610-L612 | |
taomujian/linbing | fe772a58f41e3b046b51a866bdb7e4655abaf51a | python/app/thirdparty/dirsearch/thirdparty/jinja2/compiler.py | python | CodeGenerator._default_finalize | (value: t.Any) | return str(value) | The default finalize function if the environment isn't
configured with one. Or, if the environment has one, this is
called on that function's output for constants. | The default finalize function if the environment isn't
configured with one. Or, if the environment has one, this is
called on that function's output for constants. | [
"The",
"default",
"finalize",
"function",
"if",
"the",
"environment",
"isn",
"t",
"configured",
"with",
"one",
".",
"Or",
"if",
"the",
"environment",
"has",
"one",
"this",
"is",
"called",
"on",
"that",
"function",
"s",
"output",
"for",
"constants",
"."
] | def _default_finalize(value: t.Any) -> t.Any:
"""The default finalize function if the environment isn't
configured with one. Or, if the environment has one, this is
called on that function's output for constants.
"""
return str(value) | [
"def",
"_default_finalize",
"(",
"value",
":",
"t",
".",
"Any",
")",
"->",
"t",
".",
"Any",
":",
"return",
"str",
"(",
"value",
")"
] | https://github.com/taomujian/linbing/blob/fe772a58f41e3b046b51a866bdb7e4655abaf51a/python/app/thirdparty/dirsearch/thirdparty/jinja2/compiler.py#L1364-L1369 | |
meduza-corp/interstellar | 40a801ccd7856491726f5a126621d9318cabe2e1 | gsutil/gslib/commands/help.py | python | HelpCommand._LoadHelpMaps | (self) | return (help_type_map, help_name_map) | Returns tuple of help type and help name.
help type is a dict with key: help type
value: list of HelpProviders
help name is a dict with key: help command name or alias
value: HelpProvider
Returns:
(help type, help name) | Returns tuple of help type and help name. | [
"Returns",
"tuple",
"of",
"help",
"type",
"and",
"help",
"name",
"."
] | def _LoadHelpMaps(self):
"""Returns tuple of help type and help name.
help type is a dict with key: help type
value: list of HelpProviders
help name is a dict with key: help command name or alias
value: HelpProvider
Returns:
(help type, help name)
"""
# Import all gslib.commands submodules.
for _, module_name, _ in pkgutil.iter_modules(gslib.commands.__path__):
__import__('gslib.commands.%s' % module_name)
# Import all gslib.addlhelp submodules.
for _, module_name, _ in pkgutil.iter_modules(gslib.addlhelp.__path__):
__import__('gslib.addlhelp.%s' % module_name)
help_type_map = {}
help_name_map = {}
for s in gslib.help_provider.ALL_HELP_TYPES:
help_type_map[s] = []
# Only include HelpProvider subclasses in the dict.
for help_prov in itertools.chain(
HelpProvider.__subclasses__(), Command.__subclasses__()):
if help_prov is Command:
# Skip the Command base class itself; we just want its subclasses,
# where the help command text lives (in addition to non-Command
# HelpProviders, like naming.py).
continue
gslib.help_provider.SanityCheck(help_prov, help_name_map)
help_name_map[help_prov.help_spec.help_name] = help_prov
for help_name_aliases in help_prov.help_spec.help_name_aliases:
help_name_map[help_name_aliases] = help_prov
help_type_map[help_prov.help_spec.help_type].append(help_prov)
return (help_type_map, help_name_map) | [
"def",
"_LoadHelpMaps",
"(",
"self",
")",
":",
"# Import all gslib.commands submodules.",
"for",
"_",
",",
"module_name",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"gslib",
".",
"commands",
".",
"__path__",
")",
":",
"__import__",
"(",
"'gslib.command... | https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/gslib/commands/help.py#L206-L242 | |
MacHu-GWU/uszipcode-project | d5ca6d7bd0544043dfc8fee3393ee17e1c96c01d | uszipcode/search.py | python | SearchEngine._resolve_sort_by | (sort_by: str, flag_radius_query: bool) | return sort_by | Result ``sort_by`` argument.
:param sort_by: str, or sqlalchemy ORM attribute.
:param flag_radius_query:
:return: | Result ``sort_by`` argument. | [
"Result",
"sort_by",
"argument",
"."
] | def _resolve_sort_by(sort_by: str, flag_radius_query: bool):
"""
Result ``sort_by`` argument.
:param sort_by: str, or sqlalchemy ORM attribute.
:param flag_radius_query:
:return:
"""
if sort_by is None:
if flag_radius_query:
sort_by = SORT_BY_DIST
elif isinstance(sort_by, str):
if sort_by.lower() == SORT_BY_DIST:
if flag_radius_query is False:
msg = "`sort_by` arg can be 'dist' only under distance based query!"
raise ValueError(msg)
sort_by = SORT_BY_DIST
elif sort_by not in SimpleZipcode.__table__.columns:
msg = "`sort_by` arg has to be one of the Zipcode attribute or 'dist'!"
raise ValueError(msg)
else:
sort_by = sort_by.name
return sort_by | [
"def",
"_resolve_sort_by",
"(",
"sort_by",
":",
"str",
",",
"flag_radius_query",
":",
"bool",
")",
":",
"if",
"sort_by",
"is",
"None",
":",
"if",
"flag_radius_query",
":",
"sort_by",
"=",
"SORT_BY_DIST",
"elif",
"isinstance",
"(",
"sort_by",
",",
"str",
")",... | https://github.com/MacHu-GWU/uszipcode-project/blob/d5ca6d7bd0544043dfc8fee3393ee17e1c96c01d/uszipcode/search.py#L384-L407 | |
marshmallow-code/webargs | a6691d069c940219090854b077438ef8b6a865f1 | src/webargs/core.py | python | Parser._update_args_kwargs | (
args: tuple,
kwargs: dict[str, typing.Any],
parsed_args: tuple,
as_kwargs: bool,
) | return args, kwargs | Update args or kwargs with parsed_args depending on as_kwargs | Update args or kwargs with parsed_args depending on as_kwargs | [
"Update",
"args",
"or",
"kwargs",
"with",
"parsed_args",
"depending",
"on",
"as_kwargs"
] | def _update_args_kwargs(
args: tuple,
kwargs: dict[str, typing.Any],
parsed_args: tuple,
as_kwargs: bool,
) -> tuple[tuple, typing.Mapping]:
"""Update args or kwargs with parsed_args depending on as_kwargs"""
if as_kwargs:
kwargs.update(parsed_args)
else:
# Add parsed_args after other positional arguments
args += (parsed_args,)
return args, kwargs | [
"def",
"_update_args_kwargs",
"(",
"args",
":",
"tuple",
",",
"kwargs",
":",
"dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
",",
"parsed_args",
":",
"tuple",
",",
"as_kwargs",
":",
"bool",
",",
")",
"->",
"tuple",
"[",
"tuple",
",",
"typing",
".... | https://github.com/marshmallow-code/webargs/blob/a6691d069c940219090854b077438ef8b6a865f1/src/webargs/core.py#L372-L384 | |
Fortran-FOSS-Programmers/ford | e93b27188c763a019713f64e2270ae98c8f226e1 | ford/graphs.py | python | TypeGraph.add_nodes | (self, nodes, nesting=1) | Adds edges showing inheritance and composition relationships
between derived types listed in the nodes. | Adds edges showing inheritance and composition relationships
between derived types listed in the nodes. | [
"Adds",
"edges",
"showing",
"inheritance",
"and",
"composition",
"relationships",
"between",
"derived",
"types",
"listed",
"in",
"the",
"nodes",
"."
] | def add_nodes(self, nodes, nesting=1):
"""
Adds edges showing inheritance and composition relationships
between derived types listed in the nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges for this hop
for i, n in zip(range(len(nodes)), nodes):
r, g, b = rainbowcolour(i, len(nodes))
colour = "#%02X%02X%02X" % (r, g, b)
for keys in n.comp_types.keys():
if keys not in self.added:
hopNodes.add(keys)
for c in n.comp_types:
if c not in self.added:
hopNodes.add(c)
hopEdges.append((n, c, "dashed", colour, n.comp_types[c]))
if n.ancestor:
if n.ancestor not in self.added:
hopNodes.add(n.ancestor)
hopEdges.append((n, n.ancestor, "solid", colour))
# add nodes, edges and attributes to the graph if maximum number of
# nodes is not exceeded
if self.add_to_graph(hopNodes, hopEdges, nesting):
self.dot.attr("graph", size="11.875,1000.0") | [
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
",",
"nesting",
"=",
"1",
")",
":",
"hopNodes",
"=",
"set",
"(",
")",
"# nodes in this hop",
"hopEdges",
"=",
"[",
"]",
"# edges in this hop",
"# get nodes and edges for this hop",
"for",
"i",
",",
"n",
"in",
"z... | https://github.com/Fortran-FOSS-Programmers/ford/blob/e93b27188c763a019713f64e2270ae98c8f226e1/ford/graphs.py#L994-L1019 | ||
mtianyan/VueDjangoAntdProBookShop | fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2 | third_party/social_core/backends/open_id.py | python | OpenIdAuth.setup_request | (self, params=None) | return request | Setup request | Setup request | [
"Setup",
"request"
] | def setup_request(self, params=None):
"""Setup request"""
request = self.openid_request(params)
# Request some user details. Use attribute exchange if provider
# advertises support.
if request.endpoint.supportsType(ax.AXMessage.ns_uri):
fetch_request = ax.FetchRequest()
# Mark all attributes as required, Google ignores optional ones
for attr, alias in self.get_ax_attributes():
fetch_request.add(ax.AttrInfo(attr, alias=alias,
required=True))
else:
fetch_request = sreg.SRegRequest(
optional=list(dict(self.get_sreg_attributes()).keys())
)
request.addExtension(fetch_request)
# Add PAPE Extension for if configured
preferred_policies = self.setting(
'OPENID_PAPE_PREFERRED_AUTH_POLICIES'
)
preferred_level_types = self.setting(
'OPENID_PAPE_PREFERRED_AUTH_LEVEL_TYPES'
)
max_age = self.setting('OPENID_PAPE_MAX_AUTH_AGE')
if max_age is not None:
try:
max_age = int(max_age)
except (ValueError, TypeError):
max_age = None
if max_age is not None or preferred_policies or preferred_level_types:
pape_request = pape.Request(
max_auth_age=max_age,
preferred_auth_policies=preferred_policies,
preferred_auth_level_types=preferred_level_types
)
request.addExtension(pape_request)
return request | [
"def",
"setup_request",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"openid_request",
"(",
"params",
")",
"# Request some user details. Use attribute exchange if provider",
"# advertises support.",
"if",
"request",
".",
"endpoint",
... | https://github.com/mtianyan/VueDjangoAntdProBookShop/blob/fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2/third_party/social_core/backends/open_id.py#L188-L226 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py | python | MatchFirst.__ior__ | (self, other ) | return self.append( other ) | [] | def __ior__(self, other ):
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
return self.append( other ) | [
"def",
"__ior__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"return",
"self",
".",
"append",
"(",
"other",
")"
] | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py#L3571-L3574 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/simplejson/scanner.py | python | _import_c_make_scanner | () | [] | def _import_c_make_scanner():
try:
from ._speedups import make_scanner
return make_scanner
except ImportError:
return None | [
"def",
"_import_c_make_scanner",
"(",
")",
":",
"try",
":",
"from",
".",
"_speedups",
"import",
"make_scanner",
"return",
"make_scanner",
"except",
"ImportError",
":",
"return",
"None"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/simplejson/scanner.py#L5-L10 | ||||
spectralpython/spectral | e1cd919f5f66abddc219b76926450240feaaed8f | spectral/algorithms/continuum.py | python | continuum_points | (spectrum, bands, mode='convex') | return _find_continuum_points_recursive(spectrum, bands, mode == 'segmented', indices) | Returns points of spectra that belong to it's continuum.
Arguments:
`spectrum` (:class:`numpy.ndarray`)
1d :class:`numpy.ndarray` holding spectral signature.
`bands` (:class:`numpy.ndarray`):
1d :class:`numpy.ndarray`, holding band values of spectra.
Length of `bands` should be the same as `spectrum`.
Note that bands should be sorted in ascending order (which is often
not the case with AVIRIS), otherwise unexpected results could occure.
`mode` (string, default 'convex'):
Default mode is 'convex' which returns convex upper hull of the
spectrum. Another supported mode is 'segmented' which builds
segmented upper hull. This is usefull to identify more detailed
contour of the spectrum, but without strong absorption bands.
Returns:
2-tuple, with each element being :class:`numpy.ndarray`.
First element contains reflectance values of points that belong to
continuum. Second element contains corresponding bands.
By applying linear interpolation to this data as x and y, we get
continuum of spectrum. However this function is particularly useful to
applying other interpolations or any other processing on these points. | Returns points of spectra that belong to it's continuum. | [
"Returns",
"points",
"of",
"spectra",
"that",
"belong",
"to",
"it",
"s",
"continuum",
"."
] | def continuum_points(spectrum, bands, mode='convex'):
'''Returns points of spectra that belong to it's continuum.
Arguments:
`spectrum` (:class:`numpy.ndarray`)
1d :class:`numpy.ndarray` holding spectral signature.
`bands` (:class:`numpy.ndarray`):
1d :class:`numpy.ndarray`, holding band values of spectra.
Length of `bands` should be the same as `spectrum`.
Note that bands should be sorted in ascending order (which is often
not the case with AVIRIS), otherwise unexpected results could occure.
`mode` (string, default 'convex'):
Default mode is 'convex' which returns convex upper hull of the
spectrum. Another supported mode is 'segmented' which builds
segmented upper hull. This is usefull to identify more detailed
contour of the spectrum, but without strong absorption bands.
Returns:
2-tuple, with each element being :class:`numpy.ndarray`.
First element contains reflectance values of points that belong to
continuum. Second element contains corresponding bands.
By applying linear interpolation to this data as x and y, we get
continuum of spectrum. However this function is particularly useful to
applying other interpolations or any other processing on these points.
'''
if not isinstance(spectrum, np.ndarray):
raise TypeError('Expected spectra to be a numpy.ndarray.')
if not isinstance(bands, np.ndarray):
raise TypeError('Expected bands to be a numpy.ndarray.')
if len(spectrum.shape) != 1:
raise ValueError('Expected spectra to be 1d array.')
if len(bands.shape) != 1:
raise ValueError('Expected bands to be 1d array.')
indices = np.empty_like(spectrum, dtype='int64')
return _find_continuum_points_recursive(spectrum, bands, mode == 'segmented', indices) | [
"def",
"continuum_points",
"(",
"spectrum",
",",
"bands",
",",
"mode",
"=",
"'convex'",
")",
":",
"if",
"not",
"isinstance",
"(",
"spectrum",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Expected spectra to be a numpy.ndarray.'",
")",
"if"... | https://github.com/spectralpython/spectral/blob/e1cd919f5f66abddc219b76926450240feaaed8f/spectral/algorithms/continuum.py#L232-L274 | |
david-abel/simple_rl | d8fe6007efb4840377f085a4e35ba89aaa2cdf6d | simple_rl/utils/mdp_visualizer.py | python | visualize_policy | (mdp, policy, draw_state, action_char_dict, cur_state=None, scr_width=720, scr_height=720) | Args:
mdp (MDP)
policy (lambda: S --> A)
draw_state (lambda)
action_char_dict (dict):
Key: action
Val: str
cur_state (State)
Summary: | Args:
mdp (MDP)
policy (lambda: S --> A)
draw_state (lambda)
action_char_dict (dict):
Key: action
Val: str
cur_state (State) | [
"Args",
":",
"mdp",
"(",
"MDP",
")",
"policy",
"(",
"lambda",
":",
"S",
"--",
">",
"A",
")",
"draw_state",
"(",
"lambda",
")",
"action_char_dict",
"(",
"dict",
")",
":",
"Key",
":",
"action",
"Val",
":",
"str",
"cur_state",
"(",
"State",
")"
] | def visualize_policy(mdp, policy, draw_state, action_char_dict, cur_state=None, scr_width=720, scr_height=720):
'''
Args:
mdp (MDP)
policy (lambda: S --> A)
draw_state (lambda)
action_char_dict (dict):
Key: action
Val: str
cur_state (State)
Summary:
'''
screen = pygame.display.set_mode((scr_width, scr_height))
# Setup and draw initial state.
cur_state = mdp.get_init_state() if cur_state is None else cur_state
agent_shape = _vis_init(screen, mdp, draw_state, cur_state, value=True)
draw_state(screen, mdp, cur_state, policy=policy, action_char_dict=action_char_dict, show_value=False, draw_statics=True)
pygame.display.flip()
while True:
# Check for key presses.
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
# Quit.
pygame.quit()
sys.exit()
time.sleep(0.1) | [
"def",
"visualize_policy",
"(",
"mdp",
",",
"policy",
",",
"draw_state",
",",
"action_char_dict",
",",
"cur_state",
"=",
"None",
",",
"scr_width",
"=",
"720",
",",
"scr_height",
"=",
"720",
")",
":",
"screen",
"=",
"pygame",
".",
"display",
".",
"set_mode"... | https://github.com/david-abel/simple_rl/blob/d8fe6007efb4840377f085a4e35ba89aaa2cdf6d/simple_rl/utils/mdp_visualizer.py#L90-L120 | ||
lovelylain/pyctp | fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d | example/pyctp2/trader/trade_command_queue.py | python | BaseTradeCommandQueue.put_command | (self, command) | [] | def put_command(self, command):
#print(command.priority,str(command))
self._queue.put((command.priority, command)) | [
"def",
"put_command",
"(",
"self",
",",
"command",
")",
":",
"#print(command.priority,str(command))",
"self",
".",
"_queue",
".",
"put",
"(",
"(",
"command",
".",
"priority",
",",
"command",
")",
")"
] | https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/trader/trade_command_queue.py#L60-L62 | ||||
luigifreda/pyslam | 5cf7a1526dcb404032daf7cb7d59bab78d4e4bd9 | thirdparty/contextdesc/evaluations.py | python | format_data | (config) | Post-processing and generate custom files. | Post-processing and generate custom files. | [
"Post",
"-",
"processing",
"and",
"generate",
"custom",
"files",
"."
] | def format_data(config):
"""Post-processing and generate custom files."""
prog_bar = progressbar.ProgressBar()
config['stage'] = 'post_format'
dataset = get_dataset(config['data_name'])(**config)
prog_bar.max_value = dataset.data_length
test_set = dataset.get_test_set()
idx = 0
while True:
try:
data = next(test_set)
dataset.format_data(data)
prog_bar.update(idx)
idx += 1
except dataset.end_set:
break | [
"def",
"format_data",
"(",
"config",
")",
":",
"prog_bar",
"=",
"progressbar",
".",
"ProgressBar",
"(",
")",
"config",
"[",
"'stage'",
"]",
"=",
"'post_format'",
"dataset",
"=",
"get_dataset",
"(",
"config",
"[",
"'data_name'",
"]",
")",
"(",
"*",
"*",
"... | https://github.com/luigifreda/pyslam/blob/5cf7a1526dcb404032daf7cb7d59bab78d4e4bd9/thirdparty/contextdesc/evaluations.py#L114-L130 | ||
santatic/web2attack | 44b6e481a3d56cf0d98073ae0fb69833dda563d9 | w2a/lib/mysql/connector/protocol.py | python | MySQLProtocol.read_text_result | (self, sock, count=1) | return (rows, eof) | Read MySQL text result
Reads all or given number of rows from the socket.
Returns a tuple with 2 elements: a list with all rows and
the EOF packet. | Read MySQL text result | [
"Read",
"MySQL",
"text",
"result"
] | def read_text_result(self, sock, count=1):
"""Read MySQL text result
Reads all or given number of rows from the socket.
Returns a tuple with 2 elements: a list with all rows and
the EOF packet.
"""
rows = []
eof = None
rowdata = None
i = 0
while True:
if eof is not None:
break
if i == count:
break
packet = sock.recv()
if packet[0:3] == b'\xff\xff\xff':
data = packet[4:]
packet = sock.recv()
while packet[0:3] == b'\xff\xff\xff':
data += packet[4:]
packet = sock.recv()
if packet[4] == 254:
eof = self.parse_eof(packet)
else:
data += packet[4:]
rowdata = utils.read_lc_string_list(data)
elif packet[4] == 254:
eof = self.parse_eof(packet)
rowdata = None
else:
eof = None
rowdata = utils.read_lc_string_list(packet[4:])
if eof is None and rowdata is not None:
rows.append(rowdata)
i += 1
return (rows, eof) | [
"def",
"read_text_result",
"(",
"self",
",",
"sock",
",",
"count",
"=",
"1",
")",
":",
"rows",
"=",
"[",
"]",
"eof",
"=",
"None",
"rowdata",
"=",
"None",
"i",
"=",
"0",
"while",
"True",
":",
"if",
"eof",
"is",
"not",
"None",
":",
"break",
"if",
... | https://github.com/santatic/web2attack/blob/44b6e481a3d56cf0d98073ae0fb69833dda563d9/w2a/lib/mysql/connector/protocol.py#L214-L252 | |
ucbdrive/hd3 | 84792e27eec81ed27671018c231538e6de8cd6be | utils/png.py | python | Reader.asFloat | (self, maxval=1.0) | return x, y, iterfloat(), info | Return image pixels as per :meth:`asDirect` method, but scale
all pixel values to be floating point values between 0.0 and
*maxval*. | Return image pixels as per :meth:`asDirect` method, but scale
all pixel values to be floating point values between 0.0 and
*maxval*. | [
"Return",
"image",
"pixels",
"as",
"per",
":",
"meth",
":",
"asDirect",
"method",
"but",
"scale",
"all",
"pixel",
"values",
"to",
"be",
"floating",
"point",
"values",
"between",
"0",
".",
"0",
"and",
"*",
"maxval",
"*",
"."
] | def asFloat(self, maxval=1.0):
"""Return image pixels as per :meth:`asDirect` method, but scale
all pixel values to be floating point values between 0.0 and
*maxval*.
"""
x, y, pixels, info = self.asDirect()
sourcemaxval = 2**info['bitdepth'] - 1
del info['bitdepth']
info['maxval'] = float(maxval)
factor = float(maxval) / float(sourcemaxval)
def iterfloat():
for row in pixels:
yield [factor * p for p in row]
return x, y, iterfloat(), info | [
"def",
"asFloat",
"(",
"self",
",",
"maxval",
"=",
"1.0",
")",
":",
"x",
",",
"y",
",",
"pixels",
",",
"info",
"=",
"self",
".",
"asDirect",
"(",
")",
"sourcemaxval",
"=",
"2",
"**",
"info",
"[",
"'bitdepth'",
"]",
"-",
"1",
"del",
"info",
"[",
... | https://github.com/ucbdrive/hd3/blob/84792e27eec81ed27671018c231538e6de8cd6be/utils/png.py#L2050-L2066 | |
OWASP/ZSC | 5bb9fed69efdc17996be4856b54af632aaed87b0 | module/readline_windows/pyreadline/modes/basemode.py | python | BaseMode.forward_word_extend_selection | (self, e) | Move forward to the end of the next word. Words are composed of
letters and digits. | Move forward to the end of the next word. Words are composed of
letters and digits. | [
"Move",
"forward",
"to",
"the",
"end",
"of",
"the",
"next",
"word",
".",
"Words",
"are",
"composed",
"of",
"letters",
"and",
"digits",
"."
] | def forward_word_extend_selection(self, e): #
"""Move forward to the end of the next word. Words are composed of
letters and digits."""
self.l_buffer.forward_word_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"forward_word_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"#",
"self",
".",
"l_buffer",
".",
"forward_word_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | https://github.com/OWASP/ZSC/blob/5bb9fed69efdc17996be4856b54af632aaed87b0/module/readline_windows/pyreadline/modes/basemode.py#L386-L390 | ||
qutebrowser/qutebrowser | 3a2aaaacbf97f4bf0c72463f3da94ed2822a5442 | scripts/dev/build_release.py | python | _maybe_remove | (path) | Remove a path if it exists. | Remove a path if it exists. | [
"Remove",
"a",
"path",
"if",
"it",
"exists",
"."
] | def _maybe_remove(path):
"""Remove a path if it exists."""
try:
shutil.rmtree(path)
except FileNotFoundError:
pass | [
"def",
"_maybe_remove",
"(",
"path",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"except",
"FileNotFoundError",
":",
"pass"
] | https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/scripts/dev/build_release.py#L93-L98 | ||
EmbarkStudios/blender-tools | 68e5c367bc040b6f327ad9507aab4c7b5b0a559b | exporter/export_collection.py | python | get_export_filename | (export_name, export_type, include_extension=True) | return f"{export_type}_{export_name}{extension}" | Gets a preview of the export filename based on `export_name` and `export_type`. | Gets a preview of the export filename based on `export_name` and `export_type`. | [
"Gets",
"a",
"preview",
"of",
"the",
"export",
"filename",
"based",
"on",
"export_name",
"and",
"export_type",
"."
] | def get_export_filename(export_name, export_type, include_extension=True):
"""Gets a preview of the export filename based on `export_name` and `export_type`."""
export_name = validate_export_name(export_name)
extension = ("." + get_export_extension(export_type).lower()) if include_extension else ""
return f"{export_type}_{export_name}{extension}" | [
"def",
"get_export_filename",
"(",
"export_name",
",",
"export_type",
",",
"include_extension",
"=",
"True",
")",
":",
"export_name",
"=",
"validate_export_name",
"(",
"export_name",
")",
"extension",
"=",
"(",
"\".\"",
"+",
"get_export_extension",
"(",
"export_type... | https://github.com/EmbarkStudios/blender-tools/blob/68e5c367bc040b6f327ad9507aab4c7b5b0a559b/exporter/export_collection.py#L23-L27 | |
Rapptz/discord.py | 45d498c1b76deaf3b394d17ccf56112fa691d160 | discord/ui/select.py | python | Select.values | (self) | return self._selected_values | List[:class:`str`]: A list of values that have been selected by the user. | List[:class:`str`]: A list of values that have been selected by the user. | [
"List",
"[",
":",
"class",
":",
"str",
"]",
":",
"A",
"list",
"of",
"values",
"that",
"have",
"been",
"selected",
"by",
"the",
"user",
"."
] | def values(self) -> List[str]:
"""List[:class:`str`]: A list of values that have been selected by the user."""
return self._selected_values | [
"def",
"values",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_selected_values"
] | https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ui/select.py#L259-L261 | |
modflowpy/flopy | eecd1ad193c5972093c9712e5c4b7a83284f0688 | flopy/utils/recarray_utils.py | python | create_empty_recarray | (length, dtype, default_value=0) | return r.view(np.recarray) | Create a empty recarray with a defined default value for floats.
Parameters
----------
length : int
Shape of the empty recarray.
dtype : np.dtype
dtype of the empty recarray.
default_value : float
default value to use for floats in recarray.
Returns
-------
r : np.recarray
Recarray of type dtype with shape length.
Examples
--------
>>> import numpy as np
>>> import flopy
>>> dtype = np.dtype([('x', np.float32), ('y', np.float32)])
>>> ra = flopy.utils.create_empty_recarray(10, dtype) | Create a empty recarray with a defined default value for floats. | [
"Create",
"a",
"empty",
"recarray",
"with",
"a",
"defined",
"default",
"value",
"for",
"floats",
"."
] | def create_empty_recarray(length, dtype, default_value=0):
"""
Create a empty recarray with a defined default value for floats.
Parameters
----------
length : int
Shape of the empty recarray.
dtype : np.dtype
dtype of the empty recarray.
default_value : float
default value to use for floats in recarray.
Returns
-------
r : np.recarray
Recarray of type dtype with shape length.
Examples
--------
>>> import numpy as np
>>> import flopy
>>> dtype = np.dtype([('x', np.float32), ('y', np.float32)])
>>> ra = flopy.utils.create_empty_recarray(10, dtype)
"""
r = np.zeros(length, dtype=dtype)
msg = "dtype argument must be an instance of np.dtype, not list."
assert isinstance(dtype, np.dtype), msg
for name in dtype.names:
dt = dtype.fields[name][0]
if np.issubdtype(dt, np.float_):
r[name] = default_value
return r.view(np.recarray) | [
"def",
"create_empty_recarray",
"(",
"length",
",",
"dtype",
",",
"default_value",
"=",
"0",
")",
":",
"r",
"=",
"np",
".",
"zeros",
"(",
"length",
",",
"dtype",
"=",
"dtype",
")",
"msg",
"=",
"\"dtype argument must be an instance of np.dtype, not list.\"",
"ass... | https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/utils/recarray_utils.py#L4-L37 | |
richardaecn/class-balanced-loss | 1d7857208a2abc03d84e35a9d5383af8225d4b4d | tpu/models/official/retinanet/retinanet_model.py | python | add_metric_fn_inputs | (params, cls_outputs, box_outputs, metric_fn_inputs) | Selects top-k predictions and adds the selected to metric_fn_inputs.
Args:
params: a parameter dictionary that includes `min_level`, `max_level`,
`batch_size`, and `num_classes`.
cls_outputs: an OrderDict with keys representing levels and values
representing logits in [batch_size, height, width, num_anchors].
box_outputs: an OrderDict with keys representing levels and values
representing box regression targets in
[batch_size, height, width, num_anchors * 4].
metric_fn_inputs: a dictionary that will hold the top-k selections. | Selects top-k predictions and adds the selected to metric_fn_inputs. | [
"Selects",
"top",
"-",
"k",
"predictions",
"and",
"adds",
"the",
"selected",
"to",
"metric_fn_inputs",
"."
] | def add_metric_fn_inputs(params, cls_outputs, box_outputs, metric_fn_inputs):
"""Selects top-k predictions and adds the selected to metric_fn_inputs.
Args:
params: a parameter dictionary that includes `min_level`, `max_level`,
`batch_size`, and `num_classes`.
cls_outputs: an OrderDict with keys representing levels and values
representing logits in [batch_size, height, width, num_anchors].
box_outputs: an OrderDict with keys representing levels and values
representing box regression targets in
[batch_size, height, width, num_anchors * 4].
metric_fn_inputs: a dictionary that will hold the top-k selections.
"""
cls_outputs_all = []
box_outputs_all = []
# Concatenates class and box of all levels into one tensor.
for level in range(params['min_level'], params['max_level'] + 1):
cls_outputs_all.append(tf.reshape(
cls_outputs[level],
[params['batch_size'], -1, params['num_classes']]))
box_outputs_all.append(tf.reshape(
box_outputs[level], [params['batch_size'], -1, 4]))
cls_outputs_all = tf.concat(cls_outputs_all, 1)
box_outputs_all = tf.concat(box_outputs_all, 1)
# cls_outputs_all has a shape of [batch_size, N, num_classes] and
# box_outputs_all has a shape of [batch_size, N, 4]. The batch_size here
# is per-shard batch size. Recently, top-k on TPU supports batch
# dimension (b/67110441), but the following function performs top-k on
# each sample.
cls_outputs_all_after_topk = []
box_outputs_all_after_topk = []
indices_all = []
classes_all = []
for index in range(params['batch_size']):
cls_outputs_per_sample = cls_outputs_all[index]
box_outputs_per_sample = box_outputs_all[index]
cls_outputs_per_sample_reshape = tf.reshape(cls_outputs_per_sample,
[-1])
_, cls_topk_indices = tf.nn.top_k(
cls_outputs_per_sample_reshape, k=anchors.MAX_DETECTION_POINTS)
# Gets top-k class and box scores.
indices = tf.div(cls_topk_indices, params['num_classes'])
classes = tf.mod(cls_topk_indices, params['num_classes'])
cls_indices = tf.stack([indices, classes], axis=1)
cls_outputs_after_topk = tf.gather_nd(cls_outputs_per_sample,
cls_indices)
cls_outputs_all_after_topk.append(cls_outputs_after_topk)
box_outputs_after_topk = tf.gather_nd(
box_outputs_per_sample, tf.expand_dims(indices, 1))
box_outputs_all_after_topk.append(box_outputs_after_topk)
indices_all.append(indices)
classes_all.append(classes)
# Concatenates via the batch dimension.
cls_outputs_all_after_topk = tf.stack(cls_outputs_all_after_topk, axis=0)
box_outputs_all_after_topk = tf.stack(box_outputs_all_after_topk, axis=0)
indices_all = tf.stack(indices_all, axis=0)
classes_all = tf.stack(classes_all, axis=0)
metric_fn_inputs['cls_outputs_all'] = cls_outputs_all_after_topk
metric_fn_inputs['box_outputs_all'] = box_outputs_all_after_topk
metric_fn_inputs['indices_all'] = indices_all
metric_fn_inputs['classes_all'] = classes_all | [
"def",
"add_metric_fn_inputs",
"(",
"params",
",",
"cls_outputs",
",",
"box_outputs",
",",
"metric_fn_inputs",
")",
":",
"cls_outputs_all",
"=",
"[",
"]",
"box_outputs_all",
"=",
"[",
"]",
"# Concatenates class and box of all levels into one tensor.",
"for",
"level",
"i... | https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/official/retinanet/retinanet_model.py#L246-L308 | ||
onnx/sklearn-onnx | 8e19d19b8a9bcae7f17d5b7cc2514cf6b89f8199 | skl2onnx/common/tree_ensemble.py | python | find_switch_point | (fy, nfy) | return a | Finds the double so that
``(float)x != (float)(x + espilon)``. | Finds the double so that
``(float)x != (float)(x + espilon)``. | [
"Finds",
"the",
"double",
"so",
"that",
"(",
"float",
")",
"x",
"!",
"=",
"(",
"float",
")",
"(",
"x",
"+",
"espilon",
")",
"."
] | def find_switch_point(fy, nfy):
"""
Finds the double so that
``(float)x != (float)(x + espilon)``.
"""
a = np.float64(fy)
b = np.float64(nfy)
fa = np.float32(a)
a0, b0 = a, a
while a != a0 or b != b0:
a0, b0 = a, b
m = (a + b) / 2
fm = np.float32(m)
if fm == fa:
a = m
fa = fm
else:
b = m
return a | [
"def",
"find_switch_point",
"(",
"fy",
",",
"nfy",
")",
":",
"a",
"=",
"np",
".",
"float64",
"(",
"fy",
")",
"b",
"=",
"np",
".",
"float64",
"(",
"nfy",
")",
"fa",
"=",
"np",
".",
"float32",
"(",
"a",
")",
"a0",
",",
"b0",
"=",
"a",
",",
"a... | https://github.com/onnx/sklearn-onnx/blob/8e19d19b8a9bcae7f17d5b7cc2514cf6b89f8199/skl2onnx/common/tree_ensemble.py#L48-L66 | |
sxjscience/HKO-7 | adeb05a366d4b57f94a5ddb814af57cc62ffe3c5 | nowcasting/models/deconvolution_symbol.py | python | deconv2d_3d | (data,
num_filter,
kernel=(1, 1, 1),
stride=(1, 1, 1),
pad=(0, 0, 0),
adj=(0, 0, 0),
no_bias=True,
target_shape=None,
name=None,
use_3d=True,
**kwargs) | If use_3d == False use a 2D deconvolution with the same number of parameters. | If use_3d == False use a 2D deconvolution with the same number of parameters. | [
"If",
"use_3d",
"==",
"False",
"use",
"a",
"2D",
"deconvolution",
"with",
"the",
"same",
"number",
"of",
"parameters",
"."
] | def deconv2d_3d(data,
num_filter,
kernel=(1, 1, 1),
stride=(1, 1, 1),
pad=(0, 0, 0),
adj=(0, 0, 0),
no_bias=True,
target_shape=None,
name=None,
use_3d=True,
**kwargs):
"""If use_3d == False use a 2D deconvolution with the same number of parameters."""
if use_3d:
return deconv3d_act(
data=data,
num_filter=num_filter,
kernel=kernel,
stride=stride,
pad=pad,
adj=adj,
no_bias=no_bias,
target_shape=target_shape,
act_type=act_type,
name=name,
**kwargs)
else:
return deconv2d_act(
data=data,
num_filter=num_filter * kernel[0],
kernel=kernel[1:],
stride=stride[1:],
pad=pad[1:],
adj=adj[1:],
no_bias=no_bias,
target_shape=target_shape,
act_type=act_type,
name=name,
**kwargs) | [
"def",
"deconv2d_3d",
"(",
"data",
",",
"num_filter",
",",
"kernel",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"stride",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"pad",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"adj",
"=",
"(",
... | https://github.com/sxjscience/HKO-7/blob/adeb05a366d4b57f94a5ddb814af57cc62ffe3c5/nowcasting/models/deconvolution_symbol.py#L714-L751 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/entity.py | python | GeometryEntity.__new__ | (cls, *args, **kwargs) | return Basic.__new__(cls, *args) | [] | def __new__(cls, *args, **kwargs):
args = map(sympify, args)
return Basic.__new__(cls, *args) | [
"def",
"__new__",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"map",
"(",
"sympify",
",",
"args",
")",
"return",
"Basic",
".",
"__new__",
"(",
"cls",
",",
"*",
"args",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/entity.py#L42-L44 | |||
nithinmurali/pygsheets | 09e985ccfe0585e8aa0633af8d0c0f038e3b3e1a | pygsheets/client.py | python | Client.teamDriveId | (self) | return self.drive.team_drive_id | Enable team drive support
Deprecated: use client.drive.enable_team_drive(team_drive_id=?) | Enable team drive support | [
"Enable",
"team",
"drive",
"support"
] | def teamDriveId(self):
""" Enable team drive support
Deprecated: use client.drive.enable_team_drive(team_drive_id=?)
"""
return self.drive.team_drive_id | [
"def",
"teamDriveId",
"(",
"self",
")",
":",
"return",
"self",
".",
"drive",
".",
"team_drive_id"
] | https://github.com/nithinmurali/pygsheets/blob/09e985ccfe0585e8aa0633af8d0c0f038e3b3e1a/pygsheets/client.py#L65-L70 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/thirdparty/beautifulsoup/beautifulsoup.py | python | PageElement.nextSiblingGenerator | (self) | [] | def nextSiblingGenerator(self):
i = self
while i is not None:
i = i.nextSibling
yield i | [
"def",
"nextSiblingGenerator",
"(",
"self",
")",
":",
"i",
"=",
"self",
"while",
"i",
"is",
"not",
"None",
":",
"i",
"=",
"i",
".",
"nextSibling",
"yield",
"i"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/beautifulsoup/beautifulsoup.py#L377-L381 | ||||
BruceDone/scrapy_demo | eeb4c1d035b45276309212260950a9aed6f69911 | ka/ka/spiders/cnblogs.py | python | ListeningKafkaSpider.spider_idle | (self) | Schedules a request if available, otherwise waits. | Schedules a request if available, otherwise waits. | [
"Schedules",
"a",
"request",
"if",
"available",
"otherwise",
"waits",
"."
] | def spider_idle(self):
"""Schedules a request if available, otherwise waits."""
self.schedule_next_request()
raise DontCloseSpider | [
"def",
"spider_idle",
"(",
"self",
")",
":",
"self",
".",
"schedule_next_request",
"(",
")",
"raise",
"DontCloseSpider"
] | https://github.com/BruceDone/scrapy_demo/blob/eeb4c1d035b45276309212260950a9aed6f69911/ka/ka/spiders/cnblogs.py#L79-L82 | ||
wxWidgets/Phoenix | b2199e299a6ca6d866aa6f3d0888499136ead9d6 | wx/lib/agw/peakmeter.py | python | PeakMeterCtrl.SetBackgroundColour | (self, colourBgnd) | Changes the background colour of :class:`PeakMeterCtrl`.
:param `colourBgnd`: the colour to be used as the background colour, pass
:class:`NullColour` to reset to the default colour.
:note: The background colour is usually painted by the default :class:`EraseEvent`
event handler function under Windows and automatically under GTK.
:note: Setting the background colour does not cause an immediate refresh, so
you may wish to call :meth:`wx.Window.ClearBackground` or :meth:`wx.Window.Refresh` after
calling this function.
:note: Overridden from :class:`wx.Control`. | Changes the background colour of :class:`PeakMeterCtrl`. | [
"Changes",
"the",
"background",
"colour",
"of",
":",
"class",
":",
"PeakMeterCtrl",
"."
] | def SetBackgroundColour(self, colourBgnd):
"""
Changes the background colour of :class:`PeakMeterCtrl`.
:param `colourBgnd`: the colour to be used as the background colour, pass
:class:`NullColour` to reset to the default colour.
:note: The background colour is usually painted by the default :class:`EraseEvent`
event handler function under Windows and automatically under GTK.
:note: Setting the background colour does not cause an immediate refresh, so
you may wish to call :meth:`wx.Window.ClearBackground` or :meth:`wx.Window.Refresh` after
calling this function.
:note: Overridden from :class:`wx.Control`.
"""
wx.Control.SetBackgroundColour(self, colourBgnd)
self._clrBackground = colourBgnd
self.Refresh() | [
"def",
"SetBackgroundColour",
"(",
"self",
",",
"colourBgnd",
")",
":",
"wx",
".",
"Control",
".",
"SetBackgroundColour",
"(",
"self",
",",
"colourBgnd",
")",
"self",
".",
"_clrBackground",
"=",
"colourBgnd",
"self",
".",
"Refresh",
"(",
")"
] | https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/peakmeter.py#L397-L416 | ||
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/caldav/icalendardirectoryservice.py | python | ICalendarStoreDirectoryRecord.proxyFor | (readWrite, ignoreDisabled=True) | Returns the set of records currently delegating to this record
with the access indicated by the readWrite argument. If readWrite is
True, then write-access delegators are returned, otherwise the read-
only-access delegators are returned.
@param readWrite: Whether to look up read-write delegators, or
read-only delegators
@type readWrite: L{bool}
@param ignoreDisabled: If L{True} disabled delegators are not returned
@type ignoreDisabled: L{bool}
@return: A Deferred firing with a set of records | Returns the set of records currently delegating to this record
with the access indicated by the readWrite argument. If readWrite is
True, then write-access delegators are returned, otherwise the read-
only-access delegators are returned. | [
"Returns",
"the",
"set",
"of",
"records",
"currently",
"delegating",
"to",
"this",
"record",
"with",
"the",
"access",
"indicated",
"by",
"the",
"readWrite",
"argument",
".",
"If",
"readWrite",
"is",
"True",
"then",
"write",
"-",
"access",
"delegators",
"are",
... | def proxyFor(readWrite, ignoreDisabled=True): # @NoSelf
"""
Returns the set of records currently delegating to this record
with the access indicated by the readWrite argument. If readWrite is
True, then write-access delegators are returned, otherwise the read-
only-access delegators are returned.
@param readWrite: Whether to look up read-write delegators, or
read-only delegators
@type readWrite: L{bool}
@param ignoreDisabled: If L{True} disabled delegators are not returned
@type ignoreDisabled: L{bool}
@return: A Deferred firing with a set of records
""" | [
"def",
"proxyFor",
"(",
"readWrite",
",",
"ignoreDisabled",
"=",
"True",
")",
":",
"# @NoSelf"
] | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/caldav/icalendardirectoryservice.py#L136-L150 | ||
Sekunde/3D-SIS | b90018a68df1fd14c4ad6f16702e9c74f309f11f | lib/utils/logger.py | python | Logger.scalar_summary | (self, tag, value, step) | Log a scalar variable. | Log a scalar variable. | [
"Log",
"a",
"scalar",
"variable",
"."
] | def scalar_summary(self, tag, value, step):
"""Log a scalar variable."""
summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])
self.writer.add_summary(summary, step) | [
"def",
"scalar_summary",
"(",
"self",
",",
"tag",
",",
"value",
",",
"step",
")",
":",
"summary",
"=",
"tf",
".",
"Summary",
"(",
"value",
"=",
"[",
"tf",
".",
"Summary",
".",
"Value",
"(",
"tag",
"=",
"tag",
",",
"simple_value",
"=",
"value",
")",... | https://github.com/Sekunde/3D-SIS/blob/b90018a68df1fd14c4ad6f16702e9c74f309f11f/lib/utils/logger.py#L17-L20 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/dateutil/parser/_parser.py | python | parserinfo.ampm | (self, name) | [] | def ampm(self, name):
try:
return self._ampm[name.lower()]
except KeyError:
return None | [
"def",
"ampm",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"_ampm",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/dateutil/parser/_parser.py#L342-L346 | ||||
probcomp/bayeslite | 211e5eb3821a464a2fffeb9d35e3097e1b7a99ba | src/parse.py | python | bql_string_complete_p | (string) | return (not nonsemi) or (semantics.phrase is not None) | True if `string` has at least one complete BQL phrase or error.
False if empty or if the last BQL phrase is incomplete. | True if `string` has at least one complete BQL phrase or error. | [
"True",
"if",
"string",
"has",
"at",
"least",
"one",
"complete",
"BQL",
"phrase",
"or",
"error",
"."
] | def bql_string_complete_p(string):
"""True if `string` has at least one complete BQL phrase or error.
False if empty or if the last BQL phrase is incomplete.
"""
scanner = scan.BQLScanner(StringIO.StringIO(string), '(string)')
semantics = BQLSemantics()
parser = grammar.Parser(semantics)
nonsemi = False
while not semantics.failed:
token = scanner.read()
if token[0] == -1: # error
# Say it's complete so the caller will try to parse it and
# choke on the error.
return True
elif token[0] == 0:
# EOF. Hope we have a complete phrase.
break
elif token[0] != grammar.T_SEMI:
# Got a non-semicolon token. Clear any previous phrase,
# if we had one.
nonsemi = True
semantics.phrase = None
parser.feed(token)
if 0 < len(semantics.errors):
return True
if semantics.failed:
return True
return (not nonsemi) or (semantics.phrase is not None) | [
"def",
"bql_string_complete_p",
"(",
"string",
")",
":",
"scanner",
"=",
"scan",
".",
"BQLScanner",
"(",
"StringIO",
".",
"StringIO",
"(",
"string",
")",
",",
"'(string)'",
")",
"semantics",
"=",
"BQLSemantics",
"(",
")",
"parser",
"=",
"grammar",
".",
"Pa... | https://github.com/probcomp/bayeslite/blob/211e5eb3821a464a2fffeb9d35e3097e1b7a99ba/src/parse.py#L86-L114 | |
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idautils.py | python | Structs | () | Get a list of structures
@return: List of tuples (idx, sid, name) | Get a list of structures | [
"Get",
"a",
"list",
"of",
"structures"
] | def Structs():
"""
Get a list of structures
@return: List of tuples (idx, sid, name)
"""
idx = idc.GetFirstStrucIdx()
while idx != idaapi.BADADDR:
sid = idc.GetStrucId(idx)
yield (idx, sid, idc.GetStrucName(sid))
idx = idc.GetNextStrucIdx(idx) | [
"def",
"Structs",
"(",
")",
":",
"idx",
"=",
"idc",
".",
"GetFirstStrucIdx",
"(",
")",
"while",
"idx",
"!=",
"idaapi",
".",
"BADADDR",
":",
"sid",
"=",
"idc",
".",
"GetStrucId",
"(",
"idx",
")",
"yield",
"(",
"idx",
",",
"sid",
",",
"idc",
".",
"... | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idautils.py#L318-L328 | ||
rockstor/rockstor-core | 81a0d5f5e0a6dfe5a922199828f66eeab0253e65 | src/rockstor/cli/share_detail_console.py | python | ShareDetailConsole.do_snapshot | (self, args) | snapshot operations on the share | snapshot operations on the share | [
"snapshot",
"operations",
"on",
"the",
"share"
] | def do_snapshot(self, args):
"""
snapshot operations on the share
"""
input_snap = args.split()
snap_console = SnapshotConsole(self.greeting, self.share)
if len(input_snap) > 0:
return snap_console.onecmd(" ".join(input_snap))
snap_console.cmdloop() | [
"def",
"do_snapshot",
"(",
"self",
",",
"args",
")",
":",
"input_snap",
"=",
"args",
".",
"split",
"(",
")",
"snap_console",
"=",
"SnapshotConsole",
"(",
"self",
".",
"greeting",
",",
"self",
".",
"share",
")",
"if",
"len",
"(",
"input_snap",
")",
">",... | https://github.com/rockstor/rockstor-core/blob/81a0d5f5e0a6dfe5a922199828f66eeab0253e65/src/rockstor/cli/share_detail_console.py#L60-L68 | ||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v2beta2_metric_spec.py | python | V2beta2MetricSpec.__repr__ | (self) | return self.to_str() | For `print` and `pprint` | For `print` and `pprint` | [
"For",
"print",
"and",
"pprint"
] | def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str() | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"self",
".",
"to_str",
"(",
")"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v2beta2_metric_spec.py#L211-L213 | |
Ericsson/codechecker | c4e43f62dc3acbf71d3109b337db7c97f7852f43 | tools/report-converter/codechecker_report_converter/report/parser/plist.py | python | Parser._get_bug_path_event_range | (self, event: BugPathEvent) | return Range(event.line, event.column, event.line, event.column) | Get range for bug path event. | Get range for bug path event. | [
"Get",
"range",
"for",
"bug",
"path",
"event",
"."
] | def _get_bug_path_event_range(self, event: BugPathEvent) -> Range:
""" Get range for bug path event. """
if event.range:
return event.range
return Range(event.line, event.column, event.line, event.column) | [
"def",
"_get_bug_path_event_range",
"(",
"self",
",",
"event",
":",
"BugPathEvent",
")",
"->",
"Range",
":",
"if",
"event",
".",
"range",
":",
"return",
"event",
".",
"range",
"return",
"Range",
"(",
"event",
".",
"line",
",",
"event",
".",
"column",
","... | https://github.com/Ericsson/codechecker/blob/c4e43f62dc3acbf71d3109b337db7c97f7852f43/tools/report-converter/codechecker_report_converter/report/parser/plist.py#L542-L547 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/_datasource.py | python | DataSource.abspath | (self, path) | return os.path.join(self._destpath, netloc, upath) | Return absolute path of file in the DataSource directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----------
path : str
Can be a local file or a remote URL.
Returns
-------
out : str
Complete path, including the `DataSource` destination directory.
Notes
-----
The functionality is based on `os.path.abspath`. | Return absolute path of file in the DataSource directory. | [
"Return",
"absolute",
"path",
"of",
"file",
"in",
"the",
"DataSource",
"directory",
"."
] | def abspath(self, path):
"""
Return absolute path of file in the DataSource directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----------
path : str
Can be a local file or a remote URL.
Returns
-------
out : str
Complete path, including the `DataSource` destination directory.
Notes
-----
The functionality is based on `os.path.abspath`.
"""
# We do this here to reduce the 'import numpy' initial import time.
if sys.version_info[0] >= 3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
# TODO: This should be more robust. Handles case where path includes
# the destpath, but not other sub-paths. Failing case:
# path = /home/guido/datafile.txt
# destpath = /home/alex/
# upath = self.abspath(path)
# upath == '/home/alex/home/guido/datafile.txt'
# handle case where path includes self._destpath
splitpath = path.split(self._destpath, 2)
if len(splitpath) > 1:
path = splitpath[1]
scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
netloc = self._sanitize_relative_path(netloc)
upath = self._sanitize_relative_path(upath)
return os.path.join(self._destpath, netloc, upath) | [
"def",
"abspath",
"(",
"self",
",",
"path",
")",
":",
"# We do this here to reduce the 'import numpy' initial import time.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">=",
"3",
":",
"from",
"urllib",
".",
"parse",
"import",
"urlparse",
"else",
":",
"from... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/_datasource.py#L343-L386 | |
funnyzhou/FPN-Pytorch | 423a4499c4e826d17367762e821b51b9b1b0f2f3 | lib/datasets/roidb.py | python | extend_with_flipped_entries | (roidb, dataset) | Flip each entry in the given roidb and return a new roidb that is the
concatenation of the original roidb and the flipped entries.
"Flipping" an entry means that that image and associated metadata (e.g.,
ground truth boxes and object proposals) are horizontally flipped. | Flip each entry in the given roidb and return a new roidb that is the
concatenation of the original roidb and the flipped entries. | [
"Flip",
"each",
"entry",
"in",
"the",
"given",
"roidb",
"and",
"return",
"a",
"new",
"roidb",
"that",
"is",
"the",
"concatenation",
"of",
"the",
"original",
"roidb",
"and",
"the",
"flipped",
"entries",
"."
] | def extend_with_flipped_entries(roidb, dataset):
"""Flip each entry in the given roidb and return a new roidb that is the
concatenation of the original roidb and the flipped entries.
"Flipping" an entry means that that image and associated metadata (e.g.,
ground truth boxes and object proposals) are horizontally flipped.
"""
flipped_roidb = []
for entry in roidb:
width = entry['width']
boxes = entry['boxes'].copy()
oldx1 = boxes[:, 0].copy()
oldx2 = boxes[:, 2].copy()
boxes[:, 0] = width - oldx2 - 1
boxes[:, 2] = width - oldx1 - 1
assert (boxes[:, 2] >= boxes[:, 0]).all()
flipped_entry = {}
dont_copy = ('boxes', 'segms', 'gt_keypoints', 'flipped')
for k, v in entry.items():
if k not in dont_copy:
flipped_entry[k] = v
flipped_entry['boxes'] = boxes
flipped_entry['segms'] = segm_utils.flip_segms(
entry['segms'], entry['height'], entry['width']
)
if dataset.keypoints is not None:
flipped_entry['gt_keypoints'] = keypoint_utils.flip_keypoints(
dataset.keypoints, dataset.keypoint_flip_map,
entry['gt_keypoints'], entry['width']
)
flipped_entry['flipped'] = True
flipped_roidb.append(flipped_entry)
roidb.extend(flipped_roidb) | [
"def",
"extend_with_flipped_entries",
"(",
"roidb",
",",
"dataset",
")",
":",
"flipped_roidb",
"=",
"[",
"]",
"for",
"entry",
"in",
"roidb",
":",
"width",
"=",
"entry",
"[",
"'width'",
"]",
"boxes",
"=",
"entry",
"[",
"'boxes'",
"]",
".",
"copy",
"(",
... | https://github.com/funnyzhou/FPN-Pytorch/blob/423a4499c4e826d17367762e821b51b9b1b0f2f3/lib/datasets/roidb.py#L84-L116 | ||
django-mptt/django-mptt | 7a6a54c6d2572a45ea63bd639c25507108fff3e6 | mptt/models.py | python | classpropertytype.__init__ | (self, name, bases=(), members={}) | return super().__init__(
members.get("__get__"),
members.get("__set__"),
members.get("__delete__"),
members.get("__doc__"),
) | [] | def __init__(self, name, bases=(), members={}):
return super().__init__(
members.get("__get__"),
members.get("__set__"),
members.get("__delete__"),
members.get("__doc__"),
) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"bases",
"=",
"(",
")",
",",
"members",
"=",
"{",
"}",
")",
":",
"return",
"super",
"(",
")",
".",
"__init__",
"(",
"members",
".",
"get",
"(",
"\"__get__\"",
")",
",",
"members",
".",
"get",
"(",... | https://github.com/django-mptt/django-mptt/blob/7a6a54c6d2572a45ea63bd639c25507108fff3e6/mptt/models.py#L44-L50 | |||
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | docs/source/developer/inline_overload_example.py | python | ol_bar_scalar | (x) | [] | def ol_bar_scalar(x):
# An overload that will inline based on a cost model, it only applies to
# scalar values in the numerical domain as per the type guard on Number
if isinstance(x, types.Number):
def impl(x):
return x + 1
return impl | [
"def",
"ol_bar_scalar",
"(",
"x",
")",
":",
"# An overload that will inline based on a cost model, it only applies to",
"# scalar values in the numerical domain as per the type guard on Number",
"if",
"isinstance",
"(",
"x",
",",
"types",
".",
"Number",
")",
":",
"def",
"impl",... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/docs/source/developer/inline_overload_example.py#L27-L33 | ||||
mrlesmithjr/Ansible | d44f0dc0d942bdf3bf7334b307e6048f0ee16e36 | roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py | python | Session.put | (self, url, data=None, **kwargs) | return self.request('PUT', url, data=data, **kwargs) | Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response | Sends a PUT request. Returns :class:`Response` object. | [
"Sends",
"a",
"PUT",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def put(self, url, data=None, **kwargs):
"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PUT', url, data=data, **kwargs) | [
"def",
"put",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'PUT'",
",",
"url",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/sessions.py#L524-L533 | |
p2pool/p2pool | 53c438bbada06b9d4a9a465bc13f7694a7a322b7 | wstools/WSDLTools.py | python | Binding.__init__ | (self, name, type, documentation='') | [] | def __init__(self, name, type, documentation=''):
Element.__init__(self, name, documentation)
self.operations = Collection(self)
self.type = type | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"type",
",",
"documentation",
"=",
"''",
")",
":",
"Element",
".",
"__init__",
"(",
"self",
",",
"name",
",",
"documentation",
")",
"self",
".",
"operations",
"=",
"Collection",
"(",
"self",
")",
"self"... | https://github.com/p2pool/p2pool/blob/53c438bbada06b9d4a9a465bc13f7694a7a322b7/wstools/WSDLTools.py#L765-L768 | ||||
SFDO-Tooling/CumulusCI | 825ae1f122b25dc41761c52a4ddfa1938d2a4b6e | cumulusci/utils/xml/metadata_tree.py | python | MetadataElement.find | (self, tag, **kwargs) | return next(self._findall(tag, kwargs), None) | Find a single direct child-elements with name `tag` | Find a single direct child-elements with name `tag` | [
"Find",
"a",
"single",
"direct",
"child",
"-",
"elements",
"with",
"name",
"tag"
] | def find(self, tag, **kwargs):
"""Find a single direct child-elements with name `tag`"""
return next(self._findall(tag, kwargs), None) | [
"def",
"find",
"(",
"self",
",",
"tag",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"next",
"(",
"self",
".",
"_findall",
"(",
"tag",
",",
"kwargs",
")",
",",
"None",
")"
] | https://github.com/SFDO-Tooling/CumulusCI/blob/825ae1f122b25dc41761c52a4ddfa1938d2a4b6e/cumulusci/utils/xml/metadata_tree.py#L228-L230 | |
talkpython/mastering-pycharm-course | d9c578e9d1b06797a27e8e8ddea05da1eab742a5 | demos/projects/databases/pypi_org/bin/load_data.py | python | do_import_languages | (file_data: List[dict]) | [] | def do_import_languages(file_data: List[dict]):
imported = set()
print("Importing languages ... ", flush=True)
with progressbar.ProgressBar(max_value=len(file_data)) as bar:
for idx, p in enumerate(file_data):
info = p.get('info')
classifiers = info.get('classifiers')
for c in classifiers:
if 'Programming Language' not in c:
continue
original = c
c = c.replace('Implementation ::', '').replace('::', ':')
text = c
parts = c.split(':')
if len(parts) > 1:
text = ' '.join(parts[-2:]).strip().replace(' ', ' ')
if text not in imported:
imported.add(text)
session = db_session.create_session()
lang = ProgrammingLanguage()
lang.description = original
lang.id = text
session.add(lang)
session.commit()
bar.update(idx)
sys.stderr.flush()
sys.stdout.flush() | [
"def",
"do_import_languages",
"(",
"file_data",
":",
"List",
"[",
"dict",
"]",
")",
":",
"imported",
"=",
"set",
"(",
")",
"print",
"(",
"\"Importing languages ... \"",
",",
"flush",
"=",
"True",
")",
"with",
"progressbar",
".",
"ProgressBar",
"(",
"max_valu... | https://github.com/talkpython/mastering-pycharm-course/blob/d9c578e9d1b06797a27e8e8ddea05da1eab742a5/demos/projects/databases/pypi_org/bin/load_data.py#L40-L72 | ||||
Kismuz/btgym | 7fb3316e67f1d7a17c620630fb62fb29428b2cec | btgym/research/strategy_gen_7/base.py | python | BaseStrategy7._get_timestamp | (self) | return self.time_stamp | Sets attr. and returns current data timestamp.
Returns:
POSIX timestamp | Sets attr. and returns current data timestamp. | [
"Sets",
"attr",
".",
"and",
"returns",
"current",
"data",
"timestamp",
"."
] | def _get_timestamp(self):
"""
Sets attr. and returns current data timestamp.
Returns:
POSIX timestamp
"""
self.time_stamp = self._get_time().timestamp()
return self.time_stamp | [
"def",
"_get_timestamp",
"(",
"self",
")",
":",
"self",
".",
"time_stamp",
"=",
"self",
".",
"_get_time",
"(",
")",
".",
"timestamp",
"(",
")",
"return",
"self",
".",
"time_stamp"
] | https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/research/strategy_gen_7/base.py#L685-L694 | |
EmbarkStudios/blender-tools | 68e5c367bc040b6f327ad9507aab4c7b5b0a559b | operators/update.py | python | unregister | () | Unregister the operator classes. | Unregister the operator classes. | [
"Unregister",
"the",
"operator",
"classes",
"."
] | def unregister():
"""Unregister the operator classes."""
for cls in reversed(__classes__):
bpy.utils.unregister_class(cls) | [
"def",
"unregister",
"(",
")",
":",
"for",
"cls",
"in",
"reversed",
"(",
"__classes__",
")",
":",
"bpy",
".",
"utils",
".",
"unregister_class",
"(",
"cls",
")"
] | https://github.com/EmbarkStudios/blender-tools/blob/68e5c367bc040b6f327ad9507aab4c7b5b0a559b/operators/update.py#L250-L253 | ||
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/email/_header_value_parser.py | python | get_extended_attribute | (value) | return attribute, value | [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string. | [CFWS] 1*extended_attrtext [CFWS] | [
"[",
"CFWS",
"]",
"1",
"*",
"extended_attrtext",
"[",
"CFWS",
"]"
] | def get_extended_attribute(value):
""" [CFWS] 1*extended_attrtext [CFWS]
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string.
"""
# XXX: should we have an ExtendedAttribute TokenList?
attribute = Attribute()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
attribute.append(token)
if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
raise errors.HeaderParseError(
"expected token but found '{}'".format(value))
token, value = get_extended_attrtext(value)
attribute.append(token)
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
attribute.append(token)
return attribute, value | [
"def",
"get_extended_attribute",
"(",
"value",
")",
":",
"# XXX: should we have an ExtendedAttribute TokenList?",
"attribute",
"=",
"Attribute",
"(",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"CFWS_LEADER",
":",
"token",
",",
"value",
"=",
"get_cfws... | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/email/_header_value_parser.py#L2337-L2357 | |
zacharski/pg2dm-python | cff97fc827052ab3032b89bb64455d540c4e15b5 | ch8/kmeansPlusPlus.py | python | kClusterer.assignPointToCluster | (self, i) | return clusterNum | assign point to cluster based on distance from centroids | assign point to cluster based on distance from centroids | [
"assign",
"point",
"to",
"cluster",
"based",
"on",
"distance",
"from",
"centroids"
] | def assignPointToCluster(self, i):
""" assign point to cluster based on distance from centroids"""
min = 999999
clusterNum = -1
for centroid in range(self.k):
dist = self.euclideanDistance(i, centroid)
if dist < min:
min = dist
clusterNum = centroid
# here is where I will keep track of changing points
if clusterNum != self.memberOf[i]:
self.pointsChanged += 1
# add square of distance to running sum of squared error
self.sse += min**2
return clusterNum | [
"def",
"assignPointToCluster",
"(",
"self",
",",
"i",
")",
":",
"min",
"=",
"999999",
"clusterNum",
"=",
"-",
"1",
"for",
"centroid",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"dist",
"=",
"self",
".",
"euclideanDistance",
"(",
"i",
",",
"centr... | https://github.com/zacharski/pg2dm-python/blob/cff97fc827052ab3032b89bb64455d540c4e15b5/ch8/kmeansPlusPlus.py#L152-L166 | |
mesonbuild/meson | a22d0f9a0a787df70ce79b05d0c45de90a970048 | mesonbuild/compilers/mixins/visualstudio.py | python | VisualStudioLikeCompiler.openmp_flags | (self) | return ['/openmp'] | [] | def openmp_flags(self) -> T.List[str]:
return ['/openmp'] | [
"def",
"openmp_flags",
"(",
"self",
")",
"->",
"T",
".",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"'/openmp'",
"]"
] | https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/visualstudio.py#L208-L209 | |||
nvdv/vprof | 8898b528b4a6bea6384a2b5dbe8f38b03a47bfda | vprof/base_profiler.py | python | run_in_separate_process | (func, *args, **kwargs) | return process.output | Runs function in separate process.
This function is used instead of a decorator, since Python multiprocessing
module can't serialize decorated function on all platforms. | Runs function in separate process. | [
"Runs",
"function",
"in",
"separate",
"process",
"."
] | def run_in_separate_process(func, *args, **kwargs):
"""Runs function in separate process.
This function is used instead of a decorator, since Python multiprocessing
module can't serialize decorated function on all platforms.
"""
manager = multiprocessing.Manager()
manager_dict = manager.dict()
process = ProcessWithException(
manager_dict, target=func, args=args, kwargs=kwargs)
process.start()
process.join()
exc = process.exception
if exc:
raise exc
return process.output | [
"def",
"run_in_separate_process",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"multiprocessing",
".",
"Manager",
"(",
")",
"manager_dict",
"=",
"manager",
".",
"dict",
"(",
")",
"process",
"=",
"ProcessWithException",
... | https://github.com/nvdv/vprof/blob/8898b528b4a6bea6384a2b5dbe8f38b03a47bfda/vprof/base_profiler.py#L65-L80 | |
deepmind/dm-haiku | c7fa5908f61dec1df3b8e25031987a6dcc07ee9f | haiku/_src/basic.py | python | Sequential.__call__ | (self, inputs, *args, **kwargs) | return out | Calls all layers sequentially. | Calls all layers sequentially. | [
"Calls",
"all",
"layers",
"sequentially",
"."
] | def __call__(self, inputs, *args, **kwargs):
"""Calls all layers sequentially."""
out = inputs
for i, layer in enumerate(self.layers):
if i == 0:
out = layer(out, *args, **kwargs)
else:
out = layer(out)
return out | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"inputs",
"for",
"i",
",",
"layer",
"in",
"enumerate",
"(",
"self",
".",
"layers",
")",
":",
"if",
"i",
"==",
"0",
":",
"out",
"=",
... | https://github.com/deepmind/dm-haiku/blob/c7fa5908f61dec1df3b8e25031987a6dcc07ee9f/haiku/_src/basic.py#L116-L124 | |
liyibo/text-classification-demos | 2bc3f56e0eb2b028565881c91db26a589b050db8 | bert/run_classifier.py | python | InputFeatures.__init__ | (self, input_ids, input_mask, segment_ids, label_id) | [] | def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id | [
"def",
"__init__",
"(",
"self",
",",
"input_ids",
",",
"input_mask",
",",
"segment_ids",
",",
"label_id",
")",
":",
"self",
".",
"input_ids",
"=",
"input_ids",
"self",
".",
"input_mask",
"=",
"input_mask",
"self",
".",
"segment_ids",
"=",
"segment_ids",
"sel... | https://github.com/liyibo/text-classification-demos/blob/2bc3f56e0eb2b028565881c91db26a589b050db8/bert/run_classifier.py#L153-L157 | ||||
cronyo/cronyo | cd5abab0871b68bf31b18aac934303928130a441 | cronyo/deploy.py | python | rollback_lambda | (name, alias=LIVE) | [] | def rollback_lambda(name, alias=LIVE):
all_versions = _versions(name)
live_version = _get_version(name, alias)
try:
live_index = all_versions.index(live_version)
if live_index < 1:
raise RuntimeError('Cannot find previous version')
prev_version = all_versions[live_index - 1]
logger.info('rolling back to version {}'.format(prev_version))
_function_alias(name, prev_version)
except RuntimeError as error:
logger.error('Unable to rollback. {}'.format(repr(error))) | [
"def",
"rollback_lambda",
"(",
"name",
",",
"alias",
"=",
"LIVE",
")",
":",
"all_versions",
"=",
"_versions",
"(",
"name",
")",
"live_version",
"=",
"_get_version",
"(",
"name",
",",
"alias",
")",
"try",
":",
"live_index",
"=",
"all_versions",
".",
"index"... | https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/deploy.py#L164-L175 | ||||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/patched/notpip/_vendor/colorama/ansitowin32.py | python | StreamWrapper.closed | (self) | [] | def closed(self):
stream = self.__wrapped
try:
return stream.closed
except AttributeError:
return True | [
"def",
"closed",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"__wrapped",
"try",
":",
"return",
"stream",
".",
"closed",
"except",
"AttributeError",
":",
"return",
"True"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/colorama/ansitowin32.py#L56-L61 | ||||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/metagoofil/hachoir_core/log.py | python | Logger.info | (self, text) | [] | def info(self, text):
log.newMessage(Log.LOG_INFO, text, self) | [
"def",
"info",
"(",
"self",
",",
"text",
")",
":",
"log",
".",
"newMessage",
"(",
"Log",
".",
"LOG_INFO",
",",
"text",
",",
"self",
")"
] | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_core/log.py#L139-L140 | ||||
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/isql.py | python | IsqlCmd.do_schema | (self, arg) | return False | \nPrints schema information.\n | \nPrints schema information.\n | [
"\\",
"nPrints",
"schema",
"information",
".",
"\\",
"n"
] | def do_schema(self, arg):
"""\nPrints schema information.\n"""
print
self.db.schema(arg)
print
return False | [
"def",
"do_schema",
"(",
"self",
",",
"arg",
")",
":",
"print",
"self",
".",
"db",
".",
"schema",
"(",
"arg",
")",
"print",
"return",
"False"
] | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/isql.py#L98-L103 | |
Khan/slicker | 751c663064d152a78f7bf2cf1384e3c337f566c1 | slicker/util.py | python | toplevel_names | (file_info) | return retval | Return a dict of name -> AST node with toplevel definitions in the file.
This includes function definitions, class definitions, and constants. | Return a dict of name -> AST node with toplevel definitions in the file. | [
"Return",
"a",
"dict",
"of",
"name",
"-",
">",
"AST",
"node",
"with",
"toplevel",
"definitions",
"in",
"the",
"file",
"."
] | def toplevel_names(file_info):
"""Return a dict of name -> AST node with toplevel definitions in the file.
This includes function definitions, class definitions, and constants.
"""
# TODO(csilvers): traverse try/except, for, etc, and complain
# if we see the symbol defined inside there.
# TODO(benkraft): Figure out how to handle ast.AugAssign (+=) and multiple
# assignments like `a, b = x, y`.
retval = {}
for top_level_stmt in file_info.tree.body:
if isinstance(top_level_stmt, (ast.FunctionDef, ast.ClassDef)):
retval[top_level_stmt.name] = top_level_stmt
elif isinstance(top_level_stmt, ast.Assign):
# Ignore assignments like 'a, b = x, y', and 'x.y = 5'
if (len(top_level_stmt.targets) == 1 and
isinstance(top_level_stmt.targets[0], ast.Name)):
retval[top_level_stmt.targets[0].id] = top_level_stmt
return retval | [
"def",
"toplevel_names",
"(",
"file_info",
")",
":",
"# TODO(csilvers): traverse try/except, for, etc, and complain",
"# if we see the symbol defined inside there.",
"# TODO(benkraft): Figure out how to handle ast.AugAssign (+=) and multiple",
"# assignments like `a, b = x, y`.",
"retval",
"="... | https://github.com/Khan/slicker/blob/751c663064d152a78f7bf2cf1384e3c337f566c1/slicker/util.py#L127-L145 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | process/datadog_checks/process/lock.py | python | ReadWriteCondition.remove_writer | (self) | Releases the condition, making the underlying object available for
read or write operations. | Releases the condition, making the underlying object available for
read or write operations. | [
"Releases",
"the",
"condition",
"making",
"the",
"underlying",
"object",
"available",
"for",
"read",
"or",
"write",
"operations",
"."
] | def remove_writer(self):
"""Releases the condition, making the underlying object available for
read or write operations."""
self._condition.release() | [
"def",
"remove_writer",
"(",
"self",
")",
":",
"self",
".",
"_condition",
".",
"release",
"(",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/process/datadog_checks/process/lock.py#L59-L62 | ||
gkrizek/bash-lambda-layer | 703b0ade8174022d44779d823172ab7ac33a5505 | bin/botocore/vendored/requests/cookies.py | python | RequestsCookieJar.iteritems | (self) | Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues(). | Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues(). | [
"Dict",
"-",
"like",
"iteritems",
"()",
"that",
"returns",
"an",
"iterator",
"of",
"name",
"-",
"value",
"tuples",
"from",
"the",
"jar",
".",
"See",
"iterkeys",
"()",
"and",
"itervalues",
"()",
"."
] | def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues()."""
for cookie in iter(self):
yield cookie.name, cookie.value | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name",
",",
"cookie",
".",
"value"
] | https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/botocore/vendored/requests/cookies.py#L226-L230 | ||
echonest/echoprint-server | 8936d6f6538bb886fb6b8f6e193e0bf8106ceed7 | API/solr.py | python | utc_to_string | (value) | return value | Convert datetimes to the subset
of ISO 8601 that SOLR expects... | Convert datetimes to the subset
of ISO 8601 that SOLR expects... | [
"Convert",
"datetimes",
"to",
"the",
"subset",
"of",
"ISO",
"8601",
"that",
"SOLR",
"expects",
"..."
] | def utc_to_string(value):
"""
Convert datetimes to the subset
of ISO 8601 that SOLR expects...
"""
try:
value = value.astimezone(utc).isoformat()
except ValueError:
value = value.isoformat()
if '+' in value:
value = value.split('+')[0]
value += 'Z'
return value | [
"def",
"utc_to_string",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"value",
".",
"astimezone",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
"except",
"ValueError",
":",
"value",
"=",
"value",
".",
"isoformat",
"(",
")",
"if",
"'+'",
"in",
"val... | https://github.com/echonest/echoprint-server/blob/8936d6f6538bb886fb6b8f6e193e0bf8106ceed7/API/solr.py#L1333-L1345 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.