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
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0009/remote.py
python
remote
(function_argument, public = True)
Decorator for methods which are remotely callable. This decorator works in conjunction with classes which extend ABC Endpoint. Example: @remote def remote_method(arg1, arg2) Arguments: function_argument -- a stand-in for either the actual method OR a new name (string) for the method. In that case the method is considered mapped: Example: @remote("new_name") def remote_method(arg1, arg2) public -- A flag which indicates if this method should be part of the known dictionary of remote methods. Defaults to True. Example: @remote(False) def remote_method(arg1, arg2) Note: renaming and revising (public vs. private) can be combined. Example: @remote("new_name", False) def remote_method(arg1, arg2)
Decorator for methods which are remotely callable. This decorator works in conjunction with classes which extend ABC Endpoint. Example:
[ "Decorator", "for", "methods", "which", "are", "remotely", "callable", ".", "This", "decorator", "works", "in", "conjunction", "with", "classes", "which", "extend", "ABC", "Endpoint", ".", "Example", ":" ]
def remote(function_argument, public = True): ''' Decorator for methods which are remotely callable. This decorator works in conjunction with classes which extend ABC Endpoint. Example: @remote def remote_method(arg1, arg2) Arguments: function_argument -- a stand-in for either the actual method OR a new name (string) for the method. In that case the method is considered mapped: Example: @remote("new_name") def remote_method(arg1, arg2) public -- A flag which indicates if this method should be part of the known dictionary of remote methods. Defaults to True. Example: @remote(False) def remote_method(arg1, arg2) Note: renaming and revising (public vs. private) can be combined. Example: @remote("new_name", False) def remote_method(arg1, arg2) ''' if hasattr(function_argument, '__call__'): return _intercept(function_argument, None, public) else: if not isinstance(function_argument, basestring): if not isinstance(function_argument, bool): raise Exception('Expected an RPC method name or visibility modifier!') else: def _wrap_revised(function): function = _intercept(function, None, function_argument) return function return _wrap_revised def _wrap_remapped(function): function = _intercept(function, function_argument, public) return function return _wrap_remapped
[ "def", "remote", "(", "function_argument", ",", "public", "=", "True", ")", ":", "if", "hasattr", "(", "function_argument", ",", "'__call__'", ")", ":", "return", "_intercept", "(", "function_argument", ",", "None", ",", "public", ")", "else", ":", "if", "...
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0009/remote.py#L37-L82
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/multiprocessing/managers.py
python
public_methods
(obj)
return [ name for name in all_methods(obj) if name[0] != '_' ]
Return a list of names of methods of `obj` which do not start with '_'
Return a list of names of methods of `obj` which do not start with '_'
[ "Return", "a", "list", "of", "names", "of", "methods", "of", "obj", "which", "do", "not", "start", "with", "_" ]
def public_methods(obj): """ Return a list of names of methods of `obj` which do not start with '_' """ return [ name for name in all_methods(obj) if name[0] != '_' ]
[ "def", "public_methods", "(", "obj", ")", ":", "return", "[", "name", "for", "name", "in", "all_methods", "(", "obj", ")", "if", "name", "[", "0", "]", "!=", "'_'", "]" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/multiprocessing/managers.py#L94-L98
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/locators.py
python
SimpleScrapingLocator._prepare_threads
(self)
Threads are created only when get_project is called, and terminate before it returns. They are there primarily to parallelise I/O (i.e. fetching web pages).
Threads are created only when get_project is called, and terminate before it returns. They are there primarily to parallelise I/O (i.e. fetching web pages).
[ "Threads", "are", "created", "only", "when", "get_project", "is", "called", "and", "terminate", "before", "it", "returns", ".", "They", "are", "there", "primarily", "to", "parallelise", "I", "/", "O", "(", "i", ".", "e", ".", "fetching", "web", "pages", ...
def _prepare_threads(self): """ Threads are created only when get_project is called, and terminate before it returns. They are there primarily to parallelise I/O (i.e. fetching web pages). """ self._threads = [] for i in range(self.num_workers): t = threading.Thread(target=self._fetch) t.setDaemon(True) t.start() self._threads.append(t)
[ "def", "_prepare_threads", "(", "self", ")", ":", "self", ".", "_threads", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "num_workers", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_fetch", ")", "t...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/locators.py#L611-L622
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/parser/template/nodes/xml.py
python
TemplateXMLNode._parse_attrib
(self, graph, expression, attrib_name)
[]
def _parse_attrib(self, graph, expression, attrib_name): attrib_value = expression.attrib[attrib_name] if "<" in attrib_value and ">" in attrib_value: start = attrib_value.find("<") end = attrib_value.rfind(">") front = attrib_value[:start] middle = attrib_value[start:end + 1] back = attrib_value[end + 1:] root = TemplateNode() root.append(TemplateWordNode(front)) xml = ET.fromstring(middle) xml_node = TemplateNode() graph.parse_tag_expression(xml, xml_node) root.append(xml_node) root.append(TemplateWordNode(back)) self.set_attrib(attrib_name, root) else: self.set_attrib(attrib_name, TemplateWordNode(attrib_value))
[ "def", "_parse_attrib", "(", "self", ",", "graph", ",", "expression", ",", "attrib_name", ")", ":", "attrib_value", "=", "expression", ".", "attrib", "[", "attrib_name", "]", "if", "\"<\"", "in", "attrib_value", "and", "\">\"", "in", "attrib_value", ":", "st...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/parser/template/nodes/xml.py#L86-L109
spotty-cloud/spotty
1127c56112b33ac4772582e4edb70e2dfa4292f0
spotty/deployment/abstract_docker_instance_manager.py
python
AbstractDockerInstanceManager.start_container
(self, output: AbstractOutputWriter, dry_run=False)
Starts or restarts container on the host OS.
Starts or restarts container on the host OS.
[ "Starts", "or", "restarts", "container", "on", "the", "host", "OS", "." ]
def start_container(self, output: AbstractOutputWriter, dry_run=False): """Starts or restarts container on the host OS.""" # make sure the Dockerfile exists self._check_dockerfile_exists() # sync the project with the instance try: self.sync(output, dry_run=dry_run) except NothingToDoError: pass # generate a script that starts container start_container_script = StartContainerScript(self.container_commands).render() start_container_command = get_script_command('start-container', start_container_script) # start the container exit_code = self.exec(start_container_command) if exit_code != 0: raise ValueError('Failed to start the container')
[ "def", "start_container", "(", "self", ",", "output", ":", "AbstractOutputWriter", ",", "dry_run", "=", "False", ")", ":", "# make sure the Dockerfile exists", "self", ".", "_check_dockerfile_exists", "(", ")", "# sync the project with the instance", "try", ":", "self",...
https://github.com/spotty-cloud/spotty/blob/1127c56112b33ac4772582e4edb70e2dfa4292f0/spotty/deployment/abstract_docker_instance_manager.py#L27-L45
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/lang/snowball/romanian.py
python
RomanianStemmer.stem
(self, word)
return word
Stem a Romanian word and return the stemmed form. :param word: The word that is stemmed. :type word: str or unicode :return: The stemmed form. :rtype: unicode
Stem a Romanian word and return the stemmed form.
[ "Stem", "a", "Romanian", "word", "and", "return", "the", "stemmed", "form", "." ]
def stem(self, word): """ Stem a Romanian word and return the stemmed form. :param word: The word that is stemmed. :type word: str or unicode :return: The stemmed form. :rtype: unicode """ word = word.lower() step1_success = False step2_success = False for i in range(1, len(word) - 1): if word[i - 1] in self.__vowels and word[i + 1] in self.__vowels: if word[i] == "u": word = "".join((word[:i], "U", word[i + 1:])) elif word[i] == "i": word = "".join((word[:i], "I", word[i + 1:])) r1, r2 = self._r1r2_standard(word, self.__vowels) rv = self._rv_standard(word, self.__vowels) # STEP 0: Removal of plurals and other simplifications for suffix in self.__step0_suffixes: if word.endswith(suffix): if suffix in r1: if suffix in ("ul", "ului"): word = word[:-len(suffix)] if suffix in rv: rv = rv[:-len(suffix)] else: rv = "" elif (suffix == "aua" or suffix == "atei" or (suffix == "ile" and word[-5:-3] != "ab")): word = word[:-2] elif suffix in ("ea", "ele", "elor"): word = "".join((word[:-len(suffix)], "e")) if suffix in rv: rv = "".join((rv[:-len(suffix)], "e")) else: rv = "" elif suffix in ("ii", "iua", "iei", "iile", "iilor", "ilor"): word = "".join((word[:-len(suffix)], "i")) if suffix in rv: rv = "".join((rv[:-len(suffix)], "i")) else: rv = "" elif suffix in ("a\u0163ie", "a\u0163ia"): word = word[:-1] break # STEP 1: Reduction of combining suffixes while True: replacement_done = False for suffix in self.__step1_suffixes: if word.endswith(suffix): if suffix in r1: step1_success = True replacement_done = True if suffix in ("abilitate", "abilitati", "abilit\u0103i", "abilit\u0103\u0163i"): word = "".join((word[:-len(suffix)], "abil")) elif suffix == "ibilitate": word = word[:-5] elif suffix in ("ivitate", "ivitati", "ivit\u0103i", "ivit\u0103\u0163i"): word = "".join((word[:-len(suffix)], "iv")) elif suffix in ("icitate", "icitati", "icit\u0103i", "icit\u0103\u0163i", "icator", "icatori", "iciv", "iciva", "icive", "icivi", "iciv\u0103", "ical", "icala", "icale", "icali", "ical\u0103"): word = "".join((word[:-len(suffix)], "ic")) elif suffix in ("ativ", "ativa", "ative", "ativi", "ativ\u0103", "a\u0163iune", "atoare", "ator", "atori", "\u0103toare", "\u0103tor", "\u0103tori"): word = "".join((word[:-len(suffix)], "at")) if suffix in r2: r2 = "".join((r2[:-len(suffix)], "at")) elif suffix in ("itiv", "itiva", "itive", "itivi", "itiv\u0103", "i\u0163iune", "itoare", "itor", "itori"): word = "".join((word[:-len(suffix)], "it")) if suffix in r2: r2 = "".join((r2[:-len(suffix)], "it")) else: step1_success = False break if not replacement_done: break # STEP 2: Removal of standard suffixes for suffix in self.__step2_suffixes: if word.endswith(suffix): if suffix in r2: step2_success = True if suffix in ("iune", "iuni"): if word[-5] == "\u0163": word = "".join((word[:-5], "t")) elif suffix in ("ism", "isme", "ist", "ista", "iste", "isti", "ist\u0103", "i\u015Fti"): word = "".join((word[:-len(suffix)], "ist")) else: word = word[:-len(suffix)] break # STEP 3: Removal of verb suffixes if not step1_success and not step2_success: for suffix in self.__step3_suffixes: try: if word.endswith(suffix): if suffix in rv: if suffix in (u('seser\u0103\u0163i'), u('seser\u0103m'), u('ser\u0103\u0163i'), u('sese\u015Fi'), u('seser\u0103'), u('ser\u0103m'), 'sesem', u('se\u015Fi'), u('ser\u0103'), 'sese', u('a\u0163i'), u('e\u0163i'), u('i\u0163i'), u('\xE2\u0163i'), 'sei', u('\u0103m'), 'em', 'im', '\xE2m', 'se'): word = word[:-len(suffix)] rv = rv[:-len(suffix)] else: if (not rv.startswith(suffix) and rv[rv.index(suffix) - 1] not in "aeio\u0103\xE2\xEE"): word = word[:-len(suffix)] break except UnicodeDecodeError: # The word is unicode, but suffix is not continue # STEP 4: Removal of final vowel for suffix in ("ie", "a", "e", "i", "\u0103"): if word.endswith(suffix): if suffix in rv: word = word[:-len(suffix)] break word = word.replace("I", "i").replace("U", "u") return word
[ "def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "step1_success", "=", "False", "step2_success", "=", "False", "for", "i", "in", "range", "(", "1", ",", "len", "(", "word", ")", "-", "1", ")", ":", ...
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/lang/snowball/romanian.py#L87-L257
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
scylla/datadog_checks/scylla/config_models/defaults.py
python
instance_auth_token
(field, value)
return get_default_field_value(field, value)
[]
def instance_auth_token(field, value): return get_default_field_value(field, value)
[ "def", "instance_auth_token", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/scylla/datadog_checks/scylla/config_models/defaults.py#L33-L34
dayorbyte/MongoAlchemy
e64ef0c87feff385637459707fe6090bd789e116
mongoalchemy/fields/fields.py
python
EnumField.__init__
(self, item_type, *values, **kwargs)
:param item_type: Instance of :class:`Field` to use for validation, and (un)wrapping :param values: Possible values. ``item_type.is_valid_wrap(value)`` should be ``True``
:param item_type: Instance of :class:`Field` to use for validation, and (un)wrapping :param values: Possible values. ``item_type.is_valid_wrap(value)`` should be ``True``
[ ":", "param", "item_type", ":", "Instance", "of", ":", "class", ":", "Field", "to", "use", "for", "validation", "and", "(", "un", ")", "wrapping", ":", "param", "values", ":", "Possible", "values", ".", "item_type", ".", "is_valid_wrap", "(", "value", ")...
def __init__(self, item_type, *values, **kwargs): ''' :param item_type: Instance of :class:`Field` to use for validation, and (un)wrapping :param values: Possible values. ``item_type.is_valid_wrap(value)`` should be ``True`` ''' super(EnumField, self).__init__(**kwargs) self.item_type = item_type self.values = values
[ "def", "__init__", "(", "self", ",", "item_type", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "super", "(", "EnumField", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "item_type", "=", "item_type", "self", ...
https://github.com/dayorbyte/MongoAlchemy/blob/e64ef0c87feff385637459707fe6090bd789e116/mongoalchemy/fields/fields.py#L318-L324
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/user/forms.py
python
ChangeUserDetailsForm.validate_avatar
(self, field)
[]
def validate_avatar(self, field): if field.data is not None: error, status = check_image(field.data) if error is not None: raise ValidationError(error) return status
[ "def", "validate_avatar", "(", "self", ",", "field", ")", ":", "if", "field", ".", "data", "is", "not", "None", ":", "error", ",", "status", "=", "check_image", "(", "field", ".", "data", ")", "if", "error", "is", "not", "None", ":", "raise", "Valida...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/user/forms.py#L114-L119
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/future/backports/email/message.py
python
Message.set_charset
(self, charset)
Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed.
Set the charset of the payload to a given character set.
[ "Set", "the", "charset", "of", "the", "payload", "to", "a", "given", "character", "set", "." ]
def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. """ if charset is None: self.del_param('charset') self._charset = None return if not isinstance(charset, Charset): charset = Charset(charset) self._charset = charset if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if charset != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
[ "def", "set_charset", "(", "self", ",", "charset", ")", ":", "if", "charset", "is", "None", ":", "self", ".", "del_param", "(", "'charset'", ")", "self", ".", "_charset", "=", "None", "return", "if", "not", "isinstance", "(", "charset", ",", "Charset", ...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/future/backports/email/message.py#L287-L323
sendgrid/sendgrid-python
df13b78b0cdcb410b4516f6761c4d3138edd4b2d
sendgrid/helpers/mail/personalization.py
python
Personalization.add_email
(self, email)
[]
def add_email(self, email): email_type = type(email) if email_type.__name__ == 'To': self.add_to(email) return if email_type.__name__ == 'Cc': self.add_cc(email) return if email_type.__name__ == 'Bcc': self.add_bcc(email) return if email_type.__name__ == 'From': self.from_email = email return raise ValueError('Please use a To, From, Cc or Bcc object.')
[ "def", "add_email", "(", "self", ",", "email", ")", ":", "email_type", "=", "type", "(", "email", ")", "if", "email_type", ".", "__name__", "==", "'To'", ":", "self", ".", "add_to", "(", "email", ")", "return", "if", "email_type", ".", "__name__", "=="...
https://github.com/sendgrid/sendgrid-python/blob/df13b78b0cdcb410b4516f6761c4d3138edd4b2d/sendgrid/helpers/mail/personalization.py#L19-L33
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/geometry/manipulation_shapes/equation.py
python
getManipulatedPaths
(close, elementNode, loop, prefix, sideLength)
return [loop]
Get equated paths.
Get equated paths.
[ "Get", "equated", "paths", "." ]
def getManipulatedPaths(close, elementNode, loop, prefix, sideLength): "Get equated paths." equatePoints(elementNode, loop, prefix, 0.0) return [loop]
[ "def", "getManipulatedPaths", "(", "close", ",", "elementNode", ",", "loop", ",", "prefix", ",", "sideLength", ")", ":", "equatePoints", "(", "elementNode", ",", "loop", ",", "prefix", ",", "0.0", ")", "return", "[", "loop", "]" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/manipulation_shapes/equation.py#L59-L62
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/authkerb.py
python
BasicKerberosCredentialFactory.__init__
(self, principal=None, serviceType=None, hostname=None)
@param principal: full Kerberos principal (e.g., 'HTTP/server.example.com@EXAMPLE.COM'). If C{None} then the type and hostname arguments are used instead. @type principal: str @param serviceType: service type for Kerberos (e.g., 'HTTP'). Must be C{None} if principal used. @type serviceType: str @param hostname: hostname for this server. Must be C{None} if principal used. @type hostname: str
[]
def __init__(self, principal=None, serviceType=None, hostname=None): """ @param principal: full Kerberos principal (e.g., 'HTTP/server.example.com@EXAMPLE.COM'). If C{None} then the type and hostname arguments are used instead. @type principal: str @param serviceType: service type for Kerberos (e.g., 'HTTP'). Must be C{None} if principal used. @type serviceType: str @param hostname: hostname for this server. Must be C{None} if principal used. @type hostname: str """ super(BasicKerberosCredentialFactory, self).__init__(principal, serviceType, hostname)
[ "def", "__init__", "(", "self", ",", "principal", "=", "None", ",", "serviceType", "=", "None", ",", "hostname", "=", "None", ")", ":", "super", "(", "BasicKerberosCredentialFactory", ",", "self", ")", ".", "__init__", "(", "principal", ",", "serviceType", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/authkerb.py#L138-L150
polyaxon/polyaxon
e28d82051c2b61a84d06ce4d2388a40fc8565469
src/core/polyaxon/config_reader/manager.py
python
ConfigManager.get_auth
( self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None, )
return self._get( key=key, parser_fct=parser.get_auth, is_list=is_list, is_optional=is_optional, is_secret=is_secret, is_local=is_local, default=default, options=options, )
Get the value corresponding to the key and converts it to `V1AuthType`. Args key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. is_secret: If the key is a secret. is_local: If the key is a local to this service. default: default value if is_optional is True. options: list/tuple if provided, the value must be one of these values. Returns: `str`: value corresponding to the key.
Get the value corresponding to the key and converts it to `V1AuthType`.
[ "Get", "the", "value", "corresponding", "to", "the", "key", "and", "converts", "it", "to", "V1AuthType", "." ]
def get_auth( self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None, ) -> V1AuthType: """ Get the value corresponding to the key and converts it to `V1AuthType`. Args key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. is_secret: If the key is a secret. is_local: If the key is a local to this service. default: default value if is_optional is True. options: list/tuple if provided, the value must be one of these values. Returns: `str`: value corresponding to the key. """ return self._get( key=key, parser_fct=parser.get_auth, is_list=is_list, is_optional=is_optional, is_secret=is_secret, is_local=is_local, default=default, options=options, )
[ "def", "get_auth", "(", "self", ",", "key", ",", "is_list", "=", "False", ",", "is_optional", "=", "False", ",", "is_secret", "=", "False", ",", "is_local", "=", "False", ",", "default", "=", "None", ",", "options", "=", "None", ",", ")", "->", "V1Au...
https://github.com/polyaxon/polyaxon/blob/e28d82051c2b61a84d06ce4d2388a40fc8565469/src/core/polyaxon/config_reader/manager.py#L329-L363
Karmenzind/fp-server
931fca8fab9d7397c52cf9e76a76b1c60e190403
src/core/web.py
python
WebHandler.do_complete
(self)
wind up * may add calculation or logging here
wind up * may add calculation or logging here
[ "wind", "up", "*", "may", "add", "calculation", "or", "logging", "here" ]
async def do_complete(self): """ wind up * may add calculation or logging here """ middlewares = options.middlewares for m in middlewares: await m.finish(self)
[ "async", "def", "do_complete", "(", "self", ")", ":", "middlewares", "=", "options", ".", "middlewares", "for", "m", "in", "middlewares", ":", "await", "m", ".", "finish", "(", "self", ")" ]
https://github.com/Karmenzind/fp-server/blob/931fca8fab9d7397c52cf9e76a76b1c60e190403/src/core/web.py#L192-L199
PlasmaPy/PlasmaPy
78d63e341216475ce3318e1409296480407c9019
plasmapy/particles/ionization_state.py
python
IonizationState.kappa
(self, value: Real)
Set the kappa parameter for a kappa distribution function for electrons. The value must be between ``1.5`` and `~numpy.inf`.
Set the kappa parameter for a kappa distribution function for electrons. The value must be between ``1.5`` and `~numpy.inf`.
[ "Set", "the", "kappa", "parameter", "for", "a", "kappa", "distribution", "function", "for", "electrons", ".", "The", "value", "must", "be", "between", "1", ".", "5", "and", "~numpy", ".", "inf", "." ]
def kappa(self, value: Real): """ Set the kappa parameter for a kappa distribution function for electrons. The value must be between ``1.5`` and `~numpy.inf`. """ kappa_errmsg = "kappa must be a real number greater than 1.5" if not isinstance(value, Real): raise TypeError(kappa_errmsg) if value <= 1.5: raise ValueError(kappa_errmsg) self._kappa = np.real(value)
[ "def", "kappa", "(", "self", ",", "value", ":", "Real", ")", ":", "kappa_errmsg", "=", "\"kappa must be a real number greater than 1.5\"", "if", "not", "isinstance", "(", "value", ",", "Real", ")", ":", "raise", "TypeError", "(", "kappa_errmsg", ")", "if", "va...
https://github.com/PlasmaPy/PlasmaPy/blob/78d63e341216475ce3318e1409296480407c9019/plasmapy/particles/ionization_state.py#L684-L694
facebookresearch/pyrobot
27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f
src/pyrobot/locobot/camera.py
python
SimpleCamera.get_link_transform
(self, src, tgt)
return trans, rot, T
Returns the latest transformation from the target_frame to the source frame, i.e., the transform of source frame w.r.t target frame. If the returned transform is applied to data, it will transform data in the source_frame into the target_frame For more information, please refer to http://wiki.ros.org/tf/Overview/Using%20Published%20Transforms :param src: source frame :param tgt: target frame :type src: string :type tgt: string :returns: tuple(trans, rot, T) trans: translational vector (shape: :math:`[3,]`) rot: rotation matrix (shape: :math:`[3, 3]`) T: transofrmation matrix (shape: :math:`[4, 4]`) :rtype: tuple(np.ndarray, np.ndarray, np.ndarray)
Returns the latest transformation from the target_frame to the source frame, i.e., the transform of source frame w.r.t target frame. If the returned transform is applied to data, it will transform data in the source_frame into the target_frame
[ "Returns", "the", "latest", "transformation", "from", "the", "target_frame", "to", "the", "source", "frame", "i", ".", "e", ".", "the", "transform", "of", "source", "frame", "w", ".", "r", ".", "t", "target", "frame", ".", "If", "the", "returned", "trans...
def get_link_transform(self, src, tgt): """ Returns the latest transformation from the target_frame to the source frame, i.e., the transform of source frame w.r.t target frame. If the returned transform is applied to data, it will transform data in the source_frame into the target_frame For more information, please refer to http://wiki.ros.org/tf/Overview/Using%20Published%20Transforms :param src: source frame :param tgt: target frame :type src: string :type tgt: string :returns: tuple(trans, rot, T) trans: translational vector (shape: :math:`[3,]`) rot: rotation matrix (shape: :math:`[3, 3]`) T: transofrmation matrix (shape: :math:`[4, 4]`) :rtype: tuple(np.ndarray, np.ndarray, np.ndarray) """ trans, quat = prutil.get_tf_transform(self._tf_listener, tgt, src) rot = prutil.quat_to_rot_mat(quat) T = np.eye(4) T[:3, :3] = rot T[:3, 3] = trans return trans, rot, T
[ "def", "get_link_transform", "(", "self", ",", "src", ",", "tgt", ")", ":", "trans", ",", "quat", "=", "prutil", ".", "get_tf_transform", "(", "self", ".", "_tf_listener", ",", "tgt", ",", "src", ")", "rot", "=", "prutil", ".", "quat_to_rot_mat", "(", ...
https://github.com/facebookresearch/pyrobot/blob/27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f/src/pyrobot/locobot/camera.py#L139-L171
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/Crypto/Random/random.py
python
StrongRandom.choice
(self, seq)
return seq[self.randrange(len(seq))]
Return a random element from a (non-empty) sequence. If the seqence is empty, raises IndexError.
Return a random element from a (non-empty) sequence.
[ "Return", "a", "random", "element", "from", "a", "(", "non", "-", "empty", ")", "sequence", "." ]
def choice(self, seq): """Return a random element from a (non-empty) sequence. If the seqence is empty, raises IndexError. """ if len(seq) == 0: raise IndexError("empty sequence") return seq[self.randrange(len(seq))]
[ "def", "choice", "(", "self", ",", "seq", ")", ":", "if", "len", "(", "seq", ")", "==", "0", ":", "raise", "IndexError", "(", "\"empty sequence\"", ")", "return", "seq", "[", "self", ".", "randrange", "(", "len", "(", "seq", ")", ")", "]" ]
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/Crypto/Random/random.py#L95-L102
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/cui/settings.py
python
PhonopyConfParser._set_settings
(self)
[]
def _set_settings(self): self.set_settings() params = self._parameters # Create FORCE_SETS if "create_force_sets" in params: self._settings.set_create_force_sets(params["create_force_sets"]) if "create_force_sets_zero" in params: self._settings.set_create_force_sets_zero(params["create_force_sets_zero"]) if "create_force_constants" in params: self._settings.set_create_force_constants(params["create_force_constants"]) # Is force constants written or read? if "force_constants" in params: if params["force_constants"] == "write": self._settings.set_write_force_constants(True) elif params["force_constants"] == "read": self._settings.set_read_force_constants(True) if "read_force_constants" in params: self._settings.set_read_force_constants(params["read_force_constants"]) if "write_force_constants" in params: self._settings.set_write_force_constants(params["write_force_constants"]) if "is_full_fc" in params: self._settings.set_is_full_fc(params["is_full_fc"]) # Enforce space group symmetyr to force constants? if "fc_spg_symmetry" in params: self._settings.set_fc_spg_symmetry(params["fc_spg_symmetry"]) if "readfc_format" in params: self._settings.set_readfc_format(params["readfc_format"]) if "writefc_format" in params: self._settings.set_writefc_format(params["writefc_format"]) # Use hdf5? if "hdf5" in params: self._settings.set_is_hdf5(params["hdf5"]) # Cutoff radius of force constants if "cutoff_radius" in params: self._settings.set_cutoff_radius(params["cutoff_radius"]) # Mesh if "mesh_numbers" in params: self._settings.set_run_mode("mesh") self._settings.set_mesh_numbers(params["mesh_numbers"]) if "mp_shift" in params: self._settings.set_mesh_shift(params["mp_shift"]) if "is_time_reversal_symmetry" in params: self._settings.set_is_time_reversal_symmetry( params["is_time_reversal_symmetry"] ) if "is_mesh_symmetry" in params: self._settings.set_is_mesh_symmetry(params["is_mesh_symmetry"]) if "is_gamma_center" in params: self._settings.set_is_gamma_center(params["is_gamma_center"]) if "mesh_format" in params: self._settings.set_mesh_format(params["mesh_format"]) # band mode if "band_paths" in params: self._settings.set_run_mode("band") if "band_format" in params: self._settings.set_band_format(params["band_format"]) if "band_labels" in params: self._settings.set_band_labels(params["band_labels"]) if "band_connection" in params: self._settings.set_is_band_connection(params["band_connection"]) if "legacy_plot" in params: self._settings.set_is_legacy_plot(params["legacy_plot"]) # Q-points mode if "qpoints" in params or "read_qpoints" in params: self._settings.set_run_mode("qpoints") if self._settings.run_mode == "qpoints": if "qpoints_format" in params: self._settings.set_qpoints_format(params["qpoints_format"]) # Whether write out dynamical matrices or not if "write_dynamical_matrices" in params: self._settings.set_write_dynamical_matrices( params["write_dynamical_matrices"] ) # Whether write out mesh.yaml or mesh.hdf5 if "write_mesh" in params: self._settings.set_write_mesh(params["write_mesh"]) # Anime mode if "anime_type" in params: self._settings.set_anime_type(params["anime_type"]) if "anime" in params: self._settings.set_run_mode("anime") anime_type = self._settings.anime_type if anime_type == "v_sim": qpoints = [fracval(x) for x in params["anime"][0:3]] self._settings.set_anime_qpoint(qpoints) if len(params["anime"]) > 3: self._settings.set_anime_amplitude(float(params["anime"][3])) else: self._settings.set_anime_band_index(int(params["anime"][0])) self._settings.set_anime_amplitude(float(params["anime"][1])) self._settings.set_anime_division(int(params["anime"][2])) if len(params["anime"]) == 6: self._settings.set_anime_shift( [fracval(x) for x in params["anime"][3:6]] ) # Modulation mode if "modulation" in params: self._settings.set_run_mode("modulation") self._settings.set_modulation(params["modulation"]) # Character table mode if "irreps_qpoint" in params: self._settings.set_run_mode("irreps") self._settings.set_irreps_q_point(params["irreps_qpoint"][:3]) if len(params["irreps_qpoint"]) == 4: self._settings.set_irreps_tolerance(params["irreps_qpoint"][3]) if "show_irreps" in params: self._settings.set_show_irreps(params["show_irreps"]) if "little_cogroup" in params: self._settings.set_is_little_cogroup(params["little_cogroup"]) # DOS if "dos_range" in params: fmin = params["dos_range"][0] fmax = params["dos_range"][1] fpitch = params["dos_range"][2] self._settings.set_min_frequency(fmin) self._settings.set_max_frequency(fmax) self._settings.set_frequency_pitch(fpitch) if "dos" in params: self._settings.set_is_dos_mode(params["dos"]) if "fits_debye_model" in params: self._settings.set_fits_Debye_model(params["fits_debye_model"]) if "fmax" in params: self._settings.set_max_frequency(params["fmax"]) if "fmin" in params: self._settings.set_min_frequency(params["fmin"]) # Project PDOS x, y, z directions in Cartesian coordinates if "xyz_projection" in params: self._settings.set_xyz_projection(params["xyz_projection"]) if "pdos" not in params and self._settings.pdos_indices is None: self.set_parameter("pdos", []) if "pdos" in params: self._settings.set_pdos_indices(params["pdos"]) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) if "projection_direction" in params and not self._settings.xyz_projection: self._settings.set_projection_direction(params["projection_direction"]) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) # Thermal properties if "tprop" in params: self._settings.set_is_thermal_properties(params["tprop"]) # Exclusive conditions self._settings.set_is_thermal_displacements(False) self._settings.set_is_thermal_displacement_matrices(False) self._settings.set_is_thermal_distances(False) # Projected thermal properties if "ptprop" in params and params["ptprop"]: self._settings.set_is_thermal_properties(True) self._settings.set_is_projected_thermal_properties(True) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) # Exclusive conditions self._settings.set_is_thermal_displacements(False) self._settings.set_is_thermal_displacement_matrices(False) self._settings.set_is_thermal_distances(False) # Use imaginary frequency as real for thermal property calculation if "pretend_real" in params: self._settings.set_pretend_real(params["pretend_real"]) # Thermal displacements if "tdisp" in params and params["tdisp"]: self._settings.set_is_thermal_displacements(True) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) # Exclusive conditions self._settings.set_is_thermal_properties(False) self._settings.set_is_thermal_displacement_matrices(False) self._settings.set_is_thermal_distances(True) # Thermal displacement matrices if "tdispmat" in params and params["tdispmat"] or "tdispmat_cif" in params: self._settings.set_is_thermal_displacement_matrices(True) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) # Exclusive conditions self._settings.set_is_thermal_properties(False) self._settings.set_is_thermal_displacements(False) self._settings.set_is_thermal_distances(False) # Temperature used to calculate thermal displacement matrix # to write aniso_U to cif if "tdispmat_cif" in params: self._settings.set_thermal_displacement_matrix_temperature( params["tdispmat_cif"] ) # Thermal distances if "tdistance" in params: self._settings.set_is_thermal_distances(True) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) self._settings.set_thermal_atom_pairs(params["tdistance"]) # Exclusive conditions self._settings.set_is_thermal_properties(False) self._settings.set_is_thermal_displacements(False) self._settings.set_is_thermal_displacement_matrices(False) # Group velocity if "is_group_velocity" in params: self._settings.set_is_group_velocity(params["is_group_velocity"]) # Moment mode if "moment" in params: self._settings.set_is_moment(params["moment"]) self._settings.set_is_eigenvectors(True) self._settings.set_is_mesh_symmetry(False) if self._settings.is_moment: if "moment_order" in params: self._settings.set_moment_order(params["moment_order"]) # Number of supercells with random displacements if "random_displacements" in params: self._settings.set_random_displacements(params["random_displacements"]) if "random_seed" in params: self._settings.set_random_seed(params["random_seed"]) # Use Lapack solver via Lapacke if "lapack_solver" in params: self._settings.set_lapack_solver(params["lapack_solver"]) # Select yaml summary contents if "save_params" in params: self._settings.set_save_params(params["save_params"]) if "include_fc" in params: self._settings.set_include_force_constants(params["include_fc"]) if "include_fs" in params: self._settings.set_include_force_sets(params["include_fs"]) if "include_nac_params" in params: self._settings.set_include_nac_params(params["include_nac_params"]) if "include_disp" in params: self._settings.set_include_displacements(params["include_disp"]) if "include_all" in params: self._settings.set_include_force_constants(True) self._settings.set_include_force_sets(True) self._settings.set_include_nac_params(True) self._settings.set_include_displacements(True) # Pair shortest vectors in supercell are stored in dense format. if "store_dense_svecs" in params: self._settings.set_store_dense_svecs(params["store_dense_svecs"]) # *********************************************************** # This has to come last in this method to overwrite run_mode. # *********************************************************** if "pdos" in params and params["pdos"] == "auto": if "band_paths" in params: self._settings.set_run_mode("band_mesh") else: self._settings.set_run_mode("mesh") if "mesh_numbers" in params and "band_paths" in params: self._settings.set_run_mode("band_mesh")
[ "def", "_set_settings", "(", "self", ")", ":", "self", ".", "set_settings", "(", ")", "params", "=", "self", ".", "_parameters", "# Create FORCE_SETS", "if", "\"create_force_sets\"", "in", "params", ":", "self", ".", "_settings", ".", "set_create_force_sets", "(...
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/cui/settings.py#L2104-L2393
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_gcloud/library/gcloud_dm_resource_builder.py
python
GcloudCLI._list_manifests
(self, deployment, mname=None)
return self.gcloud_cmd(cmd, output=True, output_type='json')
list manifests if a name is specified then perform a describe
list manifests if a name is specified then perform a describe
[ "list", "manifests", "if", "a", "name", "is", "specified", "then", "perform", "a", "describe" ]
def _list_manifests(self, deployment, mname=None): ''' list manifests if a name is specified then perform a describe ''' cmd = ['deployment-manager', 'manifests', '--deployment', deployment] if mname: cmd.extend(['describe', mname]) else: cmd.append('list') cmd.extend(['--format', 'json']) return self.gcloud_cmd(cmd, output=True, output_type='json')
[ "def", "_list_manifests", "(", "self", ",", "deployment", ",", "mname", "=", "None", ")", ":", "cmd", "=", "[", "'deployment-manager'", ",", "'manifests'", ",", "'--deployment'", ",", "deployment", "]", "if", "mname", ":", "cmd", ".", "extend", "(", "[", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_gcloud/library/gcloud_dm_resource_builder.py#L143-L155
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
medusa/clients/torrent/rtorrent.py
python
RTorrentAPI.test_authentication
(self)
Test connection using authentication. :return: :rtype: tuple(bool, str)
Test connection using authentication.
[ "Test", "connection", "using", "authentication", "." ]
def test_authentication(self): """Test connection using authentication. :return: :rtype: tuple(bool, str) """ try: self.auth = None self._get_auth() except Exception: return False, f'Error: Unable to connect to {self.name}' else: if self.auth is None: return False, f'Error: Unable to get {self.name} Authentication, check your config!' else: return True, 'Success: Connected and Authenticated'
[ "def", "test_authentication", "(", "self", ")", ":", "try", ":", "self", ".", "auth", "=", "None", "self", ".", "_get_auth", "(", ")", "except", "Exception", ":", "return", "False", ",", "f'Error: Unable to connect to {self.name}'", "else", ":", "if", "self", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/clients/torrent/rtorrent.py#L127-L142
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/AutoCompleteWindow.py
python
AutoCompleteWindow._binary_search
(self, s)
return min(i, len(self.completions)-1)
Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such one.
Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such one.
[ "Find", "the", "first", "index", "in", "self", ".", "completions", "where", "completions", "[", "i", "]", "is", "greater", "or", "equal", "to", "s", "or", "the", "last", "index", "if", "there", "is", "no", "such", "one", "." ]
def _binary_search(self, s): """Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such one.""" i = 0; j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m] >= s: j = m else: i = m + 1 return min(i, len(self.completions)-1)
[ "def", "_binary_search", "(", "self", ",", "s", ")", ":", "i", "=", "0", "j", "=", "len", "(", "self", ".", "completions", ")", "while", "j", ">", "i", ":", "m", "=", "(", "i", "+", "j", ")", "//", "2", "if", "self", ".", "completions", "[", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/AutoCompleteWindow.py#L69-L80
viblo/pymunk
77647ca037d5ceabd728f20f37d2da8a3bfb73a0
pymunk/vec2d.py
python
Vec2d.rotated
(self, angle_radians: float)
return Vec2d(x, y)
Create and return a new vector by rotating this vector by angle_radians radians. :return: Rotated vector
Create and return a new vector by rotating this vector by angle_radians radians.
[ "Create", "and", "return", "a", "new", "vector", "by", "rotating", "this", "vector", "by", "angle_radians", "radians", "." ]
def rotated(self, angle_radians: float) -> "Vec2d": """Create and return a new vector by rotating this vector by angle_radians radians. :return: Rotated vector """ cos = math.cos(angle_radians) sin = math.sin(angle_radians) x = self.x * cos - self.y * sin y = self.x * sin + self.y * cos return Vec2d(x, y)
[ "def", "rotated", "(", "self", ",", "angle_radians", ":", "float", ")", "->", "\"Vec2d\"", ":", "cos", "=", "math", ".", "cos", "(", "angle_radians", ")", "sin", "=", "math", ".", "sin", "(", "angle_radians", ")", "x", "=", "self", ".", "x", "*", "...
https://github.com/viblo/pymunk/blob/77647ca037d5ceabd728f20f37d2da8a3bfb73a0/pymunk/vec2d.py#L218-L228
celiao/tmdbsimple
2c046367866667102b78247db708c0ac275f805d
tmdbsimple/genres.py
python
Genres.movie_list
(self, **kwargs)
return response
Get the list of official genres for movies. Args: language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API.
Get the list of official genres for movies.
[ "Get", "the", "list", "of", "official", "genres", "for", "movies", "." ]
def movie_list(self, **kwargs): """ Get the list of official genres for movies. Args: language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('movie_list') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
[ "def", "movie_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'movie_list'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "resp...
https://github.com/celiao/tmdbsimple/blob/2c046367866667102b78247db708c0ac275f805d/tmdbsimple/genres.py#L34-L48
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/gdb/libpython.py
python
PyObjectPtr.as_address
(self)
return long(self._gdbval)
[]
def as_address(self): return long(self._gdbval)
[ "def", "as_address", "(", "self", ")", ":", "return", "long", "(", "self", ".", "_gdbval", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/gdb/libpython.py#L388-L389
asweigart/PythonStdioGames
8bdabf93e6b1bb6af3e26fea24da93f85e8314b6
src/gamesbyexample/guillotine.py
python
getPlayerGuess
(alreadyGuessed)
Returns the letter the player entered. This function makes sure the player entered a single letter they haven't guessed before.
Returns the letter the player entered. This function makes sure the player entered a single letter they haven't guessed before.
[ "Returns", "the", "letter", "the", "player", "entered", ".", "This", "function", "makes", "sure", "the", "player", "entered", "a", "single", "letter", "they", "haven", "t", "guessed", "before", "." ]
def getPlayerGuess(alreadyGuessed): """Returns the letter the player entered. This function makes sure the player entered a single letter they haven't guessed before.""" while True: # Keep asking until the player enters a valid letter. print('Guess a letter.') guess = input('> ') guess = guess.upper() if len(guess) != 1: print('Please enter a single letter.') elif guess in alreadyGuessed: print('You have already guessed that letter. Choose again.') elif guess not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': print('Please enter a LETTER.') else: return guess
[ "def", "getPlayerGuess", "(", "alreadyGuessed", ")", ":", "while", "True", ":", "# Keep asking until the player enters a valid letter.", "print", "(", "'Guess a letter.'", ")", "guess", "=", "input", "(", "'> '", ")", "guess", "=", "guess", ".", "upper", "(", ")",...
https://github.com/asweigart/PythonStdioGames/blob/8bdabf93e6b1bb6af3e26fea24da93f85e8314b6/src/gamesbyexample/guillotine.py#L144-L158
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/db/sqlalchemy/api.py
python
_filter_host
(field, value, match_level=None)
return or_(*conditions)
Generate a filter condition for host and cluster fields. Levels are: - 'pool': Will search for an exact match - 'backend': Will search for exact match and value#* - 'host'; Will search for exact match, value@* and value#* If no level is provided we'll determine it based on the value we want to match: - 'pool': If '#' is present in value - 'backend': If '@' is present in value and '#' is not present - 'host': In any other case :param field: ORM field. Ex: objects.Volume.model.host :param value: String to compare with :param match_level: 'pool', 'backend', or 'host'
Generate a filter condition for host and cluster fields.
[ "Generate", "a", "filter", "condition", "for", "host", "and", "cluster", "fields", "." ]
def _filter_host(field, value, match_level=None): """Generate a filter condition for host and cluster fields. Levels are: - 'pool': Will search for an exact match - 'backend': Will search for exact match and value#* - 'host'; Will search for exact match, value@* and value#* If no level is provided we'll determine it based on the value we want to match: - 'pool': If '#' is present in value - 'backend': If '@' is present in value and '#' is not present - 'host': In any other case :param field: ORM field. Ex: objects.Volume.model.host :param value: String to compare with :param match_level: 'pool', 'backend', or 'host' """ # If we don't set level we'll try to determine it automatically. LIKE # operations are expensive, so we try to reduce them to the minimum. if match_level is None: if '#' in value: match_level = 'pool' elif '@' in value: match_level = 'backend' else: match_level = 'host' # Mysql is not doing case sensitive filtering, so we force it conn_str = CONF.database.connection if conn_str.startswith('mysql') and conn_str[5] in ['+', ':']: cmp_value = func.binary(value) like_op = 'LIKE BINARY' else: cmp_value = value like_op = 'LIKE' conditions = [field == cmp_value] if match_level != 'pool': conditions.append(field.op(like_op)(value + '#%')) if match_level == 'host': conditions.append(field.op(like_op)(value + '@%')) return or_(*conditions)
[ "def", "_filter_host", "(", "field", ",", "value", ",", "match_level", "=", "None", ")", ":", "# If we don't set level we'll try to determine it automatically. LIKE", "# operations are expensive, so we try to reduce them to the minimum.", "if", "match_level", "is", "None", ":", ...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/db/sqlalchemy/api.py#L372-L415
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/core/driver.py
python
RecordingDebugging.__exit__
(self, *args)
Do things after the code inside the 'with RecordingDebugging' block. Parameters ---------- *args : array Solver recording requires extra args.
Do things after the code inside the 'with RecordingDebugging' block.
[ "Do", "things", "after", "the", "code", "inside", "the", "with", "RecordingDebugging", "block", "." ]
def __exit__(self, *args): """ Do things after the code inside the 'with RecordingDebugging' block. Parameters ---------- *args : array Solver recording requires extra args. """ self.recording_requester()._post_run_model_debug_print() super().__exit__()
[ "def", "__exit__", "(", "self", ",", "*", "args", ")", ":", "self", ".", "recording_requester", "(", ")", ".", "_post_run_model_debug_print", "(", ")", "super", "(", ")", ".", "__exit__", "(", ")" ]
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/core/driver.py#L1235-L1245
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/manageorg/_content.py
python
Item.listed
(self)
return self._listed
gets the property value for listed
gets the property value for listed
[ "gets", "the", "property", "value", "for", "listed" ]
def listed(self): '''gets the property value for listed''' if self._listed is None: self.__init() return self._listed
[ "def", "listed", "(", "self", ")", ":", "if", "self", ".", "_listed", "is", "None", ":", "self", ".", "__init", "(", ")", "return", "self", ".", "_listed" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_content.py#L471-L475
amanusk/s-tui
d7a9ee4efbfc6f56b373a16dcd578881c534b2ce
s_tui/helper_functions.py
python
str_to_bool
(string)
Converts a string to a boolean
Converts a string to a boolean
[ "Converts", "a", "string", "to", "a", "boolean" ]
def str_to_bool(string): """ Converts a string to a boolean """ if string == 'True': return True if string == 'False': return False raise ValueError
[ "def", "str_to_bool", "(", "string", ")", ":", "if", "string", "==", "'True'", ":", "return", "True", "if", "string", "==", "'False'", ":", "return", "False", "raise", "ValueError" ]
https://github.com/amanusk/s-tui/blob/d7a9ee4efbfc6f56b373a16dcd578881c534b2ce/s_tui/helper_functions.py#L230-L236
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/core/layers.py
python
BaseConv2DLayer._GetWeights
(self, theta, convolution_lambda, folded_bn_padding, cast_dtype=None)
return filter_w, b
Gets a dictionary of weights and biases for the convolution. This is necessary for some operating modes where the weights are fused with batch normalization differently for training vs eval. Args: theta: A `.NestedMap` object containing underlying weights values of this layer and its children layers. convolution_lambda: Lambda which takes the convolution weights and runs the convolution. folded_bn_padding: Padding to apply to folded batch normalization moment computation (or None for no padding). cast_dtype: If not None, cast weights to the given dtype. Returns: Tuple of (filter, biases).
Gets a dictionary of weights and biases for the convolution.
[ "Gets", "a", "dictionary", "of", "weights", "and", "biases", "for", "the", "convolution", "." ]
def _GetWeights(self, theta, convolution_lambda, folded_bn_padding, cast_dtype=None): """Gets a dictionary of weights and biases for the convolution. This is necessary for some operating modes where the weights are fused with batch normalization differently for training vs eval. Args: theta: A `.NestedMap` object containing underlying weights values of this layer and its children layers. convolution_lambda: Lambda which takes the convolution weights and runs the convolution. folded_bn_padding: Padding to apply to folded batch normalization moment computation (or None for no padding). cast_dtype: If not None, cast weights to the given dtype. Returns: Tuple of (filter, biases). """ p = self.params # Original weights. filter_w = theta.w filter_output_shape = self.filter_output_shape # TODO(miachen): remove casting once tf.nn.conv2d supports tf.float64. if cast_dtype: filter_w = tf.cast(filter_w, tf.float32) if p.weight_norm: if len(filter_output_shape) == 1: # Normalize along the last dim (standard conv). filter_w = tf.nn.l2_normalize(filter_w, [0, 1, 2]) * tf.reshape( (theta.g + 1.0), [1, 1, 1, p.filter_shape[-1]]) elif len(filter_output_shape) == 2: # Normalize along the last two dimensions (depthwise conv). filter_w = tf.nn.l2_normalize(filter_w, [0, 1]) * tf.reshape( (theta.g + 1.0), [1, 1] + filter_output_shape) else: assert False, 'Unsupported weight norm filter shape' # Original bias. if p.bias: b = theta.b else: b = tf.zeros([symbolic.ToStatic(self.output_channels)], dtype=filter_w.dtype) # Pass-through if weights are not folded with batch normalization. if not self._is_bn_folded: return filter_w, b # If batch norm is fused with weights, then compute the weights as from # figure C.8 of https://arxiv.org/pdf/1712.05877.pdf for training and # figure C.6 for eval. if self.do_eval: # Gets current moments without updating. mean, variance, beta, gamma = self.bn.GetCurrentMoments(theta.bn) else: # Updates moments based on a trial run of the convolution. raw_conv_output = convolution_lambda(filter_w) mean, variance, beta, gamma = self.bn.ComputeAndUpdateMoments( theta.bn, raw_conv_output, folded_bn_padding) # Fold weights and bias. Note that this layer's bias is not used (not # applicable for batch norm case). sigma_recip = tf.math.rsqrt(variance + self.bn.epsilon) scale_correction = gamma * sigma_recip # Normal conv will have all weights in the last dim # ([_, _, _, output_channels]), which matches the 1D layout from # batch norm. Depthwise uses the last two dims so reshape # ([_, _, in_c, c_multiplier]). scale_correction = tf.reshape(scale_correction, filter_output_shape) filter_w = filter_w * scale_correction b = (beta - (gamma * mean * sigma_recip)) return filter_w, b
[ "def", "_GetWeights", "(", "self", ",", "theta", ",", "convolution_lambda", ",", "folded_bn_padding", ",", "cast_dtype", "=", "None", ")", ":", "p", "=", "self", ".", "params", "# Original weights.", "filter_w", "=", "theta", ".", "w", "filter_output_shape", "...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/core/layers.py#L379-L455
omergertel/pyformance
b71056eaf9af6cafd3e3c4a416412ae425bdc82e
pyformance/stats/moving_average.py
python
ExpWeightedMovingAvg.get_rate
(self)
return 0
[]
def get_rate(self): if self.clock.time() - self.last_tick >= self.interval: self.tick() if self.rate >= 0: return self.rate return 0
[ "def", "get_rate", "(", "self", ")", ":", "if", "self", ".", "clock", ".", "time", "(", ")", "-", "self", ".", "last_tick", ">=", "self", ".", "interval", ":", "self", ".", "tick", "(", ")", "if", "self", ".", "rate", ">=", "0", ":", "return", ...
https://github.com/omergertel/pyformance/blob/b71056eaf9af6cafd3e3c4a416412ae425bdc82e/pyformance/stats/moving_average.py#L31-L36
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/mf6/data/mfdataarray.py
python
MFTransientArray._get_array
(self, num_sp, apply_mult, **kwargs)
return output
Returns all data up to stress period num_sp in a single array. If `layer` is None, returns all data for time `layer`. Parameters ---------- num_sp : int Zero-based stress period of data to return all data up to apply_mult : bool Whether to apply multiplier to data prior to returning it
Returns all data up to stress period num_sp in a single array. If `layer` is None, returns all data for time `layer`.
[ "Returns", "all", "data", "up", "to", "stress", "period", "num_sp", "in", "a", "single", "array", ".", "If", "layer", "is", "None", "returns", "all", "data", "for", "time", "layer", "." ]
def _get_array(self, num_sp, apply_mult, **kwargs): """Returns all data up to stress period num_sp in a single array. If `layer` is None, returns all data for time `layer`. Parameters ---------- num_sp : int Zero-based stress period of data to return all data up to apply_mult : bool Whether to apply multiplier to data prior to returning it """ data = None output = None for sp in range(0, num_sp): if sp in self._data_storage: self.get_data_prep(sp) data = super().get_data(apply_mult=apply_mult, **kwargs) data = np.expand_dims(data, 0) else: # if there is no previous data provide array of # zeros, otherwise provide last array of data found if data is None: # get any data data_dimensions = None for key in self._data_storage.keys(): self.get_data_prep(key) data = super().get_data( apply_mult=apply_mult, **kwargs ) break if data is not None: if self.structure.type == DatumType.integer: data = np.full_like(data, 1) else: data = np.full_like(data, 0.0) data = np.expand_dims(data, 0) if output is None or data is None: output = data else: output = np.concatenate((output, data)) return output
[ "def", "_get_array", "(", "self", ",", "num_sp", ",", "apply_mult", ",", "*", "*", "kwargs", ")", ":", "data", "=", "None", "output", "=", "None", "for", "sp", "in", "range", "(", "0", ",", "num_sp", ")", ":", "if", "sp", "in", "self", ".", "_dat...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/mf6/data/mfdataarray.py#L1607-L1648
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/ext/makerbot_driver/errors.py
python
PacketDecodeError.__init__
(self, actual, expected)
[]
def __init__(self, actual, expected): self.value = { 'ExpectedValue': expected, 'ActualValue': actual, }
[ "def", "__init__", "(", "self", ",", "actual", ",", "expected", ")", ":", "self", ".", "value", "=", "{", "'ExpectedValue'", ":", "expected", ",", "'ActualValue'", ":", "actual", ",", "}" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_driver/errors.py#L16-L20
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/encodings/cp775.py
python
Codec.decode
(self,input,errors='strict')
return codecs.charmap_decode(input,errors,decoding_table)
[]
def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table)
[ "def", "decode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "return", "codecs", ".", "charmap_decode", "(", "input", ",", "errors", ",", "decoding_table", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/encodings/cp775.py#L14-L15
tensorwerk/hangar-py
a6deb22854a6c9e9709011b91c1c0eeda7f47bb0
src/hangar/columns/layout_flat.py
python
FlatSampleReader.schema_type
(self)
return self._schema.schema_type
Schema type of the contained data ('variable_shape', 'fixed_shape', etc).
Schema type of the contained data ('variable_shape', 'fixed_shape', etc).
[ "Schema", "type", "of", "the", "contained", "data", "(", "variable_shape", "fixed_shape", "etc", ")", "." ]
def schema_type(self): """Schema type of the contained data ('variable_shape', 'fixed_shape', etc). """ return self._schema.schema_type
[ "def", "schema_type", "(", "self", ")", ":", "return", "self", ".", "_schema", ".", "schema_type" ]
https://github.com/tensorwerk/hangar-py/blob/a6deb22854a6c9e9709011b91c1c0eeda7f47bb0/src/hangar/columns/layout_flat.py#L270-L273
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/wsgiref/simple_server.py
python
WSGIServer.server_bind
(self)
Override server_bind to store the server name.
Override server_bind to store the server name.
[ "Override", "server_bind", "to", "store", "the", "server", "name", "." ]
def server_bind(self): """Override server_bind to store the server name.""" HTTPServer.server_bind(self) self.setup_environ()
[ "def", "server_bind", "(", "self", ")", ":", "HTTPServer", ".", "server_bind", "(", "self", ")", "self", ".", "setup_environ", "(", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/wsgiref/simple_server.py#L48-L51
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/template/defaulttags.py
python
cycle
(parser, token)
return node
Cycles among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each sucessive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% cycle 'row1' 'row2' as rowcolors silent %}{# no value here #} {% for o in some_list %} <tr class="{% cycle rowcolors %}">{# first value will be "row1" #} ... </tr> {% endfor %}
Cycles among the given strings each time this tag is encountered.
[ "Cycles", "among", "the", "given", "strings", "each", "time", "this", "tag", "is", "encountered", "." ]
def cycle(parser, token): """ Cycles among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each sucessive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% cycle 'row1' 'row2' as rowcolors silent %}{# no value here #} {% for o in some_list %} <tr class="{% cycle rowcolors %}">{# first value will be "row1" #} ... </tr> {% endfor %} """ # Note: This returns the exact same node on each {% cycle name %} call; # that is, the node object returned from {% cycle a b c as name %} and the # one returned from {% cycle name %} are the exact same object. This # shouldn't cause problems (heh), but if it does, now you know. # # Ugly hack warning: This stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. args = token.split_contents() if len(args) < 2: raise TemplateSyntaxError("'cycle' tag requires at least two arguments") if ',' in args[1]: # Backwards compatibility: {% cycle a,b %} or {% cycle a,b as foo %} # case. args[1:2] = ['"%s"' % arg for arg in args[1].split(",")] if len(args) == 2: # {% cycle foo %} case. name = args[1] if not hasattr(parser, '_namedCycleNodes'): raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name) if not name in parser._namedCycleNodes: raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._namedCycleNodes[name] as_form = False if len(args) > 4: # {% cycle ... as foo [silent] %} case. if args[-3] == "as": if args[-1] != "silent": raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1]) as_form = True silent = True args = args[:-1] elif args[-2] == "as": as_form = True silent = False if as_form: name = args[-1] values = [parser.compile_filter(arg) for arg in args[1:-2]] node = CycleNode(values, name, silent=silent) if not hasattr(parser, '_namedCycleNodes'): parser._namedCycleNodes = {} parser._namedCycleNodes[name] = node else: values = [parser.compile_filter(arg) for arg in args[1:]] node = CycleNode(values) return node
[ "def", "cycle", "(", "parser", ",", "token", ")", ":", "# Note: This returns the exact same node on each {% cycle name %} call;", "# that is, the node object returned from {% cycle a b c as name %} and the", "# one returned from {% cycle name %} are the exact same object. This", "# shouldn't c...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/template/defaulttags.py#L530-L619
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/analytics.py
python
ExperimentAnalytics._reshape_artifacts
(self, artifacts, _artifact_names)
return out
Reshape trial component input/output artifacts to a pandas column. Args: artifacts: trial component input/output artifacts Returns: dict: Key: artifacts name, Value: artifacts value
Reshape trial component input/output artifacts to a pandas column.
[ "Reshape", "trial", "component", "input", "/", "output", "artifacts", "to", "a", "pandas", "column", "." ]
def _reshape_artifacts(self, artifacts, _artifact_names): """Reshape trial component input/output artifacts to a pandas column. Args: artifacts: trial component input/output artifacts Returns: dict: Key: artifacts name, Value: artifacts value """ out = OrderedDict() for name, value in sorted(artifacts.items()): if _artifact_names and (name not in _artifact_names): continue out["{} - {}".format(name, "MediaType")] = value.get("MediaType") out["{} - {}".format(name, "Value")] = value.get("Value") return out
[ "def", "_reshape_artifacts", "(", "self", ",", "artifacts", ",", "_artifact_names", ")", ":", "out", "=", "OrderedDict", "(", ")", "for", "name", ",", "value", "in", "sorted", "(", "artifacts", ".", "items", "(", ")", ")", ":", "if", "_artifact_names", "...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/analytics.py#L605-L619
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/PaloAltoNetworks_IoT3rdParty/Scripts/SendAllPANWIoTDevicesToCiscoISE/SendAllPANWIoTDevicesToCiscoISE.py
python
send_status_to_panw_iot_cloud
(status, msg)
Reports status details back to PANW IoT Cloud. param status: Status (error, disabled, success) to be send to PANW IoT cloud. param msg: Debug message to be send to PANW IoT cloud.
Reports status details back to PANW IoT Cloud. param status: Status (error, disabled, success) to be send to PANW IoT cloud. param msg: Debug message to be send to PANW IoT cloud.
[ "Reports", "status", "details", "back", "to", "PANW", "IoT", "Cloud", ".", "param", "status", ":", "Status", "(", "error", "disabled", "success", ")", "to", "be", "send", "to", "PANW", "IoT", "cloud", ".", "param", "msg", ":", "Debug", "message", "to", ...
def send_status_to_panw_iot_cloud(status, msg): """ Reports status details back to PANW IoT Cloud. param status: Status (error, disabled, success) to be send to PANW IoT cloud. param msg: Debug message to be send to PANW IoT cloud. """ resp = demisto.executeCommand("panw-iot-3rd-party-report-status-to-panw", { "status": status, "message": msg, "integration_name": "ise", "playbook_name": "PANW IoT 3rd Party Cisco ISE Integration - Bulk Export to Cisco ISE", "asset_type": 'device', "timestamp": int(round(time.time() * 1000)), "using": PANW_IOT_INSTANCE }) if isError(resp[0]): err_msg = f'Error, failed to send status to PANW IoT Cloud - {resp[0].get("Contents")}' raise Exception(err_msg)
[ "def", "send_status_to_panw_iot_cloud", "(", "status", ",", "msg", ")", ":", "resp", "=", "demisto", ".", "executeCommand", "(", "\"panw-iot-3rd-party-report-status-to-panw\"", ",", "{", "\"status\"", ":", "status", ",", "\"message\"", ":", "msg", ",", "\"integratio...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PaloAltoNetworks_IoT3rdParty/Scripts/SendAllPANWIoTDevicesToCiscoISE/SendAllPANWIoTDevicesToCiscoISE.py#L37-L55
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/plat-mac/pimp.py
python
PimpPackage.downloadPackageOnly
(self, output=None)
Download a single package, if needed. An MD5 signature is used to determine whether download is needed, and to test that we actually downloaded what we expected. If output is given it is a file-like object that will receive a log of what happens. If anything unforeseen happened the method returns an error message string.
Download a single package, if needed.
[ "Download", "a", "single", "package", "if", "needed", "." ]
def downloadPackageOnly(self, output=None): """Download a single package, if needed. An MD5 signature is used to determine whether download is needed, and to test that we actually downloaded what we expected. If output is given it is a file-like object that will receive a log of what happens. If anything unforeseen happened the method returns an error message string. """ scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL']) path = urllib.url2pathname(path) filename = os.path.split(path)[1] self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) if not self._archiveOK(): if scheme == 'manual': return "Please download package manually and save as %s" % self.archiveFilename downloader = PimpUrllibDownloader(None, self._db.preferences.downloadDir, watcher=self._db.preferences.watcher) if not downloader.download(self._dict['Download-URL'], self.archiveFilename, output): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" if not self._archiveOK(): return "archive does not have correct MD5 checksum"
[ "def", "downloadPackageOnly", "(", "self", ",", "output", "=", "None", ")", ":", "scheme", ",", "loc", ",", "path", ",", "query", ",", "frag", "=", "urlparse", ".", "urlsplit", "(", "self", ".", "_dict", "[", "'Download-URL'", "]", ")", "path", "=", ...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/plat-mac/pimp.py#L663-L690
quantumlib/Cirq
89f88b01d69222d3f1ec14d649b7b3a85ed9211f
cirq-core/cirq/qis/states.py
python
one_hot
( *, index: Union[None, int, Sequence[int]] = None, shape: Union[int, Sequence[int]], value: Any = 1, dtype: 'DTypeLike', )
return result
Returns a numpy array with all 0s and a single non-zero entry(default 1). Args: index: The index that should store the `value` argument instead of 0. If not specified, defaults to the start of the array. shape: The shape of the array. value: The hot value to place at `index` in the result. dtype: The dtype of the array. Returns: The created numpy array.
Returns a numpy array with all 0s and a single non-zero entry(default 1).
[ "Returns", "a", "numpy", "array", "with", "all", "0s", "and", "a", "single", "non", "-", "zero", "entry", "(", "default", "1", ")", "." ]
def one_hot( *, index: Union[None, int, Sequence[int]] = None, shape: Union[int, Sequence[int]], value: Any = 1, dtype: 'DTypeLike', ) -> np.ndarray: """Returns a numpy array with all 0s and a single non-zero entry(default 1). Args: index: The index that should store the `value` argument instead of 0. If not specified, defaults to the start of the array. shape: The shape of the array. value: The hot value to place at `index` in the result. dtype: The dtype of the array. Returns: The created numpy array. """ if index is None: index = 0 if isinstance(shape, int) else (0,) * len(shape) result = np.zeros(shape=shape, dtype=dtype) result[index] = value return result
[ "def", "one_hot", "(", "*", ",", "index", ":", "Union", "[", "None", ",", "int", ",", "Sequence", "[", "int", "]", "]", "=", "None", ",", "shape", ":", "Union", "[", "int", ",", "Sequence", "[", "int", "]", "]", ",", "value", ":", "Any", "=", ...
https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-core/cirq/qis/states.py#L1048-L1071
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractNoobtransWordpressCom.py
python
extractNoobtransWordpressCom
(item)
return False
Parser for 'noobtrans.wordpress.com'
Parser for 'noobtrans.wordpress.com'
[ "Parser", "for", "noobtrans", ".", "wordpress", ".", "com" ]
def extractNoobtransWordpressCom(item): ''' Parser for 'noobtrans.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractNoobtransWordpressCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "i...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractNoobtransWordpressCom.py#L2-L21
dlenski/vpn-slice
c10c3eaccc658ff12b113e6e017b170a2567c447
vpn_slice/provider.py
python
RouteProvider.flush_cache
(self)
Flush the routing cache (if necessary).
Flush the routing cache (if necessary).
[ "Flush", "the", "routing", "cache", "(", "if", "necessary", ")", "." ]
def flush_cache(self): """Flush the routing cache (if necessary)."""
[ "def", "flush_cache", "(", "self", ")", ":" ]
https://github.com/dlenski/vpn-slice/blob/c10c3eaccc658ff12b113e6e017b170a2567c447/vpn_slice/provider.py#L68-L69
BotBotMe/botbot-web
0ada6213b5f1d8bb0f71eb79aaf37704f4903564
botbot/apps/logs/templatetags/logs_tags.py
python
bbme_urlizetrunc
(value, limit, autoescape=None)
return mark_safe(urlize_impl(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape))
Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to.
Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming.
[ "Converts", "URLs", "into", "clickable", "links", "truncating", "URLs", "to", "the", "given", "character", "limit", "and", "adding", "rel", "=", "nofollow", "attribute", "to", "discourage", "spamming", "." ]
def bbme_urlizetrunc(value, limit, autoescape=None): """ Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe(urlize_impl(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape))
[ "def", "bbme_urlizetrunc", "(", "value", ",", "limit", ",", "autoescape", "=", "None", ")", ":", "return", "mark_safe", "(", "urlize_impl", "(", "value", ",", "trim_url_limit", "=", "int", "(", "limit", ")", ",", "nofollow", "=", "True", ",", "autoescape",...
https://github.com/BotBotMe/botbot-web/blob/0ada6213b5f1d8bb0f71eb79aaf37704f4903564/botbot/apps/logs/templatetags/logs_tags.py#L25-L33
CMA-ES/pycma
f6eed1ef7e747cec1ab2e5c835d6f2fd1ebc097f
cma/evolution_strategy.py
python
CMAOptions.defaults
()
return cma_default_options
return a dictionary with default option values and description
return a dictionary with default option values and description
[ "return", "a", "dictionary", "with", "default", "option", "values", "and", "description" ]
def defaults(): """return a dictionary with default option values and description""" return cma_default_options
[ "def", "defaults", "(", ")", ":", "return", "cma_default_options" ]
https://github.com/CMA-ES/pycma/blob/f6eed1ef7e747cec1ab2e5c835d6f2fd1ebc097f/cma/evolution_strategy.py#L583-L585
Xilinx/finn
d1cc9cf94f1c33354cc169c5a6517314d0e94e3b
src/finn/custom_op/fpgadataflow/pool_batch.py
python
Pool_Batch.get_instream_width
(self)
return in_width
[]
def get_instream_width(self): dt_bits = self.get_input_datatype().bitwidth() pe = self.get_nodeattr("PE") in_width = int(dt_bits * pe) return in_width
[ "def", "get_instream_width", "(", "self", ")", ":", "dt_bits", "=", "self", ".", "get_input_datatype", "(", ")", ".", "bitwidth", "(", ")", "pe", "=", "self", ".", "get_nodeattr", "(", "\"PE\"", ")", "in_width", "=", "int", "(", "dt_bits", "*", "pe", "...
https://github.com/Xilinx/finn/blob/d1cc9cf94f1c33354cc169c5a6517314d0e94e3b/src/finn/custom_op/fpgadataflow/pool_batch.py#L148-L152
williamSYSU/TextGAN-PyTorch
891635af6845edfee382de147faa4fc00c7e90eb
instructor/real_data/dgsan_instructor.py
python
DGSANInstructor._test
(self)
[]
def _test(self): print('>>> Begin test...') self._run() pass
[ "def", "_test", "(", "self", ")", ":", "print", "(", "'>>> Begin test...'", ")", "self", ".", "_run", "(", ")", "pass" ]
https://github.com/williamSYSU/TextGAN-PyTorch/blob/891635af6845edfee382de147faa4fc00c7e90eb/instructor/real_data/dgsan_instructor.py#L73-L77
sdnewhop/grinder
7432531e4a5a4ce3cc8224ac852188ef1d18432d
grinder/nmapconnector.py
python
NmapConnector.scan
( self, host: str, arguments: str = "", ports: str = "", sudo: bool = False )
The most basic Nmap caller. This is the "lowest" function in terms of Grinder Framework, all calls here are going to python-nmap library. In this function we just puts right arguments, parameters and other things to call Nmap. :param host: ip of the host to scan :param arguments: arguments for Nmap :param ports: ports to scan with Nmap :param sudo: is sudo required to Nmap scan? :return: None
The most basic Nmap caller. This is the "lowest" function in terms of Grinder Framework, all calls here are going to python-nmap library. In this function we just puts right arguments, parameters and other things to call Nmap. :param host: ip of the host to scan :param arguments: arguments for Nmap :param ports: ports to scan with Nmap :param sudo: is sudo required to Nmap scan? :return: None
[ "The", "most", "basic", "Nmap", "caller", ".", "This", "is", "the", "lowest", "function", "in", "terms", "of", "Grinder", "Framework", "all", "calls", "here", "are", "going", "to", "python", "-", "nmap", "library", ".", "In", "this", "function", "we", "j...
def scan( self, host: str, arguments: str = "", ports: str = "", sudo: bool = False ) -> None: """ The most basic Nmap caller. This is the "lowest" function in terms of Grinder Framework, all calls here are going to python-nmap library. In this function we just puts right arguments, parameters and other things to call Nmap. :param host: ip of the host to scan :param arguments: arguments for Nmap :param ports: ports to scan with Nmap :param sudo: is sudo required to Nmap scan? :return: None """ # Add special Nmap key to scan ipv6 hosts if self.check_ip_v6(host): arguments += " -6" # If user wants to scan for top-ports, # let's remove other ports from nmap scan if "top-ports" in arguments: self.nm.scan(hosts=host, arguments=arguments, sudo=sudo) # Else if user doesn't want scan for top-ports, # let's scan with defined ports elif arguments and ports: self.nm.scan(hosts=host, arguments=arguments, ports=ports, sudo=sudo) # Else if ports are not defined, let's # scan with default ports elif arguments: self.nm.scan(hosts=host, arguments=arguments, sudo=sudo) # Else if arguments are not defined, let's # scan with default arguments elif ports: self.nm.scan(hosts=host, arguments="", ports=ports, sudo=sudo) # If arguments are not set too, make # simple scan else: self.nm.scan(hosts=host, arguments="", sudo=sudo) self.results = {host: self.nm[host] for host in self.nm.all_hosts()}
[ "def", "scan", "(", "self", ",", "host", ":", "str", ",", "arguments", ":", "str", "=", "\"\"", ",", "ports", ":", "str", "=", "\"\"", ",", "sudo", ":", "bool", "=", "False", ")", "->", "None", ":", "# Add special Nmap key to scan ipv6 hosts", "if", "s...
https://github.com/sdnewhop/grinder/blob/7432531e4a5a4ce3cc8224ac852188ef1d18432d/grinder/nmapconnector.py#L32-L75
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/pydoc.py
python
HTMLDoc.docroutine
(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None)
Produce HTML documentation for a function or method object.
Produce HTML documentation for a function or method object.
[ "Produce", "HTML", "documentation", "for", "a", "function", "or", "method", "object", "." ]
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if _is_bound_method(object): imclass = object.__self__.__class__ if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.__self__ is not None: note = ' method of %s instance' % self.classlink( object.__self__.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) if name == realname: title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): reallink = '<a href="#%s">%s</a>' % ( cl.__name__ + '-' + realname, realname) skipdocs = 1 else: reallink = realname title = '<a name="%s"><strong>%s</strong></a> = %s' % ( anchor, name, reallink) argspec = None if inspect.isroutine(object): try: signature = inspect.signature(object) except (ValueError, TypeError): signature = None if signature: argspec = str(signature) if realname == '<lambda>': title = '<strong>%s</strong> <em>lambda</em> ' % name # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses if not argspec: argspec = '(...)' decl = title + self.escape(argspec) + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) if skipdocs: return '<dl><dt>%s</dt></dl>\n' % decl else: doc = self.markup( getdoc(object), self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
[ "def", "docroutine", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "funcs", "=", "{", "}", ",", "classes", "=", "{", "}", ",", "methods", "=", "{", "}", ",", "cl", "=", "None", ")", ":", "realname", "=", ...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/pydoc.py#L938-L996
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/apigateway/v20180808/models.py
python
ApiInfo.__init__
(self)
r""" :param ServiceId: API 所在的服务唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceId: str :param ServiceName: API 所在的服务的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceName: str :param ServiceDesc: API 所在的服务的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceDesc: str :param ApiId: API 接口唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiId: str :param ApiDesc: API 接口的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiDesc: str :param CreatedTime: 创建时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type CreatedTime: str :param ModifiedTime: 最后修改时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type ModifiedTime: str :param ApiName: API 接口的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiName: str :param ApiType: API 类型。可取值为NORMAL(普通API)、TSF(微服务API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiType: str :param Protocol: API 的前端请求类型,如 HTTP 或 HTTPS 或者 HTTP 和 HTTPS。 注意:此字段可能返回 null,表示取不到有效值。 :type Protocol: str :param AuthType: API 鉴权类型。可取值为 SECRET(密钥对鉴权)、NONE(免鉴权)、OAUTH。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthType: str :param ApiBusinessType: OAUTH API的类型。可取值为NORMAL(业务API)、OAUTH(授权API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiBusinessType: str :param AuthRelationApiId: OAUTH 业务API 关联的授权API 唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthRelationApiId: str :param OauthConfig: OAUTH配置。 注意:此字段可能返回 null,表示取不到有效值。 :type OauthConfig: :class:`tencentcloud.apigateway.v20180808.models.OauthConfig` :param IsDebugAfterCharge: 是否购买后调试(云市场预留参数)。 注意:此字段可能返回 null,表示取不到有效值。 :type IsDebugAfterCharge: bool :param RequestConfig: 请求的前端配置。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestConfig: :class:`tencentcloud.apigateway.v20180808.models.RequestConfig` :param ResponseType: 返回类型。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseType: str :param ResponseSuccessExample: 自定义响应配置成功响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseSuccessExample: str :param ResponseFailExample: 自定义响应配置失败响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseFailExample: str :param ResponseErrorCodes: 用户自定义错误码配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseErrorCodes: list of ErrorCodes :param RequestParameters: 前端请求参数。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestParameters: list of ReqParameter :param ServiceTimeout: API 的后端服务超时时间,单位是秒。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTimeout: int :param ServiceType: API 的后端服务类型。可取值为 HTTP、MOCK、TSF、CLB、SCF、WEBSOCKET、TARGET(内测)。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceType: str :param ServiceConfig: API 的后端服务配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceConfig: :class:`tencentcloud.apigateway.v20180808.models.ServiceConfig` :param ServiceParameters: API的后端服务参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceParameters: list of ServiceParameter :param ConstantParameters: 常量参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ConstantParameters: list of ConstantParameter :param ServiceMockReturnMessage: API 的后端 Mock 返回信息。如果 ServiceType 是 Mock,则此参数必传。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceMockReturnMessage: str :param ServiceScfFunctionName: scf 函数名称。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionName: str :param ServiceScfFunctionNamespace: scf 函数命名空间。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionNamespace: str :param ServiceScfFunctionQualifier: scf函数版本。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionQualifier: str :param ServiceScfIsIntegratedResponse: 是否开启集成响应。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfIsIntegratedResponse: bool :param ServiceWebsocketRegisterFunctionName: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionName: str :param ServiceWebsocketRegisterFunctionNamespace: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionNamespace: str :param ServiceWebsocketRegisterFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionQualifier: str :param ServiceWebsocketCleanupFunctionName: scf websocket清理函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionName: str :param ServiceWebsocketCleanupFunctionNamespace: scf websocket清理函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionNamespace: str :param ServiceWebsocketCleanupFunctionQualifier: scf websocket清理函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionQualifier: str :param InternalDomain: WEBSOCKET 回推地址。 注意:此字段可能返回 null,表示取不到有效值。 :type InternalDomain: str :param ServiceWebsocketTransportFunctionName: scf websocket传输函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionName: str :param ServiceWebsocketTransportFunctionNamespace: scf websocket传输函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionNamespace: str :param ServiceWebsocketTransportFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionQualifier: str :param MicroServices: API绑定微服务服务列表。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServices: list of MicroService :param MicroServicesInfo: 微服务信息详情。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServicesInfo: list of int :param ServiceTsfLoadBalanceConf: 微服务的负载均衡配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfLoadBalanceConf: :class:`tencentcloud.apigateway.v20180808.models.TsfLoadBalanceConfResp` :param ServiceTsfHealthCheckConf: 微服务的健康检查配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfHealthCheckConf: :class:`tencentcloud.apigateway.v20180808.models.HealthCheckConf` :param EnableCORS: 是否开启跨域。 注意:此字段可能返回 null,表示取不到有效值。 :type EnableCORS: bool :param Tags: API绑定的tag信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Tags: list of Tag :param Environments: API已发布的环境信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Environments: list of str :param IsBase64Encoded: 是否开启Base64编码,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Encoded: bool :param IsBase64Trigger: 是否开启Base64编码的header触发,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Trigger: bool :param Base64EncodedTriggerRules: Header触发规则,总规则数量不超过10。 注意:此字段可能返回 null,表示取不到有效值。 :type Base64EncodedTriggerRules: list of Base64EncodedTriggerRule
r""" :param ServiceId: API 所在的服务唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceId: str :param ServiceName: API 所在的服务的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceName: str :param ServiceDesc: API 所在的服务的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceDesc: str :param ApiId: API 接口唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiId: str :param ApiDesc: API 接口的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiDesc: str :param CreatedTime: 创建时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type CreatedTime: str :param ModifiedTime: 最后修改时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type ModifiedTime: str :param ApiName: API 接口的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiName: str :param ApiType: API 类型。可取值为NORMAL(普通API)、TSF(微服务API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiType: str :param Protocol: API 的前端请求类型,如 HTTP 或 HTTPS 或者 HTTP 和 HTTPS。 注意:此字段可能返回 null,表示取不到有效值。 :type Protocol: str :param AuthType: API 鉴权类型。可取值为 SECRET(密钥对鉴权)、NONE(免鉴权)、OAUTH。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthType: str :param ApiBusinessType: OAUTH API的类型。可取值为NORMAL(业务API)、OAUTH(授权API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiBusinessType: str :param AuthRelationApiId: OAUTH 业务API 关联的授权API 唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthRelationApiId: str :param OauthConfig: OAUTH配置。 注意:此字段可能返回 null,表示取不到有效值。 :type OauthConfig: :class:`tencentcloud.apigateway.v20180808.models.OauthConfig` :param IsDebugAfterCharge: 是否购买后调试(云市场预留参数)。 注意:此字段可能返回 null,表示取不到有效值。 :type IsDebugAfterCharge: bool :param RequestConfig: 请求的前端配置。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestConfig: :class:`tencentcloud.apigateway.v20180808.models.RequestConfig` :param ResponseType: 返回类型。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseType: str :param ResponseSuccessExample: 自定义响应配置成功响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseSuccessExample: str :param ResponseFailExample: 自定义响应配置失败响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseFailExample: str :param ResponseErrorCodes: 用户自定义错误码配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseErrorCodes: list of ErrorCodes :param RequestParameters: 前端请求参数。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestParameters: list of ReqParameter :param ServiceTimeout: API 的后端服务超时时间,单位是秒。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTimeout: int :param ServiceType: API 的后端服务类型。可取值为 HTTP、MOCK、TSF、CLB、SCF、WEBSOCKET、TARGET(内测)。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceType: str :param ServiceConfig: API 的后端服务配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceConfig: :class:`tencentcloud.apigateway.v20180808.models.ServiceConfig` :param ServiceParameters: API的后端服务参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceParameters: list of ServiceParameter :param ConstantParameters: 常量参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ConstantParameters: list of ConstantParameter :param ServiceMockReturnMessage: API 的后端 Mock 返回信息。如果 ServiceType 是 Mock,则此参数必传。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceMockReturnMessage: str :param ServiceScfFunctionName: scf 函数名称。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionName: str :param ServiceScfFunctionNamespace: scf 函数命名空间。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionNamespace: str :param ServiceScfFunctionQualifier: scf函数版本。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionQualifier: str :param ServiceScfIsIntegratedResponse: 是否开启集成响应。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfIsIntegratedResponse: bool :param ServiceWebsocketRegisterFunctionName: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionName: str :param ServiceWebsocketRegisterFunctionNamespace: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionNamespace: str :param ServiceWebsocketRegisterFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionQualifier: str :param ServiceWebsocketCleanupFunctionName: scf websocket清理函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionName: str :param ServiceWebsocketCleanupFunctionNamespace: scf websocket清理函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionNamespace: str :param ServiceWebsocketCleanupFunctionQualifier: scf websocket清理函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionQualifier: str :param InternalDomain: WEBSOCKET 回推地址。 注意:此字段可能返回 null,表示取不到有效值。 :type InternalDomain: str :param ServiceWebsocketTransportFunctionName: scf websocket传输函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionName: str :param ServiceWebsocketTransportFunctionNamespace: scf websocket传输函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionNamespace: str :param ServiceWebsocketTransportFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionQualifier: str :param MicroServices: API绑定微服务服务列表。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServices: list of MicroService :param MicroServicesInfo: 微服务信息详情。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServicesInfo: list of int :param ServiceTsfLoadBalanceConf: 微服务的负载均衡配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfLoadBalanceConf: :class:`tencentcloud.apigateway.v20180808.models.TsfLoadBalanceConfResp` :param ServiceTsfHealthCheckConf: 微服务的健康检查配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfHealthCheckConf: :class:`tencentcloud.apigateway.v20180808.models.HealthCheckConf` :param EnableCORS: 是否开启跨域。 注意:此字段可能返回 null,表示取不到有效值。 :type EnableCORS: bool :param Tags: API绑定的tag信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Tags: list of Tag :param Environments: API已发布的环境信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Environments: list of str :param IsBase64Encoded: 是否开启Base64编码,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Encoded: bool :param IsBase64Trigger: 是否开启Base64编码的header触发,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Trigger: bool :param Base64EncodedTriggerRules: Header触发规则,总规则数量不超过10。 注意:此字段可能返回 null,表示取不到有效值。 :type Base64EncodedTriggerRules: list of Base64EncodedTriggerRule
[ "r", ":", "param", "ServiceId", ":", "API", "所在的服务唯一", "ID。", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "ServiceId", ":", "str", ":", "param", "ServiceName", ":", "API", "所在的服务的名称。", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "ServiceName", ":", "str", ":...
def __init__(self): r""" :param ServiceId: API 所在的服务唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceId: str :param ServiceName: API 所在的服务的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceName: str :param ServiceDesc: API 所在的服务的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceDesc: str :param ApiId: API 接口唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiId: str :param ApiDesc: API 接口的描述。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiDesc: str :param CreatedTime: 创建时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type CreatedTime: str :param ModifiedTime: 最后修改时间,按照 ISO8601 标准表示,并且使用 UTC 时间。格式为:YYYY-MM-DDThh:mm:ssZ。 注意:此字段可能返回 null,表示取不到有效值。 :type ModifiedTime: str :param ApiName: API 接口的名称。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiName: str :param ApiType: API 类型。可取值为NORMAL(普通API)、TSF(微服务API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiType: str :param Protocol: API 的前端请求类型,如 HTTP 或 HTTPS 或者 HTTP 和 HTTPS。 注意:此字段可能返回 null,表示取不到有效值。 :type Protocol: str :param AuthType: API 鉴权类型。可取值为 SECRET(密钥对鉴权)、NONE(免鉴权)、OAUTH。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthType: str :param ApiBusinessType: OAUTH API的类型。可取值为NORMAL(业务API)、OAUTH(授权API)。 注意:此字段可能返回 null,表示取不到有效值。 :type ApiBusinessType: str :param AuthRelationApiId: OAUTH 业务API 关联的授权API 唯一 ID。 注意:此字段可能返回 null,表示取不到有效值。 :type AuthRelationApiId: str :param OauthConfig: OAUTH配置。 注意:此字段可能返回 null,表示取不到有效值。 :type OauthConfig: :class:`tencentcloud.apigateway.v20180808.models.OauthConfig` :param IsDebugAfterCharge: 是否购买后调试(云市场预留参数)。 注意:此字段可能返回 null,表示取不到有效值。 :type IsDebugAfterCharge: bool :param RequestConfig: 请求的前端配置。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestConfig: :class:`tencentcloud.apigateway.v20180808.models.RequestConfig` :param ResponseType: 返回类型。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseType: str :param ResponseSuccessExample: 自定义响应配置成功响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseSuccessExample: str :param ResponseFailExample: 自定义响应配置失败响应示例。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseFailExample: str :param ResponseErrorCodes: 用户自定义错误码配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ResponseErrorCodes: list of ErrorCodes :param RequestParameters: 前端请求参数。 注意:此字段可能返回 null,表示取不到有效值。 :type RequestParameters: list of ReqParameter :param ServiceTimeout: API 的后端服务超时时间,单位是秒。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTimeout: int :param ServiceType: API 的后端服务类型。可取值为 HTTP、MOCK、TSF、CLB、SCF、WEBSOCKET、TARGET(内测)。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceType: str :param ServiceConfig: API 的后端服务配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceConfig: :class:`tencentcloud.apigateway.v20180808.models.ServiceConfig` :param ServiceParameters: API的后端服务参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceParameters: list of ServiceParameter :param ConstantParameters: 常量参数。 注意:此字段可能返回 null,表示取不到有效值。 :type ConstantParameters: list of ConstantParameter :param ServiceMockReturnMessage: API 的后端 Mock 返回信息。如果 ServiceType 是 Mock,则此参数必传。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceMockReturnMessage: str :param ServiceScfFunctionName: scf 函数名称。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionName: str :param ServiceScfFunctionNamespace: scf 函数命名空间。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionNamespace: str :param ServiceScfFunctionQualifier: scf函数版本。当后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfFunctionQualifier: str :param ServiceScfIsIntegratedResponse: 是否开启集成响应。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceScfIsIntegratedResponse: bool :param ServiceWebsocketRegisterFunctionName: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionName: str :param ServiceWebsocketRegisterFunctionNamespace: scf websocket注册函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionNamespace: str :param ServiceWebsocketRegisterFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketRegisterFunctionQualifier: str :param ServiceWebsocketCleanupFunctionName: scf websocket清理函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionName: str :param ServiceWebsocketCleanupFunctionNamespace: scf websocket清理函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionNamespace: str :param ServiceWebsocketCleanupFunctionQualifier: scf websocket清理函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketCleanupFunctionQualifier: str :param InternalDomain: WEBSOCKET 回推地址。 注意:此字段可能返回 null,表示取不到有效值。 :type InternalDomain: str :param ServiceWebsocketTransportFunctionName: scf websocket传输函数。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionName: str :param ServiceWebsocketTransportFunctionNamespace: scf websocket传输函数命名空间。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionNamespace: str :param ServiceWebsocketTransportFunctionQualifier: scf websocket传输函数版本。当前端类型是WEBSOCKET且后端类型是SCF时生效。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceWebsocketTransportFunctionQualifier: str :param MicroServices: API绑定微服务服务列表。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServices: list of MicroService :param MicroServicesInfo: 微服务信息详情。 注意:此字段可能返回 null,表示取不到有效值。 :type MicroServicesInfo: list of int :param ServiceTsfLoadBalanceConf: 微服务的负载均衡配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfLoadBalanceConf: :class:`tencentcloud.apigateway.v20180808.models.TsfLoadBalanceConfResp` :param ServiceTsfHealthCheckConf: 微服务的健康检查配置。 注意:此字段可能返回 null,表示取不到有效值。 :type ServiceTsfHealthCheckConf: :class:`tencentcloud.apigateway.v20180808.models.HealthCheckConf` :param EnableCORS: 是否开启跨域。 注意:此字段可能返回 null,表示取不到有效值。 :type EnableCORS: bool :param Tags: API绑定的tag信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Tags: list of Tag :param Environments: API已发布的环境信息。 注意:此字段可能返回 null,表示取不到有效值。 :type Environments: list of str :param IsBase64Encoded: 是否开启Base64编码,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Encoded: bool :param IsBase64Trigger: 是否开启Base64编码的header触发,只有后端为scf时才会生效。 注意:此字段可能返回 null,表示取不到有效值。 :type IsBase64Trigger: bool :param Base64EncodedTriggerRules: Header触发规则,总规则数量不超过10。 注意:此字段可能返回 null,表示取不到有效值。 :type Base64EncodedTriggerRules: list of Base64EncodedTriggerRule """ self.ServiceId = None self.ServiceName = None self.ServiceDesc = None self.ApiId = None self.ApiDesc = None self.CreatedTime = None self.ModifiedTime = None self.ApiName = None self.ApiType = None self.Protocol = None self.AuthType = None self.ApiBusinessType = None self.AuthRelationApiId = None self.OauthConfig = None self.IsDebugAfterCharge = None self.RequestConfig = None self.ResponseType = None self.ResponseSuccessExample = None self.ResponseFailExample = None self.ResponseErrorCodes = None self.RequestParameters = None self.ServiceTimeout = None self.ServiceType = None self.ServiceConfig = None self.ServiceParameters = None self.ConstantParameters = None self.ServiceMockReturnMessage = None self.ServiceScfFunctionName = None self.ServiceScfFunctionNamespace = None self.ServiceScfFunctionQualifier = None self.ServiceScfIsIntegratedResponse = None self.ServiceWebsocketRegisterFunctionName = None self.ServiceWebsocketRegisterFunctionNamespace = None self.ServiceWebsocketRegisterFunctionQualifier = None self.ServiceWebsocketCleanupFunctionName = None self.ServiceWebsocketCleanupFunctionNamespace = None self.ServiceWebsocketCleanupFunctionQualifier = None self.InternalDomain = None self.ServiceWebsocketTransportFunctionName = None self.ServiceWebsocketTransportFunctionNamespace = None self.ServiceWebsocketTransportFunctionQualifier = None self.MicroServices = None self.MicroServicesInfo = None self.ServiceTsfLoadBalanceConf = None self.ServiceTsfHealthCheckConf = None self.EnableCORS = None self.Tags = None self.Environments = None self.IsBase64Encoded = None self.IsBase64Trigger = None self.Base64EncodedTriggerRules = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ServiceId", "=", "None", "self", ".", "ServiceName", "=", "None", "self", ".", "ServiceDesc", "=", "None", "self", ".", "ApiId", "=", "None", "self", ".", "ApiDesc", "=", "None", "self", ".", "C...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/apigateway/v20180808/models.py#L533-L739
wummel/patool
723006abd43d0926581b11df0cd37e46a30525eb
patoolib/util.py
python
tmpdir
(dir=None)
return tempfile.mkdtemp(suffix='', prefix='Unpack_', dir=dir)
Return a temporary directory for extraction.
Return a temporary directory for extraction.
[ "Return", "a", "temporary", "directory", "for", "extraction", "." ]
def tmpdir (dir=None): """Return a temporary directory for extraction.""" return tempfile.mkdtemp(suffix='', prefix='Unpack_', dir=dir)
[ "def", "tmpdir", "(", "dir", "=", "None", ")", ":", "return", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "''", ",", "prefix", "=", "'Unpack_'", ",", "dir", "=", "dir", ")" ]
https://github.com/wummel/patool/blob/723006abd43d0926581b11df0cd37e46a30525eb/patoolib/util.py#L468-L470
pyscf/pyscf
0adfb464333f5ceee07b664f291d4084801bae64
pyscf/fci/cistring.py
python
gen_cre_str_index
(orb_list, nelec)
return gen_cre_str_index_o1(orb_list, nelec)
linkstr_index to map between N electron string to N+1 electron string. It maps the given string to the address of the string which is generated by the creation operator. For given string str0, index[str0] is nvir x 4 array. Each entry [i(cre),--,str1,sign] means starting from str0, creating i, to get str1.
linkstr_index to map between N electron string to N+1 electron string. It maps the given string to the address of the string which is generated by the creation operator.
[ "linkstr_index", "to", "map", "between", "N", "electron", "string", "to", "N", "+", "1", "electron", "string", ".", "It", "maps", "the", "given", "string", "to", "the", "address", "of", "the", "string", "which", "is", "generated", "by", "the", "creation", ...
def gen_cre_str_index(orb_list, nelec): '''linkstr_index to map between N electron string to N+1 electron string. It maps the given string to the address of the string which is generated by the creation operator. For given string str0, index[str0] is nvir x 4 array. Each entry [i(cre),--,str1,sign] means starting from str0, creating i, to get str1. ''' return gen_cre_str_index_o1(orb_list, nelec)
[ "def", "gen_cre_str_index", "(", "orb_list", ",", "nelec", ")", ":", "return", "gen_cre_str_index_o1", "(", "orb_list", ",", "nelec", ")" ]
https://github.com/pyscf/pyscf/blob/0adfb464333f5ceee07b664f291d4084801bae64/pyscf/fci/cistring.py#L286-L294
nicrusso7/rex-gym
26663048bd3c3da307714da4458b1a2a9dc81824
rex_gym/envs/gym/turn_env.py
python
RexTurnEnv._get_true_observation
(self)
return self._true_observation
Get the true observations of this environment. It includes the roll, the error between current pitch and desired pitch, roll dot and pitch dot of the base. Returns: The observation list.
Get the true observations of this environment.
[ "Get", "the", "true", "observations", "of", "this", "environment", "." ]
def _get_true_observation(self): """Get the true observations of this environment. It includes the roll, the error between current pitch and desired pitch, roll dot and pitch dot of the base. Returns: The observation list. """ observation = [] roll, pitch, _ = self.rex.GetTrueBaseRollPitchYaw() roll_rate, pitch_rate, _ = self.rex.GetTrueBaseRollPitchYawRate() observation.extend([roll, pitch, roll_rate, pitch_rate]) self._true_observation = np.array(observation) return self._true_observation
[ "def", "_get_true_observation", "(", "self", ")", ":", "observation", "=", "[", "]", "roll", ",", "pitch", ",", "_", "=", "self", ".", "rex", ".", "GetTrueBaseRollPitchYaw", "(", ")", "roll_rate", ",", "pitch_rate", ",", "_", "=", "self", ".", "rex", "...
https://github.com/nicrusso7/rex-gym/blob/26663048bd3c3da307714da4458b1a2a9dc81824/rex_gym/envs/gym/turn_env.py#L380-L394
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/CLI/account/events.py
python
cli
(env, ack_all)
Summary and acknowledgement of upcoming and ongoing maintenance events
Summary and acknowledgement of upcoming and ongoing maintenance events
[ "Summary", "and", "acknowledgement", "of", "upcoming", "and", "ongoing", "maintenance", "events" ]
def cli(env, ack_all): """Summary and acknowledgement of upcoming and ongoing maintenance events""" manager = AccountManager(env.client) planned_events = manager.get_upcoming_events("PLANNED") unplanned_events = manager.get_upcoming_events("UNPLANNED_INCIDENT") announcement_events = manager.get_upcoming_events("ANNOUNCEMENT") add_ack_flag(planned_events, manager, ack_all) env.fout(planned_event_table(planned_events)) add_ack_flag(unplanned_events, manager, ack_all) env.fout(unplanned_event_table(unplanned_events)) add_ack_flag(announcement_events, manager, ack_all) env.fout(announcement_event_table(announcement_events))
[ "def", "cli", "(", "env", ",", "ack_all", ")", ":", "manager", "=", "AccountManager", "(", "env", ".", "client", ")", "planned_events", "=", "manager", ".", "get_upcoming_events", "(", "\"PLANNED\"", ")", "unplanned_events", "=", "manager", ".", "get_upcoming_...
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/CLI/account/events.py#L15-L30
ganglia/gmond_python_modules
2f7fcab3d27926ef4a2feb1b53c09af16a43e729
xrootd_stats/python_modules/xrootd_stats.py
python
get_xrootd_metrics
(name)
return xrootd[name]
[]
def get_xrootd_metrics(name): root = ET.fromstring(data['xml']) for i in root.findall("stats"): if i.attrib['id'] == "xrootd": for c in i.getchildren(): if c.tag not in ["ops", "aio", "lgn"]: tag = NAME_PREFIX + "xrootd_" + c.tag xrootd[tag] = c.text if c.tag == "ops": for num in xrange(len(c.getchildren())): tag = NAME_PREFIX+"xrootd_ops_"+c.getchildren()[num].tag xrootd[tag] = c.getchildren()[num].text if c.tag == "aio": for num in xrange(len(c.getchildren())): tag = NAME_PREFIX+"xrootd_aio_"+c.getchildren()[num].tag xrootd[tag] = c.getchildren()[num].text if c.tag == "lgn": for num in xrange(len(c.getchildren())): tag = NAME_PREFIX+"xrootd_lgn_"+c.getchildren()[num].tag xrootd[tag] = c.getchildren()[num].text return xrootd[name]
[ "def", "get_xrootd_metrics", "(", "name", ")", ":", "root", "=", "ET", ".", "fromstring", "(", "data", "[", "'xml'", "]", ")", "for", "i", "in", "root", ".", "findall", "(", "\"stats\"", ")", ":", "if", "i", ".", "attrib", "[", "'id'", "]", "==", ...
https://github.com/ganglia/gmond_python_modules/blob/2f7fcab3d27926ef4a2feb1b53c09af16a43e729/xrootd_stats/python_modules/xrootd_stats.py#L241-L262
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/lib2to3/fixer_util.py
python
_is_import_binding
(node, name, package=None)
return None
Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples.
Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples.
[ "Will", "reuturn", "node", "if", "node", "will", "import", "name", "or", "node", "will", "import", "*", "from", "package", ".", "None", "is", "returned", "otherwise", ".", "See", "test", "cases", "for", "examples", "." ]
def _is_import_binding(node, name, package=None): """ Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples. """ if node.type == syms.import_name and not package: imp = node.children[1] if imp.type == syms.dotted_as_names: for child in imp.children: if child.type == syms.dotted_as_name: if child.children[2].value == name: return node elif child.type == token.NAME and child.value == name: return node elif imp.type == syms.dotted_as_name: last = imp.children[-1] if last.type == token.NAME and last.value == name: return node elif imp.type == token.NAME and imp.value == name: return node elif node.type == syms.import_from: # str(...) is used to make life easier here, because # from a.b import parses to ['import', ['a', '.', 'b'], ...] if package and str(node.children[1]).strip() != package: return None n = node.children[3] if package and _find("as", n): # See test_from_import_as for explanation return None elif n.type == syms.import_as_names and _find(name, n): return node elif n.type == syms.import_as_name: child = n.children[2] if child.type == token.NAME and child.value == name: return node elif n.type == token.NAME and n.value == name: return node elif package and n.type == token.STAR: return node return None
[ "def", "_is_import_binding", "(", "node", ",", "name", ",", "package", "=", "None", ")", ":", "if", "node", ".", "type", "==", "syms", ".", "import_name", "and", "not", "package", ":", "imp", "=", "node", ".", "children", "[", "1", "]", "if", "imp", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/lib2to3/fixer_util.py#L393-L432
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/fftpack/_pseudo_diffs.py
python
sc_diff
(x, a, b, period=None, _cache=_cache)
return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x. If x_j and y_j are Fourier coefficients of periodic functions x and y, respectively, then:: y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j y_0 = 0 Parameters ---------- x : array_like Input array. a,b : float Defines the parameters of the sinh/cosh pseudo-differential operator. period : float, optional The period of the sequence x. Default is 2*pi. Notes ----- ``sc_diff(cs_diff(x,a,b),b,a) == x`` For even ``len(x)``, the Nyquist mode of x is taken as zero.
Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
[ "Return", "(", "a", "b", ")", "-", "sinh", "/", "cosh", "pseudo", "-", "derivative", "of", "a", "periodic", "sequence", "x", "." ]
def sc_diff(x, a, b, period=None, _cache=_cache): """ Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x. If x_j and y_j are Fourier coefficients of periodic functions x and y, respectively, then:: y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j y_0 = 0 Parameters ---------- x : array_like Input array. a,b : float Defines the parameters of the sinh/cosh pseudo-differential operator. period : float, optional The period of the sequence x. Default is 2*pi. Notes ----- ``sc_diff(cs_diff(x,a,b),b,a) == x`` For even ``len(x)``, the Nyquist mode of x is taken as zero. """ tmp = asarray(x) if iscomplexobj(tmp): return sc_diff(tmp.real,a,b,period) + \ 1j*sc_diff(tmp.imag,a,b,period) if period is not None: a = a*2*pi/period b = b*2*pi/period n = len(x) omega = _cache.get((n,a,b)) if omega is None: if len(_cache) > 20: while _cache: _cache.popitem() def kernel(k,a=a,b=b): if k: return sinh(a*k)/cosh(b*k) return 0 omega = convolve.init_convolution_kernel(n,kernel,d=1) _cache[(n,a,b)] = omega overwrite_x = _datacopied(tmp, x) return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
[ "def", "sc_diff", "(", "x", ",", "a", ",", "b", ",", "period", "=", "None", ",", "_cache", "=", "_cache", ")", ":", "tmp", "=", "asarray", "(", "x", ")", "if", "iscomplexobj", "(", "tmp", ")", ":", "return", "sc_diff", "(", "tmp", ".", "real", ...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/fftpack/_pseudo_diffs.py#L336-L383
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/requests/utils.py
python
from_key_val_list
(value)
return OrderedDict(value)
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: need more than 1 value to unpack >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g.,
[ "Take", "an", "object", "and", "test", "to", "see", "if", "it", "can", "be", "represented", "as", "a", "dictionary", ".", "Unless", "it", "can", "not", "be", "represented", "as", "such", "return", "an", "OrderedDict", "e", ".", "g", "." ]
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: need more than 1 value to unpack >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value)
[ "def", "from_key_val_list", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ",", "bool", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "'cannot encode...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/requests/utils.py#L154-L176
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/idlelib/EditorWindow.py
python
EditorWindow.center_insert_event
(self, event)
[]
def center_insert_event(self, event): self.center()
[ "def", "center_insert_event", "(", "self", ",", "event", ")", ":", "self", ".", "center", "(", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/idlelib/EditorWindow.py#L957-L958
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/ui/gui/tools/proxywin.py
python
ProxiedRequests.config_changed
(self, like_initial)
Propagates the change from the options. :param like_initial: If the config is like the initial one
Propagates the change from the options.
[ "Propagates", "the", "change", "from", "the", "options", "." ]
def config_changed(self, like_initial): """Propagates the change from the options. :param like_initial: If the config is like the initial one """ self.like_initial = like_initial
[ "def", "config_changed", "(", "self", ",", "like_initial", ")", ":", "self", ".", "like_initial", "=", "like_initial" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/tools/proxywin.py#L231-L236
EmuKit/emukit
cdcb0d070d7f1c5585260266160722b636786859
emukit/examples/preferential_batch_bayesian_optimization/pbbo/gp_models.py
python
ComparisonGP.get_current_best
(self)
return min(self.Y)
:return: minimum of means of predictions at all input locations (needed by q-EI)
:return: minimum of means of predictions at all input locations (needed by q-EI)
[ ":", "return", ":", "minimum", "of", "means", "of", "predictions", "at", "all", "input", "locations", "(", "needed", "by", "q", "-", "EI", ")" ]
def get_current_best(self) -> float: """ :return: minimum of means of predictions at all input locations (needed by q-EI) """ return min(self.Y)
[ "def", "get_current_best", "(", "self", ")", "->", "float", ":", "return", "min", "(", "self", ".", "Y", ")" ]
https://github.com/EmuKit/emukit/blob/cdcb0d070d7f1c5585260266160722b636786859/emukit/examples/preferential_batch_bayesian_optimization/pbbo/gp_models.py#L36-L40
gevent/gevent
ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31
src/gevent/_sslgte279.py
python
SSLSocket.accept
(self)
return newsock, addr
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.
[ "Accepts", "a", "new", "connection", "from", "a", "remote", "client", "and", "returns", "a", "tuple", "containing", "that", "new", "connection", "wrapped", "with", "a", "server", "-", "side", "SSL", "channel", "and", "the", "address", "of", "the", "remote", ...
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) newsock._drop_events_and_close(closefd=False) # Why, again? newsock = self._context.wrap_socket(newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True) return newsock, addr
[ "def", "accept", "(", "self", ")", ":", "newsock", ",", "addr", "=", "socket", ".", "accept", "(", "self", ")", "newsock", ".", "_drop_events_and_close", "(", "closefd", "=", "False", ")", "# Why, again?", "newsock", "=", "self", ".", "_context", ".", "w...
https://github.com/gevent/gevent/blob/ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31/src/gevent/_sslgte279.py#L642-L653
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/hydroshare/utils.py
python
add_file_to_resource
(resource, f, folder='', source_name='', check_target_folder=False, add_to_aggregation=True, user=None)
return ret
Add a ResourceFile to a Resource. Adds the 'format' metadata element to the resource. :param resource: Resource to which file should be added :param f: File-like object to add to a resource :param folder: folder at which the file will live :param source_name: the logical file name of the resource content file for federated iRODS resource or the federated zone name; By default, it is empty. A non-empty value indicates the file needs to be added into the federated zone, either from local disk where f holds the uploaded file from local disk, or from the federated zone directly where f is empty but source_name has the whole data object iRODS path in the federated zone :param check_target_folder: if true and the resource is a composite resource then uploading a file to the specified folder will be validated before adding the file to the resource :param add_to_aggregation: if true and the resource is a composite resource then the file being added to the resource also will be added to a fileset aggregation if such an aggregation exists in the file path :param user: user who is adding file to the resource :return: The identifier of the ResourceFile added.
Add a ResourceFile to a Resource. Adds the 'format' metadata element to the resource. :param resource: Resource to which file should be added :param f: File-like object to add to a resource :param folder: folder at which the file will live :param source_name: the logical file name of the resource content file for federated iRODS resource or the federated zone name; By default, it is empty. A non-empty value indicates the file needs to be added into the federated zone, either from local disk where f holds the uploaded file from local disk, or from the federated zone directly where f is empty but source_name has the whole data object iRODS path in the federated zone :param check_target_folder: if true and the resource is a composite resource then uploading a file to the specified folder will be validated before adding the file to the resource :param add_to_aggregation: if true and the resource is a composite resource then the file being added to the resource also will be added to a fileset aggregation if such an aggregation exists in the file path :param user: user who is adding file to the resource :return: The identifier of the ResourceFile added.
[ "Add", "a", "ResourceFile", "to", "a", "Resource", ".", "Adds", "the", "format", "metadata", "element", "to", "the", "resource", ".", ":", "param", "resource", ":", "Resource", "to", "which", "file", "should", "be", "added", ":", "param", "f", ":", "File...
def add_file_to_resource(resource, f, folder='', source_name='', check_target_folder=False, add_to_aggregation=True, user=None): """ Add a ResourceFile to a Resource. Adds the 'format' metadata element to the resource. :param resource: Resource to which file should be added :param f: File-like object to add to a resource :param folder: folder at which the file will live :param source_name: the logical file name of the resource content file for federated iRODS resource or the federated zone name; By default, it is empty. A non-empty value indicates the file needs to be added into the federated zone, either from local disk where f holds the uploaded file from local disk, or from the federated zone directly where f is empty but source_name has the whole data object iRODS path in the federated zone :param check_target_folder: if true and the resource is a composite resource then uploading a file to the specified folder will be validated before adding the file to the resource :param add_to_aggregation: if true and the resource is a composite resource then the file being added to the resource also will be added to a fileset aggregation if such an aggregation exists in the file path :param user: user who is adding file to the resource :return: The identifier of the ResourceFile added. """ # validate parameters if resource.raccess.published: if user is None or not user.is_superuser: raise ValidationError("Only admin can add files to a published resource") if check_target_folder and resource.resource_type != 'CompositeResource': raise ValidationError("Resource must be a CompositeResource for validating target folder") if f: if check_target_folder and folder: tgt_full_upload_path = os.path.join(resource.file_path, folder) if not resource.can_add_files(target_full_path=tgt_full_upload_path): err_msg = "File can't be added to this folder which represents an aggregation" raise ValidationError(err_msg) openfile = File(f) if not isinstance(f, UploadedFile) else f ret = ResourceFile.create(resource, openfile, folder=folder, source=None) if add_to_aggregation: if folder and resource.resource_type == 'CompositeResource': aggregation = resource.get_model_aggregation_in_path(folder) if aggregation is None: aggregation = resource.get_fileset_aggregation_in_path(folder) if aggregation is not None: # make the added file part of the fileset or model program/instance aggregation aggregation.add_resource_file(ret) # add format metadata element if necessary file_format_type = get_file_mime_type(f.name) elif source_name: try: # create from existing iRODS file ret = ResourceFile.create(resource, file=None, folder=folder, source=source_name) except SessionException as ex: try: ret.delete() except Exception: pass # raise the exception for the calling function to inform the error on the page interface raise SessionException(ex.exitcode, ex.stdout, ex.stderr) # add format metadata element if necessary file_format_type = get_file_mime_type(source_name) else: raise ValueError('Invalid input parameter is passed into this add_file_to_resource() ' 'function') # TODO: generate this from data in ResourceFile rather than extension if file_format_type not in [mime.value for mime in resource.metadata.formats.all()]: resource.metadata.create_element('format', value=file_format_type) ret.calculate_size() return ret
[ "def", "add_file_to_resource", "(", "resource", ",", "f", ",", "folder", "=", "''", ",", "source_name", "=", "''", ",", "check_target_folder", "=", "False", ",", "add_to_aggregation", "=", "True", ",", "user", "=", "None", ")", ":", "# validate parameters", ...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/hydroshare/utils.py#L937-L1013
paulproteus/python-scraping-code-samples
4e5396d4e311ca66c784a2b5f859308285e511da
new/seleniumrc/selenium-remote-control-1.0-beta-2/selenium-python-client-driver-1.0-beta-2/selenium.py
python
selenium.mouse_down
(self,locator)
Simulates a user pressing the left mouse button (without releasing it yet) on the specified element. 'locator' is an element locator
Simulates a user pressing the left mouse button (without releasing it yet) on the specified element. 'locator' is an element locator
[ "Simulates", "a", "user", "pressing", "the", "left", "mouse", "button", "(", "without", "releasing", "it", "yet", ")", "on", "the", "specified", "element", ".", "locator", "is", "an", "element", "locator" ]
def mouse_down(self,locator): """ Simulates a user pressing the left mouse button (without releasing it yet) on the specified element. 'locator' is an element locator """ self.do_command("mouseDown", [locator,])
[ "def", "mouse_down", "(", "self", ",", "locator", ")", ":", "self", ".", "do_command", "(", "\"mouseDown\"", ",", "[", "locator", ",", "]", ")" ]
https://github.com/paulproteus/python-scraping-code-samples/blob/4e5396d4e311ca66c784a2b5f859308285e511da/new/seleniumrc/selenium-remote-control-1.0-beta-2/selenium-python-client-driver-1.0-beta-2/selenium.py#L473-L480
hugorut/neural-cli
a8c1eaabfc7dc9425b59dec0cd3f1bd9fe9edcb4
neuralcli/neuralnet.py
python
NeuralNet.accuracy
(self, type='train')
get the accuracy of the learned parameters on a specific set
get the accuracy of the learned parameters on a specific set
[ "get", "the", "accuracy", "of", "the", "learned", "parameters", "on", "a", "specific", "set" ]
def accuracy(self, type='train'): """ get the accuracy of the learned parameters on a specific set """ examples = len(self.Y) theta1, theta2 = self.reshape_theta(self.params) a1, z2, a2, z3, h = self.feed_forward(self.X, theta1, theta2) y_pred = np.array(np.argmax(h, axis=1)) correct = 0 for x in range(examples): if self.Y[x, y_pred[x]] == 1: correct += 1 accuracy = (correct / float(examples)) self.writer.write(type +' accuracy = {0}%'.format(accuracy * 100))
[ "def", "accuracy", "(", "self", ",", "type", "=", "'train'", ")", ":", "examples", "=", "len", "(", "self", ".", "Y", ")", "theta1", ",", "theta2", "=", "self", ".", "reshape_theta", "(", "self", ".", "params", ")", "a1", ",", "z2", ",", "a2", ",...
https://github.com/hugorut/neural-cli/blob/a8c1eaabfc7dc9425b59dec0cd3f1bd9fe9edcb4/neuralcli/neuralnet.py#L303-L320
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/setuptools/command/easy_install.py
python
PthDistributions.save
(self)
Write changed .pth file back to disk
Write changed .pth file back to disk
[ "Write", "changed", ".", "pth", "file", "back", "to", "disk" ]
def save(self): """Write changed .pth file back to disk""" if not self.dirty: return rel_paths = list(map(self.make_relative, self.paths)) if rel_paths: log.debug("Saving %s", self.filename) lines = self._wrap_lines(rel_paths) data = '\n'.join(lines) + '\n' if os.path.islink(self.filename): os.unlink(self.filename) with open(self.filename, 'wt') as f: f.write(data) elif os.path.exists(self.filename): log.debug("Deleting empty %s", self.filename) os.unlink(self.filename) self.dirty = False
[ "def", "save", "(", "self", ")", ":", "if", "not", "self", ".", "dirty", ":", "return", "rel_paths", "=", "list", "(", "map", "(", "self", ".", "make_relative", ",", "self", ".", "paths", ")", ")", "if", "rel_paths", ":", "log", ".", "debug", "(", ...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/setuptools/command/easy_install.py#L1616-L1636
blawar/nut
2cf351400418399a70164987e28670309f6c9cb5
Fs/driver/interface.py
python
DirContext.ls
(self)
return []
[]
def ls(self): return []
[ "def", "ls", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/blawar/nut/blob/2cf351400418399a70164987e28670309f6c9cb5/Fs/driver/interface.py#L15-L16
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/jupyter_console-4.0.3-py3.3.egg/jupyter_console/interactiveshell.py
python
ZMQTerminalInteractiveShell.interact
(self, display_banner=None)
Closely emulate the interactive Python console.
Closely emulate the interactive Python console.
[ "Closely", "emulate", "the", "interactive", "Python", "console", "." ]
def interact(self, display_banner=None): """Closely emulate the interactive Python console.""" # batch run -> do not interact if self.exit_now: return if display_banner is None: display_banner = self.display_banner if isinstance(display_banner, string_types): self.show_banner(display_banner) elif display_banner: self.show_banner() more = False # run a non-empty no-op, so that we don't get a prompt until # we know the kernel is ready. This keeps the connection # message above the first prompt. if not self.wait_for_kernel(self.kernel_timeout): error("Kernel did not respond\n") return if self.has_readline: self.readline_startup_hook(self.pre_readline) hlen_b4_cell = self.readline.get_current_history_length() else: hlen_b4_cell = 0 # exit_now is set by a call to %Exit or %Quit, through the # ask_exit callback. while not self.exit_now: if not self.client.is_alive(): # kernel died, prompt for action or exit action = "restart" if self.manager else "wait for restart" ans = self.ask_yes_no("kernel died, %s ([y]/n)?" % action, default='y') if ans: if self.manager: self.manager.restart_kernel(True) self.wait_for_kernel(self.kernel_timeout) else: self.exit_now = True continue try: # protect prompt block from KeyboardInterrupt # when sitting on ctrl-C self.hooks.pre_prompt_hook() if more: try: prompt = self.prompt_manager.render('in2') except Exception: self.showtraceback() if self.autoindent: self.rl_do_indent = True else: try: prompt = self.separate_in + self.prompt_manager.render('in') except Exception: self.showtraceback() line = self.raw_input(prompt) if self.exit_now: # quick exit on sys.std[in|out] close break if self.autoindent: self.rl_do_indent = False except KeyboardInterrupt: #double-guard against keyboardinterrupts during kbdint handling try: self.write('\n' + self.get_exception_only()) source_raw = self.input_splitter.raw_reset() hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) more = False except KeyboardInterrupt: pass except EOFError: if self.autoindent: self.rl_do_indent = False if self.has_readline: self.readline_startup_hook(None) self.write('\n') self.exit() except bdb.BdbQuit: warn('The Python debugger has exited with a BdbQuit exception.\n' 'Because of how pdb handles the stack, it is impossible\n' 'for IPython to properly format this particular exception.\n' 'IPython will resume normal operation.') except: # exceptions here are VERY RARE, but they can be triggered # asynchronously by signal handlers, for example. self.showtraceback() else: try: self.input_splitter.push(line) more = self.input_splitter.push_accepts_more() except SyntaxError: # Run the code directly - run_cell takes care of displaying # the exception. more = False if (self.SyntaxTB.last_syntax_error and self.autoedit_syntax): self.edit_syntax_error() if not more: source_raw = self.input_splitter.raw_reset() hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) self.run_cell(source_raw) # Turn off the exit flag, so the mainloop can be restarted if desired self.exit_now = False
[ "def", "interact", "(", "self", ",", "display_banner", "=", "None", ")", ":", "# batch run -> do not interact", "if", "self", ".", "exit_now", ":", "return", "if", "display_banner", "is", "None", ":", "display_banner", "=", "self", ".", "display_banner", "if", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/jupyter_console-4.0.3-py3.3.egg/jupyter_console/interactiveshell.py#L479-L592
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/tkinter/__init__.py
python
PanedWindow.paneconfigure
(self, tagOrId, cnf=None, **kw)
Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported: after window Insert the window after the window specified. window should be the name of a window already managed by pathName. before window Insert the window before the window specified. window should be the name of a window already managed by pathName. height size Specify a height for the window. The height will be the outer dimension of the window including its border, if any. If size is an empty string, or if -height is not specified, then the height requested internally by the window will be used initially; the height may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. minsize n Specifies that the size of the window cannot be made less than n. This constraint only affects the size of the widget in the paned dimension -- the x dimension for horizontal panedwindows, the y dimension for vertical panedwindows. May be any value accepted by Tk_GetPixels. padx n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the X-direction. The value may have any of the forms accepted by Tk_GetPixels. pady n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the Y-direction. The value may have any of the forms accepted by Tk_GetPixels. sticky style If a window's pane is larger than the requested dimensions of the window, this option may be used to position (or stretch) the window within its pane. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the window will "stick" to. If both n and s (or e and w) are specified, the window will be stretched to fill the entire height (or width) of its cavity. width size Specify a width for the window. The width will be the outer dimension of the window including its border, if any. If size is an empty string, or if -width is not specified, then the width requested internally by the window will be used initially; the width may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels.
Query or modify the management options for window.
[ "Query", "or", "modify", "the", "management", "options", "for", "window", "." ]
def paneconfigure(self, tagOrId, cnf=None, **kw): """Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported: after window Insert the window after the window specified. window should be the name of a window already managed by pathName. before window Insert the window before the window specified. window should be the name of a window already managed by pathName. height size Specify a height for the window. The height will be the outer dimension of the window including its border, if any. If size is an empty string, or if -height is not specified, then the height requested internally by the window will be used initially; the height may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. minsize n Specifies that the size of the window cannot be made less than n. This constraint only affects the size of the widget in the paned dimension -- the x dimension for horizontal panedwindows, the y dimension for vertical panedwindows. May be any value accepted by Tk_GetPixels. padx n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the X-direction. The value may have any of the forms accepted by Tk_GetPixels. pady n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the Y-direction. The value may have any of the forms accepted by Tk_GetPixels. sticky style If a window's pane is larger than the requested dimensions of the window, this option may be used to position (or stretch) the window within its pane. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the window will "stick" to. If both n and s (or e and w) are specified, the window will be stretched to fill the entire height (or width) of its cavity. width size Specify a width for the window. The width will be the outer dimension of the window including its border, if any. If size is an empty string, or if -width is not specified, then the width requested internally by the window will be used initially; the width may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. """ if cnf is None and not kw: return self._getconfigure(self._w, 'paneconfigure', tagOrId) if isinstance(cnf, str) and not kw: return self._getconfigure1( self._w, 'paneconfigure', tagOrId, '-'+cnf) self.tk.call((self._w, 'paneconfigure', tagOrId) + self._options(cnf, kw))
[ "def", "paneconfigure", "(", "self", ",", "tagOrId", ",", "cnf", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "cnf", "is", "None", "and", "not", "kw", ":", "return", "self", ".", "_getconfigure", "(", "self", ".", "_w", ",", "'paneconfigure'", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/tkinter/__init__.py#L3904-L3978
robclewley/pydstool
939e3abc9dd1f180d35152bacbde57e24c85ff26
PyDSTool/utils.py
python
architecture
()
return struct.calcsize("P") * 8
Platform- and version-independent function to determine 32- or 64-bit architecture. Used primarily to determine need for "-m32" option to C compilers for external library compilation, e.g. by AUTO, Dopri, Radau. Returns integer 32 or 64.
Platform- and version-independent function to determine 32- or 64-bit architecture. Used primarily to determine need for "-m32" option to C compilers for external library compilation, e.g. by AUTO, Dopri, Radau.
[ "Platform", "-", "and", "version", "-", "independent", "function", "to", "determine", "32", "-", "or", "64", "-", "bit", "architecture", ".", "Used", "primarily", "to", "determine", "need", "for", "-", "m32", "option", "to", "C", "compilers", "for", "exter...
def architecture(): """ Platform- and version-independent function to determine 32- or 64-bit architecture. Used primarily to determine need for "-m32" option to C compilers for external library compilation, e.g. by AUTO, Dopri, Radau. Returns integer 32 or 64. """ import struct return struct.calcsize("P") * 8
[ "def", "architecture", "(", ")", ":", "import", "struct", "return", "struct", ".", "calcsize", "(", "\"P\"", ")", "*", "8" ]
https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/utils.py#L733-L742
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/distlib/util.py
python
FileOperator.copy_file
(self, infile, outfile, check=True)
Copy a file respecting dry-run and force flags.
Copy a file respecting dry-run and force flags.
[ "Copy", "a", "file", "respecting", "dry", "-", "run", "and", "force", "flags", "." ]
def copy_file(self, infile, outfile, check=True): """Copy a file respecting dry-run and force flags. """ self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying %s to %s', infile, outfile) if not self.dry_run: msg = None if check: if os.path.islink(outfile): msg = '%s is a symlink' % outfile elif os.path.exists(outfile) and not os.path.isfile(outfile): msg = '%s is a non-regular file' % outfile if msg: raise ValueError(msg + ' which would be overwritten') shutil.copyfile(infile, outfile) self.record_as_written(outfile)
[ "def", "copy_file", "(", "self", ",", "infile", ",", "outfile", ",", "check", "=", "True", ")", ":", "self", ".", "ensure_dir", "(", "os", ".", "path", ".", "dirname", "(", "outfile", ")", ")", "logger", ".", "info", "(", "'Copying %s to %s'", ",", "...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/distlib/util.py#L353-L368
explosion/sense2vec
d689bb65ce0f6c597c891cea3ba279ad1f92916f
sense2vec/sense2vec.py
python
Sense2Vec.keys
(self)
YIELDS (unicode): The string keys in the table.
YIELDS (unicode): The string keys in the table.
[ "YIELDS", "(", "unicode", ")", ":", "The", "string", "keys", "in", "the", "table", "." ]
def keys(self): """YIELDS (unicode): The string keys in the table.""" for key in self.vectors.keys(): yield self.strings[key]
[ "def", "keys", "(", "self", ")", ":", "for", "key", "in", "self", ".", "vectors", ".", "keys", "(", ")", ":", "yield", "self", ".", "strings", "[", "key", "]" ]
https://github.com/explosion/sense2vec/blob/d689bb65ce0f6c597c891cea3ba279ad1f92916f/sense2vec/sense2vec.py#L103-L106
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/lib-tk/ttk.py
python
Progressbar.step
(self, amount=None)
Increments the value option by amount. amount defaults to 1.0 if omitted.
Increments the value option by amount.
[ "Increments", "the", "value", "option", "by", "amount", "." ]
def step(self, amount=None): """Increments the value option by amount. amount defaults to 1.0 if omitted.""" self.tk.call(self._w, "step", amount)
[ "def", "step", "(", "self", ",", "amount", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"step\"", ",", "amount", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/lib-tk/ttk.py#L1021-L1025
RasaHQ/rasa-sdk
231c200d24574bb5908074df6c59f2acaa152606
scripts/release.py
python
create_release_branch
(version: Version)
return branch
Create a new branch for this release. Returns the branch name.
Create a new branch for this release. Returns the branch name.
[ "Create", "a", "new", "branch", "for", "this", "release", ".", "Returns", "the", "branch", "name", "." ]
def create_release_branch(version: Version) -> Text: """Create a new branch for this release. Returns the branch name.""" branch = f"{RELEASE_BRANCH_PREFIX}{version}" check_call(["git", "checkout", "-b", branch]) return branch
[ "def", "create_release_branch", "(", "version", ":", "Version", ")", "->", "Text", ":", "branch", "=", "f\"{RELEASE_BRANCH_PREFIX}{version}\"", "check_call", "(", "[", "\"git\"", ",", "\"checkout\"", ",", "\"-b\"", ",", "branch", "]", ")", "return", "branch" ]
https://github.com/RasaHQ/rasa-sdk/blob/231c200d24574bb5908074df6c59f2acaa152606/scripts/release.py#L204-L209
bolt-project/bolt
9cd7104aa085498da3097b72696184b9d3651c51
bolt/spark/array.py
python
BoltArraySpark.chunk
(self, size="150", axis=None, padding=None)
return chnk._chunk(size, axis, padding)
Chunks records of a distributed array. Chunking breaks arrays into subarrays, using an specified size of chunks along each value dimension. Can alternatively specify an average chunk byte size (in kilobytes) and the size of chunks (as ints) will be computed automatically. Parameters ---------- size : tuple, int, or str, optional, default = "150" A string giving the size in kilobytes, or a tuple with the size of chunks along each dimension. axis : int or tuple, optional, default = None One or more axis to chunk array along, if None will use all axes, padding: tuple or int, default = None Number of elements per dimension that will overlap with the adjacent chunk. If a tuple, specifies padding along each chunked dimension; if a int, same padding will be applied to all chunked dimensions. Returns ------- ChunkedArray
Chunks records of a distributed array.
[ "Chunks", "records", "of", "a", "distributed", "array", "." ]
def chunk(self, size="150", axis=None, padding=None): """ Chunks records of a distributed array. Chunking breaks arrays into subarrays, using an specified size of chunks along each value dimension. Can alternatively specify an average chunk byte size (in kilobytes) and the size of chunks (as ints) will be computed automatically. Parameters ---------- size : tuple, int, or str, optional, default = "150" A string giving the size in kilobytes, or a tuple with the size of chunks along each dimension. axis : int or tuple, optional, default = None One or more axis to chunk array along, if None will use all axes, padding: tuple or int, default = None Number of elements per dimension that will overlap with the adjacent chunk. If a tuple, specifies padding along each chunked dimension; if a int, same padding will be applied to all chunked dimensions. Returns ------- ChunkedArray """ if type(size) is not str: size = tupleize((size)) axis = tupleize((axis)) padding = tupleize((padding)) from bolt.spark.chunk import ChunkedArray chnk = ChunkedArray(rdd=self._rdd, shape=self._shape, split=self._split, dtype=self._dtype) return chnk._chunk(size, axis, padding)
[ "def", "chunk", "(", "self", ",", "size", "=", "\"150\"", ",", "axis", "=", "None", ",", "padding", "=", "None", ")", ":", "if", "type", "(", "size", ")", "is", "not", "str", ":", "size", "=", "tupleize", "(", "(", "size", ")", ")", "axis", "="...
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L678-L714
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
gluoncv/data/otb/tracking.py
python
OTBTracking.set_tracker
(self, path, tracker_names)
Args: path: path to tracker results, tracker_names: list of tracker name
Args: path: path to tracker results, tracker_names: list of tracker name
[ "Args", ":", "path", ":", "path", "to", "tracker", "results", "tracker_names", ":", "list", "of", "tracker", "name" ]
def set_tracker(self, path, tracker_names): """ Args: path: path to tracker results, tracker_names: list of tracker name """ self.tracker_path = path self.tracker_names = tracker_names
[ "def", "set_tracker", "(", "self", ",", "path", ",", "tracker_names", ")", ":", "self", ".", "tracker_path", "=", "path", "self", ".", "tracker_names", "=", "tracker_names" ]
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/gluoncv/data/otb/tracking.py#L212-L219
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/string.py
python
upper
(s)
return s.upper()
upper(s) -> string Return a copy of the string s converted to uppercase.
upper(s) -> string
[ "upper", "(", "s", ")", "-", ">", "string" ]
def upper(s): """upper(s) -> string Return a copy of the string s converted to uppercase. """ return s.upper()
[ "def", "upper", "(", "s", ")", ":", "return", "s", ".", "upper", "(", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/string.py#L229-L235
tctianchi/pyvenn
24d6e1ddf9fb7c9881268dbad28a979da63815fa
venn.py
python
venn6
(labels, names=['A', 'B', 'C', 'D', 'E'], **options)
return fig, ax
plots a 6-set Venn diagram @type labels: dict[str, str] @type names: list[str] @rtype: (Figure, AxesSubplot) input labels: a label dict where keys are identified via binary codes ('000001', '000010', '000100', ...), hence a valid set could look like: {'000001': 'text 1', '000010': 'text 2', '000100': 'text 3', ...}. unmentioned codes are considered as ''. names: group names more: colors, figsize, dpi, fontsize return pyplot Figure and AxesSubplot object
plots a 6-set Venn diagram
[ "plots", "a", "6", "-", "set", "Venn", "diagram" ]
def venn6(labels, names=['A', 'B', 'C', 'D', 'E'], **options): """ plots a 6-set Venn diagram @type labels: dict[str, str] @type names: list[str] @rtype: (Figure, AxesSubplot) input labels: a label dict where keys are identified via binary codes ('000001', '000010', '000100', ...), hence a valid set could look like: {'000001': 'text 1', '000010': 'text 2', '000100': 'text 3', ...}. unmentioned codes are considered as ''. names: group names more: colors, figsize, dpi, fontsize return pyplot Figure and AxesSubplot object """ colors = options.get('colors', [default_colors[i] for i in range(6)]) figsize = options.get('figsize', (20, 20)) dpi = options.get('dpi', 96) fontsize = options.get('fontsize', 14) fig = plt.figure(0, figsize=figsize, dpi=dpi) ax = fig.add_subplot(111, aspect='equal') ax.set_axis_off() ax.set_ylim(bottom=0.230, top=0.845) ax.set_xlim(left=0.173, right=0.788) # body # See https://web.archive.org/web/20040819232503/http://www.hpl.hp.com/techreports/2000/HPL-2000-73.pdf draw_triangle(fig, ax, 0.637, 0.921, 0.649, 0.274, 0.188, 0.667, colors[0]) draw_triangle(fig, ax, 0.981, 0.769, 0.335, 0.191, 0.393, 0.671, colors[1]) draw_triangle(fig, ax, 0.941, 0.397, 0.292, 0.475, 0.456, 0.747, colors[2]) draw_triangle(fig, ax, 0.662, 0.119, 0.316, 0.548, 0.662, 0.700, colors[3]) draw_triangle(fig, ax, 0.309, 0.081, 0.374, 0.718, 0.681, 0.488, colors[4]) draw_triangle(fig, ax, 0.016, 0.626, 0.726, 0.687, 0.522, 0.327, colors[5]) draw_text(fig, ax, 0.212, 0.562, labels.get('000001', ''), fontsize=fontsize) draw_text(fig, ax, 0.430, 0.249, labels.get('000010', ''), fontsize=fontsize) draw_text(fig, ax, 0.356, 0.444, labels.get('000011', ''), fontsize=fontsize) draw_text(fig, ax, 0.609, 0.255, labels.get('000100', ''), fontsize=fontsize) draw_text(fig, ax, 0.323, 0.546, labels.get('000101', ''), fontsize=fontsize) draw_text(fig, ax, 0.513, 0.316, labels.get('000110', ''), fontsize=fontsize) draw_text(fig, ax, 0.523, 0.348, labels.get('000111', ''), fontsize=fontsize) draw_text(fig, ax, 0.747, 0.458, labels.get('001000', ''), fontsize=fontsize) draw_text(fig, ax, 0.325, 0.492, labels.get('001001', ''), fontsize=fontsize) draw_text(fig, ax, 0.670, 0.481, labels.get('001010', ''), fontsize=fontsize) draw_text(fig, ax, 0.359, 0.478, labels.get('001011', ''), fontsize=fontsize) draw_text(fig, ax, 0.653, 0.444, labels.get('001100', ''), fontsize=fontsize) draw_text(fig, ax, 0.344, 0.526, labels.get('001101', ''), fontsize=fontsize) draw_text(fig, ax, 0.653, 0.466, labels.get('001110', ''), fontsize=fontsize) draw_text(fig, ax, 0.363, 0.503, labels.get('001111', ''), fontsize=fontsize) draw_text(fig, ax, 0.750, 0.616, labels.get('010000', ''), fontsize=fontsize) draw_text(fig, ax, 0.682, 0.654, labels.get('010001', ''), fontsize=fontsize) draw_text(fig, ax, 0.402, 0.310, labels.get('010010', ''), fontsize=fontsize) draw_text(fig, ax, 0.392, 0.421, labels.get('010011', ''), fontsize=fontsize) draw_text(fig, ax, 0.653, 0.691, labels.get('010100', ''), fontsize=fontsize) draw_text(fig, ax, 0.651, 0.644, labels.get('010101', ''), fontsize=fontsize) draw_text(fig, ax, 0.490, 0.340, labels.get('010110', ''), fontsize=fontsize) draw_text(fig, ax, 0.468, 0.399, labels.get('010111', ''), fontsize=fontsize) draw_text(fig, ax, 0.692, 0.545, labels.get('011000', ''), fontsize=fontsize) draw_text(fig, ax, 0.666, 0.592, labels.get('011001', ''), fontsize=fontsize) draw_text(fig, ax, 0.665, 0.496, labels.get('011010', ''), fontsize=fontsize) draw_text(fig, ax, 0.374, 0.470, labels.get('011011', ''), fontsize=fontsize) draw_text(fig, ax, 0.653, 0.537, labels.get('011100', ''), fontsize=fontsize) draw_text(fig, ax, 0.652, 0.579, labels.get('011101', ''), fontsize=fontsize) draw_text(fig, ax, 0.653, 0.488, labels.get('011110', ''), fontsize=fontsize) draw_text(fig, ax, 0.389, 0.486, labels.get('011111', ''), fontsize=fontsize) draw_text(fig, ax, 0.553, 0.806, labels.get('100000', ''), fontsize=fontsize) draw_text(fig, ax, 0.313, 0.604, labels.get('100001', ''), fontsize=fontsize) draw_text(fig, ax, 0.388, 0.694, labels.get('100010', ''), fontsize=fontsize) draw_text(fig, ax, 0.375, 0.633, labels.get('100011', ''), fontsize=fontsize) draw_text(fig, ax, 0.605, 0.359, labels.get('100100', ''), fontsize=fontsize) draw_text(fig, ax, 0.334, 0.555, labels.get('100101', ''), fontsize=fontsize) draw_text(fig, ax, 0.582, 0.397, labels.get('100110', ''), fontsize=fontsize) draw_text(fig, ax, 0.542, 0.372, labels.get('100111', ''), fontsize=fontsize) draw_text(fig, ax, 0.468, 0.708, labels.get('101000', ''), fontsize=fontsize) draw_text(fig, ax, 0.355, 0.572, labels.get('101001', ''), fontsize=fontsize) draw_text(fig, ax, 0.420, 0.679, labels.get('101010', ''), fontsize=fontsize) draw_text(fig, ax, 0.375, 0.597, labels.get('101011', ''), fontsize=fontsize) draw_text(fig, ax, 0.641, 0.436, labels.get('101100', ''), fontsize=fontsize) draw_text(fig, ax, 0.348, 0.538, labels.get('101101', ''), fontsize=fontsize) draw_text(fig, ax, 0.635, 0.453, labels.get('101110', ''), fontsize=fontsize) draw_text(fig, ax, 0.370, 0.548, labels.get('101111', ''), fontsize=fontsize) draw_text(fig, ax, 0.594, 0.689, labels.get('110000', ''), fontsize=fontsize) draw_text(fig, ax, 0.579, 0.670, labels.get('110001', ''), fontsize=fontsize) draw_text(fig, ax, 0.398, 0.670, labels.get('110010', ''), fontsize=fontsize) draw_text(fig, ax, 0.395, 0.653, labels.get('110011', ''), fontsize=fontsize) draw_text(fig, ax, 0.633, 0.682, labels.get('110100', ''), fontsize=fontsize) draw_text(fig, ax, 0.616, 0.656, labels.get('110101', ''), fontsize=fontsize) draw_text(fig, ax, 0.587, 0.427, labels.get('110110', ''), fontsize=fontsize) draw_text(fig, ax, 0.526, 0.415, labels.get('110111', ''), fontsize=fontsize) draw_text(fig, ax, 0.495, 0.677, labels.get('111000', ''), fontsize=fontsize) draw_text(fig, ax, 0.505, 0.648, labels.get('111001', ''), fontsize=fontsize) draw_text(fig, ax, 0.428, 0.663, labels.get('111010', ''), fontsize=fontsize) draw_text(fig, ax, 0.430, 0.631, labels.get('111011', ''), fontsize=fontsize) draw_text(fig, ax, 0.639, 0.524, labels.get('111100', ''), fontsize=fontsize) draw_text(fig, ax, 0.591, 0.604, labels.get('111101', ''), fontsize=fontsize) draw_text(fig, ax, 0.622, 0.477, labels.get('111110', ''), fontsize=fontsize) draw_text(fig, ax, 0.501, 0.523, labels.get('111111', ''), fontsize=fontsize) # legend draw_text(fig, ax, 0.674, 0.824, names[0], colors[0], fontsize=fontsize) draw_text(fig, ax, 0.747, 0.751, names[1], colors[1], fontsize=fontsize) draw_text(fig, ax, 0.739, 0.396, names[2], colors[2], fontsize=fontsize) draw_text(fig, ax, 0.700, 0.247, names[3], colors[3], fontsize=fontsize) draw_text(fig, ax, 0.291, 0.255, names[4], colors[4], fontsize=fontsize) draw_text(fig, ax, 0.203, 0.484, names[5], colors[5], fontsize=fontsize) leg = ax.legend(names, loc='center left', bbox_to_anchor=(1.0, 0.5), fancybox=True) leg.get_frame().set_alpha(0.5) return fig, ax
[ "def", "venn6", "(", "labels", ",", "names", "=", "[", "'A'", ",", "'B'", ",", "'C'", ",", "'D'", ",", "'E'", "]", ",", "*", "*", "options", ")", ":", "colors", "=", "options", ".", "get", "(", "'colors'", ",", "[", "default_colors", "[", "i", ...
https://github.com/tctianchi/pyvenn/blob/24d6e1ddf9fb7c9881268dbad28a979da63815fa/venn.py#L356-L467
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
deepchem/dock/binding_pocket.py
python
ConvexHullPocketFinder.__init__
(self, scoring_model: Optional[Model] = None, pad: float = 5.0)
Initialize the pocket finder. Parameters ---------- scoring_model: Model, optional (default None) If specified, use this model to prune pockets. pad: float, optional (default 5.0) The number of angstroms to pad around a binding pocket's atoms to get a binding pocket box.
Initialize the pocket finder.
[ "Initialize", "the", "pocket", "finder", "." ]
def __init__(self, scoring_model: Optional[Model] = None, pad: float = 5.0): """Initialize the pocket finder. Parameters ---------- scoring_model: Model, optional (default None) If specified, use this model to prune pockets. pad: float, optional (default 5.0) The number of angstroms to pad around a binding pocket's atoms to get a binding pocket box. """ self.scoring_model = scoring_model self.pad = pad
[ "def", "__init__", "(", "self", ",", "scoring_model", ":", "Optional", "[", "Model", "]", "=", "None", ",", "pad", ":", "float", "=", "5.0", ")", ":", "self", ".", "scoring_model", "=", "scoring_model", "self", ".", "pad", "=", "pad" ]
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/dock/binding_pocket.py#L88-L100
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/utils/server.py
python
ThreadedServer._accept_method
(self, sock)
[]
def _accept_method(self, sock): t = threading.Thread(target = self._authenticate_and_serve_client, args = (sock,)) t.setDaemon(True) t.start()
[ "def", "_accept_method", "(", "self", ",", "sock", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_authenticate_and_serve_client", ",", "args", "=", "(", "sock", ",", ")", ")", "t", ".", "setDaemon", "(", "True", ")",...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/utils/server.py#L271-L274
pyca/pyopenssl
fb26edde0aa27670c7bb24c0daeb05516e83d7b0
src/OpenSSL/_util.py
python
path_bytes
(s)
Convert a Python path to a :py:class:`bytes` for the path which can be passed into an OpenSSL API accepting a filename. :param s: A path (valid for os.fspath). :return: An instance of :py:class:`bytes`.
Convert a Python path to a :py:class:`bytes` for the path which can be passed into an OpenSSL API accepting a filename.
[ "Convert", "a", "Python", "path", "to", "a", ":", "py", ":", "class", ":", "bytes", "for", "the", "path", "which", "can", "be", "passed", "into", "an", "OpenSSL", "API", "accepting", "a", "filename", "." ]
def path_bytes(s): """ Convert a Python path to a :py:class:`bytes` for the path which can be passed into an OpenSSL API accepting a filename. :param s: A path (valid for os.fspath). :return: An instance of :py:class:`bytes`. """ b = os.fspath(s) if isinstance(b, str): return b.encode(sys.getfilesystemencoding()) else: return b
[ "def", "path_bytes", "(", "s", ")", ":", "b", "=", "os", ".", "fspath", "(", "s", ")", "if", "isinstance", "(", "b", ",", "str", ")", ":", "return", "b", ".", "encode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "else", ":", "return...
https://github.com/pyca/pyopenssl/blob/fb26edde0aa27670c7bb24c0daeb05516e83d7b0/src/OpenSSL/_util.py#L74-L88
jimenbian/DataMining
6b1fc93319a3cdda835e158029ac133665d13191
SMO/src/SMO.py
python
selectJrand
(i,m)
return j
[]
def selectJrand(i,m): j=i #we want to select any J not equal to i while (j==i): j = int(random.uniform(0,m)) return j
[ "def", "selectJrand", "(", "i", ",", "m", ")", ":", "j", "=", "i", "#we want to select any J not equal to i", "while", "(", "j", "==", "i", ")", ":", "j", "=", "int", "(", "random", ".", "uniform", "(", "0", ",", "m", ")", ")", "return", "j" ]
https://github.com/jimenbian/DataMining/blob/6b1fc93319a3cdda835e158029ac133665d13191/SMO/src/SMO.py#L14-L18
project-alice-assistant/ProjectAlice
9e0ba019643bdae0a5535c9fa4180739231dc361
core/user/UserManager.py
python
UserManager.checkIfAllUser
(self, state: str)
return self._users and all(self._users[username].state == state for username in self.getAllUserNames())
Checks if the given state applies to all users (except for guests) :param state: the state to check :return: boolean
Checks if the given state applies to all users (except for guests) :param state: the state to check :return: boolean
[ "Checks", "if", "the", "given", "state", "applies", "to", "all", "users", "(", "except", "for", "guests", ")", ":", "param", "state", ":", "the", "state", "to", "check", ":", "return", ":", "boolean" ]
def checkIfAllUser(self, state: str) -> bool: """ Checks if the given state applies to all users (except for guests) :param state: the state to check :return: boolean """ return self._users and all(self._users[username].state == state for username in self.getAllUserNames())
[ "def", "checkIfAllUser", "(", "self", ",", "state", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "_users", "and", "all", "(", "self", ".", "_users", "[", "username", "]", ".", "state", "==", "state", "for", "username", "in", "self", "."...
https://github.com/project-alice-assistant/ProjectAlice/blob/9e0ba019643bdae0a5535c9fa4180739231dc361/core/user/UserManager.py#L178-L184
anishathalye/git-remote-dropbox
01b630ab697d9b9423915e88e43dd24072e0d591
git_remote_dropbox/cli/helper.py
python
main
()
Main entry point for git-remote-dropbox Git remote helper.
Main entry point for git-remote-dropbox Git remote helper.
[ "Main", "entry", "point", "for", "git", "-", "remote", "-", "dropbox", "Git", "remote", "helper", "." ]
def main(): """ Main entry point for git-remote-dropbox Git remote helper. """ # configure system stdout_to_binary() url = sys.argv[2] helper = get_helper(url) try: helper.run() except Exception: if helper.verbosity >= Level.DEBUG: raise # re-raise exception so it prints out a stack trace else: error('unexpected exception (run with -v for details)') except KeyboardInterrupt: # exit silently with an error code exit(1)
[ "def", "main", "(", ")", ":", "# configure system", "stdout_to_binary", "(", ")", "url", "=", "sys", ".", "argv", "[", "2", "]", "helper", "=", "get_helper", "(", "url", ")", "try", ":", "helper", ".", "run", "(", ")", "except", "Exception", ":", "if...
https://github.com/anishathalye/git-remote-dropbox/blob/01b630ab697d9b9423915e88e43dd24072e0d591/git_remote_dropbox/cli/helper.py#L13-L31
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/sqlalchemy/dialects/firebird/kinterbasdb.py
python
FBDialect_kinterbasdb._get_server_version_info
(self, connection)
return self._parse_version_info(version)
Get the version of the Firebird server used by a connection. Returns a tuple of (`major`, `minor`, `build`), three integers representing the version of the attached server.
Get the version of the Firebird server used by a connection.
[ "Get", "the", "version", "of", "the", "Firebird", "server", "used", "by", "a", "connection", "." ]
def _get_server_version_info(self, connection): """Get the version of the Firebird server used by a connection. Returns a tuple of (`major`, `minor`, `build`), three integers representing the version of the attached server. """ # This is the simpler approach (the other uses the services api), # that for backward compatibility reasons returns a string like # LI-V6.3.3.12981 Firebird 2.0 # where the first version is a fake one resembling the old # Interbase signature. fbconn = connection.connection version = fbconn.server_version return self._parse_version_info(version)
[ "def", "_get_server_version_info", "(", "self", ",", "connection", ")", ":", "# This is the simpler approach (the other uses the services api),", "# that for backward compatibility reasons returns a string like", "# LI-V6.3.3.12981 Firebird 2.0", "# where the first version is a fake one rese...
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/sqlalchemy/dialects/firebird/kinterbasdb.py#L143-L159
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/tkinter/__init__.py
python
Spinbox.selection_range
(self, start, end)
Set the selection from START to END (not included).
Set the selection from START to END (not included).
[ "Set", "the", "selection", "from", "START", "to", "END", "(", "not", "included", ")", "." ]
def selection_range(self, start, end): """Set the selection from START to END (not included).""" self.selection('range', start, end)
[ "def", "selection_range", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "selection", "(", "'range'", ",", "start", ",", "end", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/tkinter/__init__.py#L4355-L4357
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/wsgiref/simple_server.py
python
make_server
( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler )
return server
Create a new WSGI server listening on `host` and `port` for `app`
Create a new WSGI server listening on `host` and `port` for `app`
[ "Create", "a", "new", "WSGI", "server", "listening", "on", "host", "and", "port", "for", "app" ]
def make_server( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler ): """Create a new WSGI server listening on `host` and `port` for `app`""" server = server_class((host, port), handler_class) server.set_app(app) return server
[ "def", "make_server", "(", "host", ",", "port", ",", "app", ",", "server_class", "=", "WSGIServer", ",", "handler_class", "=", "WSGIRequestHandler", ")", ":", "server", "=", "server_class", "(", "(", "host", ",", "port", ")", ",", "handler_class", ")", "se...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/wsgiref/simple_server.py#L140-L146
IntelPython/sdc
1ebf55c00ef38dfbd401a70b3945e352a5a38b87
sdc/sdc_autogenerated.py
python
sdc_str_arr_operator_ne
(self, other)
return _sdc_str_arr_operator_ne_impl
[]
def sdc_str_arr_operator_ne(self, other): self_is_str_arr = self == string_array_type other_is_str_arr = other == string_array_type operands_are_arrays = self_is_str_arr and other_is_str_arr if not (operands_are_arrays or (self_is_str_arr and isinstance(other, types.UnicodeType)) or (isinstance(self, types.UnicodeType) and other_is_str_arr)): return None if operands_are_arrays: def _sdc_str_arr_operator_ne_impl(self, other): if len(self) != len(other): raise ValueError("Mismatch of String Arrays sizes in operator.ne") n = len(self) out_list = [False] * n for i in numba.prange(n): out_list[i] = (self[i] != other[i] or (str_arr_is_na(self, i) or str_arr_is_na(other, i))) return out_list elif self_is_str_arr: def _sdc_str_arr_operator_ne_impl(self, other): n = len(self) out_list = [False] * n for i in numba.prange(n): out_list[i] = (self[i] != other or (str_arr_is_na(self, i))) return out_list elif other_is_str_arr: def _sdc_str_arr_operator_ne_impl(self, other): n = len(other) out_list = [False] * n for i in numba.prange(n): out_list[i] = (self != other[i] or (str_arr_is_na(other, i))) return out_list else: return None return _sdc_str_arr_operator_ne_impl
[ "def", "sdc_str_arr_operator_ne", "(", "self", ",", "other", ")", ":", "self_is_str_arr", "=", "self", "==", "string_array_type", "other_is_str_arr", "=", "other", "==", "string_array_type", "operands_are_arrays", "=", "self_is_str_arr", "and", "other_is_str_arr", "if",...
https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/sdc/sdc_autogenerated.py#L2881-L2921
juanifioren/django-oidc-provider
f0daed07b2ac7608565b80d4c80ccf04d8c416a8
oidc_provider/lib/utils/token.py
python
create_code
(user, client, scope, nonce, is_authentication, code_challenge=None, code_challenge_method=None)
return code
Create and populate a Code object. Return a Code object.
Create and populate a Code object. Return a Code object.
[ "Create", "and", "populate", "a", "Code", "object", ".", "Return", "a", "Code", "object", "." ]
def create_code(user, client, scope, nonce, is_authentication, code_challenge=None, code_challenge_method=None): """ Create and populate a Code object. Return a Code object. """ code = Code() code.user = user code.client = client code.code = uuid.uuid4().hex if code_challenge and code_challenge_method: code.code_challenge = code_challenge code.code_challenge_method = code_challenge_method code.expires_at = timezone.now() + timedelta( seconds=settings.get('OIDC_CODE_EXPIRE')) code.scope = scope code.nonce = nonce code.is_authentication = is_authentication return code
[ "def", "create_code", "(", "user", ",", "client", ",", "scope", ",", "nonce", ",", "is_authentication", ",", "code_challenge", "=", "None", ",", "code_challenge_method", "=", "None", ")", ":", "code", "=", "Code", "(", ")", "code", ".", "user", "=", "use...
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/token.py#L126-L148
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/mailbox.py
python
Mailbox.lock
(self)
Lock the mailbox.
Lock the mailbox.
[ "Lock", "the", "mailbox", "." ]
def lock(self): """Lock the mailbox.""" raise NotImplementedError('Method must be implemented by subclass')
[ "def", "lock", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Method must be implemented by subclass'", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/mailbox.py#L186-L188
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/legacy/transformer/utils/metrics.py
python
padded_accuracy_topk
(logits, labels, k)
Percentage of times that top-k predictions matches labels on non-0s.
Percentage of times that top-k predictions matches labels on non-0s.
[ "Percentage", "of", "times", "that", "top", "-", "k", "predictions", "matches", "labels", "on", "non", "-", "0s", "." ]
def padded_accuracy_topk(logits, labels, k): """Percentage of times that top-k predictions matches labels on non-0s.""" with tf.variable_scope("padded_accuracy_topk", values=[logits, labels]): logits, labels = _pad_tensors_to_same_length(logits, labels) weights = tf.cast(tf.not_equal(labels, 0), tf.float32) effective_k = tf.minimum(k, tf.shape(logits)[-1]) _, outputs = tf.nn.top_k(logits, k=effective_k) outputs = tf.cast(outputs, tf.int32) padded_labels = tf.cast(labels, tf.int32) padded_labels = tf.expand_dims(padded_labels, axis=-1) padded_labels += tf.zeros_like(outputs) # Pad to same shape. same = tf.cast(tf.equal(outputs, padded_labels), tf.float32) same_topk = tf.reduce_sum(same, axis=-1) return same_topk, weights
[ "def", "padded_accuracy_topk", "(", "logits", ",", "labels", ",", "k", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"padded_accuracy_topk\"", ",", "values", "=", "[", "logits", ",", "labels", "]", ")", ":", "logits", ",", "labels", "=", "_pad_tens...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/legacy/transformer/utils/metrics.py#L151-L164
yuanxiaosc/DeepNude-an-Image-to-Image-technology
87d684ef59d2de4e8b38f66a71cdd392b203ab95
Neural_style_transfer/train_and_inference_by_image_transfer_model.py
python
ImageTransferBaseOnVGG19.style_content_loss
(self, outputs, style_weight=1e-2, content_weight=1e4)
return loss
[]
def style_content_loss(self, outputs, style_weight=1e-2, content_weight=1e4): style_outputs = outputs['style'] content_outputs = outputs['content'] style_loss = tf.add_n([tf.reduce_mean((style_outputs[name] - self.style_targets[name]) ** 2) for name in style_outputs.keys()]) style_loss *= style_weight / self.extractor.num_style_layers content_loss = tf.add_n([tf.reduce_mean((content_outputs[name] - self.content_targets[name]) ** 2) for name in content_outputs.keys()]) content_loss *= content_weight / self.extractor.num_content_layers loss = style_loss + content_loss return loss
[ "def", "style_content_loss", "(", "self", ",", "outputs", ",", "style_weight", "=", "1e-2", ",", "content_weight", "=", "1e4", ")", ":", "style_outputs", "=", "outputs", "[", "'style'", "]", "content_outputs", "=", "outputs", "[", "'content'", "]", "style_loss...
https://github.com/yuanxiaosc/DeepNude-an-Image-to-Image-technology/blob/87d684ef59d2de4e8b38f66a71cdd392b203ab95/Neural_style_transfer/train_and_inference_by_image_transfer_model.py#L81-L92
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/nephoscale.py
python
NephoscaleNodeDriver.destroy_node
(self, node)
return result.get("response") in VALID_RESPONSE_CODES
destroy a node
destroy a node
[ "destroy", "a", "node" ]
def destroy_node(self, node): """destroy a node""" result = self.connection.request( "/server/cloud/%s/" % node.id, method="DELETE" ).object return result.get("response") in VALID_RESPONSE_CODES
[ "def", "destroy_node", "(", "self", ",", "node", ")", ":", "result", "=", "self", ".", "connection", ".", "request", "(", "\"/server/cloud/%s/\"", "%", "node", ".", "id", ",", "method", "=", "\"DELETE\"", ")", ".", "object", "return", "result", ".", "get...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/nephoscale.py#L233-L238
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
static/deploy/openvino/python/transforms/seg_transforms.py
python
RandomDistort.__init__
(self, brightness_range=0.5, brightness_prob=0.5, contrast_range=0.5, contrast_prob=0.5, saturation_range=0.5, saturation_prob=0.5, hue_range=18, hue_prob=0.5)
[]
def __init__(self, brightness_range=0.5, brightness_prob=0.5, contrast_range=0.5, contrast_prob=0.5, saturation_range=0.5, saturation_prob=0.5, hue_range=18, hue_prob=0.5): self.brightness_range = brightness_range self.brightness_prob = brightness_prob self.contrast_range = contrast_range self.contrast_prob = contrast_prob self.saturation_range = saturation_range self.saturation_prob = saturation_prob self.hue_range = hue_range self.hue_prob = hue_prob
[ "def", "__init__", "(", "self", ",", "brightness_range", "=", "0.5", ",", "brightness_prob", "=", "0.5", ",", "contrast_range", "=", "0.5", ",", "contrast_prob", "=", "0.5", ",", "saturation_range", "=", "0.5", ",", "saturation_prob", "=", "0.5", ",", "hue_r...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/static/deploy/openvino/python/transforms/seg_transforms.py#L973-L989
ewels/MultiQC
9b953261d3d684c24eef1827a5ce6718c847a5af
multiqc/modules/pycoqc/pycoqc.py
python
MultiqcModule.load_data
(self, f)
Load the PycoQC YAML file
Load the PycoQC YAML file
[ "Load", "the", "PycoQC", "YAML", "file" ]
def load_data(self, f): """Load the PycoQC YAML file""" try: return yaml.load(f, Loader=yaml.SafeLoader) except Exception as e: log.warning("Could not parse YAML for '{}': \n {}".format(f, e)) return None
[ "def", "load_data", "(", "self", ",", "f", ")", ":", "try", ":", "return", "yaml", ".", "load", "(", "f", ",", "Loader", "=", "yaml", ".", "SafeLoader", ")", "except", "Exception", "as", "e", ":", "log", ".", "warning", "(", "\"Could not parse YAML for...
https://github.com/ewels/MultiQC/blob/9b953261d3d684c24eef1827a5ce6718c847a5af/multiqc/modules/pycoqc/pycoqc.py#L61-L67
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/nntplib.py
python
NNTP.body
(self, id, file=None)
return self.artcmd('BODY ' + id, file)
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
[ "Process", "a", "BODY", "command", ".", "Argument", ":", "-", "id", ":", "article", "number", "or", "message", "id", "-", "file", ":", "Filename", "string", "or", "file", "object", "to", "store", "the", "article", "in", "Returns", ":", "-", "resp", ":"...
def body(self, id, file=None): """Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used""" return self.artcmd('BODY ' + id, file)
[ "def", "body", "(", "self", ",", "id", ",", "file", "=", "None", ")", ":", "return", "self", ".", "artcmd", "(", "'BODY '", "+", "id", ",", "file", ")" ]
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/nntplib.py#L431-L442
DetectionTeamUCAS/R2CNN-Plus-Plus_Tensorflow
06a1faf36d8f1a127612e428d5475c8f04f345c6
data/io/image_preprocess.py
python
short_side_resize
(img_tensor, gtboxes_and_label, target_shortside_len)
return img_tensor, tf.transpose(tf.stack([x1, y1, x2, y2, x3, y3, x4, y4, label], axis=0))
:param img_tensor:[h, w, c], gtboxes_and_label:[-1, 9] :param target_shortside_len: :return:
[]
def short_side_resize(img_tensor, gtboxes_and_label, target_shortside_len): ''' :param img_tensor:[h, w, c], gtboxes_and_label:[-1, 9] :param target_shortside_len: :return: ''' h, w = tf.shape(img_tensor)[0], tf.shape(img_tensor)[1] new_h, new_w = tf.cond(tf.less(h, w), true_fn=lambda: (target_shortside_len, target_shortside_len * w//h), false_fn=lambda: (target_shortside_len * h//w, target_shortside_len)) img_tensor = tf.expand_dims(img_tensor, axis=0) img_tensor = tf.image.resize_bilinear(img_tensor, [new_h, new_w]) x1, y1, x2, y2, x3, y3, x4, y4, label = tf.unstack(gtboxes_and_label, axis=1) x1, x2, x3, x4 = x1 * new_w//w, x2 * new_w//w, x3 * new_w//w, x4 * new_w//w y1, y2, y3, y4 = y1 * new_h//h, y2 * new_h//h, y3 * new_h//h, y4 * new_h//h img_tensor = tf.squeeze(img_tensor, axis=0) # ensure image tensor rank is 3 return img_tensor, tf.transpose(tf.stack([x1, y1, x2, y2, x3, y3, x4, y4, label], axis=0))
[ "def", "short_side_resize", "(", "img_tensor", ",", "gtboxes_and_label", ",", "target_shortside_len", ")", ":", "h", ",", "w", "=", "tf", ".", "shape", "(", "img_tensor", ")", "[", "0", "]", ",", "tf", ".", "shape", "(", "img_tensor", ")", "[", "1", "]...
https://github.com/DetectionTeamUCAS/R2CNN-Plus-Plus_Tensorflow/blob/06a1faf36d8f1a127612e428d5475c8f04f345c6/data/io/image_preprocess.py#L12-L35
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/datasets/common/dataset.py
python
Dataset.transforms
(self)
return self._transforms
Transform function which can replace transforms.
Transform function which can replace transforms.
[ "Transform", "function", "which", "can", "replace", "transforms", "." ]
def transforms(self): """Transform function which can replace transforms.""" return self._transforms
[ "def", "transforms", "(", "self", ")", ":", "return", "self", ".", "_transforms" ]
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/datasets/common/dataset.py#L78-L80
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/qwikswitch/sensor.py
python
QSSensor.__init__
(self, sensor)
Initialize the sensor.
Initialize the sensor.
[ "Initialize", "the", "sensor", "." ]
def __init__(self, sensor): """Initialize the sensor.""" super().__init__(sensor["id"], sensor["name"]) self.channel = sensor["channel"] sensor_type = sensor["type"] self._decode, self.unit = SENSORS[sensor_type] # this cannot happen because it only happens in bool and this should be redirected to binary_sensor assert not isinstance( self.unit, type ), f"boolean sensor id={sensor['id']} name={sensor['name']}"
[ "def", "__init__", "(", "self", ",", "sensor", ")", ":", "super", "(", ")", ".", "__init__", "(", "sensor", "[", "\"id\"", "]", ",", "sensor", "[", "\"name\"", "]", ")", "self", ".", "channel", "=", "sensor", "[", "\"channel\"", "]", "sensor_type", "...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/qwikswitch/sensor.py#L39-L50