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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
keiffster/program-y | 8c99b56f8c32f01a7b9887b5daae9465619d0385 | src/programy/dialog/tokenizer/tokenizer.py | python | Tokenizer.load_tokenizer | (configuration) | return Tokenizer(configuration.split_chars) | [] | def load_tokenizer(configuration):
if configuration is not None and configuration.classname is not None:
try:
YLogger.info(None, "Loading tokenizer from class [%s]", configuration.classname)
tokenizer_class = ClassLoader.instantiate_class(configuration.classname)
return tokenizer_class(configuration.split_chars)
except Exception as error:
YLogger.exception(None, "Failed to load tokenizer, defaulting to default", error)
return Tokenizer(configuration.split_chars) | [
"def",
"load_tokenizer",
"(",
"configuration",
")",
":",
"if",
"configuration",
"is",
"not",
"None",
"and",
"configuration",
".",
"classname",
"is",
"not",
"None",
":",
"try",
":",
"YLogger",
".",
"info",
"(",
"None",
",",
"\"Loading tokenizer from class [%s]\""... | https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/dialog/tokenizer/tokenizer.py#L46-L55 | |||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/decimal.py | python | Decimal.__format__ | (self, specifier, context=None, _localeconv=None) | return _format_number(self._sign, intpart, fracpart, exp, spec) | Format a Decimal instance according to the given specifier.
The specifier should be a standard format specifier, with the
form described in PEP 3101. Formatting types 'e', 'E', 'f',
'F', 'g', 'G', 'n' and '%' are supported. If the formatting
type is omitted it defaults to 'g' or 'G', depending on the
value of context.capitals. | Format a Decimal instance according to the given specifier. | [
"Format",
"a",
"Decimal",
"instance",
"according",
"to",
"the",
"given",
"specifier",
"."
] | def __format__(self, specifier, context=None, _localeconv=None):
"""Format a Decimal instance according to the given specifier.
The specifier should be a standard format specifier, with the
form described in PEP 3101. Formatting types 'e', 'E', 'f',
'F', 'g', 'G', 'n' and '%' are supported. If the formatting
type is omitted it defaults to 'g' or 'G', depending on the
value of context.capitals.
"""
# Note: PEP 3101 says that if the type is not present then
# there should be at least one digit after the decimal point.
# We take the liberty of ignoring this requirement for
# Decimal---it's presumably there to make sure that
# format(float, '') behaves similarly to str(float).
if context is None:
context = getcontext()
spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
# special values don't care about the type or precision
if self._is_special:
sign = _format_sign(self._sign, spec)
body = str(self.copy_abs())
return _format_align(sign, body, spec)
# a type of None defaults to 'g' or 'G', depending on context
if spec['type'] is None:
spec['type'] = ['g', 'G'][context.capitals]
# if type is '%', adjust exponent of self accordingly
if spec['type'] == '%':
self = _dec_from_triple(self._sign, self._int, self._exp+2)
# round if necessary, taking rounding mode from the context
rounding = context.rounding
precision = spec['precision']
if precision is not None:
if spec['type'] in 'eE':
self = self._round(precision+1, rounding)
elif spec['type'] in 'fF%':
self = self._rescale(-precision, rounding)
elif spec['type'] in 'gG' and len(self._int) > precision:
self = self._round(precision, rounding)
# special case: zeros with a positive exponent can't be
# represented in fixed point; rescale them to 0e0.
if not self and self._exp > 0 and spec['type'] in 'fF%':
self = self._rescale(0, rounding)
# figure out placement of the decimal point
leftdigits = self._exp + len(self._int)
if spec['type'] in 'eE':
if not self and precision is not None:
dotplace = 1 - precision
else:
dotplace = 1
elif spec['type'] in 'fF%':
dotplace = leftdigits
elif spec['type'] in 'gG':
if self._exp <= 0 and leftdigits > -6:
dotplace = leftdigits
else:
dotplace = 1
# find digits before and after decimal point, and get exponent
if dotplace < 0:
intpart = '0'
fracpart = '0'*(-dotplace) + self._int
elif dotplace > len(self._int):
intpart = self._int + '0'*(dotplace-len(self._int))
fracpart = ''
else:
intpart = self._int[:dotplace] or '0'
fracpart = self._int[dotplace:]
exp = leftdigits-dotplace
# done with the decimal-specific stuff; hand over the rest
# of the formatting to the _format_number function
return _format_number(self._sign, intpart, fracpart, exp, spec) | [
"def",
"__format__",
"(",
"self",
",",
"specifier",
",",
"context",
"=",
"None",
",",
"_localeconv",
"=",
"None",
")",
":",
"# Note: PEP 3101 says that if the type is not present then",
"# there should be at least one digit after the decimal point.",
"# We take the liberty of ign... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/decimal.py#L3644-L3722 | |
Arelle/Arelle | 20f3d8a8afd41668e1520799acd333349ce0ba17 | arelle/ModelDtsObject.py | python | ModelType.elements | (self) | ([QName]) -- List of element QNames that are descendants (content elements) | ([QName]) -- List of element QNames that are descendants (content elements) | [
"(",
"[",
"QName",
"]",
")",
"--",
"List",
"of",
"element",
"QNames",
"that",
"are",
"descendants",
"(",
"content",
"elements",
")"
] | def elements(self):
"""([QName]) -- List of element QNames that are descendants (content elements)"""
try:
return self._elements
except AttributeError:
self._elements = XmlUtil.schemaDescendantsNames(self, XbrlConst.xsd, "element")
return self._elements | [
"def",
"elements",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_elements",
"except",
"AttributeError",
":",
"self",
".",
"_elements",
"=",
"XmlUtil",
".",
"schemaDescendantsNames",
"(",
"self",
",",
"XbrlConst",
".",
"xsd",
",",
"\"element\"",... | https://github.com/Arelle/Arelle/blob/20f3d8a8afd41668e1520799acd333349ce0ba17/arelle/ModelDtsObject.py#L1335-L1341 | ||
tdamdouni/Pythonista | 3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad | stash/autopep8.py | python | filter_results | (source, results, aggressive) | Filter out spurious reports from pep8.
If aggressive is True, we allow possibly unsafe fixes (E711, E712). | Filter out spurious reports from pep8. | [
"Filter",
"out",
"spurious",
"reports",
"from",
"pep8",
"."
] | def filter_results(source, results, aggressive):
"""Filter out spurious reports from pep8.
If aggressive is True, we allow possibly unsafe fixes (E711, E712).
"""
non_docstring_string_line_numbers = multiline_string_lines(
source, include_docstrings=False)
all_string_line_numbers = multiline_string_lines(
source, include_docstrings=True)
commented_out_code_line_numbers = commented_out_code_lines(source)
has_e901 = any(result['id'].lower() == 'e901' for result in results)
for r in results:
issue_id = r['id'].lower()
if r['line'] in non_docstring_string_line_numbers:
if issue_id.startswith(('e1', 'e501', 'w191')):
continue
if r['line'] in all_string_line_numbers:
if issue_id in ['e501']:
continue
# We must offset by 1 for lines that contain the trailing contents of
# multiline strings.
if not aggressive and (r['line'] + 1) in all_string_line_numbers:
# Do not modify multiline strings in non-aggressive mode. Remove
# trailing whitespace could break doctests.
if issue_id.startswith(('w29', 'w39')):
continue
if aggressive <= 0:
if issue_id.startswith(('e711', 'w6')):
continue
if aggressive <= 1:
if issue_id.startswith(('e712', 'e713')):
continue
if r['line'] in commented_out_code_line_numbers:
if issue_id.startswith(('e26', 'e501')):
continue
# Do not touch indentation if there is a token error caused by
# incomplete multi-line statement. Otherwise, we risk screwing up the
# indentation.
if has_e901:
if issue_id.startswith(('e1', 'e7')):
continue
yield r | [
"def",
"filter_results",
"(",
"source",
",",
"results",
",",
"aggressive",
")",
":",
"non_docstring_string_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",",
"include_docstrings",
"=",
"False",
")",
"all_string_line_numbers",
"=",
"multiline_string_lines",
... | https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/stash/autopep8.py#L2700-L2753 | ||
InsaneLife/dssm | 1d32e137654e03994f7ba6cfde52e1d47601027c | data_input.py | python | Vocabulary._truncate_seq_pair | (tokens_a, tokens_b, max_length) | Truncates a sequence pair in place to the maximum length. | Truncates a sequence pair in place to the maximum length. | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length",
"."
] | def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop() | [
"def",
"_truncate_seq_pair",
"(",
"tokens_a",
",",
"tokens_b",
",",
"max_length",
")",
":",
"while",
"True",
":",
"total_length",
"=",
"len",
"(",
"tokens_a",
")",
"+",
"len",
"(",
"tokens_b",
")",
"if",
"total_length",
"<=",
"max_length",
":",
"break",
"i... | https://github.com/InsaneLife/dssm/blob/1d32e137654e03994f7ba6cfde52e1d47601027c/data_input.py#L108-L117 | ||
vcheckzen/FODI | 3bb23644938a33c3fdfb9611a622e35ed4ce6532 | back-end-py/main/3rd/Crypto/Util/strxor.py | python | strxor | (term1, term2, output=None) | XOR two byte strings.
Args:
term1 (bytes/bytearray/memoryview):
The first term of the XOR operation.
term2 (bytes/bytearray/memoryview):
The second term of the XOR operation.
output (bytearray/memoryview):
The location where the result must be written to.
If ``None``, the result is returned.
:Return:
If ``output`` is ``None``, a new ``bytes`` string with the result.
Otherwise ``None``. | XOR two byte strings.
Args:
term1 (bytes/bytearray/memoryview):
The first term of the XOR operation.
term2 (bytes/bytearray/memoryview):
The second term of the XOR operation.
output (bytearray/memoryview):
The location where the result must be written to.
If ``None``, the result is returned.
:Return:
If ``output`` is ``None``, a new ``bytes`` string with the result.
Otherwise ``None``. | [
"XOR",
"two",
"byte",
"strings",
".",
"Args",
":",
"term1",
"(",
"bytes",
"/",
"bytearray",
"/",
"memoryview",
")",
":",
"The",
"first",
"term",
"of",
"the",
"XOR",
"operation",
".",
"term2",
"(",
"bytes",
"/",
"bytearray",
"/",
"memoryview",
")",
":",... | def strxor(term1, term2, output=None):
"""XOR two byte strings.
Args:
term1 (bytes/bytearray/memoryview):
The first term of the XOR operation.
term2 (bytes/bytearray/memoryview):
The second term of the XOR operation.
output (bytearray/memoryview):
The location where the result must be written to.
If ``None``, the result is returned.
:Return:
If ``output`` is ``None``, a new ``bytes`` string with the result.
Otherwise ``None``.
"""
if len(term1) != len(term2):
raise ValueError("Only byte strings of equal length can be xored")
if output is None:
result = create_string_buffer(len(term1))
else:
# Note: output may overlap with either input
result = output
if not is_writeable_buffer(output):
raise TypeError("output must be a bytearray or a writeable memoryview")
if len(term1) != len(output):
raise ValueError("output must have the same length as the input"
" (%d bytes)" % len(term1))
_raw_strxor.strxor(c_uint8_ptr(term1),
c_uint8_ptr(term2),
c_uint8_ptr(result),
c_size_t(len(term1)))
if output is None:
return get_raw_buffer(result)
else:
return None | [
"def",
"strxor",
"(",
"term1",
",",
"term2",
",",
"output",
"=",
"None",
")",
":",
"if",
"len",
"(",
"term1",
")",
"!=",
"len",
"(",
"term2",
")",
":",
"raise",
"ValueError",
"(",
"\"Only byte strings of equal length can be xored\"",
")",
"if",
"output",
"... | https://github.com/vcheckzen/FODI/blob/3bb23644938a33c3fdfb9611a622e35ed4ce6532/back-end-py/main/3rd/Crypto/Util/strxor.py#L47-L87 | ||
FSecureLABS/Jandroid | e31d0dab58a2bfd6ed8e0a387172b8bd7c893436 | libs/platform-tools/platform-tools_linux/systrace/catapult/devil/devil/android/sdk/adb_wrapper.py | python | AdbWrapper.GetDeviceSerial | (self) | return self._device_serial | Gets the device serial number associated with this object.
Returns:
Device serial number as a string. | Gets the device serial number associated with this object. | [
"Gets",
"the",
"device",
"serial",
"number",
"associated",
"with",
"this",
"object",
"."
] | def GetDeviceSerial(self):
"""Gets the device serial number associated with this object.
Returns:
Device serial number as a string.
"""
return self._device_serial | [
"def",
"GetDeviceSerial",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_serial"
] | https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_linux/systrace/catapult/devil/devil/android/sdk/adb_wrapper.py#L420-L426 | |
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/llnl/util/argparsewriter.py | python | ArgparseWriter.parse | (self, parser, prog) | return Command(
prog, description, usage, positionals, optionals, subcommands) | Parses the parser object and returns the relavent components.
Parameters:
parser (argparse.ArgumentParser): the parser
prog (str): the command name
Returns:
(Command) information about the command from the parser | Parses the parser object and returns the relavent components. | [
"Parses",
"the",
"parser",
"object",
"and",
"returns",
"the",
"relavent",
"components",
"."
] | def parse(self, parser, prog):
"""Parses the parser object and returns the relavent components.
Parameters:
parser (argparse.ArgumentParser): the parser
prog (str): the command name
Returns:
(Command) information about the command from the parser
"""
self.parser = parser
split_prog = parser.prog.split(' ')
split_prog[-1] = prog
prog = ' '.join(split_prog)
description = parser.description
fmt = parser._get_formatter()
actions = parser._actions
groups = parser._mutually_exclusive_groups
usage = fmt._format_usage(None, actions, groups, '').strip()
# Go through actions and split them into optionals, positionals,
# and subcommands
optionals = []
positionals = []
subcommands = []
for action in actions:
if action.option_strings:
flags = action.option_strings
dest_flags = fmt._format_action_invocation(action)
help = self._expand_help(action) if action.help else ''
help = help.replace('\n', ' ')
optionals.append((flags, dest_flags, help))
elif isinstance(action, argparse._SubParsersAction):
for subaction in action._choices_actions:
subparser = action._name_parser_map[subaction.dest]
subcommands.append((subparser, subaction.dest))
# Look for aliases of the form 'name (alias, ...)'
if self.aliases:
match = re.match(r'(.*) \((.*)\)', subaction.metavar)
if match:
aliases = match.group(2).split(', ')
for alias in aliases:
subparser = action._name_parser_map[alias]
subcommands.append((subparser, alias))
else:
args = fmt._format_action_invocation(action)
help = self._expand_help(action) if action.help else ''
help = help.replace('\n', ' ')
positionals.append((args, help))
return Command(
prog, description, usage, positionals, optionals, subcommands) | [
"def",
"parse",
"(",
"self",
",",
"parser",
",",
"prog",
")",
":",
"self",
".",
"parser",
"=",
"parser",
"split_prog",
"=",
"parser",
".",
"prog",
".",
"split",
"(",
"' '",
")",
"split_prog",
"[",
"-",
"1",
"]",
"=",
"prog",
"prog",
"=",
"' '",
"... | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/llnl/util/argparsewriter.py#L62-L116 | |
scrapy/scrapy | b04cfa48328d5d5749dca6f50fa34e0cfc664c89 | scrapy/extensions/throttle.py | python | AutoThrottle.from_crawler | (cls, crawler) | return cls(crawler) | [] | def from_crawler(cls, crawler):
return cls(crawler) | [
"def",
"from_crawler",
"(",
"cls",
",",
"crawler",
")",
":",
"return",
"cls",
"(",
"crawler",
")"
] | https://github.com/scrapy/scrapy/blob/b04cfa48328d5d5749dca6f50fa34e0cfc664c89/scrapy/extensions/throttle.py#L22-L23 | |||
joxeankoret/diaphora | dcb5a25ac9fe23a285b657e5389cf770de7ac928 | pygments/lexer.py | python | using | (_other, **kwargs) | return callback | Callback that processes the match with a different lexer.
The keyword arguments are forwarded to the lexer, except `state` which
is handled separately.
`state` specifies the state that the new lexer will start in, and can
be an enumerable such as ('root', 'inline', 'string') or a simple
string which is assumed to be on top of the root state.
Note: For that to work, `_other` must not be an `ExtendedRegexLexer`. | Callback that processes the match with a different lexer. | [
"Callback",
"that",
"processes",
"the",
"match",
"with",
"a",
"different",
"lexer",
"."
] | def using(_other, **kwargs):
"""
Callback that processes the match with a different lexer.
The keyword arguments are forwarded to the lexer, except `state` which
is handled separately.
`state` specifies the state that the new lexer will start in, and can
be an enumerable such as ('root', 'inline', 'string') or a simple
string which is assumed to be on top of the root state.
Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.
"""
gt_kwargs = {}
if 'state' in kwargs:
s = kwargs.pop('state')
if isinstance(s, (list, tuple)):
gt_kwargs['stack'] = s
else:
gt_kwargs['stack'] = ('root', s)
if _other is this:
def callback(lexer, match, ctx=None):
# if keyword arguments are given the callback
# function has to create a new lexer instance
if kwargs:
# XXX: cache that somehow
kwargs.update(lexer.options)
lx = lexer.__class__(**kwargs)
else:
lx = lexer
s = match.start()
for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
yield i + s, t, v
if ctx:
ctx.pos = match.end()
else:
def callback(lexer, match, ctx=None):
# XXX: cache that somehow
kwargs.update(lexer.options)
lx = _other(**kwargs)
s = match.start()
for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
yield i + s, t, v
if ctx:
ctx.pos = match.end()
return callback | [
"def",
"using",
"(",
"_other",
",",
"*",
"*",
"kwargs",
")",
":",
"gt_kwargs",
"=",
"{",
"}",
"if",
"'state'",
"in",
"kwargs",
":",
"s",
"=",
"kwargs",
".",
"pop",
"(",
"'state'",
")",
"if",
"isinstance",
"(",
"s",
",",
"(",
"list",
",",
"tuple",... | https://github.com/joxeankoret/diaphora/blob/dcb5a25ac9fe23a285b657e5389cf770de7ac928/pygments/lexer.py#L340-L387 | |
c0rv4x/project-black | 2d3df00ba1b1453c99ec5a247793a74e11adba2a | black/workers/dirsearch/dirsearch_ext/thirdparty/requests/adapters.py | python | HTTPAdapter.close | (self) | Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections. | Disposes of any internal state. | [
"Disposes",
"of",
"any",
"internal",
"state",
"."
] | def close(self):
"""Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections.
"""
self.poolmanager.clear() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"poolmanager",
".",
"clear",
"(",
")"
] | https://github.com/c0rv4x/project-black/blob/2d3df00ba1b1453c99ec5a247793a74e11adba2a/black/workers/dirsearch/dirsearch_ext/thirdparty/requests/adapters.py#L256-L262 | ||
ring04h/wyportmap | c4201e2313504e780a7f25238eba2a2d3223e739 | sqlalchemy/engine/interfaces.py | python | Dialect.do_commit_twophase | (self, connection, xid, is_prepared=True,
recover=False) | Commit a two phase transaction on the given connection.
:param connection: a :class:`.Connection`.
:param xid: xid
:param is_prepared: whether or not
:meth:`.TwoPhaseTransaction.prepare` was called.
:param recover: if the recover flag was passed. | Commit a two phase transaction on the given connection. | [
"Commit",
"a",
"two",
"phase",
"transaction",
"on",
"the",
"given",
"connection",
"."
] | def do_commit_twophase(self, connection, xid, is_prepared=True,
recover=False):
"""Commit a two phase transaction on the given connection.
:param connection: a :class:`.Connection`.
:param xid: xid
:param is_prepared: whether or not
:meth:`.TwoPhaseTransaction.prepare` was called.
:param recover: if the recover flag was passed.
"""
raise NotImplementedError() | [
"def",
"do_commit_twophase",
"(",
"self",
",",
"connection",
",",
"xid",
",",
"is_prepared",
"=",
"True",
",",
"recover",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/engine/interfaces.py#L570-L583 | ||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/apis/core_api.py | python | CoreApi.get_api_versions_with_http_info | (self, **kwargs) | return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIVersions',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | get available API versions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_api_versions_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: V1APIVersions
If the method is called asynchronously,
returns the request thread. | get available API versions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_api_versions_with_http_info(callback=callback_function) | [
"get",
"available",
"API",
"versions",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"invoked",
"when"... | def get_api_versions_with_http_info(self, **kwargs):
"""
get available API versions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_api_versions_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: V1APIVersions
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_versions" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
resource_path = '/api/'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIVersions',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | [
"def",
"get_api_versions_with_http_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"all_params",
"=",
"[",
"]",
"all_params",
".",
"append",
"(",
"'callback'",
")",
"all_params",
".",
"append",
"(",
"'_return_http_data_only'",
")",
"all_params",
".",
"a... | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/apis/core_api.py#L67-L138 | |
meduza-corp/interstellar | 40a801ccd7856491726f5a126621d9318cabe2e1 | gsutil/third_party/boto/boto/mws/connection.py | python | MWSConnection.list_orders_by_next_token | (self, request, response, **kw) | return self._post_request(request, kw, response) | Returns the next page of orders using the NextToken value
that was returned by your previous request to either
ListOrders or ListOrdersByNextToken. | Returns the next page of orders using the NextToken value
that was returned by your previous request to either
ListOrders or ListOrdersByNextToken. | [
"Returns",
"the",
"next",
"page",
"of",
"orders",
"using",
"the",
"NextToken",
"value",
"that",
"was",
"returned",
"by",
"your",
"previous",
"request",
"to",
"either",
"ListOrders",
"or",
"ListOrdersByNextToken",
"."
] | def list_orders_by_next_token(self, request, response, **kw):
"""Returns the next page of orders using the NextToken value
that was returned by your previous request to either
ListOrders or ListOrdersByNextToken.
"""
return self._post_request(request, kw, response) | [
"def",
"list_orders_by_next_token",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_post_request",
"(",
"request",
",",
"kw",
",",
"response",
")"
] | https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/mws/connection.py#L735-L740 | |
microsoft/DeepSpeed | 3a4cb042433a2e8351887922f8362d3752c52a42 | deepspeed/utils/groups.py | python | initialize_expert_parallel | (expert_parallel_size_) | Initialize expert plus data parallel groups.
Example - E + D parallel
world_size = 16
expert_parallel_size = 2 # number of experts in same group
expert_data_parallel_group = [0,2,4,6,8,10,12,14], [1,3,5,7,9,11,13,15] - all reduce is only on MoE params
expert_parallel_group = [0, 1], [2,3], [4,5], [6,7], [8,9] - no all reduce, but all to all
data_parallel_group = [0,1,...,15] - all reduce is only on non-MoE | Initialize expert plus data parallel groups. | [
"Initialize",
"expert",
"plus",
"data",
"parallel",
"groups",
"."
] | def initialize_expert_parallel(expert_parallel_size_):
"""
Initialize expert plus data parallel groups.
Example - E + D parallel
world_size = 16
expert_parallel_size = 2 # number of experts in same group
expert_data_parallel_group = [0,2,4,6,8,10,12,14], [1,3,5,7,9,11,13,15] - all reduce is only on MoE params
expert_parallel_group = [0, 1], [2,3], [4,5], [6,7], [8,9] - no all reduce, but all to all
data_parallel_group = [0,1,...,15] - all reduce is only on non-MoE
"""
assert torch.distributed.is_initialized()
log_dist(
'initializing deepspeed expert parallel group with size {}'.format(
expert_parallel_size_),
[0])
world_size = get_data_parallel_world_size()
rank = get_data_parallel_rank()
expert_parallel_size_ = min(expert_parallel_size_, world_size)
ensure_divisibility(world_size, expert_parallel_size_)
# Build the expert data parallel groups.
global _EXPERT_DATA_PARALLEL_GROUP
assert _EXPERT_DATA_PARALLEL_GROUP is None, \
'expert data parallel group is already initialized'
for i in range(expert_parallel_size_):
ranks = range(i, world_size, expert_parallel_size_)
group = torch.distributed.new_group(ranks)
# TODO: remove
log_dist(
f'creating expert data parallel process group with ranks: {list(ranks)}',
[0])
if i == (rank % expert_parallel_size_):
_EXPERT_DATA_PARALLEL_GROUP = group
# Build the expert parallel groups.
global _EXPERT_PARALLEL_GROUP
assert _EXPERT_PARALLEL_GROUP is None, \
'expert parallel group is already initialized'
for i in range(world_size // expert_parallel_size_):
ranks = range(i * expert_parallel_size_, (i + 1) * expert_parallel_size_)
group = torch.distributed.new_group(ranks)
# TODO: remove
log_dist(f'creating expert parallel process group with ranks: {list(ranks)}',
[0])
if i == (rank // expert_parallel_size_):
_EXPERT_PARALLEL_GROUP = group | [
"def",
"initialize_expert_parallel",
"(",
"expert_parallel_size_",
")",
":",
"assert",
"torch",
".",
"distributed",
".",
"is_initialized",
"(",
")",
"log_dist",
"(",
"'initializing deepspeed expert parallel group with size {}'",
".",
"format",
"(",
"expert_parallel_size_",
... | https://github.com/microsoft/DeepSpeed/blob/3a4cb042433a2e8351887922f8362d3752c52a42/deepspeed/utils/groups.py#L166-L216 | ||
PyTorchLightning/pytorch-lightning | 5914fb748fb53d826ab337fc2484feab9883a104 | pytorch_lightning/core/hooks.py | python | ModelHooks.on_before_backward | (self, loss: torch.Tensor) | Called before ``loss.backward()``.
Args:
loss: Loss divided by number of batches for gradient accumulation and scaled if using native AMP. | Called before ``loss.backward()``. | [
"Called",
"before",
"loss",
".",
"backward",
"()",
"."
] | def on_before_backward(self, loss: torch.Tensor) -> None:
"""Called before ``loss.backward()``.
Args:
loss: Loss divided by number of batches for gradient accumulation and scaled if using native AMP.
"""
pass | [
"def",
"on_before_backward",
"(",
"self",
",",
"loss",
":",
"torch",
".",
"Tensor",
")",
"->",
"None",
":",
"pass"
] | https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/core/hooks.py#L240-L246 | ||
capless/warrant | e81f9a6dd6e36be3b6fa1dbbd11334ec92124ace | warrant/__init__.py | python | UserObj.__init__ | (self, username, attribute_list, cognito_obj, metadata=None, attr_map=None) | :param username:
:param attribute_list:
:param metadata: Dictionary of User metadata | :param username:
:param attribute_list:
:param metadata: Dictionary of User metadata | [
":",
"param",
"username",
":",
":",
"param",
"attribute_list",
":",
":",
"param",
"metadata",
":",
"Dictionary",
"of",
"User",
"metadata"
] | def __init__(self, username, attribute_list, cognito_obj, metadata=None, attr_map=None):
"""
:param username:
:param attribute_list:
:param metadata: Dictionary of User metadata
"""
self.username = username
self.pk = username
self._cognito = cognito_obj
self._attr_map = {} if attr_map is None else attr_map
self._data = cognito_to_dict(attribute_list, self._attr_map)
self.sub = self._data.pop('sub', None)
self.email_verified = self._data.pop('email_verified', None)
self.phone_number_verified = self._data.pop('phone_number_verified', None)
self._metadata = {} if metadata is None else metadata | [
"def",
"__init__",
"(",
"self",
",",
"username",
",",
"attribute_list",
",",
"cognito_obj",
",",
"metadata",
"=",
"None",
",",
"attr_map",
"=",
"None",
")",
":",
"self",
".",
"username",
"=",
"username",
"self",
".",
"pk",
"=",
"username",
"self",
".",
... | https://github.com/capless/warrant/blob/e81f9a6dd6e36be3b6fa1dbbd11334ec92124ace/warrant/__init__.py#L63-L77 | ||
nodesign/weio | 1d67d705a5c36a2e825ad13feab910b0aca9a2e8 | openWrt/files/usr/lib/python2.7/site-packages/tornado/template.py | python | _Text.__init__ | (self, value, line) | [] | def __init__(self, value, line):
self.value = value
self.line = line | [
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"line",
")",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"line",
"=",
"line"
] | https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/template.py#L555-L557 | ||||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/risco/entity.py | python | RiscoEntity.async_added_to_hass | (self) | When entity is added to hass. | When entity is added to hass. | [
"When",
"entity",
"is",
"added",
"to",
"hass",
"."
] | async def async_added_to_hass(self):
"""When entity is added to hass."""
self.async_on_remove(
self.coordinator.async_add_listener(self._refresh_from_coordinator)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"coordinator",
".",
"async_add_listener",
"(",
"self",
".",
"_refresh_from_coordinator",
")",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/risco/entity.py#L20-L24 | ||
pywavefront/PyWavefront | 7ae734c3317e2af59b93f3e24b68e5a57a2088ab | pywavefront/material.py | python | MaterialParser.parse_map_Ns | (self) | Specular color map | Specular color map | [
"Specular",
"color",
"map"
] | def parse_map_Ns(self):
"""Specular color map"""
name = self.line[self.line.find(' ') + 1:].strip()
self.this_material.set_texture_specular_highlight(name, self.dir) | [
"def",
"parse_map_Ns",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"line",
"[",
"self",
".",
"line",
".",
"find",
"(",
"' '",
")",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"self",
".",
"this_material",
".",
"set_texture_specular_highlight",
"... | https://github.com/pywavefront/PyWavefront/blob/7ae734c3317e2af59b93f3e24b68e5a57a2088ab/pywavefront/material.py#L231-L234 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/encodings/iso8859_8.py | python | Codec.decode | (self,input,errors='strict') | return codecs.charmap_decode(input,errors,decoding_table) | [] | def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table) | [
"def",
"decode",
"(",
"self",
",",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"codecs",
".",
"charmap_decode",
"(",
"input",
",",
"errors",
",",
"decoding_table",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/encodings/iso8859_8.py#L14-L15 | |||
pytransitions/transitions | 9663094f4566c016b11563e7a7d6d3802593845c | transitions/extensions/markup.py | python | MarkupMachine._identify_callback | (self, name) | return callback_type, target | [] | def _identify_callback(self, name):
callback_type, target = super(MarkupMachine, self)._identify_callback(name)
if callback_type:
self._needs_update = True
return callback_type, target | [
"def",
"_identify_callback",
"(",
"self",
",",
"name",
")",
":",
"callback_type",
",",
"target",
"=",
"super",
"(",
"MarkupMachine",
",",
"self",
")",
".",
"_identify_callback",
"(",
"name",
")",
"if",
"callback_type",
":",
"self",
".",
"_needs_update",
"=",... | https://github.com/pytransitions/transitions/blob/9663094f4566c016b11563e7a7d6d3802593845c/transitions/extensions/markup.py#L163-L167 | |||
abr/abr_control | a248ec56166f01791857a766ac58ee0920c0861c | abr_control/utils/transformations.py | python | random_rotation_matrix | (rand=None) | return quaternion_matrix(random_quaternion(rand)) | Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True | Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True | [
"Return",
"uniform",
"random",
"rotation",
"matrix",
".",
"rand",
":",
"array",
"like",
"Three",
"independent",
"random",
"variables",
"that",
"are",
"uniformly",
"distributed",
"between",
"0",
"and",
"1",
"for",
"each",
"returned",
"quaternion",
".",
">>>",
"... | def random_rotation_matrix(rand=None):
"""Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
"""
return quaternion_matrix(random_quaternion(rand)) | [
"def",
"random_rotation_matrix",
"(",
"rand",
"=",
"None",
")",
":",
"return",
"quaternion_matrix",
"(",
"random_quaternion",
"(",
"rand",
")",
")"
] | https://github.com/abr/abr_control/blob/a248ec56166f01791857a766ac58ee0920c0861c/abr_control/utils/transformations.py#L1398-L1407 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/ldap3/strategy/base.py | python | BaseStrategy.compute_ldap_message_size | (data) | return ret_value | Compute LDAP Message size according to BER definite length rules
Returns -1 if too few data to compute message length | Compute LDAP Message size according to BER definite length rules
Returns -1 if too few data to compute message length | [
"Compute",
"LDAP",
"Message",
"size",
"according",
"to",
"BER",
"definite",
"length",
"rules",
"Returns",
"-",
"1",
"if",
"too",
"few",
"data",
"to",
"compute",
"message",
"length"
] | def compute_ldap_message_size(data):
"""
Compute LDAP Message size according to BER definite length rules
Returns -1 if too few data to compute message length
"""
if isinstance(data, str): # fix for Python 2, data is string not bytes
data = bytearray(data) # Python 2 bytearray is equivalent to Python 3 bytes
ret_value = -1
if len(data) > 2:
if data[1] <= 127: # BER definite length - short form. Highest bit of byte 1 is 0, message length is in the last 7 bits - Value can be up to 127 bytes long
ret_value = data[1] + 2
else: # BER definite length - long form. Highest bit of byte 1 is 1, last 7 bits counts the number of following octets containing the value length
bytes_length = data[1] - 128
if len(data) >= bytes_length + 2:
value_length = 0
cont = bytes_length
for byte in data[2:2 + bytes_length]:
cont -= 1
value_length += byte * (256 ** cont)
ret_value = value_length + 2 + bytes_length
return ret_value | [
"def",
"compute_ldap_message_size",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"# fix for Python 2, data is string not bytes",
"data",
"=",
"bytearray",
"(",
"data",
")",
"# Python 2 bytearray is equivalent to Python 3 bytes",
"ret_value... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/ldap3/strategy/base.py#L430-L452 | |
OpenCobolIDE/OpenCobolIDE | c78d0d335378e5fe0a5e74f53c19b68b55e85388 | open_cobol_ide/extlibs/future/backports/datetime.py | python | timedelta.__rsub__ | (self, other) | return NotImplemented | [] | def __rsub__(self, other):
if isinstance(other, timedelta):
return -self + other
return NotImplemented | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"timedelta",
")",
":",
"return",
"-",
"self",
"+",
"other",
"return",
"NotImplemented"
] | https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/future/backports/datetime.py#L490-L493 | |||
kvazis/homeassistant | aca227a780f806d861342e3611025a52a3bb4366 | custom_components/xiaomi_miot_raw/fan.py | python | MiotFan.preset_mode | (self) | return self._speed | Return the current speed. | Return the current speed. | [
"Return",
"the",
"current",
"speed",
"."
] | def preset_mode(self):
"""Return the current speed."""
try:
self._speed = self.get_key_by_value(self._ctrl_params['speed'],self.device_state_attributes[self._did_prefix + 'speed'])
except KeyError:
self._speed = None
return self._speed | [
"def",
"preset_mode",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_speed",
"=",
"self",
".",
"get_key_by_value",
"(",
"self",
".",
"_ctrl_params",
"[",
"'speed'",
"]",
",",
"self",
".",
"device_state_attributes",
"[",
"self",
".",
"_did_prefix",
"+",
... | https://github.com/kvazis/homeassistant/blob/aca227a780f806d861342e3611025a52a3bb4366/custom_components/xiaomi_miot_raw/fan.py#L210-L216 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/conch/ssh/filetransfer.py | python | FileTransferClient.extendedRequest | (self, request, data) | return self._sendRequest(FXP_EXTENDED, NS(request) + data) | Make an extended request of the server.
The method returns a Deferred that is called back with
the result of the extended request.
@param request: the name of the extended request to make.
@param data: any other data that goes along with the request. | Make an extended request of the server. | [
"Make",
"an",
"extended",
"request",
"of",
"the",
"server",
"."
] | def extendedRequest(self, request, data):
"""
Make an extended request of the server.
The method returns a Deferred that is called back with
the result of the extended request.
@param request: the name of the extended request to make.
@param data: any other data that goes along with the request.
"""
return self._sendRequest(FXP_EXTENDED, NS(request) + data) | [
"def",
"extendedRequest",
"(",
"self",
",",
"request",
",",
"data",
")",
":",
"return",
"self",
".",
"_sendRequest",
"(",
"FXP_EXTENDED",
",",
"NS",
"(",
"request",
")",
"+",
"data",
")"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/conch/ssh/filetransfer.py#L684-L694 | |
Komodo/KomodoEdit | 61edab75dce2bdb03943b387b0608ea36f548e8e | src/codeintel/play/core.py | python | GBSizerItem.SetGBSizer | (*args, **kwargs) | return _core.GBSizerItem_SetGBSizer(*args, **kwargs) | SetGBSizer(GridBagSizer sizer) | SetGBSizer(GridBagSizer sizer) | [
"SetGBSizer",
"(",
"GridBagSizer",
"sizer",
")"
] | def SetGBSizer(*args, **kwargs):
"""SetGBSizer(GridBagSizer sizer)"""
return _core.GBSizerItem_SetGBSizer(*args, **kwargs) | [
"def",
"SetGBSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core",
".",
"GBSizerItem_SetGBSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L8857-L8859 | |
bitcoin-core/HWI | 6871946c2176f2f9777b6ac8f0614d96d99bfa0e | hwilib/devices/trezorlib/messages.py | python | AuthorizeCoinJoin.__init__ | (
self,
*,
coordinator: "str",
max_total_fee: "int",
address_n: Optional[List["int"]] = None,
fee_per_anonymity: Optional["int"] = 0,
coin_name: Optional["str"] = 'Bitcoin',
script_type: Optional["InputScriptType"] = InputScriptType.SPENDADDRESS,
amount_unit: Optional["AmountUnit"] = AmountUnit.BITCOIN,
) | [] | def __init__(
self,
*,
coordinator: "str",
max_total_fee: "int",
address_n: Optional[List["int"]] = None,
fee_per_anonymity: Optional["int"] = 0,
coin_name: Optional["str"] = 'Bitcoin',
script_type: Optional["InputScriptType"] = InputScriptType.SPENDADDRESS,
amount_unit: Optional["AmountUnit"] = AmountUnit.BITCOIN,
) -> None:
self.address_n = address_n if address_n is not None else []
self.coordinator = coordinator
self.max_total_fee = max_total_fee
self.fee_per_anonymity = fee_per_anonymity
self.coin_name = coin_name
self.script_type = script_type
self.amount_unit = amount_unit | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"coordinator",
":",
"\"str\"",
",",
"max_total_fee",
":",
"\"int\"",
",",
"address_n",
":",
"Optional",
"[",
"List",
"[",
"\"int\"",
"]",
"]",
"=",
"None",
",",
"fee_per_anonymity",
":",
"Optional",
"[",
"\"... | https://github.com/bitcoin-core/HWI/blob/6871946c2176f2f9777b6ac8f0614d96d99bfa0e/hwilib/devices/trezorlib/messages.py#L1016-L1033 | ||||
feliam/pysymemu | ad02e52122099d537372eb4d11fd5024b8a3857f | cpu.py | python | Cpu.MOV | (cpu, dest, src) | Move.
Copies the second operand (source operand) to the first operand (destination
operand). The source operand can be an immediate value, general-purpose
register, segment register, or memory location; the destination register
can be a general-purpose register, segment register, or memory location.
Both operands must be the same size, which can be a byte, a word, or a
doubleword.
@param cpu: current CPU.
@param dest: destination operand.
@param src: source operand. | Move.
Copies the second operand (source operand) to the first operand (destination
operand). The source operand can be an immediate value, general-purpose
register, segment register, or memory location; the destination register
can be a general-purpose register, segment register, or memory location.
Both operands must be the same size, which can be a byte, a word, or a
doubleword. | [
"Move",
".",
"Copies",
"the",
"second",
"operand",
"(",
"source",
"operand",
")",
"to",
"the",
"first",
"operand",
"(",
"destination",
"operand",
")",
".",
"The",
"source",
"operand",
"can",
"be",
"an",
"immediate",
"value",
"general",
"-",
"purpose",
"reg... | def MOV(cpu, dest, src):
'''
Move.
Copies the second operand (source operand) to the first operand (destination
operand). The source operand can be an immediate value, general-purpose
register, segment register, or memory location; the destination register
can be a general-purpose register, segment register, or memory location.
Both operands must be the same size, which can be a byte, a word, or a
doubleword.
@param cpu: current CPU.
@param dest: destination operand.
@param src: source operand.
'''
dest.write(src.read()) | [
"def",
"MOV",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"dest",
".",
"write",
"(",
"src",
".",
"read",
"(",
")",
")"
] | https://github.com/feliam/pysymemu/blob/ad02e52122099d537372eb4d11fd5024b8a3857f/cpu.py#L2609-L2624 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/wsgiref/handlers.py | python | _needs_transcode | (k) | return _is_request(k) or k.startswith('HTTP_') or k.startswith('SSL_') \
or (k.startswith('REDIRECT_') and _needs_transcode(k[9:])) | [] | def _needs_transcode(k):
return _is_request(k) or k.startswith('HTTP_') or k.startswith('SSL_') \
or (k.startswith('REDIRECT_') and _needs_transcode(k[9:])) | [
"def",
"_needs_transcode",
"(",
"k",
")",
":",
"return",
"_is_request",
"(",
"k",
")",
"or",
"k",
".",
"startswith",
"(",
"'HTTP_'",
")",
"or",
"k",
".",
"startswith",
"(",
"'SSL_'",
")",
"or",
"(",
"k",
".",
"startswith",
"(",
"'REDIRECT_'",
")",
"a... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/wsgiref/handlers.py#L30-L32 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-mac/videoreader.py | python | _Reader._movietime_to_ms | (self, time) | return value | [] | def _movietime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.movietimescale, None), 1000)
return value | [
"def",
"_movietime_to_ms",
"(",
"self",
",",
"time",
")",
":",
"value",
",",
"d1",
",",
"d2",
"=",
"Qt",
".",
"ConvertTimeScale",
"(",
"(",
"time",
",",
"self",
".",
"movietimescale",
",",
"None",
")",
",",
"1000",
")",
"return",
"value"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/videoreader.py#L121-L123 | |||
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/distutils/command/register.py | python | register.send_metadata | (self) | Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is a ConfigParser-formatted file with a section
[distutils] containing username and password entries (both
in clear text). Eg:
[distutils]
index-servers =
pypi
[pypi]
username: fred
password: sekrit
Otherwise, to figure who the user is, we offer the user three
choices:
1. use existing login,
2. register as a new user, or
3. set the password to a random string and email the user. | Send the metadata to the package index server. | [
"Send",
"the",
"metadata",
"to",
"the",
"package",
"index",
"server",
"."
] | def send_metadata(self):
''' Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is a ConfigParser-formatted file with a section
[distutils] containing username and password entries (both
in clear text). Eg:
[distutils]
index-servers =
pypi
[pypi]
username: fred
password: sekrit
Otherwise, to figure who the user is, we offer the user three
choices:
1. use existing login,
2. register as a new user, or
3. set the password to a random string and email the user.
'''
# see if we can short-cut and get the username/password from the
# config
if self.has_config:
choice = '1'
username = self.username
password = self.password
else:
choice = 'x'
username = password = ''
# get the user's login info
choices = '1 2 3 4'.split()
while choice not in choices:
self.announce('''\
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your selection [default 1]: ''', log.INFO)
choice = input()
if not choice:
choice = '1'
elif choice not in choices:
print('Please choose one of the four options!')
if choice == '1':
# get the username and password
while not username:
username = input('Username: ')
while not password:
password = getpass.getpass('Password: ')
# set up the authentication
auth = urllib.request.HTTPPasswordMgr()
host = urllib.parse.urlparse(self.repository)[1]
auth.add_password(self.realm, host, username, password)
# send the info to the server and report the result
code, result = self.post_to_server(self.build_post_data('submit'),
auth)
self.announce('Server response (%s): %s' % (code, result),
log.INFO)
# possibly save the login
if code == 200:
if self.has_config:
# sharing the password in the distribution instance
# so the upload command can reuse it
self.distribution.password = password
else:
self.announce(('I can store your PyPI login so future '
'submissions will be faster.'), log.INFO)
self.announce('(the login will be stored in %s)' % \
self._get_rc_file(), log.INFO)
choice = 'X'
while choice.lower() not in 'yn':
choice = input('Save your login (y/N)?')
if not choice:
choice = 'n'
if choice.lower() == 'y':
self._store_pypirc(username, password)
elif choice == '2':
data = {':action': 'user'}
data['name'] = data['password'] = data['email'] = ''
data['confirm'] = None
while not data['name']:
data['name'] = input('Username: ')
while data['password'] != data['confirm']:
while not data['password']:
data['password'] = getpass.getpass('Password: ')
while not data['confirm']:
data['confirm'] = getpass.getpass(' Confirm: ')
if data['password'] != data['confirm']:
data['password'] = ''
data['confirm'] = None
print("Password and confirm don't match!")
while not data['email']:
data['email'] = input(' EMail: ')
code, result = self.post_to_server(data)
if code != 200:
log.info('Server response (%s): %s', code, result)
else:
log.info('You will receive an email shortly.')
log.info(('Follow the instructions in it to '
'complete registration.'))
elif choice == '3':
data = {':action': 'password_reset'}
data['email'] = ''
while not data['email']:
data['email'] = input('Your email address: ')
code, result = self.post_to_server(data)
log.info('Server response (%s): %s', code, result) | [
"def",
"send_metadata",
"(",
"self",
")",
":",
"# see if we can short-cut and get the username/password from the",
"# config",
"if",
"self",
".",
"has_config",
":",
"choice",
"=",
"'1'",
"username",
"=",
"self",
".",
"username",
"password",
"=",
"self",
".",
"passwo... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/distutils/command/register.py#L99-L219 | ||
DataBiosphere/toil | 2e148eee2114ece8dcc3ec8a83f36333266ece0d | src/toil/job.py | python | Job.disk | (self) | return self.description.disk | The maximum number of bytes of disk the job will require to run.
:rtype: int | The maximum number of bytes of disk the job will require to run. | [
"The",
"maximum",
"number",
"of",
"bytes",
"of",
"disk",
"the",
"job",
"will",
"require",
"to",
"run",
"."
] | def disk(self) -> int:
"""
The maximum number of bytes of disk the job will require to run.
:rtype: int
"""
return self.description.disk | [
"def",
"disk",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"description",
".",
"disk"
] | https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/job.py#L1110-L1116 | |
google/rekall | 55d1925f2df9759a989b35271b4fa48fc54a1c86 | rekall-core/rekall/plugins/linux/common.py | python | LinuxPageOffset.calculate | (self) | return self.session.profile.GetPageOffset() | Returns PAGE_OFFSET. | Returns PAGE_OFFSET. | [
"Returns",
"PAGE_OFFSET",
"."
] | def calculate(self):
"""Returns PAGE_OFFSET."""
return self.session.profile.GetPageOffset() | [
"def",
"calculate",
"(",
"self",
")",
":",
"return",
"self",
".",
"session",
".",
"profile",
".",
"GetPageOffset",
"(",
")"
] | https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/linux/common.py#L399-L401 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/form_processor/models.py | python | CommCareCaseSQL.get_opening_transactions | (self) | return self._transactions_by_type(CaseTransaction.TYPE_FORM | CaseTransaction.TYPE_CASE_CREATE) | [] | def get_opening_transactions(self):
return self._transactions_by_type(CaseTransaction.TYPE_FORM | CaseTransaction.TYPE_CASE_CREATE) | [
"def",
"get_opening_transactions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_transactions_by_type",
"(",
"CaseTransaction",
".",
"TYPE_FORM",
"|",
"CaseTransaction",
".",
"TYPE_CASE_CREATE",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/form_processor/models.py#L953-L954 | |||
cocos2d/bindings-generator | f85b28b482192e6a26b121d687567098ff4db562 | clang/cindex.py | python | TypeKind.spelling | (self) | return conf.lib.clang_getTypeKindSpelling(self.value) | Retrieve the spelling of this TypeKind. | Retrieve the spelling of this TypeKind. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"TypeKind",
"."
] | def spelling(self):
"""Retrieve the spelling of this TypeKind."""
return conf.lib.clang_getTypeKindSpelling(self.value) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeKindSpelling",
"(",
"self",
".",
"value",
")"
] | https://github.com/cocos2d/bindings-generator/blob/f85b28b482192e6a26b121d687567098ff4db562/clang/cindex.py#L1948-L1950 | |
marcosfede/algorithms | 1ee7c815f9d556c9cef4d4b0d21ee3a409d21629 | graph/markov_chain.py | python | iterating_markov_chain | (chain, state) | [] | def iterating_markov_chain(chain, state):
while True:
state = next_state(chain, state)
yield state | [
"def",
"iterating_markov_chain",
"(",
"chain",
",",
"state",
")",
":",
"while",
"True",
":",
"state",
"=",
"next_state",
"(",
"chain",
",",
"state",
")",
"yield",
"state"
] | https://github.com/marcosfede/algorithms/blob/1ee7c815f9d556c9cef4d4b0d21ee3a409d21629/graph/markov_chain.py#L26-L29 | ||||
Matheus-Garbelini/sweyntooth_bluetooth_low_energy_attacks | 40c985b9a9ff1189ddf278462440b120cf96b196 | libs/scapy/packet.py | python | Packet.hashret | (self) | return self.payload.hashret() | DEV: returns a string that has the same value for a request
and its answer. | DEV: returns a string that has the same value for a request
and its answer. | [
"DEV",
":",
"returns",
"a",
"string",
"that",
"has",
"the",
"same",
"value",
"for",
"a",
"request",
"and",
"its",
"answer",
"."
] | def hashret(self):
"""DEV: returns a string that has the same value for a request
and its answer."""
return self.payload.hashret() | [
"def",
"hashret",
"(",
"self",
")",
":",
"return",
"self",
".",
"payload",
".",
"hashret",
"(",
")"
] | https://github.com/Matheus-Garbelini/sweyntooth_bluetooth_low_energy_attacks/blob/40c985b9a9ff1189ddf278462440b120cf96b196/libs/scapy/packet.py#L1066-L1069 | |
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/locale.py | python | currency | (val, symbol=True, grouping=False, international=False) | return s.replace('<', '').replace('>', '') | Formats val according to the currency settings
in the current locale. | Formats val according to the currency settings
in the current locale. | [
"Formats",
"val",
"according",
"to",
"the",
"currency",
"settings",
"in",
"the",
"current",
"locale",
"."
] | def currency(val, symbol=True, grouping=False, international=False):
"""Formats val according to the currency settings
in the current locale."""
conv = localeconv()
# check for illegal values
digits = conv[international and 'int_frac_digits' or 'frac_digits']
if digits == 127:
raise ValueError("Currency formatting is not possible using "
"the 'C' locale.")
s = format('%%.%if' % digits, abs(val), grouping, monetary=True)
# '<' and '>' are markers if the sign must be inserted between symbol and value
s = '<' + s + '>'
if symbol:
smb = conv[international and 'int_curr_symbol' or 'currency_symbol']
precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes']
separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space']
if precedes:
s = smb + (separated and ' ' or '') + s
else:
s = s + (separated and ' ' or '') + smb
sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn']
sign = conv[val<0 and 'negative_sign' or 'positive_sign']
if sign_pos == 0:
s = '(' + s + ')'
elif sign_pos == 1:
s = sign + s
elif sign_pos == 2:
s = s + sign
elif sign_pos == 3:
s = s.replace('<', sign)
elif sign_pos == 4:
s = s.replace('>', sign)
else:
# the default if nothing specified;
# this should be the most fitting sign position
s = sign + s
return s.replace('<', '').replace('>', '') | [
"def",
"currency",
"(",
"val",
",",
"symbol",
"=",
"True",
",",
"grouping",
"=",
"False",
",",
"international",
"=",
"False",
")",
":",
"conv",
"=",
"localeconv",
"(",
")",
"# check for illegal values",
"digits",
"=",
"conv",
"[",
"international",
"and",
"... | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/locale.py#L254-L297 | |
gpiozero/gpiozero | 2b6aa5314830fedf3701113b6713161086defa38 | gpiozero/input_devices.py | python | DistanceSensor.threshold_distance | (self) | return self.threshold * self.max_distance | The distance, measured in meters, that will trigger the
:attr:`when_in_range` and :attr:`when_out_of_range` events when
crossed. This is simply a meter-scaled variant of the usual
:attr:`~SmoothedInputDevice.threshold` attribute. | The distance, measured in meters, that will trigger the
:attr:`when_in_range` and :attr:`when_out_of_range` events when
crossed. This is simply a meter-scaled variant of the usual
:attr:`~SmoothedInputDevice.threshold` attribute. | [
"The",
"distance",
"measured",
"in",
"meters",
"that",
"will",
"trigger",
"the",
":",
"attr",
":",
"when_in_range",
"and",
":",
"attr",
":",
"when_out_of_range",
"events",
"when",
"crossed",
".",
"This",
"is",
"simply",
"a",
"meter",
"-",
"scaled",
"variant"... | def threshold_distance(self):
"""
The distance, measured in meters, that will trigger the
:attr:`when_in_range` and :attr:`when_out_of_range` events when
crossed. This is simply a meter-scaled variant of the usual
:attr:`~SmoothedInputDevice.threshold` attribute.
"""
return self.threshold * self.max_distance | [
"def",
"threshold_distance",
"(",
"self",
")",
":",
"return",
"self",
".",
"threshold",
"*",
"self",
".",
"max_distance"
] | https://github.com/gpiozero/gpiozero/blob/2b6aa5314830fedf3701113b6713161086defa38/gpiozero/input_devices.py#L879-L886 | |
fdslight/fdslight | 69bc6b16f496b9dc628ecd1bc49f776e98e77ba0 | pywind/evtframework/handlers/udp_handler.py | python | udp_handler.udp_timeout | (self) | 重写这个方法
:return: | 重写这个方法
:return: | [
"重写这个方法",
":",
"return",
":"
] | def udp_timeout(self):
"""重写这个方法
:return:
"""
pass | [
"def",
"udp_timeout",
"(",
"self",
")",
":",
"pass"
] | https://github.com/fdslight/fdslight/blob/69bc6b16f496b9dc628ecd1bc49f776e98e77ba0/pywind/evtframework/handlers/udp_handler.py#L181-L185 | ||
MozillaSecurity/grizzly | 1c41478e32f323189a2c322ec041c3e0902a158a | grizzly/reduce/strategies/beautify.py | python | CSSBeautify.beautify_bytes | (cls, data, linesep=b"\n") | return linesep_u.join(beautified.splitlines()).encode(
"utf-8", errors="surrogateescape"
) | Perform CSS beautification on a code buffer.
Arguments:
data (bytes): The code data to be beautified.
linesep (bytes): Newline sequence used in this testcase.
Returns:
bytes: The beautified result. | Perform CSS beautification on a code buffer. | [
"Perform",
"CSS",
"beautification",
"on",
"a",
"code",
"buffer",
"."
] | def beautify_bytes(cls, data, linesep=b"\n"):
"""Perform CSS beautification on a code buffer.
Arguments:
data (bytes): The code data to be beautified.
linesep (bytes): Newline sequence used in this testcase.
Returns:
bytes: The beautified result.
"""
assert cls.import_available
linesep_u = linesep.decode("utf-8")
data = data.decode("utf-8", errors="surrogateescape")
beautified = cssbeautifier.beautify(data, cls.opts)
return linesep_u.join(beautified.splitlines()).encode(
"utf-8", errors="surrogateescape"
) | [
"def",
"beautify_bytes",
"(",
"cls",
",",
"data",
",",
"linesep",
"=",
"b\"\\n\"",
")",
":",
"assert",
"cls",
".",
"import_available",
"linesep_u",
"=",
"linesep",
".",
"decode",
"(",
"\"utf-8\"",
")",
"data",
"=",
"data",
".",
"decode",
"(",
"\"utf-8\"",
... | https://github.com/MozillaSecurity/grizzly/blob/1c41478e32f323189a2c322ec041c3e0902a158a/grizzly/reduce/strategies/beautify.py#L306-L322 | |
AnonGit90210/RamanujanMachine | 1f4f8f76e61291f4dc4a81fead4a721f21f5f943 | enum_poly_params.py | python | BasicEnumPolyParams._polynom_degree | (p) | return deg - 1 | Finds deg(p). It may be different than len(p). E.g. deg([1, 1, 0, 0]) is 1 and not 3. | Finds deg(p). It may be different than len(p). E.g. deg([1, 1, 0, 0]) is 1 and not 3. | [
"Finds",
"deg",
"(",
"p",
")",
".",
"It",
"may",
"be",
"different",
"than",
"len",
"(",
"p",
")",
".",
"E",
".",
"g",
".",
"deg",
"(",
"[",
"1",
"1",
"0",
"0",
"]",
")",
"is",
"1",
"and",
"not",
"3",
"."
] | def _polynom_degree(p):
"""Finds deg(p). It may be different than len(p). E.g. deg([1, 1, 0, 0]) is 1 and not 3."""
deg = len(p)
for i in p[::-1]:
if i != 0:
break
deg -= 1
return deg - 1 | [
"def",
"_polynom_degree",
"(",
"p",
")",
":",
"deg",
"=",
"len",
"(",
"p",
")",
"for",
"i",
"in",
"p",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"i",
"!=",
"0",
":",
"break",
"deg",
"-=",
"1",
"return",
"deg",
"-",
"1"
] | https://github.com/AnonGit90210/RamanujanMachine/blob/1f4f8f76e61291f4dc4a81fead4a721f21f5f943/enum_poly_params.py#L173-L180 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/syslog_ng.py | python | set_binary_path | (name) | return _format_state_result(name, result=True, changes=changes) | Sets the path, where the syslog-ng binary can be found. This function is
intended to be used from states.
If syslog-ng is installed via a package manager, users don't need to use
this function.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_binary_path name=/usr/sbin | Sets the path, where the syslog-ng binary can be found. This function is
intended to be used from states. | [
"Sets",
"the",
"path",
"where",
"the",
"syslog",
"-",
"ng",
"binary",
"can",
"be",
"found",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | def set_binary_path(name):
"""
Sets the path, where the syslog-ng binary can be found. This function is
intended to be used from states.
If syslog-ng is installed via a package manager, users don't need to use
this function.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_binary_path name=/usr/sbin
"""
global __SYSLOG_NG_BINARY_PATH
old = __SYSLOG_NG_BINARY_PATH
__SYSLOG_NG_BINARY_PATH = name
changes = _format_changes(old, name)
return _format_state_result(name, result=True, changes=changes) | [
"def",
"set_binary_path",
"(",
"name",
")",
":",
"global",
"__SYSLOG_NG_BINARY_PATH",
"old",
"=",
"__SYSLOG_NG_BINARY_PATH",
"__SYSLOG_NG_BINARY_PATH",
"=",
"name",
"changes",
"=",
"_format_changes",
"(",
"old",
",",
"name",
")",
"return",
"_format_state_result",
"(",... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/syslog_ng.py#L679-L698 | |
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/flaskext/sqlalchemy.py | python | Pagination.next | (self, error_out=False) | return self.query.paginate(self.page + 1, self.per_page, error_out) | Returns a :class:`Pagination` object for the next page. | Returns a :class:`Pagination` object for the next page. | [
"Returns",
"a",
":",
"class",
":",
"Pagination",
"object",
"for",
"the",
"next",
"page",
"."
] | def next(self, error_out=False):
"""Returns a :class:`Pagination` object for the next page."""
assert self.query is not None, 'a query object is required ' \
'for this method to work'
return self.query.paginate(self.page + 1, self.per_page, error_out) | [
"def",
"next",
"(",
"self",
",",
"error_out",
"=",
"False",
")",
":",
"assert",
"self",
".",
"query",
"is",
"not",
"None",
",",
"'a query object is required '",
"'for this method to work'",
"return",
"self",
".",
"query",
".",
"paginate",
"(",
"self",
".",
"... | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/flaskext/sqlalchemy.py#L282-L286 | |
Rydgel/Fake-images-please | 86c2e8086c0002ad3f598380145974d297e24329 | app/helpers/fakeimg.py | python | FakeImg.__init__ | (self, width, height, background_color, foreground_color, alpha_background, alpha_foreground, image_type,
text=None, font_name=None, font_size=None, retina=False) | Init FakeImg with parameters.
Args:
width (int): The width of the image.
height (int): The height of the image.
background_color (str): The background color of the image. It should be in web hexadecimal format.
Example: #FFF, #123456.
alpha_background (int): Alpha value of the background color.
foreground_color (str): The text color of the image. It should be in web hexadecimal format.
Example: #FFF, #123456.
alpha_foreground (int): Alpha value of the foreground color.
image_type (string): The image type which can be "png" or "webp".
text (str): Optional. The actual text which will be drawn on the image.
Default: f"{width} x {height}"
font_name (str): Optional. The font name to use.
Default: "yanone".
Fallback to "yanone" if font not found.
font_size (int): Optional. The font size to use. Default value is calculated based on the image dimension.
retina (bool): Optional. Wether to use retina display or not. It basically just multiplies dimension of
the image by 2. | Init FakeImg with parameters. | [
"Init",
"FakeImg",
"with",
"parameters",
"."
] | def __init__(self, width, height, background_color, foreground_color, alpha_background, alpha_foreground, image_type,
text=None, font_name=None, font_size=None, retina=False):
"""Init FakeImg with parameters.
Args:
width (int): The width of the image.
height (int): The height of the image.
background_color (str): The background color of the image. It should be in web hexadecimal format.
Example: #FFF, #123456.
alpha_background (int): Alpha value of the background color.
foreground_color (str): The text color of the image. It should be in web hexadecimal format.
Example: #FFF, #123456.
alpha_foreground (int): Alpha value of the foreground color.
image_type (string): The image type which can be "png" or "webp".
text (str): Optional. The actual text which will be drawn on the image.
Default: f"{width} x {height}"
font_name (str): Optional. The font name to use.
Default: "yanone".
Fallback to "yanone" if font not found.
font_size (int): Optional. The font size to use. Default value is calculated based on the image dimension.
retina (bool): Optional. Wether to use retina display or not. It basically just multiplies dimension of
the image by 2.
"""
if retina:
self.width, self.height = [x * 2 for x in [width, height]]
else:
self.width, self.height = width, height
self.background_color = f"#{background_color}"
self.alpha_background = alpha_background
self.foreground_color = f"#{foreground_color}"
self.alpha_foreground = alpha_foreground
self.image_type = image_type
self.text = text or f"{width} x {height}"
self.font_name = font_name or "yanone"
try:
if int(font_size) > 0:
if retina:
# scaling font at retina display
self.font_size = 2 * int(font_size)
else:
self.font_size = int(font_size)
else:
raise ValueError
except (ValueError, TypeError):
self.font_size = self._calculate_font_size()
self.font = self._choose_font()
self.pil_image = self._draw() | [
"def",
"__init__",
"(",
"self",
",",
"width",
",",
"height",
",",
"background_color",
",",
"foreground_color",
",",
"alpha_background",
",",
"alpha_foreground",
",",
"image_type",
",",
"text",
"=",
"None",
",",
"font_name",
"=",
"None",
",",
"font_size",
"=",
... | https://github.com/Rydgel/Fake-images-please/blob/86c2e8086c0002ad3f598380145974d297e24329/app/helpers/fakeimg.py#L15-L61 | ||
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/Rotten-Tomatoes/PyAl/Request/requests/packages/urllib3/poolmanager.py | python | PoolManager.urlopen | (self, method, url, redirect=True, **kw) | return self.urlopen(method, redirect_location, **kw) | Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. | Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``. | [
"Same",
"as",
":",
"meth",
":",
"urllib3",
".",
"connectionpool",
".",
"HTTPConnectionPool",
".",
"urlopen",
"with",
"custom",
"cross",
"-",
"host",
"redirect",
"logic",
"and",
"only",
"sends",
"the",
"request",
"-",
"uri",
"portion",
"of",
"the",
"url",
"... | def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
if response.status == 303:
method = 'GET'
log.info("Redirecting %s -> %s" % (url, redirect_location))
kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown
return self.urlopen(method, redirect_location, **kw) | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"redirect",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"conn",
"=",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"... | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Rotten-Tomatoes/PyAl/Request/requests/packages/urllib3/poolmanager.py#L102-L128 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/google/appengine/api/remote_socket/_remote_socket.py | python | getdefaulttimeout | () | return _GLOBAL_TIMEOUT_VALUE | getdefaulttimeout() -> timeout
Returns the default timeout in floating seconds for new socket objects.
A value of None indicates that new socket objects have no timeout.
When the socket module is first imported, the default is None. | getdefaulttimeout() -> timeout | [
"getdefaulttimeout",
"()",
"-",
">",
"timeout"
] | def getdefaulttimeout():
"""getdefaulttimeout() -> timeout
Returns the default timeout in floating seconds for new socket objects.
A value of None indicates that new socket objects have no timeout.
When the socket module is first imported, the default is None.
"""
if _GLOBAL_TIMEOUT_VALUE < 0.0:
return None
return _GLOBAL_TIMEOUT_VALUE | [
"def",
"getdefaulttimeout",
"(",
")",
":",
"if",
"_GLOBAL_TIMEOUT_VALUE",
"<",
"0.0",
":",
"return",
"None",
"return",
"_GLOBAL_TIMEOUT_VALUE"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/remote_socket/_remote_socket.py#L375-L385 | |
cocrawler/cocrawler | a9be74308fe666130cb9ca3dd64e18f4c30d2894 | cocrawler/robots.py | python | Robots.fetch_robots | (self, schemenetloc, dns_entry, crawler,
seed_host=None, get_kwargs={}) | return robots | https://developers.google.com/search/reference/robots_txt
3xx redir == follow up to 5 hops, then consider it a 404.
4xx errors == no crawl restrictions
5xx errors == full disallow. fast retry if 503.
if site appears to return 5xx for 404, then 5xx is treated as a 404 | https://developers.google.com/search/reference/robots_txt
3xx redir == follow up to 5 hops, then consider it a 404.
4xx errors == no crawl restrictions
5xx errors == full disallow. fast retry if 503.
if site appears to return 5xx for 404, then 5xx is treated as a 404 | [
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"/",
"search",
"/",
"reference",
"/",
"robots_txt",
"3xx",
"redir",
"==",
"follow",
"up",
"to",
"5",
"hops",
"then",
"consider",
"it",
"a",
"404",
".",
"4xx",
"errors",
"==",
"no",
"crawl",
... | async def fetch_robots(self, schemenetloc, dns_entry, crawler,
seed_host=None, get_kwargs={}):
'''
https://developers.google.com/search/reference/robots_txt
3xx redir == follow up to 5 hops, then consider it a 404.
4xx errors == no crawl restrictions
5xx errors == full disallow. fast retry if 503.
if site appears to return 5xx for 404, then 5xx is treated as a 404
'''
url = URL(schemenetloc + '/robots.txt')
# We might enter this routine multiple times, so, sleep if we aren't the first
if schemenetloc in self.in_progress:
while schemenetloc in self.in_progress:
LOGGER.debug('sleeping because someone beat me to the robots punch')
stats.stats_sum('robots sleep for collision', 1)
with stats.coroutine_state('robots collision sleep'):
interval = random.uniform(0.2, 0.3)
await asyncio.sleep(interval)
# at this point robots might be in the cache... or not.
try:
robots = self.datalayer.read_robots_cache(schemenetloc)
except KeyError:
robots = None
if robots is not None:
return robots
# ok, so it's not in the cache -- and the other guy's fetch failed.
# if we just fell through, there would be a big race.
# treat this as a "no data" failure.
LOGGER.debug('some other fetch of robots has failed.')
stats.stats_sum('robots sleep then cache miss', 1)
return None
self.in_progress.add(schemenetloc)
f = await fetcher.fetch(url, self.session, max_page_size=self.max_robots_page_size,
allow_redirects=True, max_redirects=5, stats_prefix='robots ',
get_kwargs=get_kwargs)
json_log = {'action': 'fetch', 'time': time.time()}
if f.ip is not None:
json_log['ip'] = f.ip
if f.last_exception:
if f.last_exception.startswith('ClientError: TooManyRedirects'):
error = 'got too many redirects, treating as empty robots'
json_log['error'] = error
self.jsonlog(schemenetloc, json_log)
return self._cache_empty_robots(schemenetloc, None)
else:
json_log['error'] = 'max tries exceeded, final exception is: ' + f.last_exception
self.jsonlog(schemenetloc, json_log)
self.in_progress.discard(schemenetloc)
return None
if f.response.history:
redir_history = [str(h.url) for h in f.response.history]
redir_history.append(str(f.response.url))
json_log['redir_history'] = redir_history
stats.stats_sum('robots fetched', 1)
# If the url was redirected to a different host/robots.txt, let's cache that final host too
final_url = str(f.response.url) # YARL object
final_schemenetloc = None
if final_url != url.url:
final_parts = urllib.parse.urlsplit(final_url)
if final_parts.path == '/robots.txt':
final_schemenetloc = final_parts.scheme + '://' + final_parts.netloc
json_log['final_host'] = final_schemenetloc
status = f.response.status
json_log['status'] = status
json_log['t_first_byte'] = f.t_first_byte
if str(status).startswith('3') or str(status).startswith('4'):
if status >= 400:
error = 'got a 4xx, treating as empty robots'
else:
error = 'too many redirects, treating as empty robots'
json_log['error'] = error
self.jsonlog(schemenetloc, json_log)
return self._cache_empty_robots(schemenetloc, final_schemenetloc)
if str(status).startswith('5'):
json_log['error'] = 'got a 5xx, treating as deny' # same as google
self.jsonlog(schemenetloc, json_log)
self.in_progress.discard(schemenetloc)
return None
# we got a 2xx, so let's use the final headers to facet the final server
if dns_entry:
host_geoip = dns_entry[3]
else:
host_geoip = {}
if final_schemenetloc:
# if the hostname is the same and only the scheme is different, that's ok
# TODO: use URL.hostname
if ((final_url.replace('https://', 'http://', 1) != url.url and
final_url.replace('http://', 'https://', 1) != url.url)):
host_geoip = {} # the passed-in one is for the initial server
post_fetch.post_robots_txt(f, final_url, host_geoip, json_log['time'], crawler, seed_host=seed_host)
body_bytes = f.body_bytes
content_encoding = f.response.headers.get('content-encoding', 'identity')
if content_encoding != 'identity':
body_bytes = content.decompress(f.body_bytes, content_encoding, url=final_url)
with stats.record_burn('robots sha1'):
sha1 = 'sha1:' + hashlib.sha1(body_bytes).hexdigest()
json_log['checksum'] = sha1
body_bytes = strip_bom(body_bytes).lstrip()
plausible, message = is_plausible_robots(body_bytes)
if not plausible:
# policy: treat as empty
json_log['error'] = 'saw an implausible robots.txt, treating as empty'
json_log['implausible'] = message
self.jsonlog(schemenetloc, json_log)
return self._cache_empty_robots(schemenetloc, final_schemenetloc)
try:
body = body_bytes.decode(encoding='utf8', errors='replace')
except asyncio.CancelledError:
raise
except Exception as e:
# log as surprising, also treat like a fetch error
json_log['error'] = 'robots body decode threw a surprising exception: ' + repr(e)
self.jsonlog(schemenetloc, json_log)
self.in_progress.discard(schemenetloc)
return None
robots_facets(body, self.robotname, json_log)
with stats.record_burn('robots parse', url=schemenetloc):
robots = reppy.robots.Robots.parse('', body)
with stats.record_burn('robots is_allowed', url=schemenetloc):
check = robots.allowed('/', '*')
if check == 'denied':
json_log['generic_deny_slash'] = True
check = robots.allowed('/', 'googlebot')
json_log['google_deny_slash'] = check == 'denied'
self.datalayer.cache_robots(schemenetloc, robots)
self.in_progress.discard(schemenetloc)
if final_schemenetloc:
self.datalayer.cache_robots(final_schemenetloc, robots)
# we did not set this but we'll discard it anyway
self.in_progress.discard(final_schemenetloc)
sitemaps = list(robots.sitemaps)
if sitemaps:
json_log['sitemap_lines'] = len(sitemaps)
self.jsonlog(schemenetloc, json_log)
return robots | [
"async",
"def",
"fetch_robots",
"(",
"self",
",",
"schemenetloc",
",",
"dns_entry",
",",
"crawler",
",",
"seed_host",
"=",
"None",
",",
"get_kwargs",
"=",
"{",
"}",
")",
":",
"url",
"=",
"URL",
"(",
"schemenetloc",
"+",
"'/robots.txt'",
")",
"# We might en... | https://github.com/cocrawler/cocrawler/blob/a9be74308fe666130cb9ca3dd64e18f4c30d2894/cocrawler/robots.py#L181-L339 | |
uqfoundation/multiprocess | 028cc73f02655e6451d92e5147d19d8c10aebe50 | py2.7/multiprocess/util.py | python | Finalize.cancel | (self) | Cancel finalization of the object | Cancel finalization of the object | [
"Cancel",
"finalization",
"of",
"the",
"object"
] | def cancel(self):
'''
Cancel finalization of the object
'''
try:
del _finalizer_registry[self._key]
except KeyError:
pass
else:
self._weakref = self._callback = self._args = \
self._kwargs = self._key = None | [
"def",
"cancel",
"(",
"self",
")",
":",
"try",
":",
"del",
"_finalizer_registry",
"[",
"self",
".",
"_key",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
"_weakref",
"=",
"self",
".",
"_callback",
"=",
"self",
".",
"_args",
"=",
"... | https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py2.7/multiprocess/util.py#L215-L225 | ||
wistbean/learn_python3_spider | 73c873f4845f4385f097e5057407d03dd37a117b | stackoverflow/venv/lib/python3.6/site-packages/twisted/application/internet.py | python | StreamServerEndpointService.stopService | (self) | return d | Stop listening on the port if it is already listening, otherwise,
cancel the attempt to listen.
@return: a L{Deferred<twisted.internet.defer.Deferred>} which fires
with L{None} when the port has stopped listening. | Stop listening on the port if it is already listening, otherwise,
cancel the attempt to listen. | [
"Stop",
"listening",
"on",
"the",
"port",
"if",
"it",
"is",
"already",
"listening",
"otherwise",
"cancel",
"the",
"attempt",
"to",
"listen",
"."
] | def stopService(self):
"""
Stop listening on the port if it is already listening, otherwise,
cancel the attempt to listen.
@return: a L{Deferred<twisted.internet.defer.Deferred>} which fires
with L{None} when the port has stopped listening.
"""
self._waitingForPort.cancel()
def stopIt(port):
if port is not None:
return port.stopListening()
d = self._waitingForPort.addCallback(stopIt)
def stop(passthrough):
self.running = False
return passthrough
d.addBoth(stop)
return d | [
"def",
"stopService",
"(",
"self",
")",
":",
"self",
".",
"_waitingForPort",
".",
"cancel",
"(",
")",
"def",
"stopIt",
"(",
"port",
")",
":",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"port",
".",
"stopListening",
"(",
")",
"d",
"=",
"self",
... | https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/internet.py#L383-L400 | |
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/redis/connection.py | python | HiredisParser.__init__ | (self, socket_read_size) | [] | def __init__(self, socket_read_size):
if not HIREDIS_AVAILABLE:
raise RedisError("Hiredis is not installed")
self.socket_read_size = socket_read_size
if HIREDIS_USE_BYTE_BUFFER:
self._buffer = bytearray(socket_read_size) | [
"def",
"__init__",
"(",
"self",
",",
"socket_read_size",
")",
":",
"if",
"not",
"HIREDIS_AVAILABLE",
":",
"raise",
"RedisError",
"(",
"\"Hiredis is not installed\"",
")",
"self",
".",
"socket_read_size",
"=",
"socket_read_size",
"if",
"HIREDIS_USE_BYTE_BUFFER",
":",
... | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/redis/connection.py#L286-L292 | ||||
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/sqlalchemy/sql/expression.py | python | desc | (column) | return _UnaryExpression(column, modifier=operators.desc_op) | Return a descending ``ORDER BY`` clause element.
e.g.::
someselect.order_by(desc(table1.mycol))
produces::
ORDER BY mycol DESC | Return a descending ``ORDER BY`` clause element. | [
"Return",
"a",
"descending",
"ORDER",
"BY",
"clause",
"element",
"."
] | def desc(column):
"""Return a descending ``ORDER BY`` clause element.
e.g.::
someselect.order_by(desc(table1.mycol))
produces::
ORDER BY mycol DESC
"""
return _UnaryExpression(column, modifier=operators.desc_op) | [
"def",
"desc",
"(",
"column",
")",
":",
"return",
"_UnaryExpression",
"(",
"column",
",",
"modifier",
"=",
"operators",
".",
"desc_op",
")"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/sql/expression.py#L84-L96 | |
Fallen-Breath/MCDReforged | fdb1d2520b35f916123f265dbd94603981bb2b0c | mcdreforged/plugin/server_interface.py | python | PluginServerInterface.save_config_simple | (
self, config: Union[dict, Serializable], file_name: str = 'config.json', *,
in_data_folder: bool = True, encoding: str = 'utf8'
) | A simple method to save your dict or Serializable type config as a json file
:param config: The config instance to be saved
:param file_name: The name of the config file. It can also be a path to the config file
:param in_data_folder: If True, the parent directory of file operating is the data folder of the plugin
:param encoding: The encoding method to write the config file | A simple method to save your dict or Serializable type config as a json file
:param config: The config instance to be saved
:param file_name: The name of the config file. It can also be a path to the config file
:param in_data_folder: If True, the parent directory of file operating is the data folder of the plugin
:param encoding: The encoding method to write the config file | [
"A",
"simple",
"method",
"to",
"save",
"your",
"dict",
"or",
"Serializable",
"type",
"config",
"as",
"a",
"json",
"file",
":",
"param",
"config",
":",
"The",
"config",
"instance",
"to",
"be",
"saved",
":",
"param",
"file_name",
":",
"The",
"name",
"of",
... | def save_config_simple(
self, config: Union[dict, Serializable], file_name: str = 'config.json', *,
in_data_folder: bool = True, encoding: str = 'utf8'
) -> None:
"""
A simple method to save your dict or Serializable type config as a json file
:param config: The config instance to be saved
:param file_name: The name of the config file. It can also be a path to the config file
:param in_data_folder: If True, the parent directory of file operating is the data folder of the plugin
:param encoding: The encoding method to write the config file
"""
config_file_path = os.path.join(self.get_data_folder(), file_name) if in_data_folder else file_name
if isinstance(config, Serializable):
data = config.serialize()
else:
data = config
target_folder = os.path.dirname(config_file_path)
if len(target_folder) > 0 and not os.path.isdir(target_folder):
os.makedirs(target_folder)
with open(config_file_path, 'w', encoding=encoding) as file:
# config file should be nicely readable, so here come the indent and non-ascii chars
json.dump(data, file, indent=4, ensure_ascii=False) | [
"def",
"save_config_simple",
"(",
"self",
",",
"config",
":",
"Union",
"[",
"dict",
",",
"Serializable",
"]",
",",
"file_name",
":",
"str",
"=",
"'config.json'",
",",
"*",
",",
"in_data_folder",
":",
"bool",
"=",
"True",
",",
"encoding",
":",
"str",
"=",... | https://github.com/Fallen-Breath/MCDReforged/blob/fdb1d2520b35f916123f265dbd94603981bb2b0c/mcdreforged/plugin/server_interface.py#L776-L797 | ||
tuzhaopeng/NMT-Coverage | afe87b04a82933384688c7e441a4c7b3b38fee8d | build/lib/groundhog/layers/basic.py | python | Container.tensor_from_layer | (self, arg, collect_params=True) | Grab the theano tensor representing the computation of this
layer/operator iff `arg` is a layer.
:type collect_params: bool
:param collect_params: Flag. If true, also collect the parameters
and inputs of the layer `arg` and make them parameters and inputs
needed to compute the current layer/operator | Grab the theano tensor representing the computation of this
layer/operator iff `arg` is a layer. | [
"Grab",
"the",
"theano",
"tensor",
"representing",
"the",
"computation",
"of",
"this",
"layer",
"/",
"operator",
"iff",
"arg",
"is",
"a",
"layer",
"."
] | def tensor_from_layer(self, arg, collect_params=True):
"""
Grab the theano tensor representing the computation of this
layer/operator iff `arg` is a layer.
:type collect_params: bool
:param collect_params: Flag. If true, also collect the parameters
and inputs of the layer `arg` and make them parameters and inputs
needed to compute the current layer/operator
"""
if not collect_params:
if isinstance(arg, Container):
return arg.out
else:
return arg
if isinstance(arg, Container):
self.merge_params(arg)
return arg.out
elif isinstance(arg, theano.gof.Variable):
inps = [x for x in theano.gof.graph.inputs([arg])
if not isinstance(x, (TT.Constant, theano.compile.SharedVariable))]
self.add_inputs(inps)
return arg
else:
return arg | [
"def",
"tensor_from_layer",
"(",
"self",
",",
"arg",
",",
"collect_params",
"=",
"True",
")",
":",
"if",
"not",
"collect_params",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Container",
")",
":",
"return",
"arg",
".",
"out",
"else",
":",
"return",
"arg",
... | https://github.com/tuzhaopeng/NMT-Coverage/blob/afe87b04a82933384688c7e441a4c7b3b38fee8d/build/lib/groundhog/layers/basic.py#L79-L105 | ||
dedupeio/dedupe-examples | e09cac9e09b1534508a064197f6f86275fe9fa87 | csv_example/csv_example.py | python | preProcess | (column) | return column | Do a little bit of data cleaning with the help of Unidecode and Regex.
Things like casing, extra spaces, quotes and new lines can be ignored. | Do a little bit of data cleaning with the help of Unidecode and Regex.
Things like casing, extra spaces, quotes and new lines can be ignored. | [
"Do",
"a",
"little",
"bit",
"of",
"data",
"cleaning",
"with",
"the",
"help",
"of",
"Unidecode",
"and",
"Regex",
".",
"Things",
"like",
"casing",
"extra",
"spaces",
"quotes",
"and",
"new",
"lines",
"can",
"be",
"ignored",
"."
] | def preProcess(column):
"""
Do a little bit of data cleaning with the help of Unidecode and Regex.
Things like casing, extra spaces, quotes and new lines can be ignored.
"""
column = unidecode(column)
column = re.sub(' +', ' ', column)
column = re.sub('\n', ' ', column)
column = column.strip().strip('"').strip("'").lower().strip()
# If data is missing, indicate that by setting the value to `None`
if not column:
column = None
return column | [
"def",
"preProcess",
"(",
"column",
")",
":",
"column",
"=",
"unidecode",
"(",
"column",
")",
"column",
"=",
"re",
".",
"sub",
"(",
"' +'",
",",
"' '",
",",
"column",
")",
"column",
"=",
"re",
".",
"sub",
"(",
"'\\n'",
",",
"' '",
",",
"column",
... | https://github.com/dedupeio/dedupe-examples/blob/e09cac9e09b1534508a064197f6f86275fe9fa87/csv_example/csv_example.py#L27-L39 | |
awslabs/autogluon | 7309118f2ab1c9519f25acf61a283a95af95842b | tabular/src/autogluon/tabular/models/catboost/catboost_utils.py | python | RegressionCustomMetric.evaluate | (self, approxes, target, weight) | return score, 1 | [] | def evaluate(self, approxes, target, weight):
y_pred = self._get_y_pred(approxes=approxes)
score = self.metric(np.array(target), y_pred)
return score, 1 | [
"def",
"evaluate",
"(",
"self",
",",
"approxes",
",",
"target",
",",
"weight",
")",
":",
"y_pred",
"=",
"self",
".",
"_get_y_pred",
"(",
"approxes",
"=",
"approxes",
")",
"score",
"=",
"self",
".",
"metric",
"(",
"np",
".",
"array",
"(",
"target",
")... | https://github.com/awslabs/autogluon/blob/7309118f2ab1c9519f25acf61a283a95af95842b/tabular/src/autogluon/tabular/models/catboost/catboost_utils.py#L78-L82 | |||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/nntplib.py | python | NNTP.statparse | (self, resp) | return resp, nr, id | Internal: parse the response of a STAT, NEXT or LAST command. | Internal: parse the response of a STAT, NEXT or LAST command. | [
"Internal",
":",
"parse",
"the",
"response",
"of",
"a",
"STAT",
"NEXT",
"or",
"LAST",
"command",
"."
] | def statparse(self, resp):
"""Internal: parse the response of a STAT, NEXT or LAST command."""
if resp[:2] != '22':
raise NNTPReplyError(resp)
words = resp.split()
nr = 0
id = ''
n = len(words)
if n > 1:
nr = words[1]
if n > 2:
id = words[2]
return resp, nr, id | [
"def",
"statparse",
"(",
"self",
",",
"resp",
")",
":",
"if",
"resp",
"[",
":",
"2",
"]",
"!=",
"'22'",
":",
"raise",
"NNTPReplyError",
"(",
"resp",
")",
"words",
"=",
"resp",
".",
"split",
"(",
")",
"nr",
"=",
"0",
"id",
"=",
"''",
"n",
"=",
... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/nntplib.py#L377-L389 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/scapy/asn1/asn1.py | python | ASN1_OID.__repr__ | (self) | return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), conf.mib._oidname(self.val)) | [] | def __repr__(self):
return "<%s[%r]>" % (self.__dict__.get("name", self.__class__.__name__), conf.mib._oidname(self.val)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"<%s[%r]>\"",
"%",
"(",
"self",
".",
"__dict__",
".",
"get",
"(",
"\"name\"",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
",",
"conf",
".",
"mib",
".",
"_oidname",
"(",
"self",
".",
"val"... | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/asn1/asn1.py#L294-L295 | |||
django/django | 0a17666045de6739ae1c2ac695041823d5f827f7 | django/core/management/color.py | python | make_style | (config_string='') | return style | Create a Style object from the given config_string.
If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used. | Create a Style object from the given config_string. | [
"Create",
"a",
"Style",
"object",
"from",
"the",
"given",
"config_string",
"."
] | def make_style(config_string=''):
"""
Create a Style object from the given config_string.
If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used.
"""
style = Style()
color_settings = termcolors.parse_color_setting(config_string)
# The nocolor palette has all available roles.
# Use that palette as the basis for populating
# the palette as defined in the environment.
for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
if color_settings:
format = color_settings.get(role, {})
style_func = termcolors.make_style(**format)
else:
def style_func(x):
return x
setattr(style, role, style_func)
# For backwards compatibility,
# set style for ERROR_OUTPUT == ERROR
style.ERROR_OUTPUT = style.ERROR
return style | [
"def",
"make_style",
"(",
"config_string",
"=",
"''",
")",
":",
"style",
"=",
"Style",
"(",
")",
"color_settings",
"=",
"termcolors",
".",
"parse_color_setting",
"(",
"config_string",
")",
"# The nocolor palette has all available roles.",
"# Use that palette as the basis ... | https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/core/management/color.py#L63-L90 | |
twisted/twisted | dee676b040dd38b847ea6fb112a712cb5e119490 | src/twisted/web/error.py | python | RedirectWithNoLocation.__init__ | (self, code, message, uri) | Initializes a page redirect exception when no location is given.
@type code: L{bytes}
@param code: Refers to an HTTP status code, for example
C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to
a descriptive string that is used instead.
@type message: L{bytes}
@param message: A short error message.
@type uri: L{bytes}
@param uri: The URI which failed to give a proper location header
field. | Initializes a page redirect exception when no location is given. | [
"Initializes",
"a",
"page",
"redirect",
"exception",
"when",
"no",
"location",
"is",
"given",
"."
] | def __init__(self, code, message, uri):
"""
Initializes a page redirect exception when no location is given.
@type code: L{bytes}
@param code: Refers to an HTTP status code, for example
C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to
a descriptive string that is used instead.
@type message: L{bytes}
@param message: A short error message.
@type uri: L{bytes}
@param uri: The URI which failed to give a proper location header
field.
"""
Error.__init__(self, code, message)
self.message = self.message + b" to " + uri
self.uri = uri | [
"def",
"__init__",
"(",
"self",
",",
"code",
",",
"message",
",",
"uri",
")",
":",
"Error",
".",
"__init__",
"(",
"self",
",",
"code",
",",
"message",
")",
"self",
".",
"message",
"=",
"self",
".",
"message",
"+",
"b\" to \"",
"+",
"uri",
"self",
"... | https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/web/error.py#L177-L195 | ||
tensorflow/text | d67199e5ab80c455f425bf56fa65f4dd0cb805a1 | tensorflow_text/python/ops/sentencepiece_tokenizer.py | python | SentencepieceTokenizer.id_to_string | (self, input, name=None) | Converts vocabulary id into a token.
Args:
input: An arbitrary tensor of int32 representing the token IDs.
name: The name argument that is passed to the op function.
Returns:
A tensor of string with the same shape as input. | Converts vocabulary id into a token. | [
"Converts",
"vocabulary",
"id",
"into",
"a",
"token",
"."
] | def id_to_string(self, input, name=None): # pylint: disable=redefined-builtin
"""Converts vocabulary id into a token.
Args:
input: An arbitrary tensor of int32 representing the token IDs.
name: The name argument that is passed to the op function.
Returns:
A tensor of string with the same shape as input.
"""
with ops.name_scope(name, "SentencepieceTokenizerIdToString",
[self, input]):
input_tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor(input)
if input_tensor.shape.ndims is None:
raise ValueError("Rank of input_tensor must be statically known.")
if input_tensor.shape.ndims == 0:
strings = self.id_to_string(array_ops.stack([input_tensor]))
return strings[0]
if ragged_tensor.is_ragged(input_tensor):
strings = self.id_to_string(input_tensor.flat_values)
return input_tensor.with_flat_values(strings)
if input_tensor.shape.ndims > 1:
return array_ops.reshape(
self.id_to_string(array_ops.reshape(input_tensor, [-1])),
array_ops.shape(input_tensor))
return gen_sentencepiece_tokenizer.sentencepiece_id_to_string_op(
self._model_resource.resource_handle, input) | [
"def",
"id_to_string",
"(",
"self",
",",
"input",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"SentencepieceTokenizerIdToString\"",
",",
"[",
"self",
",",
"input",
"]",
")",
"... | https://github.com/tensorflow/text/blob/d67199e5ab80c455f425bf56fa65f4dd0cb805a1/tensorflow_text/python/ops/sentencepiece_tokenizer.py#L292-L318 | ||
adobe/ops-cli | 2384257c4199b3ff37e366f48b4dfce3ac282524 | src/ops/inventory/plugin/azr.py | python | DictGlue.__init__ | (self, data={}) | [] | def __init__(self, data={}):
self.__dict__.update(data) | [
"def",
"__init__",
"(",
"self",
",",
"data",
"=",
"{",
"}",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"data",
")"
] | https://github.com/adobe/ops-cli/blob/2384257c4199b3ff37e366f48b4dfce3ac282524/src/ops/inventory/plugin/azr.py#L18-L19 | ||||
manosim/django-rest-framework-docs | 94571d05617d24816ba8fdc5e836d17645a88319 | rest_framework_docs/api_docs.py | python | ApiDocumentation._is_format_endpoint | (self, pattern) | return '?P<format>' in pattern._regex | Exclude endpoints with a "format" parameter | Exclude endpoints with a "format" parameter | [
"Exclude",
"endpoints",
"with",
"a",
"format",
"parameter"
] | def _is_format_endpoint(self, pattern):
"""
Exclude endpoints with a "format" parameter
"""
return '?P<format>' in pattern._regex | [
"def",
"_is_format_endpoint",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"'?P<format>'",
"in",
"pattern",
".",
"_regex"
] | https://github.com/manosim/django-rest-framework-docs/blob/94571d05617d24816ba8fdc5e836d17645a88319/rest_framework_docs/api_docs.py#L39-L43 | |
hackingmaterials/atomate | bdca913591d22a6f71d4914c69f3ee191e2d96db | atomate/vasp/powerups.py | python | set_queue_options | (
original_wf,
walltime=None,
time_min=None,
qos=None,
fw_name_constraint=None,
task_name_constraint=None,
) | return original_wf | Modify queue submission parameters of Fireworks in a Workflow.
This powerup overrides paramters in the qadapter file by setting values in
the 'queueadapter' key of a Firework spec. For example, the walltime
requested from a queue can be modified on a per-workflow basis.
Args:
original_wf (Workflow):
walltime (str): Total walltime to request for the job in HH:MM:SS
format e.g., "00:10:00" for 10 minutes.
time_min (str): Minimum walltime to request in HH:MM:SS format.
Specifying both `walltime` and `time_min` can improve throughput on
some queues.
qos (str): QoS level to request. Typical examples include "regular",
"flex", and "scavenger". For Cori KNL "flex" QoS, it is necessary
to specify a `time_min` of no more than 2 hours.
fw_name_constraint (str): name of the Fireworks to be tagged (all if
None is passed)
task_name_constraint (str): name of the Firetasks to be tagged (e.g.
None or 'RunVasp')
Returns:
Workflow: workflow with modified queue options | Modify queue submission parameters of Fireworks in a Workflow. | [
"Modify",
"queue",
"submission",
"parameters",
"of",
"Fireworks",
"in",
"a",
"Workflow",
"."
] | def set_queue_options(
original_wf,
walltime=None,
time_min=None,
qos=None,
fw_name_constraint=None,
task_name_constraint=None,
):
"""
Modify queue submission parameters of Fireworks in a Workflow.
This powerup overrides paramters in the qadapter file by setting values in
the 'queueadapter' key of a Firework spec. For example, the walltime
requested from a queue can be modified on a per-workflow basis.
Args:
original_wf (Workflow):
walltime (str): Total walltime to request for the job in HH:MM:SS
format e.g., "00:10:00" for 10 minutes.
time_min (str): Minimum walltime to request in HH:MM:SS format.
Specifying both `walltime` and `time_min` can improve throughput on
some queues.
qos (str): QoS level to request. Typical examples include "regular",
"flex", and "scavenger". For Cori KNL "flex" QoS, it is necessary
to specify a `time_min` of no more than 2 hours.
fw_name_constraint (str): name of the Fireworks to be tagged (all if
None is passed)
task_name_constraint (str): name of the Firetasks to be tagged (e.g.
None or 'RunVasp')
Returns:
Workflow: workflow with modified queue options
"""
qsettings = {}
if walltime:
qsettings.update({"walltime": walltime})
if time_min:
qsettings.update({"time_min": time_min})
if qos:
qsettings.update({"qos": qos})
idx_list = get_fws_and_tasks(
original_wf,
fw_name_constraint=fw_name_constraint,
task_name_constraint=task_name_constraint,
)
for idx_fw, idx_t in idx_list:
original_wf.fws[idx_fw].spec.update({"_queueadapter": qsettings})
return original_wf | [
"def",
"set_queue_options",
"(",
"original_wf",
",",
"walltime",
"=",
"None",
",",
"time_min",
"=",
"None",
",",
"qos",
"=",
"None",
",",
"fw_name_constraint",
"=",
"None",
",",
"task_name_constraint",
"=",
"None",
",",
")",
":",
"qsettings",
"=",
"{",
"}"... | https://github.com/hackingmaterials/atomate/blob/bdca913591d22a6f71d4914c69f3ee191e2d96db/atomate/vasp/powerups.py#L419-L469 | |
qxf2/wtfiswronghere | 1726a2718af8250e9fff3ec541293094b2b9586a | 09_challenge/09_challenge.py | python | fizzbuzz | (max_num) | This method implements FizzBuzz | This method implements FizzBuzz | [
"This",
"method",
"implements",
"FizzBuzz"
] | def fizzbuzz(max_num):
"This method implements FizzBuzz"
# adding some redundant declarations on purpose
# we will make our script 'tighter' in one of coming exercises
three_mul = 'fizz'
five_mul = 'buzz'
num1 = 3
num2 = 5
# Google for 'range in python' to see what it does
for i in range(6,max_num):
# % or modulo division gives you the remainder
if i%num1==0 and i%num2==0:
print(i,three_mul+five_mul)
elif i%num1==0:
print(i,three_mul)
elif i%num2==0:
print(i,five_mul) | [
"def",
"fizzbuzz",
"(",
"max_num",
")",
":",
"# adding some redundant declarations on purpose",
"# we will make our script 'tighter' in one of coming exercises",
"three_mul",
"=",
"'fizz'",
"five_mul",
"=",
"'buzz'",
"num1",
"=",
"3",
"num2",
"=",
"5",
"# Google for 'range in... | https://github.com/qxf2/wtfiswronghere/blob/1726a2718af8250e9fff3ec541293094b2b9586a/09_challenge/09_challenge.py#L12-L30 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/tarfile.py | python | TarInfo._proc_member | (self, tarfile) | Choose the right processing method depending on
the type and call it. | Choose the right processing method depending on
the type and call it. | [
"Choose",
"the",
"right",
"processing",
"method",
"depending",
"on",
"the",
"type",
"and",
"call",
"it",
"."
] | def _proc_member(self, tarfile):
"""Choose the right processing method depending on
the type and call it.
"""
if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
return self._proc_gnulong(tarfile)
elif self.type == GNUTYPE_SPARSE:
return self._proc_sparse(tarfile)
elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
return self._proc_pax(tarfile)
else:
return self._proc_builtin(tarfile) | [
"def",
"_proc_member",
"(",
"self",
",",
"tarfile",
")",
":",
"if",
"self",
".",
"type",
"in",
"(",
"GNUTYPE_LONGNAME",
",",
"GNUTYPE_LONGLINK",
")",
":",
"return",
"self",
".",
"_proc_gnulong",
"(",
"tarfile",
")",
"elif",
"self",
".",
"type",
"==",
"GN... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tarfile.py#L1118-L1129 | ||
huawei-noah/vega | d9f13deede7f2b584e4b1d32ffdb833856129989 | vega/modules/operators/prune.py | python | _parse_module_name | (name, module) | Parse the module name of mindspore. | Parse the module name of mindspore. | [
"Parse",
"the",
"module",
"name",
"of",
"mindspore",
"."
] | def _parse_module_name(name, module):
"""Parse the module name of mindspore."""
if vega.is_ms_backend():
while (list(module.cells()) != []):
module = list(module.cells())[0]
name_list = name.split("/")[1:]
new_name = ""
for name in name_list:
name = "." + name.split("-")[0]
new_name += name
return new_name[1:], module
else:
return name, module | [
"def",
"_parse_module_name",
"(",
"name",
",",
"module",
")",
":",
"if",
"vega",
".",
"is_ms_backend",
"(",
")",
":",
"while",
"(",
"list",
"(",
"module",
".",
"cells",
"(",
")",
")",
"!=",
"[",
"]",
")",
":",
"module",
"=",
"list",
"(",
"module",
... | https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/modules/operators/prune.py#L60-L73 | ||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/IPython/html/services/sessions/sessionmanager.py | python | SessionManager.__del__ | (self) | Close connection once SessionManager closes | Close connection once SessionManager closes | [
"Close",
"connection",
"once",
"SessionManager",
"closes"
] | def __del__(self):
"""Close connection once SessionManager closes"""
self.cursor.close() | [
"def",
"__del__",
"(",
"self",
")",
":",
"self",
".",
"cursor",
".",
"close",
"(",
")"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/html/services/sessions/sessionmanager.py#L55-L57 | ||
uqfoundation/multiprocess | 028cc73f02655e6451d92e5147d19d8c10aebe50 | py3.5/multiprocess/context.py | python | BaseContext.RawArray | (self, typecode_or_type, size_or_initializer) | return RawArray(typecode_or_type, size_or_initializer) | Returns a shared array | Returns a shared array | [
"Returns",
"a",
"shared",
"array"
] | def RawArray(self, typecode_or_type, size_or_initializer):
'''Returns a shared array'''
from .sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer) | [
"def",
"RawArray",
"(",
"self",
",",
"typecode_or_type",
",",
"size_or_initializer",
")",
":",
"from",
".",
"sharedctypes",
"import",
"RawArray",
"return",
"RawArray",
"(",
"typecode_or_type",
",",
"size_or_initializer",
")"
] | https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.5/multiprocess/context.py#L125-L128 | |
myhdl/myhdl | 7b17942abbb2d9374df13f4f1f8c9d4589e1c88c | example/manual/ram.py | python | ram | (dout, din, addr, we, clk, depth=128) | return write, read | Ram model | Ram model | [
"Ram",
"model"
] | def ram(dout, din, addr, we, clk, depth=128):
""" Ram model """
mem = [Signal(intbv(0)[8:]) for i in range(depth)]
@always(clk.posedge)
def write():
if we:
mem[addr].next = din
@always_comb
def read():
dout.next = mem[addr]
return write, read | [
"def",
"ram",
"(",
"dout",
",",
"din",
",",
"addr",
",",
"we",
",",
"clk",
",",
"depth",
"=",
"128",
")",
":",
"mem",
"=",
"[",
"Signal",
"(",
"intbv",
"(",
"0",
")",
"[",
"8",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"depth",
")",
... | https://github.com/myhdl/myhdl/blob/7b17942abbb2d9374df13f4f1f8c9d4589e1c88c/example/manual/ram.py#L4-L18 | |
OpenEIT/OpenEIT | 0448694e8092361ae5ccb45fba81dee543a6244b | OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/corebluetooth/provider.py | python | CentralDelegate.peripheral_didDiscoverServices_ | (self, peripheral, services) | Called when services are discovered for a device. | Called when services are discovered for a device. | [
"Called",
"when",
"services",
"are",
"discovered",
"for",
"a",
"device",
"."
] | def peripheral_didDiscoverServices_(self, peripheral, services):
"""Called when services are discovered for a device."""
logger.debug('peripheral_didDiscoverServices called')
# Make sure the discovered services are added to the list of known
# services, and kick off characteristic discovery for each one.
# NOTE: For some reason the services parameter is never set to a good
# value, instead you must query peripheral.services() to enumerate the
# discovered services.
for service in peripheral.services():
if service_list().get(service) is None:
service_list().add(service, CoreBluetoothGattService(service))
# Kick off characteristic discovery for this service. Just discover
# all characteristics for now.
peripheral.discoverCharacteristics_forService_(None, service) | [
"def",
"peripheral_didDiscoverServices_",
"(",
"self",
",",
"peripheral",
",",
"services",
")",
":",
"logger",
".",
"debug",
"(",
"'peripheral_didDiscoverServices called'",
")",
"# Make sure the discovered services are added to the list of known",
"# services, and kick off characte... | https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/corebluetooth/provider.py#L124-L137 | ||
osmr/imgclsmob | f2993d3ce73a2f7ddba05da3891defb08547d504 | chainer_/chainercv2/models/densenet_cifar.py | python | densenet40_k24_bc_svhn | (classes=10, **kwargs) | return get_densenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_svhn", **kwargs) | DenseNet-BC-40 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters. | DenseNet-BC-40 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993. | [
"DenseNet",
"-",
"BC",
"-",
"40",
"(",
"k",
"=",
"24",
")",
"model",
"for",
"SVHN",
"from",
"Densely",
"Connected",
"Convolutional",
"Networks",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1608",
".",
"06993",
"."
] | def densenet40_k24_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_svhn", **kwargs) | [
"def",
"densenet40_k24_bc_svhn",
"(",
"classes",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_densenet_cifar",
"(",
"classes",
"=",
"classes",
",",
"blocks",
"=",
"40",
",",
"growth_rate",
"=",
"24",
",",
"bottleneck",
"=",
"True",
",",
"... | https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/densenet_cifar.py#L354-L369 | |
dpressel/mead-baseline | 9987e6b37fa6525a4ddc187c305e292a718f59a9 | layers/eight_mile/pytorch/serialize.py | python | from_gmlp_encoder_stack_array | (
pytorch_encoder_stack: GatedMLPEncoderStack, d: Dict, name: str = "GatedMLPEncoderStack"
) | Restore weights from a `GatedMLPEncoderStack`
:param pytorch_encoder_stack: A gMLP encoder stack
:param d: A Dict containing sets of arrays
:param name: A name for this primitive
:return: None | Restore weights from a `GatedMLPEncoderStack` | [
"Restore",
"weights",
"from",
"a",
"GatedMLPEncoderStack"
] | def from_gmlp_encoder_stack_array(
pytorch_encoder_stack: GatedMLPEncoderStack, d: Dict, name: str = "GatedMLPEncoderStack"
):
"""Restore weights from a `GatedMLPEncoderStack`
:param pytorch_encoder_stack: A gMLP encoder stack
:param d: A Dict containing sets of arrays
:param name: A name for this primitive
:return: None
"""
if isinstance(pytorch_encoder_stack.ln, nn.LayerNorm):
from_weight_array(pytorch_encoder_stack.ln, d, f"{name}/ln")
for i, enc_pyt in enumerate(pytorch_encoder_stack.encoders):
from_gmlp_encoder_array(enc_pyt, d, f"{name}/{i}") | [
"def",
"from_gmlp_encoder_stack_array",
"(",
"pytorch_encoder_stack",
":",
"GatedMLPEncoderStack",
",",
"d",
":",
"Dict",
",",
"name",
":",
"str",
"=",
"\"GatedMLPEncoderStack\"",
")",
":",
"if",
"isinstance",
"(",
"pytorch_encoder_stack",
".",
"ln",
",",
"nn",
".... | https://github.com/dpressel/mead-baseline/blob/9987e6b37fa6525a4ddc187c305e292a718f59a9/layers/eight_mile/pytorch/serialize.py#L657-L670 | ||
marsbroshok/VAD-python | 48bb998fce05330b065b874123eb94508cb9121a | vad.py | python | VoiceActivityDetector.plot_detected_speech_regions | (self) | return self | Performs speech detection and plot original signal and speech regions. | Performs speech detection and plot original signal and speech regions. | [
"Performs",
"speech",
"detection",
"and",
"plot",
"original",
"signal",
"and",
"speech",
"regions",
"."
] | def plot_detected_speech_regions(self):
""" Performs speech detection and plot original signal and speech regions.
"""
data = self.data
detected_windows = self.detect_speech()
data_speech = np.zeros(len(data))
it = np.nditer(detected_windows[:,0], flags=['f_index'])
while not it.finished:
data_speech[int(it[0])] = data[int(it[0])] * detected_windows[it.index,1]
it.iternext()
plt.figure()
plt.plot(data_speech)
plt.plot(data)
plt.show()
return self | [
"def",
"plot_detected_speech_regions",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"detected_windows",
"=",
"self",
".",
"detect_speech",
"(",
")",
"data_speech",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"data",
")",
")",
"it",
"=",
"np",
... | https://github.com/marsbroshok/VAD-python/blob/48bb998fce05330b065b874123eb94508cb9121a/vad.py#L114-L128 | |
elfi-dev/elfi | 07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c | elfi/store.py | python | StoreBase.__delitem__ | (self, batch_index) | Delete data from location `batch_index`. | Delete data from location `batch_index`. | [
"Delete",
"data",
"from",
"location",
"batch_index",
"."
] | def __delitem__(self, batch_index):
"""Delete data from location `batch_index`."""
raise NotImplementedError | [
"def",
"__delitem__",
"(",
"self",
",",
"batch_index",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/elfi-dev/elfi/blob/07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c/elfi/store.py#L400-L402 | ||
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pkg_resources/__init__.py | python | Distribution.__hash__ | (self) | return hash(self.hashcmp) | [] | def __hash__(self):
return hash(self.hashcmp) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"hashcmp",
")"
] | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pkg_resources/__init__.py#L2387-L2388 | |||
nucleic/enaml | 65c2a2a2d765e88f2e1103046680571894bb41ed | enaml/core/parser/base_parser.py | python | BaseEnamlParser.p_if_stmt1 | (self, p) | if_stmt : IF namedexpr_test COLON suite | if_stmt : IF namedexpr_test COLON suite | [
"if_stmt",
":",
"IF",
"namedexpr_test",
"COLON",
"suite"
] | def p_if_stmt1(self, p):
''' if_stmt : IF namedexpr_test COLON suite '''
if_stmt = ast.If()
if_stmt.test = p[2]
if_stmt.body = p[4]
if_stmt.lineno = p.lineno(1)
ast.fix_missing_locations(if_stmt)
if_stmt.orelse = []
p[0] = if_stmt | [
"def",
"p_if_stmt1",
"(",
"self",
",",
"p",
")",
":",
"if_stmt",
"=",
"ast",
".",
"If",
"(",
")",
"if_stmt",
".",
"test",
"=",
"p",
"[",
"2",
"]",
"if_stmt",
".",
"body",
"=",
"p",
"[",
"4",
"]",
"if_stmt",
".",
"lineno",
"=",
"p",
".",
"line... | https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/core/parser/base_parser.py#L1653-L1661 | ||
sisl/MADRL | 4a6d780e8cf111f312b757cca1b9f83441644958 | madrl_environments/hostage.py | python | CircAgent.velocity | (self) | return self._velocity | [] | def velocity(self):
assert self._velocity is not None
return self._velocity | [
"def",
"velocity",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_velocity",
"is",
"not",
"None",
"return",
"self",
".",
"_velocity"
] | https://github.com/sisl/MADRL/blob/4a6d780e8cf111f312b757cca1b9f83441644958/madrl_environments/hostage.py#L45-L47 | |||
ycszen/TorchSeg | 62eeb159aee77972048d9d7688a28249d3c56735 | model/bisenet/cityscapes.bisenet.X39/config.py | python | add_path | (path) | [] | def add_path(path):
if path not in sys.path:
sys.path.insert(0, path) | [
"def",
"add_path",
"(",
"path",
")",
":",
"if",
"path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
")"
] | https://github.com/ycszen/TorchSeg/blob/62eeb159aee77972048d9d7688a28249d3c56735/model/bisenet/cityscapes.bisenet.X39/config.py#L49-L51 | ||||
getsentry/sentry | 83b1f25aac3e08075e0e2495bc29efaf35aca18a | src/sentry/api/endpoints/event_owners.py | python | EventOwnersEndpoint.get | (self, request: Request, project, event_id) | return Response(
{
"owners": ordered_owners,
# TODO(mattrobenolt): We need to change the API here to return
# all rules, just keeping this way currently for API compat
"rule": rules[0].matcher if rules else None,
"rules": rules or [],
}
) | Retrieve suggested owners information for an event
``````````````````````````````````````````````````
:pparam string project_slug: the slug of the project the event
belongs to.
:pparam string event_id: the id of the event.
:auth: required | Retrieve suggested owners information for an event
`````````````````````````````````````````````````` | [
"Retrieve",
"suggested",
"owners",
"information",
"for",
"an",
"event"
] | def get(self, request: Request, project, event_id) -> Response:
"""
Retrieve suggested owners information for an event
``````````````````````````````````````````````````
:pparam string project_slug: the slug of the project the event
belongs to.
:pparam string event_id: the id of the event.
:auth: required
"""
event = eventstore.get_event_by_id(project.id, event_id)
if event is None:
return Response({"detail": "Event not found"}, status=404)
owners, rules = ProjectOwnership.get_owners(project.id, event.data)
# For sake of the API, we don't differentiate between
# the implicit "everyone" and no owners
if owners == ProjectOwnership.Everyone:
owners = []
serialized_owners = serialize(
ActorTuple.resolve_many(owners), request.user, ActorSerializer()
)
# Make sure the serialized owners are in the correct order
ordered_owners = []
owner_by_id = {(o["id"], o["type"]): o for o in serialized_owners}
for o in owners:
key = (str(o.id), "team" if o.type == Team else "user")
if owner_by_id.get(key):
ordered_owners.append(owner_by_id[key])
return Response(
{
"owners": ordered_owners,
# TODO(mattrobenolt): We need to change the API here to return
# all rules, just keeping this way currently for API compat
"rule": rules[0].matcher if rules else None,
"rules": rules or [],
}
) | [
"def",
"get",
"(",
"self",
",",
"request",
":",
"Request",
",",
"project",
",",
"event_id",
")",
"->",
"Response",
":",
"event",
"=",
"eventstore",
".",
"get_event_by_id",
"(",
"project",
".",
"id",
",",
"event_id",
")",
"if",
"event",
"is",
"None",
":... | https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/api/endpoints/event_owners.py#L12-L53 | |
influxdata/influxdb-python | 7cb565698c88bfbf9f4804650231bd28d09e2e6d | examples/tutorial_pandas.py | python | main | (host='localhost', port=8086) | Instantiate the connection to the InfluxDB client. | Instantiate the connection to the InfluxDB client. | [
"Instantiate",
"the",
"connection",
"to",
"the",
"InfluxDB",
"client",
"."
] | def main(host='localhost', port=8086):
"""Instantiate the connection to the InfluxDB client."""
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'line'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014-11-16',
periods=30, freq='H'), columns=['0'])
print("Create database: " + dbname)
client.create_database(dbname)
print("Write DataFrame")
client.write_points(df, 'demo', protocol=protocol)
print("Write DataFrame with Tags")
client.write_points(df, 'demo',
{'k1': 'v1', 'k2': 'v2'}, protocol=protocol)
print("Read DataFrame")
client.query("select * from demo")
print("Delete database: " + dbname)
client.drop_database(dbname) | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
")",
":",
"user",
"=",
"'root'",
"password",
"=",
"'root'",
"dbname",
"=",
"'demo'",
"protocol",
"=",
"'line'",
"client",
"=",
"DataFrameClient",
"(",
"host",
",",
"port",
",",
"... | https://github.com/influxdata/influxdb-python/blob/7cb565698c88bfbf9f4804650231bd28d09e2e6d/examples/tutorial_pandas.py#L10-L38 | ||
szaghi/FoBiS | 3fdc47499a953fbba4cf10adb204bfc6c4a1b2bb | src/main/python/fobis/FoBiSConfig.py | python | FoBiSConfig._check_vlibs_md5sum | (self) | Check if the md5sum of volatile libraries has changed and, in case, a re-build is triggered. | Check if the md5sum of volatile libraries has changed and, in case, a re-build is triggered. | [
"Check",
"if",
"the",
"md5sum",
"of",
"volatile",
"libraries",
"has",
"changed",
"and",
"in",
"case",
"a",
"re",
"-",
"build",
"is",
"triggered",
"."
] | def _check_vlibs_md5sum(self):
"""
Check if the md5sum of volatile libraries has changed and, in case, a re-build is triggered.
"""
for lib in self.cliargs.vlibs:
if not os.path.exists(lib):
self.print_r("The volatile library " + lib + " is not found!")
hashfile, comparison = self._check_md5sum(filename=lib, hashfile=os.path.join(self.cliargs.build_dir, '.' + os.path.basename(lib) + '.md5'))
if hashfile:
self.cliargs.force_compile = (not comparison) or self.cliargs.force_compile
if not comparison:
self.print_r("The volatile library " + lib + " is changed with respect the last building: forcing to (re-)compile all") | [
"def",
"_check_vlibs_md5sum",
"(",
"self",
")",
":",
"for",
"lib",
"in",
"self",
".",
"cliargs",
".",
"vlibs",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"lib",
")",
":",
"self",
".",
"print_r",
"(",
"\"The volatile library \"",
"+",
"lib... | https://github.com/szaghi/FoBiS/blob/3fdc47499a953fbba4cf10adb204bfc6c4a1b2bb/src/main/python/fobis/FoBiSConfig.py#L167-L178 | ||
brython-dev/brython | 9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3 | www/src/Lib/email/message.py | python | Message.get_content_charset | (self, failobj=None) | return charset.lower() | Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned. | Return the charset parameter of the Content-Type header. | [
"Return",
"the",
"charset",
"parameter",
"of",
"the",
"Content",
"-",
"Type",
"header",
"."
] | def get_content_charset(self, failobj=None):
"""Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
"""
missing = object()
charset = self.get_param('charset', missing)
if charset is missing:
return failobj
if isinstance(charset, tuple):
# RFC 2231 encoded, so decode it, and it better end up as ascii.
pcharset = charset[0] or 'us-ascii'
try:
# LookupError will be raised if the charset isn't known to
# Python. UnicodeError will be raised if the encoded text
# contains a character not in the charset.
as_bytes = charset[2].encode('raw-unicode-escape')
charset = str(as_bytes, pcharset)
except (LookupError, UnicodeError):
charset = charset[2]
# charset characters must be in us-ascii range
try:
charset.encode('us-ascii')
except UnicodeError:
return failobj
# RFC 2046, $4.1.2 says charsets are not case sensitive
return charset.lower() | [
"def",
"get_content_charset",
"(",
"self",
",",
"failobj",
"=",
"None",
")",
":",
"missing",
"=",
"object",
"(",
")",
"charset",
"=",
"self",
".",
"get_param",
"(",
"'charset'",
",",
"missing",
")",
"if",
"charset",
"is",
"missing",
":",
"return",
"failo... | https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/email/message.py#L881-L909 | |
KU4NG/OPMS_v3 | dbeeb74d9c0ff0ee3cfb940da7a1dadefcf9cfd4 | apps/users/views.py | python | SendActiveUserEmailView.get | (self, request) | return render(request, 'users/login/active_user.html', context=context) | [] | def get(self, request):
context = {}
return render(request, 'users/login/active_user.html', context=context) | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"context",
"=",
"{",
"}",
"return",
"render",
"(",
"request",
",",
"'users/login/active_user.html'",
",",
"context",
"=",
"context",
")"
] | https://github.com/KU4NG/OPMS_v3/blob/dbeeb74d9c0ff0ee3cfb940da7a1dadefcf9cfd4/apps/users/views.py#L269-L271 | |||
scotch/engineauth | e6e8f76edb3974c631f843e4e482723fddd1a36c | engineauth/models.py | python | User.add_email | (self, value, primary=False, verified=False, type=None) | return self.email_model.create(value, self.get_id(), primary=primary,
verified=verified, type=type) | [] | def add_email(self, value, primary=False, verified=False, type=None):
return self.email_model.create(value, self.get_id(), primary=primary,
verified=verified, type=type) | [
"def",
"add_email",
"(",
"self",
",",
"value",
",",
"primary",
"=",
"False",
",",
"verified",
"=",
"False",
",",
"type",
"=",
"None",
")",
":",
"return",
"self",
".",
"email_model",
".",
"create",
"(",
"value",
",",
"self",
".",
"get_id",
"(",
")",
... | https://github.com/scotch/engineauth/blob/e6e8f76edb3974c631f843e4e482723fddd1a36c/engineauth/models.py#L252-L254 | |||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/environ.py | python | item | (keys, default="") | return ret | Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None | Get one or more salt process environment variables.
Returns a dict. | [
"Get",
"one",
"or",
"more",
"salt",
"process",
"environment",
"variables",
".",
"Returns",
"a",
"dict",
"."
] | def item(keys, default=""):
"""
Get one or more salt process environment variables.
Returns a dict.
keys
Either a string or a list of strings that will be used as the
keys for environment lookup.
default
If the key is not found in the environment, return this value.
Default: ''
CLI Example:
.. code-block:: bash
salt '*' environ.item foo
salt '*' environ.item '[foo, baz]' default=None
"""
ret = {}
key_list = []
if isinstance(keys, str):
key_list.append(keys)
elif isinstance(keys, list):
key_list = keys
else:
log.debug(
"%s: 'keys' argument is not a string or list type: '%s'", __name__, keys
)
for key in key_list:
ret[key] = os.environ.get(key, default)
return ret | [
"def",
"item",
"(",
"keys",
",",
"default",
"=",
"\"\"",
")",
":",
"ret",
"=",
"{",
"}",
"key_list",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"keys",
",",
"str",
")",
":",
"key_list",
".",
"append",
"(",
"keys",
")",
"elif",
"isinstance",
"(",
"ke... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/environ.py#L254-L286 | |
iiau-tracker/SPLT | a196e603798e9be969d9d985c087c11cad1cda43 | lib/object_detection/builders/model_builder.py | python | build | (model_config, is_training) | Builds a DetectionModel based on the model config.
Args:
model_config: A model.proto object containing the config for the desired
DetectionModel.
is_training: True if this model is being built for training purposes.
Returns:
DetectionModel based on the config.
Raises:
ValueError: On invalid meta architecture or model. | Builds a DetectionModel based on the model config. | [
"Builds",
"a",
"DetectionModel",
"based",
"on",
"the",
"model",
"config",
"."
] | def build(model_config, is_training):
"""Builds a DetectionModel based on the model config.
Args:
model_config: A model.proto object containing the config for the desired
DetectionModel.
is_training: True if this model is being built for training purposes.
Returns:
DetectionModel based on the config.
Raises:
ValueError: On invalid meta architecture or model.
"""
if not isinstance(model_config, model_pb2.DetectionModel):
raise ValueError('model_config not of type model_pb2.DetectionModel.')
meta_architecture = model_config.WhichOneof('model')
if meta_architecture == 'ssd':
return _build_ssd_model(model_config.ssd, is_training)
if meta_architecture == 'faster_rcnn':
return _build_faster_rcnn_model(model_config.faster_rcnn, is_training)
raise ValueError('Unknown meta architecture: {}'.format(meta_architecture)) | [
"def",
"build",
"(",
"model_config",
",",
"is_training",
")",
":",
"if",
"not",
"isinstance",
"(",
"model_config",
",",
"model_pb2",
".",
"DetectionModel",
")",
":",
"raise",
"ValueError",
"(",
"'model_config not of type model_pb2.DetectionModel.'",
")",
"meta_archite... | https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/builders/model_builder.py#L55-L76 | ||
fonttools/fonttools | 892322aaff6a89bea5927379ec06bc0da3dfb7df | Lib/fontTools/ttLib/tables/E_B_D_T_.py | python | ebdt_bitmap_format_7.compile | (self, ttFont) | return data + self.imageData | [] | def compile(self, ttFont):
data = sstruct.pack(bigGlyphMetricsFormat, self.metrics)
return data + self.imageData | [
"def",
"compile",
"(",
"self",
",",
"ttFont",
")",
":",
"data",
"=",
"sstruct",
".",
"pack",
"(",
"bigGlyphMetricsFormat",
",",
"self",
".",
"metrics",
")",
"return",
"data",
"+",
"self",
".",
"imageData"
] | https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ttLib/tables/E_B_D_T_.py#L657-L659 | |||
p5py/p5 | 4ef1580b26179f1973c1669751da4522c5823f17 | p5/pmath/vector.py | python | Vector.random_2D | (cls) | return vec | Return a random 2D unit vector. | Return a random 2D unit vector. | [
"Return",
"a",
"random",
"2D",
"unit",
"vector",
"."
] | def random_2D(cls):
"""Return a random 2D unit vector.
"""
x, y = 2 * (random(2) - 0.5)
vec = cls(x, y)
vec.normalize()
return vec | [
"def",
"random_2D",
"(",
"cls",
")",
":",
"x",
",",
"y",
"=",
"2",
"*",
"(",
"random",
"(",
"2",
")",
"-",
"0.5",
")",
"vec",
"=",
"cls",
"(",
"x",
",",
"y",
")",
"vec",
".",
"normalize",
"(",
")",
"return",
"vec"
] | https://github.com/p5py/p5/blob/4ef1580b26179f1973c1669751da4522c5823f17/p5/pmath/vector.py#L415-L421 | |
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/sub_collab/common.py | python | Observer.update | (event, producer, data=None) | Single method stub to recieve named events from a producer with an
optional payload of data. | Single method stub to recieve named events from a producer with an
optional payload of data. | [
"Single",
"method",
"stub",
"to",
"recieve",
"named",
"events",
"from",
"a",
"producer",
"with",
"an",
"optional",
"payload",
"of",
"data",
"."
] | def update(event, producer, data=None):
"""
Single method stub to recieve named events from a producer with an
optional payload of data.
""" | [
"def",
"update",
"(",
"event",
",",
"producer",
",",
"data",
"=",
"None",
")",
":"
] | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/sub_collab/common.py#L30-L34 | ||
albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | mac/pyobjc-core/Lib/objc/_properties.py | python | array_proxy.__lt__ | (self, other) | [] | def __lt__(self, other):
if isinstance(other, array_proxy):
return self._wrapped < other._wrapped
else:
return self._wrapped < other | [
"def",
"__lt__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"array_proxy",
")",
":",
"return",
"self",
".",
"_wrapped",
"<",
"other",
".",
"_wrapped",
"else",
":",
"return",
"self",
".",
"_wrapped",
"<",
"other"
] | https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-core/Lib/objc/_properties.py#L510-L515 | ||||
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | int_pointer.assign | (self, *args) | return _idaapi.int_pointer_assign(self, *args) | assign(self, value) | assign(self, value) | [
"assign",
"(",
"self",
"value",
")"
] | def assign(self, *args):
"""
assign(self, value)
"""
return _idaapi.int_pointer_assign(self, *args) | [
"def",
"assign",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"int_pointer_assign",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L2423-L2427 | |
natanielruiz/deep-head-pose | f7bbb9981c2953c2eca67748d6492a64c8243946 | code/datasets.py | python | BIWI.__len__ | (self) | return self.length | [] | def __len__(self):
# 15,667
return self.length | [
"def",
"__len__",
"(",
"self",
")",
":",
"# 15,667",
"return",
"self",
".",
"length"
] | https://github.com/natanielruiz/deep-head-pose/blob/f7bbb9981c2953c2eca67748d6492a64c8243946/code/datasets.py#L566-L568 | |||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/cherrypy/_cpdispatch.py | python | RoutesDispatcher.connect | (self, name, route, controller, **kwargs) | [] | def connect(self, name, route, controller, **kwargs):
self.controllers[name] = controller
self.mapper.connect(name, route, controller=name, **kwargs) | [
"def",
"connect",
"(",
"self",
",",
"name",
",",
"route",
",",
"controller",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"controllers",
"[",
"name",
"]",
"=",
"controller",
"self",
".",
"mapper",
".",
"connect",
"(",
"name",
",",
"route",
",",
... | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/cherrypy/_cpdispatch.py#L516-L518 | ||||
google-research/language | 61fa7260ac7d690d11ef72ca863e45a37c0bdc80 | language/question_answering/bert_joint/run_nq.py | python | get_first_annotation | (e) | return None, -1, (-1, -1) | Returns the first short or long answer in the example.
Args:
e: (dict) annotated example.
Returns:
annotation: (dict) selected annotation
annotated_idx: (int) index of the first annotated candidate.
annotated_sa: (tuple) char offset of the start and end token
of the short answer. The end token is exclusive. | Returns the first short or long answer in the example. | [
"Returns",
"the",
"first",
"short",
"or",
"long",
"answer",
"in",
"the",
"example",
"."
] | def get_first_annotation(e):
"""Returns the first short or long answer in the example.
Args:
e: (dict) annotated example.
Returns:
annotation: (dict) selected annotation
annotated_idx: (int) index of the first annotated candidate.
annotated_sa: (tuple) char offset of the start and end token
of the short answer. The end token is exclusive.
"""
positive_annotations = sorted(
[a for a in e["annotations"] if has_long_answer(a)],
key=lambda a: a["long_answer"]["candidate_index"])
for a in positive_annotations:
if a["short_answers"]:
idx = a["long_answer"]["candidate_index"]
start_token = a["short_answers"][0]["start_token"]
end_token = a["short_answers"][-1]["end_token"]
return a, idx, (token_to_char_offset(e, idx, start_token),
token_to_char_offset(e, idx, end_token) - 1)
for a in positive_annotations:
idx = a["long_answer"]["candidate_index"]
return a, idx, (-1, -1)
return None, -1, (-1, -1) | [
"def",
"get_first_annotation",
"(",
"e",
")",
":",
"positive_annotations",
"=",
"sorted",
"(",
"[",
"a",
"for",
"a",
"in",
"e",
"[",
"\"annotations\"",
"]",
"if",
"has_long_answer",
"(",
"a",
")",
"]",
",",
"key",
"=",
"lambda",
"a",
":",
"a",
"[",
"... | https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/question_answering/bert_joint/run_nq.py#L237-L265 | |
merenlab/anvio | 9b792e2cedc49ecb7c0bed768261595a0d87c012 | anvio/variability.py | python | ProcessIndelCounts.__init__ | (self, indels, coverage, min_indel_fraction=0, test_class=None, min_coverage_for_variability=1) | A class to process raw variability information for a given allele counts array
Creates self.d, a dictionary of equal-length arrays that describes information related to
variability.
Parameters
==========
indels : dictionary
A dictionary that looks like this:
{
6279666787066445523: OrderedDict([
('split_name', 'IGD_000000000532_split_00001'),
('pos', 2),
('pos_in_contig', 2),
('corresponding_gene_call', 25396),
('in_noncoding_gene_call', 0),
('in_coding_gene_call', 1),
('base_pos_in_codon', 3),
('codon_order_in_gene', 0),
('cov_outlier_in_split', 1),
('cov_outlier_in_contig', 1),
('reference', 'T'),
('type', 'INS'),
('sequence', 'CTGACGGCT'),
('length', 9),
('count', 1)
]),
-5035942137885303221: OrderedDict([
('split_name', 'IGD_000000000532_split_00001'),
('pos', 0),
('pos_in_contig', 0),
('corresponding_gene_call', 25396),
('in_noncoding_gene_call', 0),
('in_coding_gene_call', 1),
('base_pos_in_codon', 1),
('codon_order_in_gene', 0),
('cov_outlier_in_split', 1),
('cov_outlier_in_contig', 1),
('reference', 'G'),
('type', 'INS'),
('sequence', 'CTCACGG'),
('length', 7),
('count', 1)
]),
...
}
The keys are unique identifiers. The OrderedDicts should have at least the key `pos`,
but there are no restrictions on what other keys it may have.
coverage : array
What is the coverage for the sequence this is for? This should have length equal to sequence
test_class : VariablityTestFactory, None
If not None, indels will be filtered out if they are deemed not worth reporting
min_coverage_for_variability : int, 1
positions below this coverage value will be filtered out | A class to process raw variability information for a given allele counts array | [
"A",
"class",
"to",
"process",
"raw",
"variability",
"information",
"for",
"a",
"given",
"allele",
"counts",
"array"
] | def __init__(self, indels, coverage, min_indel_fraction=0, test_class=None, min_coverage_for_variability=1):
"""A class to process raw variability information for a given allele counts array
Creates self.d, a dictionary of equal-length arrays that describes information related to
variability.
Parameters
==========
indels : dictionary
A dictionary that looks like this:
{
6279666787066445523: OrderedDict([
('split_name', 'IGD_000000000532_split_00001'),
('pos', 2),
('pos_in_contig', 2),
('corresponding_gene_call', 25396),
('in_noncoding_gene_call', 0),
('in_coding_gene_call', 1),
('base_pos_in_codon', 3),
('codon_order_in_gene', 0),
('cov_outlier_in_split', 1),
('cov_outlier_in_contig', 1),
('reference', 'T'),
('type', 'INS'),
('sequence', 'CTGACGGCT'),
('length', 9),
('count', 1)
]),
-5035942137885303221: OrderedDict([
('split_name', 'IGD_000000000532_split_00001'),
('pos', 0),
('pos_in_contig', 0),
('corresponding_gene_call', 25396),
('in_noncoding_gene_call', 0),
('in_coding_gene_call', 1),
('base_pos_in_codon', 1),
('codon_order_in_gene', 0),
('cov_outlier_in_split', 1),
('cov_outlier_in_contig', 1),
('reference', 'G'),
('type', 'INS'),
('sequence', 'CTCACGG'),
('length', 7),
('count', 1)
]),
...
}
The keys are unique identifiers. The OrderedDicts should have at least the key `pos`,
but there are no restrictions on what other keys it may have.
coverage : array
What is the coverage for the sequence this is for? This should have length equal to sequence
test_class : VariablityTestFactory, None
If not None, indels will be filtered out if they are deemed not worth reporting
min_coverage_for_variability : int, 1
positions below this coverage value will be filtered out
"""
self.indels = indels
self.coverage = coverage
self.test_class = test_class if test_class is not None else VariablityTestFactory(params=None)
self.min_coverage_for_variability = min_coverage_for_variability | [
"def",
"__init__",
"(",
"self",
",",
"indels",
",",
"coverage",
",",
"min_indel_fraction",
"=",
"0",
",",
"test_class",
"=",
"None",
",",
"min_coverage_for_variability",
"=",
"1",
")",
":",
"self",
".",
"indels",
"=",
"indels",
"self",
".",
"coverage",
"="... | https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/variability.py#L362-L427 | ||
whyliam/whyliam.workflows.youdao | 2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c | urllib3/util/ssl_.py | python | _const_compare_digest_backport | (a, b) | return result == 0 | Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise. | Compare two digests of equal length in constant time. | [
"Compare",
"two",
"digests",
"of",
"equal",
"length",
"in",
"constant",
"time",
"."
] | def _const_compare_digest_backport(a, b):
"""
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
"""
result = abs(len(a) - len(b))
for l, r in zip(bytearray(a), bytearray(b)):
result |= l ^ r
return result == 0 | [
"def",
"_const_compare_digest_backport",
"(",
"a",
",",
"b",
")",
":",
"result",
"=",
"abs",
"(",
"len",
"(",
"a",
")",
"-",
"len",
"(",
"b",
")",
")",
"for",
"l",
",",
"r",
"in",
"zip",
"(",
"bytearray",
"(",
"a",
")",
",",
"bytearray",
"(",
"... | https://github.com/whyliam/whyliam.workflows.youdao/blob/2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c/urllib3/util/ssl_.py#L24-L34 | |
aiidateam/aiida-core | c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2 | aiida/orm/implementation/nodes.py | python | BackendNode.description | (self, value: str) | Set the description.
:param value: the new value to set | Set the description. | [
"Set",
"the",
"description",
"."
] | def description(self, value: str) -> None:
"""Set the description.
:param value: the new value to set
""" | [
"def",
"description",
"(",
"self",
",",
"value",
":",
"str",
")",
"->",
"None",
":"
] | https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/implementation/nodes.py#L100-L104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.