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
jessevdk/cldoc
fc7f59405c4a891b8367c80a700f5aa3c5c9230c
cldoc/clang/cindex.py
python
Type.is_function_variadic
(self)
return conf.lib.clang_isFunctionTypeVariadic(self)
Determine whether this function Type is a variadic function type.
Determine whether this function Type is a variadic function type.
[ "Determine", "whether", "this", "function", "Type", "is", "a", "variadic", "function", "type", "." ]
def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
[ "def", "is_function_variadic", "(", "self", ")", ":", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "conf", ".", "lib", ".", "clang_isFunctionTypeVariadic", "(", "self", ")" ]
https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L2299-L2303
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/sensehat.py
python
get_temperature
()
return _sensehat.get_temperature()
Gets the temperature in degrees Celsius from the humidity sensor. Equivalent to calling ``get_temperature_from_humidity``. If you get strange results try using ``get_temperature_from_pressure``.
Gets the temperature in degrees Celsius from the humidity sensor. Equivalent to calling ``get_temperature_from_humidity``.
[ "Gets", "the", "temperature", "in", "degrees", "Celsius", "from", "the", "humidity", "sensor", ".", "Equivalent", "to", "calling", "get_temperature_from_humidity", "." ]
def get_temperature(): """ Gets the temperature in degrees Celsius from the humidity sensor. Equivalent to calling ``get_temperature_from_humidity``. If you get strange results try using ``get_temperature_from_pressure``. """ return _sensehat.get_temperature()
[ "def", "get_temperature", "(", ")", ":", "return", "_sensehat", ".", "get_temperature", "(", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/sensehat.py#L273-L280
hhursev/recipe-scrapers
478b9ddb0dda02b17b14f299eea729bef8131aa9
recipe_scrapers/bowlofdelicious.py
python
BowlOfDelicious.host
(cls)
return "bowlofdelicious.com"
[]
def host(cls): return "bowlofdelicious.com"
[ "def", "host", "(", "cls", ")", ":", "return", "\"bowlofdelicious.com\"" ]
https://github.com/hhursev/recipe-scrapers/blob/478b9ddb0dda02b17b14f299eea729bef8131aa9/recipe_scrapers/bowlofdelicious.py#L6-L7
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/cognito/identity/layer1.py
python
CognitoIdentityConnection.get_id
(self, account_id, identity_pool_id, logins=None)
return self.make_request(action='GetId', body=json.dumps(params))
Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account. :type account_id: string :param account_id: A standard AWS account ID (9+ digits). :type identity_pool_id: string :param identity_pool_id: An identity pool ID in the format REGION:GUID. :type logins: map :param logins: A set of optional name-value pairs that map provider names to provider tokens. The available provider names for `Logins` are as follows: + Facebook: `graph.facebook.com` + Google: `accounts.google.com` + Amazon: `www.amazon.com`
Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.
[ "Generates", "(", "or", "retrieves", ")", "a", "Cognito", "ID", ".", "Supplying", "multiple", "logins", "will", "create", "an", "implicit", "linked", "account", "." ]
def get_id(self, account_id, identity_pool_id, logins=None): """ Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account. :type account_id: string :param account_id: A standard AWS account ID (9+ digits). :type identity_pool_id: string :param identity_pool_id: An identity pool ID in the format REGION:GUID. :type logins: map :param logins: A set of optional name-value pairs that map provider names to provider tokens. The available provider names for `Logins` are as follows: + Facebook: `graph.facebook.com` + Google: `accounts.google.com` + Amazon: `www.amazon.com` """ params = { 'AccountId': account_id, 'IdentityPoolId': identity_pool_id, } if logins is not None: params['Logins'] = logins return self.make_request(action='GetId', body=json.dumps(params))
[ "def", "get_id", "(", "self", ",", "account_id", ",", "identity_pool_id", ",", "logins", "=", "None", ")", ":", "params", "=", "{", "'AccountId'", ":", "account_id", ",", "'IdentityPoolId'", ":", "identity_pool_id", ",", "}", "if", "logins", "is", "not", "...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/cognito/identity/layer1.py#L168-L196
instaloader/instaloader
d6e5e310054aa42d3fd8d881389f04d1b4cdbe72
instaloader/structures.py
python
Profile.from_username
(cls, context: InstaloaderContext, username: str)
return profile
Create a Profile instance from a given username, raise exception if it does not exist. See also :meth:`Instaloader.check_profile_id`. :param context: :attr:`Instaloader.context` :param username: Username :raises: :class:`ProfileNotExistsException`
Create a Profile instance from a given username, raise exception if it does not exist.
[ "Create", "a", "Profile", "instance", "from", "a", "given", "username", "raise", "exception", "if", "it", "does", "not", "exist", "." ]
def from_username(cls, context: InstaloaderContext, username: str): """Create a Profile instance from a given username, raise exception if it does not exist. See also :meth:`Instaloader.check_profile_id`. :param context: :attr:`Instaloader.context` :param username: Username :raises: :class:`ProfileNotExistsException` """ # pylint:disable=protected-access profile = cls(context, {'username': username.lower()}) profile._obtain_metadata() # to raise ProfileNotExistsException now in case username is invalid return profile
[ "def", "from_username", "(", "cls", ",", "context", ":", "InstaloaderContext", ",", "username", ":", "str", ")", ":", "# pylint:disable=protected-access", "profile", "=", "cls", "(", "context", ",", "{", "'username'", ":", "username", ".", "lower", "(", ")", ...
https://github.com/instaloader/instaloader/blob/d6e5e310054aa42d3fd8d881389f04d1b4cdbe72/instaloader/structures.py#L629-L641
tenzir/threatbus
a26096e7b61b3eddf25c445d40a6cd2ea4420558
apps/zmq-app-template/zmq_app_template/template.py
python
subscribe
(endpoint: str, topic: str, snapshot: int, timeout: int = 5)
return send_manage_message(endpoint, action, timeout)
Subscribes this app to Threat Bus for the given topic. Requests an optional snapshot of historical indicators. @param endpoint The ZMQ management endpoint of Threat Bus ('host:port') @param topic The topic to subscribe to @param snapshot An integer value to request n days of historical IoC items @param timeout The period after which the connection attempt is aborted
Subscribes this app to Threat Bus for the given topic. Requests an optional snapshot of historical indicators.
[ "Subscribes", "this", "app", "to", "Threat", "Bus", "for", "the", "given", "topic", ".", "Requests", "an", "optional", "snapshot", "of", "historical", "indicators", "." ]
def subscribe(endpoint: str, topic: str, snapshot: int, timeout: int = 5): """ Subscribes this app to Threat Bus for the given topic. Requests an optional snapshot of historical indicators. @param endpoint The ZMQ management endpoint of Threat Bus ('host:port') @param topic The topic to subscribe to @param snapshot An integer value to request n days of historical IoC items @param timeout The period after which the connection attempt is aborted """ global logger logger.info(f"Subscribing to topic '{topic}'...") action = {"action": "subscribe", "topic": topic, "snapshot": snapshot} return send_manage_message(endpoint, action, timeout)
[ "def", "subscribe", "(", "endpoint", ":", "str", ",", "topic", ":", "str", ",", "snapshot", ":", "int", ",", "timeout", ":", "int", "=", "5", ")", ":", "global", "logger", "logger", ".", "info", "(", "f\"Subscribing to topic '{topic}'...\"", ")", "action",...
https://github.com/tenzir/threatbus/blob/a26096e7b61b3eddf25c445d40a6cd2ea4420558/apps/zmq-app-template/zmq_app_template/template.py#L132-L144
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/mako/pygen.py
python
PythonPrinter.__init__
(self, stream)
[]
def __init__(self, stream): # indentation counter self.indent = 0 # a stack storing information about why we incremented # the indentation counter, to help us determine if we # should decrement it self.indent_detail = [] # the string of whitespace multiplied by the indent # counter to produce a line self.indentstring = " " # the stream we are writing to self.stream = stream # current line number self.lineno = 1 # a list of lines that represents a buffered "block" of code, # which can be later printed relative to an indent level self.line_buffer = [] self.in_indent_lines = False self._reset_multi_line_flags() # mapping of generated python lines to template # source lines self.source_map = {}
[ "def", "__init__", "(", "self", ",", "stream", ")", ":", "# indentation counter", "self", ".", "indent", "=", "0", "# a stack storing information about why we incremented", "# the indentation counter, to help us determine if we", "# should decrement it", "self", ".", "indent_de...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/mako/pygen.py#L15-L44
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idc.py
python
GetDisasm
(ea)
return GetDisasmEx(ea, 0)
Get disassembly line @param ea: linear address of instruction @return: "" - could not decode instruction at the specified location @note: this function may not return exactly the same mnemonics as you see on the screen.
Get disassembly line
[ "Get", "disassembly", "line" ]
def GetDisasm(ea): """ Get disassembly line @param ea: linear address of instruction @return: "" - could not decode instruction at the specified location @note: this function may not return exactly the same mnemonics as you see on the screen. """ return GetDisasmEx(ea, 0)
[ "def", "GetDisasm", "(", "ea", ")", ":", "return", "GetDisasmEx", "(", "ea", ",", "0", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idc.py#L2213-L2224
ricequant/rqalpha
d8b345ca3fde299e061c6a89c1f2c362c3584c96
rqalpha/portfolio/__init__.py
python
Portfolio.accounts
(self)
return self._accounts
账户字典
账户字典
[ "账户字典" ]
def accounts(self): # type: () -> Dict[DEFAULT_ACCOUNT_TYPE, Account] """ 账户字典 """ return self._accounts
[ "def", "accounts", "(", "self", ")", ":", "# type: () -> Dict[DEFAULT_ACCOUNT_TYPE, Account]", "return", "self", ".", "_accounts" ]
https://github.com/ricequant/rqalpha/blob/d8b345ca3fde299e061c6a89c1f2c362c3584c96/rqalpha/portfolio/__init__.py#L111-L116
googlefonts/fontbakery
cb8196c3a636b63654f8370636cb3f438b60d5b1
Lib/fontbakery/profiles/googlefonts.py
python
com_google_fonts_check_old_ttfautohint
(ttFont)
Font has old ttfautohint applied?
Font has old ttfautohint applied?
[ "Font", "has", "old", "ttfautohint", "applied?" ]
def com_google_fonts_check_old_ttfautohint(ttFont): """Font has old ttfautohint applied?""" from fontbakery.utils import get_name_entry_strings def ttfautohint_version(values): import re for value in values: results = re.search(r'ttfautohint \(v(.*)\)', value) if results: return results.group(1) version_strings = get_name_entry_strings(ttFont, NameID.VERSION_STRING) ttfa_version = ttfautohint_version(version_strings) if len(version_strings) == 0: yield FAIL,\ Message("lacks-version-strings", "This font file lacks mandatory " "version strings in its name table.") elif ttfa_version is None: yield INFO,\ Message("version-not-detected", f"Could not detect which version of" f" ttfautohint was used in this font." f" It is typically specified as a comment" f" in the font version entries of the 'name' table." f" Such font version strings are currently:" f" {version_strings}") else: try: if LATEST_TTFAUTOHINT_VERSION > ttfa_version: yield WARN,\ Message("old-ttfa", f"ttfautohint used in font = {ttfa_version};" f" latest = {LATEST_TTFAUTOHINT_VERSION};" f" Need to re-run with the newer version!") else: yield PASS, (f"Font has been hinted with ttfautohint {ttfa_version}" f" which is greater than or equal to the latest" f" known version {LATEST_TTFAUTOHINT_VERSION}") except ValueError: yield FAIL,\ Message("parse-error", f"Failed to parse ttfautohint version values:" f" latest = '{LATEST_TTFAUTOHINT_VERSION}';" f" used_in_font = '{ttfa_version}'")
[ "def", "com_google_fonts_check_old_ttfautohint", "(", "ttFont", ")", ":", "from", "fontbakery", ".", "utils", "import", "get_name_entry_strings", "def", "ttfautohint_version", "(", "values", ")", ":", "import", "re", "for", "value", "in", "values", ":", "results", ...
https://github.com/googlefonts/fontbakery/blob/cb8196c3a636b63654f8370636cb3f438b60d5b1/Lib/fontbakery/profiles/googlefonts.py#L1600-L1644
hudson-and-thames/mlfinlab
79dcc7120ec84110578f75b025a75850eb72fc73
mlfinlab/microstructural_features/entropy.py
python
get_konto_entropy
(message: str, window: int = 0)
Advances in Financial Machine Learning, Snippet 18.4, page 268. Implementations of Algorithms Discussed in Gao et al.[2008] Get Kontoyiannis entropy :param message: (str or array) Encoded message :param window: (int) Expanding window length, can be negative :return: (float) Kontoyiannis entropy
Advances in Financial Machine Learning, Snippet 18.4, page 268.
[ "Advances", "in", "Financial", "Machine", "Learning", "Snippet", "18", ".", "4", "page", "268", "." ]
def get_konto_entropy(message: str, window: int = 0) -> float: """ Advances in Financial Machine Learning, Snippet 18.4, page 268. Implementations of Algorithms Discussed in Gao et al.[2008] Get Kontoyiannis entropy :param message: (str or array) Encoded message :param window: (int) Expanding window length, can be negative :return: (float) Kontoyiannis entropy """ pass
[ "def", "get_konto_entropy", "(", "message", ":", "str", ",", "window", ":", "int", "=", "0", ")", "->", "float", ":", "pass" ]
https://github.com/hudson-and-thames/mlfinlab/blob/79dcc7120ec84110578f75b025a75850eb72fc73/mlfinlab/microstructural_features/entropy.py#L82-L95
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
var/spack/repos/builtin/packages/catalyst/package.py
python
Catalyst.root_cmakelists_dir
(self)
return os.path.join(self.stage.source_path, 'Catalyst-v' + str(self.version))
The relative path to the directory containing CMakeLists.txt This path is relative to the root of the extracted tarball, not to the ``build_directory``. Defaults to the current directory. :return: directory containing CMakeLists.txt
The relative path to the directory containing CMakeLists.txt
[ "The", "relative", "path", "to", "the", "directory", "containing", "CMakeLists", ".", "txt" ]
def root_cmakelists_dir(self): """The relative path to the directory containing CMakeLists.txt This path is relative to the root of the extracted tarball, not to the ``build_directory``. Defaults to the current directory. :return: directory containing CMakeLists.txt """ return os.path.join(self.stage.source_path, 'Catalyst-v' + str(self.version))
[ "def", "root_cmakelists_dir", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "stage", ".", "source_path", ",", "'Catalyst-v'", "+", "str", "(", "self", ".", "version", ")", ")" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/var/spack/repos/builtin/packages/catalyst/package.py#L192-L201
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/devices/cassette.py
python
TapeBitStream.write_intro
(self)
Write some noise to give the reader something to get started.
Write some noise to give the reader something to get started.
[ "Write", "some", "noise", "to", "give", "the", "reader", "something", "to", "get", "started", "." ]
def write_intro(self): """Write some noise to give the reader something to get started.""" # We just need some bits here # however on a new CAS file this works like a magic-sequence... for b in bytearray(self.intro): self.write_byte(b) # Write seven bits, so that we are byte-aligned after the sync bit # (after the 256-byte pilot). Makes CAS-files easier to read in hex. for _ in range(7): self.write_bit(0) self.write_pause(100)
[ "def", "write_intro", "(", "self", ")", ":", "# We just need some bits here", "# however on a new CAS file this works like a magic-sequence...", "for", "b", "in", "bytearray", "(", "self", ".", "intro", ")", ":", "self", ".", "write_byte", "(", "b", ")", "# Write seve...
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/devices/cassette.py#L443-L453
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
idc_get_local_type_name
(*args)
return _idaapi.idc_get_local_type_name(*args)
idc_get_local_type_name(ordinal) -> char
idc_get_local_type_name(ordinal) -> char
[ "idc_get_local_type_name", "(", "ordinal", ")", "-", ">", "char" ]
def idc_get_local_type_name(*args): """ idc_get_local_type_name(ordinal) -> char """ return _idaapi.idc_get_local_type_name(*args)
[ "def", "idc_get_local_type_name", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "idc_get_local_type_name", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L33146-L33150
dragnet-org/dragnet
4a1649d9b29bf64ccc5a86200e415e8b04cd257b
dragnet/extractor.py
python
Extractor._has_enough_blocks
(self, blocks)
return True
[]
def _has_enough_blocks(self, blocks): if len(blocks) < 3: logging.warning( 'extraction failed: too few blocks (%s)', len(blocks)) return False return True
[ "def", "_has_enough_blocks", "(", "self", ",", "blocks", ")", ":", "if", "len", "(", "blocks", ")", "<", "3", ":", "logging", ".", "warning", "(", "'extraction failed: too few blocks (%s)'", ",", "len", "(", "blocks", ")", ")", "return", "False", "return", ...
https://github.com/dragnet-org/dragnet/blob/4a1649d9b29bf64ccc5a86200e415e8b04cd257b/dragnet/extractor.py#L120-L125
python-social-auth/social-core
1ea27e8989657bb35dd37b6ee2e038e1358fbc96
social_core/backends/cilogon.py
python
CILogonOAuth2.user_data
(self, token, *args, **kwargs)
Loads user data from endpoint
Loads user data from endpoint
[ "Loads", "user", "data", "from", "endpoint" ]
def user_data(self, token, *args, **kwargs): """Loads user data from endpoint""" url = 'https://cilogon.org/oauth2/userinfo' data = {'access_token': token} try: return self.get_json(url, method='POST', data=data) except ValueError: return None
[ "def", "user_data", "(", "self", ",", "token", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'https://cilogon.org/oauth2/userinfo'", "data", "=", "{", "'access_token'", ":", "token", "}", "try", ":", "return", "self", ".", "get_json", ...
https://github.com/python-social-auth/social-core/blob/1ea27e8989657bb35dd37b6ee2e038e1358fbc96/social_core/backends/cilogon.py#L18-L25
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/rlib/objectmodel.py
python
_Specialize.ll
(self)
return decorated_func
This is version of argtypes that cares about low-level types (so it'll get additional copies for two different types of pointers for example). Same warnings about exponential behavior apply.
This is version of argtypes that cares about low-level types (so it'll get additional copies for two different types of pointers for example). Same warnings about exponential behavior apply.
[ "This", "is", "version", "of", "argtypes", "that", "cares", "about", "low", "-", "level", "types", "(", "so", "it", "ll", "get", "additional", "copies", "for", "two", "different", "types", "of", "pointers", "for", "example", ")", ".", "Same", "warnings", ...
def ll(self): """ This is version of argtypes that cares about low-level types (so it'll get additional copies for two different types of pointers for example). Same warnings about exponential behavior apply. """ def decorated_func(func): func._annspecialcase_ = 'specialize:ll' return func return decorated_func
[ "def", "ll", "(", "self", ")", ":", "def", "decorated_func", "(", "func", ")", ":", "func", ".", "_annspecialcase_", "=", "'specialize:ll'", "return", "func", "return", "decorated_func" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/rlib/objectmodel.py#L83-L92
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/setuptools/sandbox.py
python
_needs_hiding
(mod_name)
return bool(pattern.match(mod_name))
>>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') True
>>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') True
[ ">>>", "_needs_hiding", "(", "setuptools", ")", "True", ">>>", "_needs_hiding", "(", "pkg_resources", ")", "True", ">>>", "_needs_hiding", "(", "setuptools_plugin", ")", "False", ">>>", "_needs_hiding", "(", "setuptools", ".", "__init__", ")", "True", ">>>", "_n...
def _needs_hiding(mod_name): """ >>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') True """ pattern = re.compile(r'(setuptools|pkg_resources|distutils|Cython)(\.|$)') return bool(pattern.match(mod_name))
[ "def", "_needs_hiding", "(", "mod_name", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'(setuptools|pkg_resources|distutils|Cython)(\\.|$)'", ")", "return", "bool", "(", "pattern", ".", "match", "(", "mod_name", ")", ")" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/setuptools/sandbox.py#L201-L219
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/cgi.py
python
parse_qsl
(qs, keep_blank_values=0, strict_parsing=0)
return urllib.parse.parse_qsl(qs, keep_blank_values, strict_parsing)
Parse a query given as a string argument.
Parse a query given as a string argument.
[ "Parse", "a", "query", "given", "as", "a", "string", "argument", "." ]
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument.""" warn("cgi.parse_qsl is deprecated, use urllib.parse.parse_qsl instead", DeprecationWarning, 2) return urllib.parse.parse_qsl(qs, keep_blank_values, strict_parsing)
[ "def", "parse_qsl", "(", "qs", ",", "keep_blank_values", "=", "0", ",", "strict_parsing", "=", "0", ")", ":", "warn", "(", "\"cgi.parse_qsl is deprecated, use urllib.parse.parse_qsl instead\"", ",", "DeprecationWarning", ",", "2", ")", "return", "urllib", ".", "pars...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/cgi.py#L195-L199
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/dvs.py
python
_get_diff_dict
(dict1, dict2)
return ret_dict
Returns a dictionary with the diffs between two dictionaries It will ignore any key that doesn't exist in dict2
Returns a dictionary with the diffs between two dictionaries
[ "Returns", "a", "dictionary", "with", "the", "diffs", "between", "two", "dictionaries" ]
def _get_diff_dict(dict1, dict2): """ Returns a dictionary with the diffs between two dictionaries It will ignore any key that doesn't exist in dict2 """ ret_dict = {} for p in dict2.keys(): if p not in dict1: ret_dict.update({p: {"val1": None, "val2": dict2[p]}}) elif dict1[p] != dict2[p]: if isinstance(dict1[p], dict) and isinstance(dict2[p], dict): sub_diff_dict = _get_diff_dict(dict1[p], dict2[p]) if sub_diff_dict: ret_dict.update({p: sub_diff_dict}) else: ret_dict.update({p: {"val1": dict1[p], "val2": dict2[p]}}) return ret_dict
[ "def", "_get_diff_dict", "(", "dict1", ",", "dict2", ")", ":", "ret_dict", "=", "{", "}", "for", "p", "in", "dict2", ".", "keys", "(", ")", ":", "if", "p", "not", "in", "dict1", ":", "ret_dict", ".", "update", "(", "{", "p", ":", "{", "\"val1\"",...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/dvs.py#L452-L469
rlvaugh/Impractical_Python_Projects
ff9065e94430dc4ecf76d2c9e78f05fae499213e
Chapter_13/tvashtar.py
python
Particle.vector
(self)
Calculate particle vector at launch.
Calculate particle vector at launch.
[ "Calculate", "particle", "vector", "at", "launch", "." ]
def vector(self): """Calculate particle vector at launch.""" orient = random.uniform(60, 120) # 90 is vertical radians = math.radians(orient) self.dx = self.vel * math.cos(radians) self.dy = -self.vel * math.sin(radians)
[ "def", "vector", "(", "self", ")", ":", "orient", "=", "random", ".", "uniform", "(", "60", ",", "120", ")", "# 90 is vertical", "radians", "=", "math", ".", "radians", "(", "orient", ")", "self", ".", "dx", "=", "self", ".", "vel", "*", "math", "....
https://github.com/rlvaugh/Impractical_Python_Projects/blob/ff9065e94430dc4ecf76d2c9e78f05fae499213e/Chapter_13/tvashtar.py#L41-L46
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
py2manager/gluon/languages.py
python
read_possible_plural_rules
()
return plurals
Creates list of all possible plural rules files The result is cached in PLURAL_RULES dictionary to increase speed
Creates list of all possible plural rules files The result is cached in PLURAL_RULES dictionary to increase speed
[ "Creates", "list", "of", "all", "possible", "plural", "rules", "files", "The", "result", "is", "cached", "in", "PLURAL_RULES", "dictionary", "to", "increase", "speed" ]
def read_possible_plural_rules(): """ Creates list of all possible plural rules files The result is cached in PLURAL_RULES dictionary to increase speed """ plurals = {} try: import gluon.contrib.plural_rules as package for importer, modname, ispkg in pkgutil.iter_modules(package.__path__): if len(modname) == 2: module = __import__(package.__name__ + '.' + modname, fromlist=[modname]) lang = modname pname = modname + '.py' nplurals = getattr(module, 'nplurals', DEFAULT_NPLURALS) get_plural_id = getattr( module, 'get_plural_id', DEFAULT_GET_PLURAL_ID) construct_plural_form = getattr( module, 'construct_plural_form', DEFAULT_CONSTRUCT_PLURAL_FORM) plurals[lang] = (lang, nplurals, get_plural_id, construct_plural_form) except ImportError: e = sys.exc_info()[1] logging.warn('Unable to import plural rules: %s' % e) return plurals
[ "def", "read_possible_plural_rules", "(", ")", ":", "plurals", "=", "{", "}", "try", ":", "import", "gluon", ".", "contrib", ".", "plural_rules", "as", "package", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/languages.py#L185-L211
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/hostvirtual.py
python
HostVirtualNodeDriver._wait_for_node
(self, node_id, timeout=30, interval=5.0)
:param node_id: ID of the node to wait for. :type node_id: ``int`` :param timeout: Timeout (in seconds). :type timeout: ``int`` :param interval: How long to wait (in seconds) between each attempt. :type interval: ``float`` :return: Node representing the newly built server :rtype: :class:`Node`
:param node_id: ID of the node to wait for. :type node_id: ``int``
[ ":", "param", "node_id", ":", "ID", "of", "the", "node", "to", "wait", "for", ".", ":", "type", "node_id", ":", "int" ]
def _wait_for_node(self, node_id, timeout=30, interval=5.0): """ :param node_id: ID of the node to wait for. :type node_id: ``int`` :param timeout: Timeout (in seconds). :type timeout: ``int`` :param interval: How long to wait (in seconds) between each attempt. :type interval: ``float`` :return: Node representing the newly built server :rtype: :class:`Node` """ # poll until we get a node for i in range(0, timeout, int(interval)): try: node = self.ex_get_node(node_id) return node except HostVirtualException: time.sleep(interval) raise HostVirtualException(412, "Timeout on getting node details")
[ "def", "_wait_for_node", "(", "self", ",", "node_id", ",", "timeout", "=", "30", ",", "interval", "=", "5.0", ")", ":", "# poll until we get a node", "for", "i", "in", "range", "(", "0", ",", "timeout", ",", "int", "(", "interval", ")", ")", ":", "try"...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/hostvirtual.py#L441-L463
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/utilities/logger.py
python
PackageLogger.exit
(self, status=0)
Exit the interpreter.
Exit the interpreter.
[ "Exit", "the", "interpreter", "." ]
def exit(self, status=0): """Exit the interpreter.""" sys.exit(status)
[ "def", "exit", "(", "self", ",", "status", "=", "0", ")", ":", "sys", ".", "exit", "(", "status", ")" ]
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/utilities/logger.py#L168-L171
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/tkinter/font.py
python
Font.actual
(self, option=None, displayof=None)
Return actual font attributes
Return actual font attributes
[ "Return", "actual", "font", "attributes" ]
def actual(self, option=None, displayof=None): "Return actual font attributes" args = () if displayof: args = ('-displayof', displayof) if option: args = args + ('-' + option, ) return self._call("font", "actual", self.name, *args) else: return self._mkdict( self._split(self._call("font", "actual", self.name, *args)))
[ "def", "actual", "(", "self", ",", "option", "=", "None", ",", "displayof", "=", "None", ")", ":", "args", "=", "(", ")", "if", "displayof", ":", "args", "=", "(", "'-displayof'", ",", "displayof", ")", "if", "option", ":", "args", "=", "args", "+"...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/tkinter/font.py#L124-L134
m-labs/nmigen
6c5afdc3c37e82854b08861e8b6d95f644b45f6e
nmigen/hdl/ast.py
python
UserValue.lower
(self)
Conversion to a concrete representation.
Conversion to a concrete representation.
[ "Conversion", "to", "a", "concrete", "representation", "." ]
def lower(self): """Conversion to a concrete representation.""" pass
[ "def", "lower", "(", "self", ")", ":", "pass" ]
https://github.com/m-labs/nmigen/blob/6c5afdc3c37e82854b08861e8b6d95f644b45f6e/nmigen/hdl/ast.py#L1134-L1136
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/api/controllers/secretmeta.py
python
SecretMetadataController.__init__
(self, secret)
[]
def __init__(self, secret): LOG.debug('=== Creating SecretMetadataController ===') self.secret = secret self.secret_project_id = self.secret.project.external_id self.secret_repo = repo.get_secret_repository() self.user_meta_repo = repo.get_secret_user_meta_repository() self.metadata_validator = validators.NewSecretMetadataValidator() self.metadatum_validator = validators.NewSecretMetadatumValidator()
[ "def", "__init__", "(", "self", ",", "secret", ")", ":", "LOG", ".", "debug", "(", "'=== Creating SecretMetadataController ==='", ")", "self", ".", "secret", "=", "secret", "self", ".", "secret_project_id", "=", "self", ".", "secret", ".", "project", ".", "e...
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/api/controllers/secretmeta.py#L34-L41
thu-ml/tianshou
a2d76d1276bef334bba537a355a5ea12f4279410
tianshou/policy/modelfree/npg.py
python
NPGPolicy._MVP
(self, v: torch.Tensor, flat_kl_grad: torch.Tensor)
return flat_kl_grad_grad + v * self._damping
Matrix vector product.
Matrix vector product.
[ "Matrix", "vector", "product", "." ]
def _MVP(self, v: torch.Tensor, flat_kl_grad: torch.Tensor) -> torch.Tensor: """Matrix vector product.""" # caculate second order gradient of kl with respect to theta kl_v = (flat_kl_grad * v).sum() flat_kl_grad_grad = self._get_flat_grad(kl_v, self.actor, retain_graph=True).detach() return flat_kl_grad_grad + v * self._damping
[ "def", "_MVP", "(", "self", ",", "v", ":", "torch", ".", "Tensor", ",", "flat_kl_grad", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# caculate second order gradient of kl with respect to theta", "kl_v", "=", "(", "flat_kl_grad", "*", ...
https://github.com/thu-ml/tianshou/blob/a2d76d1276bef334bba537a355a5ea12f4279410/tianshou/policy/modelfree/npg.py#L140-L146
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/objspace/std/bytesobject.py
python
W_AbstractBytesObject.descr_swapcase
(self, space)
S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa.
S.swapcase() -> string
[ "S", ".", "swapcase", "()", "-", ">", "string" ]
def descr_swapcase(self, space): """S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. """
[ "def", "descr_swapcase", "(", "self", ",", "space", ")", ":" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/objspace/std/bytesobject.py#L399-L404
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol47903.py
python
decode_replay_initdata
(contents)
return decoder.instance(replay_initdata_typeid)
Decodes and return the replay init data from the contents byte string.
Decodes and return the replay init data from the contents byte string.
[ "Decodes", "and", "return", "the", "replay", "init", "data", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_initdata(contents): """Decodes and return the replay init data from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) return decoder.instance(replay_initdata_typeid)
[ "def", "decode_replay_initdata", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "return", "decoder", ".", "instance", "(", "replay_initdata_typeid", ")" ]
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol47903.py#L437-L440
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/mailbox.py
python
MaildirMessage.get_subdir
(self)
return self._subdir
Return 'new' or 'cur'.
Return 'new' or 'cur'.
[ "Return", "new", "or", "cur", "." ]
def get_subdir(self): """Return 'new' or 'cur'.""" return self._subdir
[ "def", "get_subdir", "(", "self", ")", ":", "return", "self", ".", "_subdir" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/mailbox.py#L1431-L1433
junfu1115/DANet
56a612ec1ed5c2573ebc8df04ad08475fbf13a52
encoding/functions/customize.py
python
NonMaxSuppression
(boxes, scores, threshold)
r"""Non-Maximum Suppression The algorithm begins by storing the highest-scoring bounding box, and eliminating any box whose intersection-over-union (IoU) with it is too great. The procedure repeats on the surviving boxes, and so on until there are no boxes left. The stored boxes are returned. NB: The function returns a tuple (mask, indices), where indices index into the input boxes and are sorted according to score, from higest to lowest. indices[i][mask[i]] gives the indices of the surviving boxes from the ith batch, sorted by score. Args: - boxes :math:`(N, n_boxes, 4)` - scroes :math:`(N, n_boxes)` - threshold (float): IoU above which to eliminate boxes Outputs: - mask: :math:`(N, n_boxes)` - indicies: :math:`(N, n_boxes)` Examples:: >>> boxes = torch.Tensor([[[10., 20., 20., 15.], >>> [24., 22., 50., 54.], >>> [10., 21., 20. 14.5]]]) >>> scores = torch.abs(torch.randn([1, 3])) >>> mask, indices = NonMaxSuppression(boxes, scores, 0.7) >>> #indices are SORTED according to score. >>> surviving_box_indices = indices[mask]
r"""Non-Maximum Suppression The algorithm begins by storing the highest-scoring bounding box, and eliminating any box whose intersection-over-union (IoU) with it is too great. The procedure repeats on the surviving boxes, and so on until there are no boxes left. The stored boxes are returned.
[ "r", "Non", "-", "Maximum", "Suppression", "The", "algorithm", "begins", "by", "storing", "the", "highest", "-", "scoring", "bounding", "box", "and", "eliminating", "any", "box", "whose", "intersection", "-", "over", "-", "union", "(", "IoU", ")", "with", ...
def NonMaxSuppression(boxes, scores, threshold): r"""Non-Maximum Suppression The algorithm begins by storing the highest-scoring bounding box, and eliminating any box whose intersection-over-union (IoU) with it is too great. The procedure repeats on the surviving boxes, and so on until there are no boxes left. The stored boxes are returned. NB: The function returns a tuple (mask, indices), where indices index into the input boxes and are sorted according to score, from higest to lowest. indices[i][mask[i]] gives the indices of the surviving boxes from the ith batch, sorted by score. Args: - boxes :math:`(N, n_boxes, 4)` - scroes :math:`(N, n_boxes)` - threshold (float): IoU above which to eliminate boxes Outputs: - mask: :math:`(N, n_boxes)` - indicies: :math:`(N, n_boxes)` Examples:: >>> boxes = torch.Tensor([[[10., 20., 20., 15.], >>> [24., 22., 50., 54.], >>> [10., 21., 20. 14.5]]]) >>> scores = torch.abs(torch.randn([1, 3])) >>> mask, indices = NonMaxSuppression(boxes, scores, 0.7) >>> #indices are SORTED according to score. >>> surviving_box_indices = indices[mask] """ if boxes.is_cuda: return lib.gpu.non_max_suppression(boxes, scores, threshold) else: return lib.cpu.non_max_suppression(boxes, scores, threshold)
[ "def", "NonMaxSuppression", "(", "boxes", ",", "scores", ",", "threshold", ")", ":", "if", "boxes", ".", "is_cuda", ":", "return", "lib", ".", "gpu", ".", "non_max_suppression", "(", "boxes", ",", "scores", ",", "threshold", ")", "else", ":", "return", "...
https://github.com/junfu1115/DANet/blob/56a612ec1ed5c2573ebc8df04ad08475fbf13a52/encoding/functions/customize.py#L18-L54
aroberge/friendly
0b82326ba1cb982f8612885ac60957f095d7476f
friendly/core.py
python
TracebackData.get_source_info
(self)
Retrieves the file name and the line of code where the exception was raised.
Retrieves the file name and the line of code where the exception was raised.
[ "Retrieves", "the", "file", "name", "and", "the", "line", "of", "code", "where", "the", "exception", "was", "raised", "." ]
def get_source_info(self): """Retrieves the file name and the line of code where the exception was raised. """ if issubclass(self.exception_type, SyntaxError): self.filename = self.value.filename # Python 3.10 introduced new arguments. For simplicity, # we give them some default values for other Python versions # so that we can use these elsewhere without having to perform # additional checks. if not hasattr(self.value, "end_offset"): self.value.end_offset = ( self.value.offset + 1 if self.value.offset else 0 ) self.value.end_lineno = self.value.lineno if self.value.text is not None: self.bad_line = self.value.text # typically includes "\n" return # this can happen with editors_helpers.check_syntax() try: self.bad_line = cache.get_source_lines(self.filename)[ self.value.lineno - 1 ] except Exception: # noqa self.bad_line = "\n" return if self.records: self.exception_frame, self.filename, linenumber, _, _, _ = self.records[-1] _, line = cache.get_formatted_partial_source(self.filename, linenumber) self.bad_line = line.rstrip() if len(self.records) > 1: self.program_stopped_frame, filename, linenumber, *_rest = self.records[ 0 ] _, line = cache.get_formatted_partial_source(filename, linenumber) self.program_stopped_bad_line = line.rstrip() else: self.program_stopped_bad_line = self.bad_line self.program_stopped_frame = self.exception_frame return # We should never reach this stage. def _log_error(): # pragma: no cover debug_helper.log("Internal error in TracebackData.get_source_info.") debug_helper.log("No records found.") debug_helper.log("self.exception_type:" + str(self.exception_type)) debug_helper.log("self.value:" + str(self.value)) debug_helper.log_error() _log_error()
[ "def", "get_source_info", "(", "self", ")", ":", "if", "issubclass", "(", "self", ".", "exception_type", ",", "SyntaxError", ")", ":", "self", ".", "filename", "=", "self", ".", "value", ".", "filename", "# Python 3.10 introduced new arguments. For simplicity,", "...
https://github.com/aroberge/friendly/blob/0b82326ba1cb982f8612885ac60957f095d7476f/friendly/core.py#L135-L186
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/gui/uberwidgets/connectionlist.py
python
ConnectionPanel.UpdateSkin
(self)
The usual update skin
The usual update skin
[ "The", "usual", "update", "skin" ]
def UpdateSkin(self): """ The usual update skin """ key = self.skinkey s = lambda k,d=None: skin.get('%s.%s'%(key,k),d) self.bg = s('backgrounds.account',lambda: SkinColor(wx.WHITE)) self.majorfont = s('Fonts.Account', default_font) self.minorfont = s('Fonts.StateAndLink',default_font) self.linkfont = CopyFont(self.minorfont, underline=True) self.majorfc = s('FontColors.Account', wx.BLACK) self.statefc = s('FontColors.State',lambda: wx.Colour(125,125,125)) self.linkfc = s('FontColors.Link', wx.BLUE) self.closeicon = [None]*3 self.closeicon[0] = s('Icons.Close',skin.get('AppDefaults.removeicon')).ResizedSmaller(16) self.closeicon[1] = s('Icons.CloseHover',self.closeicon[0]).ResizedSmaller(16) self.closeicon[2] = s('Icons.CloseDown',self.closeicon[1]).ResizedSmaller(16) self.liconsize = s('ServiceIconSize',16) self.padding = s('Padding',lambda: wx.Point(3,3)) self.stateicon = self.account.statusicon.ResizedSmaller(16) self.licon = self.account.serviceicon.Resized(self.liconsize) if self.initover: self.CalcLayout()
[ "def", "UpdateSkin", "(", "self", ")", ":", "key", "=", "self", ".", "skinkey", "s", "=", "lambda", "k", ",", "d", "=", "None", ":", "skin", ".", "get", "(", "'%s.%s'", "%", "(", "key", ",", "k", ")", ",", "d", ")", "self", ".", "bg", "=", ...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/gui/uberwidgets/connectionlist.py#L502-L529
psd-tools/psd-tools
00241f3aed2ca52a8012e198a0f390ff7d8edca9
src/psd_tools/api/psd_image.py
python
PSDImage.open
(cls, fp, **kwargs)
return self
Open a PSD document. :param fp: filename or file-like object. :param encoding: charset encoding of the pascal string within the file, default 'macroman'. Some psd files need explicit encoding option. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object.
Open a PSD document.
[ "Open", "a", "PSD", "document", "." ]
def open(cls, fp, **kwargs): """ Open a PSD document. :param fp: filename or file-like object. :param encoding: charset encoding of the pascal string within the file, default 'macroman'. Some psd files need explicit encoding option. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object. """ if hasattr(fp, 'read'): self = cls(PSD.read(fp, **kwargs)) else: with open(fp, 'rb') as f: self = cls(PSD.read(f, **kwargs)) return self
[ "def", "open", "(", "cls", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "fp", ",", "'read'", ")", ":", "self", "=", "cls", "(", "PSD", ".", "read", "(", "fp", ",", "*", "*", "kwargs", ")", ")", "else", ":", "with", "o...
https://github.com/psd-tools/psd-tools/blob/00241f3aed2ca52a8012e198a0f390ff7d8edca9/src/psd_tools/api/psd_image.py#L90-L104
pculture/miro
d8e4594441939514dd2ac29812bf37087bb3aea5
tv/lib/downloader.py
python
RemoteDownloader.get_filename
(self)
return self.filename
Returns the filename that we're downloading to. Should not be called until state is "finished."
Returns the filename that we're downloading to. Should not be called until state is "finished."
[ "Returns", "the", "filename", "that", "we", "re", "downloading", "to", ".", "Should", "not", "be", "called", "until", "state", "is", "finished", "." ]
def get_filename(self): """Returns the filename that we're downloading to. Should not be called until state is "finished." """ self.confirm_db_thread() return self.filename
[ "def", "get_filename", "(", "self", ")", ":", "self", ".", "confirm_db_thread", "(", ")", "return", "self", ".", "filename" ]
https://github.com/pculture/miro/blob/d8e4594441939514dd2ac29812bf37087bb3aea5/tv/lib/downloader.py#L873-L878
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.multiple_domains
(self)
return False
Returns True if there are multiple domains in the jar. Returns False otherwise.
Returns True if there are multiple domains in the jar. Returns False otherwise.
[ "Returns", "True", "if", "there", "are", "multiple", "domains", "in", "the", "jar", ".", "Returns", "False", "otherwise", "." ]
def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise.""" domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False
[ "def", "multiple_domains", "(", "self", ")", ":", "domains", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "domain", "is", "not", "None", "and", "cookie", ".", "domain", "in", "domains", ":", "return", "Tru...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py#L255-L263
CharlesBlonde/libpurecoollink
a91362c57a0bc4126279c8c51c407dd713b08e10
libpurecoollink/dyson_pure_state.py
python
DysonPureHotCoolState.__init__
(self, payload)
Create a new Dyson Hot+Cool state. :param product_type: Product type :param payload: Message payload
Create a new Dyson Hot+Cool state.
[ "Create", "a", "new", "Dyson", "Hot", "+", "Cool", "state", "." ]
def __init__(self, payload): """Create a new Dyson Hot+Cool state. :param product_type: Product type :param payload: Message payload """ super().__init__(payload) self._tilt = DysonPureCoolState._get_field_value(self._state, 'tilt') self._fan_focus = DysonPureCoolState._get_field_value(self._state, 'ffoc') self._heat_target = DysonPureCoolState._get_field_value(self._state, 'hmax') self._heat_mode = DysonPureCoolState._get_field_value(self._state, 'hmod') self._heat_state = DysonPureCoolState._get_field_value(self._state, 'hsta')
[ "def", "__init__", "(", "self", ",", "payload", ")", ":", "super", "(", ")", ".", "__init__", "(", "payload", ")", "self", ".", "_tilt", "=", "DysonPureCoolState", ".", "_get_field_value", "(", "self", ".", "_state", ",", "'tilt'", ")", "self", ".", "_...
https://github.com/CharlesBlonde/libpurecoollink/blob/a91362c57a0bc4126279c8c51c407dd713b08e10/libpurecoollink/dyson_pure_state.py#L165-L181
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
urwid/wimp.py
python
CheckBox._repr_words
(self)
return self.__super._repr_words() + [ python3_repr(self.label)]
[]
def _repr_words(self): return self.__super._repr_words() + [ python3_repr(self.label)]
[ "def", "_repr_words", "(", "self", ")", ":", "return", "self", ".", "__super", ".", "_repr_words", "(", ")", "+", "[", "python3_repr", "(", "self", ".", "label", ")", "]" ]
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/urwid/wimp.py#L161-L163
mozilla/telemetry-airflow
8162470e6eaad5688715ee53f32336ebc00bf352
jobs/taar_lite_guidguid.py
python
is_valid_addon
(broadcast_amo_whitelist, guid, addon)
return not ( addon.is_system or addon.app_disabled or addon.type != "extension" or addon.user_disabled or addon.foreign_install or # make sure the amo_whitelist has been broadcast to worker nodes. guid not in broadcast_amo_whitelist.value or # Make sure that the Pioneer addon is explicitly # excluded guid == "pioneer-opt-in@mozilla.org" )
Filter individual addons out to exclude, system addons, legacy addons, disabled addons, sideloaded addons.
Filter individual addons out to exclude, system addons, legacy addons, disabled addons, sideloaded addons.
[ "Filter", "individual", "addons", "out", "to", "exclude", "system", "addons", "legacy", "addons", "disabled", "addons", "sideloaded", "addons", "." ]
def is_valid_addon(broadcast_amo_whitelist, guid, addon): """ Filter individual addons out to exclude, system addons, legacy addons, disabled addons, sideloaded addons. """ return not ( addon.is_system or addon.app_disabled or addon.type != "extension" or addon.user_disabled or addon.foreign_install or # make sure the amo_whitelist has been broadcast to worker nodes. guid not in broadcast_amo_whitelist.value or # Make sure that the Pioneer addon is explicitly # excluded guid == "pioneer-opt-in@mozilla.org" )
[ "def", "is_valid_addon", "(", "broadcast_amo_whitelist", ",", "guid", ",", "addon", ")", ":", "return", "not", "(", "addon", ".", "is_system", "or", "addon", ".", "app_disabled", "or", "addon", ".", "type", "!=", "\"extension\"", "or", "addon", ".", "user_di...
https://github.com/mozilla/telemetry-airflow/blob/8162470e6eaad5688715ee53f32336ebc00bf352/jobs/taar_lite_guidguid.py#L36-L54
owid/covid-19-data
936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92
scripts/src/cowidev/vax/manual/twitter/maldives.py
python
main
(api)
[]
def main(api): Maldives(api).to_csv()
[ "def", "main", "(", "api", ")", ":", "Maldives", "(", "api", ")", ".", "to_csv", "(", ")" ]
https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/manual/twitter/maldives.py#L39-L40
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/tensorpack/callbacks/monitor.py
python
TFEventWriter.__init__
(self, logdir=None, max_queue=10, flush_secs=120)
Args: Same as in :class:`tf.summary.FileWriter`. logdir will be ``logger.get_logger_dir()`` by default.
Args: Same as in :class:`tf.summary.FileWriter`. logdir will be ``logger.get_logger_dir()`` by default.
[ "Args", ":", "Same", "as", "in", ":", "class", ":", "tf", ".", "summary", ".", "FileWriter", ".", "logdir", "will", "be", "logger", ".", "get_logger_dir", "()", "by", "default", "." ]
def __init__(self, logdir=None, max_queue=10, flush_secs=120): """ Args: Same as in :class:`tf.summary.FileWriter`. logdir will be ``logger.get_logger_dir()`` by default. """ if logdir is None: logdir = logger.get_logger_dir() assert tf.gfile.IsDirectory(logdir), logdir self._logdir = logdir self._max_queue = max_queue self._flush_secs = flush_secs
[ "def", "__init__", "(", "self", ",", "logdir", "=", "None", ",", "max_queue", "=", "10", ",", "flush_secs", "=", "120", ")", ":", "if", "logdir", "is", "None", ":", "logdir", "=", "logger", ".", "get_logger_dir", "(", ")", "assert", "tf", ".", "gfile...
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/callbacks/monitor.py#L209-L220
maxjiang93/ugscnn
89cdd512e21a2d0cbb884e52ee75645c39ad6ed7
baseline/exp3_2d3ds/models/vgg.py
python
vgg19
(pretrained=False, **kwargs)
return model
VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
VGG 19-layer model (configuration "E")
[ "VGG", "19", "-", "layer", "model", "(", "configuration", "E", ")" ]
def vgg19(pretrained=False, **kwargs): """VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) return model
[ "def", "vgg19", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "pretrained", ":", "kwargs", "[", "'init_weights'", "]", "=", "False", "model", "=", "VGG", "(", "make_layers", "(", "cfg", "[", "'E'", "]", ")", ",", "*", "*...
https://github.com/maxjiang93/ugscnn/blob/89cdd512e21a2d0cbb884e52ee75645c39ad6ed7/baseline/exp3_2d3ds/models/vgg.py#L172-L183
tenzir/threatbus
a26096e7b61b3eddf25c445d40a6cd2ea4420558
apps/suricata/suricata_threatbus/suricata.py
python
stop_signal
()
Implements Python's asyncio eventloop signal handler https://docs.python.org/3/library/asyncio-eventloop.html Cancels all running tasks and exits the app.
Implements Python's asyncio eventloop signal handler https://docs.python.org/3/library/asyncio-eventloop.html Cancels all running tasks and exits the app.
[ "Implements", "Python", "s", "asyncio", "eventloop", "signal", "handler", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "asyncio", "-", "eventloop", ".", "html", "Cancels", "all", "running", "tasks", "and", "exits", ...
async def stop_signal(): """ Implements Python's asyncio eventloop signal handler https://docs.python.org/3/library/asyncio-eventloop.html Cancels all running tasks and exits the app. """ global user_exit user_exit = True await cancel_async_tasks()
[ "async", "def", "stop_signal", "(", ")", ":", "global", "user_exit", "user_exit", "=", "True", "await", "cancel_async_tasks", "(", ")" ]
https://github.com/tenzir/threatbus/blob/a26096e7b61b3eddf25c445d40a6cd2ea4420558/apps/suricata/suricata_threatbus/suricata.py#L89-L97
TristenHarr/MyPyBuilder
5823ae9e5fcd2d745a70425c37a3aaa432c0389d
GuiBuilder/BUILDER/ProjectTemplate/Tabs/FrameTab/FrameTabBuild.py
python
FrameTab.refresh_edit_frames
(self)
This is used to refresh the edit frame :return: None
This is used to refresh the edit frame
[ "This", "is", "used", "to", "refresh", "the", "edit", "frame" ]
def refresh_edit_frames(self): """ This is used to refresh the edit frame :return: None """ tmp = FrameWidget() for key in list(self.window.containers['edit_frame_frame'].containers.keys()): garbage = self.window.containers['edit_frame_frame'].containers.pop(key) garbage.destroy() del garbage for item in tmp.edit_components: tmp_args = [] for arg in item['args']: if arg is None: tmp_args.append(self.commands[item['id']]) elif arg == 'hotfix': # TODO: Remove hotfix for something more stable tmp_args.append(self.choose_edit_frame) else: tmp_args.append(arg) item['args'] = tmp_args self.window.containers['edit_frame_frame'].add_widget(**item)
[ "def", "refresh_edit_frames", "(", "self", ")", ":", "tmp", "=", "FrameWidget", "(", ")", "for", "key", "in", "list", "(", "self", ".", "window", ".", "containers", "[", "'edit_frame_frame'", "]", ".", "containers", ".", "keys", "(", ")", ")", ":", "ga...
https://github.com/TristenHarr/MyPyBuilder/blob/5823ae9e5fcd2d745a70425c37a3aaa432c0389d/GuiBuilder/BUILDER/ProjectTemplate/Tabs/FrameTab/FrameTabBuild.py#L219-L240
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/rtf2xml/list_numbers.py
python
ListNumbers.__init__
(self, in_file, bug_handler, copy=None, run_level=1, )
Required: 'file' Optional: 'copy'-- whether to make a copy of result for debugging 'temp_dir' --where to output temporary results (default is directory from which the script is run.) Returns: nothing
Required: 'file' Optional: 'copy'-- whether to make a copy of result for debugging 'temp_dir' --where to output temporary results (default is directory from which the script is run.) Returns: nothing
[ "Required", ":", "file", "Optional", ":", "copy", "--", "whether", "to", "make", "a", "copy", "of", "result", "for", "debugging", "temp_dir", "--", "where", "to", "output", "temporary", "results", "(", "default", "is", "directory", "from", "which", "the", ...
def __init__(self, in_file, bug_handler, copy=None, run_level=1, ): """ Required: 'file' Optional: 'copy'-- whether to make a copy of result for debugging 'temp_dir' --where to output temporary results (default is directory from which the script is run.) Returns: nothing """ self.__file = in_file self.__bug_handler = bug_handler self.__copy = copy self.__write_to = better_mktemp()
[ "def", "__init__", "(", "self", ",", "in_file", ",", "bug_handler", ",", "copy", "=", "None", ",", "run_level", "=", "1", ",", ")", ":", "self", ".", "__file", "=", "in_file", "self", ".", "__bug_handler", "=", "bug_handler", "self", ".", "__copy", "="...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/rtf2xml/list_numbers.py#L25-L44
sony/nnabla
5b022f309bf2fa3ade0b6cb9bf05da9ddc67f104
python/src/nnabla/utils/converter/onnx/importer.py
python
generate_stack
(node_name, in_name, out_name, axis, base_name, func_counter)
return sp
Generate a Stack operator to stack specified buffer
Generate a Stack operator to stack specified buffer
[ "Generate", "a", "Stack", "operator", "to", "stack", "specified", "buffer" ]
def generate_stack(node_name, in_name, out_name, axis, base_name, func_counter): """Generate a Stack operator to stack specified buffer""" sp = nnabla_pb2.Function() sp.type = "Stack" set_function_name(sp, node_name, base_name, func_counter) sp.input.extend(in_name) sp.output.extend([out_name]) spp = sp.stack_param spp.axis = axis return sp
[ "def", "generate_stack", "(", "node_name", ",", "in_name", ",", "out_name", ",", "axis", ",", "base_name", ",", "func_counter", ")", ":", "sp", "=", "nnabla_pb2", ".", "Function", "(", ")", "sp", ".", "type", "=", "\"Stack\"", "set_function_name", "(", "sp...
https://github.com/sony/nnabla/blob/5b022f309bf2fa3ade0b6cb9bf05da9ddc67f104/python/src/nnabla/utils/converter/onnx/importer.py#L152-L161
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/vod/v20180717/models.py
python
DescribeSampleSnapshotTemplatesResponse.__init__
(self)
r""" :param TotalCount: 符合过滤条件的记录总数。 :type TotalCount: int :param SampleSnapshotTemplateSet: 采样截图模板详情列表。 :type SampleSnapshotTemplateSet: list of SampleSnapshotTemplate :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param TotalCount: 符合过滤条件的记录总数。 :type TotalCount: int :param SampleSnapshotTemplateSet: 采样截图模板详情列表。 :type SampleSnapshotTemplateSet: list of SampleSnapshotTemplate :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "TotalCount", ":", "符合过滤条件的记录总数。", ":", "type", "TotalCount", ":", "int", ":", "param", "SampleSnapshotTemplateSet", ":", "采样截图模板详情列表。", ":", "type", "SampleSnapshotTemplateSet", ":", "list", "of", "SampleSnapshotTemplate", ":", "param", "RequestI...
def __init__(self): r""" :param TotalCount: 符合过滤条件的记录总数。 :type TotalCount: int :param SampleSnapshotTemplateSet: 采样截图模板详情列表。 :type SampleSnapshotTemplateSet: list of SampleSnapshotTemplate :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.SampleSnapshotTemplateSet = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TotalCount", "=", "None", "self", ".", "SampleSnapshotTemplateSet", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vod/v20180717/models.py#L9887-L9898
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/html5lib/_inputstream.py
python
EncodingParser.handlePossibleTag
(self, endTag)
return True
[]
def handlePossibleTag(self, endTag): data = self.data if data.currentByte not in asciiLettersBytes: # If the next byte is not an ascii letter either ignore this # fragment (possible start tag case) or treat it according to # handleOther if endTag: data.previous() self.handleOther() return True c = data.skipUntil(spacesAngleBrackets) if c == b"<": # return to the first step in the overall "two step" algorithm # reprocessing the < byte data.previous() else: # Read all attributes attr = self.getAttribute() while attr is not None: attr = self.getAttribute() return True
[ "def", "handlePossibleTag", "(", "self", ",", "endTag", ")", ":", "data", "=", "self", ".", "data", "if", "data", ".", "currentByte", "not", "in", "asciiLettersBytes", ":", "# If the next byte is not an ascii letter either ignore this", "# fragment (possible start tag cas...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/html5lib/_inputstream.py#L766-L787
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/jobs.py
python
fg
(args, stdin=None)
return resume_job(args, wording="fg")
xonsh command: fg Bring the currently active job to the foreground, or, if a single number is given as an argument, bring that job to the foreground. Additionally, specify "+" for the most recent job and "-" for the second most recent job.
xonsh command: fg
[ "xonsh", "command", ":", "fg" ]
def fg(args, stdin=None): """ xonsh command: fg Bring the currently active job to the foreground, or, if a single number is given as an argument, bring that job to the foreground. Additionally, specify "+" for the most recent job and "-" for the second most recent job. """ return resume_job(args, wording="fg")
[ "def", "fg", "(", "args", ",", "stdin", "=", "None", ")", ":", "return", "resume_job", "(", "args", ",", "wording", "=", "\"fg\"", ")" ]
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/jobs.py#L426-L434
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/api/apps_v1_api.py
python
AppsV1Api.read_namespaced_deployment_scale
(self, name, namespace, **kwargs)
return self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
read_namespaced_deployment_scale # noqa: E501 read scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_scale(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread.
read_namespaced_deployment_scale # noqa: E501
[ "read_namespaced_deployment_scale", "#", "noqa", ":", "E501" ]
def read_namespaced_deployment_scale(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment_scale # noqa: E501 read scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_scale(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
[ "def", "read_namespaced_deployment_scale", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "read_namespaced_deployment_scale_with_http_in...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/apps_v1_api.py#L6503-L6528
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/parlai/mturk/core/dev/mturk_manager.py
python
MTurkManager.remove_worker_qualification
(self, worker_id, qual_name, reason='')
Remove a qualification from a worker
Remove a qualification from a worker
[ "Remove", "a", "qualification", "from", "a", "worker" ]
def remove_worker_qualification(self, worker_id, qual_name, reason=''): """Remove a qualification from a worker""" qual_id = mturk_utils.find_qualification(qual_name, self.is_sandbox) if qual_id is False or qual_id is None: shared_utils.print_and_log( logging.WARN, 'Could not remove from worker {} qualification {}, as the ' 'qualification could not be found to exist.' ''.format(worker_id, qual_name), should_print=True, ) return try: mturk_utils.remove_worker_qualification( worker_id, qual_id, self.is_sandbox, reason ) shared_utils.print_and_log( logging.INFO, 'removed {}\'s qualification {}'.format(worker_id, qual_name), should_print=True, ) except Exception as e: shared_utils.print_and_log( logging.WARN if not self.has_time_limit else logging.INFO, 'removing {}\'s qualification {} failed with error {}. This ' 'can be because the worker didn\'t have that qualification.' ''.format(worker_id, qual_name, repr(e)), should_print=True, )
[ "def", "remove_worker_qualification", "(", "self", ",", "worker_id", ",", "qual_name", ",", "reason", "=", "''", ")", ":", "qual_id", "=", "mturk_utils", ".", "find_qualification", "(", "qual_name", ",", "self", ".", "is_sandbox", ")", "if", "qual_id", "is", ...
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/mturk/core/dev/mturk_manager.py#L1721-L1749
SeldonIO/alibi
ce961caf995d22648a8338857822c90428af4765
alibi/explainers/backends/cfrl_tabular.py
python
sample
(X_hat_split: List[np.ndarray], X_ohe: np.ndarray, C: Optional[np.ndarray], category_map: Dict[int, List[str]], stats: Dict[int, Dict[str, float]])
return X_ohe_hat_split
Samples an instance from the given reconstruction according to the conditional vector and the dictionary of statistics. Parameters ---------- X_hat_split List of reconstructed columns from the auto-encoder. The categorical columns contain logits. X_ohe One-hot encoded representation of the input. C Conditional vector. category_map Dictionary of category mapping. The keys are column indexes and the values are lists containing the possible values for a feature. stats Dictionary of statistic of the training data. Contains the minimum and maximum value of each numerical feature in the training set. Each key is an index of the column and each value is another dictionary containing `min` and `max` keys. Returns ------- X_ohe_hat_split Most probable reconstruction sample according to the autoencoder, sampled according to the conditional vector and the dictionary of statistics. This method assumes that the input array, `X_ohe` , has the first columns corresponding to the numerical features, and the rest are one-hot encodings of the categorical columns.
Samples an instance from the given reconstruction according to the conditional vector and the dictionary of statistics.
[ "Samples", "an", "instance", "from", "the", "given", "reconstruction", "according", "to", "the", "conditional", "vector", "and", "the", "dictionary", "of", "statistics", "." ]
def sample(X_hat_split: List[np.ndarray], X_ohe: np.ndarray, C: Optional[np.ndarray], category_map: Dict[int, List[str]], stats: Dict[int, Dict[str, float]]) -> List[np.ndarray]: """ Samples an instance from the given reconstruction according to the conditional vector and the dictionary of statistics. Parameters ---------- X_hat_split List of reconstructed columns from the auto-encoder. The categorical columns contain logits. X_ohe One-hot encoded representation of the input. C Conditional vector. category_map Dictionary of category mapping. The keys are column indexes and the values are lists containing the possible values for a feature. stats Dictionary of statistic of the training data. Contains the minimum and maximum value of each numerical feature in the training set. Each key is an index of the column and each value is another dictionary containing `min` and `max` keys. Returns ------- X_ohe_hat_split Most probable reconstruction sample according to the autoencoder, sampled according to the conditional vector and the dictionary of statistics. This method assumes that the input array, `X_ohe` , has the first columns corresponding to the numerical features, and the rest are one-hot encodings of the categorical columns. """ X_ohe_num_split, X_ohe_cat_split = split_ohe(X_ohe, category_map) C_num_split, C_cat_split = split_ohe(C, category_map) if (C is not None) else (None, None) X_ohe_hat_split = [] # list of sampled numerical columns and sampled categorical columns num_feat, cat_feat = len(X_ohe_num_split), len(X_ohe_cat_split) if num_feat > 0: # Sample numerical columns X_ohe_hat_split += sample_numerical(X_hat_num_split=X_hat_split[:num_feat], X_ohe_num_split=X_ohe_num_split, C_num_split=C_num_split, stats=stats) if cat_feat > 0: # Sample categorical columns X_ohe_hat_split += sample_categorical(X_hat_cat_split=X_hat_split[-cat_feat:], C_cat_split=C_cat_split) return X_ohe_hat_split
[ "def", "sample", "(", "X_hat_split", ":", "List", "[", "np", ".", "ndarray", "]", ",", "X_ohe", ":", "np", ".", "ndarray", ",", "C", ":", "Optional", "[", "np", ".", "ndarray", "]", ",", "category_map", ":", "Dict", "[", "int", ",", "List", "[", ...
https://github.com/SeldonIO/alibi/blob/ce961caf995d22648a8338857822c90428af4765/alibi/explainers/backends/cfrl_tabular.py#L372-L422
getnikola/nikola
2da876e9322e42a93f8295f950e336465c6a4ee5
nikola/plugins/command/github_deploy.py
python
CommandGitHubDeploy._run_command
(self, command, xfail=False)
Run a command that may or may not fail.
Run a command that may or may not fail.
[ "Run", "a", "command", "that", "may", "or", "may", "not", "fail", "." ]
def _run_command(self, command, xfail=False): """Run a command that may or may not fail.""" self.logger.info("==> {0}".format(command)) try: subprocess.check_call(command) return 0 except subprocess.CalledProcessError as e: if xfail: return e.returncode self.logger.error( 'Failed GitHub deployment -- command {0} ' 'returned {1}'.format(e.cmd, e.returncode) ) raise DeployFailedException(e.returncode)
[ "def", "_run_command", "(", "self", ",", "command", ",", "xfail", "=", "False", ")", ":", "self", ".", "logger", ".", "info", "(", "\"==> {0}\"", ".", "format", "(", "command", ")", ")", "try", ":", "subprocess", ".", "check_call", "(", "command", ")",...
https://github.com/getnikola/nikola/blob/2da876e9322e42a93f8295f950e336465c6a4ee5/nikola/plugins/command/github_deploy.py#L110-L123
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/setuptools/msvc.py
python
SystemInfo.WindowsSdkDir
(self)
return sdkdir
Microsoft Windows SDK directory.
Microsoft Windows SDK directory.
[ "Microsoft", "Windows", "SDK", "directory", "." ]
def WindowsSdkDir(self): """ Microsoft Windows SDK directory. """ sdkdir = '' for ver in self.WindowsSdkVersion: # Try to get it from registry loc = os.path.join(self.ri.windows_sdk, 'v%s' % ver) sdkdir = self.ri.lookup(loc, 'installationfolder') if sdkdir: break if not sdkdir or not os.path.isdir(sdkdir): # Try to get "VC++ for Python" version from registry path = os.path.join(self.ri.vc_for_python, '%0.1f' % self.vc_ver) install_base = self.ri.lookup(path, 'installdir') if install_base: sdkdir = os.path.join(install_base, 'WinSDK') if not sdkdir or not os.path.isdir(sdkdir): # If fail, use default new path for ver in self.WindowsSdkVersion: intver = ver[:ver.rfind('.')] path = r'Microsoft SDKs\Windows Kits\%s' % (intver) d = os.path.join(self.ProgramFiles, path) if os.path.isdir(d): sdkdir = d if not sdkdir or not os.path.isdir(sdkdir): # If fail, use default old path for ver in self.WindowsSdkVersion: path = r'Microsoft SDKs\Windows\v%s' % ver d = os.path.join(self.ProgramFiles, path) if os.path.isdir(d): sdkdir = d if not sdkdir: # If fail, use Platform SDK sdkdir = os.path.join(self.VCInstallDir, 'PlatformSDK') return sdkdir
[ "def", "WindowsSdkDir", "(", "self", ")", ":", "sdkdir", "=", "''", "for", "ver", "in", "self", ".", "WindowsSdkVersion", ":", "# Try to get it from registry", "loc", "=", "os", ".", "path", ".", "join", "(", "self", ".", "ri", ".", "windows_sdk", ",", "...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/setuptools/msvc.py#L599-L634
pyvisa/pyvisa-py
91e3475883b0f6e20dd308f0925f9940fcf818ea
pyvisa_py/sessions.py
python
Session.register_unavailable
( cls, interface_type: constants.InterfaceType, resource_class: str, msg: str )
Register that no session class exists. This creates a fake session that will raise a ValueError if called. Parameters ---------- interface_type : constants.InterfaceType Type of interface. resource_class : str Class of the resource msg : str Message detailing why no session class exists for this particular interface type, resource class pair. Returns ------- Type[Session] Fake session.
Register that no session class exists.
[ "Register", "that", "no", "session", "class", "exists", "." ]
def register_unavailable( cls, interface_type: constants.InterfaceType, resource_class: str, msg: str ) -> None: """Register that no session class exists. This creates a fake session that will raise a ValueError if called. Parameters ---------- interface_type : constants.InterfaceType Type of interface. resource_class : str Class of the resource msg : str Message detailing why no session class exists for this particular interface type, resource class pair. Returns ------- Type[Session] Fake session. """ class _internal(Session): #: Message detailing why no session is available. session_issue: str = msg def __init__(self, *args, **kwargs) -> None: raise ValueError(msg) def _get_attribute(self, attr): raise NotImplementedError() def _set_attribute(self, attr, value): raise NotImplementedError() def close(self): raise NotImplementedError() if (interface_type, resource_class) in cls._session_classes: logger.warning( "%s is already registered in the ResourceManager. " "Overwriting with unavailable %s", ((interface_type, resource_class), msg), ) cls._session_classes[(interface_type, resource_class)] = _internal
[ "def", "register_unavailable", "(", "cls", ",", "interface_type", ":", "constants", ".", "InterfaceType", ",", "resource_class", ":", "str", ",", "msg", ":", "str", ")", "->", "None", ":", "class", "_internal", "(", "Session", ")", ":", "#: Message detailing w...
https://github.com/pyvisa/pyvisa-py/blob/91e3475883b0f6e20dd308f0925f9940fcf818ea/pyvisa_py/sessions.py#L236-L284
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/marathon.py
python
apps
()
return {"apps": [app["id"] for app in response["dict"]["apps"]]}
Return a list of the currently installed app ids. CLI Example: .. code-block:: bash salt marathon-minion-id marathon.apps
Return a list of the currently installed app ids.
[ "Return", "a", "list", "of", "the", "currently", "installed", "app", "ids", "." ]
def apps(): """ Return a list of the currently installed app ids. CLI Example: .. code-block:: bash salt marathon-minion-id marathon.apps """ response = salt.utils.http.query( "{}/v2/apps".format(_base_url()), decode_type="json", decode=True, ) return {"apps": [app["id"] for app in response["dict"]["apps"]]}
[ "def", "apps", "(", ")", ":", "response", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "\"{}/v2/apps\"", ".", "format", "(", "_base_url", "(", ")", ")", ",", "decode_type", "=", "\"json\"", ",", "decode", "=", "True", ",", ")", "return"...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/marathon.py#L51-L66
georgesung/ssd_tensorflow_traffic_sign_detection
d9a16cc330842c1d5b93bd1c64df8079cd9197e8
model.py
python
nms
(y_pred_conf, y_pred_loc, prob)
return boxes
Non-Maximum Suppression (NMS) Performs NMS on all boxes of each class where predicted probability > CONF_THRES For all boxes exceeding IOU threshold, select the box with highest confidence Returns a lsit of box coordinates post-NMS Arguments: * y_pred_conf: Class predictions, numpy array of shape (num_feature_map_cells * num_defaul_boxes,) * y_pred_loc: Bounding box coordinates, numpy array of shape (num_feature_map_cells * num_defaul_boxes * 4,) These coordinates are normalized coordinates relative to center of feature map cell * prob: Class probabilities, numpy array of shape (num_feature_map_cells * num_defaul_boxes,) Returns: * boxes: Numpy array of boxes, with shape (num_boxes, 6). shape[0] is interpreted as: [x1, y1, x2, y2, class, probability], where x1/y1/x2/y2 are the coordinates of the upper-left and lower-right corners. Box coordinates assume the image size is IMG_W x IMG_H. Remember to rescale box coordinates if your target image has different dimensions.
Non-Maximum Suppression (NMS) Performs NMS on all boxes of each class where predicted probability > CONF_THRES For all boxes exceeding IOU threshold, select the box with highest confidence Returns a lsit of box coordinates post-NMS
[ "Non", "-", "Maximum", "Suppression", "(", "NMS", ")", "Performs", "NMS", "on", "all", "boxes", "of", "each", "class", "where", "predicted", "probability", ">", "CONF_THRES", "For", "all", "boxes", "exceeding", "IOU", "threshold", "select", "the", "box", "wi...
def nms(y_pred_conf, y_pred_loc, prob): """ Non-Maximum Suppression (NMS) Performs NMS on all boxes of each class where predicted probability > CONF_THRES For all boxes exceeding IOU threshold, select the box with highest confidence Returns a lsit of box coordinates post-NMS Arguments: * y_pred_conf: Class predictions, numpy array of shape (num_feature_map_cells * num_defaul_boxes,) * y_pred_loc: Bounding box coordinates, numpy array of shape (num_feature_map_cells * num_defaul_boxes * 4,) These coordinates are normalized coordinates relative to center of feature map cell * prob: Class probabilities, numpy array of shape (num_feature_map_cells * num_defaul_boxes,) Returns: * boxes: Numpy array of boxes, with shape (num_boxes, 6). shape[0] is interpreted as: [x1, y1, x2, y2, class, probability], where x1/y1/x2/y2 are the coordinates of the upper-left and lower-right corners. Box coordinates assume the image size is IMG_W x IMG_H. Remember to rescale box coordinates if your target image has different dimensions. """ # Keep track of boxes for each class class_boxes = {} # class -> [(x1, y1, x2, y2, prob), (...), ...] with open('signnames.csv', 'r') as f: for line in f: cls, _ = line.split(',') class_boxes[float(cls)] = [] # Go through all possible boxes and perform class-based greedy NMS (greedy based on class prediction confidence) y_idx = 0 for fm_size in FM_SIZES: fm_h, fm_w = fm_size # feature map height and width for row in range(fm_h): for col in range(fm_w): for db in DEFAULT_BOXES: # Only perform calculations if class confidence > CONF_THRESH and not background class if prob[y_idx] > CONF_THRESH and y_pred_conf[y_idx] > 0.: # Calculate absolute coordinates of predicted bounding box xc, yc = col + 0.5, row + 0.5 # center of current feature map cell center_coords = np.array([xc, yc, xc, yc]) abs_box_coords = center_coords + y_pred_loc[y_idx*4 : y_idx*4 + 4] # predictions are offsets to center of fm cell # Calculate predicted box coordinates in actual image scale = np.array([IMG_W/fm_w, IMG_H/fm_h, IMG_W/fm_w, IMG_H/fm_h]) box_coords = abs_box_coords * scale box_coords = [int(round(x)) for x in box_coords] # Compare this box to all previous boxes of this class cls = y_pred_conf[y_idx] cls_prob = prob[y_idx] box = (*box_coords, cls, cls_prob) if len(class_boxes[cls]) == 0: class_boxes[cls].append(box) else: suppressed = False # did this box suppress other box(es)? overlapped = False # did this box overlap with other box(es)? for other_box in class_boxes[cls]: iou = calc_iou(box[:4], other_box[:4]) if iou > NMS_IOU_THRESH: overlapped = True # If current box has higher confidence than other box if box[5] > other_box[5]: class_boxes[cls].remove(other_box) suppressed = True if suppressed or not overlapped: class_boxes[cls].append(box) y_idx += 1 # Gather all the pruned boxes and return them boxes = [] for cls in class_boxes.keys(): for class_box in class_boxes[cls]: boxes.append(class_box) boxes = np.array(boxes) return boxes
[ "def", "nms", "(", "y_pred_conf", ",", "y_pred_loc", ",", "prob", ")", ":", "# Keep track of boxes for each class", "class_boxes", "=", "{", "}", "# class -> [(x1, y1, x2, y2, prob), (...), ...]", "with", "open", "(", "'signnames.csv'", ",", "'r'", ")", "as", "f", "...
https://github.com/georgesung/ssd_tensorflow_traffic_sign_detection/blob/d9a16cc330842c1d5b93bd1c64df8079cd9197e8/model.py#L193-L267
f-dangel/backpack
1da7e53ebb2c490e2b7dd9f79116583641f3cca1
backpack/core/derivatives/linear.py
python
LinearDerivatives._jac_t_mat_prod
( self, module: Linear, g_inp: Tuple[Tensor], g_out: Tuple[Tensor], mat: Tensor, subsampling: List[int] = None, )
return einsum("vn...o,oi->vn...i", mat, module.weight)
Batch-apply transposed Jacobian of the output w.r.t. the input. Args: module: Linear layer. g_inp: Gradients w.r.t. module input. Not required by the implementation. g_out: Gradients w.r.t. module output. Not required by the implementation. mat: Batch of ``V`` vectors of same shape as the layer output (``[N, *, out_features]``) to which the transposed output-input Jacobian is applied. Has shape ``[V, N, *, out_features]``; but if used with sub-sampling, ``N`` is replaced by ``len(subsampling)``. subsampling: Indices of active samples. ``None`` means all samples. Returns: Batched transposed Jacobian vector products. Has shape ``[V, N, *, in_features]``. If used with sub-sampling, ``N`` is replaced by ``len(subsampling)``.
Batch-apply transposed Jacobian of the output w.r.t. the input.
[ "Batch", "-", "apply", "transposed", "Jacobian", "of", "the", "output", "w", ".", "r", ".", "t", ".", "the", "input", "." ]
def _jac_t_mat_prod( self, module: Linear, g_inp: Tuple[Tensor], g_out: Tuple[Tensor], mat: Tensor, subsampling: List[int] = None, ) -> Tensor: """Batch-apply transposed Jacobian of the output w.r.t. the input. Args: module: Linear layer. g_inp: Gradients w.r.t. module input. Not required by the implementation. g_out: Gradients w.r.t. module output. Not required by the implementation. mat: Batch of ``V`` vectors of same shape as the layer output (``[N, *, out_features]``) to which the transposed output-input Jacobian is applied. Has shape ``[V, N, *, out_features]``; but if used with sub-sampling, ``N`` is replaced by ``len(subsampling)``. subsampling: Indices of active samples. ``None`` means all samples. Returns: Batched transposed Jacobian vector products. Has shape ``[V, N, *, in_features]``. If used with sub-sampling, ``N`` is replaced by ``len(subsampling)``. """ return einsum("vn...o,oi->vn...i", mat, module.weight)
[ "def", "_jac_t_mat_prod", "(", "self", ",", "module", ":", "Linear", ",", "g_inp", ":", "Tuple", "[", "Tensor", "]", ",", "g_out", ":", "Tuple", "[", "Tensor", "]", ",", "mat", ":", "Tensor", ",", "subsampling", ":", "List", "[", "int", "]", "=", "...
https://github.com/f-dangel/backpack/blob/1da7e53ebb2c490e2b7dd9f79116583641f3cca1/backpack/core/derivatives/linear.py#L33-L58
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/layout/dock_layout.py
python
DockLayout.children
(self)
return self.items[:]
Get the list of children of the dock layout.
Get the list of children of the dock layout.
[ "Get", "the", "list", "of", "children", "of", "the", "dock", "layout", "." ]
def children(self): """ Get the list of children of the dock layout. """ return self.items[:]
[ "def", "children", "(", "self", ")", ":", "return", "self", ".", "items", "[", ":", "]" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/layout/dock_layout.py#L339-L343
rbw/pysnow
2b1c4accdf235675c4a4e610b31fb0a3cd4f9923
docs/_themes/sphinx_rtd_theme/__init__.py
python
get_html_theme_path
()
return cur_dir
Return list of HTML theme paths.
Return list of HTML theme paths.
[ "Return", "list", "of", "HTML", "theme", "paths", "." ]
def get_html_theme_path(): """Return list of HTML theme paths.""" cur_dir = path.abspath(path.dirname(path.dirname(__file__))) return cur_dir
[ "def", "get_html_theme_path", "(", ")", ":", "cur_dir", "=", "path", ".", "abspath", "(", "path", ".", "dirname", "(", "path", ".", "dirname", "(", "__file__", ")", ")", ")", "return", "cur_dir" ]
https://github.com/rbw/pysnow/blob/2b1c4accdf235675c4a4e610b31fb0a3cd4f9923/docs/_themes/sphinx_rtd_theme/__init__.py#L12-L15
artetxem/monoses
352c90120a543467b81175b94abaea65cd819933
bli/induce-dictionary.py
python
induce_dictionary
(args)
[]
def induce_dictionary(args): for src, trg in ('src', 'trg'), ('trg', 'src'): bash('zcat ' + quote(args.working + '/step9/' + src + '2' + trg + '.phrase-table.gz') + ' | python3 ' + quote(PT2DICT) + ' -f ' + str(args.feature) + (' -r' if args.reverse else '') + (' --phrases' if args.phrases else '') + ' | ' + quote(MOSES + '/scripts/tokenizer/deescape-special-chars.perl') + ' | LC_ALL=C sort -k1,1 -k3,3gr' + ' > ' + quote(args.working + '/' + (trg + '2' + src if args.reverse else src + '2' + trg) + '.dic'))
[ "def", "induce_dictionary", "(", "args", ")", ":", "for", "src", ",", "trg", "in", "(", "'src'", ",", "'trg'", ")", ",", "(", "'trg'", ",", "'src'", ")", ":", "bash", "(", "'zcat '", "+", "quote", "(", "args", ".", "working", "+", "'/step9/'", "+",...
https://github.com/artetxem/monoses/blob/352c90120a543467b81175b94abaea65cd819933/bli/induce-dictionary.py#L227-L233
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/task_pool.py
python
TaskPool.log_task_pool
(self, log_lvl=logging.DEBUG)
Log content of task and prerequisite pools in debug mode.
Log content of task and prerequisite pools in debug mode.
[ "Log", "content", "of", "task", "and", "prerequisite", "pools", "in", "debug", "mode", "." ]
def log_task_pool(self, log_lvl=logging.DEBUG): """Log content of task and prerequisite pools in debug mode.""" for pool, name in [ (self.main_pool_list, "Main"), (self.hidden_pool_list, "Hidden") ]: if pool: LOG.log( log_lvl, f"{name} pool:\n" + "\n".join( f"* {itask} status={itask.state.status}" f" runahead={itask.state.is_runahead}" f" queued={itask.state.is_queued}" for itask in pool ) )
[ "def", "log_task_pool", "(", "self", ",", "log_lvl", "=", "logging", ".", "DEBUG", ")", ":", "for", "pool", ",", "name", "in", "[", "(", "self", ".", "main_pool_list", ",", "\"Main\"", ")", ",", "(", "self", ".", "hidden_pool_list", ",", "\"Hidden\"", ...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/task_pool.py#L1627-L1643
LinkedInAttic/indextank-service
880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e
storefront/api_linked_models.py
python
Deploy.is_writable
(self)
return self.status == Deploy.States.controllable or \ self.status == Deploy.States.recovering or \ self.status == Deploy.States.move_requested or \ self.status == Deploy.States.moving
Returns True if new data has to be written to this deployment.
Returns True if new data has to be written to this deployment.
[ "Returns", "True", "if", "new", "data", "has", "to", "be", "written", "to", "this", "deployment", "." ]
def is_writable(self): '''Returns True if new data has to be written to this deployment.''' return self.status == Deploy.States.controllable or \ self.status == Deploy.States.recovering or \ self.status == Deploy.States.move_requested or \ self.status == Deploy.States.moving
[ "def", "is_writable", "(", "self", ")", ":", "return", "self", ".", "status", "==", "Deploy", ".", "States", ".", "controllable", "or", "self", ".", "status", "==", "Deploy", ".", "States", ".", "recovering", "or", "self", ".", "status", "==", "Deploy", ...
https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/storefront/api_linked_models.py#L848-L853
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/service_catalog/service_catalog_client.py
python
ServiceCatalogClient.list_private_application_packages
(self, private_application_id, **kwargs)
Lists the packages in the specified private application. :param str private_application_id: (required) The unique identifier for the private application. :param str private_application_package_id: (optional) The unique identifier for the private application package. :param list[str] package_type: (optional) Name of the package type. If multiple package types are provided, then any resource with one or more matching package types will be returned. Allowed values are: "STACK" :param int limit: (optional) How many records to return. Specify a value greater than zero and less than or equal to 1000. The default is 30. :param str page: (optional) The value of the `opc-next-page` response header from the previous \"List\" call. :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str sort_by: (optional) The field to use to sort listed results. You can only specify one field to sort by. `TIMECREATED` displays results in descending order by default. You can change your preference by specifying a different sort order. Allowed values are: "TIMECREATED", "VERSION" :param str sort_order: (optional) The sort order to apply, either `ASC` or `DESC`. Default is `ASC`. Allowed values are: "ASC", "DESC" :param str display_name: (optional) Exact match name filter. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.service_catalog.models.PrivateApplicationPackageCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/servicecatalog/list_private_application_packages.py.html>`__ to see an example of how to use list_private_application_packages API.
Lists the packages in the specified private application.
[ "Lists", "the", "packages", "in", "the", "specified", "private", "application", "." ]
def list_private_application_packages(self, private_application_id, **kwargs): """ Lists the packages in the specified private application. :param str private_application_id: (required) The unique identifier for the private application. :param str private_application_package_id: (optional) The unique identifier for the private application package. :param list[str] package_type: (optional) Name of the package type. If multiple package types are provided, then any resource with one or more matching package types will be returned. Allowed values are: "STACK" :param int limit: (optional) How many records to return. Specify a value greater than zero and less than or equal to 1000. The default is 30. :param str page: (optional) The value of the `opc-next-page` response header from the previous \"List\" call. :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str sort_by: (optional) The field to use to sort listed results. You can only specify one field to sort by. `TIMECREATED` displays results in descending order by default. You can change your preference by specifying a different sort order. Allowed values are: "TIMECREATED", "VERSION" :param str sort_order: (optional) The sort order to apply, either `ASC` or `DESC`. Default is `ASC`. Allowed values are: "ASC", "DESC" :param str display_name: (optional) Exact match name filter. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.service_catalog.models.PrivateApplicationPackageCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/servicecatalog/list_private_application_packages.py.html>`__ to see an example of how to use list_private_application_packages API. """ resource_path = "/privateApplicationPackages" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "private_application_package_id", "package_type", "limit", "page", "opc_request_id", "sort_by", "sort_order", "display_name" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "list_private_application_packages got unknown kwargs: {!r}".format(extra_kwargs)) if 'package_type' in kwargs: package_type_allowed_values = ["STACK"] for package_type_item in kwargs['package_type']: if package_type_item not in package_type_allowed_values: raise ValueError( "Invalid value for `package_type`, must be one of {0}".format(package_type_allowed_values) ) if 'sort_by' in kwargs: sort_by_allowed_values = ["TIMECREATED", "VERSION"] if kwargs['sort_by'] not in sort_by_allowed_values: raise ValueError( "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values) ) if 'sort_order' in kwargs: sort_order_allowed_values = ["ASC", "DESC"] if kwargs['sort_order'] not in sort_order_allowed_values: raise ValueError( "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values) ) query_params = { "privateApplicationId": private_application_id, "privateApplicationPackageId": kwargs.get("private_application_package_id", missing), "packageType": self.base_client.generate_collection_format_param(kwargs.get("package_type", missing), 'multi'), "limit": kwargs.get("limit", missing), "page": kwargs.get("page", missing), "sortBy": kwargs.get("sort_by", missing), "sortOrder": kwargs.get("sort_order", missing), "displayName": kwargs.get("display_name", missing) } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="PrivateApplicationPackageCollection") else: return self.base_client.call_api( resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="PrivateApplicationPackageCollection")
[ "def", "list_private_application_packages", "(", "self", ",", "private_application_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/privateApplicationPackages\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"r...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/service_catalog/service_catalog_client.py#L1587-L1726
idanr1986/cuckoo-droid
1350274639473d3d2b0ac740cae133ca53ab7444
analyzer/android_on_linux/lib/api/androguard/apk.py
python
APK.get_details_permissions
(self)
return l
Return permissions with details :rtype: list of string
Return permissions with details
[ "Return", "permissions", "with", "details" ]
def get_details_permissions(self) : """ Return permissions with details :rtype: list of string """ l = {} for i in self.permissions : perm = i pos = i.rfind(".") if pos != -1 : perm = i[pos+1:] try : l[ i ] = DVM_PERMISSIONS["MANIFEST_PERMISSION"][ perm ] except KeyError : l[ i ] = [ "dangerous", "Unknown permission from android reference", "Unknown permission from android reference" ] return l
[ "def", "get_details_permissions", "(", "self", ")", ":", "l", "=", "{", "}", "for", "i", "in", "self", ".", "permissions", ":", "perm", "=", "i", "pos", "=", "i", ".", "rfind", "(", "\".\"", ")", "if", "pos", "!=", "-", "1", ":", "perm", "=", "...
https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android_on_linux/lib/api/androguard/apk.py#L526-L546
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/random.py
python
Random.choices
(self, population, weights=None, *, cum_weights=None, k=1)
return [population[bisect(cum_weights, random() * total, 0, hi)] for i in range(k)]
Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability.
Return a k sized list of population elements chosen with replacement.
[ "Return", "a", "k", "sized", "list", "of", "population", "elements", "chosen", "with", "replacement", "." ]
def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.random if cum_weights is None: if weights is None: _int = int total = len(population) return [population[_int(random() * total)] for i in range(k)] cum_weights = list(_itertools.accumulate(weights)) elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != len(population): raise ValueError('The number of weights does not match the population') bisect = _bisect.bisect total = cum_weights[-1] hi = len(cum_weights) - 1 return [population[bisect(cum_weights, random() * total, 0, hi)] for i in range(k)]
[ "def", "choices", "(", "self", ",", "population", ",", "weights", "=", "None", ",", "*", ",", "cum_weights", "=", "None", ",", "k", "=", "1", ")", ":", "random", "=", "self", ".", "random", "if", "cum_weights", "is", "None", ":", "if", "weights", "...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/random.py#L344-L366
cenkalti/github-flask
9f58d61b7d328cef857edbb5c64a5d3f716367cb
flask_github.py
python
GitHub.authorized_handler
(self, f)
return decorated
Decorator for the route that is used as the callback for authorizing with GitHub. This callback URL can be set in the settings for the app or passed in during authorization.
Decorator for the route that is used as the callback for authorizing with GitHub. This callback URL can be set in the settings for the app or passed in during authorization.
[ "Decorator", "for", "the", "route", "that", "is", "used", "as", "the", "callback", "for", "authorizing", "with", "GitHub", ".", "This", "callback", "URL", "can", "be", "set", "in", "the", "settings", "for", "the", "app", "or", "passed", "in", "during", "...
def authorized_handler(self, f): """ Decorator for the route that is used as the callback for authorizing with GitHub. This callback URL can be set in the settings for the app or passed in during authorization. """ @wraps(f) def decorated(*args, **kwargs): if 'code' in request.args: data = self._handle_response() else: data = self._handle_invalid_response() return f(*((data,) + args), **kwargs) return decorated
[ "def", "authorized_handler", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'code'", "in", "request", ".", "args", ":", "data", "=", "self", ".", "_han...
https://github.com/cenkalti/github-flask/blob/9f58d61b7d328cef857edbb5c64a5d3f716367cb/flask_github.py#L170-L184
jhpyle/docassemble
b90c84e57af59aa88b3404d44d0b125c70f832cc
docassemble_base/docassemble/base/functions.py
python
set_info
(**kwargs)
Used to set the values of global variables you wish to retrieve through get_info().
Used to set the values of global variables you wish to retrieve through get_info().
[ "Used", "to", "set", "the", "values", "of", "global", "variables", "you", "wish", "to", "retrieve", "through", "get_info", "()", "." ]
def set_info(**kwargs): """Used to set the values of global variables you wish to retrieve through get_info().""" for att, val in kwargs.items(): setattr(this_thread.global_vars, att, val)
[ "def", "set_info", "(", "*", "*", "kwargs", ")", ":", "for", "att", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "this_thread", ".", "global_vars", ",", "att", ",", "val", ")" ]
https://github.com/jhpyle/docassemble/blob/b90c84e57af59aa88b3404d44d0b125c70f832cc/docassemble_base/docassemble/base/functions.py#L1169-L1172
ntasfi/PyGame-Learning-Environment
3dbe79dc0c35559bb441b9359948aabf9bb3d331
ple/games/pong.py
python
Pong.getScore
(self)
return self.score_sum
[]
def getScore(self): return self.score_sum
[ "def", "getScore", "(", "self", ")", ":", "return", "self", ".", "score_sum" ]
https://github.com/ntasfi/PyGame-Learning-Environment/blob/3dbe79dc0c35559bb441b9359948aabf9bb3d331/ple/games/pong.py#L290-L291
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/fgsm_v3_random/nets/mobilenet_v1.py
python
mobilenet_v1_base
(inputs, final_endpoint='Conv2d_13_pointwise', min_depth=8, depth_multiplier=1.0, conv_defs=None, output_stride=None, scope=None)
Mobilenet v1. Constructs a Mobilenet v1 network from inputs to the given final endpoint. Args: inputs: a tensor of shape [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_0', 'Conv2d_1_pointwise', 'Conv2d_2_pointwise', 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5'_pointwise, 'Conv2d_6_pointwise', 'Conv2d_7_pointwise', 'Conv2d_8_pointwise', 'Conv2d_9_pointwise', 'Conv2d_10_pointwise', 'Conv2d_11_pointwise', 'Conv2d_12_pointwise', 'Conv2d_13_pointwise']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. output_stride: An integer that specifies the requested ratio of input to output spatial resolution. If not None, then we invoke atrous convolution if necessary to prevent the network from reducing the spatial resolution of the activation maps. Allowed values are 8 (accurate fully convolutional mode), 16 (fast fully convolutional mode), 32 (classification mode). scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0, or the target output_stride is not allowed.
Mobilenet v1.
[ "Mobilenet", "v1", "." ]
def mobilenet_v1_base(inputs, final_endpoint='Conv2d_13_pointwise', min_depth=8, depth_multiplier=1.0, conv_defs=None, output_stride=None, scope=None): """Mobilenet v1. Constructs a Mobilenet v1 network from inputs to the given final endpoint. Args: inputs: a tensor of shape [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_0', 'Conv2d_1_pointwise', 'Conv2d_2_pointwise', 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5'_pointwise, 'Conv2d_6_pointwise', 'Conv2d_7_pointwise', 'Conv2d_8_pointwise', 'Conv2d_9_pointwise', 'Conv2d_10_pointwise', 'Conv2d_11_pointwise', 'Conv2d_12_pointwise', 'Conv2d_13_pointwise']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. output_stride: An integer that specifies the requested ratio of input to output spatial resolution. If not None, then we invoke atrous convolution if necessary to prevent the network from reducing the spatial resolution of the activation maps. Allowed values are 8 (accurate fully convolutional mode), 16 (fast fully convolutional mode), 32 (classification mode). scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0, or the target output_stride is not allowed. """ depth = lambda d: max(int(d * depth_multiplier), min_depth) end_points = {} # Used to find thinned depths for each layer. if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') if conv_defs is None: conv_defs = _CONV_DEFS if output_stride is not None and output_stride not in [8, 16, 32]: raise ValueError('Only allowed output_stride values are 8, 16, 32.') with tf.variable_scope(scope, 'MobilenetV1', [inputs]): with slim.arg_scope([slim.conv2d, slim.separable_conv2d], padding='SAME'): # The current_stride variable keeps track of the output stride of the # activations, i.e., the running product of convolution strides up to the # current network layer. This allows us to invoke atrous convolution # whenever applying the next convolution would result in the activations # having output stride larger than the target output_stride. current_stride = 1 # The atrous convolution rate parameter. rate = 1 net = inputs for i, conv_def in enumerate(conv_defs): end_point_base = 'Conv2d_%d' % i if output_stride is not None and current_stride == output_stride: # If we have reached the target output_stride, then we need to employ # atrous convolution with stride=1 and multiply the atrous rate by the # current unit's stride for use in subsequent layers. layer_stride = 1 layer_rate = rate rate *= conv_def.stride else: layer_stride = conv_def.stride layer_rate = 1 current_stride *= conv_def.stride if isinstance(conv_def, Conv): end_point = end_point_base net = slim.conv2d(net, depth(conv_def.depth), conv_def.kernel, stride=conv_def.stride, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points elif isinstance(conv_def, DepthSepConv): end_point = end_point_base + '_depthwise' # By passing filters=None # separable_conv2d produces only a depthwise convolution layer net = slim.separable_conv2d(net, None, conv_def.kernel, depth_multiplier=1, stride=layer_stride, rate=layer_rate, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points end_point = end_point_base + '_pointwise' net = slim.conv2d(net, depth(conv_def.depth), [1, 1], stride=1, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points else: raise ValueError('Unknown convolution type %s for layer %d' % (conv_def.ltype, i)) raise ValueError('Unknown final endpoint %s' % final_endpoint)
[ "def", "mobilenet_v1_base", "(", "inputs", ",", "final_endpoint", "=", "'Conv2d_13_pointwise'", ",", "min_depth", "=", "8", ",", "depth_multiplier", "=", "1.0", ",", "conv_defs", "=", "None", ",", "output_stride", "=", "None", ",", "scope", "=", "None", ")", ...
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/fgsm_v3_random/nets/mobilenet_v1.py#L142-L266
arsaboo/homeassistant-config
53c998986fbe84d793a0b174757154ab30e676e4
custom_components/aarlo/pyaarlo/media.py
python
ArloVideo.media_duration_seconds
(self)
return self._attrs.get("mediaDurationSecond", None)
Returns how long the recording last.
Returns how long the recording last.
[ "Returns", "how", "long", "the", "recording", "last", "." ]
def media_duration_seconds(self): """Returns how long the recording last.""" return self._attrs.get("mediaDurationSecond", None)
[ "def", "media_duration_seconds", "(", "self", ")", ":", "return", "self", ".", "_attrs", ".", "get", "(", "\"mediaDurationSecond\"", ",", "None", ")" ]
https://github.com/arsaboo/homeassistant-config/blob/53c998986fbe84d793a0b174757154ab30e676e4/custom_components/aarlo/pyaarlo/media.py#L247-L249
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/classify/maxent.py
python
GISEncoding.__init__
(self, labels, mapping, unseen_features=False, alwayson_features=False, C=None)
:param C: The correction constant. The value of the correction feature is based on this value. In particular, its value is ``C - sum([v for (f,v) in encoding])``. :seealso: ``BinaryMaxentFeatureEncoding.__init__``
:param C: The correction constant. The value of the correction feature is based on this value. In particular, its value is ``C - sum([v for (f,v) in encoding])``. :seealso: ``BinaryMaxentFeatureEncoding.__init__``
[ ":", "param", "C", ":", "The", "correction", "constant", ".", "The", "value", "of", "the", "correction", "feature", "is", "based", "on", "this", "value", ".", "In", "particular", "its", "value", "is", "C", "-", "sum", "(", "[", "v", "for", "(", "f", ...
def __init__(self, labels, mapping, unseen_features=False, alwayson_features=False, C=None): """ :param C: The correction constant. The value of the correction feature is based on this value. In particular, its value is ``C - sum([v for (f,v) in encoding])``. :seealso: ``BinaryMaxentFeatureEncoding.__init__`` """ BinaryMaxentFeatureEncoding.__init__( self, labels, mapping, unseen_features, alwayson_features) if C is None: C = len(set([fname for (fname,fval,label) in mapping]))+1 self._C = C
[ "def", "__init__", "(", "self", ",", "labels", ",", "mapping", ",", "unseen_features", "=", "False", ",", "alwayson_features", "=", "False", ",", "C", "=", "None", ")", ":", "BinaryMaxentFeatureEncoding", ".", "__init__", "(", "self", ",", "labels", ",", "...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/classify/maxent.py#L669-L681
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py
python
PathReader.processPathWordA
(self)
Process path word A.
Process path word A.
[ "Process", "path", "word", "A", "." ]
def processPathWordA(self): 'Process path word A.' self.addPathArc( self.getComplexByExtraIndex( 6 ) )
[ "def", "processPathWordA", "(", "self", ")", ":", "self", ".", "addPathArc", "(", "self", ".", "getComplexByExtraIndex", "(", "6", ")", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py#L724-L726
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/admin/helpers.py
python
AdminReadonlyField.contents
(self)
return conditional_escape(result_repr)
[]
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = force_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.html.format_html(), format_html_join(), " "or django.utils.safestring.mark_safe() instead." % attr, RemovedInDjango20Warning ) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
[ "def", "contents", "(", "self", ")", ":", "from", "django", ".", "contrib", ".", "admin", ".", "templatetags", ".", "admin_list", "import", "_boolean_icon", "field", ",", "obj", ",", "model_admin", "=", "self", ".", "field", "[", "'field'", "]", ",", "se...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/helpers.py#L205-L238
arthurdejong/python-stdnum
02dec52602ae0709b940b781fc1fcebfde7340b7
stdnum/ch/vat.py
python
is_valid
(number)
Check if the number is a valid VAT number.
Check if the number is a valid VAT number.
[ "Check", "if", "the", "number", "is", "a", "valid", "VAT", "number", "." ]
def is_valid(number): """Check if the number is a valid VAT number.""" try: return bool(validate(number)) except ValidationError: return False
[ "def", "is_valid", "(", "number", ")", ":", "try", ":", "return", "bool", "(", "validate", "(", "number", ")", ")", "except", "ValidationError", ":", "return", "False" ]
https://github.com/arthurdejong/python-stdnum/blob/02dec52602ae0709b940b781fc1fcebfde7340b7/stdnum/ch/vat.py#L68-L73
tav/pylibs
3c16b843681f54130ee6a022275289cadb2f2a69
mako/runtime.py
python
Context._push_writer
(self)
return buf.write
push a capturing buffer onto this Context and return the new Writer function.
push a capturing buffer onto this Context and return the new Writer function.
[ "push", "a", "capturing", "buffer", "onto", "this", "Context", "and", "return", "the", "new", "Writer", "function", "." ]
def _push_writer(self): """push a capturing buffer onto this Context and return the new Writer function.""" buf = util.FastEncodingBuffer() self._buffer_stack.append(buf) return buf.write
[ "def", "_push_writer", "(", "self", ")", ":", "buf", "=", "util", ".", "FastEncodingBuffer", "(", ")", "self", ".", "_buffer_stack", ".", "append", "(", "buf", ")", "return", "buf", ".", "write" ]
https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/mako/runtime.py#L50-L55
poljar/weechat-matrix
b88614e557399e8b3b623a3d29b2694acc019a44
matrix/commands.py
python
grouper
(iterable, n, fillvalue=None)
return zip_longest(*args, fillvalue=fillvalue)
Collect data into fixed-length chunks or blocks
Collect data into fixed-length chunks or blocks
[ "Collect", "data", "into", "fixed", "-", "length", "chunks", "or", "blocks" ]
def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
[ "def", "grouper", "(", "iterable", ",", "n", ",", "fillvalue", "=", "None", ")", ":", "# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"", "args", "=", "[", "iter", "(", "iterable", ")", "]", "*", "n", "return", "zip_longest", "(", "*", "args", ",", "fillvalue"...
https://github.com/poljar/weechat-matrix/blob/b88614e557399e8b3b623a3d29b2694acc019a44/matrix/commands.py#L220-L224
tz28/deep-learning
9baa081a487aac1e9dceb15b9a1a0ed73608280a
rnn.py
python
initialize_parameters
(n_a, n_x, n_y)
return parameters
Initialize parameters with small random values Returns: parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, of shape (n_a, n_a) Wya -- Weight matrix relating the hidden-state to the output, of shape (n_y, n_a) b -- Bias, numpy array of shape (n_a, 1) by -- Bias relating the hidden-state to the output, of shape (n_y, 1)
Initialize parameters with small random values Returns: parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, of shape (n_a, n_a) Wya -- Weight matrix relating the hidden-state to the output, of shape (n_y, n_a) b -- Bias, numpy array of shape (n_a, 1) by -- Bias relating the hidden-state to the output, of shape (n_y, 1)
[ "Initialize", "parameters", "with", "small", "random", "values", "Returns", ":", "parameters", "--", "python", "dictionary", "containing", ":", "Wax", "--", "Weight", "matrix", "multiplying", "the", "input", "of", "shape", "(", "n_a", "n_x", ")", "Waa", "--", ...
def initialize_parameters(n_a, n_x, n_y): """ Initialize parameters with small random values Returns: parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, of shape (n_a, n_a) Wya -- Weight matrix relating the hidden-state to the output, of shape (n_y, n_a) b -- Bias, numpy array of shape (n_a, 1) by -- Bias relating the hidden-state to the output, of shape (n_y, 1) """ np.random.seed(1) Wax = np.random.randn(n_a, n_x) * 0.01 # input to hidden Waa = np.random.randn(n_a, n_a) * 0.01 # hidden to hidden Wya = np.random.randn(n_y, n_a) * 0.01 # hidden to output ba = np.zeros((n_a, 1)) # hidden bias by = np.zeros((n_y, 1)) # output bias parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by} return parameters
[ "def", "initialize_parameters", "(", "n_a", ",", "n_x", ",", "n_y", ")", ":", "np", ".", "random", ".", "seed", "(", "1", ")", "Wax", "=", "np", ".", "random", ".", "randn", "(", "n_a", ",", "n_x", ")", "*", "0.01", "# input to hidden", "Waa", "=",...
https://github.com/tz28/deep-learning/blob/9baa081a487aac1e9dceb15b9a1a0ed73608280a/rnn.py#L4-L23
deepset-ai/haystack
79fdda8a7cf393d774803608a4874f2a6e63cf6f
haystack/schema.py
python
EvaluationResult._build_document_metrics_df
( self, documents: pd.DataFrame, simulated_top_k_retriever: int = -1, doc_relevance_col: str = "gold_id_match" )
return metrics_df
Builds a dataframe containing document metrics (columns) per query (index). Document metrics are: - mrr (Mean Reciprocal Rank: see https://en.wikipedia.org/wiki/Mean_reciprocal_rank) - map (Mean Average Precision: see https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Mean_average_precision) - precision (Precision: How many of the returned documents were relevant?) - recall_multi_hit (Recall according to Information Retrieval definition: How many of the relevant documents were retrieved per query?) - recall_single_hit (Recall for Question Answering: Did the query return at least one relevant document? -> 1.0 or 0.0)
Builds a dataframe containing document metrics (columns) per query (index). Document metrics are: - mrr (Mean Reciprocal Rank: see https://en.wikipedia.org/wiki/Mean_reciprocal_rank) - map (Mean Average Precision: see https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Mean_average_precision) - precision (Precision: How many of the returned documents were relevant?) - recall_multi_hit (Recall according to Information Retrieval definition: How many of the relevant documents were retrieved per query?) - recall_single_hit (Recall for Question Answering: Did the query return at least one relevant document? -> 1.0 or 0.0)
[ "Builds", "a", "dataframe", "containing", "document", "metrics", "(", "columns", ")", "per", "query", "(", "index", ")", ".", "Document", "metrics", "are", ":", "-", "mrr", "(", "Mean", "Reciprocal", "Rank", ":", "see", "https", ":", "//", "en", ".", "...
def _build_document_metrics_df( self, documents: pd.DataFrame, simulated_top_k_retriever: int = -1, doc_relevance_col: str = "gold_id_match" ) -> pd.DataFrame: """ Builds a dataframe containing document metrics (columns) per query (index). Document metrics are: - mrr (Mean Reciprocal Rank: see https://en.wikipedia.org/wiki/Mean_reciprocal_rank) - map (Mean Average Precision: see https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Mean_average_precision) - precision (Precision: How many of the returned documents were relevant?) - recall_multi_hit (Recall according to Information Retrieval definition: How many of the relevant documents were retrieved per query?) - recall_single_hit (Recall for Question Answering: Did the query return at least one relevant document? -> 1.0 or 0.0) """ if simulated_top_k_retriever != -1: documents = documents[documents["rank"] <= simulated_top_k_retriever] metrics = [] queries = documents["query"].unique() for query in queries: query_df = documents[documents["query"] == query] gold_ids = query_df["gold_document_ids"].iloc[0] retrieved = len(query_df) relevance_criteria_ids = list(query_df[query_df[doc_relevance_col] == 1]["document_id"].values) num_relevants = len(set(gold_ids + relevance_criteria_ids)) num_retrieved_relevants = query_df[doc_relevance_col].values.sum() rank_retrieved_relevants = query_df[query_df[doc_relevance_col] == 1]["rank"].values avp_retrieved_relevants = [query_df[doc_relevance_col].values[:rank].sum() / rank for rank in rank_retrieved_relevants] avg_precision = np.sum(avp_retrieved_relevants) / num_relevants if num_relevants > 0 else 0.0 recall_multi_hit = num_retrieved_relevants / num_relevants if num_relevants > 0 else 0.0 recall_single_hit = min(num_retrieved_relevants, 1) precision = num_retrieved_relevants / retrieved if retrieved > 0 else 0.0 rr = 1.0 / rank_retrieved_relevants.min() if len(rank_retrieved_relevants) > 0 else 0.0 metrics.append({ "recall_multi_hit": recall_multi_hit, "recall_single_hit": recall_single_hit, "precision": precision, "map": avg_precision, "mrr": rr }) metrics_df = pd.DataFrame.from_records(metrics, index=queries) return metrics_df
[ "def", "_build_document_metrics_df", "(", "self", ",", "documents", ":", "pd", ".", "DataFrame", ",", "simulated_top_k_retriever", ":", "int", "=", "-", "1", ",", "doc_relevance_col", ":", "str", "=", "\"gold_id_match\"", ")", "->", "pd", ".", "DataFrame", ":"...
https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/schema.py#L913-L960
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
weioLib/weioFiles.py
python
checkIfDirectoryExists
(path)
[]
def checkIfDirectoryExists(path): if (os.path.isdir(path)): return True else : return False
[ "def", "checkIfDirectoryExists", "(", "path", ")", ":", "if", "(", "os", ".", "path", ".", "isdir", "(", "path", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/weioLib/weioFiles.py#L207-L211
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/collections.py
python
_set_decorators
()
return l
Tailored instrumentation wrappers for any set-like class.
Tailored instrumentation wrappers for any set-like class.
[ "Tailored", "instrumentation", "wrappers", "for", "any", "set", "-", "like", "class", "." ]
def _set_decorators(): """Tailored instrumentation wrappers for any set-like class.""" def _tidy(fn): fn._sa_instrumented = True fn.__doc__ = getattr(set, fn.__name__).__doc__ Unspecified = util.symbol('Unspecified') def add(fn): def add(self, value, _sa_initiator=None): if value not in self: value = __set(self, value, _sa_initiator) # testlib.pragma exempt:__hash__ fn(self, value) _tidy(add) return add def discard(fn): def discard(self, value, _sa_initiator=None): # testlib.pragma exempt:__hash__ if value in self: __del(self, value, _sa_initiator) # testlib.pragma exempt:__hash__ fn(self, value) _tidy(discard) return discard def remove(fn): def remove(self, value, _sa_initiator=None): # testlib.pragma exempt:__hash__ if value in self: __del(self, value, _sa_initiator) # testlib.pragma exempt:__hash__ fn(self, value) _tidy(remove) return remove def pop(fn): def pop(self): __before_delete(self) item = fn(self) __del(self, item) return item _tidy(pop) return pop def clear(fn): def clear(self): for item in list(self): self.remove(item) _tidy(clear) return clear def update(fn): def update(self, value): for item in value: self.add(item) _tidy(update) return update def __ior__(fn): def __ior__(self, value): if not _set_binops_check_strict(self, value): return NotImplemented for item in value: self.add(item) return self _tidy(__ior__) return __ior__ def difference_update(fn): def difference_update(self, value): for item in value: self.discard(item) _tidy(difference_update) return difference_update def __isub__(fn): def __isub__(self, value): if not _set_binops_check_strict(self, value): return NotImplemented for item in value: self.discard(item) return self _tidy(__isub__) return __isub__ def intersection_update(fn): def intersection_update(self, other): want, have = self.intersection(other), set(self) remove, add = have - want, want - have for item in remove: self.remove(item) for item in add: self.add(item) _tidy(intersection_update) return intersection_update def __iand__(fn): def __iand__(self, other): if not _set_binops_check_strict(self, other): return NotImplemented want, have = self.intersection(other), set(self) remove, add = have - want, want - have for item in remove: self.remove(item) for item in add: self.add(item) return self _tidy(__iand__) return __iand__ def symmetric_difference_update(fn): def symmetric_difference_update(self, other): want, have = self.symmetric_difference(other), set(self) remove, add = have - want, want - have for item in remove: self.remove(item) for item in add: self.add(item) _tidy(symmetric_difference_update) return symmetric_difference_update def __ixor__(fn): def __ixor__(self, other): if not _set_binops_check_strict(self, other): return NotImplemented want, have = self.symmetric_difference(other), set(self) remove, add = have - want, want - have for item in remove: self.remove(item) for item in add: self.add(item) return self _tidy(__ixor__) return __ixor__ l = locals().copy() l.pop('_tidy') l.pop('Unspecified') return l
[ "def", "_set_decorators", "(", ")", ":", "def", "_tidy", "(", "fn", ")", ":", "fn", ".", "_sa_instrumented", "=", "True", "fn", ".", "__doc__", "=", "getattr", "(", "set", ",", "fn", ".", "__name__", ")", ".", "__doc__", "Unspecified", "=", "util", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/collections.py#L1286-L1431
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/pygimplib/_lib/future/future/backports/urllib/request.py
python
getproxies_environment
()
return proxies
Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor.
Return a dictionary of scheme -> proxy server URL mappings.
[ "Return", "a", "dictionary", "of", "scheme", "-", ">", "proxy", "server", "URL", "mappings", "." ]
def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
[ "def", "getproxies_environment", "(", ")", ":", "proxies", "=", "{", "}", "for", "name", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "value", "and", "name", "[", "-", "...
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/future/backports/urllib/request.py#L2395-L2409
yiranran/Unpaired-Portrait-Drawing
b67591912a3e18622d56d3cd91cd6b71f1715649
data/base_dataset.py
python
BaseDataset.__getitem__
(self, index)
Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns: a dictionary of data with their names. It ususally contains the data itself and its metadata information.
Return a data point and its metadata information.
[ "Return", "a", "data", "point", "and", "its", "metadata", "information", "." ]
def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index - - a random integer for data indexing Returns: a dictionary of data with their names. It ususally contains the data itself and its metadata information. """ pass
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "pass" ]
https://github.com/yiranran/Unpaired-Portrait-Drawing/blob/b67591912a3e18622d56d3cd91cd6b71f1715649/data/base_dataset.py#L52-L61
naparuba/shinken
8163d645e801fa43ee1704f099a4684f120e667b
shinken/scheduler.py
python
Scheduler.restore_object_retention_data
(self, o, data)
Now load interesting properties in hosts/services Tagging retention=False prop that not be directly load Items will be with theirs status, but not in checking, so a new check will be launched like with a normal beginning (random distributed scheduling) :param Item o: The object to load data to :param dict data: The object's loaded retention data
Now load interesting properties in hosts/services Tagging retention=False prop that not be directly load Items will be with theirs status, but not in checking, so a new check will be launched like with a normal beginning (random distributed scheduling)
[ "Now", "load", "interesting", "properties", "in", "hosts", "/", "services", "Tagging", "retention", "=", "False", "prop", "that", "not", "be", "directly", "load", "Items", "will", "be", "with", "theirs", "status", "but", "not", "in", "checking", "so", "a", ...
def restore_object_retention_data(self, o, data): """ Now load interesting properties in hosts/services Tagging retention=False prop that not be directly load Items will be with theirs status, but not in checking, so a new check will be launched like with a normal beginning (random distributed scheduling) :param Item o: The object to load data to :param dict data: The object's loaded retention data """ # First manage all running properties running_properties = o.__class__.running_properties for prop, entry in running_properties.items(): if entry.retention: # Maybe the saved one was not with this value, so # we just bypass this if prop in data: setattr(o, prop, data[prop]) # Ok, some are in properties too (like active check enabled # or not. Will OVERRIDE THE CONFIGURATION VALUE! properties = o.__class__.properties for prop, entry in properties.items(): if entry.retention: # Maybe the saved one was not with this value, so # we just bypass this if prop in data: setattr(o, prop, data[prop]) # Now manage all linked oects load from previous run for a in o.notifications_in_progress.values(): a.ref = o self.add(a) # Also raises the action id, so do not overlap ids a.assume_at_least_id(a.id) # And also add downtimes and comments for dt in o.downtimes: dt.ref = o if hasattr(dt, 'extra_comment'): dt.extra_comment.ref = o else: dt.extra_comment = None # raises the downtime id to do not overlap Downtime.id = max(Downtime.id, dt.id + 1) self.add(dt) for c in o.comments: c.ref = o self.add(c) # raises comment id to do not overlap ids Comment.id = max(Comment.id, c.id + 1) if o.acknowledgement is not None: o.acknowledgement.ref = o # Raises the id of future ack so we don't overwrite # these one Acknowledge.id = max(Acknowledge.id, o.acknowledgement.id + 1) # Relink the notified_contacts as a set() of true contacts objects # it it was load from the retention, it's now a list of contacts # names if 'notified_contacts' in data: new_notified_contacts = set() for cname in o.notified_contacts: c = self.contacts.find_by_name(cname) # Maybe the contact is gone. Skip it if c: new_notified_contacts.add(c) o.notified_contacts = new_notified_contacts
[ "def", "restore_object_retention_data", "(", "self", ",", "o", ",", "data", ")", ":", "# First manage all running properties", "running_properties", "=", "o", ".", "__class__", ".", "running_properties", "for", "prop", ",", "entry", "in", "running_properties", ".", ...
https://github.com/naparuba/shinken/blob/8163d645e801fa43ee1704f099a4684f120e667b/shinken/scheduler.py#L1121-L1185
Tiiiger/SGC
2c7a2727e82e462d8ef9d6e57f0b08888e16488f
downstream/TextSGC/utils.py
python
loadWord2Vec
(filename)
return vocab, embd, word_vector_map
Read Word Vectors
Read Word Vectors
[ "Read", "Word", "Vectors" ]
def loadWord2Vec(filename): """Read Word Vectors""" vocab = [] embd = [] word_vector_map = {} file = open(filename, 'r') for line in file.readlines(): row = line.strip().split(' ') if(len(row) > 2): vocab.append(row[0]) vector = row[1:] length = len(vector) for i in range(length): vector[i] = float(vector[i]) embd.append(vector) word_vector_map[row[0]] = vector print('Loaded Word Vectors!') file.close() return vocab, embd, word_vector_map
[ "def", "loadWord2Vec", "(", "filename", ")", ":", "vocab", "=", "[", "]", "embd", "=", "[", "]", "word_vector_map", "=", "{", "}", "file", "=", "open", "(", "filename", ",", "'r'", ")", "for", "line", "in", "file", ".", "readlines", "(", ")", ":", ...
https://github.com/Tiiiger/SGC/blob/2c7a2727e82e462d8ef9d6e57f0b08888e16488f/downstream/TextSGC/utils.py#L73-L91
mozilla/dxr
ef09324a32930e2769e6ff63eaa8de76fcf79ee3
dxr/utils.py
python
decode_es_datetime
(es_datetime)
Turn an elasticsearch datetime into a datetime object.
Turn an elasticsearch datetime into a datetime object.
[ "Turn", "an", "elasticsearch", "datetime", "into", "a", "datetime", "object", "." ]
def decode_es_datetime(es_datetime): """Turn an elasticsearch datetime into a datetime object.""" try: return datetime.strptime(es_datetime, '%Y-%m-%dT%H:%M:%S') except ValueError: # For newer ES versions return datetime.strptime(es_datetime, '%Y-%m-%dT%H:%M:%S.%f')
[ "def", "decode_es_datetime", "(", "es_datetime", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "es_datetime", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "except", "ValueError", ":", "# For newer ES versions", "return", "datetime", ".", "strptime", "(", "...
https://github.com/mozilla/dxr/blob/ef09324a32930e2769e6ff63eaa8de76fcf79ee3/dxr/utils.py#L151-L157
sagiebenaim/DistanceGAN
f827205ee45de351261f44505109395192894351
cyclegan_arch/util/png.py
python
encode
(buf, width, height)
return b''.join( [ SIGNATURE ] + chunk(b'IHDR', struct.pack("!2I5B", width, height, bit_depth, COLOR_TYPE_RGB, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b''.join(raw_data()), 9)) + chunk(b'IEND', b'') )
buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB...
buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB...
[ "buf", ":", "must", "be", "bytes", "or", "a", "bytearray", "in", "py3", "a", "regular", "string", "in", "py2", ".", "formatted", "RGBRGB", "..." ]
def encode(buf, width, height): """ buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBRGB... """ assert (width * height * 3 == len(buf)) bpp = 3 def raw_data(): # reverse the vertical line order and add null bytes at the start row_bytes = width * bpp for row_start in range((height - 1) * width * bpp, -1, -row_bytes): yield b'\x00' yield buf[row_start:row_start + row_bytes] def chunk(tag, data): return [ struct.pack("!I", len(data)), tag, data, struct.pack("!I", 0xFFFFFFFF & zlib.crc32(data, zlib.crc32(tag))) ] SIGNATURE = b'\x89PNG\r\n\x1a\n' COLOR_TYPE_RGB = 2 COLOR_TYPE_RGBA = 6 bit_depth = 8 return b''.join( [ SIGNATURE ] + chunk(b'IHDR', struct.pack("!2I5B", width, height, bit_depth, COLOR_TYPE_RGB, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b''.join(raw_data()), 9)) + chunk(b'IEND', b'') )
[ "def", "encode", "(", "buf", ",", "width", ",", "height", ")", ":", "assert", "(", "width", "*", "height", "*", "3", "==", "len", "(", "buf", ")", ")", "bpp", "=", "3", "def", "raw_data", "(", ")", ":", "# reverse the vertical line order and add null byt...
https://github.com/sagiebenaim/DistanceGAN/blob/f827205ee45de351261f44505109395192894351/cyclegan_arch/util/png.py#L4-L33
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/plot/plot3d/shapes2.py
python
Line.tachyon_repr
(self, render_params)
return cmds
Return representation of the line suitable for plotting using the Tachyon ray tracer. TESTS:: sage: L = line3d([(cos(i),sin(i),i^2) for i in srange(0,10,.01)],color='red') sage: L.tachyon_repr(L.default_render_params())[0] 'FCylinder base 1.0 0.0 0.0 apex 0.9999500004166653 0.009999833334166664 0.0001 rad 0.005 texture...'
Return representation of the line suitable for plotting using the Tachyon ray tracer.
[ "Return", "representation", "of", "the", "line", "suitable", "for", "plotting", "using", "the", "Tachyon", "ray", "tracer", "." ]
def tachyon_repr(self, render_params): """ Return representation of the line suitable for plotting using the Tachyon ray tracer. TESTS:: sage: L = line3d([(cos(i),sin(i),i^2) for i in srange(0,10,.01)],color='red') sage: L.tachyon_repr(L.default_render_params())[0] 'FCylinder base 1.0 0.0 0.0 apex 0.9999500004166653 0.009999833334166664 0.0001 rad 0.005 texture...' """ T = render_params.transform cmds = [] px, py, pz = self.points[0] if T is None else T(self.points[0]) radius = self.thickness * TACHYON_PIXEL for P in self.points[1:]: x, y, z = P if T is None else T(P) if self.arrow_head and P is self.points[-1]: A = shapes.arrow3d((px, py, pz), (x, y, z), radius = radius, texture = self.texture) render_params.push_transform(~T) cmds.append(A.tachyon_repr(render_params)) render_params.pop_transform() else: cmd = ('FCylinder base {pos[0]!r} {pos[1]!r} {pos[2]!r} ' 'apex {apex[0]!r} {apex[1]!r} {apex[2]!r} ' 'rad {radius!r} {texture}').format( pos=(px, py, pz), apex=(x, y, z), radius=radius, texture=self.texture.id) cmds.append(cmd) px, py, pz = x, y, z return cmds
[ "def", "tachyon_repr", "(", "self", ",", "render_params", ")", ":", "T", "=", "render_params", ".", "transform", "cmds", "=", "[", "]", "px", ",", "py", ",", "pz", "=", "self", ".", "points", "[", "0", "]", "if", "T", "is", "None", "else", "T", "...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/plot/plot3d/shapes2.py#L983-L1013
alecthomas/voluptuous
980a55f57c0ecdd4fd3fec687dbbabf132f9e022
voluptuous/schema_builder.py
python
_iterate_object
(obj)
Return iterator over object attributes. Respect objects with defined __slots__.
Return iterator over object attributes. Respect objects with defined __slots__.
[ "Return", "iterator", "over", "object", "attributes", ".", "Respect", "objects", "with", "defined", "__slots__", "." ]
def _iterate_object(obj): """Return iterator over object attributes. Respect objects with defined __slots__. """ d = {} try: d = vars(obj) except TypeError: # maybe we have named tuple here? if hasattr(obj, '_asdict'): d = obj._asdict() for item in iteritems(d): yield item try: slots = obj.__slots__ except AttributeError: pass else: for key in slots: if key != '__dict__': yield (key, getattr(obj, key))
[ "def", "_iterate_object", "(", "obj", ")", ":", "d", "=", "{", "}", "try", ":", "d", "=", "vars", "(", "obj", ")", "except", "TypeError", ":", "# maybe we have named tuple here?", "if", "hasattr", "(", "obj", ",", "'_asdict'", ")", ":", "d", "=", "obj"...
https://github.com/alecthomas/voluptuous/blob/980a55f57c0ecdd4fd3fec687dbbabf132f9e022/voluptuous/schema_builder.py#L885-L906
python-provy/provy
ca3d5e96a2210daf3c1fd4b96e047efff152db14
provy/more/debian/database/postgresql.py
python
PostgreSQLRole.provision
(self)
Installs `PostgreSQL <http://www.postgresql.org/>`_ and its dependencies. This method should be called upon if overriden in base classes, or PostgreSQL won't work properly in the remote server. Example: :: class MySampleRole(Role): def provision(self): self.provision_role(PostgreSQLRole) # no need to call this if using with block.
Installs `PostgreSQL <http://www.postgresql.org/>`_ and its dependencies. This method should be called upon if overriden in base classes, or PostgreSQL won't work properly in the remote server.
[ "Installs", "PostgreSQL", "<http", ":", "//", "www", ".", "postgresql", ".", "org", "/", ">", "_", "and", "its", "dependencies", ".", "This", "method", "should", "be", "called", "upon", "if", "overriden", "in", "base", "classes", "or", "PostgreSQL", "won",...
def provision(self): ''' Installs `PostgreSQL <http://www.postgresql.org/>`_ and its dependencies. This method should be called upon if overriden in base classes, or PostgreSQL won't work properly in the remote server. Example: :: class MySampleRole(Role): def provision(self): self.provision_role(PostgreSQLRole) # no need to call this if using with block. ''' with self.using(AptitudeRole) as role: role.ensure_package_installed('postgresql') role.ensure_package_installed('postgresql-server-dev-%s' % self.__get_version())
[ "def", "provision", "(", "self", ")", ":", "with", "self", ".", "using", "(", "AptitudeRole", ")", "as", "role", ":", "role", ".", "ensure_package_installed", "(", "'postgresql'", ")", "role", ".", "ensure_package_installed", "(", "'postgresql-server-dev-%s'", "...
https://github.com/python-provy/provy/blob/ca3d5e96a2210daf3c1fd4b96e047efff152db14/provy/more/debian/database/postgresql.py#L30-L44
anki/cozmo-python-sdk
dd29edef18748fcd816550469195323842a7872e
examples/apps/quick_tap.py
python
QuickTapGame.report_scores
(self)
Prints the current scores of the game.
Prints the current scores of the game.
[ "Prints", "the", "current", "scores", "of", "the", "game", "." ]
def report_scores(self): '''Prints the current scores of the game.''' print('---------------------------------------------------') print('Player score: {}'.format(self.player.score)) print('Cozmo score: {}'.format(self.cozmo_player.score)) print('---------------------------------------------------')
[ "def", "report_scores", "(", "self", ")", ":", "print", "(", "'---------------------------------------------------'", ")", "print", "(", "'Player score: {}'", ".", "format", "(", "self", ".", "player", ".", "score", ")", ")", "print", "(", "'Cozmo score: {}'", "."...
https://github.com/anki/cozmo-python-sdk/blob/dd29edef18748fcd816550469195323842a7872e/examples/apps/quick_tap.py#L287-L292
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail/wagtailusers/forms.py
python
BaseGroupPagePermissionFormSet.empty_form
(self)
return empty_form
[]
def empty_form(self): empty_form = super(BaseGroupPagePermissionFormSet, self).empty_form empty_form.fields['DELETE'].widget = forms.HiddenInput() return empty_form
[ "def", "empty_form", "(", "self", ")", ":", "empty_form", "=", "super", "(", "BaseGroupPagePermissionFormSet", ",", "self", ")", ".", "empty_form", "empty_form", ".", "fields", "[", "'DELETE'", "]", ".", "widget", "=", "forms", ".", "HiddenInput", "(", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/wagtailusers/forms.py#L291-L294
larsyencken/csvdiff
533326dd1db7252cd37a67eabf6b56e9f2646221
csvdiff/patch.py
python
validate
(diff)
return jsonschema.validate(diff, SCHEMA)
Check the diff against the schema, raising an exception if it doesn't match.
Check the diff against the schema, raising an exception if it doesn't match.
[ "Check", "the", "diff", "against", "the", "schema", "raising", "an", "exception", "if", "it", "doesn", "t", "match", "." ]
def validate(diff): """ Check the diff against the schema, raising an exception if it doesn't match. """ return jsonschema.validate(diff, SCHEMA)
[ "def", "validate", "(", "diff", ")", ":", "return", "jsonschema", ".", "validate", "(", "diff", ",", "SCHEMA", ")" ]
https://github.com/larsyencken/csvdiff/blob/533326dd1db7252cd37a67eabf6b56e9f2646221/csvdiff/patch.py#L98-L103
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/python-3.7.2-embed-win32/gevent/pywsgi.py
python
LoggingLogAdapter.__init__
(self, logger, level=20)
Write information to the *logger* at the given *level* (default to INFO).
Write information to the *logger* at the given *level* (default to INFO).
[ "Write", "information", "to", "the", "*", "logger", "*", "at", "the", "given", "*", "level", "*", "(", "default", "to", "INFO", ")", "." ]
def __init__(self, logger, level=20): """ Write information to the *logger* at the given *level* (default to INFO). """ self._logger = logger self._level = level
[ "def", "__init__", "(", "self", ",", "logger", ",", "level", "=", "20", ")", ":", "self", ".", "_logger", "=", "logger", "self", ".", "_level", "=", "level" ]
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-win32/gevent/pywsgi.py#L1177-L1182
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/djangorestframework-3.9.4/rest_framework/fields.py
python
Field.get_initial
(self)
return self.initial
Return a value to use when the field is being returned as a primitive value, without any object instance.
Return a value to use when the field is being returned as a primitive value, without any object instance.
[ "Return", "a", "value", "to", "use", "when", "the", "field", "is", "being", "returned", "as", "a", "primitive", "value", "without", "any", "object", "instance", "." ]
def get_initial(self): """ Return a value to use when the field is being returned as a primitive value, without any object instance. """ if callable(self.initial): return self.initial() return self.initial
[ "def", "get_initial", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "initial", ")", ":", "return", "self", ".", "initial", "(", ")", "return", "self", ".", "initial" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/djangorestframework-3.9.4/rest_framework/fields.py#L414-L421
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/distutils/cmd.py
python
Command.make_file
(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1)
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks.
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks.
[ "Special", "case", "of", "execute", "()", "for", "operations", "that", "process", "one", "or", "more", "input", "files", "and", "generate", "one", "output", "file", ".", "Works", "just", "like", "execute", "()", "except", "the", "operation", "is", "skipped",...
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1): """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the command defined 'self.force', and it is true, then the command is unconditionally run -- does no timestamp checks. """ if skip_msg is None: skip_msg = "skipping %s (inputs unchanged)" % outfile # Allow 'infiles' to be a single string if isinstance(infiles, str): infiles = (infiles,) elif not isinstance(infiles, (list, tuple)): raise TypeError( "'infiles' must be a string, or a list or tuple of strings") if exec_msg is None: exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) # If 'outfile' must be regenerated (either because it doesn't # exist, is out-of-date, or the 'force' flag is true) then # perform the action that presumably regenerates it if self.force or dep_util.newer_group(infiles, outfile): self.execute(func, args, exec_msg, level) # Otherwise, print the "skip" message else: log.debug(skip_msg)
[ "def", "make_file", "(", "self", ",", "infiles", ",", "outfile", ",", "func", ",", "args", ",", "exec_msg", "=", "None", ",", "skip_msg", "=", "None", ",", "level", "=", "1", ")", ":", "if", "skip_msg", "is", "None", ":", "skip_msg", "=", "\"skipping...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/distutils/cmd.py#L374-L404
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/tornado/platform/twisted.py
python
TwistedIOLoop.update_handler
(self, fd, events)
[]
def update_handler(self, fd, events): fd, fileobj = self.split_fd(fd) if events & tornado.ioloop.IOLoop.READ: if not self.fds[fd].reading: self.fds[fd].reading = True self.reactor.addReader(self.fds[fd]) else: if self.fds[fd].reading: self.fds[fd].reading = False self.reactor.removeReader(self.fds[fd]) if events & tornado.ioloop.IOLoop.WRITE: if not self.fds[fd].writing: self.fds[fd].writing = True self.reactor.addWriter(self.fds[fd]) else: if self.fds[fd].writing: self.fds[fd].writing = False self.reactor.removeWriter(self.fds[fd])
[ "def", "update_handler", "(", "self", ",", "fd", ",", "events", ")", ":", "fd", ",", "fileobj", "=", "self", ".", "split_fd", "(", "fd", ")", "if", "events", "&", "tornado", ".", "ioloop", ".", "IOLoop", ".", "READ", ":", "if", "not", "self", ".", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/tornado/platform/twisted.py#L460-L477
awslabs/sockeye
ec2d13f7beb42d8c4f389dba0172250dc9154d5a
sockeye/evaluate.py
python
raw_corpus_rouge1
(hypotheses: Iterable[str], references: Iterable[str])
return rouge.rouge_1(hypotheses, references)
Simple wrapper around ROUGE-1 implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream. :return: ROUGE-1 score as float between 0 and 1.
Simple wrapper around ROUGE-1 implementation.
[ "Simple", "wrapper", "around", "ROUGE", "-", "1", "implementation", "." ]
def raw_corpus_rouge1(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around ROUGE-1 implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream. :return: ROUGE-1 score as float between 0 and 1. """ return rouge.rouge_1(hypotheses, references)
[ "def", "raw_corpus_rouge1", "(", "hypotheses", ":", "Iterable", "[", "str", "]", ",", "references", ":", "Iterable", "[", "str", "]", ")", "->", "float", ":", "return", "rouge", ".", "rouge_1", "(", "hypotheses", ",", "references", ")" ]
https://github.com/awslabs/sockeye/blob/ec2d13f7beb42d8c4f389dba0172250dc9154d5a/sockeye/evaluate.py#L60-L68
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/distutils/ccompiler.py
python
CCompiler.set_library_dirs
(self, dirs)
Set the list of library search directories to 'dirs' (a list of strings). This does not affect any standard library search path that the linker may search by default.
Set the list of library search directories to 'dirs' (a list of strings). This does not affect any standard library search path that the linker may search by default.
[ "Set", "the", "list", "of", "library", "search", "directories", "to", "dirs", "(", "a", "list", "of", "strings", ")", ".", "This", "does", "not", "affect", "any", "standard", "library", "search", "path", "that", "the", "linker", "may", "search", "by", "d...
def set_library_dirs(self, dirs): """Set the list of library search directories to 'dirs' (a list of strings). This does not affect any standard library search path that the linker may search by default. """ self.library_dirs = dirs[:]
[ "def", "set_library_dirs", "(", "self", ",", "dirs", ")", ":", "self", ".", "library_dirs", "=", "dirs", "[", ":", "]" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/distutils/ccompiler.py#L267-L272