id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,900 | pypa/twine | twine/exceptions.py | UploadToDeprecatedPyPIDetected.from_args | def from_args(cls, target_url, default_url, test_url):
"""Return an UploadToDeprecatedPyPIDetected instance."""
return cls("You're trying to upload to the legacy PyPI site '{}'. "
"Uploading to those sites is deprecated. \n "
"The new sites are pypi.org and test.pypi.org. Try using "
"{} (or {}) to upload your packages instead. "
"These are the default URLs for Twine now. \n More at "
"https://packaging.python.org/guides/migrating-to-pypi-org/"
" .".format(target_url, default_url, test_url)
) | python | def from_args(cls, target_url, default_url, test_url):
return cls("You're trying to upload to the legacy PyPI site '{}'. "
"Uploading to those sites is deprecated. \n "
"The new sites are pypi.org and test.pypi.org. Try using "
"{} (or {}) to upload your packages instead. "
"These are the default URLs for Twine now. \n More at "
"https://packaging.python.org/guides/migrating-to-pypi-org/"
" .".format(target_url, default_url, test_url)
) | [
"def",
"from_args",
"(",
"cls",
",",
"target_url",
",",
"default_url",
",",
"test_url",
")",
":",
"return",
"cls",
"(",
"\"You're trying to upload to the legacy PyPI site '{}'. \"",
"\"Uploading to those sites is deprecated. \\n \"",
"\"The new sites are pypi.org and test.pypi.org.... | Return an UploadToDeprecatedPyPIDetected instance. | [
"Return",
"an",
"UploadToDeprecatedPyPIDetected",
"instance",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/exceptions.py#L51-L60 |
226,901 | pypa/twine | twine/utils.py | check_status_code | def check_status_code(response, verbose):
"""
Shouldn't happen, thanks to the UploadToDeprecatedPyPIDetected
exception, but this is in case that breaks and it does.
"""
if (response.status_code == 410 and
response.url.startswith(("https://pypi.python.org",
"https://testpypi.python.org"))):
print("It appears you're uploading to pypi.python.org (or "
"testpypi.python.org). You've received a 410 error response. "
"Uploading to those sites is deprecated. The new sites are "
"pypi.org and test.pypi.org. Try using "
"https://upload.pypi.org/legacy/ "
"(or https://test.pypi.org/legacy/) to upload your packages "
"instead. These are the default URLs for Twine now. More at "
"https://packaging.python.org/guides/migrating-to-pypi-org/ ")
try:
response.raise_for_status()
except HTTPError as err:
if response.text:
if verbose:
print('Content received from server:\n{}'.format(
response.text))
else:
print('NOTE: Try --verbose to see response content.')
raise err | python | def check_status_code(response, verbose):
if (response.status_code == 410 and
response.url.startswith(("https://pypi.python.org",
"https://testpypi.python.org"))):
print("It appears you're uploading to pypi.python.org (or "
"testpypi.python.org). You've received a 410 error response. "
"Uploading to those sites is deprecated. The new sites are "
"pypi.org and test.pypi.org. Try using "
"https://upload.pypi.org/legacy/ "
"(or https://test.pypi.org/legacy/) to upload your packages "
"instead. These are the default URLs for Twine now. More at "
"https://packaging.python.org/guides/migrating-to-pypi-org/ ")
try:
response.raise_for_status()
except HTTPError as err:
if response.text:
if verbose:
print('Content received from server:\n{}'.format(
response.text))
else:
print('NOTE: Try --verbose to see response content.')
raise err | [
"def",
"check_status_code",
"(",
"response",
",",
"verbose",
")",
":",
"if",
"(",
"response",
".",
"status_code",
"==",
"410",
"and",
"response",
".",
"url",
".",
"startswith",
"(",
"(",
"\"https://pypi.python.org\"",
",",
"\"https://testpypi.python.org\"",
")",
... | Shouldn't happen, thanks to the UploadToDeprecatedPyPIDetected
exception, but this is in case that breaks and it does. | [
"Shouldn",
"t",
"happen",
"thanks",
"to",
"the",
"UploadToDeprecatedPyPIDetected",
"exception",
"but",
"this",
"is",
"in",
"case",
"that",
"breaks",
"and",
"it",
"does",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/utils.py#L147-L172 |
226,902 | pypa/twine | twine/utils.py | no_positional | def no_positional(allow_self=False):
"""A decorator that doesn't allow for positional arguments.
:param bool allow_self:
Whether to allow ``self`` as a positional argument.
"""
def reject_positional_args(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
allowed_positional_args = 0
if allow_self:
allowed_positional_args = 1
received_positional_args = len(args)
if received_positional_args > allowed_positional_args:
function_name = function.__name__
verb = 'were' if received_positional_args > 1 else 'was'
raise TypeError(('{}() takes {} positional arguments but {} '
'{} given').format(
function_name,
allowed_positional_args,
received_positional_args,
verb,
))
return function(*args, **kwargs)
return wrapper
return reject_positional_args | python | def no_positional(allow_self=False):
def reject_positional_args(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
allowed_positional_args = 0
if allow_self:
allowed_positional_args = 1
received_positional_args = len(args)
if received_positional_args > allowed_positional_args:
function_name = function.__name__
verb = 'were' if received_positional_args > 1 else 'was'
raise TypeError(('{}() takes {} positional arguments but {} '
'{} given').format(
function_name,
allowed_positional_args,
received_positional_args,
verb,
))
return function(*args, **kwargs)
return wrapper
return reject_positional_args | [
"def",
"no_positional",
"(",
"allow_self",
"=",
"False",
")",
":",
"def",
"reject_positional_args",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | A decorator that doesn't allow for positional arguments.
:param bool allow_self:
Whether to allow ``self`` as a positional argument. | [
"A",
"decorator",
"that",
"doesn",
"t",
"allow",
"for",
"positional",
"arguments",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/utils.py#L308-L333 |
226,903 | pypa/twine | twine/wheel.py | Wheel.find_candidate_metadata_files | def find_candidate_metadata_files(names):
"""Filter files that may be METADATA files."""
tuples = [
x.split('/') for x in map(try_decode, names)
if 'METADATA' in x
]
return [x[1] for x in sorted([(len(x), x) for x in tuples])] | python | def find_candidate_metadata_files(names):
tuples = [
x.split('/') for x in map(try_decode, names)
if 'METADATA' in x
]
return [x[1] for x in sorted([(len(x), x) for x in tuples])] | [
"def",
"find_candidate_metadata_files",
"(",
"names",
")",
":",
"tuples",
"=",
"[",
"x",
".",
"split",
"(",
"'/'",
")",
"for",
"x",
"in",
"map",
"(",
"try_decode",
",",
"names",
")",
"if",
"'METADATA'",
"in",
"x",
"]",
"return",
"[",
"x",
"[",
"1",
... | Filter files that may be METADATA files. | [
"Filter",
"files",
"that",
"may",
"be",
"METADATA",
"files",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/wheel.py#L59-L65 |
226,904 | pypa/twine | twine/package.py | HashManager.hash | def hash(self):
"""Hash the file contents."""
with open(self.filename, "rb") as fp:
for content in iter(lambda: fp.read(io.DEFAULT_BUFFER_SIZE), b''):
self._md5_update(content)
self._sha2_update(content)
self._blake_update(content) | python | def hash(self):
with open(self.filename, "rb") as fp:
for content in iter(lambda: fp.read(io.DEFAULT_BUFFER_SIZE), b''):
self._md5_update(content)
self._sha2_update(content)
self._blake_update(content) | [
"def",
"hash",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"for",
"content",
"in",
"iter",
"(",
"lambda",
":",
"fp",
".",
"read",
"(",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
",",
"b''",
... | Hash the file contents. | [
"Hash",
"the",
"file",
"contents",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/package.py#L223-L229 |
226,905 | pypa/twine | twine/settings.py | Settings.register_argparse_arguments | def register_argparse_arguments(parser):
"""Register the arguments for argparse."""
parser.add_argument(
"-r", "--repository",
action=utils.EnvironmentDefault,
env="TWINE_REPOSITORY",
default="pypi",
help="The repository (package index) to upload the package to. "
"Should be a section in the config file (default: "
"%(default)s). (Can also be set via %(env)s environment "
"variable.)",
)
parser.add_argument(
"--repository-url",
action=utils.EnvironmentDefault,
env="TWINE_REPOSITORY_URL",
default=None,
required=False,
help="The repository (package index) URL to upload the package to."
" This overrides --repository. "
"(Can also be set via %(env)s environment variable.)"
)
parser.add_argument(
"-s", "--sign",
action="store_true",
default=False,
help="Sign files to upload using GPG.",
)
parser.add_argument(
"--sign-with",
default="gpg",
help="GPG program used to sign uploads (default: %(default)s).",
)
parser.add_argument(
"-i", "--identity",
help="GPG identity used to sign files.",
)
parser.add_argument(
"-u", "--username",
action=utils.EnvironmentDefault,
env="TWINE_USERNAME",
required=False,
help="The username to authenticate to the repository "
"(package index) as. (Can also be set via "
"%(env)s environment variable.)",
)
parser.add_argument(
"-p", "--password",
action=utils.EnvironmentDefault,
env="TWINE_PASSWORD",
required=False,
help="The password to authenticate to the repository "
"(package index) with. (Can also be set via "
"%(env)s environment variable.)",
)
parser.add_argument(
"-c", "--comment",
help="The comment to include with the distribution file.",
)
parser.add_argument(
"--config-file",
default="~/.pypirc",
help="The .pypirc config file to use.",
)
parser.add_argument(
"--skip-existing",
default=False,
action="store_true",
help="Continue uploading files if one already exists. (Only valid "
"when uploading to PyPI. Other implementations may not "
"support this.)",
)
parser.add_argument(
"--cert",
action=utils.EnvironmentDefault,
env="TWINE_CERT",
default=None,
required=False,
metavar="path",
help="Path to alternate CA bundle (can also be set via %(env)s "
"environment variable).",
)
parser.add_argument(
"--client-cert",
metavar="path",
help="Path to SSL client certificate, a single file containing the"
" private key and the certificate in PEM format.",
)
parser.add_argument(
"--verbose",
default=False,
required=False,
action="store_true",
help="Show verbose output."
)
parser.add_argument(
"--disable-progress-bar",
default=False,
required=False,
action="store_true",
help="Disable the progress bar."
) | python | def register_argparse_arguments(parser):
parser.add_argument(
"-r", "--repository",
action=utils.EnvironmentDefault,
env="TWINE_REPOSITORY",
default="pypi",
help="The repository (package index) to upload the package to. "
"Should be a section in the config file (default: "
"%(default)s). (Can also be set via %(env)s environment "
"variable.)",
)
parser.add_argument(
"--repository-url",
action=utils.EnvironmentDefault,
env="TWINE_REPOSITORY_URL",
default=None,
required=False,
help="The repository (package index) URL to upload the package to."
" This overrides --repository. "
"(Can also be set via %(env)s environment variable.)"
)
parser.add_argument(
"-s", "--sign",
action="store_true",
default=False,
help="Sign files to upload using GPG.",
)
parser.add_argument(
"--sign-with",
default="gpg",
help="GPG program used to sign uploads (default: %(default)s).",
)
parser.add_argument(
"-i", "--identity",
help="GPG identity used to sign files.",
)
parser.add_argument(
"-u", "--username",
action=utils.EnvironmentDefault,
env="TWINE_USERNAME",
required=False,
help="The username to authenticate to the repository "
"(package index) as. (Can also be set via "
"%(env)s environment variable.)",
)
parser.add_argument(
"-p", "--password",
action=utils.EnvironmentDefault,
env="TWINE_PASSWORD",
required=False,
help="The password to authenticate to the repository "
"(package index) with. (Can also be set via "
"%(env)s environment variable.)",
)
parser.add_argument(
"-c", "--comment",
help="The comment to include with the distribution file.",
)
parser.add_argument(
"--config-file",
default="~/.pypirc",
help="The .pypirc config file to use.",
)
parser.add_argument(
"--skip-existing",
default=False,
action="store_true",
help="Continue uploading files if one already exists. (Only valid "
"when uploading to PyPI. Other implementations may not "
"support this.)",
)
parser.add_argument(
"--cert",
action=utils.EnvironmentDefault,
env="TWINE_CERT",
default=None,
required=False,
metavar="path",
help="Path to alternate CA bundle (can also be set via %(env)s "
"environment variable).",
)
parser.add_argument(
"--client-cert",
metavar="path",
help="Path to SSL client certificate, a single file containing the"
" private key and the certificate in PEM format.",
)
parser.add_argument(
"--verbose",
default=False,
required=False,
action="store_true",
help="Show verbose output."
)
parser.add_argument(
"--disable-progress-bar",
default=False,
required=False,
action="store_true",
help="Disable the progress bar."
) | [
"def",
"register_argparse_arguments",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"\"-r\"",
",",
"\"--repository\"",
",",
"action",
"=",
"utils",
".",
"EnvironmentDefault",
",",
"env",
"=",
"\"TWINE_REPOSITORY\"",
",",
"default",
"=",
"\"pypi\"",
... | Register the arguments for argparse. | [
"Register",
"the",
"arguments",
"for",
"argparse",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/settings.py#L120-L221 |
226,906 | pypa/twine | twine/settings.py | Settings.from_argparse | def from_argparse(cls, args):
"""Generate the Settings from parsed arguments."""
settings = vars(args)
settings['repository_name'] = settings.pop('repository')
settings['cacert'] = settings.pop('cert')
return cls(**settings) | python | def from_argparse(cls, args):
settings = vars(args)
settings['repository_name'] = settings.pop('repository')
settings['cacert'] = settings.pop('cert')
return cls(**settings) | [
"def",
"from_argparse",
"(",
"cls",
",",
"args",
")",
":",
"settings",
"=",
"vars",
"(",
"args",
")",
"settings",
"[",
"'repository_name'",
"]",
"=",
"settings",
".",
"pop",
"(",
"'repository'",
")",
"settings",
"[",
"'cacert'",
"]",
"=",
"settings",
"."... | Generate the Settings from parsed arguments. | [
"Generate",
"the",
"Settings",
"from",
"parsed",
"arguments",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/settings.py#L224-L229 |
226,907 | pypa/twine | twine/settings.py | Settings.check_repository_url | def check_repository_url(self):
"""Verify we are not using legacy PyPI.
:raises:
:class:`~twine.exceptions.UploadToDeprecatedPyPIDetected`
"""
repository_url = self.repository_config['repository']
if repository_url.startswith((repository.LEGACY_PYPI,
repository.LEGACY_TEST_PYPI)):
raise exceptions.UploadToDeprecatedPyPIDetected.from_args(
repository_url,
utils.DEFAULT_REPOSITORY,
utils.TEST_REPOSITORY
) | python | def check_repository_url(self):
repository_url = self.repository_config['repository']
if repository_url.startswith((repository.LEGACY_PYPI,
repository.LEGACY_TEST_PYPI)):
raise exceptions.UploadToDeprecatedPyPIDetected.from_args(
repository_url,
utils.DEFAULT_REPOSITORY,
utils.TEST_REPOSITORY
) | [
"def",
"check_repository_url",
"(",
"self",
")",
":",
"repository_url",
"=",
"self",
".",
"repository_config",
"[",
"'repository'",
"]",
"if",
"repository_url",
".",
"startswith",
"(",
"(",
"repository",
".",
"LEGACY_PYPI",
",",
"repository",
".",
"LEGACY_TEST_PYP... | Verify we are not using legacy PyPI.
:raises:
:class:`~twine.exceptions.UploadToDeprecatedPyPIDetected` | [
"Verify",
"we",
"are",
"not",
"using",
"legacy",
"PyPI",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/settings.py#L270-L284 |
226,908 | pypa/twine | twine/settings.py | Settings.create_repository | def create_repository(self):
"""Create a new repository for uploading."""
repo = repository.Repository(
self.repository_config['repository'],
self.username,
self.password,
self.disable_progress_bar
)
repo.set_certificate_authority(self.cacert)
repo.set_client_certificate(self.client_cert)
return repo | python | def create_repository(self):
repo = repository.Repository(
self.repository_config['repository'],
self.username,
self.password,
self.disable_progress_bar
)
repo.set_certificate_authority(self.cacert)
repo.set_client_certificate(self.client_cert)
return repo | [
"def",
"create_repository",
"(",
"self",
")",
":",
"repo",
"=",
"repository",
".",
"Repository",
"(",
"self",
".",
"repository_config",
"[",
"'repository'",
"]",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
",",
"self",
".",
"disable_progress_... | Create a new repository for uploading. | [
"Create",
"a",
"new",
"repository",
"for",
"uploading",
"."
] | c854b2a7b451bf13878f709900261dbcbaf59ca0 | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/settings.py#L286-L296 |
226,909 | Gorialis/jishaku | jishaku/repl/__init__.py | get_var_dict_from_ctx | def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = '_'):
"""
Returns the dict to be used in REPL for a given Context.
"""
raw_var_dict = {
'author': ctx.author,
'bot': ctx.bot,
'channel': ctx.channel,
'ctx': ctx,
'find': discord.utils.find,
'get': discord.utils.get,
'guild': ctx.guild,
'message': ctx.message,
'msg': ctx.message
}
return {f'{prefix}{k}': v for k, v in raw_var_dict.items()} | python | def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = '_'):
raw_var_dict = {
'author': ctx.author,
'bot': ctx.bot,
'channel': ctx.channel,
'ctx': ctx,
'find': discord.utils.find,
'get': discord.utils.get,
'guild': ctx.guild,
'message': ctx.message,
'msg': ctx.message
}
return {f'{prefix}{k}': v for k, v in raw_var_dict.items()} | [
"def",
"get_var_dict_from_ctx",
"(",
"ctx",
":",
"commands",
".",
"Context",
",",
"prefix",
":",
"str",
"=",
"'_'",
")",
":",
"raw_var_dict",
"=",
"{",
"'author'",
":",
"ctx",
".",
"author",
",",
"'bot'",
":",
"ctx",
".",
"bot",
",",
"'channel'",
":",
... | Returns the dict to be used in REPL for a given Context. | [
"Returns",
"the",
"dict",
"to",
"be",
"used",
"in",
"REPL",
"for",
"a",
"given",
"Context",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/__init__.py#L23-L40 |
226,910 | Gorialis/jishaku | jishaku/shell.py | background_reader | def background_reader(stream, loop: asyncio.AbstractEventLoop, callback):
"""
Reads a stream and forwards each line to an async callback.
"""
for line in iter(stream.readline, b''):
loop.call_soon_threadsafe(loop.create_task, callback(line)) | python | def background_reader(stream, loop: asyncio.AbstractEventLoop, callback):
for line in iter(stream.readline, b''):
loop.call_soon_threadsafe(loop.create_task, callback(line)) | [
"def",
"background_reader",
"(",
"stream",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
",",
"callback",
")",
":",
"for",
"line",
"in",
"iter",
"(",
"stream",
".",
"readline",
",",
"b''",
")",
":",
"loop",
".",
"call_soon_threadsafe",
"(",
"loop"... | Reads a stream and forwards each line to an async callback. | [
"Reads",
"a",
"stream",
"and",
"forwards",
"each",
"line",
"to",
"an",
"async",
"callback",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/shell.py#L26-L32 |
226,911 | Gorialis/jishaku | jishaku/shell.py | ShellReader.make_reader_task | def make_reader_task(self, stream, callback):
"""
Create a reader executor task for a stream.
"""
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) | python | def make_reader_task(self, stream, callback):
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) | [
"def",
"make_reader_task",
"(",
"self",
",",
"stream",
",",
"callback",
")",
":",
"return",
"self",
".",
"loop",
".",
"create_task",
"(",
"self",
".",
"executor_wrapper",
"(",
"background_reader",
",",
"stream",
",",
"self",
".",
"loop",
",",
"callback",
"... | Create a reader executor task for a stream. | [
"Create",
"a",
"reader",
"executor",
"task",
"for",
"a",
"stream",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/shell.py#L83-L88 |
226,912 | Gorialis/jishaku | jishaku/shell.py | ShellReader.clean_bytes | def clean_bytes(line):
"""
Cleans a byte sequence of shell directives and decodes it.
"""
text = line.decode('utf-8').replace('\r', '').strip('\n')
return re.sub(r'\x1b[^m]*m', '', text).replace("``", "`\u200b`").strip('\n') | python | def clean_bytes(line):
text = line.decode('utf-8').replace('\r', '').strip('\n')
return re.sub(r'\x1b[^m]*m', '', text).replace("``", "`\u200b`").strip('\n') | [
"def",
"clean_bytes",
"(",
"line",
")",
":",
"text",
"=",
"line",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
".",
"strip",
"(",
"'\\n'",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\x1b[^m]*m'",
",",
"''",
",",
... | Cleans a byte sequence of shell directives and decodes it. | [
"Cleans",
"a",
"byte",
"sequence",
"of",
"shell",
"directives",
"and",
"decodes",
"it",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/shell.py#L91-L97 |
226,913 | Gorialis/jishaku | jishaku/shell.py | ShellReader.stderr_handler | async def stderr_handler(self, line):
"""
Handler for this class for stderr.
"""
await self.queue.put(self.clean_bytes(b'[stderr] ' + line)) | python | async def stderr_handler(self, line):
await self.queue.put(self.clean_bytes(b'[stderr] ' + line)) | [
"async",
"def",
"stderr_handler",
"(",
"self",
",",
"line",
")",
":",
"await",
"self",
".",
"queue",
".",
"put",
"(",
"self",
".",
"clean_bytes",
"(",
"b'[stderr] '",
"+",
"line",
")",
")"
] | Handler for this class for stderr. | [
"Handler",
"for",
"this",
"class",
"for",
"stderr",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/shell.py#L106-L111 |
226,914 | Gorialis/jishaku | jishaku/repl/compilation.py | wrap_code | def wrap_code(code: str, args: str = '') -> ast.Module:
"""
Compiles Python code into an async function or generator,
and automatically adds return if the function body is a single evaluation.
Also adds inline import expression support.
"""
if sys.version_info >= (3, 7):
user_code = import_expression.parse(code, mode='exec')
injected = ''
else:
injected = code
mod = import_expression.parse(CORO_CODE.format(args, textwrap.indent(injected, ' ' * 8)), mode='exec')
definition = mod.body[-1] # async def ...:
assert isinstance(definition, ast.AsyncFunctionDef)
try_block = definition.body[-1] # try:
assert isinstance(try_block, ast.Try)
if sys.version_info >= (3, 7):
try_block.body.extend(user_code.body)
else:
ast.increment_lineno(mod, -16) # bring line numbers back in sync with repl
ast.fix_missing_locations(mod)
is_asyncgen = any(isinstance(node, ast.Yield) for node in ast.walk(try_block))
last_expr = try_block.body[-1]
# if the last part isn't an expression, ignore it
if not isinstance(last_expr, ast.Expr):
return mod
# if the last expression is not a yield
if not isinstance(last_expr.value, ast.Yield):
# copy the expression into a return/yield
if is_asyncgen:
# copy the value of the expression into a yield
yield_stmt = ast.Yield(last_expr.value)
ast.copy_location(yield_stmt, last_expr)
# place the yield into its own expression
yield_expr = ast.Expr(yield_stmt)
ast.copy_location(yield_expr, last_expr)
# place the yield where the original expression was
try_block.body[-1] = yield_expr
else:
# copy the expression into a return
return_stmt = ast.Return(last_expr.value)
ast.copy_location(return_stmt, last_expr)
# place the return where the original expression was
try_block.body[-1] = return_stmt
return mod | python | def wrap_code(code: str, args: str = '') -> ast.Module:
if sys.version_info >= (3, 7):
user_code = import_expression.parse(code, mode='exec')
injected = ''
else:
injected = code
mod = import_expression.parse(CORO_CODE.format(args, textwrap.indent(injected, ' ' * 8)), mode='exec')
definition = mod.body[-1] # async def ...:
assert isinstance(definition, ast.AsyncFunctionDef)
try_block = definition.body[-1] # try:
assert isinstance(try_block, ast.Try)
if sys.version_info >= (3, 7):
try_block.body.extend(user_code.body)
else:
ast.increment_lineno(mod, -16) # bring line numbers back in sync with repl
ast.fix_missing_locations(mod)
is_asyncgen = any(isinstance(node, ast.Yield) for node in ast.walk(try_block))
last_expr = try_block.body[-1]
# if the last part isn't an expression, ignore it
if not isinstance(last_expr, ast.Expr):
return mod
# if the last expression is not a yield
if not isinstance(last_expr.value, ast.Yield):
# copy the expression into a return/yield
if is_asyncgen:
# copy the value of the expression into a yield
yield_stmt = ast.Yield(last_expr.value)
ast.copy_location(yield_stmt, last_expr)
# place the yield into its own expression
yield_expr = ast.Expr(yield_stmt)
ast.copy_location(yield_expr, last_expr)
# place the yield where the original expression was
try_block.body[-1] = yield_expr
else:
# copy the expression into a return
return_stmt = ast.Return(last_expr.value)
ast.copy_location(return_stmt, last_expr)
# place the return where the original expression was
try_block.body[-1] = return_stmt
return mod | [
"def",
"wrap_code",
"(",
"code",
":",
"str",
",",
"args",
":",
"str",
"=",
"''",
")",
"->",
"ast",
".",
"Module",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"7",
")",
":",
"user_code",
"=",
"import_expression",
".",
"parse",
"(",
... | Compiles Python code into an async function or generator,
and automatically adds return if the function body is a single evaluation.
Also adds inline import expression support. | [
"Compiles",
"Python",
"code",
"into",
"an",
"async",
"function",
"or",
"generator",
"and",
"automatically",
"adds",
"return",
"if",
"the",
"function",
"body",
"is",
"a",
"single",
"evaluation",
".",
"Also",
"adds",
"inline",
"import",
"expression",
"support",
... | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/compilation.py#L49-L106 |
226,915 | Gorialis/jishaku | jishaku/repl/compilation.py | AsyncCodeExecutor.traverse | async def traverse(self, func):
"""
Traverses an async function or generator, yielding each result.
This function is private. The class should be used as an iterator instead of using this method.
"""
# this allows the reference to be stolen
async_executor = self
if inspect.isasyncgenfunction(func):
async for result in func(*async_executor.args):
yield result
else:
yield await func(*async_executor.args) | python | async def traverse(self, func):
# this allows the reference to be stolen
async_executor = self
if inspect.isasyncgenfunction(func):
async for result in func(*async_executor.args):
yield result
else:
yield await func(*async_executor.args) | [
"async",
"def",
"traverse",
"(",
"self",
",",
"func",
")",
":",
"# this allows the reference to be stolen",
"async_executor",
"=",
"self",
"if",
"inspect",
".",
"isasyncgenfunction",
"(",
"func",
")",
":",
"async",
"for",
"result",
"in",
"func",
"(",
"*",
"asy... | Traverses an async function or generator, yielding each result.
This function is private. The class should be used as an iterator instead of using this method. | [
"Traverses",
"an",
"async",
"function",
"or",
"generator",
"yielding",
"each",
"result",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/compilation.py#L150-L164 |
226,916 | Gorialis/jishaku | jishaku/repl/scope.py | get_parent_scope_from_var | def get_parent_scope_from_var(name, global_ok=False, skip_frames=0) -> typing.Optional[Scope]:
"""
Iterates up the frame stack looking for a frame-scope containing the given variable name.
Returns
--------
Optional[Scope]
The relevant :class:`Scope` or None
"""
stack = inspect.stack()
try:
for frame_info in stack[skip_frames + 1:]:
frame = None
try:
frame = frame_info.frame
if name in frame.f_locals or (global_ok and name in frame.f_globals):
return Scope(globals_=frame.f_globals, locals_=frame.f_locals)
finally:
del frame
finally:
del stack
return None | python | def get_parent_scope_from_var(name, global_ok=False, skip_frames=0) -> typing.Optional[Scope]:
stack = inspect.stack()
try:
for frame_info in stack[skip_frames + 1:]:
frame = None
try:
frame = frame_info.frame
if name in frame.f_locals or (global_ok and name in frame.f_globals):
return Scope(globals_=frame.f_globals, locals_=frame.f_locals)
finally:
del frame
finally:
del stack
return None | [
"def",
"get_parent_scope_from_var",
"(",
"name",
",",
"global_ok",
"=",
"False",
",",
"skip_frames",
"=",
"0",
")",
"->",
"typing",
".",
"Optional",
"[",
"Scope",
"]",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"try",
":",
"for",
"frame_info",... | Iterates up the frame stack looking for a frame-scope containing the given variable name.
Returns
--------
Optional[Scope]
The relevant :class:`Scope` or None | [
"Iterates",
"up",
"the",
"frame",
"stack",
"looking",
"for",
"a",
"frame",
"-",
"scope",
"containing",
"the",
"given",
"variable",
"name",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/scope.py#L118-L143 |
226,917 | Gorialis/jishaku | jishaku/repl/scope.py | get_parent_var | def get_parent_var(name, global_ok=False, default=None, skip_frames=0):
"""
Directly gets a variable from a parent frame-scope.
Returns
--------
Any
The content of the variable found by the given name, or None.
"""
scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_frames=skip_frames + 1)
if not scope:
return default
if name in scope.locals:
return scope.locals.get(name, default)
return scope.globals.get(name, default) | python | def get_parent_var(name, global_ok=False, default=None, skip_frames=0):
scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_frames=skip_frames + 1)
if not scope:
return default
if name in scope.locals:
return scope.locals.get(name, default)
return scope.globals.get(name, default) | [
"def",
"get_parent_var",
"(",
"name",
",",
"global_ok",
"=",
"False",
",",
"default",
"=",
"None",
",",
"skip_frames",
"=",
"0",
")",
":",
"scope",
"=",
"get_parent_scope_from_var",
"(",
"name",
",",
"global_ok",
"=",
"global_ok",
",",
"skip_frames",
"=",
... | Directly gets a variable from a parent frame-scope.
Returns
--------
Any
The content of the variable found by the given name, or None. | [
"Directly",
"gets",
"a",
"variable",
"from",
"a",
"parent",
"frame",
"-",
"scope",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/scope.py#L146-L164 |
226,918 | Gorialis/jishaku | jishaku/repl/scope.py | Scope.clear_intersection | def clear_intersection(self, other_dict):
"""
Clears out locals and globals from this scope where the key-value pair matches
with other_dict.
This allows cleanup of temporary variables that may have washed up into this
Scope.
Arguments
---------
other_dict: a :class:`dict` to be used to determine scope clearance.
Returns
-------
Scope
The updated scope (self).
"""
for key, value in other_dict.items():
if key in self.globals and self.globals[key] is value:
del self.globals[key]
if key in self.locals and self.locals[key] is value:
del self.locals[key]
return self | python | def clear_intersection(self, other_dict):
for key, value in other_dict.items():
if key in self.globals and self.globals[key] is value:
del self.globals[key]
if key in self.locals and self.locals[key] is value:
del self.locals[key]
return self | [
"def",
"clear_intersection",
"(",
"self",
",",
"other_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"other_dict",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"globals",
"and",
"self",
".",
"globals",
"[",
"key",
"]",
"is",
"valu... | Clears out locals and globals from this scope where the key-value pair matches
with other_dict.
This allows cleanup of temporary variables that may have washed up into this
Scope.
Arguments
---------
other_dict: a :class:`dict` to be used to determine scope clearance.
Returns
-------
Scope
The updated scope (self). | [
"Clears",
"out",
"locals",
"and",
"globals",
"from",
"this",
"scope",
"where",
"the",
"key",
"-",
"value",
"pair",
"matches",
"with",
"other_dict",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/scope.py#L39-L63 |
226,919 | Gorialis/jishaku | jishaku/repl/scope.py | Scope.update | def update(self, other):
"""
Updates this scope with the content of another scope.
Arguments
---------
other: a :class:`Scope` instance.
Returns
-------
Scope
The updated scope (self).
"""
self.globals.update(other.globals)
self.locals.update(other.locals)
return self | python | def update(self, other):
self.globals.update(other.globals)
self.locals.update(other.locals)
return self | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"globals",
".",
"update",
"(",
"other",
".",
"globals",
")",
"self",
".",
"locals",
".",
"update",
"(",
"other",
".",
"locals",
")",
"return",
"self"
] | Updates this scope with the content of another scope.
Arguments
---------
other: a :class:`Scope` instance.
Returns
-------
Scope
The updated scope (self). | [
"Updates",
"this",
"scope",
"with",
"the",
"content",
"of",
"another",
"scope",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/scope.py#L65-L81 |
226,920 | Gorialis/jishaku | jishaku/exception_handling.py | send_traceback | async def send_traceback(destination: discord.abc.Messageable, verbosity: int, *exc_info):
"""
Sends a traceback of an exception to a destination.
Used when REPL fails for any reason.
:param destination: Where to send this information to
:param verbosity: How far back this traceback should go. 0 shows just the last stack.
:param exc_info: Information about this exception, from sys.exc_info or similar.
:return: The last message sent
"""
# to make pylint stop moaning
etype, value, trace = exc_info
traceback_content = "".join(traceback.format_exception(etype, value, trace, verbosity)).replace("``", "`\u200b`")
paginator = commands.Paginator(prefix='```py')
for line in traceback_content.split('\n'):
paginator.add_line(line)
message = None
for page in paginator.pages:
message = await destination.send(page)
return message | python | async def send_traceback(destination: discord.abc.Messageable, verbosity: int, *exc_info):
# to make pylint stop moaning
etype, value, trace = exc_info
traceback_content = "".join(traceback.format_exception(etype, value, trace, verbosity)).replace("``", "`\u200b`")
paginator = commands.Paginator(prefix='```py')
for line in traceback_content.split('\n'):
paginator.add_line(line)
message = None
for page in paginator.pages:
message = await destination.send(page)
return message | [
"async",
"def",
"send_traceback",
"(",
"destination",
":",
"discord",
".",
"abc",
".",
"Messageable",
",",
"verbosity",
":",
"int",
",",
"*",
"exc_info",
")",
":",
"# to make pylint stop moaning",
"etype",
",",
"value",
",",
"trace",
"=",
"exc_info",
"tracebac... | Sends a traceback of an exception to a destination.
Used when REPL fails for any reason.
:param destination: Where to send this information to
:param verbosity: How far back this traceback should go. 0 shows just the last stack.
:param exc_info: Information about this exception, from sys.exc_info or similar.
:return: The last message sent | [
"Sends",
"a",
"traceback",
"of",
"an",
"exception",
"to",
"a",
"destination",
".",
"Used",
"when",
"REPL",
"fails",
"for",
"any",
"reason",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/exception_handling.py#L23-L48 |
226,921 | Gorialis/jishaku | jishaku/exception_handling.py | do_after_sleep | async def do_after_sleep(delay: float, coro, *args, **kwargs):
"""
Performs an action after a set amount of time.
This function only calls the coroutine after the delay,
preventing asyncio complaints about destroyed coros.
:param delay: Time in seconds
:param coro: Coroutine to run
:param args: Arguments to pass to coroutine
:param kwargs: Keyword arguments to pass to coroutine
:return: Whatever the coroutine returned.
"""
await asyncio.sleep(delay)
return await coro(*args, **kwargs) | python | async def do_after_sleep(delay: float, coro, *args, **kwargs):
await asyncio.sleep(delay)
return await coro(*args, **kwargs) | [
"async",
"def",
"do_after_sleep",
"(",
"delay",
":",
"float",
",",
"coro",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"delay",
")",
"return",
"await",
"coro",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | Performs an action after a set amount of time.
This function only calls the coroutine after the delay,
preventing asyncio complaints about destroyed coros.
:param delay: Time in seconds
:param coro: Coroutine to run
:param args: Arguments to pass to coroutine
:param kwargs: Keyword arguments to pass to coroutine
:return: Whatever the coroutine returned. | [
"Performs",
"an",
"action",
"after",
"a",
"set",
"amount",
"of",
"time",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/exception_handling.py#L51-L65 |
226,922 | Gorialis/jishaku | jishaku/exception_handling.py | attempt_add_reaction | async def attempt_add_reaction(msg: discord.Message, reaction: typing.Union[str, discord.Emoji])\
-> typing.Optional[discord.Reaction]:
"""
Try to add a reaction to a message, ignoring it if it fails for any reason.
:param msg: The message to add the reaction to.
:param reaction: The reaction emoji, could be a string or `discord.Emoji`
:return: A `discord.Reaction` or None, depending on if it failed or not.
"""
try:
return await msg.add_reaction(reaction)
except discord.HTTPException:
pass | python | async def attempt_add_reaction(msg: discord.Message, reaction: typing.Union[str, discord.Emoji])\
-> typing.Optional[discord.Reaction]:
try:
return await msg.add_reaction(reaction)
except discord.HTTPException:
pass | [
"async",
"def",
"attempt_add_reaction",
"(",
"msg",
":",
"discord",
".",
"Message",
",",
"reaction",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"discord",
".",
"Emoji",
"]",
")",
"->",
"typing",
".",
"Optional",
"[",
"discord",
".",
"Reaction",
"]",
... | Try to add a reaction to a message, ignoring it if it fails for any reason.
:param msg: The message to add the reaction to.
:param reaction: The reaction emoji, could be a string or `discord.Emoji`
:return: A `discord.Reaction` or None, depending on if it failed or not. | [
"Try",
"to",
"add",
"a",
"reaction",
"to",
"a",
"message",
"ignoring",
"it",
"if",
"it",
"fails",
"for",
"any",
"reason",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/exception_handling.py#L68-L80 |
226,923 | Gorialis/jishaku | jishaku/repl/inspections.py | add_inspection | def add_inspection(name):
"""
Add a Jishaku object inspection
"""
# create the real decorator
def inspection_inner(func):
"""
Jishaku inspection decorator
"""
# pylint: disable=inconsistent-return-statements
# create an encapsulated version of the inspection that swallows exceptions
@functools.wraps(func)
def encapsulated(*args, **kwargs):
try:
return func(*args, **kwargs)
except (TypeError, AttributeError, ValueError, OSError):
return
INSPECTIONS.append((name, encapsulated))
return func
return inspection_inner | python | def add_inspection(name):
# create the real decorator
def inspection_inner(func):
"""
Jishaku inspection decorator
"""
# pylint: disable=inconsistent-return-statements
# create an encapsulated version of the inspection that swallows exceptions
@functools.wraps(func)
def encapsulated(*args, **kwargs):
try:
return func(*args, **kwargs)
except (TypeError, AttributeError, ValueError, OSError):
return
INSPECTIONS.append((name, encapsulated))
return func
return inspection_inner | [
"def",
"add_inspection",
"(",
"name",
")",
":",
"# create the real decorator",
"def",
"inspection_inner",
"(",
"func",
")",
":",
"\"\"\"\n Jishaku inspection decorator\n \"\"\"",
"# pylint: disable=inconsistent-return-statements",
"# create an encapsulated version of the ... | Add a Jishaku object inspection | [
"Add",
"a",
"Jishaku",
"object",
"inspection"
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/inspections.py#L22-L45 |
226,924 | Gorialis/jishaku | jishaku/repl/inspections.py | all_inspections | def all_inspections(obj):
"""
Generator to iterate all current Jishaku inspections.
"""
for name, callback in INSPECTIONS:
result = callback(obj)
if result:
yield name, result | python | def all_inspections(obj):
for name, callback in INSPECTIONS:
result = callback(obj)
if result:
yield name, result | [
"def",
"all_inspections",
"(",
"obj",
")",
":",
"for",
"name",
",",
"callback",
"in",
"INSPECTIONS",
":",
"result",
"=",
"callback",
"(",
"obj",
")",
"if",
"result",
":",
"yield",
"name",
",",
"result"
] | Generator to iterate all current Jishaku inspections. | [
"Generator",
"to",
"iterate",
"all",
"current",
"Jishaku",
"inspections",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/inspections.py#L48-L56 |
226,925 | Gorialis/jishaku | jishaku/repl/inspections.py | class_name | def class_name(obj):
"""
Get the name of an object, including the module name if available.
"""
name = obj.__name__
module = getattr(obj, '__module__')
if module:
name = f'{module}.{name}'
return name | python | def class_name(obj):
name = obj.__name__
module = getattr(obj, '__module__')
if module:
name = f'{module}.{name}'
return name | [
"def",
"class_name",
"(",
"obj",
")",
":",
"name",
"=",
"obj",
".",
"__name__",
"module",
"=",
"getattr",
"(",
"obj",
",",
"'__module__'",
")",
"if",
"module",
":",
"name",
"=",
"f'{module}.{name}'",
"return",
"name"
] | Get the name of an object, including the module name if available. | [
"Get",
"the",
"name",
"of",
"an",
"object",
"including",
"the",
"module",
"name",
"if",
"available",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/inspections.py#L59-L69 |
226,926 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.pages | def pages(self):
"""
Returns the paginator's pages without prematurely closing the active page.
"""
# protected access has to be permitted here to not close the paginator's pages
# pylint: disable=protected-access
paginator_pages = list(self.paginator._pages)
if len(self.paginator._current_page) > 1:
paginator_pages.append('\n'.join(self.paginator._current_page) + '\n' + (self.paginator.suffix or ''))
# pylint: enable=protected-access
return paginator_pages | python | def pages(self):
# protected access has to be permitted here to not close the paginator's pages
# pylint: disable=protected-access
paginator_pages = list(self.paginator._pages)
if len(self.paginator._current_page) > 1:
paginator_pages.append('\n'.join(self.paginator._current_page) + '\n' + (self.paginator.suffix or ''))
# pylint: enable=protected-access
return paginator_pages | [
"def",
"pages",
"(",
"self",
")",
":",
"# protected access has to be permitted here to not close the paginator's pages",
"# pylint: disable=protected-access",
"paginator_pages",
"=",
"list",
"(",
"self",
".",
"paginator",
".",
"_pages",
")",
"if",
"len",
"(",
"self",
".",... | Returns the paginator's pages without prematurely closing the active page. | [
"Returns",
"the",
"paginator",
"s",
"pages",
"without",
"prematurely",
"closing",
"the",
"active",
"page",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L72-L84 |
226,927 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.display_page | def display_page(self):
"""
Returns the current page the paginator interface is on.
"""
self._display_page = max(0, min(self.page_count - 1, self._display_page))
return self._display_page | python | def display_page(self):
self._display_page = max(0, min(self.page_count - 1, self._display_page))
return self._display_page | [
"def",
"display_page",
"(",
"self",
")",
":",
"self",
".",
"_display_page",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"self",
".",
"page_count",
"-",
"1",
",",
"self",
".",
"_display_page",
")",
")",
"return",
"self",
".",
"_display_page"
] | Returns the current page the paginator interface is on. | [
"Returns",
"the",
"current",
"page",
"the",
"paginator",
"interface",
"is",
"on",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L95-L101 |
226,928 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.display_page | def display_page(self, value):
"""
Sets the current page the paginator is on. Automatically pushes values inbounds.
"""
self._display_page = max(0, min(self.page_count - 1, value)) | python | def display_page(self, value):
self._display_page = max(0, min(self.page_count - 1, value)) | [
"def",
"display_page",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_display_page",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"self",
".",
"page_count",
"-",
"1",
",",
"value",
")",
")"
] | Sets the current page the paginator is on. Automatically pushes values inbounds. | [
"Sets",
"the",
"current",
"page",
"the",
"paginator",
"is",
"on",
".",
"Automatically",
"pushes",
"values",
"inbounds",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L104-L109 |
226,929 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.page_size | def page_size(self) -> int:
"""
A property that returns how large a page is, calculated from the paginator properties.
If this exceeds `max_page_size`, an exception is raised upon instantiation.
"""
page_count = self.page_count
return self.paginator.max_size + len(f'\nPage {page_count}/{page_count}') | python | def page_size(self) -> int:
page_count = self.page_count
return self.paginator.max_size + len(f'\nPage {page_count}/{page_count}') | [
"def",
"page_size",
"(",
"self",
")",
"->",
"int",
":",
"page_count",
"=",
"self",
".",
"page_count",
"return",
"self",
".",
"paginator",
".",
"max_size",
"+",
"len",
"(",
"f'\\nPage {page_count}/{page_count}'",
")"
] | A property that returns how large a page is, calculated from the paginator properties.
If this exceeds `max_page_size`, an exception is raised upon instantiation. | [
"A",
"property",
"that",
"returns",
"how",
"large",
"a",
"page",
"is",
"calculated",
"from",
"the",
"paginator",
"properties",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L114-L121 |
226,930 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.add_line | async def add_line(self, *args, **kwargs):
"""
A proxy function that allows this PaginatorInterface to remain locked to the last page
if it is already on it.
"""
display_page = self.display_page
page_count = self.page_count
self.paginator.add_line(*args, **kwargs)
new_page_count = self.page_count
if display_page + 1 == page_count:
# To keep position fixed on the end, update position to new last page and update message.
self._display_page = new_page_count
self.bot.loop.create_task(self.update()) | python | async def add_line(self, *args, **kwargs):
display_page = self.display_page
page_count = self.page_count
self.paginator.add_line(*args, **kwargs)
new_page_count = self.page_count
if display_page + 1 == page_count:
# To keep position fixed on the end, update position to new last page and update message.
self._display_page = new_page_count
self.bot.loop.create_task(self.update()) | [
"async",
"def",
"add_line",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"display_page",
"=",
"self",
".",
"display_page",
"page_count",
"=",
"self",
".",
"page_count",
"self",
".",
"paginator",
".",
"add_line",
"(",
"*",
"args",
"... | A proxy function that allows this PaginatorInterface to remain locked to the last page
if it is already on it. | [
"A",
"proxy",
"function",
"that",
"allows",
"this",
"PaginatorInterface",
"to",
"remain",
"locked",
"to",
"the",
"last",
"page",
"if",
"it",
"is",
"already",
"on",
"it",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L137-L153 |
226,931 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.send_to | async def send_to(self, destination: discord.abc.Messageable):
"""
Sends a message to the given destination with this interface.
This automatically creates the response task for you.
"""
self.message = await destination.send(**self.send_kwargs)
# add the close reaction
await self.message.add_reaction(self.emojis.close)
# if there is more than one page, and the reactions haven't been sent yet, send navigation emotes
if not self.sent_page_reactions and self.page_count > 1:
await self.send_all_reactions()
if self.task:
self.task.cancel()
self.task = self.bot.loop.create_task(self.wait_loop()) | python | async def send_to(self, destination: discord.abc.Messageable):
self.message = await destination.send(**self.send_kwargs)
# add the close reaction
await self.message.add_reaction(self.emojis.close)
# if there is more than one page, and the reactions haven't been sent yet, send navigation emotes
if not self.sent_page_reactions and self.page_count > 1:
await self.send_all_reactions()
if self.task:
self.task.cancel()
self.task = self.bot.loop.create_task(self.wait_loop()) | [
"async",
"def",
"send_to",
"(",
"self",
",",
"destination",
":",
"discord",
".",
"abc",
".",
"Messageable",
")",
":",
"self",
".",
"message",
"=",
"await",
"destination",
".",
"send",
"(",
"*",
"*",
"self",
".",
"send_kwargs",
")",
"# add the close reactio... | Sends a message to the given destination with this interface.
This automatically creates the response task for you. | [
"Sends",
"a",
"message",
"to",
"the",
"given",
"destination",
"with",
"this",
"interface",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L155-L174 |
226,932 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.send_all_reactions | async def send_all_reactions(self):
"""
Sends all reactions for this paginator, if any are missing.
This method is generally for internal use only.
"""
for emoji in filter(None, self.emojis):
await self.message.add_reaction(emoji)
self.sent_page_reactions = True | python | async def send_all_reactions(self):
for emoji in filter(None, self.emojis):
await self.message.add_reaction(emoji)
self.sent_page_reactions = True | [
"async",
"def",
"send_all_reactions",
"(",
"self",
")",
":",
"for",
"emoji",
"in",
"filter",
"(",
"None",
",",
"self",
".",
"emojis",
")",
":",
"await",
"self",
".",
"message",
".",
"add_reaction",
"(",
"emoji",
")",
"self",
".",
"sent_page_reactions",
"... | Sends all reactions for this paginator, if any are missing.
This method is generally for internal use only. | [
"Sends",
"all",
"reactions",
"for",
"this",
"paginator",
"if",
"any",
"are",
"missing",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L176-L185 |
226,933 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.wait_loop | async def wait_loop(self):
"""
Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`.
"""
start, back, forward, end, close = self.emojis
def check(payload: discord.RawReactionActionEvent):
"""
Checks if this reaction is related to the paginator interface.
"""
owner_check = not self.owner or payload.user_id == self.owner.id
emoji = payload.emoji
if isinstance(emoji, discord.PartialEmoji) and emoji.is_unicode_emoji():
emoji = emoji.name
return payload.message_id == self.message.id and \
emoji and emoji in self.emojis and \
payload.user_id != self.bot.user.id and owner_check
try:
while not self.bot.is_closed():
payload = await self.bot.wait_for('raw_reaction_add', check=check, timeout=self.timeout)
emoji = payload.emoji
if isinstance(emoji, discord.PartialEmoji) and emoji.is_unicode_emoji():
emoji = emoji.name
if emoji == close:
await self.message.delete()
return
if emoji == start:
self._display_page = 0
elif emoji == end:
self._display_page = self.page_count - 1
elif emoji == back:
self._display_page -= 1
elif emoji == forward:
self._display_page += 1
self.bot.loop.create_task(self.update())
try:
await self.message.remove_reaction(payload.emoji, discord.Object(id=payload.user_id))
except discord.Forbidden:
pass
except asyncio.TimeoutError:
if self.delete_message:
return await self.message.delete()
for emoji in filter(None, self.emojis):
try:
await self.message.remove_reaction(emoji, self.message.guild.me)
except (discord.Forbidden, discord.NotFound):
pass | python | async def wait_loop(self):
start, back, forward, end, close = self.emojis
def check(payload: discord.RawReactionActionEvent):
"""
Checks if this reaction is related to the paginator interface.
"""
owner_check = not self.owner or payload.user_id == self.owner.id
emoji = payload.emoji
if isinstance(emoji, discord.PartialEmoji) and emoji.is_unicode_emoji():
emoji = emoji.name
return payload.message_id == self.message.id and \
emoji and emoji in self.emojis and \
payload.user_id != self.bot.user.id and owner_check
try:
while not self.bot.is_closed():
payload = await self.bot.wait_for('raw_reaction_add', check=check, timeout=self.timeout)
emoji = payload.emoji
if isinstance(emoji, discord.PartialEmoji) and emoji.is_unicode_emoji():
emoji = emoji.name
if emoji == close:
await self.message.delete()
return
if emoji == start:
self._display_page = 0
elif emoji == end:
self._display_page = self.page_count - 1
elif emoji == back:
self._display_page -= 1
elif emoji == forward:
self._display_page += 1
self.bot.loop.create_task(self.update())
try:
await self.message.remove_reaction(payload.emoji, discord.Object(id=payload.user_id))
except discord.Forbidden:
pass
except asyncio.TimeoutError:
if self.delete_message:
return await self.message.delete()
for emoji in filter(None, self.emojis):
try:
await self.message.remove_reaction(emoji, self.message.guild.me)
except (discord.Forbidden, discord.NotFound):
pass | [
"async",
"def",
"wait_loop",
"(",
"self",
")",
":",
"start",
",",
"back",
",",
"forward",
",",
"end",
",",
"close",
"=",
"self",
".",
"emojis",
"def",
"check",
"(",
"payload",
":",
"discord",
".",
"RawReactionActionEvent",
")",
":",
"\"\"\"\n Ch... | Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`. | [
"Waits",
"on",
"a",
"loop",
"for",
"reactions",
"to",
"the",
"message",
".",
"This",
"should",
"not",
"be",
"called",
"manually",
"-",
"it",
"is",
"handled",
"by",
"send_to",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L197-L255 |
226,934 | Gorialis/jishaku | jishaku/paginators.py | PaginatorInterface.update | async def update(self):
"""
Updates this interface's messages with the latest data.
"""
if self.update_lock.locked():
return
async with self.update_lock:
if self.update_lock.locked():
# if this engagement has caused the semaphore to exhaust,
# we are overloaded and need to calm down.
await asyncio.sleep(1)
if not self.message:
# too fast, stagger so this update gets through
await asyncio.sleep(0.5)
if not self.sent_page_reactions and self.page_count > 1:
self.bot.loop.create_task(self.send_all_reactions())
self.sent_page_reactions = True # don't spawn any more tasks
await self.message.edit(**self.send_kwargs) | python | async def update(self):
if self.update_lock.locked():
return
async with self.update_lock:
if self.update_lock.locked():
# if this engagement has caused the semaphore to exhaust,
# we are overloaded and need to calm down.
await asyncio.sleep(1)
if not self.message:
# too fast, stagger so this update gets through
await asyncio.sleep(0.5)
if not self.sent_page_reactions and self.page_count > 1:
self.bot.loop.create_task(self.send_all_reactions())
self.sent_page_reactions = True # don't spawn any more tasks
await self.message.edit(**self.send_kwargs) | [
"async",
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"update_lock",
".",
"locked",
"(",
")",
":",
"return",
"async",
"with",
"self",
".",
"update_lock",
":",
"if",
"self",
".",
"update_lock",
".",
"locked",
"(",
")",
":",
"# if this enga... | Updates this interface's messages with the latest data. | [
"Updates",
"this",
"interface",
"s",
"messages",
"with",
"the",
"latest",
"data",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L257-L279 |
226,935 | Gorialis/jishaku | jishaku/cog.py | Jishaku.submit | def submit(self, ctx: commands.Context):
"""
A context-manager that submits the current task to jishaku's task list
and removes it afterwards.
Arguments
---------
ctx: commands.Context
A Context object used to derive information about this command task.
"""
self.task_count += 1
cmdtask = CommandTask(self.task_count, ctx, asyncio.Task.current_task())
self.tasks.append(cmdtask)
try:
yield cmdtask
finally:
if cmdtask in self.tasks:
self.tasks.remove(cmdtask) | python | def submit(self, ctx: commands.Context):
self.task_count += 1
cmdtask = CommandTask(self.task_count, ctx, asyncio.Task.current_task())
self.tasks.append(cmdtask)
try:
yield cmdtask
finally:
if cmdtask in self.tasks:
self.tasks.remove(cmdtask) | [
"def",
"submit",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"self",
".",
"task_count",
"+=",
"1",
"cmdtask",
"=",
"CommandTask",
"(",
"self",
".",
"task_count",
",",
"ctx",
",",
"asyncio",
".",
"Task",
".",
"current_task",
"(",... | A context-manager that submits the current task to jishaku's task list
and removes it afterwards.
Arguments
---------
ctx: commands.Context
A Context object used to derive information about this command task. | [
"A",
"context",
"-",
"manager",
"that",
"submits",
"the",
"current",
"task",
"to",
"jishaku",
"s",
"task",
"list",
"and",
"removes",
"it",
"afterwards",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L95-L114 |
226,936 | Gorialis/jishaku | jishaku/cog.py | Jishaku.cog_check | async def cog_check(self, ctx: commands.Context):
"""
Local check, makes all commands in this cog owner-only
"""
if not await ctx.bot.is_owner(ctx.author):
raise commands.NotOwner("You must own this bot to use Jishaku.")
return True | python | async def cog_check(self, ctx: commands.Context):
if not await ctx.bot.is_owner(ctx.author):
raise commands.NotOwner("You must own this bot to use Jishaku.")
return True | [
"async",
"def",
"cog_check",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"if",
"not",
"await",
"ctx",
".",
"bot",
".",
"is_owner",
"(",
"ctx",
".",
"author",
")",
":",
"raise",
"commands",
".",
"NotOwner",
"(",
"\"You must own t... | Local check, makes all commands in this cog owner-only | [
"Local",
"check",
"makes",
"all",
"commands",
"in",
"this",
"cog",
"owner",
"-",
"only"
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L116-L123 |
226,937 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk | async def jsk(self, ctx: commands.Context):
"""
The Jishaku debug and diagnostic commands.
This command on its own gives a status brief.
All other functionality is within its subcommands.
"""
summary = [
f"Jishaku v{__version__}, discord.py `{package_version('discord.py')}`, "
f"`Python {sys.version}` on `{sys.platform}`".replace("\n", ""),
f"Module was loaded {humanize.naturaltime(self.load_time)}, "
f"cog was loaded {humanize.naturaltime(self.start_time)}.",
""
]
if psutil:
proc = psutil.Process()
with proc.oneshot():
mem = proc.memory_full_info()
summary.append(f"Using {humanize.naturalsize(mem.rss)} physical memory and "
f"{humanize.naturalsize(mem.vms)} virtual memory, "
f"{humanize.naturalsize(mem.uss)} of which unique to this process.")
name = proc.name()
pid = proc.pid
thread_count = proc.num_threads()
summary.append(f"Running on PID {pid} (`{name}`) with {thread_count} thread(s).")
summary.append("") # blank line
cache_summary = f"{len(self.bot.guilds)} guild(s) and {len(self.bot.users)} user(s)"
if isinstance(self.bot, discord.AutoShardedClient):
summary.append(f"This bot is automatically sharded and can see {cache_summary}.")
elif self.bot.shard_count:
summary.append(f"This bot is manually sharded and can see {cache_summary}.")
else:
summary.append(f"This bot is not sharded and can see {cache_summary}.")
summary.append(f"Average websocket latency: {round(self.bot.latency * 1000, 2)}ms")
await ctx.send("\n".join(summary)) | python | async def jsk(self, ctx: commands.Context):
summary = [
f"Jishaku v{__version__}, discord.py `{package_version('discord.py')}`, "
f"`Python {sys.version}` on `{sys.platform}`".replace("\n", ""),
f"Module was loaded {humanize.naturaltime(self.load_time)}, "
f"cog was loaded {humanize.naturaltime(self.start_time)}.",
""
]
if psutil:
proc = psutil.Process()
with proc.oneshot():
mem = proc.memory_full_info()
summary.append(f"Using {humanize.naturalsize(mem.rss)} physical memory and "
f"{humanize.naturalsize(mem.vms)} virtual memory, "
f"{humanize.naturalsize(mem.uss)} of which unique to this process.")
name = proc.name()
pid = proc.pid
thread_count = proc.num_threads()
summary.append(f"Running on PID {pid} (`{name}`) with {thread_count} thread(s).")
summary.append("") # blank line
cache_summary = f"{len(self.bot.guilds)} guild(s) and {len(self.bot.users)} user(s)"
if isinstance(self.bot, discord.AutoShardedClient):
summary.append(f"This bot is automatically sharded and can see {cache_summary}.")
elif self.bot.shard_count:
summary.append(f"This bot is manually sharded and can see {cache_summary}.")
else:
summary.append(f"This bot is not sharded and can see {cache_summary}.")
summary.append(f"Average websocket latency: {round(self.bot.latency * 1000, 2)}ms")
await ctx.send("\n".join(summary)) | [
"async",
"def",
"jsk",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"summary",
"=",
"[",
"f\"Jishaku v{__version__}, discord.py `{package_version('discord.py')}`, \"",
"f\"`Python {sys.version}` on `{sys.platform}`\"",
".",
"replace",
"(",
"\"\\n\"",
... | The Jishaku debug and diagnostic commands.
This command on its own gives a status brief.
All other functionality is within its subcommands. | [
"The",
"Jishaku",
"debug",
"and",
"diagnostic",
"commands",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L127-L171 |
226,938 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_hide | async def jsk_hide(self, ctx: commands.Context):
"""
Hides Jishaku from the help command.
"""
if self.jsk.hidden:
return await ctx.send("Jishaku is already hidden.")
self.jsk.hidden = True
await ctx.send("Jishaku is now hidden.") | python | async def jsk_hide(self, ctx: commands.Context):
if self.jsk.hidden:
return await ctx.send("Jishaku is already hidden.")
self.jsk.hidden = True
await ctx.send("Jishaku is now hidden.") | [
"async",
"def",
"jsk_hide",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"if",
"self",
".",
"jsk",
".",
"hidden",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"Jishaku is already hidden.\"",
")",
"self",
".",
"jsk",
".",
"h... | Hides Jishaku from the help command. | [
"Hides",
"Jishaku",
"from",
"the",
"help",
"command",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L175-L184 |
226,939 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_show | async def jsk_show(self, ctx: commands.Context):
"""
Shows Jishaku in the help command.
"""
if not self.jsk.hidden:
return await ctx.send("Jishaku is already visible.")
self.jsk.hidden = False
await ctx.send("Jishaku is now visible.") | python | async def jsk_show(self, ctx: commands.Context):
if not self.jsk.hidden:
return await ctx.send("Jishaku is already visible.")
self.jsk.hidden = False
await ctx.send("Jishaku is now visible.") | [
"async",
"def",
"jsk_show",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"if",
"not",
"self",
".",
"jsk",
".",
"hidden",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"Jishaku is already visible.\"",
")",
"self",
".",
"jsk",
... | Shows Jishaku in the help command. | [
"Shows",
"Jishaku",
"in",
"the",
"help",
"command",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L187-L196 |
226,940 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_tasks | async def jsk_tasks(self, ctx: commands.Context):
"""
Shows the currently running jishaku tasks.
"""
if not self.tasks:
return await ctx.send("No currently running tasks.")
paginator = commands.Paginator(max_size=1985)
for task in self.tasks:
paginator.add_line(f"{task.index}: `{task.ctx.command.qualified_name}`, invoked at "
f"{task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | python | async def jsk_tasks(self, ctx: commands.Context):
if not self.tasks:
return await ctx.send("No currently running tasks.")
paginator = commands.Paginator(max_size=1985)
for task in self.tasks:
paginator.add_line(f"{task.index}: `{task.ctx.command.qualified_name}`, invoked at "
f"{task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | [
"async",
"def",
"jsk_tasks",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"No currently running tasks.\"",
")",
"paginator",
"=",
"commands",
".",
... | Shows the currently running jishaku tasks. | [
"Shows",
"the",
"currently",
"running",
"jishaku",
"tasks",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L199-L214 |
226,941 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_cancel | async def jsk_cancel(self, ctx: commands.Context, *, index: int):
"""
Cancels a task with the given index.
If the index passed is -1, will cancel the last task instead.
"""
if not self.tasks:
return await ctx.send("No tasks to cancel.")
if index == -1:
task = self.tasks.pop()
else:
task = discord.utils.get(self.tasks, index=index)
if task:
self.tasks.remove(task)
else:
return await ctx.send("Unknown task.")
task.task.cancel()
return await ctx.send(f"Cancelled task {task.index}: `{task.ctx.command.qualified_name}`,"
f" invoked at {task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC") | python | async def jsk_cancel(self, ctx: commands.Context, *, index: int):
if not self.tasks:
return await ctx.send("No tasks to cancel.")
if index == -1:
task = self.tasks.pop()
else:
task = discord.utils.get(self.tasks, index=index)
if task:
self.tasks.remove(task)
else:
return await ctx.send("Unknown task.")
task.task.cancel()
return await ctx.send(f"Cancelled task {task.index}: `{task.ctx.command.qualified_name}`,"
f" invoked at {task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC") | [
"async",
"def",
"jsk_cancel",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"index",
":",
"int",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"No tasks to cancel.\"",
")",
... | Cancels a task with the given index.
If the index passed is -1, will cancel the last task instead. | [
"Cancels",
"a",
"task",
"with",
"the",
"given",
"index",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L217-L238 |
226,942 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_load | async def jsk_load(self, ctx: commands.Context, *extensions: ExtensionConverter):
"""
Loads or reloads the given extension names.
Reports any extensions that failed to load.
"""
paginator = commands.Paginator(prefix='', suffix='')
for extension in itertools.chain(*extensions):
method, icon = (
(self.bot.reload_extension, "\N{CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS}")
if extension in self.bot.extensions else
(self.bot.load_extension, "\N{INBOX TRAY}")
)
try:
method(extension)
except Exception as exc: # pylint: disable=broad-except
traceback_data = ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__, 1))
paginator.add_line(
f"{icon}\N{WARNING SIGN} `{extension}`\n```py\n{traceback_data}\n```",
empty=True
)
else:
paginator.add_line(f"{icon} `{extension}`", empty=True)
for page in paginator.pages:
await ctx.send(page) | python | async def jsk_load(self, ctx: commands.Context, *extensions: ExtensionConverter):
paginator = commands.Paginator(prefix='', suffix='')
for extension in itertools.chain(*extensions):
method, icon = (
(self.bot.reload_extension, "\N{CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS}")
if extension in self.bot.extensions else
(self.bot.load_extension, "\N{INBOX TRAY}")
)
try:
method(extension)
except Exception as exc: # pylint: disable=broad-except
traceback_data = ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__, 1))
paginator.add_line(
f"{icon}\N{WARNING SIGN} `{extension}`\n```py\n{traceback_data}\n```",
empty=True
)
else:
paginator.add_line(f"{icon} `{extension}`", empty=True)
for page in paginator.pages:
await ctx.send(page) | [
"async",
"def",
"jsk_load",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
"extensions",
":",
"ExtensionConverter",
")",
":",
"paginator",
"=",
"commands",
".",
"Paginator",
"(",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
... | Loads or reloads the given extension names.
Reports any extensions that failed to load. | [
"Loads",
"or",
"reloads",
"the",
"given",
"extension",
"names",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L242-L271 |
226,943 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_shutdown | async def jsk_shutdown(self, ctx: commands.Context):
"""
Logs this bot out.
"""
await ctx.send("Logging out now..")
await ctx.bot.logout() | python | async def jsk_shutdown(self, ctx: commands.Context):
await ctx.send("Logging out now..")
await ctx.bot.logout() | [
"async",
"def",
"jsk_shutdown",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Logging out now..\"",
")",
"await",
"ctx",
".",
"bot",
".",
"logout",
"(",
")"
] | Logs this bot out. | [
"Logs",
"this",
"bot",
"out",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L301-L307 |
226,944 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_su | async def jsk_su(self, ctx: commands.Context, target: discord.User, *, command_string: str):
"""
Run a command as someone else.
This will try to resolve to a Member, but will use a User if it can't find one.
"""
if ctx.guild:
# Try to upgrade to a Member instance
# This used to be done by a Union converter, but doing it like this makes
# the command more compatible with chaining, e.g. `jsk in .. jsk su ..`
target = ctx.guild.get_member(target.id) or target
alt_ctx = await copy_context_with(ctx, author=target, content=ctx.prefix + command_string)
if alt_ctx.command is None:
if alt_ctx.invoked_with is None:
return await ctx.send('This bot has been hard-configured to ignore this user.')
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.invoke(alt_ctx) | python | async def jsk_su(self, ctx: commands.Context, target: discord.User, *, command_string: str):
if ctx.guild:
# Try to upgrade to a Member instance
# This used to be done by a Union converter, but doing it like this makes
# the command more compatible with chaining, e.g. `jsk in .. jsk su ..`
target = ctx.guild.get_member(target.id) or target
alt_ctx = await copy_context_with(ctx, author=target, content=ctx.prefix + command_string)
if alt_ctx.command is None:
if alt_ctx.invoked_with is None:
return await ctx.send('This bot has been hard-configured to ignore this user.')
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.invoke(alt_ctx) | [
"async",
"def",
"jsk_su",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"target",
":",
"discord",
".",
"User",
",",
"*",
",",
"command_string",
":",
"str",
")",
":",
"if",
"ctx",
".",
"guild",
":",
"# Try to upgrade to a Member instance",
... | Run a command as someone else.
This will try to resolve to a Member, but will use a User if it can't find one. | [
"Run",
"a",
"command",
"as",
"someone",
"else",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L311-L331 |
226,945 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_in | async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str):
"""
Run a command as if it were in a different channel.
"""
alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.invoke(alt_ctx) | python | async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str):
alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.invoke(alt_ctx) | [
"async",
"def",
"jsk_in",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"channel",
":",
"discord",
".",
"TextChannel",
",",
"*",
",",
"command_string",
":",
"str",
")",
":",
"alt_ctx",
"=",
"await",
"copy_context_with",
"(",
"ctx",
",",
... | Run a command as if it were in a different channel. | [
"Run",
"a",
"command",
"as",
"if",
"it",
"were",
"in",
"a",
"different",
"channel",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L334-L344 |
226,946 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_sudo | async def jsk_sudo(self, ctx: commands.Context, *, command_string: str):
"""
Run a command bypassing all checks and cooldowns.
This also bypasses permission checks so this has a high possibility of making a command raise.
"""
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.reinvoke(alt_ctx) | python | async def jsk_sudo(self, ctx: commands.Context, *, command_string: str):
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
return await alt_ctx.command.reinvoke(alt_ctx) | [
"async",
"def",
"jsk_sudo",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"command_string",
":",
"str",
")",
":",
"alt_ctx",
"=",
"await",
"copy_context_with",
"(",
"ctx",
",",
"content",
"=",
"ctx",
".",
"prefix",
"+",
"comm... | Run a command bypassing all checks and cooldowns.
This also bypasses permission checks so this has a high possibility of making a command raise. | [
"Run",
"a",
"command",
"bypassing",
"all",
"checks",
"and",
"cooldowns",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L347-L359 |
226,947 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_repeat | async def jsk_repeat(self, ctx: commands.Context, times: int, *, command_string: str):
"""
Runs a command multiple times in a row.
This acts like the command was invoked several times manually, so it obeys cooldowns.
"""
with self.submit(ctx): # allow repeats to be cancelled
for _ in range(times):
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
await alt_ctx.command.reinvoke(alt_ctx) | python | async def jsk_repeat(self, ctx: commands.Context, times: int, *, command_string: str):
with self.submit(ctx): # allow repeats to be cancelled
for _ in range(times):
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
await alt_ctx.command.reinvoke(alt_ctx) | [
"async",
"def",
"jsk_repeat",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"times",
":",
"int",
",",
"*",
",",
"command_string",
":",
"str",
")",
":",
"with",
"self",
".",
"submit",
"(",
"ctx",
")",
":",
"# allow repeats to be cancelled... | Runs a command multiple times in a row.
This acts like the command was invoked several times manually, so it obeys cooldowns. | [
"Runs",
"a",
"command",
"multiple",
"times",
"in",
"a",
"row",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L362-L376 |
226,948 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_debug | async def jsk_debug(self, ctx: commands.Context, *, command_string: str):
"""
Run a command timing execution and catching exceptions.
"""
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
start = time.perf_counter()
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
await alt_ctx.command.invoke(alt_ctx)
end = time.perf_counter()
return await ctx.send(f"Command `{alt_ctx.command.qualified_name}` finished in {end - start:.3f}s.") | python | async def jsk_debug(self, ctx: commands.Context, *, command_string: str):
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found')
start = time.perf_counter()
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
await alt_ctx.command.invoke(alt_ctx)
end = time.perf_counter()
return await ctx.send(f"Command `{alt_ctx.command.qualified_name}` finished in {end - start:.3f}s.") | [
"async",
"def",
"jsk_debug",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"command_string",
":",
"str",
")",
":",
"alt_ctx",
"=",
"await",
"copy_context_with",
"(",
"ctx",
",",
"content",
"=",
"ctx",
".",
"prefix",
"+",
"com... | Run a command timing execution and catching exceptions. | [
"Run",
"a",
"command",
"timing",
"execution",
"and",
"catching",
"exceptions",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L379-L396 |
226,949 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_cat | async def jsk_cat(self, ctx: commands.Context, argument: str):
"""
Read out a file, using syntax highlighting if detected.
Lines and linespans are supported by adding '#L12' or '#L12-14' etc to the end of the filename.
"""
match = self.__cat_line_regex.search(argument)
if not match: # should never happen
return await ctx.send("Couldn't parse this input.")
path = match.group(1)
line_span = None
if match.group(2):
start = int(match.group(2))
line_span = (start, int(match.group(3) or start))
if not os.path.exists(path) or os.path.isdir(path):
return await ctx.send(f"`{path}`: No file by that name.")
size = os.path.getsize(path)
if size <= 0:
return await ctx.send(f"`{path}`: Cowardly refusing to read a file with no size stat"
f" (it may be empty, endless or inaccessible).")
if size > 50 * (1024 ** 2):
return await ctx.send(f"`{path}`: Cowardly refusing to read a file >50MB.")
try:
with open(path, "rb") as file:
paginator = WrappedFilePaginator(file, line_span=line_span, max_size=1985)
except UnicodeDecodeError:
return await ctx.send(f"`{path}`: Couldn't determine the encoding of this file.")
except ValueError as exc:
return await ctx.send(f"`{path}`: Couldn't read this file, {exc}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | python | async def jsk_cat(self, ctx: commands.Context, argument: str):
match = self.__cat_line_regex.search(argument)
if not match: # should never happen
return await ctx.send("Couldn't parse this input.")
path = match.group(1)
line_span = None
if match.group(2):
start = int(match.group(2))
line_span = (start, int(match.group(3) or start))
if not os.path.exists(path) or os.path.isdir(path):
return await ctx.send(f"`{path}`: No file by that name.")
size = os.path.getsize(path)
if size <= 0:
return await ctx.send(f"`{path}`: Cowardly refusing to read a file with no size stat"
f" (it may be empty, endless or inaccessible).")
if size > 50 * (1024 ** 2):
return await ctx.send(f"`{path}`: Cowardly refusing to read a file >50MB.")
try:
with open(path, "rb") as file:
paginator = WrappedFilePaginator(file, line_span=line_span, max_size=1985)
except UnicodeDecodeError:
return await ctx.send(f"`{path}`: Couldn't determine the encoding of this file.")
except ValueError as exc:
return await ctx.send(f"`{path}`: Couldn't read this file, {exc}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | [
"async",
"def",
"jsk_cat",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"argument",
":",
"str",
")",
":",
"match",
"=",
"self",
".",
"__cat_line_regex",
".",
"search",
"(",
"argument",
")",
"if",
"not",
"match",
":",
"# should never hap... | Read out a file, using syntax highlighting if detected.
Lines and linespans are supported by adding '#L12' or '#L12-14' etc to the end of the filename. | [
"Read",
"out",
"a",
"file",
"using",
"syntax",
"highlighting",
"if",
"detected",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L402-L443 |
226,950 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_curl | async def jsk_curl(self, ctx: commands.Context, url: str):
"""
Download and display a text file from the internet.
This command is similar to jsk cat, but accepts a URL.
"""
# remove embed maskers if present
url = url.lstrip("<").rstrip(">")
async with ReplResponseReactor(ctx.message):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
hints = (
response.content_type,
url
)
code = response.status
if not data:
return await ctx.send(f"HTTP response was empty (status code {code}).")
try:
paginator = WrappedFilePaginator(io.BytesIO(data), language_hints=hints, max_size=1985)
except UnicodeDecodeError:
return await ctx.send(f"Couldn't determine the encoding of the response. (status code {code})")
except ValueError as exc:
return await ctx.send(f"Couldn't read response (status code {code}), {exc}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | python | async def jsk_curl(self, ctx: commands.Context, url: str):
# remove embed maskers if present
url = url.lstrip("<").rstrip(">")
async with ReplResponseReactor(ctx.message):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
hints = (
response.content_type,
url
)
code = response.status
if not data:
return await ctx.send(f"HTTP response was empty (status code {code}).")
try:
paginator = WrappedFilePaginator(io.BytesIO(data), language_hints=hints, max_size=1985)
except UnicodeDecodeError:
return await ctx.send(f"Couldn't determine the encoding of the response. (status code {code})")
except ValueError as exc:
return await ctx.send(f"Couldn't read response (status code {code}), {exc}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | [
"async",
"def",
"jsk_curl",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"url",
":",
"str",
")",
":",
"# remove embed maskers if present",
"url",
"=",
"url",
".",
"lstrip",
"(",
"\"<\"",
")",
".",
"rstrip",
"(",
"\">\"",
")",
"async",
... | Download and display a text file from the internet.
This command is similar to jsk cat, but accepts a URL. | [
"Download",
"and",
"display",
"a",
"text",
"file",
"from",
"the",
"internet",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L446-L477 |
226,951 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_source | async def jsk_source(self, ctx: commands.Context, *, command_name: str):
"""
Displays the source code for a command.
"""
command = self.bot.get_command(command_name)
if not command:
return await ctx.send(f"Couldn't find command `{command_name}`.")
try:
source_lines, _ = inspect.getsourcelines(command.callback)
except (TypeError, OSError):
return await ctx.send(f"Was unable to retrieve the source for `{command}` for some reason.")
# getsourcelines for some reason returns WITH line endings
source_lines = ''.join(source_lines).split('\n')
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)
for line in source_lines:
paginator.add_line(line)
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | python | async def jsk_source(self, ctx: commands.Context, *, command_name: str):
command = self.bot.get_command(command_name)
if not command:
return await ctx.send(f"Couldn't find command `{command_name}`.")
try:
source_lines, _ = inspect.getsourcelines(command.callback)
except (TypeError, OSError):
return await ctx.send(f"Was unable to retrieve the source for `{command}` for some reason.")
# getsourcelines for some reason returns WITH line endings
source_lines = ''.join(source_lines).split('\n')
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)
for line in source_lines:
paginator.add_line(line)
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx) | [
"async",
"def",
"jsk_source",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"command_name",
":",
"str",
")",
":",
"command",
"=",
"self",
".",
"bot",
".",
"get_command",
"(",
"command_name",
")",
"if",
"not",
"command",
":",
... | Displays the source code for a command. | [
"Displays",
"the",
"source",
"code",
"for",
"a",
"command",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L480-L502 |
226,952 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_retain | async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None):
"""
Turn variable retention for REPL on or off.
Provide no argument for current status.
"""
if toggle is None:
if self.retain:
return await ctx.send("Variable retention is set to ON.")
return await ctx.send("Variable retention is set to OFF.")
if toggle:
if self.retain:
return await ctx.send("Variable retention is already set to ON.")
self.retain = True
self._scope = Scope()
return await ctx.send("Variable retention is ON. Future REPL sessions will retain their scope.")
if not self.retain:
return await ctx.send("Variable retention is already set to OFF.")
self.retain = False
return await ctx.send("Variable retention is OFF. Future REPL sessions will dispose their scope when done.") | python | async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None):
if toggle is None:
if self.retain:
return await ctx.send("Variable retention is set to ON.")
return await ctx.send("Variable retention is set to OFF.")
if toggle:
if self.retain:
return await ctx.send("Variable retention is already set to ON.")
self.retain = True
self._scope = Scope()
return await ctx.send("Variable retention is ON. Future REPL sessions will retain their scope.")
if not self.retain:
return await ctx.send("Variable retention is already set to OFF.")
self.retain = False
return await ctx.send("Variable retention is OFF. Future REPL sessions will dispose their scope when done.") | [
"async",
"def",
"jsk_retain",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"toggle",
":",
"bool",
"=",
"None",
")",
":",
"if",
"toggle",
"is",
"None",
":",
"if",
"self",
".",
"retain",
":",
"return",
"await",
"ctx",
".",... | Turn variable retention for REPL on or off.
Provide no argument for current status. | [
"Turn",
"variable",
"retention",
"for",
"REPL",
"on",
"or",
"off",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L506-L531 |
226,953 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_python | async def jsk_python(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Direct evaluation of Python code.
"""
arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
arg_dict["_"] = self.last_result
scope = self.scope
try:
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
if result is None:
continue
self.last_result = result
if isinstance(result, discord.File):
await ctx.send(file=result)
elif isinstance(result, discord.Embed):
await ctx.send(embed=result)
elif isinstance(result, PaginatorInterface):
await result.send_to(ctx)
else:
if not isinstance(result, str):
# repr all non-strings
result = repr(result)
if len(result) > 2000:
# inconsistency here, results get wrapped in codeblocks when they are too large
# but don't if they're not. probably not that bad, but noting for later review
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)
paginator.add_line(result)
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
else:
if result.strip() == '':
result = "\u200b"
await ctx.send(result.replace(self.bot.http.token, "[token omitted]"))
finally:
scope.clear_intersection(arg_dict) | python | async def jsk_python(self, ctx: commands.Context, *, argument: CodeblockConverter):
arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
arg_dict["_"] = self.last_result
scope = self.scope
try:
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
if result is None:
continue
self.last_result = result
if isinstance(result, discord.File):
await ctx.send(file=result)
elif isinstance(result, discord.Embed):
await ctx.send(embed=result)
elif isinstance(result, PaginatorInterface):
await result.send_to(ctx)
else:
if not isinstance(result, str):
# repr all non-strings
result = repr(result)
if len(result) > 2000:
# inconsistency here, results get wrapped in codeblocks when they are too large
# but don't if they're not. probably not that bad, but noting for later review
paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)
paginator.add_line(result)
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
else:
if result.strip() == '':
result = "\u200b"
await ctx.send(result.replace(self.bot.http.token, "[token omitted]"))
finally:
scope.clear_intersection(arg_dict) | [
"async",
"def",
"jsk_python",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"arg_dict",
"=",
"get_var_dict_from_ctx",
"(",
"ctx",
",",
"SCOPE_PREFIX",
")",
"arg_dict",
"[",
"\"_\"",
... | Direct evaluation of Python code. | [
"Direct",
"evaluation",
"of",
"Python",
"code",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L534-L579 |
226,954 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_python_inspect | async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Evaluation of Python code with inspect information.
"""
arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
arg_dict["_"] = self.last_result
scope = self.scope
try:
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
self.last_result = result
header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")
if len(header) > 485:
header = header[0:482] + "..."
paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)
for name, res in all_inspections(result):
paginator.add_line(f"{name:16.16} :: {res}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
finally:
scope.clear_intersection(arg_dict) | python | async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter):
arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
arg_dict["_"] = self.last_result
scope = self.scope
try:
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
self.last_result = result
header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")
if len(header) > 485:
header = header[0:482] + "..."
paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)
for name, res in all_inspections(result):
paginator.add_line(f"{name:16.16} :: {res}")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
await interface.send_to(ctx)
finally:
scope.clear_intersection(arg_dict) | [
"async",
"def",
"jsk_python_inspect",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"arg_dict",
"=",
"get_var_dict_from_ctx",
"(",
"ctx",
",",
"SCOPE_PREFIX",
")",
"arg_dict",
"[",
"... | Evaluation of Python code with inspect information. | [
"Evaluation",
"of",
"Python",
"code",
"with",
"inspect",
"information",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L582-L611 |
226,955 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_shell | async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
paginator = WrappedPaginator(prefix="```sh", max_size=1985)
paginator.add_line(f"$ {argument.content}\n")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(argument.content) as reader:
async for line in reader:
if interface.closed:
return
await interface.add_line(line)
await interface.add_line(f"\n[status] Return code {reader.close_code}") | python | async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
paginator = WrappedPaginator(prefix="```sh", max_size=1985)
paginator.add_line(f"$ {argument.content}\n")
interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
self.bot.loop.create_task(interface.send_to(ctx))
with ShellReader(argument.content) as reader:
async for line in reader:
if interface.closed:
return
await interface.add_line(line)
await interface.add_line(f"\n[status] Return code {reader.close_code}") | [
"async",
"def",
"jsk_shell",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"async",
"with",
"ReplResponseReactor",
"(",
"ctx",
".",
"message",
")",
":",
"with",
"self",
".",
"sub... | Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator. | [
"Executes",
"statements",
"in",
"the",
"system",
"shell",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L615-L636 |
226,956 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_git | async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Shortcut for 'jsk sh git'. Invokes the system shell.
"""
return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, "git " + argument.content)) | python | async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):
return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, "git " + argument.content)) | [
"async",
"def",
"jsk_git",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"return",
"await",
"ctx",
".",
"invoke",
"(",
"self",
".",
"jsk_shell",
",",
"argument",
"=",
"Codeblock"... | Shortcut for 'jsk sh git'. Invokes the system shell. | [
"Shortcut",
"for",
"jsk",
"sh",
"git",
".",
"Invokes",
"the",
"system",
"shell",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L639-L644 |
226,957 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_voice | async def jsk_voice(self, ctx: commands.Context):
"""
Voice-related commands.
If invoked without subcommand, relays current voice state.
"""
# if using a subcommand, short out
if ctx.invoked_subcommand is not None and ctx.invoked_subcommand is not self.jsk_voice:
return
# give info about the current voice client if there is one
voice = ctx.guild.voice_client
if not voice or not voice.is_connected():
return await ctx.send("Not connected.")
await ctx.send(f"Connected to {voice.channel.name}, "
f"{'paused' if voice.is_paused() else 'playing' if voice.is_playing() else 'idle'}.") | python | async def jsk_voice(self, ctx: commands.Context):
# if using a subcommand, short out
if ctx.invoked_subcommand is not None and ctx.invoked_subcommand is not self.jsk_voice:
return
# give info about the current voice client if there is one
voice = ctx.guild.voice_client
if not voice or not voice.is_connected():
return await ctx.send("Not connected.")
await ctx.send(f"Connected to {voice.channel.name}, "
f"{'paused' if voice.is_paused() else 'playing' if voice.is_playing() else 'idle'}.") | [
"async",
"def",
"jsk_voice",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"# if using a subcommand, short out",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"not",
"None",
"and",
"ctx",
".",
"invoked_subcommand",
"is",
"not",
"self",
".... | Voice-related commands.
If invoked without subcommand, relays current voice state. | [
"Voice",
"-",
"related",
"commands",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L649-L667 |
226,958 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_join | async def jsk_vc_join(self, ctx: commands.Context, *,
destination: typing.Union[discord.VoiceChannel, discord.Member] = None):
"""
Joins a voice channel, or moves to it if already connected.
Passing a voice channel uses that voice channel.
Passing a member will use that member's current voice channel.
Passing nothing will use the author's voice channel.
"""
destination = destination or ctx.author
if isinstance(destination, discord.Member):
if destination.voice and destination.voice.channel:
destination = destination.voice.channel
else:
return await ctx.send("Member has no voice channel.")
voice = ctx.guild.voice_client
if voice:
await voice.move_to(destination)
else:
await destination.connect(reconnect=True)
await ctx.send(f"Connected to {destination.name}.") | python | async def jsk_vc_join(self, ctx: commands.Context, *,
destination: typing.Union[discord.VoiceChannel, discord.Member] = None):
destination = destination or ctx.author
if isinstance(destination, discord.Member):
if destination.voice and destination.voice.channel:
destination = destination.voice.channel
else:
return await ctx.send("Member has no voice channel.")
voice = ctx.guild.voice_client
if voice:
await voice.move_to(destination)
else:
await destination.connect(reconnect=True)
await ctx.send(f"Connected to {destination.name}.") | [
"async",
"def",
"jsk_vc_join",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"destination",
":",
"typing",
".",
"Union",
"[",
"discord",
".",
"VoiceChannel",
",",
"discord",
".",
"Member",
"]",
"=",
"None",
")",
":",
"destina... | Joins a voice channel, or moves to it if already connected.
Passing a voice channel uses that voice channel.
Passing a member will use that member's current voice channel.
Passing nothing will use the author's voice channel. | [
"Joins",
"a",
"voice",
"channel",
"or",
"moves",
"to",
"it",
"if",
"already",
"connected",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L670-L695 |
226,959 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_disconnect | async def jsk_vc_disconnect(self, ctx: commands.Context):
"""
Disconnects from the voice channel in this guild, if there is one.
"""
voice = ctx.guild.voice_client
await voice.disconnect()
await ctx.send(f"Disconnected from {voice.channel.name}.") | python | async def jsk_vc_disconnect(self, ctx: commands.Context):
voice = ctx.guild.voice_client
await voice.disconnect()
await ctx.send(f"Disconnected from {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_disconnect",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"await",
"voice",
".",
"disconnect",
"(",
")",
"await",
"ctx",
".",
"send",
"(",
"f\"Disconne... | Disconnects from the voice channel in this guild, if there is one. | [
"Disconnects",
"from",
"the",
"voice",
"channel",
"in",
"this",
"guild",
"if",
"there",
"is",
"one",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L699-L707 |
226,960 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_stop | async def jsk_vc_stop(self, ctx: commands.Context):
"""
Stops running an audio source, if there is one.
"""
voice = ctx.guild.voice_client
voice.stop()
await ctx.send(f"Stopped playing audio in {voice.channel.name}.") | python | async def jsk_vc_stop(self, ctx: commands.Context):
voice = ctx.guild.voice_client
voice.stop()
await ctx.send(f"Stopped playing audio in {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_stop",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"voice",
".",
"stop",
"(",
")",
"await",
"ctx",
".",
"send",
"(",
"f\"Stopped playing audio in {voice... | Stops running an audio source, if there is one. | [
"Stops",
"running",
"an",
"audio",
"source",
"if",
"there",
"is",
"one",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L711-L719 |
226,961 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_pause | async def jsk_vc_pause(self, ctx: commands.Context):
"""
Pauses a running audio source, if there is one.
"""
voice = ctx.guild.voice_client
if voice.is_paused():
return await ctx.send("Audio is already paused.")
voice.pause()
await ctx.send(f"Paused audio in {voice.channel.name}.") | python | async def jsk_vc_pause(self, ctx: commands.Context):
voice = ctx.guild.voice_client
if voice.is_paused():
return await ctx.send("Audio is already paused.")
voice.pause()
await ctx.send(f"Paused audio in {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_pause",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"if",
"voice",
".",
"is_paused",
"(",
")",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\... | Pauses a running audio source, if there is one. | [
"Pauses",
"a",
"running",
"audio",
"source",
"if",
"there",
"is",
"one",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L723-L734 |
226,962 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_resume | async def jsk_vc_resume(self, ctx: commands.Context):
"""
Resumes a running audio source, if there is one.
"""
voice = ctx.guild.voice_client
if not voice.is_paused():
return await ctx.send("Audio is not paused.")
voice.resume()
await ctx.send(f"Resumed audio in {voice.channel.name}.") | python | async def jsk_vc_resume(self, ctx: commands.Context):
voice = ctx.guild.voice_client
if not voice.is_paused():
return await ctx.send("Audio is not paused.")
voice.resume()
await ctx.send(f"Resumed audio in {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_resume",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"if",
"not",
"voice",
".",
"is_paused",
"(",
")",
":",
"return",
"await",
"ctx",
".",
"send",
... | Resumes a running audio source, if there is one. | [
"Resumes",
"a",
"running",
"audio",
"source",
"if",
"there",
"is",
"one",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L738-L749 |
226,963 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_volume | async def jsk_vc_volume(self, ctx: commands.Context, *, percentage: float):
"""
Adjusts the volume of an audio source if it is supported.
"""
volume = max(0.0, min(1.0, percentage / 100))
source = ctx.guild.voice_client.source
if not isinstance(source, discord.PCMVolumeTransformer):
return await ctx.send("This source doesn't support adjusting volume or "
"the interface to do so is not exposed.")
source.volume = volume
await ctx.send(f"Volume set to {volume * 100:.2f}%") | python | async def jsk_vc_volume(self, ctx: commands.Context, *, percentage: float):
volume = max(0.0, min(1.0, percentage / 100))
source = ctx.guild.voice_client.source
if not isinstance(source, discord.PCMVolumeTransformer):
return await ctx.send("This source doesn't support adjusting volume or "
"the interface to do so is not exposed.")
source.volume = volume
await ctx.send(f"Volume set to {volume * 100:.2f}%") | [
"async",
"def",
"jsk_vc_volume",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"percentage",
":",
"float",
")",
":",
"volume",
"=",
"max",
"(",
"0.0",
",",
"min",
"(",
"1.0",
",",
"percentage",
"/",
"100",
")",
")",
"sour... | Adjusts the volume of an audio source if it is supported. | [
"Adjusts",
"the",
"volume",
"of",
"an",
"audio",
"source",
"if",
"it",
"is",
"supported",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L753-L768 |
226,964 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_play | async def jsk_vc_play(self, ctx: commands.Context, *, uri: str):
"""
Plays audio direct from a URI.
Can be either a local file or an audio resource on the internet.
"""
voice = ctx.guild.voice_client
if voice.is_playing():
voice.stop()
# remove embed maskers if present
uri = uri.lstrip("<").rstrip(">")
voice.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(uri)))
await ctx.send(f"Playing in {voice.channel.name}.") | python | async def jsk_vc_play(self, ctx: commands.Context, *, uri: str):
voice = ctx.guild.voice_client
if voice.is_playing():
voice.stop()
# remove embed maskers if present
uri = uri.lstrip("<").rstrip(">")
voice.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(uri)))
await ctx.send(f"Playing in {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_play",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"uri",
":",
"str",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"if",
"voice",
".",
"is_playing",
"(",
")",
":",
"voice",
"... | Plays audio direct from a URI.
Can be either a local file or an audio resource on the internet. | [
"Plays",
"audio",
"direct",
"from",
"a",
"URI",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L772-L788 |
226,965 | Gorialis/jishaku | jishaku/cog.py | Jishaku.jsk_vc_youtube_dl | async def jsk_vc_youtube_dl(self, ctx: commands.Context, *, url: str):
"""
Plays audio from youtube_dl-compatible sources.
"""
if not youtube_dl:
return await ctx.send("youtube_dl is not installed.")
voice = ctx.guild.voice_client
if voice.is_playing():
voice.stop()
# remove embed maskers if present
url = url.lstrip("<").rstrip(">")
voice.play(discord.PCMVolumeTransformer(BasicYouTubeDLSource(url)))
await ctx.send(f"Playing in {voice.channel.name}.") | python | async def jsk_vc_youtube_dl(self, ctx: commands.Context, *, url: str):
if not youtube_dl:
return await ctx.send("youtube_dl is not installed.")
voice = ctx.guild.voice_client
if voice.is_playing():
voice.stop()
# remove embed maskers if present
url = url.lstrip("<").rstrip(">")
voice.play(discord.PCMVolumeTransformer(BasicYouTubeDLSource(url)))
await ctx.send(f"Playing in {voice.channel.name}.") | [
"async",
"def",
"jsk_vc_youtube_dl",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"url",
":",
"str",
")",
":",
"if",
"not",
"youtube_dl",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"youtube_dl is not installed.\"",
")",
... | Plays audio from youtube_dl-compatible sources. | [
"Plays",
"audio",
"from",
"youtube_dl",
"-",
"compatible",
"sources",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L792-L809 |
226,966 | Gorialis/jishaku | jishaku/hljs.py | get_language | def get_language(query: str) -> str:
"""Tries to work out the highlight.js language of a given file name or
shebang. Returns an empty string if none match.
"""
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return '' | python | def get_language(query: str) -> str:
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return '' | [
"def",
"get_language",
"(",
"query",
":",
"str",
")",
"->",
"str",
":",
"query",
"=",
"query",
".",
"lower",
"(",
")",
"for",
"language",
"in",
"LANGUAGES",
":",
"if",
"query",
".",
"endswith",
"(",
"language",
")",
":",
"return",
"language",
"return",... | Tries to work out the highlight.js language of a given file name or
shebang. Returns an empty string if none match. | [
"Tries",
"to",
"work",
"out",
"the",
"highlight",
".",
"js",
"language",
"of",
"a",
"given",
"file",
"name",
"or",
"shebang",
".",
"Returns",
"an",
"empty",
"string",
"if",
"none",
"match",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/hljs.py#L340-L348 |
226,967 | Gorialis/jishaku | jishaku/modules.py | find_extensions_in | def find_extensions_in(path: typing.Union[str, pathlib.Path]) -> list:
"""
Tries to find things that look like bot extensions in a directory.
"""
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
if not path.is_dir():
return []
extension_names = []
# Find extensions directly in this folder
for subpath in path.glob('*.py'):
parts = subpath.with_suffix('').parts
if parts[0] == '.':
parts = parts[1:]
extension_names.append('.'.join(parts))
# Find extensions as subfolder modules
for subpath in path.glob('*/__init__.py'):
parts = subpath.parent.parts
if parts[0] == '.':
parts = parts[1:]
extension_names.append('.'.join(parts))
return extension_names | python | def find_extensions_in(path: typing.Union[str, pathlib.Path]) -> list:
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
if not path.is_dir():
return []
extension_names = []
# Find extensions directly in this folder
for subpath in path.glob('*.py'):
parts = subpath.with_suffix('').parts
if parts[0] == '.':
parts = parts[1:]
extension_names.append('.'.join(parts))
# Find extensions as subfolder modules
for subpath in path.glob('*/__init__.py'):
parts = subpath.parent.parts
if parts[0] == '.':
parts = parts[1:]
extension_names.append('.'.join(parts))
return extension_names | [
"def",
"find_extensions_in",
"(",
"path",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
"]",
")",
"->",
"list",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"pathlib",
".",
"Path",
")",
":",
"path",
"=",
"pathlib",
".",
... | Tries to find things that look like bot extensions in a directory. | [
"Tries",
"to",
"find",
"things",
"that",
"look",
"like",
"bot",
"extensions",
"in",
"a",
"directory",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/modules.py#L23-L52 |
226,968 | Gorialis/jishaku | jishaku/modules.py | resolve_extensions | def resolve_extensions(bot: commands.Bot, name: str) -> list:
"""
Tries to resolve extension queries into a list of extension names.
"""
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
path = path / part
return find_extensions_in(path)
if name == '~':
return list(bot.extensions.keys())
return [name] | python | def resolve_extensions(bot: commands.Bot, name: str) -> list:
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
path = path / part
return find_extensions_in(path)
if name == '~':
return list(bot.extensions.keys())
return [name] | [
"def",
"resolve_extensions",
"(",
"bot",
":",
"commands",
".",
"Bot",
",",
"name",
":",
"str",
")",
"->",
"list",
":",
"if",
"name",
".",
"endswith",
"(",
"'.*'",
")",
":",
"module_parts",
"=",
"name",
"[",
":",
"-",
"2",
"]",
".",
"split",
"(",
... | Tries to resolve extension queries into a list of extension names. | [
"Tries",
"to",
"resolve",
"extension",
"queries",
"into",
"a",
"list",
"of",
"extension",
"names",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/modules.py#L55-L72 |
226,969 | Gorialis/jishaku | jishaku/modules.py | package_version | def package_version(package_name: str) -> typing.Optional[str]:
"""
Returns package version as a string, or None if it couldn't be found.
"""
try:
return pkg_resources.get_distribution(package_name).version
except (pkg_resources.DistributionNotFound, AttributeError):
return None | python | def package_version(package_name: str) -> typing.Optional[str]:
try:
return pkg_resources.get_distribution(package_name).version
except (pkg_resources.DistributionNotFound, AttributeError):
return None | [
"def",
"package_version",
"(",
"package_name",
":",
"str",
")",
"->",
"typing",
".",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"return",
"pkg_resources",
".",
"get_distribution",
"(",
"package_name",
")",
".",
"version",
"except",
"(",
"pkg_resources",
"... | Returns package version as a string, or None if it couldn't be found. | [
"Returns",
"package",
"version",
"as",
"a",
"string",
"or",
"None",
"if",
"it",
"couldn",
"t",
"be",
"found",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/modules.py#L75-L83 |
226,970 | Gorialis/jishaku | jishaku/voice.py | vc_check | async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument
"""
Check for whether VC is available in this bot.
"""
if not discord.voice_client.has_nacl:
raise commands.CheckFailure("voice cannot be used because PyNaCl is not loaded")
if not discord.opus.is_loaded():
raise commands.CheckFailure("voice cannot be used because libopus is not loaded")
return True | python | async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument
if not discord.voice_client.has_nacl:
raise commands.CheckFailure("voice cannot be used because PyNaCl is not loaded")
if not discord.opus.is_loaded():
raise commands.CheckFailure("voice cannot be used because libopus is not loaded")
return True | [
"async",
"def",
"vc_check",
"(",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"discord",
".",
"voice_client",
".",
"has_nacl",
":",
"raise",
"commands",
".",
"CheckFailure",
"(",
"\"voice cannot be used because ... | Check for whether VC is available in this bot. | [
"Check",
"for",
"whether",
"VC",
"is",
"available",
"in",
"this",
"bot",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/voice.py#L24-L35 |
226,971 | Gorialis/jishaku | jishaku/voice.py | connected_check | async def connected_check(ctx: commands.Context):
"""
Check whether we are connected to VC in this guild.
"""
voice = ctx.guild.voice_client
if not voice or not voice.is_connected():
raise commands.CheckFailure("Not connected to VC in this guild")
return True | python | async def connected_check(ctx: commands.Context):
voice = ctx.guild.voice_client
if not voice or not voice.is_connected():
raise commands.CheckFailure("Not connected to VC in this guild")
return True | [
"async",
"def",
"connected_check",
"(",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"if",
"not",
"voice",
"or",
"not",
"voice",
".",
"is_connected",
"(",
")",
":",
"raise",
"commands",
".",
... | Check whether we are connected to VC in this guild. | [
"Check",
"whether",
"we",
"are",
"connected",
"to",
"VC",
"in",
"this",
"guild",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/voice.py#L38-L48 |
226,972 | Gorialis/jishaku | jishaku/voice.py | playing_check | async def playing_check(ctx: commands.Context):
"""
Checks whether we are playing audio in VC in this guild.
This doubles up as a connection check.
"""
if await connected_check(ctx) and not ctx.guild.voice_client.is_playing():
raise commands.CheckFailure("The voice client in this guild is not playing anything.")
return True | python | async def playing_check(ctx: commands.Context):
if await connected_check(ctx) and not ctx.guild.voice_client.is_playing():
raise commands.CheckFailure("The voice client in this guild is not playing anything.")
return True | [
"async",
"def",
"playing_check",
"(",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"if",
"await",
"connected_check",
"(",
"ctx",
")",
"and",
"not",
"ctx",
".",
"guild",
".",
"voice_client",
".",
"is_playing",
"(",
")",
":",
"raise",
"commands",
".",... | Checks whether we are playing audio in VC in this guild.
This doubles up as a connection check. | [
"Checks",
"whether",
"we",
"are",
"playing",
"audio",
"in",
"VC",
"in",
"this",
"guild",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/voice.py#L51-L61 |
226,973 | Gorialis/jishaku | jishaku/functools.py | executor_function | def executor_function(sync_function: typing.Callable):
"""A decorator that wraps a sync function in an executor, changing it into an async function.
This allows processing functions to be wrapped and used immediately as an async function.
Examples
---------
Pushing processing with the Python Imaging Library into an executor:
.. code-block:: python3
from io import BytesIO
from PIL import Image
from jishaku.functools import executor_function
@executor_function
def color_processing(color: discord.Color):
with Image.new('RGB', (64, 64), color.to_rgb()) as im:
buff = BytesIO()
im.save(buff, 'png')
buff.seek(0)
return buff
@bot.command()
async def color(ctx: commands.Context, color: discord.Color=None):
color = color or ctx.author.color
buff = await color_processing(color=color)
await ctx.send(file=discord.File(fp=buff, filename='color.png'))
"""
@functools.wraps(sync_function)
async def sync_wrapper(*args, **kwargs):
"""
Asynchronous function that wraps a sync function with an executor.
"""
loop = asyncio.get_event_loop()
internal_function = functools.partial(sync_function, *args, **kwargs)
return await loop.run_in_executor(None, internal_function)
return sync_wrapper | python | def executor_function(sync_function: typing.Callable):
@functools.wraps(sync_function)
async def sync_wrapper(*args, **kwargs):
"""
Asynchronous function that wraps a sync function with an executor.
"""
loop = asyncio.get_event_loop()
internal_function = functools.partial(sync_function, *args, **kwargs)
return await loop.run_in_executor(None, internal_function)
return sync_wrapper | [
"def",
"executor_function",
"(",
"sync_function",
":",
"typing",
".",
"Callable",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"sync_function",
")",
"async",
"def",
"sync_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Async... | A decorator that wraps a sync function in an executor, changing it into an async function.
This allows processing functions to be wrapped and used immediately as an async function.
Examples
---------
Pushing processing with the Python Imaging Library into an executor:
.. code-block:: python3
from io import BytesIO
from PIL import Image
from jishaku.functools import executor_function
@executor_function
def color_processing(color: discord.Color):
with Image.new('RGB', (64, 64), color.to_rgb()) as im:
buff = BytesIO()
im.save(buff, 'png')
buff.seek(0)
return buff
@bot.command()
async def color(ctx: commands.Context, color: discord.Color=None):
color = color or ctx.author.color
buff = await color_processing(color=color)
await ctx.send(file=discord.File(fp=buff, filename='color.png')) | [
"A",
"decorator",
"that",
"wraps",
"a",
"sync",
"function",
"in",
"an",
"executor",
"changing",
"it",
"into",
"an",
"async",
"function",
"."
] | fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/functools.py#L19-L64 |
226,974 | mailgun/talon | talon/signature/learning/featurespace.py | features | def features(sender=''):
'''Returns a list of signature features.'''
return [
# This one isn't from paper.
# Meant to match companies names, sender's names, address.
many_capitalized_words,
# This one is not from paper.
# Line is too long.
# This one is less aggressive than `Line is too short`
lambda line: 1 if len(line) > TOO_LONG_SIGNATURE_LINE else 0,
# Line contains email pattern.
binary_regex_search(RE_EMAIL),
# Line contains url.
binary_regex_search(RE_URL),
# Line contains phone number pattern.
binary_regex_search(RE_RELAX_PHONE),
# Line matches the regular expression "^[\s]*---*[\s]*$".
binary_regex_match(RE_SEPARATOR),
# Line has a sequence of 10 or more special characters.
binary_regex_search(RE_SPECIAL_CHARS),
# Line contains any typical signature words.
binary_regex_search(RE_SIGNATURE_WORDS),
# Line contains a pattern like Vitor R. Carvalho or William W. Cohen.
binary_regex_search(RE_NAME),
# Percentage of punctuation symbols in the line is larger than 50%
lambda line: 1 if punctuation_percent(line) > 50 else 0,
# Percentage of punctuation symbols in the line is larger than 90%
lambda line: 1 if punctuation_percent(line) > 90 else 0,
contains_sender_names(sender)
] | python | def features(sender=''):
'''Returns a list of signature features.'''
return [
# This one isn't from paper.
# Meant to match companies names, sender's names, address.
many_capitalized_words,
# This one is not from paper.
# Line is too long.
# This one is less aggressive than `Line is too short`
lambda line: 1 if len(line) > TOO_LONG_SIGNATURE_LINE else 0,
# Line contains email pattern.
binary_regex_search(RE_EMAIL),
# Line contains url.
binary_regex_search(RE_URL),
# Line contains phone number pattern.
binary_regex_search(RE_RELAX_PHONE),
# Line matches the regular expression "^[\s]*---*[\s]*$".
binary_regex_match(RE_SEPARATOR),
# Line has a sequence of 10 or more special characters.
binary_regex_search(RE_SPECIAL_CHARS),
# Line contains any typical signature words.
binary_regex_search(RE_SIGNATURE_WORDS),
# Line contains a pattern like Vitor R. Carvalho or William W. Cohen.
binary_regex_search(RE_NAME),
# Percentage of punctuation symbols in the line is larger than 50%
lambda line: 1 if punctuation_percent(line) > 50 else 0,
# Percentage of punctuation symbols in the line is larger than 90%
lambda line: 1 if punctuation_percent(line) > 90 else 0,
contains_sender_names(sender)
] | [
"def",
"features",
"(",
"sender",
"=",
"''",
")",
":",
"return",
"[",
"# This one isn't from paper.",
"# Meant to match companies names, sender's names, address.",
"many_capitalized_words",
",",
"# This one is not from paper.",
"# Line is too long.",
"# This one is less aggressive th... | Returns a list of signature features. | [
"Returns",
"a",
"list",
"of",
"signature",
"features",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/featurespace.py#L18-L47 |
226,975 | mailgun/talon | talon/signature/learning/featurespace.py | apply_features | def apply_features(body, features):
'''Applies features to message body lines.
Returns list of lists. Each of the lists corresponds to the body line
and is constituted by the numbers of features occurrences (0 or 1).
E.g. if element j of list i equals 1 this means that
feature j occurred in line i (counting from the last line of the body).
'''
# collect all non empty lines
lines = [line for line in body.splitlines() if line.strip()]
# take the last SIGNATURE_MAX_LINES
last_lines = lines[-SIGNATURE_MAX_LINES:]
# apply features, fallback to zeros
return ([[f(line) for f in features] for line in last_lines] or
[[0 for f in features]]) | python | def apply_features(body, features):
'''Applies features to message body lines.
Returns list of lists. Each of the lists corresponds to the body line
and is constituted by the numbers of features occurrences (0 or 1).
E.g. if element j of list i equals 1 this means that
feature j occurred in line i (counting from the last line of the body).
'''
# collect all non empty lines
lines = [line for line in body.splitlines() if line.strip()]
# take the last SIGNATURE_MAX_LINES
last_lines = lines[-SIGNATURE_MAX_LINES:]
# apply features, fallback to zeros
return ([[f(line) for f in features] for line in last_lines] or
[[0 for f in features]]) | [
"def",
"apply_features",
"(",
"body",
",",
"features",
")",
":",
"# collect all non empty lines",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"body",
".",
"splitlines",
"(",
")",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"# take the last SIGNATURE_MAX_LIN... | Applies features to message body lines.
Returns list of lists. Each of the lists corresponds to the body line
and is constituted by the numbers of features occurrences (0 or 1).
E.g. if element j of list i equals 1 this means that
feature j occurred in line i (counting from the last line of the body). | [
"Applies",
"features",
"to",
"message",
"body",
"lines",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/featurespace.py#L50-L66 |
226,976 | mailgun/talon | talon/signature/learning/featurespace.py | build_pattern | def build_pattern(body, features):
'''Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain feature occurred
in the last lines of the body.
'''
line_patterns = apply_features(body, features)
return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns) | python | def build_pattern(body, features):
'''Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain feature occurred
in the last lines of the body.
'''
line_patterns = apply_features(body, features)
return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns) | [
"def",
"build_pattern",
"(",
"body",
",",
"features",
")",
":",
"line_patterns",
"=",
"apply_features",
"(",
"body",
",",
"features",
")",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"[",
"i",
"+",
"j",
"for",
"i",
",",
"j",
"in",
"zip",
... | Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain feature occurred
in the last lines of the body. | [
"Converts",
"body",
"into",
"a",
"pattern",
"i",
".",
"e",
".",
"a",
"point",
"in",
"the",
"features",
"space",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/featurespace.py#L69-L77 |
226,977 | mailgun/talon | talon/signature/bruteforce.py | get_signature_candidate | def get_signature_candidate(lines):
"""Return lines that could hold signature
The lines should:
* be among last SIGNATURE_MAX_LINES non-empty lines.
* not include first line
* be shorter than TOO_LONG_SIGNATURE_LINE
* not include more than one line that starts with dashes
"""
# non empty lines indexes
non_empty = [i for i, line in enumerate(lines) if line.strip()]
# if message is empty or just one line then there is no signature
if len(non_empty) <= 1:
return []
# we don't expect signature to start at the 1st line
candidate = non_empty[1:]
# signature shouldn't be longer then SIGNATURE_MAX_LINES
candidate = candidate[-SIGNATURE_MAX_LINES:]
markers = _mark_candidate_indexes(lines, candidate)
candidate = _process_marked_candidate_indexes(candidate, markers)
# get actual lines for the candidate instead of indexes
if candidate:
candidate = lines[candidate[0]:]
return candidate
return [] | python | def get_signature_candidate(lines):
# non empty lines indexes
non_empty = [i for i, line in enumerate(lines) if line.strip()]
# if message is empty or just one line then there is no signature
if len(non_empty) <= 1:
return []
# we don't expect signature to start at the 1st line
candidate = non_empty[1:]
# signature shouldn't be longer then SIGNATURE_MAX_LINES
candidate = candidate[-SIGNATURE_MAX_LINES:]
markers = _mark_candidate_indexes(lines, candidate)
candidate = _process_marked_candidate_indexes(candidate, markers)
# get actual lines for the candidate instead of indexes
if candidate:
candidate = lines[candidate[0]:]
return candidate
return [] | [
"def",
"get_signature_candidate",
"(",
"lines",
")",
":",
"# non empty lines indexes",
"non_empty",
"=",
"[",
"i",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"# if message is empty or just one line t... | Return lines that could hold signature
The lines should:
* be among last SIGNATURE_MAX_LINES non-empty lines.
* not include first line
* be shorter than TOO_LONG_SIGNATURE_LINE
* not include more than one line that starts with dashes | [
"Return",
"lines",
"that",
"could",
"hold",
"signature"
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/bruteforce.py#L118-L148 |
226,978 | mailgun/talon | talon/signature/bruteforce.py | _mark_candidate_indexes | def _mark_candidate_indexes(lines, candidate):
"""Mark candidate indexes with markers
Markers:
* c - line that could be a signature line
* l - long line
* d - line that starts with dashes but has other chars as well
>>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3])
'cdc'
"""
# at first consider everything to be potential signature lines
markers = list('c' * len(candidate))
# mark lines starting from bottom up
for i, line_idx in reversed(list(enumerate(candidate))):
if len(lines[line_idx].strip()) > TOO_LONG_SIGNATURE_LINE:
markers[i] = 'l'
else:
line = lines[line_idx].strip()
if line.startswith('-') and line.strip("-"):
markers[i] = 'd'
return "".join(markers) | python | def _mark_candidate_indexes(lines, candidate):
# at first consider everything to be potential signature lines
markers = list('c' * len(candidate))
# mark lines starting from bottom up
for i, line_idx in reversed(list(enumerate(candidate))):
if len(lines[line_idx].strip()) > TOO_LONG_SIGNATURE_LINE:
markers[i] = 'l'
else:
line = lines[line_idx].strip()
if line.startswith('-') and line.strip("-"):
markers[i] = 'd'
return "".join(markers) | [
"def",
"_mark_candidate_indexes",
"(",
"lines",
",",
"candidate",
")",
":",
"# at first consider everything to be potential signature lines",
"markers",
"=",
"list",
"(",
"'c'",
"*",
"len",
"(",
"candidate",
")",
")",
"# mark lines starting from bottom up",
"for",
"i",
... | Mark candidate indexes with markers
Markers:
* c - line that could be a signature line
* l - long line
* d - line that starts with dashes but has other chars as well
>>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3])
'cdc' | [
"Mark",
"candidate",
"indexes",
"with",
"markers"
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/bruteforce.py#L151-L175 |
226,979 | mailgun/talon | talon/signature/bruteforce.py | _process_marked_candidate_indexes | def _process_marked_candidate_indexes(candidate, markers):
"""
Run regexes against candidate's marked indexes to strip
signature candidate.
>>> _process_marked_candidate_indexes([9, 12, 14, 15, 17], 'clddc')
[15, 17]
"""
match = RE_SIGNATURE_CANDIDATE.match(markers[::-1])
return candidate[-match.end('candidate'):] if match else [] | python | def _process_marked_candidate_indexes(candidate, markers):
match = RE_SIGNATURE_CANDIDATE.match(markers[::-1])
return candidate[-match.end('candidate'):] if match else [] | [
"def",
"_process_marked_candidate_indexes",
"(",
"candidate",
",",
"markers",
")",
":",
"match",
"=",
"RE_SIGNATURE_CANDIDATE",
".",
"match",
"(",
"markers",
"[",
":",
":",
"-",
"1",
"]",
")",
"return",
"candidate",
"[",
"-",
"match",
".",
"end",
"(",
"'ca... | Run regexes against candidate's marked indexes to strip
signature candidate.
>>> _process_marked_candidate_indexes([9, 12, 14, 15, 17], 'clddc')
[15, 17] | [
"Run",
"regexes",
"against",
"candidate",
"s",
"marked",
"indexes",
"to",
"strip",
"signature",
"candidate",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/bruteforce.py#L178-L187 |
226,980 | mailgun/talon | talon/signature/learning/helpers.py | contains_sender_names | def contains_sender_names(sender):
'''Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1
>>> contains_sender_names("<serobnic@mail.ru>")("Serobnic")
1
>>> contains_sender_names("<serobnic@mail.ru>")("serobnic")
1
'''
names = '( |$)|'.join(flatten_list([[e, e.capitalize()]
for e in extract_names(sender)]))
names = names or sender
if names != '':
return binary_regex_search(re.compile(names))
return lambda s: 0 | python | def contains_sender_names(sender):
'''Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1
>>> contains_sender_names("<serobnic@mail.ru>")("Serobnic")
1
>>> contains_sender_names("<serobnic@mail.ru>")("serobnic")
1
'''
names = '( |$)|'.join(flatten_list([[e, e.capitalize()]
for e in extract_names(sender)]))
names = names or sender
if names != '':
return binary_regex_search(re.compile(names))
return lambda s: 0 | [
"def",
"contains_sender_names",
"(",
"sender",
")",
":",
"names",
"=",
"'( |$)|'",
".",
"join",
"(",
"flatten_list",
"(",
"[",
"[",
"e",
",",
"e",
".",
"capitalize",
"(",
")",
"]",
"for",
"e",
"in",
"extract_names",
"(",
"sender",
")",
"]",
")",
")",... | Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1
>>> contains_sender_names("<serobnic@mail.ru>")("Serobnic")
1
>>> contains_sender_names("<serobnic@mail.ru>")("serobnic")
1 | [
"Returns",
"a",
"functions",
"to",
"search",
"sender",
"\\",
"s",
"name",
"or",
"it",
"\\",
"s",
"part",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/helpers.py#L104-L124 |
226,981 | mailgun/talon | talon/signature/learning/helpers.py | categories_percent | def categories_percent(s, categories):
'''Returns category characters percent.
>>> categories_percent("qqq ggg hhh", ["Po"])
0.0
>>> categories_percent("q,w.", ["Po"])
50.0
>>> categories_percent("qqq ggg hhh", ["Nd"])
0.0
>>> categories_percent("q5", ["Nd"])
50.0
>>> categories_percent("s.s,5s", ["Po", "Nd"])
50.0
'''
count = 0
s = to_unicode(s, precise=True)
for c in s:
if unicodedata.category(c) in categories:
count += 1
return 100 * float(count) / len(s) if len(s) else 0 | python | def categories_percent(s, categories):
'''Returns category characters percent.
>>> categories_percent("qqq ggg hhh", ["Po"])
0.0
>>> categories_percent("q,w.", ["Po"])
50.0
>>> categories_percent("qqq ggg hhh", ["Nd"])
0.0
>>> categories_percent("q5", ["Nd"])
50.0
>>> categories_percent("s.s,5s", ["Po", "Nd"])
50.0
'''
count = 0
s = to_unicode(s, precise=True)
for c in s:
if unicodedata.category(c) in categories:
count += 1
return 100 * float(count) / len(s) if len(s) else 0 | [
"def",
"categories_percent",
"(",
"s",
",",
"categories",
")",
":",
"count",
"=",
"0",
"s",
"=",
"to_unicode",
"(",
"s",
",",
"precise",
"=",
"True",
")",
"for",
"c",
"in",
"s",
":",
"if",
"unicodedata",
".",
"category",
"(",
"c",
")",
"in",
"categ... | Returns category characters percent.
>>> categories_percent("qqq ggg hhh", ["Po"])
0.0
>>> categories_percent("q,w.", ["Po"])
50.0
>>> categories_percent("qqq ggg hhh", ["Nd"])
0.0
>>> categories_percent("q5", ["Nd"])
50.0
>>> categories_percent("s.s,5s", ["Po", "Nd"])
50.0 | [
"Returns",
"category",
"characters",
"percent",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/helpers.py#L150-L169 |
226,982 | mailgun/talon | talon/signature/learning/helpers.py | capitalized_words_percent | def capitalized_words_percent(s):
'''Returns capitalized words percent.'''
s = to_unicode(s, precise=True)
words = re.split('\s', s)
words = [w for w in words if w.strip()]
words = [w for w in words if len(w) > 2]
capitalized_words_counter = 0
valid_words_counter = 0
for word in words:
if not INVALID_WORD_START.match(word):
valid_words_counter += 1
if word[0].isupper() and not word[1].isupper():
capitalized_words_counter += 1
if valid_words_counter > 0 and len(words) > 1:
return 100 * float(capitalized_words_counter) / valid_words_counter
return 0 | python | def capitalized_words_percent(s):
'''Returns capitalized words percent.'''
s = to_unicode(s, precise=True)
words = re.split('\s', s)
words = [w for w in words if w.strip()]
words = [w for w in words if len(w) > 2]
capitalized_words_counter = 0
valid_words_counter = 0
for word in words:
if not INVALID_WORD_START.match(word):
valid_words_counter += 1
if word[0].isupper() and not word[1].isupper():
capitalized_words_counter += 1
if valid_words_counter > 0 and len(words) > 1:
return 100 * float(capitalized_words_counter) / valid_words_counter
return 0 | [
"def",
"capitalized_words_percent",
"(",
"s",
")",
":",
"s",
"=",
"to_unicode",
"(",
"s",
",",
"precise",
"=",
"True",
")",
"words",
"=",
"re",
".",
"split",
"(",
"'\\s'",
",",
"s",
")",
"words",
"=",
"[",
"w",
"for",
"w",
"in",
"words",
"if",
"w... | Returns capitalized words percent. | [
"Returns",
"capitalized",
"words",
"percent",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/helpers.py#L183-L199 |
226,983 | mailgun/talon | talon/signature/learning/helpers.py | has_signature | def has_signature(body, sender):
'''Checks if the body has signature. Returns True or False.'''
non_empty = [line for line in body.splitlines() if line.strip()]
candidate = non_empty[-SIGNATURE_MAX_LINES:]
upvotes = 0
for line in candidate:
# we check lines for sender's name, phone, email and url,
# those signature lines don't take more then 27 lines
if len(line.strip()) > 27:
continue
elif contains_sender_names(sender)(line):
return True
elif (binary_regex_search(RE_RELAX_PHONE)(line) +
binary_regex_search(RE_EMAIL)(line) +
binary_regex_search(RE_URL)(line) == 1):
upvotes += 1
if upvotes > 1:
return True | python | def has_signature(body, sender):
'''Checks if the body has signature. Returns True or False.'''
non_empty = [line for line in body.splitlines() if line.strip()]
candidate = non_empty[-SIGNATURE_MAX_LINES:]
upvotes = 0
for line in candidate:
# we check lines for sender's name, phone, email and url,
# those signature lines don't take more then 27 lines
if len(line.strip()) > 27:
continue
elif contains_sender_names(sender)(line):
return True
elif (binary_regex_search(RE_RELAX_PHONE)(line) +
binary_regex_search(RE_EMAIL)(line) +
binary_regex_search(RE_URL)(line) == 1):
upvotes += 1
if upvotes > 1:
return True | [
"def",
"has_signature",
"(",
"body",
",",
"sender",
")",
":",
"non_empty",
"=",
"[",
"line",
"for",
"line",
"in",
"body",
".",
"splitlines",
"(",
")",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"candidate",
"=",
"non_empty",
"[",
"-",
"SIGNATURE_MAX_LI... | Checks if the body has signature. Returns True or False. | [
"Checks",
"if",
"the",
"body",
"has",
"signature",
".",
"Returns",
"True",
"or",
"False",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/helpers.py#L210-L227 |
226,984 | mailgun/talon | talon/quotations.py | remove_initial_spaces_and_mark_message_lines | def remove_initial_spaces_and_mark_message_lines(lines):
"""
Removes the initial spaces in each line before marking message lines.
This ensures headers can be identified if they are indented with spaces.
"""
i = 0
while i < len(lines):
lines[i] = lines[i].lstrip(' ')
i += 1
return mark_message_lines(lines) | python | def remove_initial_spaces_and_mark_message_lines(lines):
i = 0
while i < len(lines):
lines[i] = lines[i].lstrip(' ')
i += 1
return mark_message_lines(lines) | [
"def",
"remove_initial_spaces_and_mark_message_lines",
"(",
"lines",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"lines",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"lines",
"[",
"i",
"]",
".",
"lstrip",
"(",
"' '",
")",
"i",
"+=",
"1",
"re... | Removes the initial spaces in each line before marking message lines.
This ensures headers can be identified if they are indented with spaces. | [
"Removes",
"the",
"initial",
"spaces",
"in",
"each",
"line",
"before",
"marking",
"message",
"lines",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L219-L229 |
226,985 | mailgun/talon | talon/quotations.py | mark_message_lines | def mark_message_lines(lines):
"""Mark message lines with markers to distinguish quotation lines.
Markers:
* e - empty line
* m - line that starts with quotation marker '>'
* s - splitter line
* t - presumably lines from the last message in the conversation
>>> mark_message_lines(['answer', 'From: foo@bar.com', '', '> question'])
'tsem'
"""
markers = ['e' for _ in lines]
i = 0
while i < len(lines):
if not lines[i].strip():
markers[i] = 'e' # empty line
elif QUOT_PATTERN.match(lines[i]):
markers[i] = 'm' # line with quotation marker
elif RE_FWD.match(lines[i]):
markers[i] = 'f' # ---- Forwarded message ----
else:
# in case splitter is spread across several lines
splitter = is_splitter('\n'.join(lines[i:i + SPLITTER_MAX_LINES]))
if splitter:
# append as many splitter markers as lines in splitter
splitter_lines = splitter.group().splitlines()
for j in range(len(splitter_lines)):
markers[i + j] = 's'
# skip splitter lines
i += len(splitter_lines) - 1
else:
# probably the line from the last message in the conversation
markers[i] = 't'
i += 1
return ''.join(markers) | python | def mark_message_lines(lines):
markers = ['e' for _ in lines]
i = 0
while i < len(lines):
if not lines[i].strip():
markers[i] = 'e' # empty line
elif QUOT_PATTERN.match(lines[i]):
markers[i] = 'm' # line with quotation marker
elif RE_FWD.match(lines[i]):
markers[i] = 'f' # ---- Forwarded message ----
else:
# in case splitter is spread across several lines
splitter = is_splitter('\n'.join(lines[i:i + SPLITTER_MAX_LINES]))
if splitter:
# append as many splitter markers as lines in splitter
splitter_lines = splitter.group().splitlines()
for j in range(len(splitter_lines)):
markers[i + j] = 's'
# skip splitter lines
i += len(splitter_lines) - 1
else:
# probably the line from the last message in the conversation
markers[i] = 't'
i += 1
return ''.join(markers) | [
"def",
"mark_message_lines",
"(",
"lines",
")",
":",
"markers",
"=",
"[",
"'e'",
"for",
"_",
"in",
"lines",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"not",
"lines",
"[",
"i",
"]",
".",
"strip",
"(",
")",
":",
... | Mark message lines with markers to distinguish quotation lines.
Markers:
* e - empty line
* m - line that starts with quotation marker '>'
* s - splitter line
* t - presumably lines from the last message in the conversation
>>> mark_message_lines(['answer', 'From: foo@bar.com', '', '> question'])
'tsem' | [
"Mark",
"message",
"lines",
"with",
"markers",
"to",
"distinguish",
"quotation",
"lines",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L232-L271 |
226,986 | mailgun/talon | talon/quotations.py | process_marked_lines | def process_marked_lines(lines, markers, return_flags=[False, -1, -1]):
"""Run regexes against message's marked lines to strip quotations.
Return only last message lines.
>>> mark_message_lines(['Hello', 'From: foo@bar.com', '', '> Hi', 'tsem'])
['Hello']
Also returns return_flags.
return_flags = [were_lines_deleted, first_deleted_line,
last_deleted_line]
"""
markers = ''.join(markers)
# if there are no splitter there should be no markers
if 's' not in markers and not re.search('(me*){3}', markers):
markers = markers.replace('m', 't')
if re.match('[te]*f', markers):
return_flags[:] = [False, -1, -1]
return lines
# inlined reply
# use lookbehind assertions to find overlapping entries e.g. for 'mtmtm'
# both 't' entries should be found
for inline_reply in re.finditer('(?<=m)e*(t[te]*)m', markers):
# long links could break sequence of quotation lines but they shouldn't
# be considered an inline reply
links = (
RE_PARENTHESIS_LINK.search(lines[inline_reply.start() - 1]) or
RE_PARENTHESIS_LINK.match(lines[inline_reply.start()].strip()))
if not links:
return_flags[:] = [False, -1, -1]
return lines
# cut out text lines coming after splitter if there are no markers there
quotation = re.search('(se*)+((t|f)+e*)+', markers)
if quotation:
return_flags[:] = [True, quotation.start(), len(lines)]
return lines[:quotation.start()]
# handle the case with markers
quotation = (RE_QUOTATION.search(markers) or
RE_EMPTY_QUOTATION.search(markers))
if quotation:
return_flags[:] = True, quotation.start(1), quotation.end(1)
return lines[:quotation.start(1)] + lines[quotation.end(1):]
return_flags[:] = [False, -1, -1]
return lines | python | def process_marked_lines(lines, markers, return_flags=[False, -1, -1]):
markers = ''.join(markers)
# if there are no splitter there should be no markers
if 's' not in markers and not re.search('(me*){3}', markers):
markers = markers.replace('m', 't')
if re.match('[te]*f', markers):
return_flags[:] = [False, -1, -1]
return lines
# inlined reply
# use lookbehind assertions to find overlapping entries e.g. for 'mtmtm'
# both 't' entries should be found
for inline_reply in re.finditer('(?<=m)e*(t[te]*)m', markers):
# long links could break sequence of quotation lines but they shouldn't
# be considered an inline reply
links = (
RE_PARENTHESIS_LINK.search(lines[inline_reply.start() - 1]) or
RE_PARENTHESIS_LINK.match(lines[inline_reply.start()].strip()))
if not links:
return_flags[:] = [False, -1, -1]
return lines
# cut out text lines coming after splitter if there are no markers there
quotation = re.search('(se*)+((t|f)+e*)+', markers)
if quotation:
return_flags[:] = [True, quotation.start(), len(lines)]
return lines[:quotation.start()]
# handle the case with markers
quotation = (RE_QUOTATION.search(markers) or
RE_EMPTY_QUOTATION.search(markers))
if quotation:
return_flags[:] = True, quotation.start(1), quotation.end(1)
return lines[:quotation.start(1)] + lines[quotation.end(1):]
return_flags[:] = [False, -1, -1]
return lines | [
"def",
"process_marked_lines",
"(",
"lines",
",",
"markers",
",",
"return_flags",
"=",
"[",
"False",
",",
"-",
"1",
",",
"-",
"1",
"]",
")",
":",
"markers",
"=",
"''",
".",
"join",
"(",
"markers",
")",
"# if there are no splitter there should be no markers",
... | Run regexes against message's marked lines to strip quotations.
Return only last message lines.
>>> mark_message_lines(['Hello', 'From: foo@bar.com', '', '> Hi', 'tsem'])
['Hello']
Also returns return_flags.
return_flags = [were_lines_deleted, first_deleted_line,
last_deleted_line] | [
"Run",
"regexes",
"against",
"message",
"s",
"marked",
"lines",
"to",
"strip",
"quotations",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L274-L322 |
226,987 | mailgun/talon | talon/quotations.py | preprocess | def preprocess(msg_body, delimiter, content_type='text/plain'):
"""Prepares msg_body for being stripped.
Replaces link brackets so that they couldn't be taken for quotation marker.
Splits line in two if splitter pattern preceded by some text on the same
line (done only for 'On <date> <person> wrote:' pattern).
Converts msg_body into a unicode.
"""
msg_body = _replace_link_brackets(msg_body)
msg_body = _wrap_splitter_with_newline(msg_body, delimiter, content_type)
return msg_body | python | def preprocess(msg_body, delimiter, content_type='text/plain'):
msg_body = _replace_link_brackets(msg_body)
msg_body = _wrap_splitter_with_newline(msg_body, delimiter, content_type)
return msg_body | [
"def",
"preprocess",
"(",
"msg_body",
",",
"delimiter",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"msg_body",
"=",
"_replace_link_brackets",
"(",
"msg_body",
")",
"msg_body",
"=",
"_wrap_splitter_with_newline",
"(",
"msg_body",
",",
"delimiter",
",",
"co... | Prepares msg_body for being stripped.
Replaces link brackets so that they couldn't be taken for quotation marker.
Splits line in two if splitter pattern preceded by some text on the same
line (done only for 'On <date> <person> wrote:' pattern).
Converts msg_body into a unicode. | [
"Prepares",
"msg_body",
"for",
"being",
"stripped",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L325-L338 |
226,988 | mailgun/talon | talon/quotations.py | extract_from_plain | def extract_from_plain(msg_body):
"""Extracts a non quoted message from provided plain text."""
stripped_text = msg_body
delimiter = get_delimiter(msg_body)
msg_body = preprocess(msg_body, delimiter)
# don't process too long messages
lines = msg_body.splitlines()[:MAX_LINES_COUNT]
markers = mark_message_lines(lines)
lines = process_marked_lines(lines, markers)
# concatenate lines, change links back, strip and return
msg_body = delimiter.join(lines)
msg_body = postprocess(msg_body)
return msg_body | python | def extract_from_plain(msg_body):
stripped_text = msg_body
delimiter = get_delimiter(msg_body)
msg_body = preprocess(msg_body, delimiter)
# don't process too long messages
lines = msg_body.splitlines()[:MAX_LINES_COUNT]
markers = mark_message_lines(lines)
lines = process_marked_lines(lines, markers)
# concatenate lines, change links back, strip and return
msg_body = delimiter.join(lines)
msg_body = postprocess(msg_body)
return msg_body | [
"def",
"extract_from_plain",
"(",
"msg_body",
")",
":",
"stripped_text",
"=",
"msg_body",
"delimiter",
"=",
"get_delimiter",
"(",
"msg_body",
")",
"msg_body",
"=",
"preprocess",
"(",
"msg_body",
",",
"delimiter",
")",
"# don't process too long messages",
"lines",
"=... | Extracts a non quoted message from provided plain text. | [
"Extracts",
"a",
"non",
"quoted",
"message",
"from",
"provided",
"plain",
"text",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L389-L403 |
226,989 | mailgun/talon | talon/quotations.py | _mark_quoted_email_splitlines | def _mark_quoted_email_splitlines(markers, lines):
"""
When there are headers indented with '>' characters, this method will
attempt to identify if the header is a splitline header. If it is, then we
mark it with 's' instead of leaving it as 'm' and return the new markers.
"""
# Create a list of markers to easily alter specific characters
markerlist = list(markers)
for i, line in enumerate(lines):
if markerlist[i] != 'm':
continue
for pattern in SPLITTER_PATTERNS:
matcher = re.search(pattern, line)
if matcher:
markerlist[i] = 's'
break
return "".join(markerlist) | python | def _mark_quoted_email_splitlines(markers, lines):
# Create a list of markers to easily alter specific characters
markerlist = list(markers)
for i, line in enumerate(lines):
if markerlist[i] != 'm':
continue
for pattern in SPLITTER_PATTERNS:
matcher = re.search(pattern, line)
if matcher:
markerlist[i] = 's'
break
return "".join(markerlist) | [
"def",
"_mark_quoted_email_splitlines",
"(",
"markers",
",",
"lines",
")",
":",
"# Create a list of markers to easily alter specific characters",
"markerlist",
"=",
"list",
"(",
"markers",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if"... | When there are headers indented with '>' characters, this method will
attempt to identify if the header is a splitline header. If it is, then we
mark it with 's' instead of leaving it as 'm' and return the new markers. | [
"When",
"there",
"are",
"headers",
"indented",
"with",
">",
"characters",
"this",
"method",
"will",
"attempt",
"to",
"identify",
"if",
"the",
"header",
"is",
"a",
"splitline",
"header",
".",
"If",
"it",
"is",
"then",
"we",
"mark",
"it",
"with",
"s",
"ins... | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L547-L564 |
226,990 | mailgun/talon | talon/quotations.py | _correct_splitlines_in_headers | def _correct_splitlines_in_headers(markers, lines):
"""
Corrects markers by removing splitlines deemed to be inside header blocks.
"""
updated_markers = ""
i = 0
in_header_block = False
for m in markers:
# Only set in_header_block flag when we hit an 's' and line is a header
if m == 's':
if not in_header_block:
if bool(re.search(RE_HEADER, lines[i])):
in_header_block = True
else:
if QUOT_PATTERN.match(lines[i]):
m = 'm'
else:
m = 't'
# If the line is not a header line, set in_header_block false.
if not bool(re.search(RE_HEADER, lines[i])):
in_header_block = False
# Add the marker to the new updated markers string.
updated_markers += m
i += 1
return updated_markers | python | def _correct_splitlines_in_headers(markers, lines):
updated_markers = ""
i = 0
in_header_block = False
for m in markers:
# Only set in_header_block flag when we hit an 's' and line is a header
if m == 's':
if not in_header_block:
if bool(re.search(RE_HEADER, lines[i])):
in_header_block = True
else:
if QUOT_PATTERN.match(lines[i]):
m = 'm'
else:
m = 't'
# If the line is not a header line, set in_header_block false.
if not bool(re.search(RE_HEADER, lines[i])):
in_header_block = False
# Add the marker to the new updated markers string.
updated_markers += m
i += 1
return updated_markers | [
"def",
"_correct_splitlines_in_headers",
"(",
"markers",
",",
"lines",
")",
":",
"updated_markers",
"=",
"\"\"",
"i",
"=",
"0",
"in_header_block",
"=",
"False",
"for",
"m",
"in",
"markers",
":",
"# Only set in_header_block flag when we hit an 's' and line is a header",
... | Corrects markers by removing splitlines deemed to be inside header blocks. | [
"Corrects",
"markers",
"by",
"removing",
"splitlines",
"deemed",
"to",
"be",
"inside",
"header",
"blocks",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L567-L594 |
226,991 | mailgun/talon | talon/quotations.py | is_splitter | def is_splitter(line):
'''
Returns Matcher object if provided string is a splitter and
None otherwise.
'''
for pattern in SPLITTER_PATTERNS:
matcher = re.match(pattern, line)
if matcher:
return matcher | python | def is_splitter(line):
'''
Returns Matcher object if provided string is a splitter and
None otherwise.
'''
for pattern in SPLITTER_PATTERNS:
matcher = re.match(pattern, line)
if matcher:
return matcher | [
"def",
"is_splitter",
"(",
"line",
")",
":",
"for",
"pattern",
"in",
"SPLITTER_PATTERNS",
":",
"matcher",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"line",
")",
"if",
"matcher",
":",
"return",
"matcher"
] | Returns Matcher object if provided string is a splitter and
None otherwise. | [
"Returns",
"Matcher",
"object",
"if",
"provided",
"string",
"is",
"a",
"splitter",
"and",
"None",
"otherwise",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/quotations.py#L601-L609 |
226,992 | mailgun/talon | talon/signature/extraction.py | is_signature_line | def is_signature_line(line, sender, classifier):
'''Checks if the line belongs to signature. Returns True or False.'''
data = numpy.array(build_pattern(line, features(sender))).reshape(1, -1)
return classifier.predict(data) > 0 | python | def is_signature_line(line, sender, classifier):
'''Checks if the line belongs to signature. Returns True or False.'''
data = numpy.array(build_pattern(line, features(sender))).reshape(1, -1)
return classifier.predict(data) > 0 | [
"def",
"is_signature_line",
"(",
"line",
",",
"sender",
",",
"classifier",
")",
":",
"data",
"=",
"numpy",
".",
"array",
"(",
"build_pattern",
"(",
"line",
",",
"features",
"(",
"sender",
")",
")",
")",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
... | Checks if the line belongs to signature. Returns True or False. | [
"Checks",
"if",
"the",
"line",
"belongs",
"to",
"signature",
".",
"Returns",
"True",
"or",
"False",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/extraction.py#L33-L36 |
226,993 | mailgun/talon | talon/signature/extraction.py | extract | def extract(body, sender):
"""Strips signature from the body of the message.
Returns stripped body and signature as a tuple.
If no signature is found the corresponding returned value is None.
"""
try:
delimiter = get_delimiter(body)
body = body.strip()
if has_signature(body, sender):
lines = body.splitlines()
markers = _mark_lines(lines, sender)
text, signature = _process_marked_lines(lines, markers)
if signature:
text = delimiter.join(text)
if text.strip():
return (text, delimiter.join(signature))
except Exception as e:
log.exception('ERROR when extracting signature with classifiers')
return (body, None) | python | def extract(body, sender):
try:
delimiter = get_delimiter(body)
body = body.strip()
if has_signature(body, sender):
lines = body.splitlines()
markers = _mark_lines(lines, sender)
text, signature = _process_marked_lines(lines, markers)
if signature:
text = delimiter.join(text)
if text.strip():
return (text, delimiter.join(signature))
except Exception as e:
log.exception('ERROR when extracting signature with classifiers')
return (body, None) | [
"def",
"extract",
"(",
"body",
",",
"sender",
")",
":",
"try",
":",
"delimiter",
"=",
"get_delimiter",
"(",
"body",
")",
"body",
"=",
"body",
".",
"strip",
"(",
")",
"if",
"has_signature",
"(",
"body",
",",
"sender",
")",
":",
"lines",
"=",
"body",
... | Strips signature from the body of the message.
Returns stripped body and signature as a tuple.
If no signature is found the corresponding returned value is None. | [
"Strips",
"signature",
"from",
"the",
"body",
"of",
"the",
"message",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/extraction.py#L39-L63 |
226,994 | mailgun/talon | talon/signature/extraction.py | _mark_lines | def _mark_lines(lines, sender):
"""Mark message lines with markers to distinguish signature lines.
Markers:
* e - empty line
* s - line identified as signature
* t - other i.e. ordinary text line
>>> mark_message_lines(['Some text', '', 'Bob'], 'Bob')
'tes'
"""
global EXTRACTOR
candidate = get_signature_candidate(lines)
# at first consider everything to be text no signature
markers = list('t' * len(lines))
# mark lines starting from bottom up
# mark only lines that belong to candidate
# no need to mark all lines of the message
for i, line in reversed(list(enumerate(candidate))):
# markers correspond to lines not candidate
# so we need to recalculate our index to be
# relative to lines not candidate
j = len(lines) - len(candidate) + i
if not line.strip():
markers[j] = 'e'
elif is_signature_line(line, sender, EXTRACTOR):
markers[j] = 's'
return "".join(markers) | python | def _mark_lines(lines, sender):
global EXTRACTOR
candidate = get_signature_candidate(lines)
# at first consider everything to be text no signature
markers = list('t' * len(lines))
# mark lines starting from bottom up
# mark only lines that belong to candidate
# no need to mark all lines of the message
for i, line in reversed(list(enumerate(candidate))):
# markers correspond to lines not candidate
# so we need to recalculate our index to be
# relative to lines not candidate
j = len(lines) - len(candidate) + i
if not line.strip():
markers[j] = 'e'
elif is_signature_line(line, sender, EXTRACTOR):
markers[j] = 's'
return "".join(markers) | [
"def",
"_mark_lines",
"(",
"lines",
",",
"sender",
")",
":",
"global",
"EXTRACTOR",
"candidate",
"=",
"get_signature_candidate",
"(",
"lines",
")",
"# at first consider everything to be text no signature",
"markers",
"=",
"list",
"(",
"'t'",
"*",
"len",
"(",
"lines"... | Mark message lines with markers to distinguish signature lines.
Markers:
* e - empty line
* s - line identified as signature
* t - other i.e. ordinary text line
>>> mark_message_lines(['Some text', '', 'Bob'], 'Bob')
'tes' | [
"Mark",
"message",
"lines",
"with",
"markers",
"to",
"distinguish",
"signature",
"lines",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/extraction.py#L66-L98 |
226,995 | mailgun/talon | talon/signature/extraction.py | _process_marked_lines | def _process_marked_lines(lines, markers):
"""Run regexes against message's marked lines to strip signature.
>>> _process_marked_lines(['Some text', '', 'Bob'], 'tes')
(['Some text', ''], ['Bob'])
"""
# reverse lines and match signature pattern for reversed lines
signature = RE_REVERSE_SIGNATURE.match(markers[::-1])
if signature:
return (lines[:-signature.end()], lines[-signature.end():])
return (lines, None) | python | def _process_marked_lines(lines, markers):
# reverse lines and match signature pattern for reversed lines
signature = RE_REVERSE_SIGNATURE.match(markers[::-1])
if signature:
return (lines[:-signature.end()], lines[-signature.end():])
return (lines, None) | [
"def",
"_process_marked_lines",
"(",
"lines",
",",
"markers",
")",
":",
"# reverse lines and match signature pattern for reversed lines",
"signature",
"=",
"RE_REVERSE_SIGNATURE",
".",
"match",
"(",
"markers",
"[",
":",
":",
"-",
"1",
"]",
")",
"if",
"signature",
":... | Run regexes against message's marked lines to strip signature.
>>> _process_marked_lines(['Some text', '', 'Bob'], 'tes')
(['Some text', ''], ['Bob']) | [
"Run",
"regexes",
"against",
"message",
"s",
"marked",
"lines",
"to",
"strip",
"signature",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/extraction.py#L101-L112 |
226,996 | mailgun/talon | talon/signature/learning/classifier.py | train | def train(classifier, train_data_filename, save_classifier_filename=None):
"""Trains and saves classifier so that it could be easily loaded later."""
file_data = genfromtxt(train_data_filename, delimiter=",")
train_data, labels = file_data[:, :-1], file_data[:, -1]
classifier.fit(train_data, labels)
if save_classifier_filename:
joblib.dump(classifier, save_classifier_filename)
return classifier | python | def train(classifier, train_data_filename, save_classifier_filename=None):
file_data = genfromtxt(train_data_filename, delimiter=",")
train_data, labels = file_data[:, :-1], file_data[:, -1]
classifier.fit(train_data, labels)
if save_classifier_filename:
joblib.dump(classifier, save_classifier_filename)
return classifier | [
"def",
"train",
"(",
"classifier",
",",
"train_data_filename",
",",
"save_classifier_filename",
"=",
"None",
")",
":",
"file_data",
"=",
"genfromtxt",
"(",
"train_data_filename",
",",
"delimiter",
"=",
"\",\"",
")",
"train_data",
",",
"labels",
"=",
"file_data",
... | Trains and saves classifier so that it could be easily loaded later. | [
"Trains",
"and",
"saves",
"classifier",
"so",
"that",
"it",
"could",
"be",
"easily",
"loaded",
"later",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/classifier.py#L20-L28 |
226,997 | mailgun/talon | talon/signature/learning/classifier.py | load | def load(saved_classifier_filename, train_data_filename):
"""Loads saved classifier. """
try:
return joblib.load(saved_classifier_filename)
except Exception:
import sys
if sys.version_info > (3, 0):
return load_compat(saved_classifier_filename)
raise | python | def load(saved_classifier_filename, train_data_filename):
try:
return joblib.load(saved_classifier_filename)
except Exception:
import sys
if sys.version_info > (3, 0):
return load_compat(saved_classifier_filename)
raise | [
"def",
"load",
"(",
"saved_classifier_filename",
",",
"train_data_filename",
")",
":",
"try",
":",
"return",
"joblib",
".",
"load",
"(",
"saved_classifier_filename",
")",
"except",
"Exception",
":",
"import",
"sys",
"if",
"sys",
".",
"version_info",
">",
"(",
... | Loads saved classifier. | [
"Loads",
"saved",
"classifier",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/classifier.py#L31-L40 |
226,998 | mailgun/talon | talon/signature/learning/dataset.py | parse_msg_sender | def parse_msg_sender(filename, sender_known=True):
"""Given a filename returns the sender and the message.
Here the message is assumed to be a whole MIME message or just
message body.
>>> sender, msg = parse_msg_sender('msg.eml')
>>> sender, msg = parse_msg_sender('msg_body')
If you don't want to consider the sender's name in your classification
algorithm:
>>> parse_msg_sender(filename, False)
"""
import sys
kwargs = {}
if sys.version_info > (3, 0):
kwargs["encoding"] = "utf8"
sender, msg = None, None
if os.path.isfile(filename) and not is_sender_filename(filename):
with open(filename, **kwargs) as f:
msg = f.read()
sender = u''
if sender_known:
sender_filename = build_sender_filename(filename)
if os.path.exists(sender_filename):
with open(sender_filename) as sender_file:
sender = sender_file.read().strip()
else:
# if sender isn't found then the next line fails
# and it is ok
lines = msg.splitlines()
for line in lines:
match = re.match('From:(.*)', line)
if match:
sender = match.group(1)
break
return (sender, msg) | python | def parse_msg_sender(filename, sender_known=True):
import sys
kwargs = {}
if sys.version_info > (3, 0):
kwargs["encoding"] = "utf8"
sender, msg = None, None
if os.path.isfile(filename) and not is_sender_filename(filename):
with open(filename, **kwargs) as f:
msg = f.read()
sender = u''
if sender_known:
sender_filename = build_sender_filename(filename)
if os.path.exists(sender_filename):
with open(sender_filename) as sender_file:
sender = sender_file.read().strip()
else:
# if sender isn't found then the next line fails
# and it is ok
lines = msg.splitlines()
for line in lines:
match = re.match('From:(.*)', line)
if match:
sender = match.group(1)
break
return (sender, msg) | [
"def",
"parse_msg_sender",
"(",
"filename",
",",
"sender_known",
"=",
"True",
")",
":",
"import",
"sys",
"kwargs",
"=",
"{",
"}",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
":",
"kwargs",
"[",
"\"encoding\"",
"]",
"=",
"\"utf8\"",
... | Given a filename returns the sender and the message.
Here the message is assumed to be a whole MIME message or just
message body.
>>> sender, msg = parse_msg_sender('msg.eml')
>>> sender, msg = parse_msg_sender('msg_body')
If you don't want to consider the sender's name in your classification
algorithm:
>>> parse_msg_sender(filename, False) | [
"Given",
"a",
"filename",
"returns",
"the",
"sender",
"and",
"the",
"message",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/dataset.py#L48-L85 |
226,999 | mailgun/talon | talon/signature/learning/dataset.py | build_detection_class | def build_detection_class(folder, dataset_filename,
label, sender_known=True):
"""Builds signature detection class.
Signature detection dataset includes patterns for two classes:
* class for positive patterns (goes with label 1)
* class for negative patterns (goes with label -1)
The patterns are build of emails from `folder` and appended to
dataset file.
>>> build_signature_detection_class('emails/P', 'train.data', 1)
"""
with open(dataset_filename, 'a') as dataset:
for filename in os.listdir(folder):
filename = os.path.join(folder, filename)
sender, msg = parse_msg_sender(filename, sender_known)
if sender is None or msg is None:
continue
msg = re.sub('|'.join(ANNOTATIONS), '', msg)
X = build_pattern(msg, features(sender))
X.append(label)
labeled_pattern = ','.join([str(e) for e in X])
dataset.write(labeled_pattern + '\n') | python | def build_detection_class(folder, dataset_filename,
label, sender_known=True):
with open(dataset_filename, 'a') as dataset:
for filename in os.listdir(folder):
filename = os.path.join(folder, filename)
sender, msg = parse_msg_sender(filename, sender_known)
if sender is None or msg is None:
continue
msg = re.sub('|'.join(ANNOTATIONS), '', msg)
X = build_pattern(msg, features(sender))
X.append(label)
labeled_pattern = ','.join([str(e) for e in X])
dataset.write(labeled_pattern + '\n') | [
"def",
"build_detection_class",
"(",
"folder",
",",
"dataset_filename",
",",
"label",
",",
"sender_known",
"=",
"True",
")",
":",
"with",
"open",
"(",
"dataset_filename",
",",
"'a'",
")",
"as",
"dataset",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
... | Builds signature detection class.
Signature detection dataset includes patterns for two classes:
* class for positive patterns (goes with label 1)
* class for negative patterns (goes with label -1)
The patterns are build of emails from `folder` and appended to
dataset file.
>>> build_signature_detection_class('emails/P', 'train.data', 1) | [
"Builds",
"signature",
"detection",
"class",
"."
] | cdd84563dd329c4f887591807870d10015e0c7a7 | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/dataset.py#L88-L111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.