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
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
python
Proxy.callRemote
(self, method, *args)
return factory.deferred
Call remote XML-RPC C{method} with given arguments. @return: a L{defer.Deferred} that will fire with the method response, or a failure if the method failed. Generally, the failure type will be L{Fault}, but you can also have an C{IndexError} on some buggy servers giving empty responses. If the deferred is cancelled before the request completes, the connection is closed and the deferred will fire with a L{defer.CancelledError}.
Call remote XML-RPC C{method} with given arguments.
[ "Call", "remote", "XML", "-", "RPC", "C", "{", "method", "}", "with", "given", "arguments", "." ]
def callRemote(self, method, *args): """ Call remote XML-RPC C{method} with given arguments. @return: a L{defer.Deferred} that will fire with the method response, or a failure if the method failed. Generally, the failure type will be L{Fault}, but you can also have an C{IndexError} on some buggy servers giving empty responses. If the deferred is cancelled before the request completes, the connection is closed and the deferred will fire with a L{defer.CancelledError}. """ def cancel(d): factory.deferred = None connector.disconnect() factory = self.queryFactory( self.path, self.host, method, self.user, self.password, self.allowNone, args, cancel, self.useDateTime) if self.secure: from twisted.internet import ssl connector = self._reactor.connectSSL( nativeString(self.host), self.port or 443, factory, ssl.ClientContextFactory(), timeout=self.connectTimeout) else: connector = self._reactor.connectTCP( nativeString(self.host), self.port or 80, factory, timeout=self.connectTimeout) return factory.deferred
[ "def", "callRemote", "(", "self", ",", "method", ",", "*", "args", ")", ":", "def", "cancel", "(", "d", ")", ":", "factory", ".", "deferred", "=", "None", "connector", ".", "disconnect", "(", ")", "factory", "=", "self", ".", "queryFactory", "(", "se...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py#L555-L585
nilearn/nilearn
9edba4471747efacf21260bf470a346307f52706
nilearn/externals/tempita/__init__.py
python
TemplateObjectGetter.__init__
(self, template_obj)
[]
def __init__(self, template_obj): self.__template_obj = template_obj
[ "def", "__init__", "(", "self", ",", "template_obj", ")", ":", "self", ".", "__template_obj", "=", "template_obj" ]
https://github.com/nilearn/nilearn/blob/9edba4471747efacf21260bf470a346307f52706/nilearn/externals/tempita/__init__.py#L611-L612
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
b_cont2_9_d
(name, formals, info, k)
[]
def b_cont2_9_d(name, formals, info, k): if (False if (((list_q(formals)) and (not(association_q(formals)))) is False) else True): GLOBALS['value1_reg'] = trace_lambda_aexp(name, formals, value1_reg, info) GLOBALS['k_reg'] = k GLOBALS['pc'] = apply_cont2 else: GLOBALS['value1_reg'] = mu_trace_lambda_aexp(name, head(formals), last(formals), value1_reg, info) GLOBALS['k_reg'] = k GLOBALS['pc'] = apply_cont2
[ "def", "b_cont2_9_d", "(", "name", ",", "formals", ",", "info", ",", "k", ")", ":", "if", "(", "False", "if", "(", "(", "(", "list_q", "(", "formals", ")", ")", "and", "(", "not", "(", "association_q", "(", "formals", ")", ")", ")", ")", "is", ...
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L2381-L2389
mongodb/mongo-python-driver
c760f900f2e4109a247c2ffc8ad3549362007772
bson/__init__.py
python
_encode_int
(name, value, dummy0, dummy1)
Encode a python int.
Encode a python int.
[ "Encode", "a", "python", "int", "." ]
def _encode_int(name, value, dummy0, dummy1): """Encode a python int.""" if -2147483648 <= value <= 2147483647: return b"\x10" + name + _PACK_INT(value) else: try: return b"\x12" + name + _PACK_LONG(value) except struct.error: raise OverflowError("BSON can only handle up to 8-byte ints")
[ "def", "_encode_int", "(", "name", ",", "value", ",", "dummy0", ",", "dummy1", ")", ":", "if", "-", "2147483648", "<=", "value", "<=", "2147483647", ":", "return", "b\"\\x10\"", "+", "name", "+", "_PACK_INT", "(", "value", ")", "else", ":", "try", ":",...
https://github.com/mongodb/mongo-python-driver/blob/c760f900f2e4109a247c2ffc8ad3549362007772/bson/__init__.py#L640-L648
rpm-software-management/dnf
a96abad2cde8c46f7f36d7774d9d86f2d94715db
dnf/cli/term.py
python
Term.sub_mode
(self, haystack, mode, needles, **kwds)
return self.sub_norm(haystack, self.MODE[mode], needles, **kwds)
Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*. :param haystack: the string to be modified :param mode: the mode to set the matches to be in. Valid values are given by self.MODE.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE[*mode*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles*
Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*.
[ "Search", "the", "string", "*", "haystack", "*", "for", "all", "occurrences", "of", "any", "string", "in", "the", "list", "*", "needles", "*", ".", "Prefix", "each", "occurrence", "with", "self", ".", "MODE", "[", "*", "mode", "*", "]", "and", "postfix...
def sub_mode(self, haystack, mode, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*. :param haystack: the string to be modified :param mode: the mode to set the matches to be in. Valid values are given by self.MODE.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE[*mode*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub_norm(haystack, self.MODE[mode], needles, **kwds)
[ "def", "sub_mode", "(", "self", ",", "haystack", ",", "mode", ",", "needles", ",", "*", "*", "kwds", ")", ":", "return", "self", ".", "sub_norm", "(", "haystack", ",", "self", ".", "MODE", "[", "mode", "]", ",", "needles", ",", "*", "*", "kwds", ...
https://github.com/rpm-software-management/dnf/blob/a96abad2cde8c46f7f36d7774d9d86f2d94715db/dnf/cli/term.py#L313-L331
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/fbbt/interval.py
python
inv
(xl, xu, feasibility_tol)
return lb, ub
The case where xl is very slightly positive but should be very slightly negative (or xu is very slightly negative but should be very slightly positive) should not be an issue. Suppose xu is 2 and xl is 1e-15 but should be -1e-15. The bounds obtained from this function will be [0.5, 1e15] or [0.5, inf), depending on the value of feasibility_tol. The true bounds are (-inf, -1e15] U [0.5, inf), where U is union. The exclusion of (-inf, -1e15] should be acceptable. Additionally, it very important to return a non-negative interval when xl is non-negative.
The case where xl is very slightly positive but should be very slightly negative (or xu is very slightly negative but should be very slightly positive) should not be an issue. Suppose xu is 2 and xl is 1e-15 but should be -1e-15. The bounds obtained from this function will be [0.5, 1e15] or [0.5, inf), depending on the value of feasibility_tol. The true bounds are (-inf, -1e15] U [0.5, inf), where U is union. The exclusion of (-inf, -1e15] should be acceptable. Additionally, it very important to return a non-negative interval when xl is non-negative.
[ "The", "case", "where", "xl", "is", "very", "slightly", "positive", "but", "should", "be", "very", "slightly", "negative", "(", "or", "xu", "is", "very", "slightly", "negative", "but", "should", "be", "very", "slightly", "positive", ")", "should", "not", "...
def inv(xl, xu, feasibility_tol): """ The case where xl is very slightly positive but should be very slightly negative (or xu is very slightly negative but should be very slightly positive) should not be an issue. Suppose xu is 2 and xl is 1e-15 but should be -1e-15. The bounds obtained from this function will be [0.5, 1e15] or [0.5, inf), depending on the value of feasibility_tol. The true bounds are (-inf, -1e15] U [0.5, inf), where U is union. The exclusion of (-inf, -1e15] should be acceptable. Additionally, it very important to return a non-negative interval when xl is non-negative. """ if xu - xl <= -feasibility_tol: raise InfeasibleConstraintException(f'lower bound is greater than upper bound in inv; xl: {xl}; xu: {xu}') elif xu <= 0 <= xl: # This has to return -inf to inf because it could later be multiplied by 0 lb = -inf ub = inf elif xl < 0 < xu: lb = -inf ub = inf elif 0 <= xl <= feasibility_tol: # xu must be strictly positive ub = inf lb = 1.0 / xu elif xl > feasibility_tol: # xl and xu must be strictly positive ub = 1.0 / xl lb = 1.0 / xu elif -feasibility_tol <= xu <= 0: # xl must be strictly negative lb = -inf ub = 1.0 / xl elif xu < -feasibility_tol: # xl and xu must be strictly negative ub = 1.0 / xl lb = 1.0 / xu else: # everything else lb = -inf ub = inf return lb, ub
[ "def", "inv", "(", "xl", ",", "xu", ",", "feasibility_tol", ")", ":", "if", "xu", "-", "xl", "<=", "-", "feasibility_tol", ":", "raise", "InfeasibleConstraintException", "(", "f'lower bound is greater than upper bound in inv; xl: {xl}; xu: {xu}'", ")", "elif", "xu", ...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/fbbt/interval.py#L42-L79
wandb/client
3963364d8112b7dedb928fa423b6878ea1b467d9
wandb/vendor/graphql-core-1.1/graphql/language/parser.py
python
parse_type_system_definition
(parser)
TypeSystemDefinition : - SchemaDefinition - TypeDefinition - TypeExtensionDefinition - DirectiveDefinition TypeDefinition : - ScalarTypeDefinition - ObjectTypeDefinition - InterfaceTypeDefinition - UnionTypeDefinition - EnumTypeDefinition - InputObjectTypeDefinition
TypeSystemDefinition : - SchemaDefinition - TypeDefinition - TypeExtensionDefinition - DirectiveDefinition
[ "TypeSystemDefinition", ":", "-", "SchemaDefinition", "-", "TypeDefinition", "-", "TypeExtensionDefinition", "-", "DirectiveDefinition" ]
def parse_type_system_definition(parser): ''' TypeSystemDefinition : - SchemaDefinition - TypeDefinition - TypeExtensionDefinition - DirectiveDefinition TypeDefinition : - ScalarTypeDefinition - ObjectTypeDefinition - InterfaceTypeDefinition - UnionTypeDefinition - EnumTypeDefinition - InputObjectTypeDefinition ''' if not peek(parser, TokenKind.NAME): raise unexpected(parser) name = parser.token.value if name == 'schema': return parse_schema_definition(parser) elif name == 'scalar': return parse_scalar_type_definition(parser) elif name == 'type': return parse_object_type_definition(parser) elif name == 'interface': return parse_interface_type_definition(parser) elif name == 'union': return parse_union_type_definition(parser) elif name == 'enum': return parse_enum_type_definition(parser) elif name == 'input': return parse_input_object_type_definition(parser) elif name == 'extend': return parse_type_extension_definition(parser) elif name == 'directive': return parse_directive_definition(parser) raise unexpected(parser)
[ "def", "parse_type_system_definition", "(", "parser", ")", ":", "if", "not", "peek", "(", "parser", ",", "TokenKind", ".", "NAME", ")", ":", "raise", "unexpected", "(", "parser", ")", "name", "=", "parser", ".", "token", ".", "value", "if", "name", "==",...
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/vendor/graphql-core-1.1/graphql/language/parser.py#L520-L568
O365/python-o365
7f77005c3cee8177d0141e79b8eda8a7b60c5124
O365/drive.py
python
Drive._classifier
(item)
Subclass to change factory classes
Subclass to change factory classes
[ "Subclass", "to", "change", "factory", "classes" ]
def _classifier(item): """ Subclass to change factory classes """ if 'folder' in item: return Folder elif 'image' in item: return Image elif 'photo' in item: return Photo else: return File
[ "def", "_classifier", "(", "item", ")", ":", "if", "'folder'", "in", "item", ":", "return", "Folder", "elif", "'image'", "in", "item", ":", "return", "Image", "elif", "'photo'", "in", "item", ":", "return", "Photo", "else", ":", "return", "File" ]
https://github.com/O365/python-o365/blob/7f77005c3cee8177d0141e79b8eda8a7b60c5124/O365/drive.py#L1682-L1691
WeblateOrg/weblate
8126f3dda9d24f2846b755955132a8b8410866c8
weblate/legal/pipeline.py
python
tos_confirm
(strategy, backend, user, current_partial, **kwargs)
return None
Force authentication when adding new association.
Force authentication when adding new association.
[ "Force", "authentication", "when", "adding", "new", "association", "." ]
def tos_confirm(strategy, backend, user, current_partial, **kwargs): """Force authentication when adding new association.""" agreement = Agreement.objects.get_or_create(user=user)[0] if not agreement.is_current(): if user: strategy.request.session["tos_user"] = user.pk url = "{}?partial_token={}".format( reverse("social:complete", args=(backend.name,)), current_partial.token ) return redirect( "{}?{}".format(reverse("legal:confirm"), urlencode({"next": url})) ) strategy.request.session.pop("tos_user", None) return None
[ "def", "tos_confirm", "(", "strategy", ",", "backend", ",", "user", ",", "current_partial", ",", "*", "*", "kwargs", ")", ":", "agreement", "=", "Agreement", ".", "objects", ".", "get_or_create", "(", "user", "=", "user", ")", "[", "0", "]", "if", "not...
https://github.com/WeblateOrg/weblate/blob/8126f3dda9d24f2846b755955132a8b8410866c8/weblate/legal/pipeline.py#L29-L42
xmengli/H-DenseUNet
06cc436a43196310fe933d114a353839907cc176
Keras-2.0.8/keras/backend/common.py
python
set_image_data_format
(data_format)
Sets the value of the data format convention. # Arguments data_format: string. `'channels_first'` or `'channels_last'`. # Example ```python >>> from keras import backend as K >>> K.image_data_format() 'channels_first' >>> K.set_image_data_format('channels_last') >>> K.image_data_format() 'channels_last' ```
Sets the value of the data format convention.
[ "Sets", "the", "value", "of", "the", "data", "format", "convention", "." ]
def set_image_data_format(data_format): """Sets the value of the data format convention. # Arguments data_format: string. `'channels_first'` or `'channels_last'`. # Example ```python >>> from keras import backend as K >>> K.image_data_format() 'channels_first' >>> K.set_image_data_format('channels_last') >>> K.image_data_format() 'channels_last' ``` """ global _IMAGE_DATA_FORMAT if data_format not in {'channels_last', 'channels_first'}: raise ValueError('Unknown data_format:', data_format) _IMAGE_DATA_FORMAT = str(data_format)
[ "def", "set_image_data_format", "(", "data_format", ")", ":", "global", "_IMAGE_DATA_FORMAT", "if", "data_format", "not", "in", "{", "'channels_last'", ",", "'channels_first'", "}", ":", "raise", "ValueError", "(", "'Unknown data_format:'", ",", "data_format", ")", ...
https://github.com/xmengli/H-DenseUNet/blob/06cc436a43196310fe933d114a353839907cc176/Keras-2.0.8/keras/backend/common.py#L124-L143
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/database.py
python
DependencyGraph.to_dot
(self, f, skip_disconnected=True)
Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations :type skip_disconnected: ``bool``
Writes a DOT output for the graph to the provided file *f*.
[ "Writes", "a", "DOT", "output", "for", "the", "graph", "to", "the", "provided", "file", "*", "f", "*", "." ]
def to_dot(self, f, skip_disconnected=True): """Writes a DOT output for the graph to the provided file *f*. If *skip_disconnected* is set to ``True``, then all distributions that are not dependent on any other distribution are skipped. :type f: has to support ``file``-like operations :type skip_disconnected: ``bool`` """ disconnected = [] f.write("digraph dependencies {\n") for dist, adjs in self.adjacency_list.items(): if len(adjs) == 0 and not skip_disconnected: disconnected.append(dist) for other, label in adjs: if not label is None: f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, other.name, label)) else: f.write('"%s" -> "%s"\n' % (dist.name, other.name)) if not skip_disconnected and len(disconnected) > 0: f.write('subgraph disconnected {\n') f.write('label = "Disconnected"\n') f.write('bgcolor = red\n') for dist in disconnected: f.write('"%s"' % dist.name) f.write('\n') f.write('}\n') f.write('}\n')
[ "def", "to_dot", "(", "self", ",", "f", ",", "skip_disconnected", "=", "True", ")", ":", "disconnected", "=", "[", "]", "f", ".", "write", "(", "\"digraph dependencies {\\n\"", ")", "for", "dist", ",", "adjs", "in", "self", ".", "adjacency_list", ".", "i...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/database.py#L1127-L1157
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
examples/simple/factories/factory_faker.py
python
SpacelessPostalcodeProvider.postcode_spaceless
(self)
return self.bothify('%###??').upper()
Spaceless postal code.
Spaceless postal code.
[ "Spaceless", "postal", "code", "." ]
def postcode_spaceless(self): """Spaceless postal code.""" return self.bothify('%###??').upper()
[ "def", "postcode_spaceless", "(", "self", ")", ":", "return", "self", ".", "bothify", "(", "'%###??'", ")", ".", "upper", "(", ")" ]
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/examples/simple/factories/factory_faker.py#L29-L31
HackThisSite/CTF-Writeups
d9a63fb11838d9be61953d9dc927b4b5fdf4e50e
2017/Boston Key Party/RSA Buffets/Factorizer.py
python
Factorizer.extended_gcd
(self,aa, bb)
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
Extended Euclidean Algorithm, from https://rosettacode.org/wiki/Modular_inverse#Python
Extended Euclidean Algorithm, from https://rosettacode.org/wiki/Modular_inverse#Python
[ "Extended", "Euclidean", "Algorithm", "from", "https", ":", "//", "rosettacode", ".", "org", "/", "wiki", "/", "Modular_inverse#Python" ]
def extended_gcd(self,aa, bb): """Extended Euclidean Algorithm, from https://rosettacode.org/wiki/Modular_inverse#Python """ lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
[ "def", "extended_gcd", "(", "self", ",", "aa", ",", "bb", ")", ":", "lastremainder", ",", "remainder", "=", "abs", "(", "aa", ")", ",", "abs", "(", "bb", ")", "x", ",", "lastx", ",", "y", ",", "lasty", "=", "0", ",", "1", ",", "1", ",", "0", ...
https://github.com/HackThisSite/CTF-Writeups/blob/d9a63fb11838d9be61953d9dc927b4b5fdf4e50e/2017/Boston Key Party/RSA Buffets/Factorizer.py#L279-L289
bridgecrewio/checkov
f4f8caead6aa2f1824ae1cc88cd1816b12211629
checkov/serverless/parsers/parser.py
python
_load_var_data
( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory )
return value
Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved
Load data based on the type/path (see param_lookup_function parameter of process_variables for more info).
[ "Load", "data", "based", "on", "the", "type", "/", "path", "(", "see", "param_lookup_function", "parameter", "of", "process_variables", "for", "more", "info", ")", "." ]
def _load_var_data( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory ): """ Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved """ value = None if var_type is None: value = var_location elif var_type == "self": value = _determine_variable_value_from_dict(self_data_source, var_location, None) elif var_type == "env": value = _determine_variable_value_from_dict(os.environ, var_location, None) elif var_type.startswith("file("): match = FILE_LOCATION_PATTERN.match(var_type) if match is None: return None data_source = _load_file_data(match[1], file_cache, service_file_directory) value = _determine_variable_value_from_dict(data_source, var_location, None) if value is None and fallback_var_location is not None: return _load_var_data(fallback_var_type, fallback_var_location, None, None, file_cache, self_data_source, service_file_directory) return value
[ "def", "_load_var_data", "(", "var_type", ",", "var_location", ",", "fallback_var_type", ",", "fallback_var_location", ",", "file_cache", ",", "self_data_source", ",", "service_file_directory", ")", ":", "value", "=", "None", "if", "var_type", "is", "None", ":", "...
https://github.com/bridgecrewio/checkov/blob/f4f8caead6aa2f1824ae1cc88cd1816b12211629/checkov/serverless/parsers/parser.py#L182-L218
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp2/trader/position.py
python
BaseCloser.id
(self)
return self._id
[]
def id(self): return self._id
[ "def", "id", "(", "self", ")", ":", "return", "self", ".", "_id" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/trader/position.py#L789-L790
lbryio/lbry-sdk
f78e3825ca0f130834d3876a824f9d380501ced8
lbry/wallet/server/daemon.py
python
LBCDaemon.getclaimbyid
(self, claim_id)
return await self._send_single('getclaimbyid', (claim_id,))
Given a claim id, retrieves claim information.
Given a claim id, retrieves claim information.
[ "Given", "a", "claim", "id", "retrieves", "claim", "information", "." ]
async def getclaimbyid(self, claim_id): '''Given a claim id, retrieves claim information.''' return await self._send_single('getclaimbyid', (claim_id,))
[ "async", "def", "getclaimbyid", "(", "self", ",", "claim_id", ")", ":", "return", "await", "self", ".", "_send_single", "(", "'getclaimbyid'", ",", "(", "claim_id", ",", ")", ")" ]
https://github.com/lbryio/lbry-sdk/blob/f78e3825ca0f130834d3876a824f9d380501ced8/lbry/wallet/server/daemon.py#L338-L340
anchore/anchore
35d45722e6a97fb4172a607e8c7f57810b615119
anchore/util/scripting.py
python
ScriptSetExecutor.check
(self, init_if_missing=False)
Check the path and construct if not found and init_if_missing=True :param init_if_missing: create the path if not found :return: true if exists false if not
Check the path and construct if not found and init_if_missing=True :param init_if_missing: create the path if not found :return: true if exists false if not
[ "Check", "the", "path", "and", "construct", "if", "not", "found", "and", "init_if_missing", "=", "True", ":", "param", "init_if_missing", ":", "create", "the", "path", "if", "not", "found", ":", "return", ":", "true", "if", "exists", "false", "if", "not" ]
def check(self, init_if_missing=False): """ Check the path and construct if not found and init_if_missing=True :param init_if_missing: create the path if not found :return: true if exists false if not """ for d in self.path_overrides + [self.inputdir]: if os.path.exists(d): self.allpaths.append(d) if len(self.allpaths) > 0: return(True) if init_if_missing: os.makedirs(self.inputdir) return True
[ "def", "check", "(", "self", ",", "init_if_missing", "=", "False", ")", ":", "for", "d", "in", "self", ".", "path_overrides", "+", "[", "self", ".", "inputdir", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "self", ".", "a...
https://github.com/anchore/anchore/blob/35d45722e6a97fb4172a607e8c7f57810b615119/anchore/util/scripting.py#L116-L130
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/sgmllib.py
python
SGMLParser.setliteral
(self, *args)
Enter literal mode (CDATA). Intended for derived classes only.
Enter literal mode (CDATA). Intended for derived classes only.
[ "Enter", "literal", "mode", "(", "CDATA", ")", ".", "Intended", "for", "derived", "classes", "only", "." ]
def setliteral(self, *args): """Enter literal mode (CDATA). Intended for derived classes only. """ self.literal = 1
[ "def", "setliteral", "(", "self", ",", "*", "args", ")", ":", "self", ".", "literal", "=", "1" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/sgmllib.py#L57-L62
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/sqlalchemy/sql/compiler.py
python
IdentifierPreparer._requires_quotes
(self, value)
return (lc_value in self.reserved_words or value[0] in self.illegal_initial_characters or not self.legal_characters.match(util.text_type(value)) or (lc_value != value))
Return True if the given identifier requires quoting.
Return True if the given identifier requires quoting.
[ "Return", "True", "if", "the", "given", "identifier", "requires", "quoting", "." ]
def _requires_quotes(self, value): """Return True if the given identifier requires quoting.""" lc_value = value.lower() return (lc_value in self.reserved_words or value[0] in self.illegal_initial_characters or not self.legal_characters.match(util.text_type(value)) or (lc_value != value))
[ "def", "_requires_quotes", "(", "self", ",", "value", ")", ":", "lc_value", "=", "value", ".", "lower", "(", ")", "return", "(", "lc_value", "in", "self", ".", "reserved_words", "or", "value", "[", "0", "]", "in", "self", ".", "illegal_initial_characters",...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/sql/compiler.py#L2882-L2888
frappe/erpnext
9d36e30ef7043b391b5ed2523b8288bf46c45d18
erpnext/regional/report/uae_vat_201/uae_vat_201.py
python
get_tourist_tax_return_tax
(filters)
Returns the sum of the tax of each Sales invoice with non zero tourist_tax_return.
Returns the sum of the tax of each Sales invoice with non zero tourist_tax_return.
[ "Returns", "the", "sum", "of", "the", "tax", "of", "each", "Sales", "invoice", "with", "non", "zero", "tourist_tax_return", "." ]
def get_tourist_tax_return_tax(filters): """Returns the sum of the tax of each Sales invoice with non zero tourist_tax_return.""" query_filters = get_filters(filters) query_filters.append(['tourist_tax_return', '>', 0]) query_filters.append(['docstatus', '=', 1]) try: return frappe.db.get_all('Sales Invoice', filters = query_filters, fields = ['sum(tourist_tax_return)'], as_list=True, limit = 1 )[0][0] or 0 except (IndexError, TypeError): return 0
[ "def", "get_tourist_tax_return_tax", "(", "filters", ")", ":", "query_filters", "=", "get_filters", "(", "filters", ")", "query_filters", ".", "append", "(", "[", "'tourist_tax_return'", ",", "'>'", ",", "0", "]", ")", "query_filters", ".", "append", "(", "[",...
https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/regional/report/uae_vat_201/uae_vat_201.py#L282-L295
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/scattergeo/marker/_colorbar.py
python
ColorBar.ticklen
(self)
return self["ticklen"]
Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf]
[ "Sets", "the", "tick", "length", "(", "in", "px", ")", ".", "The", "ticklen", "property", "is", "a", "number", "and", "may", "be", "specified", "as", ":", "-", "An", "int", "or", "float", "in", "the", "interval", "[", "0", "inf", "]" ]
def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"]
[ "def", "ticklen", "(", "self", ")", ":", "return", "self", "[", "\"ticklen\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scattergeo/marker/_colorbar.py#L928-L939
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_tokenizers_objects.py
python
RetriBertTokenizerFast.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["tokenizers"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"tokenizers\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_tokenizers_objects.py#L321-L322
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
utils/nDynamics.py
python
isNRigid
(nRigid)
return isNType(nRigid,'nRigid')
Check if the specified object is an nRigid node @param nRigid: Object to query @type nRigid: str
Check if the specified object is an nRigid node
[ "Check", "if", "the", "specified", "object", "is", "an", "nRigid", "node" ]
def isNRigid(nRigid): ''' Check if the specified object is an nRigid node @param nRigid: Object to query @type nRigid: str ''' return isNType(nRigid,'nRigid')
[ "def", "isNRigid", "(", "nRigid", ")", ":", "return", "isNType", "(", "nRigid", ",", "'nRigid'", ")" ]
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/utils/nDynamics.py#L77-L83
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hmtk/faults/fault_models.py
python
mtkActiveFault.generate_fault_source_model
(self)
return source_model, model_weight
Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource` model_weight - Corresponding weights for each source model
Creates a resulting `openquake.hmtk` fault source set.
[ "Creates", "a", "resulting", "openquake", ".", "hmtk", "fault", "source", "set", "." ]
def generate_fault_source_model(self): ''' Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource` model_weight - Corresponding weights for each source model ''' source_model = [] model_weight = [] for iloc in range(0, self.get_number_mfd_models()): model_mfd = EvenlyDiscretizedMFD( self.mfd[0][iloc].min_mag, self.mfd[0][iloc].bin_width, self.mfd[0][iloc].occur_rates.tolist()) if isinstance(self.geometry, ComplexFaultGeometry): # Complex fault class source = mtkComplexFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_edges = self.geometry.trace else: # Simple Fault source source = mtkSimpleFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.geometry.dip, self.geometry.upper_depth, self.geometry.lower_depth, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_trace = self.geometry.trace source_model.append(source) model_weight.append(self.mfd[1][iloc]) return source_model, model_weight
[ "def", "generate_fault_source_model", "(", "self", ")", ":", "source_model", "=", "[", "]", "model_weight", "=", "[", "]", "for", "iloc", "in", "range", "(", "0", ",", "self", ".", "get_number_mfd_models", "(", ")", ")", ":", "model_mfd", "=", "EvenlyDiscr...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hmtk/faults/fault_models.py#L512-L560
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
Lib/xml/sax/saxlib.py
python
Attributes.items
(self)
Return a list of (attribute_name, value) pairs.
Return a list of (attribute_name, value) pairs.
[ "Return", "a", "list", "of", "(", "attribute_name", "value", ")", "pairs", "." ]
def items(self): "Return a list of (attribute_name, value) pairs." raise NotImplementedError("This method must be implemented!")
[ "def", "items", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"This method must be implemented!\"", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/Lib/xml/sax/saxlib.py#L132-L134
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/translations/app_translations/download.py
python
get_module_detail_enum_rows
(langs, detail, list_or_detail)
return rows
[]
def get_module_detail_enum_rows(langs, detail, list_or_detail): if not re.search(r'\benum\b', detail.format): return [] rows = [] for mapping in detail.enum: rows.append( ( mapping.key + " (ID Mapping Value)", list_or_detail ) + tuple( mapping.value.get(lang, "") for lang in langs ) ) return rows
[ "def", "get_module_detail_enum_rows", "(", "langs", ",", "detail", ",", "list_or_detail", ")", ":", "if", "not", "re", ".", "search", "(", "r'\\benum\\b'", ",", "detail", ".", "format", ")", ":", "return", "[", "]", "rows", "=", "[", "]", "for", "mapping...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/translations/app_translations/download.py#L286-L301
drckf/paysage
85ef951be2750e13c0b42121b40e530689bdc1f4
paysage/penalties.py
python
Penalty.grad
(self, tensor)
The value of the gradient of the penalty function on a tensor. Args: tensor Returns: tensor
The value of the gradient of the penalty function on a tensor.
[ "The", "value", "of", "the", "gradient", "of", "the", "penalty", "function", "on", "a", "tensor", "." ]
def grad(self, tensor): """ The value of the gradient of the penalty function on a tensor. Args: tensor Returns: tensor """ raise NotImplementedError
[ "def", "grad", "(", "self", ",", "tensor", ")", ":", "raise", "NotImplementedError" ]
https://github.com/drckf/paysage/blob/85ef951be2750e13c0b42121b40e530689bdc1f4/paysage/penalties.py#L41-L52
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/chapters/admin.py
python
ChapterAdmin.save_formset
(self, request, form, formset, change)
Associate the user to each instance saved.
Associate the user to each instance saved.
[ "Associate", "the", "user", "to", "each", "instance", "saved", "." ]
def save_formset(self, request, form, formset, change): """ Associate the user to each instance saved. """ instances = formset.save(commit=False) for instance in instances: instance.content_type = ContentType.objects.get_for_model(instance.chapter) instance.object_id = instance.chapter.pk instance.creator = request.user instance.owner = request.user instance.save()
[ "def", "save_formset", "(", "self", ",", "request", ",", "form", ",", "formset", ",", "change", ")", ":", "instances", "=", "formset", ".", "save", "(", "commit", "=", "False", ")", "for", "instance", "in", "instances", ":", "instance", ".", "content_typ...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/chapters/admin.py#L616-L626
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/ihooks.py
python
Hooks.is_builtin
(self, name)
return imp.is_builtin(name)
[]
def is_builtin(self, name): return imp.is_builtin(name)
[ "def", "is_builtin", "(", "self", ",", "name", ")", ":", "return", "imp", ".", "is_builtin", "(", "name", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/ihooks.py#L164-L164
datawire/forge
d501be4571dcef5691804c7db7008ee877933c8d
forge/docker.py
python
DockerBase.clean
(self, name)
[]
def clean(self, name): for id, bname in self.find_builders(name): Builder(self, id).kill()
[ "def", "clean", "(", "self", ",", "name", ")", ":", "for", "id", ",", "bname", "in", "self", ".", "find_builders", "(", "name", ")", ":", "Builder", "(", "self", ",", "id", ")", ".", "kill", "(", ")" ]
https://github.com/datawire/forge/blob/d501be4571dcef5691804c7db7008ee877933c8d/forge/docker.py#L165-L167
paulgb/runipy
d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe
runipy/notebook_runner.py
python
NotebookRunner.iter_code_cells
(self)
Iterate over the notebook cells containing code.
Iterate over the notebook cells containing code.
[ "Iterate", "over", "the", "notebook", "cells", "containing", "code", "." ]
def iter_code_cells(self): """Iterate over the notebook cells containing code.""" for ws in self.nb.worksheets: for cell in ws.cells: if cell.cell_type == 'code': yield cell
[ "def", "iter_code_cells", "(", "self", ")", ":", "for", "ws", "in", "self", ".", "nb", ".", "worksheets", ":", "for", "cell", "in", "ws", ".", "cells", ":", "if", "cell", ".", "cell_type", "==", "'code'", ":", "yield", "cell" ]
https://github.com/paulgb/runipy/blob/d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe/runipy/notebook_runner.py#L228-L233
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/ipaddress.py
python
IPv6Network.__init__
(self, address, strict=True)
Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied.
Instantiate a new IPv6 Network object.
[ "Instantiate", "a", "new", "IPv6", "Network", "object", "." ]
def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseNetwork.__init__(self, address) # Constructing from a packed address or integer if isinstance(address, (int, bytes)): addr = address mask = self._max_prefixlen # Constructing from a tuple (addr, [mask]) elif isinstance(address, tuple): addr = address[0] mask = address[1] if len(address) > 1 else self._max_prefixlen # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. else: args = _split_optional_netmask(address) addr = self._ip_int_from_string(args[0]) mask = args[1] if len(args) == 2 else self._max_prefixlen self.network_address = IPv6Address(addr) self.netmask, self._prefixlen = self._make_netmask(mask) packed = int(self.network_address) if packed & int(self.netmask) != packed: if strict: raise ValueError('%s has host bits set' % self) else: self.network_address = IPv6Address(packed & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__
[ "def", "__init__", "(", "self", ",", "address", ",", "strict", "=", "True", ")", ":", "_BaseNetwork", ".", "__init__", "(", "self", ",", "address", ")", "# Constructing from a packed address or integer", "if", "isinstance", "(", "address", ",", "(", "int", ","...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/ipaddress.py#L2160-L2220
colour-science/colour
38782ac059e8ddd91939f3432bf06811c16667f0
colour/temperature/ohno2013.py
python
planckian_table
(uv, cmfs, start, end, count)
return table
Returns a planckian table from given *CIE UCS* colourspace *uv* chromaticity coordinates, colour matching functions and temperature range using *Ohno (2013)* method. Parameters ---------- uv : array_like *uv* chromaticity coordinates. cmfs : XYZ_ColourMatchingFunctions Standard observer colour matching functions. start : numeric Temperature range start in kelvins. end : numeric Temperature range end in kelvins. count : int Temperatures count in the planckian table. Returns ------- list Planckian table. Examples -------- >>> from pprint import pprint >>> from colour import MSDS_CMFS, SPECTRAL_SHAPE_DEFAULT >>> cmfs = ( ... MSDS_CMFS['CIE 1931 2 Degree Standard Observer']. ... copy().align(SPECTRAL_SHAPE_DEFAULT) ... ) >>> uv = np.array([0.1978, 0.3122]) >>> pprint(planckian_table(uv, cmfs, 1000, 1010, 10)) ... # doctest: +ELLIPSIS [PlanckianTable_Tuvdi(Ti=1000.0, \ ui=0.4479628..., vi=0.3546296..., di=0.2537355...), PlanckianTable_Tuvdi(Ti=1001.1111111..., \ ui=0.4477030..., vi=0.3546521..., di=0.2534831...), PlanckianTable_Tuvdi(Ti=1002.2222222..., \ ui=0.4474434..., vi=0.3546746..., di=0.2532310...), PlanckianTable_Tuvdi(Ti=1003.3333333..., \ ui=0.4471842..., vi=0.3546970..., di=0.2529792...), PlanckianTable_Tuvdi(Ti=1004.4444444..., \ ui=0.4469252..., vi=0.3547194..., di=0.2527277...), PlanckianTable_Tuvdi(Ti=1005.5555555..., \ ui=0.4466666..., vi=0.3547417..., di=0.2524765...), PlanckianTable_Tuvdi(Ti=1006.6666666..., \ ui=0.4464083..., vi=0.3547640..., di=0.2522256...), PlanckianTable_Tuvdi(Ti=1007.7777777..., \ ui=0.4461502..., vi=0.3547862..., di=0.2519751...), PlanckianTable_Tuvdi(Ti=1008.8888888..., \ ui=0.4458925..., vi=0.3548084..., di=0.2517248...), PlanckianTable_Tuvdi(Ti=1010.0, \ ui=0.4456351..., vi=0.3548306..., di=0.2514749...)]
Returns a planckian table from given *CIE UCS* colourspace *uv* chromaticity coordinates, colour matching functions and temperature range using *Ohno (2013)* method.
[ "Returns", "a", "planckian", "table", "from", "given", "*", "CIE", "UCS", "*", "colourspace", "*", "uv", "*", "chromaticity", "coordinates", "colour", "matching", "functions", "and", "temperature", "range", "using", "*", "Ohno", "(", "2013", ")", "*", "metho...
def planckian_table(uv, cmfs, start, end, count): """ Returns a planckian table from given *CIE UCS* colourspace *uv* chromaticity coordinates, colour matching functions and temperature range using *Ohno (2013)* method. Parameters ---------- uv : array_like *uv* chromaticity coordinates. cmfs : XYZ_ColourMatchingFunctions Standard observer colour matching functions. start : numeric Temperature range start in kelvins. end : numeric Temperature range end in kelvins. count : int Temperatures count in the planckian table. Returns ------- list Planckian table. Examples -------- >>> from pprint import pprint >>> from colour import MSDS_CMFS, SPECTRAL_SHAPE_DEFAULT >>> cmfs = ( ... MSDS_CMFS['CIE 1931 2 Degree Standard Observer']. ... copy().align(SPECTRAL_SHAPE_DEFAULT) ... ) >>> uv = np.array([0.1978, 0.3122]) >>> pprint(planckian_table(uv, cmfs, 1000, 1010, 10)) ... # doctest: +ELLIPSIS [PlanckianTable_Tuvdi(Ti=1000.0, \ ui=0.4479628..., vi=0.3546296..., di=0.2537355...), PlanckianTable_Tuvdi(Ti=1001.1111111..., \ ui=0.4477030..., vi=0.3546521..., di=0.2534831...), PlanckianTable_Tuvdi(Ti=1002.2222222..., \ ui=0.4474434..., vi=0.3546746..., di=0.2532310...), PlanckianTable_Tuvdi(Ti=1003.3333333..., \ ui=0.4471842..., vi=0.3546970..., di=0.2529792...), PlanckianTable_Tuvdi(Ti=1004.4444444..., \ ui=0.4469252..., vi=0.3547194..., di=0.2527277...), PlanckianTable_Tuvdi(Ti=1005.5555555..., \ ui=0.4466666..., vi=0.3547417..., di=0.2524765...), PlanckianTable_Tuvdi(Ti=1006.6666666..., \ ui=0.4464083..., vi=0.3547640..., di=0.2522256...), PlanckianTable_Tuvdi(Ti=1007.7777777..., \ ui=0.4461502..., vi=0.3547862..., di=0.2519751...), PlanckianTable_Tuvdi(Ti=1008.8888888..., \ ui=0.4458925..., vi=0.3548084..., di=0.2517248...), PlanckianTable_Tuvdi(Ti=1010.0, \ ui=0.4456351..., vi=0.3548306..., di=0.2514749...)] """ ux, vx = uv cmfs, _illuminant = handle_spectral_arguments(cmfs) table = [] for Ti in np.linspace(start, end, count): sd = sd_blackbody(Ti, cmfs.shape) XYZ = sd_to_XYZ(sd, cmfs) XYZ /= np.max(XYZ) UVW = XYZ_to_UCS(XYZ) ui, vi = UCS_to_uv(UVW) di = np.hypot(ux - ui, vx - vi) table.append(PLANCKIAN_TABLE_TUVD(Ti, ui, vi, di)) return table
[ "def", "planckian_table", "(", "uv", ",", "cmfs", ",", "start", ",", "end", ",", "count", ")", ":", "ux", ",", "vx", "=", "uv", "cmfs", ",", "_illuminant", "=", "handle_spectral_arguments", "(", "cmfs", ")", "table", "=", "[", "]", "for", "Ti", "in",...
https://github.com/colour-science/colour/blob/38782ac059e8ddd91939f3432bf06811c16667f0/colour/temperature/ohno2013.py#L62-L133
apprenticeharper/DeDRM_tools
776f146ca00d11b24575f4fd6e8202df30a2b7ea
Obok_plugin/action.py
python
InterfacePluginAction.show_help
(self)
Extract on demand the help file resource
Extract on demand the help file resource
[ "Extract", "on", "demand", "the", "help", "file", "resource" ]
def show_help(self): ''' Extract on demand the help file resource ''' def get_help_file_resource(): # We will write the help file out every time, in case the user upgrades the plugin zip # and there is a newer help file contained within it. file_path = os.path.join(config_dir, 'plugins', HELPFILE_NAME) file_data = self.load_resources(HELPFILE_NAME)[HELPFILE_NAME].decode('utf-8') with open(file_path,'w') as f: f.write(file_data) return file_path url = 'file:///' + get_help_file_resource() open_url(QUrl(url))
[ "def", "show_help", "(", "self", ")", ":", "def", "get_help_file_resource", "(", ")", ":", "# We will write the help file out every time, in case the user upgrades the plugin zip", "# and there is a newer help file contained within it.", "file_path", "=", "os", ".", "path", ".", ...
https://github.com/apprenticeharper/DeDRM_tools/blob/776f146ca00d11b24575f4fd6e8202df30a2b7ea/Obok_plugin/action.py#L192-L205
CSAILVision/NetDissect-Lite
2163454ebeb5b15aac64e5cbd4ed8876c5c200df
loader/data_loader.py
python
SegmentationPrefetcher.fetch_tensor_batch
(self, bgr_mean=None, global_labels=False)
return self.form_caffe_tensors(batch, bgr_mean, global_labels)
Iterator for batches as arrays of tensors.
Iterator for batches as arrays of tensors.
[ "Iterator", "for", "batches", "as", "arrays", "of", "tensors", "." ]
def fetch_tensor_batch(self, bgr_mean=None, global_labels=False): '''Iterator for batches as arrays of tensors.''' batch = self.fetch_batch() return self.form_caffe_tensors(batch, bgr_mean, global_labels)
[ "def", "fetch_tensor_batch", "(", "self", ",", "bgr_mean", "=", "None", ",", "global_labels", "=", "False", ")", ":", "batch", "=", "self", ".", "fetch_batch", "(", ")", "return", "self", ".", "form_caffe_tensors", "(", "batch", ",", "bgr_mean", ",", "glob...
https://github.com/CSAILVision/NetDissect-Lite/blob/2163454ebeb5b15aac64e5cbd4ed8876c5c200df/loader/data_loader.py#L533-L536
ialbert/biostar-central
2dc7bd30691a50b2da9c2833ba354056bc686afa
biostar/recipes/models.py
python
Project.json_text
(self)
return hjson.dumps(self.api_data)
[]
def json_text(self): return hjson.dumps(self.api_data)
[ "def", "json_text", "(", "self", ")", ":", "return", "hjson", ".", "dumps", "(", "self", ".", "api_data", ")" ]
https://github.com/ialbert/biostar-central/blob/2dc7bd30691a50b2da9c2833ba354056bc686afa/biostar/recipes/models.py#L215-L216
mckinziebrandon/DeepChatModels
4fef8a6ce00d92235a2fb0e427d2ec60833022d2
chatbot/components/base/_rnn.py
python
BasicRNNCell.__call__
(self, inputs, state, scope=None)
return output, output
Most basic RNN. Define as: output = new_state = act(W * input + U * state + B).
Most basic RNN. Define as: output = new_state = act(W * input + U * state + B).
[ "Most", "basic", "RNN", ".", "Define", "as", ":", "output", "=", "new_state", "=", "act", "(", "W", "*", "input", "+", "U", "*", "state", "+", "B", ")", "." ]
def __call__(self, inputs, state, scope=None): """Most basic RNN. Define as: output = new_state = act(W * input + U * state + B). """ output = tf.tanh(bot_ops.linear_map( args=[inputs, state], output_size=self._num_units, bias=True)) return output, output
[ "def", "__call__", "(", "self", ",", "inputs", ",", "state", ",", "scope", "=", "None", ")", ":", "output", "=", "tf", ".", "tanh", "(", "bot_ops", ".", "linear_map", "(", "args", "=", "[", "inputs", ",", "state", "]", ",", "output_size", "=", "sel...
https://github.com/mckinziebrandon/DeepChatModels/blob/4fef8a6ce00d92235a2fb0e427d2ec60833022d2/chatbot/components/base/_rnn.py#L347-L355
pallets-eco/flask-openid
56824a27046451d7a09d1ed2a861c8bf942ad104
flask_openid.py
python
OpenID.try_login
(self, identity_url, ask_for=None, ask_for_optional=None, extensions=None, immediate=False)
return redirect(auth_request.redirectURL(trust_root, self.get_success_url(), immediate=immediate))
This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` and `ask_for_optional`parameter can be a set of values to be asked from the openid provider, where keys in `ask_for` are marked as required, and keys in `ask_for_optional` are marked as optional. The following strings can be used in the `ask_for` and `ask_for_optional` parameters: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` `extensions` can be a list of instances of OpenID extension requests that should be passed on with the request. If you use this, please make sure to pass the Response classes of these extensions when initializing OpenID. `immediate` can be used to indicate this request should be a so-called checkid_immediate request, resulting in the provider not showing any UI. Note that this adds a new possible response: SetupNeeded, which is the server saying it doesn't have enough information yet to authorized or reject the authentication (probably, the user needs to sign in or approve the trust root).
This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` and `ask_for_optional`parameter can be a set of values to be asked from the openid provider, where keys in `ask_for` are marked as required, and keys in `ask_for_optional` are marked as optional.
[ "This", "tries", "to", "login", "with", "the", "given", "identity", "URL", ".", "This", "function", "must", "be", "called", "from", "the", "login_handler", ".", "The", "ask_for", "and", "ask_for_optional", "parameter", "can", "be", "a", "set", "of", "values"...
def try_login(self, identity_url, ask_for=None, ask_for_optional=None, extensions=None, immediate=False): """This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` and `ask_for_optional`parameter can be a set of values to be asked from the openid provider, where keys in `ask_for` are marked as required, and keys in `ask_for_optional` are marked as optional. The following strings can be used in the `ask_for` and `ask_for_optional` parameters: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` `extensions` can be a list of instances of OpenID extension requests that should be passed on with the request. If you use this, please make sure to pass the Response classes of these extensions when initializing OpenID. `immediate` can be used to indicate this request should be a so-called checkid_immediate request, resulting in the provider not showing any UI. Note that this adds a new possible response: SetupNeeded, which is the server saying it doesn't have enough information yet to authorized or reject the authentication (probably, the user needs to sign in or approve the trust root). """ if ask_for and __debug__: for key in ask_for: if key not in ALL_KEYS: raise ValueError('invalid key %r' % key) if ask_for_optional: for key in ask_for_optional: if key not in ALL_KEYS: raise ValueError('invalid optional key %r' % key) try: consumer = Consumer(SessionWrapper(self), self.store_factory()) auth_request = consumer.begin(identity_url) if ask_for or ask_for_optional: self.attach_reg_info(auth_request, ask_for, ask_for_optional) if extensions: for extension in extensions: auth_request.addExtension(extension) except discover.DiscoveryFailure: self.signal_error('The OpenID was invalid') return redirect(self.get_current_url()) if self.url_root_as_trust_root: trust_root = request.url_root else: trust_root = request.host_url return redirect(auth_request.redirectURL(trust_root, self.get_success_url(), immediate=immediate))
[ "def", "try_login", "(", "self", ",", "identity_url", ",", "ask_for", "=", "None", ",", "ask_for_optional", "=", "None", ",", "extensions", "=", "None", ",", "immediate", "=", "False", ")", ":", "if", "ask_for", "and", "__debug__", ":", "for", "key", "in...
https://github.com/pallets-eco/flask-openid/blob/56824a27046451d7a09d1ed2a861c8bf942ad104/flask_openid.py#L519-L572
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/_backport/sysconfig.py
python
_init_non_posix
(vars)
Initialize the module as appropriate for NT
Initialize the module as appropriate for NT
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "[", "'INCLUDEPY'", "...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/_backport/sysconfig.py#L372-L381
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/handlers.py
python
TimedRotatingFileHandler.doRollover
(self)
do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix.
do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix.
[ "do", "a", "rollover", ";", "in", "this", "case", "a", "date", "/", "time", "stamp", "is", "appended", "to", "the", "filename", "when", "the", "rollover", "happens", ".", "However", "you", "want", "the", "file", "to", "be", "named", "for", "the", "star...
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) os.rename(self.baseFilename, dfn) if self.backupCount > 0: # find the oldest log file and delete it #s = glob.glob(self.baseFilename + ".20*") #if len(s) > self.backupCount: # s.sort() # os.remove(s[0]) for s in self.getFilesToDelete(): os.remove(s) #print "%s -> %s" % (self.baseFilename, dfn) self.mode = 'w' self.stream = self._open() currentTime = int(time.time()) newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstNow = time.localtime(currentTime)[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour newRolloverAt = newRolloverAt - 3600 else: # DST bows out before next rollover, so we need to add an hour newRolloverAt = newRolloverAt + 3600 self.rolloverAt = newRolloverAt
[ "def", "doRollover", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "self", ".", "stream", ".", "close", "(", ")", "self", ".", "stream", "=", "None", "# get the time that this sequence started at and make it a TimeTuple", "t", "=", "self", ".", "rol...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/handlers.py#L318-L363
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/networkx/classes/multigraph.py
python
MultiGraph.remove_edges_from
(self, ebunch)
Remove all edges specified in ebunch. Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be: - 2-tuples (u, v) All edges between u and v are removed. - 3-tuples (u, v, key) The edge identified by key is removed. - 4-tuples (u, v, key, data) where data is ignored. See Also -------- remove_edge : remove a single edge Notes ----- Will fail silently if an edge in ebunch is not in the graph. Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch=[(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch) Removing multiple copies of edges >>> G = nx.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (1, 2)]) >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph []
Remove all edges specified in ebunch.
[ "Remove", "all", "edges", "specified", "in", "ebunch", "." ]
def remove_edges_from(self, ebunch): """Remove all edges specified in ebunch. Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be: - 2-tuples (u, v) All edges between u and v are removed. - 3-tuples (u, v, key) The edge identified by key is removed. - 4-tuples (u, v, key, data) where data is ignored. See Also -------- remove_edge : remove a single edge Notes ----- Will fail silently if an edge in ebunch is not in the graph. Examples -------- >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch=[(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch) Removing multiple copies of edges >>> G = nx.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (1, 2)]) >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph [] """ for e in ebunch: try: self.remove_edge(*e[:3]) except NetworkXError: pass
[ "def", "remove_edges_from", "(", "self", ",", "ebunch", ")", ":", "for", "e", "in", "ebunch", ":", "try", ":", "self", ".", "remove_edge", "(", "*", "e", "[", ":", "3", "]", ")", "except", "NetworkXError", ":", "pass" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/networkx/classes/multigraph.py#L608-L650
selfteaching/selfteaching-python-camp
9982ee964b984595e7d664b07c389cddaf158f1e
19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/pyparsing.py
python
ParserElement.__rsub__
(self, other )
return other - self
Implementation of - operator when left operand is not a :class:`ParserElement`
Implementation of - operator when left operand is not a :class:`ParserElement`
[ "Implementation", "of", "-", "operator", "when", "left", "operand", "is", "not", "a", ":", "class", ":", "ParserElement" ]
def __rsub__(self, other ): """ Implementation of - operator when left operand is not a :class:`ParserElement` """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other - self
[ "def", "__rsub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElemen...
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/pyparsing.py#L2038-L2048
ydkhatri/mac_apt
729630c8bbe7a73cce3ca330305d3301a919cb07
plugins/helpers/common.py
python
CommonFunctions.GetTableNames
(db_conn)
return ''
Retrieve all table names in an sqlite database
Retrieve all table names in an sqlite database
[ "Retrieve", "all", "table", "names", "in", "an", "sqlite", "database" ]
def GetTableNames(db_conn): '''Retrieve all table names in an sqlite database''' try: cursor = db_conn.execute("SELECT group_concat(name) from sqlite_master WHERE type='table'") for row in cursor: return row[0] except sqlite3Error as ex: log.error ("Failed to list tables on db. Error Details: {}".format(str(ex))) return ''
[ "def", "GetTableNames", "(", "db_conn", ")", ":", "try", ":", "cursor", "=", "db_conn", ".", "execute", "(", "\"SELECT group_concat(name) from sqlite_master WHERE type='table'\"", ")", "for", "row", "in", "cursor", ":", "return", "row", "[", "0", "]", "except", ...
https://github.com/ydkhatri/mac_apt/blob/729630c8bbe7a73cce3ca330305d3301a919cb07/plugins/helpers/common.py#L206-L214
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/mutagen/monkeysaudio.py
python
MonkeysAudioInfo.__init__
(self, fileobj)
Raises MonkeysAudioHeaderError
Raises MonkeysAudioHeaderError
[ "Raises", "MonkeysAudioHeaderError" ]
def __init__(self, fileobj): """Raises MonkeysAudioHeaderError""" header = fileobj.read(76) if len(header) != 76 or not header.startswith(b"MAC "): raise MonkeysAudioHeaderError("not a Monkey's Audio file") self.version = cdata.ushort_le(header[4:6]) if self.version >= 3980: (blocks_per_frame, final_frame_blocks, total_frames, self.bits_per_sample, self.channels, self.sample_rate) = struct.unpack("<IIIHHI", header[56:76]) else: compression_level = cdata.ushort_le(header[6:8]) self.channels, self.sample_rate = struct.unpack( "<HI", header[10:16]) total_frames, final_frame_blocks = struct.unpack( "<II", header[24:32]) if self.version >= 3950: blocks_per_frame = 73728 * 4 elif self.version >= 3900 or (self.version >= 3800 and compression_level == 4): blocks_per_frame = 73728 else: blocks_per_frame = 9216 self.version /= 1000.0 self.length = 0.0 if (self.sample_rate != 0) and (total_frames > 0): total_blocks = ((total_frames - 1) * blocks_per_frame + final_frame_blocks) self.length = float(total_blocks) / self.sample_rate
[ "def", "__init__", "(", "self", ",", "fileobj", ")", ":", "header", "=", "fileobj", ".", "read", "(", "76", ")", "if", "len", "(", "header", ")", "!=", "76", "or", "not", "header", ".", "startswith", "(", "b\"MAC \"", ")", ":", "raise", "MonkeysAudio...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mutagen/monkeysaudio.py#L45-L74
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/pyparsing/helpers.py
python
replace_html_entity
(t)
return _htmlEntityMap.get(t.entity)
Helper parser action to replace common HTML entities with their special characters
Helper parser action to replace common HTML entities with their special characters
[ "Helper", "parser", "action", "to", "replace", "common", "HTML", "entities", "with", "their", "special", "characters" ]
def replace_html_entity(t): """Helper parser action to replace common HTML entities with their special characters""" return _htmlEntityMap.get(t.entity)
[ "def", "replace_html_entity", "(", "t", ")", ":", "return", "_htmlEntityMap", ".", "get", "(", "t", ".", "entity", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/pyparsing/helpers.py#L683-L685
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py
python
create_cookie
(name, value, **kwargs)
return cookielib.Cookie(**result)
Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie").
Make a cookie from underspecified parameters.
[ "Make", "a", "cookie", "from", "underspecified", "parameters", "." ]
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result)
[ "def", "create_cookie", "(", "name", ",", "value", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "'version'", ":", "0", ",", "'name'", ":", "name", ",", "'value'", ":", "value", ",", "'port'", ":", "None", ",", "'domain'", ":", "''", ",", ...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py#L441-L474
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/lib/deploymentconfig.py
python
DeploymentConfig.delete_env_var
(self, keys)
return False
delete a list of keys
delete a list of keys
[ "delete", "a", "list", "of", "keys" ]
def delete_env_var(self, keys): '''delete a list of keys ''' if not isinstance(keys, list): keys = [keys] env_vars_array = self.get_env_vars() modified = False idx = None for key in keys: for env_idx, env_var in enumerate(env_vars_array): if env_var['name'] == key: idx = env_idx break if idx: modified = True del env_vars_array[idx] if modified: return True return False
[ "def", "delete_env_var", "(", "self", ",", "keys", ")", ":", "if", "not", "isinstance", "(", "keys", ",", "list", ")", ":", "keys", "=", "[", "keys", "]", "env_vars_array", "=", "self", ".", "get_env_vars", "(", ")", "modified", "=", "False", "idx", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/lib/deploymentconfig.py#L128-L149
MeanEYE/Sunflower
1024bbdde3b8e202ddad3553b321a7b6230bffc9
sunflower/plugins/file_list/file_list.py
python
FileList._clear_sort_function
(self)
Clear sort settings
Clear sort settings
[ "Clear", "sort", "settings" ]
def _clear_sort_function(self): """Clear sort settings""" self._store.set_sort_column_id(Gtk.TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, True)
[ "def", "_clear_sort_function", "(", "self", ")", ":", "self", ".", "_store", ".", "set_sort_column_id", "(", "Gtk", ".", "TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID", ",", "True", ")" ]
https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/plugins/file_list/file_list.py#L1185-L1187
twiddli/happypanda
6acf2560404cb23385c7c0a3c07797035301ad75
version/gallerydb.py
python
default_chap_exec
(gallery_or_id, chap, only_values=False)
return execute
Pass a Gallery object or gallery id and a Chapter object
Pass a Gallery object or gallery id and a Chapter object
[ "Pass", "a", "Gallery", "object", "or", "gallery", "id", "and", "a", "Chapter", "object" ]
def default_chap_exec(gallery_or_id, chap, only_values=False): "Pass a Gallery object or gallery id and a Chapter object" if isinstance(gallery_or_id, Gallery): gid = gallery_or_id.id in_archive = gallery_or_id.is_archive else: gid = gallery_or_id in_archive = chap.in_archive if only_values: execute = (gid, chap.title, chap.number, str.encode(chap.path), chap.pages, in_archive) else: execute = (""" INSERT INTO chapters(series_id, chapter_title, chapter_number, chapter_path, pages, in_archive) VALUES(:series_id, :chapter_title, :chapter_number, :chapter_path, :pages, :in_archive)""", {'series_id':gid, 'chapter_title':chap.title, 'chapter_number':chap.number, 'chapter_path':str.encode(chap.path), 'pages':chap.pages, 'in_archive':in_archive}) return execute
[ "def", "default_chap_exec", "(", "gallery_or_id", ",", "chap", ",", "only_values", "=", "False", ")", ":", "if", "isinstance", "(", "gallery_or_id", ",", "Gallery", ")", ":", "gid", "=", "gallery_or_id", ".", "id", "in_archive", "=", "gallery_or_id", ".", "i...
https://github.com/twiddli/happypanda/blob/6acf2560404cb23385c7c0a3c07797035301ad75/version/gallerydb.py#L175-L196
matthiask/plata
a743b8ef3838c1c2764620b18c394afc9708c4d5
plata/shop/views.py
python
Shop.render_confirmation
(self, request, context)
return self.render( request, self.confirmation_template, self.get_context(request, context) )
Renders the confirmation page
Renders the confirmation page
[ "Renders", "the", "confirmation", "page" ]
def render_confirmation(self, request, context): """Renders the confirmation page""" return self.render( request, self.confirmation_template, self.get_context(request, context) )
[ "def", "render_confirmation", "(", "self", ",", "request", ",", "context", ")", ":", "return", "self", ".", "render", "(", "request", ",", "self", ".", "confirmation_template", ",", "self", ".", "get_context", "(", "request", ",", "context", ")", ")" ]
https://github.com/matthiask/plata/blob/a743b8ef3838c1c2764620b18c394afc9708c4d5/plata/shop/views.py#L641-L645
asappresearch/flambe
98f10f859fe9223fd2d1d76d430f77cdbddc0956
flambe/experiment/utils.py
python
local_has_gpu
()
return torch.cuda.is_available()
Returns is local process has GPU Returns ------- bool
Returns is local process has GPU
[ "Returns", "is", "local", "process", "has", "GPU" ]
def local_has_gpu() -> bool: """Returns is local process has GPU Returns ------- bool """ return torch.cuda.is_available()
[ "def", "local_has_gpu", "(", ")", "->", "bool", ":", "return", "torch", ".", "cuda", ".", "is_available", "(", ")" ]
https://github.com/asappresearch/flambe/blob/98f10f859fe9223fd2d1d76d430f77cdbddc0956/flambe/experiment/utils.py#L491-L499
yandex/yandex-tank
b41bcc04396c4ed46fc8b28a261197320854fd33
yandextank/plugins/Phantom/reader.py
python
PhantomStatsReader._format_chunk
(self, chunk)
return list(itt.chain(*(self._decode_stat_data(chunk) for chunk in chunks)))
[]
def _format_chunk(self, chunk): chunks = [json.loads('{%s}}' % s) for s in chunk.split('\n},')] return list(itt.chain(*(self._decode_stat_data(chunk) for chunk in chunks)))
[ "def", "_format_chunk", "(", "self", ",", "chunk", ")", ":", "chunks", "=", "[", "json", ".", "loads", "(", "'{%s}}'", "%", "s", ")", "for", "s", "in", "chunk", ".", "split", "(", "'\\n},'", ")", "]", "return", "list", "(", "itt", ".", "chain", "...
https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/plugins/Phantom/reader.py#L145-L147
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/process.py
python
SSHProcess.set_writer
(self, writer: Optional[_WriterProtocol[AnyStr]], datatype: DataType)
Set a writer used to forward data from the channel
Set a writer used to forward data from the channel
[ "Set", "a", "writer", "used", "to", "forward", "data", "from", "the", "channel" ]
def set_writer(self, writer: Optional[_WriterProtocol[AnyStr]], datatype: DataType) -> None: """Set a writer used to forward data from the channel""" old_writer = self._writers.get(datatype) if old_writer: old_writer.close() self.clear_writer(datatype) if writer: self._writers[datatype] = writer
[ "def", "set_writer", "(", "self", ",", "writer", ":", "Optional", "[", "_WriterProtocol", "[", "AnyStr", "]", "]", ",", "datatype", ":", "DataType", ")", "->", "None", ":", "old_writer", "=", "self", ".", "_writers", ".", "get", "(", "datatype", ")", "...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/process.py#L1007-L1018
quip/quip-api
19f3b32a05ed092a70dc2c616e214aaff8a06de2
samples/wordpress/quip.py
python
QuipClient.add_thread_members
(self, thread_id, member_ids)
return self._fetch_json("threads/add-members", post_data={ "thread_id": thread_id, "member_ids": ",".join(member_ids), })
Adds the given folder or user IDs to the given thread.
Adds the given folder or user IDs to the given thread.
[ "Adds", "the", "given", "folder", "or", "user", "IDs", "to", "the", "given", "thread", "." ]
def add_thread_members(self, thread_id, member_ids): """Adds the given folder or user IDs to the given thread.""" return self._fetch_json("threads/add-members", post_data={ "thread_id": thread_id, "member_ids": ",".join(member_ids), })
[ "def", "add_thread_members", "(", "self", ",", "thread_id", ",", "member_ids", ")", ":", "return", "self", ".", "_fetch_json", "(", "\"threads/add-members\"", ",", "post_data", "=", "{", "\"thread_id\"", ":", "thread_id", ",", "\"member_ids\"", ":", "\",\"", "."...
https://github.com/quip/quip-api/blob/19f3b32a05ed092a70dc2c616e214aaff8a06de2/samples/wordpress/quip.py#L268-L273
guofei9987/scikit-opt
e0886ed3aa3bc9023d1408816c32125d2b90c76c
sko/demo_func.py
python
griewank
(p)
return np.sum(part1) - np.prod(part2) + 1
存在多个局部最小值点,数目与问题的维度有关。 此函数是典型的非线性多模态函数,具有广泛的搜索空间,是优化算法很难处理的复杂多模态问题。 在(0,...,0)处取的全局最小值0 -600<=xi<=600
存在多个局部最小值点,数目与问题的维度有关。 此函数是典型的非线性多模态函数,具有广泛的搜索空间,是优化算法很难处理的复杂多模态问题。 在(0,...,0)处取的全局最小值0 -600<=xi<=600
[ "存在多个局部最小值点,数目与问题的维度有关。", "此函数是典型的非线性多模态函数,具有广泛的搜索空间,是优化算法很难处理的复杂多模态问题。", "在", "(", "0", "...", "0", ")", "处取的全局最小值0", "-", "600<", "=", "xi<", "=", "600" ]
def griewank(p): ''' 存在多个局部最小值点,数目与问题的维度有关。 此函数是典型的非线性多模态函数,具有广泛的搜索空间,是优化算法很难处理的复杂多模态问题。 在(0,...,0)处取的全局最小值0 -600<=xi<=600 ''' part1 = [np.square(x) / 4000 for x in p] part2 = [np.cos(x / np.sqrt(i + 1)) for i, x in enumerate(p)] return np.sum(part1) - np.prod(part2) + 1
[ "def", "griewank", "(", "p", ")", ":", "part1", "=", "[", "np", ".", "square", "(", "x", ")", "/", "4000", "for", "x", "in", "p", "]", "part2", "=", "[", "np", ".", "cos", "(", "x", "/", "np", ".", "sqrt", "(", "i", "+", "1", ")", ")", ...
https://github.com/guofei9987/scikit-opt/blob/e0886ed3aa3bc9023d1408816c32125d2b90c76c/sko/demo_func.py#L59-L68
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/integrals/manualintegrate.py
python
tansec_pattern
(symbol)
return pattern, a, b, m, n
[]
def tansec_pattern(symbol): a, b, m, n = make_wilds(symbol) pattern = sympy.tan(a*symbol)**m * sympy.sec(b*symbol)**n return pattern, a, b, m, n
[ "def", "tansec_pattern", "(", "symbol", ")", ":", "a", ",", "b", ",", "m", ",", "n", "=", "make_wilds", "(", "symbol", ")", "pattern", "=", "sympy", ".", "tan", "(", "a", "*", "symbol", ")", "**", "m", "*", "sympy", ".", "sec", "(", "b", "*", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/integrals/manualintegrate.py#L538-L542
theislab/scanpy
b69015e9e7007193c9ac461d5c6fbf845b3d6962
scanpy/tools/_paga.py
python
paga_compare_paths
( adata1: AnnData, adata2: AnnData, adjacency_key: str = 'connectivities', adjacency_key2: Optional[str] = None, )
return PAGAComparePathsResult( frac_steps=n_agreeing_steps / n_steps if n_steps > 0 else np.nan, n_steps=n_steps if n_steps > 0 else np.nan, frac_paths=n_agreeing_paths / n_paths if n_steps > 0 else np.nan, n_paths=n_paths if n_steps > 0 else np.nan, )
Compare paths in abstracted graphs in two datasets. Compute the fraction of consistent paths between leafs, a measure for the topological similarity between graphs. By increasing the verbosity to level 4 and 5, the paths that do not agree and the paths that agree are written to the output, respectively. The PAGA "groups key" needs to be the same in both objects. Parameters ---------- adata1, adata2 Annotated data matrices to compare. adjacency_key Key for indexing the adjacency matrices in `.uns['paga']` to be used in adata1 and adata2. adjacency_key2 If provided, used for adata2. Returns ------- NamedTuple with attributes frac_steps fraction of consistent steps n_steps total number of steps in paths frac_paths Fraction of consistent paths n_paths Number of paths
Compare paths in abstracted graphs in two datasets.
[ "Compare", "paths", "in", "abstracted", "graphs", "in", "two", "datasets", "." ]
def paga_compare_paths( adata1: AnnData, adata2: AnnData, adjacency_key: str = 'connectivities', adjacency_key2: Optional[str] = None, ) -> PAGAComparePathsResult: """Compare paths in abstracted graphs in two datasets. Compute the fraction of consistent paths between leafs, a measure for the topological similarity between graphs. By increasing the verbosity to level 4 and 5, the paths that do not agree and the paths that agree are written to the output, respectively. The PAGA "groups key" needs to be the same in both objects. Parameters ---------- adata1, adata2 Annotated data matrices to compare. adjacency_key Key for indexing the adjacency matrices in `.uns['paga']` to be used in adata1 and adata2. adjacency_key2 If provided, used for adata2. Returns ------- NamedTuple with attributes frac_steps fraction of consistent steps n_steps total number of steps in paths frac_paths Fraction of consistent paths n_paths Number of paths """ import networkx as nx g1 = nx.Graph(adata1.uns['paga'][adjacency_key]) g2 = nx.Graph( adata2.uns['paga'][ adjacency_key2 if adjacency_key2 is not None else adjacency_key ] ) leaf_nodes1 = [str(x) for x in g1.nodes() if g1.degree(x) == 1] logg.debug(f'leaf nodes in graph 1: {leaf_nodes1}') paga_groups = adata1.uns['paga']['groups'] asso_groups1 = _utils.identify_groups( adata1.obs[paga_groups].values, adata2.obs[paga_groups].values, ) asso_groups2 = _utils.identify_groups( adata2.obs[paga_groups].values, adata1.obs[paga_groups].values, ) orig_names1 = adata1.obs[paga_groups].cat.categories orig_names2 = adata2.obs[paga_groups].cat.categories import itertools n_steps = 0 n_agreeing_steps = 0 n_paths = 0 n_agreeing_paths = 0 # loop over all pairs of leaf nodes in the reference adata1 for (r, s) in itertools.combinations(leaf_nodes1, r=2): r2, s2 = asso_groups1[r][0], asso_groups1[s][0] on1_g1, on2_g1 = [orig_names1[int(i)] for i in [r, s]] on1_g2, on2_g2 = [orig_names2[int(i)] for i in [r2, s2]] logg.debug( f'compare shortest paths between leafs ({on1_g1}, {on2_g1}) ' f'in graph1 and ({on1_g2}, {on2_g2}) in graph2:' ) try: path1 = [str(x) for x in nx.shortest_path(g1, int(r), int(s))] except nx.NetworkXNoPath: path1 = None try: path2 = [str(x) for x in nx.shortest_path(g2, int(r2), int(s2))] except nx.NetworkXNoPath: path2 = None if path1 is None and path2 is None: # consistent behavior n_paths += 1 n_agreeing_paths += 1 n_steps += 1 n_agreeing_steps += 1 logg.debug('there are no connecting paths in both graphs') continue elif path1 is None or path2 is None: # non-consistent result n_paths += 1 n_steps += 1 continue if len(path1) >= len(path2): path_mapped = [asso_groups1[l] for l in path1] path_compare = path2 path_compare_id = 2 path_compare_orig_names = [ [orig_names2[int(s)] for s in l] for l in path_compare ] path_mapped_orig_names = [ [orig_names2[int(s)] for s in l] for l in path_mapped ] else: path_mapped = [asso_groups2[l] for l in path2] path_compare = path1 path_compare_id = 1 path_compare_orig_names = [ [orig_names1[int(s)] for s in l] for l in path_compare ] path_mapped_orig_names = [ [orig_names1[int(s)] for s in l] for l in path_mapped ] n_agreeing_steps_path = 0 ip_progress = 0 for il, l in enumerate(path_compare[:-1]): for ip, p in enumerate(path_mapped): if ( ip < ip_progress or l not in p or not ( ip + 1 < len(path_mapped) and path_compare[il + 1] in path_mapped[ip + 1] ) ): continue # make sure that a step backward leads us to the same value of l # in case we "jumped" logg.debug( f'found matching step ({l} -> {path_compare_orig_names[il + 1]}) ' f'at position {il} in path{path_compare_id} and position {ip} in path_mapped' ) consistent_history = True for iip in range(ip, ip_progress, -1): if l not in path_mapped[iip - 1]: consistent_history = False if consistent_history: # here, we take one step further back (ip_progress - 1); it's implied that this # was ok in the previous step poss = list(range(ip - 1, ip_progress - 2, -1)) logg.debug( f' step(s) backward to position(s) {poss} ' 'in path_mapped are fine, too: valid step' ) n_agreeing_steps_path += 1 ip_progress = ip + 1 break n_steps_path = len(path_compare) - 1 n_agreeing_steps += n_agreeing_steps_path n_steps += n_steps_path n_paths += 1 if n_agreeing_steps_path == n_steps_path: n_agreeing_paths += 1 # only for the output, use original names path1_orig_names = [orig_names1[int(s)] for s in path1] path2_orig_names = [orig_names2[int(s)] for s in path2] logg.debug( f' path1 = {path1_orig_names},\n' f'path_mapped = {[list(p) for p in path_mapped_orig_names]},\n' f' path2 = {path2_orig_names},\n' f'-> n_agreeing_steps = {n_agreeing_steps_path} / n_steps = {n_steps_path}.', ) return PAGAComparePathsResult( frac_steps=n_agreeing_steps / n_steps if n_steps > 0 else np.nan, n_steps=n_steps if n_steps > 0 else np.nan, frac_paths=n_agreeing_paths / n_paths if n_steps > 0 else np.nan, n_paths=n_paths if n_steps > 0 else np.nan, )
[ "def", "paga_compare_paths", "(", "adata1", ":", "AnnData", ",", "adata2", ":", "AnnData", ",", "adjacency_key", ":", "str", "=", "'connectivities'", ",", "adjacency_key2", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "PAGAComparePathsResult"...
https://github.com/theislab/scanpy/blob/b69015e9e7007193c9ac461d5c6fbf845b3d6962/scanpy/tools/_paga.py#L438-L610
reddit-archive/reddit
753b17407e9a9dca09558526805922de24133d53
r2/r2/lib/traffic/traffic.py
python
_report_interval
(interval)
Read aggregated traffic from S3 and write to postgres.
Read aggregated traffic from S3 and write to postgres.
[ "Read", "aggregated", "traffic", "from", "S3", "and", "write", "to", "postgres", "." ]
def _report_interval(interval): """Read aggregated traffic from S3 and write to postgres.""" from sqlalchemy.orm import scoped_session, sessionmaker from r2.models.traffic import engine Session = scoped_session(sessionmaker(bind=engine)) # determine interval_type from YYYY-MM[-DD][-HH] pieces = interval.split('-') pieces = [int(i) for i in pieces] if len(pieces) == 4: interval_type = 'hour' elif len(pieces) == 3: interval_type = 'day' pieces.append(0) elif len(pieces) == 2: interval_type = 'month' pieces.append(1) pieces.append(0) else: raise pg_interval = "%04d-%02d-%02d %02d:00:00" % tuple(pieces) print 'reporting interval %s (%s)' % (pg_interval, interval_type) # Read aggregates and write to traffic db for category_cls in traffic_categories: now = datetime.datetime.now() print '*** %s - %s - %s' % (category_cls.__name__, interval, now) data = get_aggregate(interval, category_cls) len_data = len(data) step = max(len_data / 5, 100) for i, (name, (uniques, pageviews)) in enumerate(data.iteritems()): try: for n in tup(name): unicode(n) except UnicodeDecodeError: print '%s - %s - %s - %s' % (category_cls.__name__, name, uniques, pageviews) continue if i % step == 0: now = datetime.datetime.now() print '%s - %s - %s/%s - %s' % (interval, category_cls.__name__, i, len_data, now) kw = {'date': pg_interval, 'interval': interval_type, 'unique_count': uniques, 'pageview_count': pageviews} kw.update(_name_to_kw(category_cls, name)) r = category_cls(**kw) try: Session.merge(r) Session.commit() except DataError: Session.rollback() continue Session.remove() now = datetime.datetime.now() print 'finished reporting %s (%s) - %s' % (pg_interval, interval_type, now)
[ "def", "_report_interval", "(", "interval", ")", ":", "from", "sqlalchemy", ".", "orm", "import", "scoped_session", ",", "sessionmaker", "from", "r2", ".", "models", ".", "traffic", "import", "engine", "Session", "=", "scoped_session", "(", "sessionmaker", "(", ...
https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/lib/traffic/traffic.py#L170-L229
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/asyncio/selector_events.py
python
BaseSelectorEventLoop._add_reader
(self, fd, callback, *args)
[]
def _add_reader(self, fd, callback, *args): self._check_closed() handle = events.Handle(callback, args, self, None) try: key = self._selector.get_key(fd) except KeyError: self._selector.register(fd, selectors.EVENT_READ, (handle, None)) else: mask, (reader, writer) = key.events, key.data self._selector.modify(fd, mask | selectors.EVENT_READ, (handle, writer)) if reader is not None: reader.cancel()
[ "def", "_add_reader", "(", "self", ",", "fd", ",", "callback", ",", "*", "args", ")", ":", "self", ".", "_check_closed", "(", ")", "handle", "=", "events", ".", "Handle", "(", "callback", ",", "args", ",", "self", ",", "None", ")", "try", ":", "key...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/asyncio/selector_events.py#L255-L268
Pylons/webob
259230aa2b8b9cf675c996e157c5cf021c256059
src/webob/request.py
python
BaseRequest._json_body__get
(self)
return json.loads(self.body.decode(self.charset))
Access the body of the request as JSON
Access the body of the request as JSON
[ "Access", "the", "body", "of", "the", "request", "as", "JSON" ]
def _json_body__get(self): """Access the body of the request as JSON""" return json.loads(self.body.decode(self.charset))
[ "def", "_json_body__get", "(", "self", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "body", ".", "decode", "(", "self", ".", "charset", ")", ")" ]
https://github.com/Pylons/webob/blob/259230aa2b8b9cf675c996e157c5cf021c256059/src/webob/request.py#L730-L733
naver/sqlova
fc68af6008fd2fd5839210e4b06a352007f609b6
bert/convert_tf_checkpoint_to_pytorch.py
python
convert
()
[]
def convert(): # Initialise PyTorch model config = BertConfig.from_json_file(args.bert_config_file) model = BertModel(config) # Load weights from TF model path = args.tf_checkpoint_path print("Converting TensorFlow checkpoint from {}".format(path)) init_vars = tf.train.list_variables(path) names = [] arrays = [] for name, shape in init_vars: print("Loading {} with shape {}".format(name, shape)) array = tf.train.load_variable(path, name) print("Numpy array shape {}".format(array.shape)) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name[5:] # skip "bert/" print("Loading {}".format(name)) name = name.split('/') if name[0] in ['redictions', 'eq_relationship']: print("Skipping") continue pointer = model for m_name in name: if re.fullmatch(r'[A-Za-z]+_\d+', m_name): l = re.split(r'_(\d+)', m_name) else: l = [m_name] if l[0] == 'kernel': pointer = getattr(pointer, 'weight') else: pointer = getattr(pointer, l[0]) if len(l) >= 2: num = int(l[1]) pointer = pointer[num] if m_name[-11:] == '_embeddings': pointer = getattr(pointer, 'weight') elif m_name == 'kernel': array = np.transpose(array) try: assert pointer.shape == array.shape except AssertionError as e: e.args += (pointer.shape, array.shape) raise pointer.data = torch.from_numpy(array) # Save pytorch-model torch.save(model.state_dict(), args.pytorch_dump_path)
[ "def", "convert", "(", ")", ":", "# Initialise PyTorch model", "config", "=", "BertConfig", ".", "from_json_file", "(", "args", ".", "bert_config_file", ")", "model", "=", "BertModel", "(", "config", ")", "# Load weights from TF model", "path", "=", "args", ".", ...
https://github.com/naver/sqlova/blob/fc68af6008fd2fd5839210e4b06a352007f609b6/bert/convert_tf_checkpoint_to_pytorch.py#L51-L102
jacobandreas/nmn2
7e42dd98420f9580fd34185ba670490a5d86fb04
misc/util.py
python
Struct.__repr__
(self)
return "Struct(%r)" % self.__dict__
[]
def __repr__(self): return "Struct(%r)" % self.__dict__
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"Struct(%r)\"", "%", "self", ".", "__dict__" ]
https://github.com/jacobandreas/nmn2/blob/7e42dd98420f9580fd34185ba670490a5d86fb04/misc/util.py#L33-L34
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py
python
Canvas.dtag
(self, *args)
Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.
Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.
[ "Delete", "tag", "or", "id", "given", "as", "last", "arguments", "in", "ARGS", "from", "items", "identified", "by", "first", "argument", "in", "ARGS", "." ]
def dtag(self, *args): """Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.""" self.tk.call((self._w, 'dtag') + args)
[ "def", "dtag", "(", "self", ",", "*", "args", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'dtag'", ")", "+", "args", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py#L2463-L2466
pyca/pyopenssl
fb26edde0aa27670c7bb24c0daeb05516e83d7b0
src/OpenSSL/crypto.py
python
X509.has_expired
(self)
return not_after < datetime.datetime.utcnow()
Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool
Check whether the certificate has expired.
[ "Check", "whether", "the", "certificate", "has", "expired", "." ]
def has_expired(self): """ Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool """ time_string = self.get_notAfter().decode("utf-8") not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ") return not_after < datetime.datetime.utcnow()
[ "def", "has_expired", "(", "self", ")", ":", "time_string", "=", "self", ".", "get_notAfter", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "not_after", "=", "datetime", ".", "datetime", ".", "strptime", "(", "time_string", ",", "\"%Y%m%d%H%M%SZ\"", ")", ...
https://github.com/pyca/pyopenssl/blob/fb26edde0aa27670c7bb24c0daeb05516e83d7b0/src/OpenSSL/crypto.py#L1376-L1386
HewlettPackard/dlcookbook-dlbs
863ac1d7e72ad2fcafc78d8a13f67d35bc00c235
python/dlbs/utils.py
python
IOUtils.check_file_extensions
(file_name, extensions)
Checks that `file_name` has one of the provided extensions. Args: file_name (str): The file name to check. extensions (tuple): A tuple of file extensions to use. Raises: ValueError: If `file_name` does not end with one of the extensions.
Checks that `file_name` has one of the provided extensions.
[ "Checks", "that", "file_name", "has", "one", "of", "the", "provided", "extensions", "." ]
def check_file_extensions(file_name, extensions): """Checks that `file_name` has one of the provided extensions. Args: file_name (str): The file name to check. extensions (tuple): A tuple of file extensions to use. Raises: ValueError: If `file_name` does not end with one of the extensions. """ if file_name is None: return assert isinstance(extensions, tuple), "The 'extensions' must be a tuple." if not file_name.endswith(extensions): raise ValueError("Invalid file extension (%s). Must be one of %s" % extensions)
[ "def", "check_file_extensions", "(", "file_name", ",", "extensions", ")", ":", "if", "file_name", "is", "None", ":", "return", "assert", "isinstance", "(", "extensions", ",", "tuple", ")", ",", "\"The 'extensions' must be a tuple.\"", "if", "not", "file_name", "."...
https://github.com/HewlettPackard/dlcookbook-dlbs/blob/863ac1d7e72ad2fcafc78d8a13f67d35bc00c235/python/dlbs/utils.py#L333-L347
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/vpc/v20170312/models.py
python
AddBandwidthPackageResourcesRequest.__init__
(self)
r""" :param ResourceIds: 资源唯一ID,当前支持EIP资源和LB资源,形如'eip-xxxx', 'lb-xxxx' :type ResourceIds: list of str :param BandwidthPackageId: 带宽包唯一标识ID,形如'bwp-xxxx' :type BandwidthPackageId: str :param NetworkType: 带宽包类型,当前支持'BGP'类型,表示内部资源是BGP IP。 :type NetworkType: str :param ResourceType: 资源类型,包括'Address', 'LoadBalance' :type ResourceType: str :param Protocol: 带宽包协议类型。当前支持'ipv4'和'ipv6'协议类型。 :type Protocol: str
r""" :param ResourceIds: 资源唯一ID,当前支持EIP资源和LB资源,形如'eip-xxxx', 'lb-xxxx' :type ResourceIds: list of str :param BandwidthPackageId: 带宽包唯一标识ID,形如'bwp-xxxx' :type BandwidthPackageId: str :param NetworkType: 带宽包类型,当前支持'BGP'类型,表示内部资源是BGP IP。 :type NetworkType: str :param ResourceType: 资源类型,包括'Address', 'LoadBalance' :type ResourceType: str :param Protocol: 带宽包协议类型。当前支持'ipv4'和'ipv6'协议类型。 :type Protocol: str
[ "r", ":", "param", "ResourceIds", ":", "资源唯一ID,当前支持EIP资源和LB资源,形如", "eip", "-", "xxxx", "lb", "-", "xxxx", ":", "type", "ResourceIds", ":", "list", "of", "str", ":", "param", "BandwidthPackageId", ":", "带宽包唯一标识ID,形如", "bwp", "-", "xxxx", ":", "type", "Bandwid...
def __init__(self): r""" :param ResourceIds: 资源唯一ID,当前支持EIP资源和LB资源,形如'eip-xxxx', 'lb-xxxx' :type ResourceIds: list of str :param BandwidthPackageId: 带宽包唯一标识ID,形如'bwp-xxxx' :type BandwidthPackageId: str :param NetworkType: 带宽包类型,当前支持'BGP'类型,表示内部资源是BGP IP。 :type NetworkType: str :param ResourceType: 资源类型,包括'Address', 'LoadBalance' :type ResourceType: str :param Protocol: 带宽包协议类型。当前支持'ipv4'和'ipv6'协议类型。 :type Protocol: str """ self.ResourceIds = None self.BandwidthPackageId = None self.NetworkType = None self.ResourceType = None self.Protocol = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ResourceIds", "=", "None", "self", ".", "BandwidthPackageId", "=", "None", "self", ".", "NetworkType", "=", "None", "self", ".", "ResourceType", "=", "None", "self", ".", "Protocol", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vpc/v20170312/models.py#L104-L121
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
components/isceobj/RtcProc/RtcProc.py
python
RtcProc.getValidPolarizationList
(self, inlist)
return validlist
Used to get list of swaths left after applying all filters - e.g, region of interest.
Used to get list of swaths left after applying all filters - e.g, region of interest.
[ "Used", "to", "get", "list", "of", "swaths", "left", "after", "applying", "all", "filters", "-", "e", ".", "g", "region", "of", "interest", "." ]
def getValidPolarizationList(self, inlist): ''' Used to get list of swaths left after applying all filters - e.g, region of interest. ''' checklist = self.getInputPolarizationList(inlist) validlist = [x for x in checklist if x in self.polarizations] return validlist
[ "def", "getValidPolarizationList", "(", "self", ",", "inlist", ")", ":", "checklist", "=", "self", ".", "getInputPolarizationList", "(", "inlist", ")", "validlist", "=", "[", "x", "for", "x", "in", "checklist", "if", "x", "in", "self", ".", "polarizations", ...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/RtcProc/RtcProc.py#L198-L207
yaqwsx/PcbDraw
09720d46f3fdb8b01c2b0e2eca39d964552e94a0
versioneer.py
python
render_pep440
(pieces)
return rendered
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
Build up version string, with post-release "local version identifier".
[ "Build", "up", "version", "string", "with", "post", "-", "release", "local", "version", "identifier", "." ]
def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered
[ "def", "render_pep440", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=...
https://github.com/yaqwsx/PcbDraw/blob/09720d46f3fdb8b01c2b0e2eca39d964552e94a0/versioneer.py#L1236-L1258
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/layout/scene/_yaxis.py
python
YAxis.linecolor
(self)
return self["linecolor"]
Sets the axis line color. The 'linecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the axis line color. The 'linecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
[ "Sets", "the", "axis", "line", "color", ".", "The", "linecolor", "property", "is", "a", "color", "and", "may", "be", "specified", "as", ":", "-", "A", "hex", "string", "(", "e", ".", "g", ".", "#ff0000", ")", "-", "An", "rgb", "/", "rgba", "string"...
def linecolor(self): """ Sets the axis line color. The 'linecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["linecolor"]
[ "def", "linecolor", "(", "self", ")", ":", "return", "self", "[", "\"linecolor\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/layout/scene/_yaxis.py#L524-L574
dmnfarrell/pandastable
9c268b3e2bfe2e718eaee4a30bd02832a0ad1614
pandastable/plotting.py
python
PlotViewer.removeSubplot
(self)
return
Remove a specific axis from the grid layout
Remove a specific axis from the grid layout
[ "Remove", "a", "specific", "axis", "from", "the", "grid", "layout" ]
def removeSubplot(self): """Remove a specific axis from the grid layout""" axname = self.layoutopts.axeslistvar.get() ax = self.gridaxes[axname] if ax in self.fig.axes: self.fig.delaxes(ax) del self.gridaxes[axname] self.canvas.show() self.layoutopts.updateAxesList() self.layoutopts.axeslistvar.set('') return
[ "def", "removeSubplot", "(", "self", ")", ":", "axname", "=", "self", ".", "layoutopts", ".", "axeslistvar", ".", "get", "(", ")", "ax", "=", "self", ".", "gridaxes", "[", "axname", "]", "if", "ax", "in", "self", ".", "fig", ".", "axes", ":", "self...
https://github.com/dmnfarrell/pandastable/blob/9c268b3e2bfe2e718eaee4a30bd02832a0ad1614/pandastable/plotting.py#L399-L410
zaiweizhang/H3DNet
e69f2855634807b37ae12e6db5963c924e64d3e7
utils/eval_det.py
python
eval_det
(pred_all, gt_all, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou)
return rec, prec, ap
Generic functions to compute precision/recall for object detection for multiple classes. Input: pred_all: map of {img_id: [(classname, bbox, score)]} gt_all: map of {img_id: [(classname, bbox)]} ovthresh: scalar, iou threshold use_07_metric: bool, if true use VOC07 11 point method Output: rec: {classname: rec} prec: {classname: prec_all} ap: {classname: scalar}
Generic functions to compute precision/recall for object detection for multiple classes. Input: pred_all: map of {img_id: [(classname, bbox, score)]} gt_all: map of {img_id: [(classname, bbox)]} ovthresh: scalar, iou threshold use_07_metric: bool, if true use VOC07 11 point method Output: rec: {classname: rec} prec: {classname: prec_all} ap: {classname: scalar}
[ "Generic", "functions", "to", "compute", "precision", "/", "recall", "for", "object", "detection", "for", "multiple", "classes", ".", "Input", ":", "pred_all", ":", "map", "of", "{", "img_id", ":", "[", "(", "classname", "bbox", "score", ")", "]", "}", "...
def eval_det(pred_all, gt_all, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou): """ Generic functions to compute precision/recall for object detection for multiple classes. Input: pred_all: map of {img_id: [(classname, bbox, score)]} gt_all: map of {img_id: [(classname, bbox)]} ovthresh: scalar, iou threshold use_07_metric: bool, if true use VOC07 11 point method Output: rec: {classname: rec} prec: {classname: prec_all} ap: {classname: scalar} """ pred = {} # map {classname: pred} gt = {} # map {classname: gt} for img_id in pred_all.keys(): for classname, bbox, score in pred_all[img_id]: if classname not in pred: pred[classname] = {} if img_id not in pred[classname]: pred[classname][img_id] = [] if classname not in gt: gt[classname] = {} if img_id not in gt[classname]: gt[classname][img_id] = [] pred[classname][img_id].append((bbox,score)) for img_id in gt_all.keys(): for classname, bbox in gt_all[img_id]: if classname not in gt: gt[classname] = {} if img_id not in gt[classname]: gt[classname][img_id] = [] gt[classname][img_id].append(bbox) rec = {} prec = {} ap = {} for classname in gt.keys(): print('Computing AP for class: ', classname) rec[classname], prec[classname], ap[classname] = eval_det_cls(pred[classname], gt[classname], ovthresh, use_07_metric, get_iou_func) print(classname, ap[classname]) return rec, prec, ap
[ "def", "eval_det", "(", "pred_all", ",", "gt_all", ",", "ovthresh", "=", "0.25", ",", "use_07_metric", "=", "False", ",", "get_iou_func", "=", "get_iou", ")", ":", "pred", "=", "{", "}", "# map {classname: pred}", "gt", "=", "{", "}", "# map {classname: gt}"...
https://github.com/zaiweizhang/H3DNet/blob/e69f2855634807b37ae12e6db5963c924e64d3e7/utils/eval_det.py#L168-L207
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/models.py
python
BaseResource.bag_checksum
(self)
get checksum of resource bag. Currently only published resources have bag checksums computed and saved :return: checksum if bag checksum exists; empty string '' otherwise
get checksum of resource bag. Currently only published resources have bag checksums computed and saved :return: checksum if bag checksum exists; empty string '' otherwise
[ "get", "checksum", "of", "resource", "bag", ".", "Currently", "only", "published", "resources", "have", "bag", "checksums", "computed", "and", "saved", ":", "return", ":", "checksum", "if", "bag", "checksum", "exists", ";", "empty", "string", "otherwise" ]
def bag_checksum(self): """ get checksum of resource bag. Currently only published resources have bag checksums computed and saved :return: checksum if bag checksum exists; empty string '' otherwise """ extra_data = self.extra_data if 'bag_checksum' in extra_data and extra_data['bag_checksum']: return extra_data['bag_checksum'].strip('\n') else: return ''
[ "def", "bag_checksum", "(", "self", ")", ":", "extra_data", "=", "self", ".", "extra_data", "if", "'bag_checksum'", "in", "extra_data", "and", "extra_data", "[", "'bag_checksum'", "]", ":", "return", "extra_data", "[", "'bag_checksum'", "]", ".", "strip", "(",...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/models.py#L3498-L3507
har07/PySastrawi
01afc81c579bde14dcb41c33686b26af8afab121
src/Sastrawi/Morphology/Disambiguator/DisambiguatorPrefixRule4.py
python
DisambiguatorPrefixRule4.disambiguate
(self, word)
Disambiguate Prefix Rule 4 Rule 4 : belajar -> bel-ajar
Disambiguate Prefix Rule 4 Rule 4 : belajar -> bel-ajar
[ "Disambiguate", "Prefix", "Rule", "4", "Rule", "4", ":", "belajar", "-", ">", "bel", "-", "ajar" ]
def disambiguate(self, word): """Disambiguate Prefix Rule 4 Rule 4 : belajar -> bel-ajar """ if word == 'belajar': return 'ajar'
[ "def", "disambiguate", "(", "self", ",", "word", ")", ":", "if", "word", "==", "'belajar'", ":", "return", "'ajar'" ]
https://github.com/har07/PySastrawi/blob/01afc81c579bde14dcb41c33686b26af8afab121/src/Sastrawi/Morphology/Disambiguator/DisambiguatorPrefixRule4.py#L6-L11
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Automatic-Summarization/pysummarization/abstractablesemantics/_mxnet/observing_media.py
python
ObservingMedia.learn
(self)
Learning.
Learning.
[ "Learning", "." ]
def learn(self): ''' Learning. ''' self.transformer_controller.learn(self.transformer_iterator)
[ "def", "learn", "(", "self", ")", ":", "self", ".", "transformer_controller", ".", "learn", "(", "self", ".", "transformer_iterator", ")" ]
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Automatic-Summarization/pysummarization/abstractablesemantics/_mxnet/observing_media.py#L105-L109
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/api/realm.py
python
set_realm_api
(realm=None)
return send_result({"added": added, "failed": failed})
This call creates a new realm or reconfigures a realm. The realm contains a list of resolvers. In the result it returns a list of added resolvers and a list of resolvers, that could not be added. :param realm: The unique name of the realm :param resolvers: A comma separated list of unique resolver names or a list object :type resolvers: string or list :param priority: Additional parameters priority.<resolvername> define the priority of the resolvers within this realm. :return: a json result with a list of Realms **Example request**: To create a new realm "newrealm", that consists of the resolvers "reso1_with_realm" and "reso2_with_realm" call: .. sourcecode:: http POST /realm/newrealm HTTP/1.1 Host: example.com Accept: application/json Content-Length: 26 Content-Type: application/x-www-form-urlencoded resolvers=reso1_with_realm, reso2_with_realm priority.reso1_with_realm=1 priority.reso2_with_realm=2 **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": { "added": ["reso1_with_realm", "reso2_with_realm"], "failed": [] } } "version": "privacyIDEA unknown" }
This call creates a new realm or reconfigures a realm. The realm contains a list of resolvers.
[ "This", "call", "creates", "a", "new", "realm", "or", "reconfigures", "a", "realm", ".", "The", "realm", "contains", "a", "list", "of", "resolvers", "." ]
def set_realm_api(realm=None): """ This call creates a new realm or reconfigures a realm. The realm contains a list of resolvers. In the result it returns a list of added resolvers and a list of resolvers, that could not be added. :param realm: The unique name of the realm :param resolvers: A comma separated list of unique resolver names or a list object :type resolvers: string or list :param priority: Additional parameters priority.<resolvername> define the priority of the resolvers within this realm. :return: a json result with a list of Realms **Example request**: To create a new realm "newrealm", that consists of the resolvers "reso1_with_realm" and "reso2_with_realm" call: .. sourcecode:: http POST /realm/newrealm HTTP/1.1 Host: example.com Accept: application/json Content-Length: 26 Content-Type: application/x-www-form-urlencoded resolvers=reso1_with_realm, reso2_with_realm priority.reso1_with_realm=1 priority.reso2_with_realm=2 **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": { "added": ["reso1_with_realm", "reso2_with_realm"], "failed": [] } } "version": "privacyIDEA unknown" } """ param = request.all_data resolvers = getParam(param, "resolvers", required) priority = get_priority_from_param(param) if type(resolvers) == "list": Resolvers = resolvers else: Resolvers = resolvers.split(',') (added, failed) = set_realm(realm, Resolvers, priority=priority) g.audit_object.log({'success': len(added) == len(Resolvers), 'info': "realm: {0!r}, resolvers: {1!r}".format(realm, resolvers)}) return send_result({"added": added, "failed": failed})
[ "def", "set_realm_api", "(", "realm", "=", "None", ")", ":", "param", "=", "request", ".", "all_data", "resolvers", "=", "getParam", "(", "param", ",", "\"resolvers\"", ",", "required", ")", "priority", "=", "get_priority_from_param", "(", "param", ")", "if"...
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/api/realm.py#L80-L148
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/req/req_uninstall.py
python
UninstallPathSet._permitted
(self, path)
return is_local(path)
Return True if the given path is one we are permitted to remove/modify, False otherwise.
Return True if the given path is one we are permitted to remove/modify, False otherwise.
[ "Return", "True", "if", "the", "given", "path", "is", "one", "we", "are", "permitted", "to", "remove", "/", "modify", "False", "otherwise", "." ]
def _permitted(self, path): """ Return True if the given path is one we are permitted to remove/modify, False otherwise. """ return is_local(path)
[ "def", "_permitted", "(", "self", ",", "path", ")", ":", "return", "is_local", "(", "path", ")" ]
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/req/req_uninstall.py#L27-L33
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/discovery_v1_endpoint_port.py
python
DiscoveryV1EndpointPort.__eq__
(self, other)
return self.to_dict() == other.to_dict()
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DiscoveryV1EndpointPort): return False return self.to_dict() == other.to_dict()
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "DiscoveryV1EndpointPort", ")", ":", "return", "False", "return", "self", ".", "to_dict", "(", ")", "==", "other", ".", "to_dict", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/discovery_v1_endpoint_port.py#L194-L199
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/packaging/markers.py
python
Marker.__str__
(self)
return _format_marker(self._markers)
[]
def __str__(self) -> str: return _format_marker(self._markers)
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "return", "_format_marker", "(", "self", ".", "_markers", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/packaging/markers.py#L285-L286
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/tensorpack/tfutils/symbolic_functions.py
python
get_scalar_var
(name, init_value, summary=False, trainable=False)
return ret
Get a scalar float variable with certain initial value. You can just call `tf.get_variable(name, initializer=init_value, trainable=False)` instead. Args: name (str): name of the variable. init_value (float): initial value. summary (bool): whether to summary this variable. trainable (bool): trainable or not. Returns: tf.Variable: the variable
Get a scalar float variable with certain initial value. You can just call `tf.get_variable(name, initializer=init_value, trainable=False)` instead.
[ "Get", "a", "scalar", "float", "variable", "with", "certain", "initial", "value", ".", "You", "can", "just", "call", "tf", ".", "get_variable", "(", "name", "initializer", "=", "init_value", "trainable", "=", "False", ")", "instead", "." ]
def get_scalar_var(name, init_value, summary=False, trainable=False): """ Get a scalar float variable with certain initial value. You can just call `tf.get_variable(name, initializer=init_value, trainable=False)` instead. Args: name (str): name of the variable. init_value (float): initial value. summary (bool): whether to summary this variable. trainable (bool): trainable or not. Returns: tf.Variable: the variable """ ret = tf.get_variable(name, initializer=float(init_value), trainable=trainable) if summary: # this is recognized in callbacks.StatHolder tf.summary.scalar(name + '-summary', ret) return ret
[ "def", "get_scalar_var", "(", "name", ",", "init_value", ",", "summary", "=", "False", ",", "trainable", "=", "False", ")", ":", "ret", "=", "tf", ".", "get_variable", "(", "name", ",", "initializer", "=", "float", "(", "init_value", ")", ",", "trainable...
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/tfutils/symbolic_functions.py#L91-L109
SheffieldML/GPy
bb1bc5088671f9316bc92a46d356734e34c2d5c0
GPy/likelihoods/poisson.py
python
Poisson.pdf_link
(self, link_f, y, Y_metadata=None)
return np.exp(self.logpdf_link(link_f, y, Y_metadata))
Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})} :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in poisson distribution :returns: likelihood evaluated for this point :rtype: float
Likelihood function given link(f)
[ "Likelihood", "function", "given", "link", "(", "f", ")" ]
def pdf_link(self, link_f, y, Y_metadata=None): """ Likelihood function given link(f) .. math:: p(y_{i}|\\lambda(f_{i})) = \\frac{\\lambda(f_{i})^{y_{i}}}{y_{i}!}e^{-\\lambda(f_{i})} :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in poisson distribution :returns: likelihood evaluated for this point :rtype: float """ assert np.atleast_1d(link_f).shape == np.atleast_1d(y).shape return np.exp(self.logpdf_link(link_f, y, Y_metadata))
[ "def", "pdf_link", "(", "self", ",", "link_f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "assert", "np", ".", "atleast_1d", "(", "link_f", ")", ".", "shape", "==", "np", ".", "atleast_1d", "(", "y", ")", ".", "shape", "return", "np", ".",...
https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/likelihoods/poisson.py#L33-L49
nengo/nengo
f5a88ba6b42b39a722299db6e889a5d034fcfeda
nengo/ensemble.py
python
Neurons.size_out
(self)
return self.ensemble.n_neurons
(int) The number of neurons in the population.
(int) The number of neurons in the population.
[ "(", "int", ")", "The", "number", "of", "neurons", "in", "the", "population", "." ]
def size_out(self): """(int) The number of neurons in the population.""" if isinstance(self.ensemble.neuron_type, Direct): # This will prevent users from connecting/probing Direct neurons # (since there aren't actually any neurons being simulated). return 0 return self.ensemble.n_neurons
[ "def", "size_out", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "ensemble", ".", "neuron_type", ",", "Direct", ")", ":", "# This will prevent users from connecting/probing Direct neurons", "# (since there aren't actually any neurons being simulated).", "return...
https://github.com/nengo/nengo/blob/f5a88ba6b42b39a722299db6e889a5d034fcfeda/nengo/ensemble.py#L259-L265
captainhammy/Houdini-Toolbox
a4e61c3c0296b3a3a153a8dd42297c316be1b0f3
python/houdini_toolbox/ui/aovs/widgets.py
python
AOVsToAddWidget.apply_as_parms
(self)
Apply AOVs and AOVGroups as multi parms.
Apply AOVs and AOVGroups as multi parms.
[ "Apply", "AOVs", "and", "AOVGroups", "as", "multi", "parms", "." ]
def apply_as_parms(self): """Apply AOVs and AOVGroups as multi parms.""" if self.node is not None: nodes = [self.node] else: nodes = utils.get_selected_mantra_nodes() if not nodes: return elements = self.tree.get_elements_to_add() utils.apply_elements_as_parms(elements, nodes)
[ "def", "apply_as_parms", "(", "self", ")", ":", "if", "self", ".", "node", "is", "not", "None", ":", "nodes", "=", "[", "self", ".", "node", "]", "else", ":", "nodes", "=", "utils", ".", "get_selected_mantra_nodes", "(", ")", "if", "not", "nodes", ":...
https://github.com/captainhammy/Houdini-Toolbox/blob/a4e61c3c0296b3a3a153a8dd42297c316be1b0f3/python/houdini_toolbox/ui/aovs/widgets.py#L1468-L1481
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/update.py
python
handle_update
(settings, update_handlers, previous_version, current_version)
[]
def handle_update(settings, update_handlers, previous_version, current_version): for version_str, update_handler in update_handlers.items(): if previous_version < pg.version.Version.parse(version_str) <= current_version: update_handler(settings)
[ "def", "handle_update", "(", "settings", ",", "update_handlers", ",", "previous_version", ",", "current_version", ")", ":", "for", "version_str", ",", "update_handler", "in", "update_handlers", ".", "items", "(", ")", ":", "if", "previous_version", "<", "pg", "....
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/update.py#L109-L112
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/gluon/validators.py
python
LazyCrypt.__eq__
(self, stored_password)
return temp_pass == stored_password
compares the current lazy crypted password with a stored password
compares the current lazy crypted password with a stored password
[ "compares", "the", "current", "lazy", "crypted", "password", "with", "a", "stored", "password" ]
def __eq__(self, stored_password): """ compares the current lazy crypted password with a stored password """ # LazyCrypt objects comparison if isinstance(stored_password, self.__class__): return ((self is stored_password) or ((self.crypt.key == stored_password.crypt.key) and (self.password == stored_password.password))) if self.crypt.key: if ':' in self.crypt.key: key = self.crypt.key.split(':')[1] else: key = self.crypt.key else: key = '' if stored_password is None: return False elif stored_password.count('$') == 2: (digest_alg, salt, hash) = stored_password.split('$') h = simple_hash(self.password, key, salt, digest_alg) temp_pass = '%s$%s$%s' % (digest_alg, salt, h) else: # no salting # guess digest_alg digest_alg = DIGEST_ALG_BY_SIZE.get(len(stored_password), None) if not digest_alg: return False else: temp_pass = simple_hash(self.password, key, '', digest_alg) return temp_pass == stored_password
[ "def", "__eq__", "(", "self", ",", "stored_password", ")", ":", "# LazyCrypt objects comparison", "if", "isinstance", "(", "stored_password", ",", "self", ".", "__class__", ")", ":", "return", "(", "(", "self", "is", "stored_password", ")", "or", "(", "(", "...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/gluon/validators.py#L2755-L2786
vyos/vyos-1x
6e8a8934a7d4e1b21d7c828e372303683b499b56
python/vyos/util.py
python
read_json
(fname, defaultonfailure=None)
read and json decode the content of a file should defaultonfailure be not None, it is returned on failure to read
read and json decode the content of a file should defaultonfailure be not None, it is returned on failure to read
[ "read", "and", "json", "decode", "the", "content", "of", "a", "file", "should", "defaultonfailure", "be", "not", "None", "it", "is", "returned", "on", "failure", "to", "read" ]
def read_json(fname, defaultonfailure=None): """ read and json decode the content of a file should defaultonfailure be not None, it is returned on failure to read """ import json try: with open(fname, 'r') as f: data = json.load(f) return data except Exception as e: if defaultonfailure is not None: return defaultonfailure raise e
[ "def", "read_json", "(", "fname", ",", "defaultonfailure", "=", "None", ")", ":", "import", "json", "try", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "return", "data", "excep...
https://github.com/vyos/vyos-1x/blob/6e8a8934a7d4e1b21d7c828e372303683b499b56/python/vyos/util.py#L225-L238
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/objects/transition_system/utils.py
python
remove_arc_from_to
(name, fr, to, ts)
Removes a transition with a specific name from a state to another state in some transition system. Assumes from and to are in the transition system! Parameters ---------- name: name of the transition fr: state from to: state to ts: transition system to use Returns ------- None
Removes a transition with a specific name from a state to another state in some transition system. Assumes from and to are in the transition system!
[ "Removes", "a", "transition", "with", "a", "specific", "name", "from", "a", "state", "to", "another", "state", "in", "some", "transition", "system", ".", "Assumes", "from", "and", "to", "are", "in", "the", "transition", "system!" ]
def remove_arc_from_to(name, fr, to, ts): """ Removes a transition with a specific name from a state to another state in some transition system. Assumes from and to are in the transition system! Parameters ---------- name: name of the transition fr: state from to: state to ts: transition system to use Returns ------- None """ ts.transitions = [t for t in ts.transitions if t.name != name] fr.outgoing = [t for t in fr.outgoing if t.name != name] to.incoming = [t for t in to.incoming if t.name != name]
[ "def", "remove_arc_from_to", "(", "name", ",", "fr", ",", "to", ",", "ts", ")", ":", "ts", ".", "transitions", "=", "[", "t", "for", "t", "in", "ts", ".", "transitions", "if", "t", ".", "name", "!=", "name", "]", "fr", ".", "outgoing", "=", "[", ...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/objects/transition_system/utils.py#L43-L61
HaoZhang95/Python24
b897224b8a0e6a5734f408df8c24846a98c553bf
00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/pkg_resources/__init__.py
python
resolve_egg_link
(path)
return next(dist_groups, ())
Given a path to an .egg-link, resolve distributions present in the referenced path.
Given a path to an .egg-link, resolve distributions present in the referenced path.
[ "Given", "a", "path", "to", "an", ".", "egg", "-", "link", "resolve", "distributions", "present", "in", "the", "referenced", "path", "." ]
def resolve_egg_link(path): """ Given a path to an .egg-link, resolve distributions present in the referenced path. """ referenced_paths = non_empty_lines(path) resolved_paths = ( os.path.join(os.path.dirname(path), ref) for ref in referenced_paths ) dist_groups = map(find_distributions, resolved_paths) return next(dist_groups, ())
[ "def", "resolve_egg_link", "(", "path", ")", ":", "referenced_paths", "=", "non_empty_lines", "(", "path", ")", "resolved_paths", "=", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "ref", ")", "for"...
https://github.com/HaoZhang95/Python24/blob/b897224b8a0e6a5734f408df8c24846a98c553bf/00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/pkg_resources/__init__.py#L2049-L2060
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo.create_ustar_header
(self, info, encoding, errors)
return self._create_header(info, USTAR_FORMAT, encoding, errors)
Return the object as a ustar header block.
Return the object as a ustar header block.
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", "." ]
def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"]) return self._create_header(info, USTAR_FORMAT, encoding, errors)
[ "def", "create_ustar_header", "(", "self", ",", "info", ",", "encoding", ",", "errors", ")", ":", "info", "[", "\"magic\"", "]", "=", "POSIX_MAGIC", "if", "len", "(", "info", "[", "\"linkname\"", "]", ")", ">", "LENGTH_LINK", ":", "raise", "ValueError", ...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/distlib/_backport/tarfile.py#L1016-L1027
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/XLSWriter.py
python
XLSWriter.cell
(self, s)
return s
[]
def cell(self, s): if isinstance(s, basestring): if not isinstance(s, unicode): s = s.decode(self.encoding) elif s is None: s = '' else: s = str(s) return s
[ "def", "cell", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "basestring", ")", ":", "if", "not", "isinstance", "(", "s", ",", "unicode", ")", ":", "s", "=", "s", ".", "decode", "(", "self", ".", "encoding", ")", "elif", "...
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/XLSWriter.py#L107-L115
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
DemoPrograms/Demo_MIDI_Player.py
python
main
()
[]
def main(): def GetCurrentTime(): ''' Get the current system time in milliseconds :return: milliseconds ''' return int(round(time.time() * 1000)) pback = PlayerGUI() button, values = pback.PlayerChooseSongGUI() if button != 'PLAY': sg.popup_cancel('Cancelled...\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) return if values['device']: midi_port = values['device'][0] else: sg.popup_cancel('No devices found\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) batch_folder = values['folder'] midi_filename = values['midifile'] # ------ Build list of files to play --------------------------------------------------------- # if batch_folder: filelist = os.listdir(batch_folder) filelist = [batch_folder+'/' + f for f in filelist if f.endswith(('.mid', '.MID'))] filetitles = [os.path.basename(f) for f in filelist] elif midi_filename: # an individual filename filelist = [midi_filename, ] filetitles = [os.path.basename(midi_filename), ] else: sg.popup_error('*** Error - No MIDI files specified ***') return # ------ LOOP THROUGH MULTIPLE FILES --------------------------------------------------------- # pback.PlayerPlaybackGUIStart(NumFiles=len(filelist) if len(filelist) <= 10 else 10) port = None # Loop through the files in the filelist for now_playing_number, current_midi_filename in enumerate(filelist): display_string = 'Playing Local File...\n{} of {}\n{}'.format( now_playing_number+1, len(filelist), current_midi_filename) midi_title = filetitles[now_playing_number] # --------------------------------- REFRESH THE GUI ----------------------------------------- # pback.PlayerPlaybackGUIUpdate(display_string) # ---===--- Output Filename is .MID --- # midi_filename = current_midi_filename # --------------------------------- MIDI - STARTS HERE ----------------------------------------- # if not port: # if the midi output port not opened yet, then open it port = mido.open_output(midi_port if midi_port else None) try: mid = mido.MidiFile(filename=midi_filename) except: print(' Fail at playing Midi file = {}****'.format(midi_filename)) sg.popup_error('Exception trying to play MIDI file:', midi_filename, 'Skipping file') continue # Build list of data contained in MIDI File using only track 0 midi_length_in_seconds = mid.length display_file_list = '>> ' + \ '\n'.join([f for i, f in enumerate( filetitles[now_playing_number:]) if i < 10]) paused = cancelled = next_file = False ######################### Loop through MIDI Messages ########################### while True : start_playback_time = GetCurrentTime() port.reset() for midi_msg_number, msg in enumerate(mid.play()): #################### GUI - read values ################## if not midi_msg_number % 4: # update the GUI every 4 MIDI messages t = (GetCurrentTime() - start_playback_time)//1000 display_midi_len = '{:02d}:{:02d}'.format( *divmod(int(midi_length_in_seconds), 60)) display_string = 'Now Playing {} of {}\n{}\n {:02d}:{:02d} of {}\nPlaylist:'.\ format(now_playing_number+1, len(filelist), midi_title, *divmod(t, 60), display_midi_len) # display list of next 10 files to be played. pback.SliderElem.update(t, range=(1, midi_length_in_seconds)) rc = pback.PlayerPlaybackGUIUpdate( display_string + '\n' + display_file_list) else: # fake rest of code as if GUI did nothing rc = PLAYER_COMMAND_NONE if paused: rc = PLAYER_COMMAND_NONE while rc == PLAYER_COMMAND_NONE: # TIGHT-ASS loop waiting on a GUI command rc = pback.PlayerPlaybackGUIUpdate(display_string) time.sleep(.25) ####################################### MIDI send data ################################## port.send(msg) # ------- Execute GUI Commands after sending MIDI data ------- # if rc == PLAYER_COMMAND_EXIT: cancelled = True break elif rc == PLAYER_COMMAND_PAUSE: paused = not paused port.reset() elif rc == PLAYER_COMMAND_NEXT: next_file = True break elif rc == PLAYER_COMMAND_RESTART_SONG: break if cancelled or next_file: break #------- DONE playing the song ------- # port.reset() # reset the midi port when done with the song if cancelled: break
[ "def", "main", "(", ")", ":", "def", "GetCurrentTime", "(", ")", ":", "'''\n Get the current system time in milliseconds\n :return: milliseconds\n '''", "return", "int", "(", "round", "(", "time", ".", "time", "(", ")", "*", "1000", ")", ")", "p...
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_MIDI_Player.py#L121-L237
tryton/trytond
9fc68232536d0707b73614eab978bd6f813e3677
trytond/pool.py
python
Pool.database_list
(cls)
:return: database list
:return: database list
[ ":", "return", ":", "database", "list" ]
def database_list(cls): ''' :return: database list ''' with cls._lock: databases = [] for database in cls._pool.keys(): if cls._locks.get(database): if cls._locks[database].acquire(False): databases.append(database) cls._locks[database].release() return databases
[ "def", "database_list", "(", "cls", ")", ":", "with", "cls", ".", "_lock", ":", "databases", "=", "[", "]", "for", "database", "in", "cls", ".", "_pool", ".", "keys", "(", ")", ":", "if", "cls", ".", "_locks", ".", "get", "(", "database", ")", ":...
https://github.com/tryton/trytond/blob/9fc68232536d0707b73614eab978bd6f813e3677/trytond/pool.py#L125-L136
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/minimum_norm/time_frequency.py
python
_prepare_tfr
(data, decim, pick_ori, Ws, K, source_ori)
return shape, is_free_ori
Prepare TFR source localization.
Prepare TFR source localization.
[ "Prepare", "TFR", "source", "localization", "." ]
def _prepare_tfr(data, decim, pick_ori, Ws, K, source_ori): """Prepare TFR source localization.""" n_times = data[:, :, ::decim].shape[2] n_freqs = len(Ws) n_sources = K.shape[0] is_free_ori = False if (source_ori == FIFF.FIFFV_MNE_FREE_ORI and pick_ori is None): is_free_ori = True n_sources //= 3 shape = (n_sources, n_freqs, n_times) return shape, is_free_ori
[ "def", "_prepare_tfr", "(", "data", ",", "decim", ",", "pick_ori", ",", "Ws", ",", "K", ",", "source_ori", ")", ":", "n_times", "=", "data", "[", ":", ",", ":", ",", ":", ":", "decim", "]", ".", "shape", "[", "2", "]", "n_freqs", "=", "len", "(...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/minimum_norm/time_frequency.py#L175-L186
Freeseer/freeseer
73c53ab6f1f22dfc89a782728f3b3070ee71b690
src/freeseer/framework/database.py
python
QtDBConnector.__create_recentconn_table
(self)
Creates the recentconn table in the database. Should be used to initialize a new table
Creates the recentconn table in the database. Should be used to initialize a new table
[ "Creates", "the", "recentconn", "table", "in", "the", "database", ".", "Should", "be", "used", "to", "initialize", "a", "new", "table" ]
def __create_recentconn_table(self): """Creates the recentconn table in the database. Should be used to initialize a new table""" QtSql.QSqlQuery('''CREATE TABLE IF NOT EXISTS recentconn (host varchar(255), port int, passphrase varchar(255), UNIQUE (host, port) ON CONFLICT REPLACE)''')
[ "def", "__create_recentconn_table", "(", "self", ")", ":", "QtSql", ".", "QSqlQuery", "(", "'''CREATE TABLE IF NOT EXISTS recentconn\n (host varchar(255),\n port int,\n passphra...
https://github.com/Freeseer/freeseer/blob/73c53ab6f1f22dfc89a782728f3b3070ee71b690/src/freeseer/framework/database.py#L580-L586
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/tensor/extra_ops.py
python
fill_diagonal
(a, val)
return fill_diagonal_(a, val)
Returns a copy of an array with all elements of the main diagonal set to a specified scalar value. .. versionadded:: 0.6 Parameters ---------- a Rectangular array of at least two dimensions. val Scalar value to fill the diagonal whose type must be compatible with that of array 'a' (i.e. 'val' cannot be viewed as an upcast of 'a'). Returns ------- array An array identical to 'a' except that its main diagonal is filled with scalar 'val'. (For an array 'a' with a.ndim >= 2, the main diagonal is the list of locations a[i, i, ..., i] (i.e. with indices all identical).) Support rectangular matrix and tensor with more than 2 dimensions if the later have all dimensions are equals.
Returns a copy of an array with all elements of the main diagonal set to a specified scalar value.
[ "Returns", "a", "copy", "of", "an", "array", "with", "all", "elements", "of", "the", "main", "diagonal", "set", "to", "a", "specified", "scalar", "value", "." ]
def fill_diagonal(a, val): """ Returns a copy of an array with all elements of the main diagonal set to a specified scalar value. .. versionadded:: 0.6 Parameters ---------- a Rectangular array of at least two dimensions. val Scalar value to fill the diagonal whose type must be compatible with that of array 'a' (i.e. 'val' cannot be viewed as an upcast of 'a'). Returns ------- array An array identical to 'a' except that its main diagonal is filled with scalar 'val'. (For an array 'a' with a.ndim >= 2, the main diagonal is the list of locations a[i, i, ..., i] (i.e. with indices all identical).) Support rectangular matrix and tensor with more than 2 dimensions if the later have all dimensions are equals. """ return fill_diagonal_(a, val)
[ "def", "fill_diagonal", "(", "a", ",", "val", ")", ":", "return", "fill_diagonal_", "(", "a", ",", "val", ")" ]
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/tensor/extra_ops.py#L887-L917
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/tracemalloc.py
python
Snapshot.load
(filename)
Load a snapshot from a file.
Load a snapshot from a file.
[ "Load", "a", "snapshot", "from", "a", "file", "." ]
def load(filename): """ Load a snapshot from a file. """ with open(filename, "rb") as fp: return pickle.load(fp)
[ "def", "load", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fp", ":", "return", "pickle", ".", "load", "(", "fp", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/tracemalloc.py#L398-L403
wandb/client
3963364d8112b7dedb928fa423b6878ea1b467d9
wandb/vendor/graphql-core-1.1/graphql/validation/rules/fields_on_correct_type.py
python
get_suggested_type_names
(schema, output_type, field_name)
return []
Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.
Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.
[ "Go", "through", "all", "of", "the", "implementations", "of", "type", "as", "well", "as", "the", "interfaces", "that", "they", "implement", ".", "If", "any", "of", "those", "types", "include", "the", "provided", "field", "suggest", "them", "sorted", "by", ...
def get_suggested_type_names(schema, output_type, field_name): '''Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.''' if isinstance(output_type, (GraphQLInterfaceType, GraphQLUnionType)): suggested_object_types = [] interface_usage_count = OrderedDict() for possible_type in schema.get_possible_types(output_type): if not possible_type.fields.get(field_name): return # This object type defines this field. suggested_object_types.append(possible_type.name) for possible_interface in possible_type.interfaces: if not possible_interface.fields.get(field_name): continue # This interface type defines this field. interface_usage_count[possible_interface.name] = ( interface_usage_count.get(possible_interface.name, 0) + 1) # Suggest interface types based on how common they are. suggested_interface_types = sorted(list(interface_usage_count.keys()), key=lambda k: interface_usage_count[k], reverse=True) # Suggest both interface and object types. suggested_interface_types.extend(suggested_object_types) return suggested_interface_types # Otherwise, must be an Object type, which does not have possible fields. return []
[ "def", "get_suggested_type_names", "(", "schema", ",", "output_type", ",", "field_name", ")", ":", "if", "isinstance", "(", "output_type", ",", "(", "GraphQLInterfaceType", ",", "GraphQLUnionType", ")", ")", ":", "suggested_object_types", "=", "[", "]", "interface...
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/vendor/graphql-core-1.1/graphql/validation/rules/fields_on_correct_type.py#L67-L100
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/api/openstack/urlmap.py
python
parse_list_header
(value)
return result
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] :param value: a string with a list header. :return: :class:`list`
Parse lists as described by RFC 2068 Section 2.
[ "Parse", "lists", "as", "described", "by", "RFC", "2068", "Section", "2", "." ]
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] :param value: a string with a list header. :return: :class:`list` """ result = [] for item in urllib2.parse_http_list(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
[ "def", "parse_list_header", "(", "value", ")", ":", "result", "=", "[", "]", "for", "item", "in", "urllib2", ".", "parse_http_list", "(", "value", ")", ":", "if", "item", "[", ":", "1", "]", "==", "item", "[", "-", "1", ":", "]", "==", "'\"'", ":...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/api/openstack/urlmap.py#L50-L71
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/PyYAML-5.4.1/lib3/yaml/__init__.py
python
add_multi_representer
(data_type, multi_representer, Dumper=Dumper)
Add a representer for the given type. Multi-representer is a function accepting a Dumper instance and an instance of the given data type or subtype and producing the corresponding representation node.
Add a representer for the given type. Multi-representer is a function accepting a Dumper instance and an instance of the given data type or subtype and producing the corresponding representation node.
[ "Add", "a", "representer", "for", "the", "given", "type", ".", "Multi", "-", "representer", "is", "a", "function", "accepting", "a", "Dumper", "instance", "and", "an", "instance", "of", "the", "given", "data", "type", "or", "subtype", "and", "producing", "...
def add_multi_representer(data_type, multi_representer, Dumper=Dumper): """ Add a representer for the given type. Multi-representer is a function accepting a Dumper instance and an instance of the given data type or subtype and producing the corresponding representation node. """ Dumper.add_multi_representer(data_type, multi_representer)
[ "def", "add_multi_representer", "(", "data_type", ",", "multi_representer", ",", "Dumper", "=", "Dumper", ")", ":", "Dumper", ".", "add_multi_representer", "(", "data_type", ",", "multi_representer", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/PyYAML-5.4.1/lib3/yaml/__init__.py#L375-L382
sqlalchemy/sqlalchemy
eb716884a4abcabae84a6aaba105568e925b7d27
lib/sqlalchemy/sql/elements.py
python
literal
(value, type_=None)
return coercions.expect(roles.LiteralValueRole, value, type_=type_)
r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`_expression.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`_expression.ColumnElement` subclass, such as a :class:`~sqlalchemy.schema.Column` object. Use this function to force the generation of a literal clause, which will be created as a :class:`BindParameter` with a bound value. :param value: the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which will provide bind-parameter translation for this literal.
r"""Return a literal clause, bound to a bind parameter.
[ "r", "Return", "a", "literal", "clause", "bound", "to", "a", "bind", "parameter", "." ]
def literal(value, type_=None): r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`_expression.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`_expression.ColumnElement` subclass, such as a :class:`~sqlalchemy.schema.Column` object. Use this function to force the generation of a literal clause, which will be created as a :class:`BindParameter` with a bound value. :param value: the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which will provide bind-parameter translation for this literal. """ return coercions.expect(roles.LiteralValueRole, value, type_=type_)
[ "def", "literal", "(", "value", ",", "type_", "=", "None", ")", ":", "return", "coercions", ".", "expect", "(", "roles", ".", "LiteralValueRole", ",", "value", ",", "type_", "=", "type_", ")" ]
https://github.com/sqlalchemy/sqlalchemy/blob/eb716884a4abcabae84a6aaba105568e925b7d27/lib/sqlalchemy/sql/elements.py#L71-L90
luyishisi/Anti-Anti-Spider
dd9ed296fdf9e7efa7eaf4ef9b5eef52b5f7f864
原Anti-Anti-Spider/6.爬虫项目源码/11.百家号/id_to_excel/get_id_mysql.py
python
ConnectDB
()
return connect, cursor
Connect MySQLdb and Print version.
Connect MySQLdb and Print version.
[ "Connect", "MySQLdb", "and", "Print", "version", "." ]
def ConnectDB(): "Connect MySQLdb and Print version." connect, cursor = None, None count = 0 while True: try : connect = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DB, port = PORT, charset ='utf8') cursor = connect.cursor() break except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) count += 1 time.sleep(10) if count > 100: print 'error > 100 end' sys.exit(1) return connect, cursor
[ "def", "ConnectDB", "(", ")", ":", "connect", ",", "cursor", "=", "None", ",", "None", "count", "=", "0", "while", "True", ":", "try", ":", "connect", "=", "MySQLdb", ".", "connect", "(", "host", "=", "HOST", ",", "user", "=", "USER", ",", "passwd"...
https://github.com/luyishisi/Anti-Anti-Spider/blob/dd9ed296fdf9e7efa7eaf4ef9b5eef52b5f7f864/原Anti-Anti-Spider/6.爬虫项目源码/11.百家号/id_to_excel/get_id_mysql.py#L24-L40