Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
WalletRpcApi.log_in
(self, request)
Logs in the wallet with a specific key.
Logs in the wallet with a specific key.
async def log_in(self, request): """ Logs in the wallet with a specific key. """ fingerprint = request["fingerprint"] if self.service.logged_in_fingerprint == fingerprint: return {"fingerprint": fingerprint} await self._stop_wallet() log_in_type = re...
[ "async", "def", "log_in", "(", "self", ",", "request", ")", ":", "fingerprint", "=", "request", "[", "\"fingerprint\"", "]", "if", "self", ".", "service", ".", "logged_in_fingerprint", "==", "fingerprint", ":", "return", "{", "\"fingerprint\"", ":", "fingerpri...
[ 132, 4 ]
[ 182, 59 ]
python
en
['en', 'error', 'th']
False
WalletRpcApi.get_next_address
(self, request: Dict)
Returns a new address
Returns a new address
async def get_next_address(self, request: Dict) -> Dict: """ Returns a new address """ assert self.service.wallet_state_manager is not None if request["new_address"] is True: create_new = True else: create_new = False wallet_id = uint32(in...
[ "async", "def", "get_next_address", "(", "self", ",", "request", ":", "Dict", ")", "->", "Dict", ":", "assert", "self", ".", "service", ".", "wallet_state_manager", "is", "not", "None", "if", "request", "[", "\"new_address\"", "]", "is", "True", ":", "crea...
[ 512, 4 ]
[ 538, 9 ]
python
en
['en', 'error', 'th']
False
BaseSessionManager.encode
(self, session_dict)
Return the given session dictionary serialized and encoded as a string.
Return the given session dictionary serialized and encoded as a string.
def encode(self, session_dict): """ Return the given session dictionary serialized and encoded as a string. """ session_store_class = self.model.get_session_store_class() return session_store_class().encode(session_dict)
[ "def", "encode", "(", "self", ",", "session_dict", ")", ":", "session_store_class", "=", "self", ".", "model", ".", "get_session_store_class", "(", ")", "return", "session_store_class", "(", ")", ".", "encode", "(", "session_dict", ")" ]
[ 12, 4 ]
[ 17, 57 ]
python
en
['en', 'error', 'th']
False
setup_bash_profile
()
Select a bash profile file to add setup code to.
Select a bash profile file to add setup code to.
def setup_bash_profile() -> None: """Select a bash profile file to add setup code to.""" BASH_PROFILES = [ os.path.expanduser(p) for p in ("~/.bash_profile", "~/.bash_login", "~/.profile") ] def clear_old_profile() -> None: # An earlier version of this script would output a fresh .bash...
[ "def", "setup_bash_profile", "(", ")", "->", "None", ":", "BASH_PROFILES", "=", "[", "os", ".", "path", ".", "expanduser", "(", "p", ")", "for", "p", "in", "(", "\"~/.bash_profile\"", ",", "\"~/.bash_login\"", ",", "\"~/.profile\"", ")", "]", "def", "clear...
[ 104, 0 ]
[ 139, 45 ]
python
en
['en', 'sm', 'en']
True
AnsiToWin32.should_wrap
(self)
True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been...
True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been...
def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionali...
[ "def", "should_wrap", "(", "self", ")", ":", "return", "self", ".", "convert", "or", "self", ".", "strip", "or", "self", ".", "autoreset" ]
[ 105, 4 ]
[ 113, 59 ]
python
en
['en', 'error', 'th']
False
AnsiToWin32.write_and_convert
(self, text)
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.findi...
[ "def", "write_and_convert", "(", "self", ",", "text", ")", ":", "cursor", "=", "0", "text", "=", "self", ".", "convert_osc", "(", "text", ")", "for", "match", "in", "self", ".", "ANSI_CSI_RE", ".", "finditer", "(", "text", ")", ":", "start", ",", "en...
[ 176, 4 ]
[ 189, 54 ]
python
en
['en', 'error', 'th']
False
KeyValStore.get_object
(self, key: str, type: Any)
Return bytes representation of stored object
Return bytes representation of stored object
async def get_object(self, key: str, type: Any) -> Any: """ Return bytes representation of stored object """ cursor = await self.db_connection.execute("SELECT * from key_val_store WHERE key=?", (key,)) row = await cursor.fetchone() await cursor.close() if row is...
[ "async", "def", "get_object", "(", "self", ",", "key", ":", "str", ",", "type", ":", "Any", ")", "->", "Any", ":", "cursor", "=", "await", "self", ".", "db_connection", ".", "execute", "(", "\"SELECT * from key_val_store WHERE key=?\"", ",", "(", "key", ",...
[ 39, 4 ]
[ 51, 55 ]
python
en
['en', 'error', 'th']
False
KeyValStore.set_object
(self, key: str, obj: Streamable)
Adds object to key val store
Adds object to key val store
async def set_object(self, key: str, obj: Streamable): """ Adds object to key val store """ async with self.db_wrapper.lock: cursor = await self.db_connection.execute( "INSERT OR REPLACE INTO key_val_store VALUES(?, ?)", (key, bytes(obj).hex())...
[ "async", "def", "set_object", "(", "self", ",", "key", ":", "str", ",", "obj", ":", "Streamable", ")", ":", "async", "with", "self", ".", "db_wrapper", ".", "lock", ":", "cursor", "=", "await", "self", ".", "db_connection", ".", "execute", "(", "\"INSE...
[ 53, 4 ]
[ 63, 45 ]
python
en
['en', 'error', 'th']
False
update_last_login
(sender, user, **kwargs)
A signal receiver which updates the last_login date for the user logging in.
A signal receiver which updates the last_login date for the user logging in.
def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login'])
[ "def", "update_last_login", "(", "sender", ",", "user", ",", "*", "*", "kwargs", ")", ":", "user", ".", "last_login", "=", "timezone", ".", "now", "(", ")", "user", ".", "save", "(", "update_fields", "=", "[", "'last_login'", "]", ")" ]
[ 18, 0 ]
[ 24, 43 ]
python
en
['en', 'error', 'th']
False
_user_has_perm
(user, perm, obj)
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checking.
def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): r...
[ "def", "_user_has_perm", "(", "user", ",", "perm", ",", "obj", ")", ":", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "not", "hasattr", "(", "backend", ",", "'has_perm'", ")", ":", "continue", "try", ":", "if", "backend", ...
[ 181, 0 ]
[ 193, 16 ]
python
en
['en', 'error', 'th']
False
_user_has_module_perms
(user, app_label)
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checking.
def _user_has_module_perms(user, app_label): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_module_perms'): continue try: if backend.has_module_perms(user, app_l...
[ "def", "_user_has_module_perms", "(", "user", ",", "app_label", ")", ":", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "not", "hasattr", "(", "backend", ",", "'has_module_perms'", ")", ":", "continue", "try", ":", "if", "backen...
[ 196, 0 ]
[ 208, 16 ]
python
en
['en', 'error', 'th']
False
UserManager._create_user
(self, username, email, password, **extra_fields)
Creates and saves a User with the given username, email and password.
Creates and saves a User with the given username, email and password.
def _create_user(self, username, email, password, **extra_fields): """ Creates and saves a User with the given username, email and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = ...
[ "def", "_create_user", "(", "self", ",", "username", ",", "email", ",", "password", ",", "*", "*", "extra_fields", ")", ":", "if", "not", "username", ":", "raise", "ValueError", "(", "'The given username must be set'", ")", "email", "=", "self", ".", "normal...
[ 142, 4 ]
[ 153, 19 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.get_group_permissions
(self, obj=None)
Returns a list of permission strings that this user has through their groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned.
Returns a list of permission strings that this user has through their groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned.
def get_group_permissions(self, obj=None): """ Returns a list of permission strings that this user has through their groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned. """ permissions = s...
[ "def", "get_group_permissions", "(", "self", ",", "obj", "=", "None", ")", ":", "permissions", "=", "set", "(", ")", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "hasattr", "(", "backend", ",", "\"get_group_permissions\"", ")",...
[ 247, 4 ]
[ 257, 26 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_perm
(self, perm, obj=None)
Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provi...
Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provi...
def has_perm(self, perm, obj=None): """ Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permi...
[ "def", "has_perm", "(", "self", ",", "perm", ",", "obj", "=", "None", ")", ":", "# Active superusers have all permissions.", "if", "self", ".", "is_active", "and", "self", ".", "is_superuser", ":", "return", "True", "# Otherwise we need to check the backends.", "ret...
[ 262, 4 ]
[ 276, 46 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_perms
(self, perm_list, obj=None)
Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object.
Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object.
def has_perms(self, perm_list, obj=None): """ Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object. """ return all(self.has_perm(perm, obj) for perm in perm_list)
[ "def", "has_perms", "(", "self", ",", "perm_list", ",", "obj", "=", "None", ")", ":", "return", "all", "(", "self", ".", "has_perm", "(", "perm", ",", "obj", ")", "for", "perm", "in", "perm_list", ")" ]
[ 278, 4 ]
[ 284, 66 ]
python
en
['en', 'error', 'th']
False
PermissionsMixin.has_module_perms
(self, app_label)
Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above.
Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above.
def has_module_perms(self, app_label): """ Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return Tr...
[ "def", "has_module_perms", "(", "self", ",", "app_label", ")", ":", "# Active superusers have all permissions.", "if", "self", ".", "is_active", "and", "self", ".", "is_superuser", ":", "return", "True", "return", "_user_has_module_perms", "(", "self", ",", "app_lab...
[ 286, 4 ]
[ 295, 54 ]
python
en
['en', 'error', 'th']
False
AbstractUser.get_full_name
(self)
Returns the first_name plus the last_name, with a space in between.
Returns the first_name plus the last_name, with a space in between.
def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip()
[ "def", "get_full_name", "(", "self", ")", ":", "full_name", "=", "'%s %s'", "%", "(", "self", ".", "first_name", ",", "self", ".", "last_name", ")", "return", "full_name", ".", "strip", "(", ")" ]
[ 350, 4 ]
[ 355, 32 ]
python
en
['en', 'error', 'th']
False
AbstractUser.get_short_name
(self)
Returns the short name for the user.
Returns the short name for the user.
def get_short_name(self): "Returns the short name for the user." return self.first_name
[ "def", "get_short_name", "(", "self", ")", ":", "return", "self", ".", "first_name" ]
[ 357, 4 ]
[ 359, 30 ]
python
en
['en', 'en', 'en']
True
AbstractUser.email_user
(self, subject, message, from_email=None, **kwargs)
Sends an email to this User.
Sends an email to this User.
def email_user(self, subject, message, from_email=None, **kwargs): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email], **kwargs)
[ "def", "email_user", "(", "self", ",", "subject", ",", "message", ",", "from_email", "=", "None", ",", "*", "*", "kwargs", ")", ":", "send_mail", "(", "subject", ",", "message", ",", "from_email", ",", "[", "self", ".", "email", "]", ",", "*", "*", ...
[ 361, 4 ]
[ 365, 71 ]
python
en
['en', 'error', 'th']
False
make_command
(*args)
Create a CommandArgs object.
Create a CommandArgs object.
def make_command(*args): # type: (Union[str, HiddenText, CommandArgs]) -> CommandArgs """ Create a CommandArgs object. """ command_args = [] # type: CommandArgs for arg in args: # Check for list instead of CommandArgs since CommandArgs is # only known during type-checking. ...
[ "def", "make_command", "(", "*", "args", ")", ":", "# type: (Union[str, HiddenText, CommandArgs]) -> CommandArgs", "command_args", "=", "[", "]", "# type: CommandArgs", "for", "arg", "in", "args", ":", "# Check for list instead of CommandArgs since CommandArgs is", "# only know...
[ 24, 0 ]
[ 39, 23 ]
python
en
['en', 'error', 'th']
False
format_command_args
(args)
Format command arguments for display.
Format command arguments for display.
def format_command_args(args): # type: (Union[List[str], CommandArgs]) -> str """ Format command arguments for display. """ # For HiddenText arguments, display the redacted form by calling str(). # Also, we don't apply str() to arguments that aren't HiddenText since # this can trigger a Unic...
[ "def", "format_command_args", "(", "args", ")", ":", "# type: (Union[List[str], CommandArgs]) -> str", "# For HiddenText arguments, display the redacted form by calling str().", "# Also, we don't apply str() to arguments that aren't HiddenText since", "# this can trigger a UnicodeDecodeError in Py...
[ 42, 0 ]
[ 55, 5 ]
python
en
['en', 'error', 'th']
False
reveal_command_args
(args)
Return the arguments in their raw, unredacted form.
Return the arguments in their raw, unredacted form.
def reveal_command_args(args): # type: (Union[List[str], CommandArgs]) -> List[str] """ Return the arguments in their raw, unredacted form. """ return [ arg.secret if isinstance(arg, HiddenText) else arg for arg in args ]
[ "def", "reveal_command_args", "(", "args", ")", ":", "# type: (Union[List[str], CommandArgs]) -> List[str]", "return", "[", "arg", ".", "secret", "if", "isinstance", "(", "arg", ",", "HiddenText", ")", "else", "arg", "for", "arg", "in", "args", "]" ]
[ 58, 0 ]
[ 65, 5 ]
python
en
['en', 'error', 'th']
False
make_subprocess_output_error
( cmd_args, # type: Union[List[str], CommandArgs] cwd, # type: Optional[str] lines, # type: List[Text] exit_status, # type: int )
Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline.
Create and return the error message to use to log a subprocess error with command output.
def make_subprocess_output_error( cmd_args, # type: Union[List[str], CommandArgs] cwd, # type: Optional[str] lines, # type: List[Text] exit_status, # type: int ): # type: (...) -> Text """ Create and return the error message to use to log a subprocess error with comm...
[ "def", "make_subprocess_output_error", "(", "cmd_args", ",", "# type: Union[List[str], CommandArgs]", "cwd", ",", "# type: Optional[str]", "lines", ",", "# type: List[Text]", "exit_status", ",", "# type: int", ")", ":", "# type: (...) -> Text", "command", "=", "format_command...
[ 68, 0 ]
[ 107, 14 ]
python
en
['en', 'error', 'th']
False
call_subprocess
( cmd, # type: Union[List[str], CommandArgs] show_stdout=False, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapp...
Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an i...
Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an i...
def call_subprocess( cmd, # type: Union[List[str], CommandArgs] show_stdout=False, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # ...
[ "def", "call_subprocess", "(", "cmd", ",", "# type: Union[List[str], CommandArgs]", "show_stdout", "=", "False", ",", "# type: bool", "cwd", "=", "None", ",", "# type: Optional[str]", "on_returncode", "=", "'raise'", ",", "# type: str", "extra_ok_returncodes", "=", "Non...
[ 110, 0 ]
[ 252, 30 ]
python
en
['en', 'error', 'th']
False
runner_with_spinner_message
(message)
Provide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner.
Provide a subprocess_runner that shows a spinner message.
def runner_with_spinner_message(message): # type: (str) -> Callable[..., None] """Provide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. """ d...
[ "def", "runner_with_spinner_message", "(", "message", ")", ":", "# type: (str) -> Callable[..., None]", "def", "runner", "(", "cmd", ",", "# type: List[str]", "cwd", "=", "None", ",", "# type: Optional[str]", "extra_environ", "=", "None", "# type: Optional[Mapping[str, Any]...
[ 255, 0 ]
[ 277, 17 ]
python
en
['en', 'en', 'en']
True
url_to_file_path
(url, filecache)
Return the file cache path based on the URL. This does not ensure the file exists!
Return the file cache path based on the URL.
def url_to_file_path(url, filecache): """Return the file cache path based on the URL. This does not ensure the file exists! """ key = CacheController.cache_url(url) return filecache._fn(key)
[ "def", "url_to_file_path", "(", "url", ",", "filecache", ")", ":", "key", "=", "CacheController", ".", "cache_url", "(", "url", ")", "return", "filecache", ".", "_fn", "(", "key", ")" ]
[ 139, 0 ]
[ 145, 29 ]
python
en
['en', 'en', 'en']
True
TestPostgresSearchBackend.test_search_tsquery_chars
(self)
Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error.
Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error.
def test_search_tsquery_chars(self): """ Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error. """ # Simple quote should be escaped inside each tsquery term. results = self.backend.search("L'amour piqué par une abeille", ...
[ "def", "test_search_tsquery_chars", "(", "self", ")", ":", "# Simple quote should be escaped inside each tsquery term.", "results", "=", "self", ".", "backend", ".", "search", "(", "\"L'amour piqué par une abeille\",", "", "models", ".", "Book", ")", "self", ".", "asser...
[ 39, 4 ]
[ 84, 68 ]
python
en
['en', 'error', 'th']
False
TestPostgresSearchBackend.test_autocomplete_tsquery_chars
(self)
Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error.
Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error.
def test_autocomplete_tsquery_chars(self): """ Checks that tsquery characters are correctly escaped and do not generate a PostgreSQL syntax error. """ # Simple quote should be escaped inside each tsquery term. results = self.backend.autocomplete("L'amour piqué par une ab...
[ "def", "test_autocomplete_tsquery_chars", "(", "self", ")", ":", "# Simple quote should be escaped inside each tsquery term.", "results", "=", "self", ".", "backend", ".", "autocomplete", "(", "\"L'amour piqué par une abeille\",", "", "models", ".", "Book", ")", "self", "...
[ 86, 4 ]
[ 136, 68 ]
python
en
['en', 'error', 'th']
False
dist_from_wheel_url
(name, url, session)
Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised.
Return a pkg_resources.Distribution from the given wheel URL.
def dist_from_wheel_url(name, url, session): # type: (str, str, PipSession) -> Distribution """Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such...
[ "def", "dist_from_wheel_url", "(", "name", ",", "url", ",", "session", ")", ":", "# type: (str, str, PipSession) -> Distribution", "with", "LazyZipOverHTTP", "(", "url", ",", "session", ")", "as", "wheel", ":", "# For read-only ZIP files, ZipFile only needs methods read,", ...
[ 29, 0 ]
[ 44, 79 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.mode
(self)
Opening mode, which is always rb.
Opening mode, which is always rb.
def mode(self): # type: () -> str """Opening mode, which is always rb.""" return 'rb'
[ "def", "mode", "(", "self", ")", ":", "# type: () -> str", "return", "'rb'" ]
[ 72, 4 ]
[ 75, 19 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.name
(self)
Path to the underlying file.
Path to the underlying file.
def name(self): # type: () -> str """Path to the underlying file.""" return self._file.name
[ "def", "name", "(", "self", ")", ":", "# type: () -> str", "return", "self", ".", "_file", ".", "name" ]
[ 78, 4 ]
[ 81, 30 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.seekable
(self)
Return whether random access is supported, which is True.
Return whether random access is supported, which is True.
def seekable(self): # type: () -> bool """Return whether random access is supported, which is True.""" return True
[ "def", "seekable", "(", "self", ")", ":", "# type: () -> bool", "return", "True" ]
[ 83, 4 ]
[ 86, 19 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.close
(self)
Close the file.
Close the file.
def close(self): # type: () -> None """Close the file.""" self._file.close()
[ "def", "close", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_file", ".", "close", "(", ")" ]
[ 88, 4 ]
[ 91, 26 ]
python
en
['en', 'it', 'en']
True
LazyZipOverHTTP.closed
(self)
Whether the file is closed.
Whether the file is closed.
def closed(self): # type: () -> bool """Whether the file is closed.""" return self._file.closed
[ "def", "closed", "(", "self", ")", ":", "# type: () -> bool", "return", "self", ".", "_file", ".", "closed" ]
[ 94, 4 ]
[ 97, 32 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.read
(self, size=-1)
Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached.
Read up to size bytes from the object and return them.
def read(self, size=-1): # type: (int) -> bytes """Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached. """ download_size...
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "# type: (int) -> bytes", "download_size", "=", "max", "(", "size", ",", "self", ".", "_chunk_size", ")", "start", ",", "length", "=", "self", ".", "tell", "(", ")", ",", "self", ".", ...
[ 99, 4 ]
[ 112, 36 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.readable
(self)
Return whether the file is readable, which is True.
Return whether the file is readable, which is True.
def readable(self): # type: () -> bool """Return whether the file is readable, which is True.""" return True
[ "def", "readable", "(", "self", ")", ":", "# type: () -> bool", "return", "True" ]
[ 114, 4 ]
[ 117, 19 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.seek
(self, offset, whence=0)
Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative; * 2: End of stream - pos usually negative.
Change stream position and return the new absolute position.
def seek(self, offset, whence=0): # type: (int, int) -> int """Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative;...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "# type: (int, int) -> int", "return", "self", ".", "_file", ".", "seek", "(", "offset", ",", "whence", ")" ]
[ 119, 4 ]
[ 128, 46 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.tell
(self)
Return the current possition.
Return the current possition.
def tell(self): # type: () -> int """Return the current possition.""" return self._file.tell()
[ "def", "tell", "(", "self", ")", ":", "# type: () -> int", "return", "self", ".", "_file", ".", "tell", "(", ")" ]
[ 130, 4 ]
[ 133, 32 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.truncate
(self, size=None)
Resize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size.
Resize the stream to the given size in bytes.
def truncate(self, size=None): # type: (Optional[int]) -> int """Resize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size. """ return self._file.trunc...
[ "def", "truncate", "(", "self", ",", "size", "=", "None", ")", ":", "# type: (Optional[int]) -> int", "return", "self", ".", "_file", ".", "truncate", "(", "size", ")" ]
[ 135, 4 ]
[ 144, 40 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP.writable
(self)
Return False.
Return False.
def writable(self): # type: () -> bool """Return False.""" return False
[ "def", "writable", "(", "self", ")", ":", "# type: () -> bool", "return", "False" ]
[ 146, 4 ]
[ 149, 20 ]
python
en
['en', 'ms', 'en']
False
LazyZipOverHTTP._stay
(self)
Return a context manager keeping the position. At the end of the block, seek back to original position.
Return a context manager keeping the position.
def _stay(self): # type: ()-> Iterator[None] """Return a context manager keeping the position. At the end of the block, seek back to original position. """ pos = self.tell() try: yield finally: self.seek(pos)
[ "def", "_stay", "(", "self", ")", ":", "# type: ()-> Iterator[None]", "pos", "=", "self", ".", "tell", "(", ")", "try", ":", "yield", "finally", ":", "self", ".", "seek", "(", "pos", ")" ]
[ 161, 4 ]
[ 171, 26 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP._check_zip
(self)
Check and download until the file is a valid ZIP.
Check and download until the file is a valid ZIP.
def _check_zip(self): # type: () -> None """Check and download until the file is a valid ZIP.""" end = self._length - 1 for start in reversed(range(0, end, self._chunk_size)): self._download(start, end) with self._stay(): try: #...
[ "def", "_check_zip", "(", "self", ")", ":", "# type: () -> None", "end", "=", "self", ".", "_length", "-", "1", "for", "start", "in", "reversed", "(", "range", "(", "0", ",", "end", ",", "self", ".", "_chunk_size", ")", ")", ":", "self", ".", "_downl...
[ 173, 4 ]
[ 187, 25 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP._stream_response
(self, start, end, base_headers=HEADERS)
Return HTTP response to a range request from start to end.
Return HTTP response to a range request from start to end.
def _stream_response(self, start, end, base_headers=HEADERS): # type: (int, int, Dict[str, str]) -> Response """Return HTTP response to a range request from start to end.""" headers = base_headers.copy() headers['Range'] = 'bytes={}-{}'.format(start, end) # TODO: Get range reques...
[ "def", "_stream_response", "(", "self", ",", "start", ",", "end", ",", "base_headers", "=", "HEADERS", ")", ":", "# type: (int, int, Dict[str, str]) -> Response", "headers", "=", "base_headers", ".", "copy", "(", ")", "headers", "[", "'Range'", "]", "=", "'bytes...
[ 189, 4 ]
[ 196, 73 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP._merge
(self, start, end, left, right)
Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data
Return an iterator of intervals to be fetched.
def _merge(self, start, end, left, right): # type: (int, int, int, int) -> Iterator[Tuple[int, int]] """Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first ove...
[ "def", "_merge", "(", "self", ",", "start", ",", "end", ",", "left", ",", "right", ")", ":", "# type: (int, int, int, int) -> Iterator[Tuple[int, int]]", "lslice", ",", "rslice", "=", "self", ".", "_left", "[", "left", ":", "right", "]", ",", "self", ".", ...
[ 198, 4 ]
[ 217, 72 ]
python
en
['en', 'en', 'en']
True
LazyZipOverHTTP._download
(self, start, end)
Download bytes from start to end inclusively.
Download bytes from start to end inclusively.
def _download(self, start, end): # type: (int, int) -> None """Download bytes from start to end inclusively.""" with self._stay(): left = bisect_left(self._right, start) right = bisect_right(self._left, end) for start, end in self._merge(start, end, left, righ...
[ "def", "_download", "(", "self", ",", "start", ",", "end", ")", ":", "# type: (int, int) -> None", "with", "self", ".", "_stay", "(", ")", ":", "left", "=", "bisect_left", "(", "self", ".", "_right", ",", "start", ")", "right", "=", "bisect_right", "(", ...
[ 219, 4 ]
[ 230, 43 ]
python
en
['en', 'en', 'en']
True
sanitize_db_inputs
(params)
Replace values in params with alternatives suitable for database insertion. That includes: * Convert numpy.floating types into Python floats; * Convert infs into the string "Infinity". Args: params: (Potentially) dirty database inputs Returns: Sanitized database inpu...
Replace values in params with alternatives suitable for database insertion.
def sanitize_db_inputs(params): """ Replace values in params with alternatives suitable for database insertion. That includes: * Convert numpy.floating types into Python floats; * Convert infs into the string "Infinity". Args: params: (Potentially) dirty database inputs R...
[ "def", "sanitize_db_inputs", "(", "params", ")", ":", "def", "sanitize", "(", "val", ")", ":", "val", "=", "substitute_inf", "(", "val", ")", "if", "isinstance", "(", "val", ",", "numpy", ".", "floating", ")", ":", "val", "=", "float", "(", "val", ")...
[ 15, 0 ]
[ 43, 18 ]
python
en
['en', 'error', 'th']
False
Database.connect
(self, check=True)
connect to the configured database args: check (bool): check if schema version is correct
connect to the configured database
def connect(self, check=True): """ connect to the configured database args: check (bool): check if schema version is correct """ logger.info("connecting to database...") self._connection = self.alchemy_engine.connect() self._connection.execution_opti...
[ "def", "connect", "(", "self", ",", "check", "=", "True", ")", ":", "logger", ".", "info", "(", "\"connecting to database...\"", ")", "self", ".", "_connection", "=", "self", ".", "alchemy_engine", ".", "connect", "(", ")", "self", ".", "_connection", ".",...
[ 98, 4 ]
[ 128, 75 ]
python
en
['en', 'error', 'th']
False
Database.connection
(self)
The database connection, will be created if it doesn't exists. This is a property to be backwards compatible with the rest of TKP. :return: a database connection
The database connection, will be created if it doesn't exists.
def connection(self): """ The database connection, will be created if it doesn't exists. This is a property to be backwards compatible with the rest of TKP. :return: a database connection """ if not self._connection: self.connect() self.cursor = sel...
[ "def", "connection", "(", "self", ")", ":", "if", "not", "self", ".", "_connection", ":", "self", ".", "connect", "(", ")", "self", ".", "cursor", "=", "self", ".", "_connection", ".", "connection", ".", "cursor", "(", ")", "return", "self", ".", "_c...
[ 131, 4 ]
[ 144, 31 ]
python
en
['en', 'error', 'th']
False
Database.close
(self)
close the connection if open
close the connection if open
def close(self): """ close the connection if open """ if self.session: self.session.close() if self._connection: self._connection.close() self._connection = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "session", ":", "self", ".", "session", ".", "close", "(", ")", "if", "self", ".", "_connection", ":", "self", ".", "_connection", ".", "close", "(", ")", "self", ".", "_connection", "=", "N...
[ 146, 4 ]
[ 156, 31 ]
python
en
['en', 'error', 'th']
False
Database.vacuum
(self, table)
Force a vacuum on a table, which removes dead rows. (Postgres only) Normally the auto vacuum process does this for you, but in some cases (for example when the table receives many insert and deletes) manual vacuuming is necessary for performance reasons. args: tab...
Force a vacuum on a table, which removes dead rows. (Postgres only)
def vacuum(self, table): """ Force a vacuum on a table, which removes dead rows. (Postgres only) Normally the auto vacuum process does this for you, but in some cases (for example when the table receives many insert and deletes) manual vacuuming is necessary for performance rea...
[ "def", "vacuum", "(", "self", ",", "table", ")", ":", "if", "self", ".", "engine", "!=", "\"postgresql\"", ":", "return", "from", "psycopg2", ".", "extensions", "import", "(", "ISOLATION_LEVEL_AUTOCOMMIT", ",", "ISOLATION_LEVEL_READ_COMMITTED", ")", "# disable aut...
[ 158, 4 ]
[ 181, 86 ]
python
en
['en', 'error', 'th']
False
get_reference_base
(fasta, chrom, pos)
Get the reference base for a position, can be used to generate odds ratio of mismatch/match change in kd vs cntrl
Get the reference base for a position, can be used to generate odds ratio of mismatch/match change in kd vs cntrl
def get_reference_base(fasta, chrom, pos): ''' Get the reference base for a position, can be used to generate odds ratio of mismatch/match change in kd vs cntrl ''' ref_base = fasta.fetch(chrom, pos, pos + 1) return ref_base
[ "def", "get_reference_base", "(", "fasta", ",", "chrom", ",", "pos", ")", ":", "ref_base", "=", "fasta", ".", "fetch", "(", "chrom", ",", "pos", ",", "pos", "+", "1", ")", "return", "ref_base" ]
[ 6, 0 ]
[ 12, 19 ]
python
en
['en', 'error', 'th']
False
calculate_mismatch_odds_ratio
(ref_base, kd_counts, cntrl_counts)
Calculate the log2 odds ratio with haldane correction (0.5 pseudocount)
Calculate the log2 odds ratio with haldane correction (0.5 pseudocount)
def calculate_mismatch_odds_ratio(ref_base, kd_counts, cntrl_counts): ''' Calculate the log2 odds ratio with haldane correction (0.5 pseudocount) ''' try: kd_m = float(kd_counts[ref_base]) except KeyError: kd_m = 0.0 kd_mm = float(kd_counts.sum() - kd_m) try: cnt...
[ "def", "calculate_mismatch_odds_ratio", "(", "ref_base", ",", "kd_counts", ",", "cntrl_counts", ")", ":", "try", ":", "kd_m", "=", "float", "(", "kd_counts", "[", "ref_base", "]", ")", "except", "KeyError", ":", "kd_m", "=", "0.0", "kd_mm", "=", "float", "...
[ 15, 0 ]
[ 33, 65 ]
python
en
['en', 'error', 'th']
False
SessionMiddleware.process_response
(self, request, response)
If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.
If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.
def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: acce...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "accessed", "=", "request", ".", "session", ".", "accessed", "modified", "=", "request", ".", "session", ".", "modified", "empty", "=", "request", ".", "session"...
[ 21, 4 ]
[ 72, 23 ]
python
en
['en', 'error', 'th']
False
current_platform
()
Get current platform name by short string.
Get current platform name by short string.
def current_platform() -> str: """Get current platform name by short string.""" if sys.platform.startswith('linux'): return 'linux' elif sys.platform.startswith('darwin'): return 'mac' elif (sys.platform.startswith('win') or sys.platform.startswith('msys') or sys.plat...
[ "def", "current_platform", "(", ")", "->", "str", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "return", "'linux'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "return", "'mac'", "elif"...
[ 49, 0 ]
[ 61, 58 ]
python
en
['en', 'da', 'en']
True
get_url
()
Get chromium download url.
Get chromium download url.
def get_url() -> str: """Get chromium download url.""" return downloadURLs[current_platform()]
[ "def", "get_url", "(", ")", "->", "str", ":", "return", "downloadURLs", "[", "current_platform", "(", ")", "]" ]
[ 64, 0 ]
[ 66, 43 ]
python
de
['de', 'la', 'nl']
False
download_zip
(url: str)
Download data from url.
Download data from url.
def download_zip(url: str) -> BytesIO: """Download data from url.""" logger.warning('start chromium download.\n' 'Download may take a few minutes.') # disable warnings so that we don't need a cert. # see https://urllib3.readthedocs.io/en/latest/advanced-usage.html for more urllib...
[ "def", "download_zip", "(", "url", ":", "str", ")", "->", "BytesIO", ":", "logger", ".", "warning", "(", "'start chromium download.\\n'", "'Download may take a few minutes.'", ")", "# disable warnings so that we don't need a cert.", "# see https://urllib3.readthedocs.io/en/latest...
[ 69, 0 ]
[ 101, 16 ]
python
en
['en', 'en', 'en']
True
extract_zip
(data: BytesIO, path: Path)
Extract zipped data to path.
Extract zipped data to path.
def extract_zip(data: BytesIO, path: Path) -> None: """Extract zipped data to path.""" # On mac zipfile module cannot extract correctly, so use unzip instead. if current_platform() == 'mac': import subprocess import shutil zip_path = path / 'chrome.zip' if not path.exists(): ...
[ "def", "extract_zip", "(", "data", ":", "BytesIO", ",", "path", ":", "Path", ")", "->", "None", ":", "# On mac zipfile module cannot extract correctly, so use unzip instead.", "if", "current_platform", "(", ")", "==", "'mac'", ":", "import", "subprocess", "import", ...
[ 104, 0 ]
[ 137, 52 ]
python
en
['lv', 'en', 'en']
True
download_chromium
()
Download and extract chromium.
Download and extract chromium.
def download_chromium() -> None: """Download and extract chromium.""" extract_zip(download_zip(get_url()), DOWNLOADS_FOLDER / REVISION)
[ "def", "download_chromium", "(", ")", "->", "None", ":", "extract_zip", "(", "download_zip", "(", "get_url", "(", ")", ")", ",", "DOWNLOADS_FOLDER", "/", "REVISION", ")" ]
[ 140, 0 ]
[ 142, 69 ]
python
en
['en', 'en', 'en']
True
chromium_excutable
()
[Deprecated] miss-spelled function. Use `chromium_executable` instead.
[Deprecated] miss-spelled function.
def chromium_excutable() -> Path: """[Deprecated] miss-spelled function. Use `chromium_executable` instead. """ logger.warning( '`chromium_excutable` function is deprecated. ' 'Use `chromium_executable instead.' ) return chromium_executable()
[ "def", "chromium_excutable", "(", ")", "->", "Path", ":", "logger", ".", "warning", "(", "'`chromium_excutable` function is deprecated. '", "'Use `chromium_executable instead.'", ")", "return", "chromium_executable", "(", ")" ]
[ 145, 0 ]
[ 154, 32 ]
python
en
['en', 'en', 'en']
True
chromium_executable
()
Get path of the chromium executable.
Get path of the chromium executable.
def chromium_executable() -> Path: """Get path of the chromium executable.""" return chromiumExecutable[current_platform()]
[ "def", "chromium_executable", "(", ")", "->", "Path", ":", "return", "chromiumExecutable", "[", "current_platform", "(", ")", "]" ]
[ 157, 0 ]
[ 159, 49 ]
python
en
['en', 'en', 'en']
True
check_chromium
()
Check if chromium is placed at correct path.
Check if chromium is placed at correct path.
def check_chromium() -> bool: """Check if chromium is placed at correct path.""" return chromium_executable().exists()
[ "def", "check_chromium", "(", ")", "->", "bool", ":", "return", "chromium_executable", "(", ")", ".", "exists", "(", ")" ]
[ 162, 0 ]
[ 164, 41 ]
python
en
['en', 'en', 'en']
True
setup_environment
(inventory, project, machine_credential, host, notification_template, label)
Create old jobs and new jobs, with various other objects to hit the related fields of Jobs. This makes sure on_delete() effects are tested properly.
Create old jobs and new jobs, with various other objects to hit the related fields of Jobs. This makes sure on_delete() effects are tested properly.
def setup_environment(inventory, project, machine_credential, host, notification_template, label): """ Create old jobs and new jobs, with various other objects to hit the related fields of Jobs. This makes sure on_delete() effects are tested properly. """ old_jobs = [] new_jobs = [] days...
[ "def", "setup_environment", "(", "inventory", ",", "project", ",", "machine_credential", ",", "host", ",", "notification_template", ",", "label", ")", ":", "old_jobs", "=", "[", "]", "new_jobs", "=", "[", "]", "days", "=", "10", "days_str", "=", "str", "("...
[ 15, 0 ]
[ 64, 41 ]
python
en
['en', 'error', 'th']
False
test_awxcollector
(setup_environment)
Efforts to improve the performance of cleanup_jobs involved sub-classing the django Collector class. This unit test will check for parity between the django Collector and the modified AWXCollector class. AWXCollector is used in cleanup_jobs to bulk-delete old jobs from the database. Specifical...
Efforts to improve the performance of cleanup_jobs involved sub-classing the django Collector class. This unit test will check for parity between the django Collector and the modified AWXCollector class. AWXCollector is used in cleanup_jobs to bulk-delete old jobs from the database.
def test_awxcollector(setup_environment): """ Efforts to improve the performance of cleanup_jobs involved sub-classing the django Collector class. This unit test will check for parity between the django Collector and the modified AWXCollector class. AWXCollector is used in cleanup_jobs to bulk-d...
[ "def", "test_awxcollector", "(", "setup_environment", ")", ":", "(", "old_jobs", ",", "new_jobs", ",", "days_str", ")", "=", "setup_environment", "collector", "=", "Collector", "(", "'default'", ")", "collector", ".", "collect", "(", "old_jobs", ")", "awx_col", ...
[ 113, 0 ]
[ 177, 57 ]
python
en
['en', 'error', 'th']
False
avatar
( request: HttpRequest, user_profile: UserProfile, email_or_id: str, medium: bool = False )
Accepts an email address or user ID and returns the avatar
Accepts an email address or user ID and returns the avatar
def avatar( request: HttpRequest, user_profile: UserProfile, email_or_id: str, medium: bool = False ) -> HttpResponse: """Accepts an email address or user ID and returns the avatar""" is_email = False try: int(email_or_id) except ValueError: is_email = True try: realm = ...
[ "def", "avatar", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "email_or_id", ":", "str", ",", "medium", ":", "bool", "=", "False", ")", "->", "HttpResponse", ":", "is_email", "=", "False", "try", ":", "int", "(", "ema...
[ 214, 0 ]
[ 246, 24 ]
python
en
['en', 'en', 'en']
True
get_members_backend
( request: HttpRequest, user_profile: UserProfile, user_id: Optional[int] = None, include_custom_profile_fields: bool = REQ(json_validator=check_bool, default=False), client_gravatar: bool = REQ(json_validator=check_bool, default=False), )
The client_gravatar field here is set to True if clients can compute their own gravatars, which saves us bandwidth. We want to eventually make this the default behavior, but we have old clients that expect the server to compute this for us.
The client_gravatar field here is set to True if clients can compute their own gravatars, which saves us bandwidth. We want to eventually make this the default behavior, but we have old clients that expect the server to compute this for us.
def get_members_backend( request: HttpRequest, user_profile: UserProfile, user_id: Optional[int] = None, include_custom_profile_fields: bool = REQ(json_validator=check_bool, default=False), client_gravatar: bool = REQ(json_validator=check_bool, default=False), ) -> HttpResponse: """ The clie...
[ "def", "get_members_backend", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "user_id", ":", "Optional", "[", "int", "]", "=", "None", ",", "include_custom_profile_fields", ":", "bool", "=", "REQ", "(", "json_validator", "=", ...
[ 520, 0 ]
[ 558, 29 ]
python
en
['en', 'error', 'th']
False
install_lib.get_outputs
(self)
Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet.
Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet.
def get_outputs(self): """Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet. """ pure_outputs = \ self._mutate_outputs(self.distribution.has_pure_modu...
[ "def", "get_outputs", "(", "self", ")", ":", "pure_outputs", "=", "self", ".", "_mutate_outputs", "(", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ",", "'build_py'", ",", "'build_lib'", ",", "self", ".", "install_dir", ")", "if", "self", ...
[ 179, 4 ]
[ 198, 60 ]
python
en
['en', 'en', 'en']
True
install_lib.get_inputs
(self)
Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by 'get_outputs()'.
Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by 'get_outputs()'.
def get_inputs(self): """Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by 'get_outputs()'. """ inputs = [] ...
[ "def", "get_inputs", "(", "self", ")", ":", "inputs", "=", "[", "]", "if", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ":", "build_py", "=", "self", ".", "get_finalized_command", "(", "'build_py'", ")", "inputs", ".", "extend", "(", "...
[ 200, 4 ]
[ 216, 21 ]
python
en
['en', 'en', 'en']
True
add_missing_messages
(user_profile: UserProfile)
This function takes a soft-deactivated user, and computes and adds to the database any UserMessage rows that were not created while the user was soft-deactivated. The end result is that from the perspective of the message database, it should be impossible to tell that the user was soft-deactivated at a...
This function takes a soft-deactivated user, and computes and adds to the database any UserMessage rows that were not created while the user was soft-deactivated. The end result is that from the perspective of the message database, it should be impossible to tell that the user was soft-deactivated at a...
def add_missing_messages(user_profile: UserProfile) -> None: """This function takes a soft-deactivated user, and computes and adds to the database any UserMessage rows that were not created while the user was soft-deactivated. The end result is that from the perspective of the message database, it shou...
[ "def", "add_missing_messages", "(", "user_profile", ":", "UserProfile", ")", "->", "None", ":", "assert", "user_profile", ".", "last_active_message_id", "is", "not", "None", "all_stream_subs", "=", "list", "(", "Subscription", ".", "objects", ".", "filter", "(", ...
[ 103, 0 ]
[ 228, 67 ]
python
en
['en', 'en', 'en']
True
NeighborKernelDensityEstimation.fit
(self, X, Y, **kwargs)
Since NKDE is a lazy learner, fit just stores the provided training data (X,Y) Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y)
Since NKDE is a lazy learner, fit just stores the provided training data (X,Y)
def fit(self, X, Y, **kwargs): """ Since NKDE is a lazy learner, fit just stores the provided training data (X,Y) Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y) """ X, Y = self._handle_input_dimensiona...
[ "def", "fit", "(", "self", ",", "X", ",", "Y", ",", "*", "*", "kwargs", ")", ":", "X", ",", "Y", "=", "self", ".", "_handle_input_dimensionality", "(", "X", ",", "Y", ",", "fitting", "=", "True", ")", "self", ".", "_build_model", "(", "X", ",", ...
[ 62, 2 ]
[ 77, 22 ]
python
en
['en', 'en', 'en']
True
NeighborKernelDensityEstimation.pdf
(self, X, Y)
Predicts the conditional probability density p(y|x). Requires the model to be fitted. Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y) Returns: conditional probability p(y|x) - numpy array of sh...
Predicts the conditional probability density p(y|x). Requires the model to be fitted.
def pdf(self, X, Y): """ Predicts the conditional probability density p(y|x). Requires the model to be fitted. Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y) Returns: conditional probabilit...
[ "def", "pdf", "(", "self", ",", "X", ",", "Y", ")", ":", "return", "np", ".", "exp", "(", "self", ".", "log_pdf", "(", "X", ",", "Y", ")", ")" ]
[ 79, 2 ]
[ 90, 36 ]
python
en
['en', 'en', 'en']
True
NeighborKernelDensityEstimation.log_pdf
(self, X, Y)
Predicts the conditional log-probability log p(y|x). Requires the model to be fitted. Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y) Returns: conditional log-probability log p(y|x) - numpy arr...
Predicts the conditional log-probability log p(y|x). Requires the model to be fitted.
def log_pdf(self, X, Y): """ Predicts the conditional log-probability log p(y|x). Requires the model to be fitted. Args: X: numpy array to be conditioned on - shape: (n_samples, n_dim_x) Y: numpy array of y targets - shape: (n_samples, n_dim_y) Returns: conditional log-pr...
[ "def", "log_pdf", "(", "self", ",", "X", ",", "Y", ")", ":", "X", ",", "Y", "=", "self", ".", "_handle_input_dimensionality", "(", "X", ",", "Y", ",", "fitting", "=", "True", ")", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "if", "n_sampl...
[ 92, 2 ]
[ 109, 32 ]
python
en
['en', 'en', 'en']
True
NeighborKernelDensityEstimation.loo_likelihood
(self, bandwidth, epsilon)
calculates the negative leave-one-out log-likelihood of the training data Args: bw: bandwidth parameter epsilon: size of the (normalized) neighborhood region
calculates the negative leave-one-out log-likelihood of the training data
def loo_likelihood(self, bandwidth, epsilon): """ calculates the negative leave-one-out log-likelihood of the training data Args: bw: bandwidth parameter epsilon: size of the (normalized) neighborhood region """ kernel_weights = self._kernel_weights(self.X_train, epsilon) # remove ...
[ "def", "loo_likelihood", "(", "self", ",", "bandwidth", ",", "epsilon", ")", ":", "kernel_weights", "=", "self", ".", "_kernel_weights", "(", "self", ".", "X_train", ",", "epsilon", ")", "# remove kernel of query x and re-normalize weights", "np", ".", "fill_diagona...
[ 114, 2 ]
[ 132, 45 ]
python
en
['en', 'error', 'th']
False
NeighborKernelDensityEstimation._log_pdf
(self, X, Y)
1. Determine weights of the Gaussians
1. Determine weights of the Gaussians
def _log_pdf(self, X, Y): """ 1. Determine weights of the Gaussians """ X_normalized = self._normalize_x(X) kernel_weights = self._kernel_weights(X_normalized, self.epsilon) """ 2. Calculate the conditional log densities """ n_samples = X.shape[0] conditional_densities = np.zeros(n_samples) ...
[ "def", "_log_pdf", "(", "self", ",", "X", ",", "Y", ")", ":", "X_normalized", "=", "self", ".", "_normalize_x", "(", "X", ")", "kernel_weights", "=", "self", ".", "_kernel_weights", "(", "X_normalized", ",", "self", ".", "epsilon", ")", "\"\"\" 2. Calculat...
[ 160, 2 ]
[ 172, 32 ]
python
en
['en', 'en', 'en']
True
main
()
Main driver.
Main driver.
def main(): """Main driver.""" args = parse_args() args.reporter = Reporter() check_config(args.reporter, args.source_dir) check_source_rmd(args.reporter, args.source_dir, args.parser) args.references = read_references(args.reporter, args.reference_path) docs = read_all_markdown(args.sourc...
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "args", ".", "reporter", "=", "Reporter", "(", ")", "check_config", "(", "args", ".", "reporter", ",", "args", ".", "source_dir", ")", "check_source_rmd", "(", "args", ".", "reporter", ...
[ 112, 0 ]
[ 130, 15 ]
python
en
['nl', 'fil', 'en']
False
parse_args
()
Parse command-line arguments.
Parse command-line arguments.
def parse_args(): """Parse command-line arguments.""" parser = ArgumentParser(description="""Check episode files in a lesson.""") parser.add_argument('-l', '--linelen', default=False, action="store_true", dest='line_lengths', ...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"\"\"Check episode files in a lesson.\"\"\"", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--linelen'", ",", "default", "=", "False", ",", "action", "=", "...
[ 133, 0 ]
[ 171, 15 ]
python
en
['en', 'fr', 'en']
True
check_config
(reporter, source_dir)
Check configuration file.
Check configuration file.
def check_config(reporter, source_dir): """Check configuration file.""" config_file = os.path.join(source_dir, '_config.yml') config = load_yaml(config_file) reporter.check_field(config_file, 'configuration', config, 'kind', 'lesson') reporter.check_field(config_file, 'conf...
[ "def", "check_config", "(", "reporter", ",", "source_dir", ")", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "'_config.yml'", ")", "config", "=", "load_yaml", "(", "config_file", ")", "reporter", ".", "check_field", "(", ...
[ 174, 0 ]
[ 193, 60 ]
python
en
['en', 'it', 'en']
True
check_source_rmd
(reporter, source_dir, parser)
Check that Rmd episode files include `source: Rmd`
Check that Rmd episode files include `source: Rmd`
def check_source_rmd(reporter, source_dir, parser): """Check that Rmd episode files include `source: Rmd`""" episode_rmd_dir = [os.path.join(source_dir, d) for d in SOURCE_RMD_DIRS] episode_rmd_files = [os.path.join(d, '*.Rmd') for d in episode_rmd_dir] results = {} for pat in episode_rmd_files: ...
[ "def", "check_source_rmd", "(", "reporter", ",", "source_dir", ",", "parser", ")", ":", "episode_rmd_dir", "=", "[", "os", ".", "path", ".", "join", "(", "source_dir", ",", "d", ")", "for", "d", "in", "SOURCE_RMD_DIRS", "]", "episode_rmd_files", "=", "[", ...
[ 195, 0 ]
[ 207, 57 ]
python
en
['en', 'en', 'en']
True
read_references
(reporter, ref_path)
Read shared file of reference links, returning dictionary of valid references {symbolic_name : URL}
Read shared file of reference links, returning dictionary of valid references {symbolic_name : URL}
def read_references(reporter, ref_path): """Read shared file of reference links, returning dictionary of valid references {symbolic_name : URL} """ if not ref_path: raise Warning("No filename has been provided.") result = {} urls_seen = set() with open(ref_path, 'r', encoding='utf...
[ "def", "read_references", "(", "reporter", ",", "ref_path", ")", ":", "if", "not", "ref_path", ":", "raise", "Warning", "(", "\"No filename has been provided.\"", ")", "result", "=", "{", "}", "urls_seen", "=", "set", "(", ")", "with", "open", "(", "ref_path...
[ 209, 0 ]
[ 252, 17 ]
python
en
['en', 'en', 'en']
True
read_all_markdown
(source_dir, parser)
Read source files, returning {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
Read source files, returning {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
def read_all_markdown(source_dir, parser): """Read source files, returning {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}} """ all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS] all_patterns = [os.path.join(d, '*.md') for d in all_dirs] ...
[ "def", "read_all_markdown", "(", "source_dir", ",", "parser", ")", ":", "all_dirs", "=", "[", "os", ".", "path", ".", "join", "(", "source_dir", ",", "d", ")", "for", "d", "in", "SOURCE_DIRS", "]", "all_patterns", "=", "[", "os", ".", "path", ".", "j...
[ 255, 0 ]
[ 268, 17 ]
python
en
['fr', 'en', 'en']
True
check_fileset
(source_dir, reporter, filenames_present)
Are all required files present? Are extraneous files present?
Are all required files present? Are extraneous files present?
def check_fileset(source_dir, reporter, filenames_present): """Are all required files present? Are extraneous files present?""" # Check files with predictable names. required = [os.path.join(source_dir, p) for p in REQUIRED_FILES] missing = set(required) - set(filenames_present) for m in missing: ...
[ "def", "check_fileset", "(", "source_dir", ",", "reporter", ",", "filenames_present", ")", ":", "# Check files with predictable names.", "required", "=", "[", "os", ".", "path", ".", "join", "(", "source_dir", ",", "p", ")", "for", "p", "in", "REQUIRED_FILES", ...
[ 271, 0 ]
[ 309, 24 ]
python
en
['en', 'en', 'en']
True
create_checker
(args, filename, info)
Create appropriate checker for file.
Create appropriate checker for file.
def create_checker(args, filename, info): """Create appropriate checker for file.""" for (pat, cls) in CHECKERS: if pat.search(filename): return cls(args, filename, **info) return NotImplemented
[ "def", "create_checker", "(", "args", ",", "filename", ",", "info", ")", ":", "for", "(", "pat", ",", "cls", ")", "in", "CHECKERS", ":", "if", "pat", ".", "search", "(", "filename", ")", ":", "return", "cls", "(", "args", ",", "filename", ",", "*",...
[ 312, 0 ]
[ 318, 25 ]
python
en
['en', 'it', 'en']
True
CheckBase.__init__
(self, args, filename, metadata, metadata_len, text, lines, doc)
Cache arguments for checking.
Cache arguments for checking.
def __init__(self, args, filename, metadata, metadata_len, text, lines, doc): """Cache arguments for checking.""" self.args = args self.reporter = self.args.reporter # for convenience self.filename = filename self.metadata = metadata self.metadata_len = metadata_len ...
[ "def", "__init__", "(", "self", ",", "args", ",", "filename", ",", "metadata", ",", "metadata_len", ",", "text", ",", "lines", ",", "doc", ")", ":", "self", ".", "args", "=", "args", "self", ".", "reporter", "=", "self", ".", "args", ".", "reporter",...
[ 323, 4 ]
[ 335, 26 ]
python
en
['en', 'en', 'en']
True
CheckBase.check_metadata
(self)
Check the YAML metadata.
Check the YAML metadata.
def check_metadata(self): """Check the YAML metadata.""" self.reporter.check(self.metadata is not None, self.filename, 'Missing metadata entirely') if self.metadata and (self.layout is not None): self.reporter.check_field( ...
[ "def", "check_metadata", "(", "self", ")", ":", "self", ".", "reporter", ".", "check", "(", "self", ".", "metadata", "is", "not", "None", ",", "self", ".", "filename", ",", "'Missing metadata entirely'", ")", "if", "self", ".", "metadata", "and", "(", "s...
[ 347, 4 ]
[ 356, 80 ]
python
en
['en', 'sn', 'en']
True
CheckBase.check_line_lengths
(self)
Check the raw text of the lesson body.
Check the raw text of the lesson body.
def check_line_lengths(self): """Check the raw text of the lesson body.""" if self.args.line_lengths: over = [i for (i, l, n) in self.lines if ( n > MAX_LINE_LEN) and (not l.startswith('!'))] self.reporter.check(not over, self.file...
[ "def", "check_line_lengths", "(", "self", ")", ":", "if", "self", ".", "args", ".", "line_lengths", ":", "over", "=", "[", "i", "for", "(", "i", ",", "l", ",", "n", ")", "in", "self", ".", "lines", "if", "(", "n", ">", "MAX_LINE_LEN", ")", "and",...
[ 358, 4 ]
[ 367, 66 ]
python
en
['en', 'en', 'en']
True
CheckBase.check_trailing_whitespace
(self)
Check for whitespace at the ends of lines.
Check for whitespace at the ends of lines.
def check_trailing_whitespace(self): """Check for whitespace at the ends of lines.""" if self.args.trailing_whitespace: trailing = [ i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)] self.reporter.check(not trailing, ...
[ "def", "check_trailing_whitespace", "(", "self", ")", ":", "if", "self", ".", "args", ".", "trailing_whitespace", ":", "trailing", "=", "[", "i", "for", "(", "i", ",", "l", ",", "n", ")", "in", "self", ".", "lines", "if", "P_TRAILING_WHITESPACE", ".", ...
[ 369, 4 ]
[ 378, 70 ]
python
en
['en', 'en', 'en']
True
CheckBase.check_blockquote_classes
(self)
Check that all blockquotes have known classes.
Check that all blockquotes have known classes.
def check_blockquote_classes(self): """Check that all blockquotes have known classes.""" for node in self.find_all(self.doc, {'type': 'blockquote'}): cls = self.get_val(node, 'attr', 'class') self.reporter.check(cls in KNOWN_BLOCKQUOTES, (self.fil...
[ "def", "check_blockquote_classes", "(", "self", ")", ":", "for", "node", "in", "self", ".", "find_all", "(", "self", ".", "doc", ",", "{", "'type'", ":", "'blockquote'", "}", ")", ":", "cls", "=", "self", ".", "get_val", "(", "node", ",", "'attr'", "...
[ 380, 4 ]
[ 388, 36 ]
python
en
['en', 'en', 'en']
True
CheckBase.check_codeblock_classes
(self)
Check that all code blocks have known classes.
Check that all code blocks have known classes.
def check_codeblock_classes(self): """Check that all code blocks have known classes.""" for node in self.find_all(self.doc, {'type': 'codeblock'}): cls = self.get_val(node, 'attr', 'class') self.reporter.check(cls in KNOWN_CODEBLOCKS, (self.filena...
[ "def", "check_codeblock_classes", "(", "self", ")", ":", "for", "node", "in", "self", ".", "find_all", "(", "self", ".", "doc", ",", "{", "'type'", ":", "'codeblock'", "}", ")", ":", "cls", "=", "self", ".", "get_val", "(", "node", ",", "'attr'", ","...
[ 390, 4 ]
[ 398, 36 ]
python
en
['en', 'en', 'en']
True
CheckBase.check_defined_link_references
(self)
Check that defined links resolve in the file. Internally-defined links match the pattern [text][label].
Check that defined links resolve in the file.
def check_defined_link_references(self): """Check that defined links resolve in the file. Internally-defined links match the pattern [text][label]. """ result = set() for node in self.find_all(self.doc, {'type': 'text'}): for match in P_INTERNAL_LINK_REF.findall(nod...
[ "def", "check_defined_link_references", "(", "self", ")", ":", "result", "=", "set", "(", ")", "for", "node", "in", "self", ".", "find_all", "(", "self", ".", "doc", ",", "{", "'type'", ":", "'text'", "}", ")", ":", "for", "match", "in", "P_INTERNAL_LI...
[ 400, 4 ]
[ 416, 54 ]
python
en
['en', 'en', 'en']
True
CheckBase.find_all
(self, node, pattern, accum=None)
Find all matches for a pattern.
Find all matches for a pattern.
def find_all(self, node, pattern, accum=None): """Find all matches for a pattern.""" assert isinstance(pattern, dict), 'Patterns must be dictionaries' if accum is None: accum = [] if self.match(node, pattern): accum.append(node) for child in node.get('chi...
[ "def", "find_all", "(", "self", ",", "node", ",", "pattern", ",", "accum", "=", "None", ")", ":", "assert", "isinstance", "(", "pattern", ",", "dict", ")", ",", "'Patterns must be dictionaries'", "if", "accum", "is", "None", ":", "accum", "=", "[", "]", ...
[ 418, 4 ]
[ 428, 20 ]
python
en
['en', 'en', 'en']
True
CheckBase.match
(self, node, pattern)
Does this node match the given pattern?
Does this node match the given pattern?
def match(self, node, pattern): """Does this node match the given pattern?""" for key in pattern: if key not in node: return False val = pattern[key] if isinstance(val, str): if node[key] != val: return False ...
[ "def", "match", "(", "self", ",", "node", ",", "pattern", ")", ":", "for", "key", "in", "pattern", ":", "if", "key", "not", "in", "node", ":", "return", "False", "val", "=", "pattern", "[", "key", "]", "if", "isinstance", "(", "val", ",", "str", ...
[ 430, 4 ]
[ 443, 19 ]
python
en
['en', 'en', 'en']
True
CheckBase.get_val
(node, *chain)
Get value one or more levels down.
Get value one or more levels down.
def get_val(node, *chain): """Get value one or more levels down.""" curr = node for selector in chain: curr = curr.get(selector, None) if curr is None: break return curr
[ "def", "get_val", "(", "node", ",", "*", "chain", ")", ":", "curr", "=", "node", "for", "selector", "in", "chain", ":", "curr", "=", "curr", ".", "get", "(", "selector", ",", "None", ")", "if", "curr", "is", "None", ":", "break", "return", "curr" ]
[ 446, 4 ]
[ 454, 19 ]
python
en
['en', 'en', 'en']
True
CheckBase.get_loc
(self, node)
Convenience method to get node's line number.
Convenience method to get node's line number.
def get_loc(self, node): """Convenience method to get node's line number.""" result = self.get_val(node, 'options', 'location') if self.metadata_len is not None: result += self.metadata_len return result
[ "def", "get_loc", "(", "self", ",", "node", ")", ":", "result", "=", "self", ".", "get_val", "(", "node", ",", "'options'", ",", "'location'", ")", "if", "self", ".", "metadata_len", "is", "not", "None", ":", "result", "+=", "self", ".", "metadata_len"...
[ 456, 4 ]
[ 462, 21 ]
python
en
['en', 'nl', 'en']
True
CheckEpisode.check
(self)
Run extra tests.
Run extra tests.
def check(self): """Run extra tests.""" super().check() self.check_reference_inclusion()
[ "def", "check", "(", "self", ")", ":", "super", "(", ")", ".", "check", "(", ")", "self", ".", "check_reference_inclusion", "(", ")" ]
[ 491, 4 ]
[ 495, 40 ]
python
en
['ca', 'en', 'en']
True
CheckEpisode.check_metadata_fields
(self, expected)
Check metadata fields.
Check metadata fields.
def check_metadata_fields(self, expected): """Check metadata fields.""" for (name, type_) in expected: if name not in self.metadata: self.reporter.add(self.filename, 'Missing metadata field {0}', name) ...
[ "def", "check_metadata_fields", "(", "self", ",", "expected", ")", ":", "for", "(", "name", ",", "type_", ")", "in", "expected", ":", "if", "name", "not", "in", "self", ".", "metadata", ":", "self", ".", "reporter", ".", "add", "(", "self", ".", "fil...
[ 510, 4 ]
[ 520, 73 ]
python
de
['id', 'de', 'en']
False
CheckEpisode.check_reference_inclusion
(self)
Check that links file has been included.
Check that links file has been included.
def check_reference_inclusion(self): """Check that links file has been included.""" if not self.args.reference_path: return for (i, last_line, line_len) in reversed(self.lines): if last_line: break require(last_line, 'No non-empt...
[ "def", "check_reference_inclusion", "(", "self", ")", ":", "if", "not", "self", ".", "args", ".", "reference_path", ":", "return", "for", "(", "i", ",", "last_line", ",", "line_len", ")", "in", "reversed", "(", "self", ".", "lines", ")", ":", "if", "la...
[ 522, 4 ]
[ 539, 47 ]
python
en
['en', 'en', 'en']
True
upload_inventory
(ansible_runner, nhosts=10, ini=False)
Helper to upload inventory script to target host
Helper to upload inventory script to target host
def upload_inventory(ansible_runner, nhosts=10, ini=False): """Helper to upload inventory script to target host""" # Create an inventory script if ini: copy_mode = '0644' copy_dest = '/tmp/inventory{}.ini'.format(random_title(non_ascii=False)) copy_content = ini_inventory(nhosts) ...
[ "def", "upload_inventory", "(", "ansible_runner", ",", "nhosts", "=", "10", ",", "ini", "=", "False", ")", ":", "# Create an inventory script", "if", "ini", ":", "copy_mode", "=", "'0644'", "copy_dest", "=", "'/tmp/inventory{}.ini'", ".", "format", "(", "random_...
[ 6, 0 ]
[ 27, 20 ]
python
en
['en', 'en', 'en']
True
generate_inventory
(nhosts=100)
Generate a somewhat complex inventory with a configurable number of hosts
Generate a somewhat complex inventory with a configurable number of hosts
def generate_inventory(nhosts=100): """Generate a somewhat complex inventory with a configurable number of hosts""" inv_list = { '_meta': { 'hostvars': {}, }, } for n in range(nhosts): hostname = 'host-%08d.example.com' % n group_evens_odds = 'evens.example.c...
[ "def", "generate_inventory", "(", "nhosts", "=", "100", ")", ":", "inv_list", "=", "{", "'_meta'", ":", "{", "'hostvars'", ":", "{", "}", ",", "}", ",", "}", "for", "n", "in", "range", "(", "nhosts", ")", ":", "hostname", "=", "'host-%08d.example.com'"...
[ 30, 0 ]
[ 74, 19 ]
python
en
['en', 'en', 'en']
True
json_inventory
(nhosts=10)
Return a JSON representation of inventory
Return a JSON representation of inventory
def json_inventory(nhosts=10): """Return a JSON representation of inventory""" return json.dumps(generate_inventory(nhosts), indent=4)
[ "def", "json_inventory", "(", "nhosts", "=", "10", ")", ":", "return", "json", ".", "dumps", "(", "generate_inventory", "(", "nhosts", ")", ",", "indent", "=", "4", ")" ]
[ 77, 0 ]
[ 79, 59 ]
python
en
['en', 'en', 'en']
True
ini_inventory
(nhosts=10)
Return a .INI representation of inventory
Return a .INI representation of inventory
def ini_inventory(nhosts=10): """Return a .INI representation of inventory""" output = list() inv_list = generate_inventory(nhosts) for group in inv_list.keys(): if group == '_meta': continue # output host groups output.append('[%s]' % group) for host in inv...
[ "def", "ini_inventory", "(", "nhosts", "=", "10", ")", ":", "output", "=", "list", "(", ")", "inv_list", "=", "generate_inventory", "(", "nhosts", ")", "for", "group", "in", "inv_list", ".", "keys", "(", ")", ":", "if", "group", "==", "'_meta'", ":", ...
[ 82, 0 ]
[ 109, 28 ]
python
en
['en', 'en', 'en']
True
colored
(text, color=None)
Colorize text w/ ANSI color sequences
Colorize text w/ ANSI color sequences
def colored(text, color=None): '''Colorize text w/ ANSI color sequences''' if _color.enabled and os.getenv('ANSI_COLORS_DISABLED') is None: fmt_str = '\033[%dm%s' if color is not None: text = fmt_str % (COLORS[color], text) text += '\033[0m' return text
[ "def", "colored", "(", "text", ",", "color", "=", "None", ")", ":", "if", "_color", ".", "enabled", "and", "os", ".", "getenv", "(", "'ANSI_COLORS_DISABLED'", ")", "is", "None", ":", "fmt_str", "=", "'\\033[%dm%s'", "if", "color", "is", "not", "None", ...
[ 78, 0 ]
[ 85, 15 ]
python
en
['en', 'fr', 'pl']
False