repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
glomex/gcdt
|
gcdt/utils.py
|
dict_selective_merge
|
def dict_selective_merge(a, b, selection, path=None):
"""Conditionally merges b into a if b's keys are contained in selection
:param a:
:param b:
:param selection: limit merge to these top-level keys
:param path:
:return:
"""
if path is None:
path = []
for key in b:
if key in selection:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
dict_selective_merge(a[key], b[key], b[key].keys(), path + [str(key)])
elif a[key] != b[key]:
# update the value
a[key] = b[key]
else:
a[key] = b[key]
return a
|
python
|
def dict_selective_merge(a, b, selection, path=None):
"""Conditionally merges b into a if b's keys are contained in selection
:param a:
:param b:
:param selection: limit merge to these top-level keys
:param path:
:return:
"""
if path is None:
path = []
for key in b:
if key in selection:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
dict_selective_merge(a[key], b[key], b[key].keys(), path + [str(key)])
elif a[key] != b[key]:
# update the value
a[key] = b[key]
else:
a[key] = b[key]
return a
|
[
"def",
"dict_selective_merge",
"(",
"a",
",",
"b",
",",
"selection",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"selection",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"b",
"[",
"key",
"]",
",",
"dict",
")",
":",
"dict_selective_merge",
"(",
"a",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
".",
"keys",
"(",
")",
",",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
"elif",
"a",
"[",
"key",
"]",
"!=",
"b",
"[",
"key",
"]",
":",
"# update the value",
"a",
"[",
"key",
"]",
"=",
"b",
"[",
"key",
"]",
"else",
":",
"a",
"[",
"key",
"]",
"=",
"b",
"[",
"key",
"]",
"return",
"a"
] |
Conditionally merges b into a if b's keys are contained in selection
:param a:
:param b:
:param selection: limit merge to these top-level keys
:param path:
:return:
|
[
"Conditionally",
"merges",
"b",
"into",
"a",
"if",
"b",
"s",
"keys",
"are",
"contained",
"in",
"selection"
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L190-L211
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
dict_merge
|
def dict_merge(a, b, path=None):
"""merges b into a"""
return dict_selective_merge(a, b, b.keys(), path)
|
python
|
def dict_merge(a, b, path=None):
"""merges b into a"""
return dict_selective_merge(a, b, b.keys(), path)
|
[
"def",
"dict_merge",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"return",
"dict_selective_merge",
"(",
"a",
",",
"b",
",",
"b",
".",
"keys",
"(",
")",
",",
"path",
")"
] |
merges b into a
|
[
"merges",
"b",
"into",
"a"
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L214-L216
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
are_credentials_still_valid
|
def are_credentials_still_valid(awsclient):
"""Check whether the credentials have expired.
:param awsclient:
:return: exit_code
"""
client = awsclient.get_client('lambda')
try:
client.list_functions()
except GracefulExit:
raise
except Exception as e:
log.debug(e)
log.error(e)
return 1
return 0
|
python
|
def are_credentials_still_valid(awsclient):
"""Check whether the credentials have expired.
:param awsclient:
:return: exit_code
"""
client = awsclient.get_client('lambda')
try:
client.list_functions()
except GracefulExit:
raise
except Exception as e:
log.debug(e)
log.error(e)
return 1
return 0
|
[
"def",
"are_credentials_still_valid",
"(",
"awsclient",
")",
":",
"client",
"=",
"awsclient",
".",
"get_client",
"(",
"'lambda'",
")",
"try",
":",
"client",
".",
"list_functions",
"(",
")",
"except",
"GracefulExit",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"e",
")",
"log",
".",
"error",
"(",
"e",
")",
"return",
"1",
"return",
"0"
] |
Check whether the credentials have expired.
:param awsclient:
:return: exit_code
|
[
"Check",
"whether",
"the",
"credentials",
"have",
"expired",
"."
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L222-L237
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
flatten
|
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if isinstance(item, collections.Sequence) and not isinstance(item, basestring):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis
|
python
|
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if isinstance(item, collections.Sequence) and not isinstance(item, basestring):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis
|
[
"def",
"flatten",
"(",
"lis",
")",
":",
"new_lis",
"=",
"[",
"]",
"for",
"item",
"in",
"lis",
":",
"if",
"isinstance",
"(",
"item",
",",
"collections",
".",
"Sequence",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"new_lis",
".",
"extend",
"(",
"flatten",
"(",
"item",
")",
")",
"else",
":",
"new_lis",
".",
"append",
"(",
"item",
")",
"return",
"new_lis"
] |
Given a list, possibly nested to any level, return it flattened.
|
[
"Given",
"a",
"list",
"possibly",
"nested",
"to",
"any",
"level",
"return",
"it",
"flattened",
"."
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L241-L249
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
signal_handler
|
def signal_handler(signum, frame):
"""
handle signals.
example: 'signal.signal(signal.SIGTERM, signal_handler)'
"""
# signals are CONSTANTS so there is no mapping from signum to description
# so please add to the mapping in case you use more signals!
description = '%d' % signum
if signum == 2:
description = 'SIGINT'
elif signum == 15:
description = 'SIGTERM'
raise GracefulExit(description)
|
python
|
def signal_handler(signum, frame):
"""
handle signals.
example: 'signal.signal(signal.SIGTERM, signal_handler)'
"""
# signals are CONSTANTS so there is no mapping from signum to description
# so please add to the mapping in case you use more signals!
description = '%d' % signum
if signum == 2:
description = 'SIGINT'
elif signum == 15:
description = 'SIGTERM'
raise GracefulExit(description)
|
[
"def",
"signal_handler",
"(",
"signum",
",",
"frame",
")",
":",
"# signals are CONSTANTS so there is no mapping from signum to description",
"# so please add to the mapping in case you use more signals!",
"description",
"=",
"'%d'",
"%",
"signum",
"if",
"signum",
"==",
"2",
":",
"description",
"=",
"'SIGINT'",
"elif",
"signum",
"==",
"15",
":",
"description",
"=",
"'SIGTERM'",
"raise",
"GracefulExit",
"(",
"description",
")"
] |
handle signals.
example: 'signal.signal(signal.SIGTERM, signal_handler)'
|
[
"handle",
"signals",
".",
"example",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
"signal_handler",
")"
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L260-L272
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
json2table
|
def json2table(json):
"""This does format a dictionary into a table.
Note this expects a dictionary (not a json string!)
:param json:
:return:
"""
filter_terms = ['ResponseMetadata']
table = []
try:
for k in filter(lambda k: k not in filter_terms, json.keys()):
table.append([k.encode('ascii', 'ignore'),
str(json[k]).encode('ascii', 'ignore')])
return tabulate(table, tablefmt='fancy_grid')
except GracefulExit:
raise
except Exception as e:
log.error(e)
return json
|
python
|
def json2table(json):
"""This does format a dictionary into a table.
Note this expects a dictionary (not a json string!)
:param json:
:return:
"""
filter_terms = ['ResponseMetadata']
table = []
try:
for k in filter(lambda k: k not in filter_terms, json.keys()):
table.append([k.encode('ascii', 'ignore'),
str(json[k]).encode('ascii', 'ignore')])
return tabulate(table, tablefmt='fancy_grid')
except GracefulExit:
raise
except Exception as e:
log.error(e)
return json
|
[
"def",
"json2table",
"(",
"json",
")",
":",
"filter_terms",
"=",
"[",
"'ResponseMetadata'",
"]",
"table",
"=",
"[",
"]",
"try",
":",
"for",
"k",
"in",
"filter",
"(",
"lambda",
"k",
":",
"k",
"not",
"in",
"filter_terms",
",",
"json",
".",
"keys",
"(",
")",
")",
":",
"table",
".",
"append",
"(",
"[",
"k",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
",",
"str",
"(",
"json",
"[",
"k",
"]",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"]",
")",
"return",
"tabulate",
"(",
"table",
",",
"tablefmt",
"=",
"'fancy_grid'",
")",
"except",
"GracefulExit",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"e",
")",
"return",
"json"
] |
This does format a dictionary into a table.
Note this expects a dictionary (not a json string!)
:param json:
:return:
|
[
"This",
"does",
"format",
"a",
"dictionary",
"into",
"a",
"table",
".",
"Note",
"this",
"expects",
"a",
"dictionary",
"(",
"not",
"a",
"json",
"string!",
")"
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L275-L293
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
random_string
|
def random_string(length=6):
"""Create a random 6 character string.
note: in case you use this function in a test during test together with
an awsclient then this function is altered so you get reproducible results
that will work with your recorded placebo json files (see helpers_aws.py).
"""
return ''.join([random.choice(string.ascii_lowercase) for i in range(length)])
|
python
|
def random_string(length=6):
"""Create a random 6 character string.
note: in case you use this function in a test during test together with
an awsclient then this function is altered so you get reproducible results
that will work with your recorded placebo json files (see helpers_aws.py).
"""
return ''.join([random.choice(string.ascii_lowercase) for i in range(length)])
|
[
"def",
"random_string",
"(",
"length",
"=",
"6",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_lowercase",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
"]",
")"
] |
Create a random 6 character string.
note: in case you use this function in a test during test together with
an awsclient then this function is altered so you get reproducible results
that will work with your recorded placebo json files (see helpers_aws.py).
|
[
"Create",
"a",
"random",
"6",
"character",
"string",
"."
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L316-L323
|
train
|
glomex/gcdt
|
gcdt/utils.py
|
all_pages
|
def all_pages(method, request, accessor, cond=None):
"""Helper to process all pages using botocore service methods (exhausts NextToken).
note: `cond` is optional... you can use it to make filtering more explicit
if you like. Alternatively you can do the filtering in the `accessor` which
is perfectly fine, too
Note: lambda uses a slightly different mechanism so there is a specific version in
ramuda_utils.
:param method: service method
:param request: request dictionary for service call
:param accessor: function to extract data from each response
:param cond: filter function to return True / False based on a response
:return: list of collected resources
"""
if cond is None:
cond = lambda x: True
result = []
next_token = None
while True:
if next_token:
request['nextToken'] = next_token
response = method(**request)
if cond(response):
data = accessor(response)
if data:
if isinstance(data, list):
result.extend(data)
else:
result.append(data)
if 'nextToken' not in response:
break
next_token = response['nextToken']
return result
|
python
|
def all_pages(method, request, accessor, cond=None):
"""Helper to process all pages using botocore service methods (exhausts NextToken).
note: `cond` is optional... you can use it to make filtering more explicit
if you like. Alternatively you can do the filtering in the `accessor` which
is perfectly fine, too
Note: lambda uses a slightly different mechanism so there is a specific version in
ramuda_utils.
:param method: service method
:param request: request dictionary for service call
:param accessor: function to extract data from each response
:param cond: filter function to return True / False based on a response
:return: list of collected resources
"""
if cond is None:
cond = lambda x: True
result = []
next_token = None
while True:
if next_token:
request['nextToken'] = next_token
response = method(**request)
if cond(response):
data = accessor(response)
if data:
if isinstance(data, list):
result.extend(data)
else:
result.append(data)
if 'nextToken' not in response:
break
next_token = response['nextToken']
return result
|
[
"def",
"all_pages",
"(",
"method",
",",
"request",
",",
"accessor",
",",
"cond",
"=",
"None",
")",
":",
"if",
"cond",
"is",
"None",
":",
"cond",
"=",
"lambda",
"x",
":",
"True",
"result",
"=",
"[",
"]",
"next_token",
"=",
"None",
"while",
"True",
":",
"if",
"next_token",
":",
"request",
"[",
"'nextToken'",
"]",
"=",
"next_token",
"response",
"=",
"method",
"(",
"*",
"*",
"request",
")",
"if",
"cond",
"(",
"response",
")",
":",
"data",
"=",
"accessor",
"(",
"response",
")",
"if",
"data",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"result",
".",
"extend",
"(",
"data",
")",
"else",
":",
"result",
".",
"append",
"(",
"data",
")",
"if",
"'nextToken'",
"not",
"in",
"response",
":",
"break",
"next_token",
"=",
"response",
"[",
"'nextToken'",
"]",
"return",
"result"
] |
Helper to process all pages using botocore service methods (exhausts NextToken).
note: `cond` is optional... you can use it to make filtering more explicit
if you like. Alternatively you can do the filtering in the `accessor` which
is perfectly fine, too
Note: lambda uses a slightly different mechanism so there is a specific version in
ramuda_utils.
:param method: service method
:param request: request dictionary for service call
:param accessor: function to extract data from each response
:param cond: filter function to return True / False based on a response
:return: list of collected resources
|
[
"Helper",
"to",
"process",
"all",
"pages",
"using",
"botocore",
"service",
"methods",
"(",
"exhausts",
"NextToken",
")",
".",
"note",
":",
"cond",
"is",
"optional",
"...",
"you",
"can",
"use",
"it",
"to",
"make",
"filtering",
"more",
"explicit",
"if",
"you",
"like",
".",
"Alternatively",
"you",
"can",
"do",
"the",
"filtering",
"in",
"the",
"accessor",
"which",
"is",
"perfectly",
"fine",
"too",
"Note",
":",
"lambda",
"uses",
"a",
"slightly",
"different",
"mechanism",
"so",
"there",
"is",
"a",
"specific",
"version",
"in",
"ramuda_utils",
"."
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L336-L369
|
train
|
clarkperkins/click-shell
|
click_shell/core.py
|
get_invoke
|
def get_invoke(command):
"""
Get the Cmd main method from the click command
:param command: The click Command object
:return: the do_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def invoke_(self, arg): # pylint: disable=unused-argument
try:
command.main(args=shlex.split(arg),
prog_name=command.name,
standalone_mode=False,
parent=self.ctx)
except click.ClickException as e:
# Show the error message
e.show()
except click.Abort:
# We got an EOF or Keyboard interrupt. Just silence it
pass
except SystemExit:
# Catch this an return the code instead. All of click's help commands do a sys.exit(),
# and that's not ideal when running in a shell.
pass
except Exception as e:
traceback.print_exception(type(e), e, None)
logger.warning(traceback.format_exc())
# Always return False so the shell doesn't exit
return False
invoke_ = update_wrapper(invoke_, command.callback)
invoke_.__name__ = 'do_%s' % command.name
return invoke_
|
python
|
def get_invoke(command):
"""
Get the Cmd main method from the click command
:param command: The click Command object
:return: the do_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def invoke_(self, arg): # pylint: disable=unused-argument
try:
command.main(args=shlex.split(arg),
prog_name=command.name,
standalone_mode=False,
parent=self.ctx)
except click.ClickException as e:
# Show the error message
e.show()
except click.Abort:
# We got an EOF or Keyboard interrupt. Just silence it
pass
except SystemExit:
# Catch this an return the code instead. All of click's help commands do a sys.exit(),
# and that's not ideal when running in a shell.
pass
except Exception as e:
traceback.print_exception(type(e), e, None)
logger.warning(traceback.format_exc())
# Always return False so the shell doesn't exit
return False
invoke_ = update_wrapper(invoke_, command.callback)
invoke_.__name__ = 'do_%s' % command.name
return invoke_
|
[
"def",
"get_invoke",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"click",
".",
"Command",
")",
"def",
"invoke_",
"(",
"self",
",",
"arg",
")",
":",
"# pylint: disable=unused-argument",
"try",
":",
"command",
".",
"main",
"(",
"args",
"=",
"shlex",
".",
"split",
"(",
"arg",
")",
",",
"prog_name",
"=",
"command",
".",
"name",
",",
"standalone_mode",
"=",
"False",
",",
"parent",
"=",
"self",
".",
"ctx",
")",
"except",
"click",
".",
"ClickException",
"as",
"e",
":",
"# Show the error message",
"e",
".",
"show",
"(",
")",
"except",
"click",
".",
"Abort",
":",
"# We got an EOF or Keyboard interrupt. Just silence it",
"pass",
"except",
"SystemExit",
":",
"# Catch this an return the code instead. All of click's help commands do a sys.exit(),",
"# and that's not ideal when running in a shell.",
"pass",
"except",
"Exception",
"as",
"e",
":",
"traceback",
".",
"print_exception",
"(",
"type",
"(",
"e",
")",
",",
"e",
",",
"None",
")",
"logger",
".",
"warning",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"# Always return False so the shell doesn't exit",
"return",
"False",
"invoke_",
"=",
"update_wrapper",
"(",
"invoke_",
",",
"command",
".",
"callback",
")",
"invoke_",
".",
"__name__",
"=",
"'do_%s'",
"%",
"command",
".",
"name",
"return",
"invoke_"
] |
Get the Cmd main method from the click command
:param command: The click Command object
:return: the do_* method for Cmd
:rtype: function
|
[
"Get",
"the",
"Cmd",
"main",
"method",
"from",
"the",
"click",
"command",
":",
"param",
"command",
":",
"The",
"click",
"Command",
"object",
":",
"return",
":",
"the",
"do_",
"*",
"method",
"for",
"Cmd",
":",
"rtype",
":",
"function"
] |
8d6e1a492176bc79e029d714f19d3156409656ea
|
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L21-L56
|
train
|
clarkperkins/click-shell
|
click_shell/core.py
|
get_help
|
def get_help(command):
"""
Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def help_(self): # pylint: disable=unused-argument
extra = {}
for key, value in command.context_settings.items():
if key not in extra:
extra[key] = value
# Print click's help message
with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx:
click.echo(ctx.get_help(), color=ctx.color)
help_.__name__ = 'help_%s' % command.name
return help_
|
python
|
def get_help(command):
"""
Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def help_(self): # pylint: disable=unused-argument
extra = {}
for key, value in command.context_settings.items():
if key not in extra:
extra[key] = value
# Print click's help message
with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx:
click.echo(ctx.get_help(), color=ctx.color)
help_.__name__ = 'help_%s' % command.name
return help_
|
[
"def",
"get_help",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"click",
".",
"Command",
")",
"def",
"help_",
"(",
"self",
")",
":",
"# pylint: disable=unused-argument",
"extra",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"command",
".",
"context_settings",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"extra",
":",
"extra",
"[",
"key",
"]",
"=",
"value",
"# Print click's help message",
"with",
"click",
".",
"Context",
"(",
"command",
",",
"info_name",
"=",
"command",
".",
"name",
",",
"parent",
"=",
"self",
".",
"ctx",
",",
"*",
"*",
"extra",
")",
"as",
"ctx",
":",
"click",
".",
"echo",
"(",
"ctx",
".",
"get_help",
"(",
")",
",",
"color",
"=",
"ctx",
".",
"color",
")",
"help_",
".",
"__name__",
"=",
"'help_%s'",
"%",
"command",
".",
"name",
"return",
"help_"
] |
Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function
|
[
"Get",
"the",
"Cmd",
"help",
"function",
"from",
"the",
"click",
"command",
":",
"param",
"command",
":",
"The",
"click",
"Command",
"object",
":",
"return",
":",
"the",
"help_",
"*",
"method",
"for",
"Cmd",
":",
"rtype",
":",
"function"
] |
8d6e1a492176bc79e029d714f19d3156409656ea
|
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L59-L79
|
train
|
clarkperkins/click-shell
|
click_shell/core.py
|
get_complete
|
def get_complete(command):
"""
Get the Cmd complete function for the click command
:param command: The click Command object
:return: the complete_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def complete_(self, text, line, begidx, endidx): # pylint: disable=unused-argument
# Parse the args
args = shlex.split(line[:begidx])
# Strip of the first item which is the name of the command
args = args[1:]
# Then pass them on to the get_choices method that click uses for completion
return list(get_choices(command, command.name, args, text))
complete_.__name__ = 'complete_%s' % command.name
return complete_
|
python
|
def get_complete(command):
"""
Get the Cmd complete function for the click command
:param command: The click Command object
:return: the complete_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def complete_(self, text, line, begidx, endidx): # pylint: disable=unused-argument
# Parse the args
args = shlex.split(line[:begidx])
# Strip of the first item which is the name of the command
args = args[1:]
# Then pass them on to the get_choices method that click uses for completion
return list(get_choices(command, command.name, args, text))
complete_.__name__ = 'complete_%s' % command.name
return complete_
|
[
"def",
"get_complete",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"click",
".",
"Command",
")",
"def",
"complete_",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"# pylint: disable=unused-argument",
"# Parse the args",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
"[",
":",
"begidx",
"]",
")",
"# Strip of the first item which is the name of the command",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"# Then pass them on to the get_choices method that click uses for completion",
"return",
"list",
"(",
"get_choices",
"(",
"command",
",",
"command",
".",
"name",
",",
"args",
",",
"text",
")",
")",
"complete_",
".",
"__name__",
"=",
"'complete_%s'",
"%",
"command",
".",
"name",
"return",
"complete_"
] |
Get the Cmd complete function for the click command
:param command: The click Command object
:return: the complete_* method for Cmd
:rtype: function
|
[
"Get",
"the",
"Cmd",
"complete",
"function",
"for",
"the",
"click",
"command",
":",
"param",
"command",
":",
"The",
"click",
"Command",
"object",
":",
"return",
":",
"the",
"complete_",
"*",
"method",
"for",
"Cmd",
":",
"rtype",
":",
"function"
] |
8d6e1a492176bc79e029d714f19d3156409656ea
|
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L82-L102
|
train
|
glomex/gcdt
|
gcdt/kumo_main.py
|
load_template
|
def load_template():
"""Bail out if template is not found.
"""
cloudformation, found = load_cloudformation_template()
if not found:
print(colored.red('could not load cloudformation.py, bailing out...'))
sys.exit(1)
return cloudformation
|
python
|
def load_template():
"""Bail out if template is not found.
"""
cloudformation, found = load_cloudformation_template()
if not found:
print(colored.red('could not load cloudformation.py, bailing out...'))
sys.exit(1)
return cloudformation
|
[
"def",
"load_template",
"(",
")",
":",
"cloudformation",
",",
"found",
"=",
"load_cloudformation_template",
"(",
")",
"if",
"not",
"found",
":",
"print",
"(",
"colored",
".",
"red",
"(",
"'could not load cloudformation.py, bailing out...'",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"cloudformation"
] |
Bail out if template is not found.
|
[
"Bail",
"out",
"if",
"template",
"is",
"not",
"found",
"."
] |
cd67cf416371337b83cb9ca3f696277125703339
|
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_main.py#L49-L56
|
train
|
ramses-tech/nefertari
|
nefertari/engine.py
|
_import_public_names
|
def _import_public_names(module):
"Import public names from module into this module, like import *"
self = sys.modules[__name__]
for name in module.__all__:
if hasattr(self, name):
# don't overwrite existing names
continue
setattr(self, name, getattr(module, name))
|
python
|
def _import_public_names(module):
"Import public names from module into this module, like import *"
self = sys.modules[__name__]
for name in module.__all__:
if hasattr(self, name):
# don't overwrite existing names
continue
setattr(self, name, getattr(module, name))
|
[
"def",
"_import_public_names",
"(",
"module",
")",
":",
"self",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"for",
"name",
"in",
"module",
".",
"__all__",
":",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"# don't overwrite existing names",
"continue",
"setattr",
"(",
"self",
",",
"name",
",",
"getattr",
"(",
"module",
",",
"name",
")",
")"
] |
Import public names from module into this module, like import *
|
[
"Import",
"public",
"names",
"from",
"module",
"into",
"this",
"module",
"like",
"import",
"*"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/engine.py#L59-L66
|
train
|
scalative/haas
|
haas/haas_application.py
|
create_argument_parser
|
def create_argument_parser():
"""Creates the argument parser for haas.
"""
parser = argparse.ArgumentParser(prog='haas')
parser.add_argument('--version', action='version',
version='%(prog)s {0}'.format(haas.__version__))
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument('-v', '--verbose', action='store_const', default=1,
dest='verbosity', const=2, help='Verbose output')
verbosity.add_argument('-q', '--quiet', action='store_const', const=0,
dest='verbosity', help='Quiet output')
parser.add_argument('-f', '--failfast', action='store_true', default=False,
help='Stop on first fail or error')
parser.add_argument('-c', '--catch', dest='catch_interrupt',
action='store_true', default=False,
help=('(Ignored) Catch ctrl-C and display results so '
'far'))
parser.add_argument('-b', '--buffer', action='store_true', default=False,
help='Buffer stdout and stderr during tests')
parser.add_argument(
'start', nargs='*', default=[os.getcwd()],
help=('One or more directories or dotted package/module names from '
'which to start searching for tests'))
parser.add_argument('-p', '--pattern', default='test*.py',
help="Pattern to match tests ('test*.py' default)")
parser.add_argument('-t', '--top-level-directory', default=None,
help=('Top level directory of project (defaults to '
'start directory)'))
_add_log_level_option(parser)
return parser
|
python
|
def create_argument_parser():
"""Creates the argument parser for haas.
"""
parser = argparse.ArgumentParser(prog='haas')
parser.add_argument('--version', action='version',
version='%(prog)s {0}'.format(haas.__version__))
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument('-v', '--verbose', action='store_const', default=1,
dest='verbosity', const=2, help='Verbose output')
verbosity.add_argument('-q', '--quiet', action='store_const', const=0,
dest='verbosity', help='Quiet output')
parser.add_argument('-f', '--failfast', action='store_true', default=False,
help='Stop on first fail or error')
parser.add_argument('-c', '--catch', dest='catch_interrupt',
action='store_true', default=False,
help=('(Ignored) Catch ctrl-C and display results so '
'far'))
parser.add_argument('-b', '--buffer', action='store_true', default=False,
help='Buffer stdout and stderr during tests')
parser.add_argument(
'start', nargs='*', default=[os.getcwd()],
help=('One or more directories or dotted package/module names from '
'which to start searching for tests'))
parser.add_argument('-p', '--pattern', default='test*.py',
help="Pattern to match tests ('test*.py' default)")
parser.add_argument('-t', '--top-level-directory', default=None,
help=('Top level directory of project (defaults to '
'start directory)'))
_add_log_level_option(parser)
return parser
|
[
"def",
"create_argument_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'haas'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s {0}'",
".",
"format",
"(",
"haas",
".",
"__version__",
")",
")",
"verbosity",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"verbosity",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_const'",
",",
"default",
"=",
"1",
",",
"dest",
"=",
"'verbosity'",
",",
"const",
"=",
"2",
",",
"help",
"=",
"'Verbose output'",
")",
"verbosity",
".",
"add_argument",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"0",
",",
"dest",
"=",
"'verbosity'",
",",
"help",
"=",
"'Quiet output'",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--failfast'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Stop on first fail or error'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--catch'",
",",
"dest",
"=",
"'catch_interrupt'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"(",
"'(Ignored) Catch ctrl-C and display results so '",
"'far'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-b'",
",",
"'--buffer'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Buffer stdout and stderr during tests'",
")",
"parser",
".",
"add_argument",
"(",
"'start'",
",",
"nargs",
"=",
"'*'",
",",
"default",
"=",
"[",
"os",
".",
"getcwd",
"(",
")",
"]",
",",
"help",
"=",
"(",
"'One or more directories or dotted package/module names from '",
"'which to start searching for tests'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--pattern'",
",",
"default",
"=",
"'test*.py'",
",",
"help",
"=",
"\"Pattern to match tests ('test*.py' default)\"",
")",
"parser",
".",
"add_argument",
"(",
"'-t'",
",",
"'--top-level-directory'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"(",
"'Top level directory of project (defaults to '",
"'start directory)'",
")",
")",
"_add_log_level_option",
"(",
"parser",
")",
"return",
"parser"
] |
Creates the argument parser for haas.
|
[
"Creates",
"the",
"argument",
"parser",
"for",
"haas",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/haas_application.py#L20-L50
|
train
|
scalative/haas
|
haas/haas_application.py
|
HaasApplication.run
|
def run(self, plugin_manager=None):
"""Run the haas test runner.
This will load and configure the selected plugins, set up the
environment and begin test discovery, loading and running.
Parameters
----------
plugin_manager : haas.plugin_manager.PluginManager
[Optional] Override the use of the default plugin manager.
"""
if plugin_manager is None:
plugin_manager = PluginManager()
plugin_manager.add_plugin_arguments(self.parser)
args = self.parser.parse_args(self.argv[1:])
environment_plugins = plugin_manager.get_enabled_hook_plugins(
plugin_manager.ENVIRONMENT_HOOK, args)
runner = plugin_manager.get_driver(
plugin_manager.TEST_RUNNER, args)
with PluginContext(environment_plugins):
loader = Loader()
discoverer = plugin_manager.get_driver(
plugin_manager.TEST_DISCOVERY, args, loader=loader)
suites = [
discoverer.discover(
start=start,
top_level_directory=args.top_level_directory,
pattern=args.pattern,
)
for start in args.start
]
if len(suites) == 1:
suite = suites[0]
else:
suite = loader.create_suite(suites)
test_count = suite.countTestCases()
result_handlers = plugin_manager.get_enabled_hook_plugins(
plugin_manager.RESULT_HANDLERS, args, test_count=test_count)
result_collector = ResultCollector(
buffer=args.buffer, failfast=args.failfast)
for result_handler in result_handlers:
result_collector.add_result_handler(result_handler)
result = runner.run(result_collector, suite)
return not result.wasSuccessful()
|
python
|
def run(self, plugin_manager=None):
"""Run the haas test runner.
This will load and configure the selected plugins, set up the
environment and begin test discovery, loading and running.
Parameters
----------
plugin_manager : haas.plugin_manager.PluginManager
[Optional] Override the use of the default plugin manager.
"""
if plugin_manager is None:
plugin_manager = PluginManager()
plugin_manager.add_plugin_arguments(self.parser)
args = self.parser.parse_args(self.argv[1:])
environment_plugins = plugin_manager.get_enabled_hook_plugins(
plugin_manager.ENVIRONMENT_HOOK, args)
runner = plugin_manager.get_driver(
plugin_manager.TEST_RUNNER, args)
with PluginContext(environment_plugins):
loader = Loader()
discoverer = plugin_manager.get_driver(
plugin_manager.TEST_DISCOVERY, args, loader=loader)
suites = [
discoverer.discover(
start=start,
top_level_directory=args.top_level_directory,
pattern=args.pattern,
)
for start in args.start
]
if len(suites) == 1:
suite = suites[0]
else:
suite = loader.create_suite(suites)
test_count = suite.countTestCases()
result_handlers = plugin_manager.get_enabled_hook_plugins(
plugin_manager.RESULT_HANDLERS, args, test_count=test_count)
result_collector = ResultCollector(
buffer=args.buffer, failfast=args.failfast)
for result_handler in result_handlers:
result_collector.add_result_handler(result_handler)
result = runner.run(result_collector, suite)
return not result.wasSuccessful()
|
[
"def",
"run",
"(",
"self",
",",
"plugin_manager",
"=",
"None",
")",
":",
"if",
"plugin_manager",
"is",
"None",
":",
"plugin_manager",
"=",
"PluginManager",
"(",
")",
"plugin_manager",
".",
"add_plugin_arguments",
"(",
"self",
".",
"parser",
")",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"self",
".",
"argv",
"[",
"1",
":",
"]",
")",
"environment_plugins",
"=",
"plugin_manager",
".",
"get_enabled_hook_plugins",
"(",
"plugin_manager",
".",
"ENVIRONMENT_HOOK",
",",
"args",
")",
"runner",
"=",
"plugin_manager",
".",
"get_driver",
"(",
"plugin_manager",
".",
"TEST_RUNNER",
",",
"args",
")",
"with",
"PluginContext",
"(",
"environment_plugins",
")",
":",
"loader",
"=",
"Loader",
"(",
")",
"discoverer",
"=",
"plugin_manager",
".",
"get_driver",
"(",
"plugin_manager",
".",
"TEST_DISCOVERY",
",",
"args",
",",
"loader",
"=",
"loader",
")",
"suites",
"=",
"[",
"discoverer",
".",
"discover",
"(",
"start",
"=",
"start",
",",
"top_level_directory",
"=",
"args",
".",
"top_level_directory",
",",
"pattern",
"=",
"args",
".",
"pattern",
",",
")",
"for",
"start",
"in",
"args",
".",
"start",
"]",
"if",
"len",
"(",
"suites",
")",
"==",
"1",
":",
"suite",
"=",
"suites",
"[",
"0",
"]",
"else",
":",
"suite",
"=",
"loader",
".",
"create_suite",
"(",
"suites",
")",
"test_count",
"=",
"suite",
".",
"countTestCases",
"(",
")",
"result_handlers",
"=",
"plugin_manager",
".",
"get_enabled_hook_plugins",
"(",
"plugin_manager",
".",
"RESULT_HANDLERS",
",",
"args",
",",
"test_count",
"=",
"test_count",
")",
"result_collector",
"=",
"ResultCollector",
"(",
"buffer",
"=",
"args",
".",
"buffer",
",",
"failfast",
"=",
"args",
".",
"failfast",
")",
"for",
"result_handler",
"in",
"result_handlers",
":",
"result_collector",
".",
"add_result_handler",
"(",
"result_handler",
")",
"result",
"=",
"runner",
".",
"run",
"(",
"result_collector",
",",
"suite",
")",
"return",
"not",
"result",
".",
"wasSuccessful",
"(",
")"
] |
Run the haas test runner.
This will load and configure the selected plugins, set up the
environment and begin test discovery, loading and running.
Parameters
----------
plugin_manager : haas.plugin_manager.PluginManager
[Optional] Override the use of the default plugin manager.
|
[
"Run",
"the",
"haas",
"test",
"runner",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/haas_application.py#L83-L133
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
encrypt_password
|
def encrypt_password(**kwargs):
""" Crypt :new_value: if it's not crypted yet. """
new_value = kwargs['new_value']
field = kwargs['field']
min_length = field.params['min_length']
if len(new_value) < min_length:
raise ValueError(
'`{}`: Value length must be more than {}'.format(
field.name, field.params['min_length']))
if new_value and not crypt.match(new_value):
new_value = str(crypt.encode(new_value))
return new_value
|
python
|
def encrypt_password(**kwargs):
""" Crypt :new_value: if it's not crypted yet. """
new_value = kwargs['new_value']
field = kwargs['field']
min_length = field.params['min_length']
if len(new_value) < min_length:
raise ValueError(
'`{}`: Value length must be more than {}'.format(
field.name, field.params['min_length']))
if new_value and not crypt.match(new_value):
new_value = str(crypt.encode(new_value))
return new_value
|
[
"def",
"encrypt_password",
"(",
"*",
"*",
"kwargs",
")",
":",
"new_value",
"=",
"kwargs",
"[",
"'new_value'",
"]",
"field",
"=",
"kwargs",
"[",
"'field'",
"]",
"min_length",
"=",
"field",
".",
"params",
"[",
"'min_length'",
"]",
"if",
"len",
"(",
"new_value",
")",
"<",
"min_length",
":",
"raise",
"ValueError",
"(",
"'`{}`: Value length must be more than {}'",
".",
"format",
"(",
"field",
".",
"name",
",",
"field",
".",
"params",
"[",
"'min_length'",
"]",
")",
")",
"if",
"new_value",
"and",
"not",
"crypt",
".",
"match",
"(",
"new_value",
")",
":",
"new_value",
"=",
"str",
"(",
"crypt",
".",
"encode",
"(",
"new_value",
")",
")",
"return",
"new_value"
] |
Crypt :new_value: if it's not crypted yet.
|
[
"Crypt",
":",
"new_value",
":",
"if",
"it",
"s",
"not",
"crypted",
"yet",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L159-L171
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
create_apikey_model
|
def create_apikey_model(user_model):
""" Generate ApiKey model class and connect it with :user_model:.
ApiKey is generated with relationship to user model class :user_model:
as a One-to-One relationship with a backreference.
ApiKey is set up to be auto-generated when a new :user_model: is created.
Returns ApiKey document class. If ApiKey is already defined, it is not
generated.
Arguments:
:user_model: Class that represents user model for which api keys will
be generated and with which ApiKey will have relationship.
"""
try:
return engine.get_document_cls('ApiKey')
except ValueError:
pass
fk_kwargs = {
'ref_column': None,
}
if hasattr(user_model, '__tablename__'):
fk_kwargs['ref_column'] = '.'.join([
user_model.__tablename__, user_model.pk_field()])
fk_kwargs['ref_column_type'] = user_model.pk_field_type()
class ApiKey(engine.BaseDocument):
__tablename__ = 'nefertari_apikey'
id = engine.IdField(primary_key=True)
token = engine.StringField(default=create_apikey_token)
user = engine.Relationship(
document=user_model.__name__,
uselist=False,
backref_name='api_key',
backref_uselist=False)
user_id = engine.ForeignKeyField(
ref_document=user_model.__name__,
**fk_kwargs)
def reset_token(self):
self.update({'token': create_apikey_token()})
return self.token
# Setup ApiKey autogeneration on :user_model: creation
ApiKey.autogenerate_for(user_model, 'user')
return ApiKey
|
python
|
def create_apikey_model(user_model):
""" Generate ApiKey model class and connect it with :user_model:.
ApiKey is generated with relationship to user model class :user_model:
as a One-to-One relationship with a backreference.
ApiKey is set up to be auto-generated when a new :user_model: is created.
Returns ApiKey document class. If ApiKey is already defined, it is not
generated.
Arguments:
:user_model: Class that represents user model for which api keys will
be generated and with which ApiKey will have relationship.
"""
try:
return engine.get_document_cls('ApiKey')
except ValueError:
pass
fk_kwargs = {
'ref_column': None,
}
if hasattr(user_model, '__tablename__'):
fk_kwargs['ref_column'] = '.'.join([
user_model.__tablename__, user_model.pk_field()])
fk_kwargs['ref_column_type'] = user_model.pk_field_type()
class ApiKey(engine.BaseDocument):
__tablename__ = 'nefertari_apikey'
id = engine.IdField(primary_key=True)
token = engine.StringField(default=create_apikey_token)
user = engine.Relationship(
document=user_model.__name__,
uselist=False,
backref_name='api_key',
backref_uselist=False)
user_id = engine.ForeignKeyField(
ref_document=user_model.__name__,
**fk_kwargs)
def reset_token(self):
self.update({'token': create_apikey_token()})
return self.token
# Setup ApiKey autogeneration on :user_model: creation
ApiKey.autogenerate_for(user_model, 'user')
return ApiKey
|
[
"def",
"create_apikey_model",
"(",
"user_model",
")",
":",
"try",
":",
"return",
"engine",
".",
"get_document_cls",
"(",
"'ApiKey'",
")",
"except",
"ValueError",
":",
"pass",
"fk_kwargs",
"=",
"{",
"'ref_column'",
":",
"None",
",",
"}",
"if",
"hasattr",
"(",
"user_model",
",",
"'__tablename__'",
")",
":",
"fk_kwargs",
"[",
"'ref_column'",
"]",
"=",
"'.'",
".",
"join",
"(",
"[",
"user_model",
".",
"__tablename__",
",",
"user_model",
".",
"pk_field",
"(",
")",
"]",
")",
"fk_kwargs",
"[",
"'ref_column_type'",
"]",
"=",
"user_model",
".",
"pk_field_type",
"(",
")",
"class",
"ApiKey",
"(",
"engine",
".",
"BaseDocument",
")",
":",
"__tablename__",
"=",
"'nefertari_apikey'",
"id",
"=",
"engine",
".",
"IdField",
"(",
"primary_key",
"=",
"True",
")",
"token",
"=",
"engine",
".",
"StringField",
"(",
"default",
"=",
"create_apikey_token",
")",
"user",
"=",
"engine",
".",
"Relationship",
"(",
"document",
"=",
"user_model",
".",
"__name__",
",",
"uselist",
"=",
"False",
",",
"backref_name",
"=",
"'api_key'",
",",
"backref_uselist",
"=",
"False",
")",
"user_id",
"=",
"engine",
".",
"ForeignKeyField",
"(",
"ref_document",
"=",
"user_model",
".",
"__name__",
",",
"*",
"*",
"fk_kwargs",
")",
"def",
"reset_token",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
"{",
"'token'",
":",
"create_apikey_token",
"(",
")",
"}",
")",
"return",
"self",
".",
"token",
"# Setup ApiKey autogeneration on :user_model: creation",
"ApiKey",
".",
"autogenerate_for",
"(",
"user_model",
",",
"'user'",
")",
"return",
"ApiKey"
] |
Generate ApiKey model class and connect it with :user_model:.
ApiKey is generated with relationship to user model class :user_model:
as a One-to-One relationship with a backreference.
ApiKey is set up to be auto-generated when a new :user_model: is created.
Returns ApiKey document class. If ApiKey is already defined, it is not
generated.
Arguments:
:user_model: Class that represents user model for which api keys will
be generated and with which ApiKey will have relationship.
|
[
"Generate",
"ApiKey",
"model",
"class",
"and",
"connect",
"it",
"with",
":",
"user_model",
":",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L195-L243
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
cache_request_user
|
def cache_request_user(user_cls, request, user_id):
""" Helper function to cache currently logged in user.
User is cached at `request._user`. Caching happens only only
if user is not already cached or if cached user's pk does not
match `user_id`.
:param user_cls: User model class to use for user lookup.
:param request: Pyramid Request instance.
:user_id: Current user primary key field value.
"""
pk_field = user_cls.pk_field()
user = getattr(request, '_user', None)
if user is None or getattr(user, pk_field, None) != user_id:
request._user = user_cls.get_item(**{pk_field: user_id})
|
python
|
def cache_request_user(user_cls, request, user_id):
""" Helper function to cache currently logged in user.
User is cached at `request._user`. Caching happens only only
if user is not already cached or if cached user's pk does not
match `user_id`.
:param user_cls: User model class to use for user lookup.
:param request: Pyramid Request instance.
:user_id: Current user primary key field value.
"""
pk_field = user_cls.pk_field()
user = getattr(request, '_user', None)
if user is None or getattr(user, pk_field, None) != user_id:
request._user = user_cls.get_item(**{pk_field: user_id})
|
[
"def",
"cache_request_user",
"(",
"user_cls",
",",
"request",
",",
"user_id",
")",
":",
"pk_field",
"=",
"user_cls",
".",
"pk_field",
"(",
")",
"user",
"=",
"getattr",
"(",
"request",
",",
"'_user'",
",",
"None",
")",
"if",
"user",
"is",
"None",
"or",
"getattr",
"(",
"user",
",",
"pk_field",
",",
"None",
")",
"!=",
"user_id",
":",
"request",
".",
"_user",
"=",
"user_cls",
".",
"get_item",
"(",
"*",
"*",
"{",
"pk_field",
":",
"user_id",
"}",
")"
] |
Helper function to cache currently logged in user.
User is cached at `request._user`. Caching happens only only
if user is not already cached or if cached user's pk does not
match `user_id`.
:param user_cls: User model class to use for user lookup.
:param request: Pyramid Request instance.
:user_id: Current user primary key field value.
|
[
"Helper",
"function",
"to",
"cache",
"currently",
"logged",
"in",
"user",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L246-L260
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.get_token_credentials
|
def get_token_credentials(cls, username, request):
""" Get api token for user with username of :username:
Used by Token-based auth as `credentials_callback` kwarg.
"""
try:
user = cls.get_item(username=username)
except Exception as ex:
log.error(str(ex))
forget(request)
else:
if user:
return user.api_key.token
|
python
|
def get_token_credentials(cls, username, request):
""" Get api token for user with username of :username:
Used by Token-based auth as `credentials_callback` kwarg.
"""
try:
user = cls.get_item(username=username)
except Exception as ex:
log.error(str(ex))
forget(request)
else:
if user:
return user.api_key.token
|
[
"def",
"get_token_credentials",
"(",
"cls",
",",
"username",
",",
"request",
")",
":",
"try",
":",
"user",
"=",
"cls",
".",
"get_item",
"(",
"username",
"=",
"username",
")",
"except",
"Exception",
"as",
"ex",
":",
"log",
".",
"error",
"(",
"str",
"(",
"ex",
")",
")",
"forget",
"(",
"request",
")",
"else",
":",
"if",
"user",
":",
"return",
"user",
".",
"api_key",
".",
"token"
] |
Get api token for user with username of :username:
Used by Token-based auth as `credentials_callback` kwarg.
|
[
"Get",
"api",
"token",
"for",
"user",
"with",
"username",
"of",
":",
"username",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L42-L54
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.get_groups_by_token
|
def get_groups_by_token(cls, username, token, request):
""" Get user's groups if user with :username: exists and their api key
token equals :token:
Used by Token-based authentication as `check` kwarg.
"""
try:
user = cls.get_item(username=username)
except Exception as ex:
log.error(str(ex))
forget(request)
return
else:
if user and user.api_key.token == token:
return ['g:%s' % g for g in user.groups]
|
python
|
def get_groups_by_token(cls, username, token, request):
""" Get user's groups if user with :username: exists and their api key
token equals :token:
Used by Token-based authentication as `check` kwarg.
"""
try:
user = cls.get_item(username=username)
except Exception as ex:
log.error(str(ex))
forget(request)
return
else:
if user and user.api_key.token == token:
return ['g:%s' % g for g in user.groups]
|
[
"def",
"get_groups_by_token",
"(",
"cls",
",",
"username",
",",
"token",
",",
"request",
")",
":",
"try",
":",
"user",
"=",
"cls",
".",
"get_item",
"(",
"username",
"=",
"username",
")",
"except",
"Exception",
"as",
"ex",
":",
"log",
".",
"error",
"(",
"str",
"(",
"ex",
")",
")",
"forget",
"(",
"request",
")",
"return",
"else",
":",
"if",
"user",
"and",
"user",
".",
"api_key",
".",
"token",
"==",
"token",
":",
"return",
"[",
"'g:%s'",
"%",
"g",
"for",
"g",
"in",
"user",
".",
"groups",
"]"
] |
Get user's groups if user with :username: exists and their api key
token equals :token:
Used by Token-based authentication as `check` kwarg.
|
[
"Get",
"user",
"s",
"groups",
"if",
"user",
"with",
":",
"username",
":",
"exists",
"and",
"their",
"api",
"key",
"token",
"equals",
":",
"token",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L57-L71
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.authenticate_by_password
|
def authenticate_by_password(cls, params):
""" Authenticate user with login and password from :params:
Used both by Token and Ticket-based auths (called from views).
"""
def verify_password(user, password):
return crypt.check(user.password, password)
success = False
user = None
login = params['login'].lower().strip()
key = 'email' if '@' in login else 'username'
try:
user = cls.get_item(**{key: login})
except Exception as ex:
log.error(str(ex))
if user:
password = params.get('password', None)
success = (password and verify_password(user, password))
return success, user
|
python
|
def authenticate_by_password(cls, params):
""" Authenticate user with login and password from :params:
Used both by Token and Ticket-based auths (called from views).
"""
def verify_password(user, password):
return crypt.check(user.password, password)
success = False
user = None
login = params['login'].lower().strip()
key = 'email' if '@' in login else 'username'
try:
user = cls.get_item(**{key: login})
except Exception as ex:
log.error(str(ex))
if user:
password = params.get('password', None)
success = (password and verify_password(user, password))
return success, user
|
[
"def",
"authenticate_by_password",
"(",
"cls",
",",
"params",
")",
":",
"def",
"verify_password",
"(",
"user",
",",
"password",
")",
":",
"return",
"crypt",
".",
"check",
"(",
"user",
".",
"password",
",",
"password",
")",
"success",
"=",
"False",
"user",
"=",
"None",
"login",
"=",
"params",
"[",
"'login'",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"key",
"=",
"'email'",
"if",
"'@'",
"in",
"login",
"else",
"'username'",
"try",
":",
"user",
"=",
"cls",
".",
"get_item",
"(",
"*",
"*",
"{",
"key",
":",
"login",
"}",
")",
"except",
"Exception",
"as",
"ex",
":",
"log",
".",
"error",
"(",
"str",
"(",
"ex",
")",
")",
"if",
"user",
":",
"password",
"=",
"params",
".",
"get",
"(",
"'password'",
",",
"None",
")",
"success",
"=",
"(",
"password",
"and",
"verify_password",
"(",
"user",
",",
"password",
")",
")",
"return",
"success",
",",
"user"
] |
Authenticate user with login and password from :params:
Used both by Token and Ticket-based auths (called from views).
|
[
"Authenticate",
"user",
"with",
"login",
"and",
"password",
"from",
":",
"params",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L74-L94
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.get_groups_by_userid
|
def get_groups_by_userid(cls, userid, request):
""" Return group identifiers of user with id :userid:
Used by Ticket-based auth as `callback` kwarg.
"""
try:
cache_request_user(cls, request, userid)
except Exception as ex:
log.error(str(ex))
forget(request)
else:
if request._user:
return ['g:%s' % g for g in request._user.groups]
|
python
|
def get_groups_by_userid(cls, userid, request):
""" Return group identifiers of user with id :userid:
Used by Ticket-based auth as `callback` kwarg.
"""
try:
cache_request_user(cls, request, userid)
except Exception as ex:
log.error(str(ex))
forget(request)
else:
if request._user:
return ['g:%s' % g for g in request._user.groups]
|
[
"def",
"get_groups_by_userid",
"(",
"cls",
",",
"userid",
",",
"request",
")",
":",
"try",
":",
"cache_request_user",
"(",
"cls",
",",
"request",
",",
"userid",
")",
"except",
"Exception",
"as",
"ex",
":",
"log",
".",
"error",
"(",
"str",
"(",
"ex",
")",
")",
"forget",
"(",
"request",
")",
"else",
":",
"if",
"request",
".",
"_user",
":",
"return",
"[",
"'g:%s'",
"%",
"g",
"for",
"g",
"in",
"request",
".",
"_user",
".",
"groups",
"]"
] |
Return group identifiers of user with id :userid:
Used by Ticket-based auth as `callback` kwarg.
|
[
"Return",
"group",
"identifiers",
"of",
"user",
"with",
"id",
":",
"userid",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L97-L109
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.create_account
|
def create_account(cls, params):
""" Create auth user instance with data from :params:.
Used by both Token and Ticket-based auths to register a user (
called from views).
"""
user_params = dictset(params).subset(
['username', 'email', 'password'])
try:
return cls.get_or_create(
email=user_params['email'],
defaults=user_params)
except JHTTPBadRequest:
raise JHTTPBadRequest('Failed to create account.')
|
python
|
def create_account(cls, params):
""" Create auth user instance with data from :params:.
Used by both Token and Ticket-based auths to register a user (
called from views).
"""
user_params = dictset(params).subset(
['username', 'email', 'password'])
try:
return cls.get_or_create(
email=user_params['email'],
defaults=user_params)
except JHTTPBadRequest:
raise JHTTPBadRequest('Failed to create account.')
|
[
"def",
"create_account",
"(",
"cls",
",",
"params",
")",
":",
"user_params",
"=",
"dictset",
"(",
"params",
")",
".",
"subset",
"(",
"[",
"'username'",
",",
"'email'",
",",
"'password'",
"]",
")",
"try",
":",
"return",
"cls",
".",
"get_or_create",
"(",
"email",
"=",
"user_params",
"[",
"'email'",
"]",
",",
"defaults",
"=",
"user_params",
")",
"except",
"JHTTPBadRequest",
":",
"raise",
"JHTTPBadRequest",
"(",
"'Failed to create account.'",
")"
] |
Create auth user instance with data from :params:.
Used by both Token and Ticket-based auths to register a user (
called from views).
|
[
"Create",
"auth",
"user",
"instance",
"with",
"data",
"from",
":",
"params",
":",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L112-L125
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.get_authuser_by_userid
|
def get_authuser_by_userid(cls, request):
""" Get user by ID.
Used by Ticket-based auth. Is added as request method to populate
`request.user`.
"""
userid = authenticated_userid(request)
if userid:
cache_request_user(cls, request, userid)
return request._user
|
python
|
def get_authuser_by_userid(cls, request):
""" Get user by ID.
Used by Ticket-based auth. Is added as request method to populate
`request.user`.
"""
userid = authenticated_userid(request)
if userid:
cache_request_user(cls, request, userid)
return request._user
|
[
"def",
"get_authuser_by_userid",
"(",
"cls",
",",
"request",
")",
":",
"userid",
"=",
"authenticated_userid",
"(",
"request",
")",
"if",
"userid",
":",
"cache_request_user",
"(",
"cls",
",",
"request",
",",
"userid",
")",
"return",
"request",
".",
"_user"
] |
Get user by ID.
Used by Ticket-based auth. Is added as request method to populate
`request.user`.
|
[
"Get",
"user",
"by",
"ID",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L128-L137
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/models.py
|
AuthModelMethodsMixin.get_authuser_by_name
|
def get_authuser_by_name(cls, request):
""" Get user by username
Used by Token-based auth. Is added as request method to populate
`request.user`.
"""
username = authenticated_userid(request)
if username:
return cls.get_item(username=username)
|
python
|
def get_authuser_by_name(cls, request):
""" Get user by username
Used by Token-based auth. Is added as request method to populate
`request.user`.
"""
username = authenticated_userid(request)
if username:
return cls.get_item(username=username)
|
[
"def",
"get_authuser_by_name",
"(",
"cls",
",",
"request",
")",
":",
"username",
"=",
"authenticated_userid",
"(",
"request",
")",
"if",
"username",
":",
"return",
"cls",
".",
"get_item",
"(",
"username",
"=",
"username",
")"
] |
Get user by username
Used by Token-based auth. Is added as request method to populate
`request.user`.
|
[
"Get",
"user",
"by",
"username"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L140-L148
|
train
|
tsileo/dirtools
|
dirtools.py
|
Dir.walk
|
def walk(self):
""" Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly. """
for root, dirs, files in os.walk(self.path, topdown=True):
# TODO relative walk, recursive call if root excluder found???
#root_excluder = get_root_excluder(root)
ndirs = []
# First we exclude directories
for d in list(dirs):
if self.is_excluded(os.path.join(root, d)):
dirs.remove(d)
elif not os.path.islink(os.path.join(root, d)):
ndirs.append(d)
nfiles = []
for fpath in (os.path.join(root, f) for f in files):
if not self.is_excluded(fpath) and not os.path.islink(fpath):
nfiles.append(os.path.relpath(fpath, root))
yield root, ndirs, nfiles
|
python
|
def walk(self):
""" Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly. """
for root, dirs, files in os.walk(self.path, topdown=True):
# TODO relative walk, recursive call if root excluder found???
#root_excluder = get_root_excluder(root)
ndirs = []
# First we exclude directories
for d in list(dirs):
if self.is_excluded(os.path.join(root, d)):
dirs.remove(d)
elif not os.path.islink(os.path.join(root, d)):
ndirs.append(d)
nfiles = []
for fpath in (os.path.join(root, f) for f in files):
if not self.is_excluded(fpath) and not os.path.islink(fpath):
nfiles.append(os.path.relpath(fpath, root))
yield root, ndirs, nfiles
|
[
"def",
"walk",
"(",
"self",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"path",
",",
"topdown",
"=",
"True",
")",
":",
"# TODO relative walk, recursive call if root excluder found???",
"#root_excluder = get_root_excluder(root)",
"ndirs",
"=",
"[",
"]",
"# First we exclude directories",
"for",
"d",
"in",
"list",
"(",
"dirs",
")",
":",
"if",
"self",
".",
"is_excluded",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
")",
")",
":",
"dirs",
".",
"remove",
"(",
"d",
")",
"elif",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
")",
")",
":",
"ndirs",
".",
"append",
"(",
"d",
")",
"nfiles",
"=",
"[",
"]",
"for",
"fpath",
"in",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"for",
"f",
"in",
"files",
")",
":",
"if",
"not",
"self",
".",
"is_excluded",
"(",
"fpath",
")",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"fpath",
")",
":",
"nfiles",
".",
"append",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"fpath",
",",
"root",
")",
")",
"yield",
"root",
",",
"ndirs",
",",
"nfiles"
] |
Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly.
|
[
"Walk",
"the",
"directory",
"like",
"os",
".",
"path",
"(",
"yields",
"a",
"3",
"-",
"tuple",
"(",
"dirpath",
"dirnames",
"filenames",
")",
"except",
"it",
"exclude",
"all",
"files",
"/",
"directories",
"on",
"the",
"fly",
"."
] |
34be55b20b4ef506869487b5fa5c6ea020604f80
|
https://github.com/tsileo/dirtools/blob/34be55b20b4ef506869487b5fa5c6ea020604f80/dirtools.py#L245-L265
|
train
|
ramses-tech/nefertari
|
nefertari/authentication/__init__.py
|
includeme
|
def includeme(config):
""" Set up event subscribers. """
from .models import (
AuthUserMixin,
random_uuid,
lower_strip,
encrypt_password,
)
add_proc = config.add_field_processors
add_proc(
[random_uuid, lower_strip],
model=AuthUserMixin, field='username')
add_proc([lower_strip], model=AuthUserMixin, field='email')
add_proc([encrypt_password], model=AuthUserMixin, field='password')
|
python
|
def includeme(config):
""" Set up event subscribers. """
from .models import (
AuthUserMixin,
random_uuid,
lower_strip,
encrypt_password,
)
add_proc = config.add_field_processors
add_proc(
[random_uuid, lower_strip],
model=AuthUserMixin, field='username')
add_proc([lower_strip], model=AuthUserMixin, field='email')
add_proc([encrypt_password], model=AuthUserMixin, field='password')
|
[
"def",
"includeme",
"(",
"config",
")",
":",
"from",
".",
"models",
"import",
"(",
"AuthUserMixin",
",",
"random_uuid",
",",
"lower_strip",
",",
"encrypt_password",
",",
")",
"add_proc",
"=",
"config",
".",
"add_field_processors",
"add_proc",
"(",
"[",
"random_uuid",
",",
"lower_strip",
"]",
",",
"model",
"=",
"AuthUserMixin",
",",
"field",
"=",
"'username'",
")",
"add_proc",
"(",
"[",
"lower_strip",
"]",
",",
"model",
"=",
"AuthUserMixin",
",",
"field",
"=",
"'email'",
")",
"add_proc",
"(",
"[",
"encrypt_password",
"]",
",",
"model",
"=",
"AuthUserMixin",
",",
"field",
"=",
"'password'",
")"
] |
Set up event subscribers.
|
[
"Set",
"up",
"event",
"subscribers",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/__init__.py#L1-L14
|
train
|
loisaidasam/pyslack
|
pyslack/__init__.py
|
SlackClient._make_request
|
def _make_request(self, method, params):
"""Make request to API endpoint
Note: Ignoring SSL cert validation due to intermittent failures
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
"""
if self.blocked_until is not None and \
datetime.datetime.utcnow() < self.blocked_until:
raise SlackError("Too many requests - wait until {0}" \
.format(self.blocked_until))
url = "%s/%s" % (SlackClient.BASE_URL, method)
params['token'] = self.token
response = requests.post(url, data=params, verify=self.verify)
if response.status_code == 429:
# Too many requests
retry_after = int(response.headers.get('retry-after', '1'))
self.blocked_until = datetime.datetime.utcnow() + \
datetime.timedelta(seconds=retry_after)
raise SlackError("Too many requests - retry after {0} second(s)" \
.format(retry_after))
result = response.json()
if not result['ok']:
raise SlackError(result['error'])
return result
|
python
|
def _make_request(self, method, params):
"""Make request to API endpoint
Note: Ignoring SSL cert validation due to intermittent failures
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
"""
if self.blocked_until is not None and \
datetime.datetime.utcnow() < self.blocked_until:
raise SlackError("Too many requests - wait until {0}" \
.format(self.blocked_until))
url = "%s/%s" % (SlackClient.BASE_URL, method)
params['token'] = self.token
response = requests.post(url, data=params, verify=self.verify)
if response.status_code == 429:
# Too many requests
retry_after = int(response.headers.get('retry-after', '1'))
self.blocked_until = datetime.datetime.utcnow() + \
datetime.timedelta(seconds=retry_after)
raise SlackError("Too many requests - retry after {0} second(s)" \
.format(retry_after))
result = response.json()
if not result['ok']:
raise SlackError(result['error'])
return result
|
[
"def",
"_make_request",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"if",
"self",
".",
"blocked_until",
"is",
"not",
"None",
"and",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"<",
"self",
".",
"blocked_until",
":",
"raise",
"SlackError",
"(",
"\"Too many requests - wait until {0}\"",
".",
"format",
"(",
"self",
".",
"blocked_until",
")",
")",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"SlackClient",
".",
"BASE_URL",
",",
"method",
")",
"params",
"[",
"'token'",
"]",
"=",
"self",
".",
"token",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"params",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"if",
"response",
".",
"status_code",
"==",
"429",
":",
"# Too many requests",
"retry_after",
"=",
"int",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'retry-after'",
",",
"'1'",
")",
")",
"self",
".",
"blocked_until",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"retry_after",
")",
"raise",
"SlackError",
"(",
"\"Too many requests - retry after {0} second(s)\"",
".",
"format",
"(",
"retry_after",
")",
")",
"result",
"=",
"response",
".",
"json",
"(",
")",
"if",
"not",
"result",
"[",
"'ok'",
"]",
":",
"raise",
"SlackError",
"(",
"result",
"[",
"'error'",
"]",
")",
"return",
"result"
] |
Make request to API endpoint
Note: Ignoring SSL cert validation due to intermittent failures
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
|
[
"Make",
"request",
"to",
"API",
"endpoint"
] |
bce0dcbe830b95ba548b58c7ceea07923589a8ec
|
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L23-L49
|
train
|
loisaidasam/pyslack
|
pyslack/__init__.py
|
SlackClient.channels_list
|
def channels_list(self, exclude_archived=True, **params):
"""channels.list
This method returns a list of all channels in the team. This includes
channels the caller is in, channels they are not currently in, and
archived channels. The number of (non-deactivated) members in each
channel is also returned.
https://api.slack.com/methods/channels.list
"""
method = 'channels.list'
params.update({'exclude_archived': exclude_archived and 1 or 0})
return self._make_request(method, params)
|
python
|
def channels_list(self, exclude_archived=True, **params):
"""channels.list
This method returns a list of all channels in the team. This includes
channels the caller is in, channels they are not currently in, and
archived channels. The number of (non-deactivated) members in each
channel is also returned.
https://api.slack.com/methods/channels.list
"""
method = 'channels.list'
params.update({'exclude_archived': exclude_archived and 1 or 0})
return self._make_request(method, params)
|
[
"def",
"channels_list",
"(",
"self",
",",
"exclude_archived",
"=",
"True",
",",
"*",
"*",
"params",
")",
":",
"method",
"=",
"'channels.list'",
"params",
".",
"update",
"(",
"{",
"'exclude_archived'",
":",
"exclude_archived",
"and",
"1",
"or",
"0",
"}",
")",
"return",
"self",
".",
"_make_request",
"(",
"method",
",",
"params",
")"
] |
channels.list
This method returns a list of all channels in the team. This includes
channels the caller is in, channels they are not currently in, and
archived channels. The number of (non-deactivated) members in each
channel is also returned.
https://api.slack.com/methods/channels.list
|
[
"channels",
".",
"list"
] |
bce0dcbe830b95ba548b58c7ceea07923589a8ec
|
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L51-L63
|
train
|
loisaidasam/pyslack
|
pyslack/__init__.py
|
SlackClient.channel_name_to_id
|
def channel_name_to_id(self, channel_name, force_lookup=False):
"""Helper name for getting a channel's id from its name
"""
if force_lookup or not self.channel_name_id_map:
channels = self.channels_list()['channels']
self.channel_name_id_map = {channel['name']: channel['id'] for channel in channels}
channel = channel_name.startswith('#') and channel_name[1:] or channel_name
return self.channel_name_id_map.get(channel)
|
python
|
def channel_name_to_id(self, channel_name, force_lookup=False):
"""Helper name for getting a channel's id from its name
"""
if force_lookup or not self.channel_name_id_map:
channels = self.channels_list()['channels']
self.channel_name_id_map = {channel['name']: channel['id'] for channel in channels}
channel = channel_name.startswith('#') and channel_name[1:] or channel_name
return self.channel_name_id_map.get(channel)
|
[
"def",
"channel_name_to_id",
"(",
"self",
",",
"channel_name",
",",
"force_lookup",
"=",
"False",
")",
":",
"if",
"force_lookup",
"or",
"not",
"self",
".",
"channel_name_id_map",
":",
"channels",
"=",
"self",
".",
"channels_list",
"(",
")",
"[",
"'channels'",
"]",
"self",
".",
"channel_name_id_map",
"=",
"{",
"channel",
"[",
"'name'",
"]",
":",
"channel",
"[",
"'id'",
"]",
"for",
"channel",
"in",
"channels",
"}",
"channel",
"=",
"channel_name",
".",
"startswith",
"(",
"'#'",
")",
"and",
"channel_name",
"[",
"1",
":",
"]",
"or",
"channel_name",
"return",
"self",
".",
"channel_name_id_map",
".",
"get",
"(",
"channel",
")"
] |
Helper name for getting a channel's id from its name
|
[
"Helper",
"name",
"for",
"getting",
"a",
"channel",
"s",
"id",
"from",
"its",
"name"
] |
bce0dcbe830b95ba548b58c7ceea07923589a8ec
|
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L65-L72
|
train
|
loisaidasam/pyslack
|
pyslack/__init__.py
|
SlackClient.chat_post_message
|
def chat_post_message(self, channel, text, **params):
"""chat.postMessage
This method posts a message to a channel.
https://api.slack.com/methods/chat.postMessage
"""
method = 'chat.postMessage'
params.update({
'channel': channel,
'text': text,
})
return self._make_request(method, params)
|
python
|
def chat_post_message(self, channel, text, **params):
"""chat.postMessage
This method posts a message to a channel.
https://api.slack.com/methods/chat.postMessage
"""
method = 'chat.postMessage'
params.update({
'channel': channel,
'text': text,
})
return self._make_request(method, params)
|
[
"def",
"chat_post_message",
"(",
"self",
",",
"channel",
",",
"text",
",",
"*",
"*",
"params",
")",
":",
"method",
"=",
"'chat.postMessage'",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel",
",",
"'text'",
":",
"text",
",",
"}",
")",
"return",
"self",
".",
"_make_request",
"(",
"method",
",",
"params",
")"
] |
chat.postMessage
This method posts a message to a channel.
https://api.slack.com/methods/chat.postMessage
|
[
"chat",
".",
"postMessage"
] |
bce0dcbe830b95ba548b58c7ceea07923589a8ec
|
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L74-L86
|
train
|
loisaidasam/pyslack
|
pyslack/__init__.py
|
SlackClient.chat_update_message
|
def chat_update_message(self, channel, text, timestamp, **params):
"""chat.update
This method updates a message.
Required parameters:
`channel`: Channel containing the message to be updated. (e.g: "C1234567890")
`text`: New text for the message, using the default formatting rules. (e.g: "Hello world")
`timestamp`: Timestamp of the message to be updated (e.g: "1405894322.002768")
https://api.slack.com/methods/chat.update
"""
method = 'chat.update'
if self._channel_is_name(channel):
# chat.update only takes channel ids (not channel names)
channel = self.channel_name_to_id(channel)
params.update({
'channel': channel,
'text': text,
'ts': timestamp,
})
return self._make_request(method, params)
|
python
|
def chat_update_message(self, channel, text, timestamp, **params):
"""chat.update
This method updates a message.
Required parameters:
`channel`: Channel containing the message to be updated. (e.g: "C1234567890")
`text`: New text for the message, using the default formatting rules. (e.g: "Hello world")
`timestamp`: Timestamp of the message to be updated (e.g: "1405894322.002768")
https://api.slack.com/methods/chat.update
"""
method = 'chat.update'
if self._channel_is_name(channel):
# chat.update only takes channel ids (not channel names)
channel = self.channel_name_to_id(channel)
params.update({
'channel': channel,
'text': text,
'ts': timestamp,
})
return self._make_request(method, params)
|
[
"def",
"chat_update_message",
"(",
"self",
",",
"channel",
",",
"text",
",",
"timestamp",
",",
"*",
"*",
"params",
")",
":",
"method",
"=",
"'chat.update'",
"if",
"self",
".",
"_channel_is_name",
"(",
"channel",
")",
":",
"# chat.update only takes channel ids (not channel names)",
"channel",
"=",
"self",
".",
"channel_name_to_id",
"(",
"channel",
")",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel",
",",
"'text'",
":",
"text",
",",
"'ts'",
":",
"timestamp",
",",
"}",
")",
"return",
"self",
".",
"_make_request",
"(",
"method",
",",
"params",
")"
] |
chat.update
This method updates a message.
Required parameters:
`channel`: Channel containing the message to be updated. (e.g: "C1234567890")
`text`: New text for the message, using the default formatting rules. (e.g: "Hello world")
`timestamp`: Timestamp of the message to be updated (e.g: "1405894322.002768")
https://api.slack.com/methods/chat.update
|
[
"chat",
".",
"update"
] |
bce0dcbe830b95ba548b58c7ceea07923589a8ec
|
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L88-L109
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
includeme
|
def includeme(config):
""" Connect view to route that catches all URIs like
'something,something,...'
"""
root = config.get_root_resource()
root.add('nef_polymorphic', '{collections:.+,.+}',
view=PolymorphicESView,
factory=PolymorphicACL)
|
python
|
def includeme(config):
""" Connect view to route that catches all URIs like
'something,something,...'
"""
root = config.get_root_resource()
root.add('nef_polymorphic', '{collections:.+,.+}',
view=PolymorphicESView,
factory=PolymorphicACL)
|
[
"def",
"includeme",
"(",
"config",
")",
":",
"root",
"=",
"config",
".",
"get_root_resource",
"(",
")",
"root",
".",
"add",
"(",
"'nef_polymorphic'",
",",
"'{collections:.+,.+}'",
",",
"view",
"=",
"PolymorphicESView",
",",
"factory",
"=",
"PolymorphicACL",
")"
] |
Connect view to route that catches all URIs like
'something,something,...'
|
[
"Connect",
"view",
"to",
"route",
"that",
"catches",
"all",
"URIs",
"like",
"something",
"something",
"..."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L37-L44
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
PolymorphicHelperMixin.get_collections
|
def get_collections(self):
""" Get names of collections from request matchdict.
:return: Names of collections
:rtype: list of str
"""
collections = self.request.matchdict['collections'].split('/')[0]
collections = [coll.strip() for coll in collections.split(',')]
return set(collections)
|
python
|
def get_collections(self):
""" Get names of collections from request matchdict.
:return: Names of collections
:rtype: list of str
"""
collections = self.request.matchdict['collections'].split('/')[0]
collections = [coll.strip() for coll in collections.split(',')]
return set(collections)
|
[
"def",
"get_collections",
"(",
"self",
")",
":",
"collections",
"=",
"self",
".",
"request",
".",
"matchdict",
"[",
"'collections'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"collections",
"=",
"[",
"coll",
".",
"strip",
"(",
")",
"for",
"coll",
"in",
"collections",
".",
"split",
"(",
"','",
")",
"]",
"return",
"set",
"(",
"collections",
")"
] |
Get names of collections from request matchdict.
:return: Names of collections
:rtype: list of str
|
[
"Get",
"names",
"of",
"collections",
"from",
"request",
"matchdict",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L52-L60
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
PolymorphicHelperMixin.get_resources
|
def get_resources(self, collections):
""" Get resources that correspond to values from :collections:.
:param collections: Collection names for which resources should be
gathered
:type collections: list of str
:return: Gathered resources
:rtype: list of Resource instances
"""
res_map = self.request.registry._model_collections
resources = [res for res in res_map.values()
if res.collection_name in collections]
resources = [res for res in resources if res]
return set(resources)
|
python
|
def get_resources(self, collections):
""" Get resources that correspond to values from :collections:.
:param collections: Collection names for which resources should be
gathered
:type collections: list of str
:return: Gathered resources
:rtype: list of Resource instances
"""
res_map = self.request.registry._model_collections
resources = [res for res in res_map.values()
if res.collection_name in collections]
resources = [res for res in resources if res]
return set(resources)
|
[
"def",
"get_resources",
"(",
"self",
",",
"collections",
")",
":",
"res_map",
"=",
"self",
".",
"request",
".",
"registry",
".",
"_model_collections",
"resources",
"=",
"[",
"res",
"for",
"res",
"in",
"res_map",
".",
"values",
"(",
")",
"if",
"res",
".",
"collection_name",
"in",
"collections",
"]",
"resources",
"=",
"[",
"res",
"for",
"res",
"in",
"resources",
"if",
"res",
"]",
"return",
"set",
"(",
"resources",
")"
] |
Get resources that correspond to values from :collections:.
:param collections: Collection names for which resources should be
gathered
:type collections: list of str
:return: Gathered resources
:rtype: list of Resource instances
|
[
"Get",
"resources",
"that",
"correspond",
"to",
"values",
"from",
":",
"collections",
":",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L62-L75
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
PolymorphicACL._get_least_permissions_aces
|
def _get_least_permissions_aces(self, resources):
""" Get ACEs with the least permissions that fit all resources.
To have access to polymorph on N collections, user MUST have
access to all of them. If this is true, ACEs are returned, that
allows 'view' permissions to current request principals.
Otherwise None is returned thus blocking all permissions except
those defined in `nefertari.acl.BaseACL`.
:param resources:
:type resources: list of Resource instances
:return: Generated Pyramid ACEs or None
:rtype: tuple or None
"""
factories = [res.view._factory for res in resources]
contexts = [factory(self.request) for factory in factories]
for ctx in contexts:
if not self.request.has_permission('view', ctx):
return
else:
return [
(Allow, principal, 'view')
for principal in self.request.effective_principals
]
|
python
|
def _get_least_permissions_aces(self, resources):
""" Get ACEs with the least permissions that fit all resources.
To have access to polymorph on N collections, user MUST have
access to all of them. If this is true, ACEs are returned, that
allows 'view' permissions to current request principals.
Otherwise None is returned thus blocking all permissions except
those defined in `nefertari.acl.BaseACL`.
:param resources:
:type resources: list of Resource instances
:return: Generated Pyramid ACEs or None
:rtype: tuple or None
"""
factories = [res.view._factory for res in resources]
contexts = [factory(self.request) for factory in factories]
for ctx in contexts:
if not self.request.has_permission('view', ctx):
return
else:
return [
(Allow, principal, 'view')
for principal in self.request.effective_principals
]
|
[
"def",
"_get_least_permissions_aces",
"(",
"self",
",",
"resources",
")",
":",
"factories",
"=",
"[",
"res",
".",
"view",
".",
"_factory",
"for",
"res",
"in",
"resources",
"]",
"contexts",
"=",
"[",
"factory",
"(",
"self",
".",
"request",
")",
"for",
"factory",
"in",
"factories",
"]",
"for",
"ctx",
"in",
"contexts",
":",
"if",
"not",
"self",
".",
"request",
".",
"has_permission",
"(",
"'view'",
",",
"ctx",
")",
":",
"return",
"else",
":",
"return",
"[",
"(",
"Allow",
",",
"principal",
",",
"'view'",
")",
"for",
"principal",
"in",
"self",
".",
"request",
".",
"effective_principals",
"]"
] |
Get ACEs with the least permissions that fit all resources.
To have access to polymorph on N collections, user MUST have
access to all of them. If this is true, ACEs are returned, that
allows 'view' permissions to current request principals.
Otherwise None is returned thus blocking all permissions except
those defined in `nefertari.acl.BaseACL`.
:param resources:
:type resources: list of Resource instances
:return: Generated Pyramid ACEs or None
:rtype: tuple or None
|
[
"Get",
"ACEs",
"with",
"the",
"least",
"permissions",
"that",
"fit",
"all",
"resources",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L89-L113
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
PolymorphicACL.set_collections_acl
|
def set_collections_acl(self):
""" Calculate and set ACL valid for requested collections.
DENY_ALL is added to ACL to make sure no access rules are
inherited.
"""
acl = [(Allow, 'g:admin', ALL_PERMISSIONS)]
collections = self.get_collections()
resources = self.get_resources(collections)
aces = self._get_least_permissions_aces(resources)
if aces is not None:
for ace in aces:
acl.append(ace)
acl.append(DENY_ALL)
self.__acl__ = tuple(acl)
|
python
|
def set_collections_acl(self):
""" Calculate and set ACL valid for requested collections.
DENY_ALL is added to ACL to make sure no access rules are
inherited.
"""
acl = [(Allow, 'g:admin', ALL_PERMISSIONS)]
collections = self.get_collections()
resources = self.get_resources(collections)
aces = self._get_least_permissions_aces(resources)
if aces is not None:
for ace in aces:
acl.append(ace)
acl.append(DENY_ALL)
self.__acl__ = tuple(acl)
|
[
"def",
"set_collections_acl",
"(",
"self",
")",
":",
"acl",
"=",
"[",
"(",
"Allow",
",",
"'g:admin'",
",",
"ALL_PERMISSIONS",
")",
"]",
"collections",
"=",
"self",
".",
"get_collections",
"(",
")",
"resources",
"=",
"self",
".",
"get_resources",
"(",
"collections",
")",
"aces",
"=",
"self",
".",
"_get_least_permissions_aces",
"(",
"resources",
")",
"if",
"aces",
"is",
"not",
"None",
":",
"for",
"ace",
"in",
"aces",
":",
"acl",
".",
"append",
"(",
"ace",
")",
"acl",
".",
"append",
"(",
"DENY_ALL",
")",
"self",
".",
"__acl__",
"=",
"tuple",
"(",
"acl",
")"
] |
Calculate and set ACL valid for requested collections.
DENY_ALL is added to ACL to make sure no access rules are
inherited.
|
[
"Calculate",
"and",
"set",
"ACL",
"valid",
"for",
"requested",
"collections",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L115-L129
|
train
|
ramses-tech/nefertari
|
nefertari/polymorphic.py
|
PolymorphicESView.determine_types
|
def determine_types(self):
""" Determine ES type names from request data.
In particular `request.matchdict['collections']` is used to
determine types names. Its value is comma-separated sequence
of collection names under which views have been registered.
"""
from nefertari.elasticsearch import ES
collections = self.get_collections()
resources = self.get_resources(collections)
models = set([res.view.Model for res in resources])
es_models = [mdl for mdl in models if mdl
and getattr(mdl, '_index_enabled', False)]
types = [ES.src2type(mdl.__name__) for mdl in es_models]
return types
|
python
|
def determine_types(self):
""" Determine ES type names from request data.
In particular `request.matchdict['collections']` is used to
determine types names. Its value is comma-separated sequence
of collection names under which views have been registered.
"""
from nefertari.elasticsearch import ES
collections = self.get_collections()
resources = self.get_resources(collections)
models = set([res.view.Model for res in resources])
es_models = [mdl for mdl in models if mdl
and getattr(mdl, '_index_enabled', False)]
types = [ES.src2type(mdl.__name__) for mdl in es_models]
return types
|
[
"def",
"determine_types",
"(",
"self",
")",
":",
"from",
"nefertari",
".",
"elasticsearch",
"import",
"ES",
"collections",
"=",
"self",
".",
"get_collections",
"(",
")",
"resources",
"=",
"self",
".",
"get_resources",
"(",
"collections",
")",
"models",
"=",
"set",
"(",
"[",
"res",
".",
"view",
".",
"Model",
"for",
"res",
"in",
"resources",
"]",
")",
"es_models",
"=",
"[",
"mdl",
"for",
"mdl",
"in",
"models",
"if",
"mdl",
"and",
"getattr",
"(",
"mdl",
",",
"'_index_enabled'",
",",
"False",
")",
"]",
"types",
"=",
"[",
"ES",
".",
"src2type",
"(",
"mdl",
".",
"__name__",
")",
"for",
"mdl",
"in",
"es_models",
"]",
"return",
"types"
] |
Determine ES type names from request data.
In particular `request.matchdict['collections']` is used to
determine types names. Its value is comma-separated sequence
of collection names under which views have been registered.
|
[
"Determine",
"ES",
"type",
"names",
"from",
"request",
"data",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L155-L169
|
train
|
asyne/cproto
|
cproto/domains/factory.py
|
get_command
|
def get_command(domain_name, command_name):
"""Returns a closure function that dispatches message to the WebSocket."""
def send_command(self, **kwargs):
return self.ws.send_message(
'{0}.{1}'.format(domain_name, command_name),
kwargs
)
return send_command
|
python
|
def get_command(domain_name, command_name):
"""Returns a closure function that dispatches message to the WebSocket."""
def send_command(self, **kwargs):
return self.ws.send_message(
'{0}.{1}'.format(domain_name, command_name),
kwargs
)
return send_command
|
[
"def",
"get_command",
"(",
"domain_name",
",",
"command_name",
")",
":",
"def",
"send_command",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"ws",
".",
"send_message",
"(",
"'{0}.{1}'",
".",
"format",
"(",
"domain_name",
",",
"command_name",
")",
",",
"kwargs",
")",
"return",
"send_command"
] |
Returns a closure function that dispatches message to the WebSocket.
|
[
"Returns",
"a",
"closure",
"function",
"that",
"dispatches",
"message",
"to",
"the",
"WebSocket",
"."
] |
9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b
|
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L5-L13
|
train
|
asyne/cproto
|
cproto/domains/factory.py
|
DomainFactory
|
def DomainFactory(domain_name, cmds):
"""Dynamically create Domain class and set it's methods."""
klass = type(str(domain_name), (BaseDomain,), {})
for c in cmds:
command = get_command(domain_name, c['name'])
setattr(klass, c['name'], classmethod(command))
return klass
|
python
|
def DomainFactory(domain_name, cmds):
"""Dynamically create Domain class and set it's methods."""
klass = type(str(domain_name), (BaseDomain,), {})
for c in cmds:
command = get_command(domain_name, c['name'])
setattr(klass, c['name'], classmethod(command))
return klass
|
[
"def",
"DomainFactory",
"(",
"domain_name",
",",
"cmds",
")",
":",
"klass",
"=",
"type",
"(",
"str",
"(",
"domain_name",
")",
",",
"(",
"BaseDomain",
",",
")",
",",
"{",
"}",
")",
"for",
"c",
"in",
"cmds",
":",
"command",
"=",
"get_command",
"(",
"domain_name",
",",
"c",
"[",
"'name'",
"]",
")",
"setattr",
"(",
"klass",
",",
"c",
"[",
"'name'",
"]",
",",
"classmethod",
"(",
"command",
")",
")",
"return",
"klass"
] |
Dynamically create Domain class and set it's methods.
|
[
"Dynamically",
"create",
"Domain",
"class",
"and",
"set",
"it",
"s",
"methods",
"."
] |
9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b
|
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L16-L24
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
main
|
def main():
"""The entrypoint for the hairball command installed via setup.py."""
description = ('PATH can be either the path to a scratch file, or a '
'directory containing scratch files. Multiple PATH '
'arguments can be provided.')
parser = OptionParser(usage='%prog -p PLUGIN_NAME [options] PATH...',
description=description,
version='%prog {}'.format(__version__))
parser.add_option('-d', '--plugin-dir', metavar='DIR',
help=('Specify the path to a directory containing '
'plugins. Plugins in this directory take '
'precedence over similarly named plugins '
'included with Hairball.'))
parser.add_option('-p', '--plugin', action='append',
help=('Use the named plugin to perform analysis. '
'This option can be provided multiple times.'))
parser.add_option('-k', '--kurt-plugin', action='append',
help=('Provide either a python import path (e.g, '
'kelp.octopi) to a package/module, or the path'
' to a python file, which will be loaded as a '
'Kurt plugin. This option can be provided '
'multiple times.'))
parser.add_option('-q', '--quiet', action='store_true',
help=('Prevent output from Hairball. Plugins may still '
'produce output.'))
parser.add_option('-C', '--no-cache', action='store_true',
help='Do not use Hairball\'s cache.', default=False)
options, args = parser.parse_args(sys.argv[1:])
if not options.plugin:
parser.error('At least one plugin must be specified via -p.')
if not args:
parser.error('At least one PATH must be provided.')
if options.plugin_dir:
if os.path.isdir(options.plugin_dir):
sys.path.append(options.plugin_dir)
else:
parser.error('{} is not a directory'.format(options.plugin_dir))
hairball = Hairball(options, args, cache=not options.no_cache)
hairball.initialize_plugins()
hairball.process()
hairball.finalize()
|
python
|
def main():
"""The entrypoint for the hairball command installed via setup.py."""
description = ('PATH can be either the path to a scratch file, or a '
'directory containing scratch files. Multiple PATH '
'arguments can be provided.')
parser = OptionParser(usage='%prog -p PLUGIN_NAME [options] PATH...',
description=description,
version='%prog {}'.format(__version__))
parser.add_option('-d', '--plugin-dir', metavar='DIR',
help=('Specify the path to a directory containing '
'plugins. Plugins in this directory take '
'precedence over similarly named plugins '
'included with Hairball.'))
parser.add_option('-p', '--plugin', action='append',
help=('Use the named plugin to perform analysis. '
'This option can be provided multiple times.'))
parser.add_option('-k', '--kurt-plugin', action='append',
help=('Provide either a python import path (e.g, '
'kelp.octopi) to a package/module, or the path'
' to a python file, which will be loaded as a '
'Kurt plugin. This option can be provided '
'multiple times.'))
parser.add_option('-q', '--quiet', action='store_true',
help=('Prevent output from Hairball. Plugins may still '
'produce output.'))
parser.add_option('-C', '--no-cache', action='store_true',
help='Do not use Hairball\'s cache.', default=False)
options, args = parser.parse_args(sys.argv[1:])
if not options.plugin:
parser.error('At least one plugin must be specified via -p.')
if not args:
parser.error('At least one PATH must be provided.')
if options.plugin_dir:
if os.path.isdir(options.plugin_dir):
sys.path.append(options.plugin_dir)
else:
parser.error('{} is not a directory'.format(options.plugin_dir))
hairball = Hairball(options, args, cache=not options.no_cache)
hairball.initialize_plugins()
hairball.process()
hairball.finalize()
|
[
"def",
"main",
"(",
")",
":",
"description",
"=",
"(",
"'PATH can be either the path to a scratch file, or a '",
"'directory containing scratch files. Multiple PATH '",
"'arguments can be provided.'",
")",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"'%prog -p PLUGIN_NAME [options] PATH...'",
",",
"description",
"=",
"description",
",",
"version",
"=",
"'%prog {}'",
".",
"format",
"(",
"__version__",
")",
")",
"parser",
".",
"add_option",
"(",
"'-d'",
",",
"'--plugin-dir'",
",",
"metavar",
"=",
"'DIR'",
",",
"help",
"=",
"(",
"'Specify the path to a directory containing '",
"'plugins. Plugins in this directory take '",
"'precedence over similarly named plugins '",
"'included with Hairball.'",
")",
")",
"parser",
".",
"add_option",
"(",
"'-p'",
",",
"'--plugin'",
",",
"action",
"=",
"'append'",
",",
"help",
"=",
"(",
"'Use the named plugin to perform analysis. '",
"'This option can be provided multiple times.'",
")",
")",
"parser",
".",
"add_option",
"(",
"'-k'",
",",
"'--kurt-plugin'",
",",
"action",
"=",
"'append'",
",",
"help",
"=",
"(",
"'Provide either a python import path (e.g, '",
"'kelp.octopi) to a package/module, or the path'",
"' to a python file, which will be loaded as a '",
"'Kurt plugin. This option can be provided '",
"'multiple times.'",
")",
")",
"parser",
".",
"add_option",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"(",
"'Prevent output from Hairball. Plugins may still '",
"'produce output.'",
")",
")",
"parser",
".",
"add_option",
"(",
"'-C'",
",",
"'--no-cache'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Do not use Hairball\\'s cache.'",
",",
"default",
"=",
"False",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"not",
"options",
".",
"plugin",
":",
"parser",
".",
"error",
"(",
"'At least one plugin must be specified via -p.'",
")",
"if",
"not",
"args",
":",
"parser",
".",
"error",
"(",
"'At least one PATH must be provided.'",
")",
"if",
"options",
".",
"plugin_dir",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"options",
".",
"plugin_dir",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"options",
".",
"plugin_dir",
")",
"else",
":",
"parser",
".",
"error",
"(",
"'{} is not a directory'",
".",
"format",
"(",
"options",
".",
"plugin_dir",
")",
")",
"hairball",
"=",
"Hairball",
"(",
"options",
",",
"args",
",",
"cache",
"=",
"not",
"options",
".",
"no_cache",
")",
"hairball",
".",
"initialize_plugins",
"(",
")",
"hairball",
".",
"process",
"(",
")",
"hairball",
".",
"finalize",
"(",
")"
] |
The entrypoint for the hairball command installed via setup.py.
|
[
"The",
"entrypoint",
"for",
"the",
"hairball",
"command",
"installed",
"via",
"setup",
".",
"py",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L238-L281
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
KurtCache.path_to_key
|
def path_to_key(filepath):
"""Return the sha1sum (key) belonging to the file at filepath."""
tmp, last = os.path.split(filepath)
tmp, middle = os.path.split(tmp)
return '{}{}{}'.format(os.path.basename(tmp), middle,
os.path.splitext(last)[0])
|
python
|
def path_to_key(filepath):
"""Return the sha1sum (key) belonging to the file at filepath."""
tmp, last = os.path.split(filepath)
tmp, middle = os.path.split(tmp)
return '{}{}{}'.format(os.path.basename(tmp), middle,
os.path.splitext(last)[0])
|
[
"def",
"path_to_key",
"(",
"filepath",
")",
":",
"tmp",
",",
"last",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"tmp",
",",
"middle",
"=",
"os",
".",
"path",
".",
"split",
"(",
"tmp",
")",
"return",
"'{}{}{}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"tmp",
")",
",",
"middle",
",",
"os",
".",
"path",
".",
"splitext",
"(",
"last",
")",
"[",
"0",
"]",
")"
] |
Return the sha1sum (key) belonging to the file at filepath.
|
[
"Return",
"the",
"sha1sum",
"(",
"key",
")",
"belonging",
"to",
"the",
"file",
"at",
"filepath",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L29-L34
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
KurtCache.key_to_path
|
def key_to_path(self, key):
"""Return the fullpath to the file with sha1sum key."""
return os.path.join(self.cache_dir, key[:2], key[2:4],
key[4:] + '.pkl')
|
python
|
def key_to_path(self, key):
"""Return the fullpath to the file with sha1sum key."""
return os.path.join(self.cache_dir, key[:2], key[2:4],
key[4:] + '.pkl')
|
[
"def",
"key_to_path",
"(",
"self",
",",
"key",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"key",
"[",
":",
"2",
"]",
",",
"key",
"[",
"2",
":",
"4",
"]",
",",
"key",
"[",
"4",
":",
"]",
"+",
"'.pkl'",
")"
] |
Return the fullpath to the file with sha1sum key.
|
[
"Return",
"the",
"fullpath",
"to",
"the",
"file",
"with",
"sha1sum",
"key",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L53-L56
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
KurtCache.load
|
def load(self, filename):
"""Optimized load and return the parsed version of filename.
Uses the on-disk parse cache if the file is located in it.
"""
# Compute sha1 hash (key)
with open(filename) as fp:
key = sha1(fp.read()).hexdigest()
path = self.key_to_path(key)
# Return the cached file if available
if key in self.hashes:
try:
with open(path) as fp:
return cPickle.load(fp)
except EOFError:
os.unlink(path)
self.hashes.remove(key)
except IOError:
self.hashes.remove(key)
# Create the nested cache directory
try:
os.makedirs(os.path.dirname(path))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
# Process the file and save in the cache
scratch = kurt.Project.load(filename) # can fail
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT,
0400), 'w') as fp:
# open file for writing but make it immediately read-only
cPickle.dump(scratch, fp, cPickle.HIGHEST_PROTOCOL)
self.hashes.add(key)
return scratch
|
python
|
def load(self, filename):
"""Optimized load and return the parsed version of filename.
Uses the on-disk parse cache if the file is located in it.
"""
# Compute sha1 hash (key)
with open(filename) as fp:
key = sha1(fp.read()).hexdigest()
path = self.key_to_path(key)
# Return the cached file if available
if key in self.hashes:
try:
with open(path) as fp:
return cPickle.load(fp)
except EOFError:
os.unlink(path)
self.hashes.remove(key)
except IOError:
self.hashes.remove(key)
# Create the nested cache directory
try:
os.makedirs(os.path.dirname(path))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
# Process the file and save in the cache
scratch = kurt.Project.load(filename) # can fail
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT,
0400), 'w') as fp:
# open file for writing but make it immediately read-only
cPickle.dump(scratch, fp, cPickle.HIGHEST_PROTOCOL)
self.hashes.add(key)
return scratch
|
[
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"# Compute sha1 hash (key)",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"key",
"=",
"sha1",
"(",
"fp",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"path",
"=",
"self",
".",
"key_to_path",
"(",
"key",
")",
"# Return the cached file if available",
"if",
"key",
"in",
"self",
".",
"hashes",
":",
"try",
":",
"with",
"open",
"(",
"path",
")",
"as",
"fp",
":",
"return",
"cPickle",
".",
"load",
"(",
"fp",
")",
"except",
"EOFError",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"self",
".",
"hashes",
".",
"remove",
"(",
"key",
")",
"except",
"IOError",
":",
"self",
".",
"hashes",
".",
"remove",
"(",
"key",
")",
"# Create the nested cache directory",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"# Process the file and save in the cache",
"scratch",
"=",
"kurt",
".",
"Project",
".",
"load",
"(",
"filename",
")",
"# can fail",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
",",
"0400",
")",
",",
"'w'",
")",
"as",
"fp",
":",
"# open file for writing but make it immediately read-only",
"cPickle",
".",
"dump",
"(",
"scratch",
",",
"fp",
",",
"cPickle",
".",
"HIGHEST_PROTOCOL",
")",
"self",
".",
"hashes",
".",
"add",
"(",
"key",
")",
"return",
"scratch"
] |
Optimized load and return the parsed version of filename.
Uses the on-disk parse cache if the file is located in it.
|
[
"Optimized",
"load",
"and",
"return",
"the",
"parsed",
"version",
"of",
"filename",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L58-L91
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
Hairball.hairball_files
|
def hairball_files(self, paths, extensions):
"""Yield filepath to files with the proper extension within paths."""
def add_file(filename):
return os.path.splitext(filename)[1] in extensions
while paths:
arg_path = paths.pop(0)
if os.path.isdir(arg_path):
found = False
for path, dirs, files in os.walk(arg_path):
dirs.sort() # Traverse in sorted order
for filename in sorted(files):
if add_file(filename):
yield os.path.join(path, filename)
found = True
if not found:
if not self.options.quiet:
print('No files found in {}'.format(arg_path))
elif add_file(arg_path):
yield arg_path
elif not self.options.quiet:
print('Invalid file {}'.format(arg_path))
print('Did you forget to load a Kurt plugin (-k)?')
|
python
|
def hairball_files(self, paths, extensions):
"""Yield filepath to files with the proper extension within paths."""
def add_file(filename):
return os.path.splitext(filename)[1] in extensions
while paths:
arg_path = paths.pop(0)
if os.path.isdir(arg_path):
found = False
for path, dirs, files in os.walk(arg_path):
dirs.sort() # Traverse in sorted order
for filename in sorted(files):
if add_file(filename):
yield os.path.join(path, filename)
found = True
if not found:
if not self.options.quiet:
print('No files found in {}'.format(arg_path))
elif add_file(arg_path):
yield arg_path
elif not self.options.quiet:
print('Invalid file {}'.format(arg_path))
print('Did you forget to load a Kurt plugin (-k)?')
|
[
"def",
"hairball_files",
"(",
"self",
",",
"paths",
",",
"extensions",
")",
":",
"def",
"add_file",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"in",
"extensions",
"while",
"paths",
":",
"arg_path",
"=",
"paths",
".",
"pop",
"(",
"0",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"arg_path",
")",
":",
"found",
"=",
"False",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"arg_path",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"# Traverse in sorted order",
"for",
"filename",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"add_file",
"(",
"filename",
")",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"if",
"not",
"self",
".",
"options",
".",
"quiet",
":",
"print",
"(",
"'No files found in {}'",
".",
"format",
"(",
"arg_path",
")",
")",
"elif",
"add_file",
"(",
"arg_path",
")",
":",
"yield",
"arg_path",
"elif",
"not",
"self",
".",
"options",
".",
"quiet",
":",
"print",
"(",
"'Invalid file {}'",
".",
"format",
"(",
"arg_path",
")",
")",
"print",
"(",
"'Did you forget to load a Kurt plugin (-k)?'",
")"
] |
Yield filepath to files with the proper extension within paths.
|
[
"Yield",
"filepath",
"to",
"files",
"with",
"the",
"proper",
"extension",
"within",
"paths",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L136-L158
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
Hairball.initialize_plugins
|
def initialize_plugins(self):
"""Attempt to Load and initialize all the plugins.
Any issues loading plugins will be output to stderr.
"""
for plugin_name in self.options.plugin:
parts = plugin_name.split('.')
if len(parts) > 1:
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
else:
# Use the titlecase format of the module name as the class name
module_name = parts[0]
class_name = parts[0].title()
# First try to load plugins from the passed in plugins_dir and then
# from the hairball.plugins package.
plugin = None
for package in (None, 'hairball.plugins'):
if package:
module_name = '{}.{}'.format(package, module_name)
try:
module = __import__(module_name, fromlist=[class_name])
# Initializes the plugin by calling its constructor
plugin = getattr(module, class_name)()
# Verify plugin is of the correct class
if not isinstance(plugin, HairballPlugin):
sys.stderr.write('Invalid type for plugin {}: {}\n'
.format(plugin_name, type(plugin)))
plugin = None
else:
break
except (ImportError, AttributeError):
pass
if plugin:
self.plugins.append(plugin)
else:
sys.stderr.write('Cannot find plugin {}\n'.format(plugin_name))
if not self.plugins:
sys.stderr.write('No plugins loaded. Goodbye!\n')
sys.exit(1)
|
python
|
def initialize_plugins(self):
"""Attempt to Load and initialize all the plugins.
Any issues loading plugins will be output to stderr.
"""
for plugin_name in self.options.plugin:
parts = plugin_name.split('.')
if len(parts) > 1:
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
else:
# Use the titlecase format of the module name as the class name
module_name = parts[0]
class_name = parts[0].title()
# First try to load plugins from the passed in plugins_dir and then
# from the hairball.plugins package.
plugin = None
for package in (None, 'hairball.plugins'):
if package:
module_name = '{}.{}'.format(package, module_name)
try:
module = __import__(module_name, fromlist=[class_name])
# Initializes the plugin by calling its constructor
plugin = getattr(module, class_name)()
# Verify plugin is of the correct class
if not isinstance(plugin, HairballPlugin):
sys.stderr.write('Invalid type for plugin {}: {}\n'
.format(plugin_name, type(plugin)))
plugin = None
else:
break
except (ImportError, AttributeError):
pass
if plugin:
self.plugins.append(plugin)
else:
sys.stderr.write('Cannot find plugin {}\n'.format(plugin_name))
if not self.plugins:
sys.stderr.write('No plugins loaded. Goodbye!\n')
sys.exit(1)
|
[
"def",
"initialize_plugins",
"(",
"self",
")",
":",
"for",
"plugin_name",
"in",
"self",
".",
"options",
".",
"plugin",
":",
"parts",
"=",
"plugin_name",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"class_name",
"=",
"parts",
"[",
"-",
"1",
"]",
"else",
":",
"# Use the titlecase format of the module name as the class name",
"module_name",
"=",
"parts",
"[",
"0",
"]",
"class_name",
"=",
"parts",
"[",
"0",
"]",
".",
"title",
"(",
")",
"# First try to load plugins from the passed in plugins_dir and then",
"# from the hairball.plugins package.",
"plugin",
"=",
"None",
"for",
"package",
"in",
"(",
"None",
",",
"'hairball.plugins'",
")",
":",
"if",
"package",
":",
"module_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"package",
",",
"module_name",
")",
"try",
":",
"module",
"=",
"__import__",
"(",
"module_name",
",",
"fromlist",
"=",
"[",
"class_name",
"]",
")",
"# Initializes the plugin by calling its constructor",
"plugin",
"=",
"getattr",
"(",
"module",
",",
"class_name",
")",
"(",
")",
"# Verify plugin is of the correct class",
"if",
"not",
"isinstance",
"(",
"plugin",
",",
"HairballPlugin",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Invalid type for plugin {}: {}\\n'",
".",
"format",
"(",
"plugin_name",
",",
"type",
"(",
"plugin",
")",
")",
")",
"plugin",
"=",
"None",
"else",
":",
"break",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
":",
"pass",
"if",
"plugin",
":",
"self",
".",
"plugins",
".",
"append",
"(",
"plugin",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Cannot find plugin {}\\n'",
".",
"format",
"(",
"plugin_name",
")",
")",
"if",
"not",
"self",
".",
"plugins",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'No plugins loaded. Goodbye!\\n'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] |
Attempt to Load and initialize all the plugins.
Any issues loading plugins will be output to stderr.
|
[
"Attempt",
"to",
"Load",
"and",
"initialize",
"all",
"the",
"plugins",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L170-L212
|
train
|
ucsb-cs-education/hairball
|
hairball/__init__.py
|
Hairball.process
|
def process(self):
"""Run the analysis across all files found in the given paths.
Each file is loaded once and all plugins are run against it before
loading the next file.
"""
for filename in self.hairball_files(self.paths, self.extensions):
if not self.options.quiet:
print(filename)
try:
if self.cache:
scratch = self.cache.load(filename)
else:
scratch = kurt.Project.load(filename)
except Exception: # pylint: disable=W0703
traceback.print_exc()
continue
for plugin in self.plugins:
# pylint: disable=W0212
plugin._process(scratch, filename=filename)
|
python
|
def process(self):
"""Run the analysis across all files found in the given paths.
Each file is loaded once and all plugins are run against it before
loading the next file.
"""
for filename in self.hairball_files(self.paths, self.extensions):
if not self.options.quiet:
print(filename)
try:
if self.cache:
scratch = self.cache.load(filename)
else:
scratch = kurt.Project.load(filename)
except Exception: # pylint: disable=W0703
traceback.print_exc()
continue
for plugin in self.plugins:
# pylint: disable=W0212
plugin._process(scratch, filename=filename)
|
[
"def",
"process",
"(",
"self",
")",
":",
"for",
"filename",
"in",
"self",
".",
"hairball_files",
"(",
"self",
".",
"paths",
",",
"self",
".",
"extensions",
")",
":",
"if",
"not",
"self",
".",
"options",
".",
"quiet",
":",
"print",
"(",
"filename",
")",
"try",
":",
"if",
"self",
".",
"cache",
":",
"scratch",
"=",
"self",
".",
"cache",
".",
"load",
"(",
"filename",
")",
"else",
":",
"scratch",
"=",
"kurt",
".",
"Project",
".",
"load",
"(",
"filename",
")",
"except",
"Exception",
":",
"# pylint: disable=W0703",
"traceback",
".",
"print_exc",
"(",
")",
"continue",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"# pylint: disable=W0212",
"plugin",
".",
"_process",
"(",
"scratch",
",",
"filename",
"=",
"filename",
")"
] |
Run the analysis across all files found in the given paths.
Each file is loaded once and all plugins are run against it before
loading the next file.
|
[
"Run",
"the",
"analysis",
"across",
"all",
"files",
"found",
"in",
"the",
"given",
"paths",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L214-L234
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
maybe_dotted
|
def maybe_dotted(module, throw=True):
""" If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
"""
try:
return Configurator().maybe_dotted(module)
except ImportError as e:
err = '%s not found. %s' % (module, e)
if throw:
raise ImportError(err)
else:
log.error(err)
return None
|
python
|
def maybe_dotted(module, throw=True):
""" If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
"""
try:
return Configurator().maybe_dotted(module)
except ImportError as e:
err = '%s not found. %s' % (module, e)
if throw:
raise ImportError(err)
else:
log.error(err)
return None
|
[
"def",
"maybe_dotted",
"(",
"module",
",",
"throw",
"=",
"True",
")",
":",
"try",
":",
"return",
"Configurator",
"(",
")",
".",
"maybe_dotted",
"(",
"module",
")",
"except",
"ImportError",
"as",
"e",
":",
"err",
"=",
"'%s not found. %s'",
"%",
"(",
"module",
",",
"e",
")",
"if",
"throw",
":",
"raise",
"ImportError",
"(",
"err",
")",
"else",
":",
"log",
".",
"error",
"(",
"err",
")",
"return",
"None"
] |
If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
|
[
"If",
"module",
"is",
"a",
"dotted",
"string",
"pointing",
"to",
"the",
"module",
"imports",
"and",
"returns",
"the",
"module",
"object",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L95-L107
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
issequence
|
def issequence(arg):
"""Return True if `arg` acts as a list and does not look like a string."""
string_behaviour = (
isinstance(arg, six.string_types) or
isinstance(arg, six.text_type))
list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__')
return not string_behaviour and list_behaviour
|
python
|
def issequence(arg):
"""Return True if `arg` acts as a list and does not look like a string."""
string_behaviour = (
isinstance(arg, six.string_types) or
isinstance(arg, six.text_type))
list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__')
return not string_behaviour and list_behaviour
|
[
"def",
"issequence",
"(",
"arg",
")",
":",
"string_behaviour",
"=",
"(",
"isinstance",
"(",
"arg",
",",
"six",
".",
"string_types",
")",
"or",
"isinstance",
"(",
"arg",
",",
"six",
".",
"text_type",
")",
")",
"list_behaviour",
"=",
"hasattr",
"(",
"arg",
",",
"'__getitem__'",
")",
"or",
"hasattr",
"(",
"arg",
",",
"'__iter__'",
")",
"return",
"not",
"string_behaviour",
"and",
"list_behaviour"
] |
Return True if `arg` acts as a list and does not look like a string.
|
[
"Return",
"True",
"if",
"arg",
"acts",
"as",
"a",
"list",
"and",
"does",
"not",
"look",
"like",
"a",
"string",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L127-L133
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
merge_dicts
|
def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception(
'Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
|
python
|
def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception(
'Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
|
[
"def",
"merge_dicts",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"b",
"[",
"key",
"]",
",",
"dict",
")",
":",
"merge_dicts",
"(",
"a",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
",",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
"elif",
"a",
"[",
"key",
"]",
"==",
"b",
"[",
"key",
"]",
":",
"pass",
"# same leaf value",
"else",
":",
"raise",
"Exception",
"(",
"'Conflict at %s'",
"%",
"'.'",
".",
"join",
"(",
"path",
"+",
"[",
"str",
"(",
"key",
")",
"]",
")",
")",
"else",
":",
"a",
"[",
"key",
"]",
"=",
"b",
"[",
"key",
"]",
"return",
"a"
] |
Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
|
[
"Merge",
"dict",
":",
"b",
":",
"into",
"dict",
":",
"a",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L136-L155
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
str2dict
|
def str2dict(dotted_str, value=None, separator='.'):
""" Convert dotted string to dict splitting by :separator: """
dict_ = {}
parts = dotted_str.split(separator)
d, prev = dict_, None
for part in parts:
prev = d
d = d.setdefault(part, {})
else:
if value is not None:
prev[part] = value
return dict_
|
python
|
def str2dict(dotted_str, value=None, separator='.'):
""" Convert dotted string to dict splitting by :separator: """
dict_ = {}
parts = dotted_str.split(separator)
d, prev = dict_, None
for part in parts:
prev = d
d = d.setdefault(part, {})
else:
if value is not None:
prev[part] = value
return dict_
|
[
"def",
"str2dict",
"(",
"dotted_str",
",",
"value",
"=",
"None",
",",
"separator",
"=",
"'.'",
")",
":",
"dict_",
"=",
"{",
"}",
"parts",
"=",
"dotted_str",
".",
"split",
"(",
"separator",
")",
"d",
",",
"prev",
"=",
"dict_",
",",
"None",
"for",
"part",
"in",
"parts",
":",
"prev",
"=",
"d",
"d",
"=",
"d",
".",
"setdefault",
"(",
"part",
",",
"{",
"}",
")",
"else",
":",
"if",
"value",
"is",
"not",
"None",
":",
"prev",
"[",
"part",
"]",
"=",
"value",
"return",
"dict_"
] |
Convert dotted string to dict splitting by :separator:
|
[
"Convert",
"dotted",
"string",
"to",
"dict",
"splitting",
"by",
":",
"separator",
":"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L158-L169
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
validate_data_privacy
|
def validate_data_privacy(request, data, wrapper_kw=None):
""" Validate :data: contains only data allowed by privacy settings.
:param request: Pyramid Request instance
:param data: Dict containing request/response data which should be
validated
"""
from nefertari import wrappers
if wrapper_kw is None:
wrapper_kw = {}
wrapper = wrappers.apply_privacy(request)
allowed_fields = wrapper(result=data, **wrapper_kw).keys()
data = data.copy()
data.pop('_type', None)
not_allowed_fields = set(data.keys()) - set(allowed_fields)
if not_allowed_fields:
raise wrappers.ValidationError(', '.join(not_allowed_fields))
|
python
|
def validate_data_privacy(request, data, wrapper_kw=None):
""" Validate :data: contains only data allowed by privacy settings.
:param request: Pyramid Request instance
:param data: Dict containing request/response data which should be
validated
"""
from nefertari import wrappers
if wrapper_kw is None:
wrapper_kw = {}
wrapper = wrappers.apply_privacy(request)
allowed_fields = wrapper(result=data, **wrapper_kw).keys()
data = data.copy()
data.pop('_type', None)
not_allowed_fields = set(data.keys()) - set(allowed_fields)
if not_allowed_fields:
raise wrappers.ValidationError(', '.join(not_allowed_fields))
|
[
"def",
"validate_data_privacy",
"(",
"request",
",",
"data",
",",
"wrapper_kw",
"=",
"None",
")",
":",
"from",
"nefertari",
"import",
"wrappers",
"if",
"wrapper_kw",
"is",
"None",
":",
"wrapper_kw",
"=",
"{",
"}",
"wrapper",
"=",
"wrappers",
".",
"apply_privacy",
"(",
"request",
")",
"allowed_fields",
"=",
"wrapper",
"(",
"result",
"=",
"data",
",",
"*",
"*",
"wrapper_kw",
")",
".",
"keys",
"(",
")",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"data",
".",
"pop",
"(",
"'_type'",
",",
"None",
")",
"not_allowed_fields",
"=",
"set",
"(",
"data",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"allowed_fields",
")",
"if",
"not_allowed_fields",
":",
"raise",
"wrappers",
".",
"ValidationError",
"(",
"', '",
".",
"join",
"(",
"not_allowed_fields",
")",
")"
] |
Validate :data: contains only data allowed by privacy settings.
:param request: Pyramid Request instance
:param data: Dict containing request/response data which should be
validated
|
[
"Validate",
":",
"data",
":",
"contains",
"only",
"data",
"allowed",
"by",
"privacy",
"settings",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L172-L190
|
train
|
ramses-tech/nefertari
|
nefertari/utils/utils.py
|
drop_reserved_params
|
def drop_reserved_params(params):
""" Drops reserved params """
from nefertari import RESERVED_PARAMS
params = params.copy()
for reserved_param in RESERVED_PARAMS:
if reserved_param in params:
params.pop(reserved_param)
return params
|
python
|
def drop_reserved_params(params):
""" Drops reserved params """
from nefertari import RESERVED_PARAMS
params = params.copy()
for reserved_param in RESERVED_PARAMS:
if reserved_param in params:
params.pop(reserved_param)
return params
|
[
"def",
"drop_reserved_params",
"(",
"params",
")",
":",
"from",
"nefertari",
"import",
"RESERVED_PARAMS",
"params",
"=",
"params",
".",
"copy",
"(",
")",
"for",
"reserved_param",
"in",
"RESERVED_PARAMS",
":",
"if",
"reserved_param",
"in",
"params",
":",
"params",
".",
"pop",
"(",
"reserved_param",
")",
"return",
"params"
] |
Drops reserved params
|
[
"Drops",
"reserved",
"params"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L193-L200
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV._send_command_raw
|
def _send_command_raw(self, command, opt=''):
"""
Description:
The TV doesn't handle long running connections very well,
so we open a new connection every time.
There might be a better way to do this,
but it's pretty quick and resilient.
Returns:
If a value is being requested ( opt2 is "?" ),
then the return value is returned.
If a value is being set,
it returns True for "OK" or False for "ERR"
"""
# According to the documentation:
# http://files.sharpusa.com/Downloads/ForHome/
# HomeEntertainment/LCDTVs/Manuals/tel_man_LC40_46_52_60LE830U.pdf
# Page 58 - Communication conditions for IP
# The connection could be lost (but not only after 3 minutes),
# so we need to the remote commands to be sure about states
end_time = time.time() + self.timeout
while time.time() < end_time:
try:
# Connect
sock_con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_con.settimeout(self.connection_timeout)
sock_con.connect((self.ip_address, self.port))
# Authenticate
sock_con.send(self.auth)
sock_con.recv(1024)
sock_con.recv(1024)
# Send command
if opt != '':
command += str(opt)
sock_con.send(str.encode(command.ljust(8) + '\r'))
status = bytes.decode(sock_con.recv(1024)).strip()
except (OSError, socket.error) as exp:
time.sleep(0.1)
if time.time() >= end_time:
raise exp
else:
sock_con.close()
# Sometimes the status is empty so
# We need to retry
if status != u'':
break
if status == "OK":
return True
elif status == "ERR":
return False
else:
try:
return int(status)
except ValueError:
return status
|
python
|
def _send_command_raw(self, command, opt=''):
"""
Description:
The TV doesn't handle long running connections very well,
so we open a new connection every time.
There might be a better way to do this,
but it's pretty quick and resilient.
Returns:
If a value is being requested ( opt2 is "?" ),
then the return value is returned.
If a value is being set,
it returns True for "OK" or False for "ERR"
"""
# According to the documentation:
# http://files.sharpusa.com/Downloads/ForHome/
# HomeEntertainment/LCDTVs/Manuals/tel_man_LC40_46_52_60LE830U.pdf
# Page 58 - Communication conditions for IP
# The connection could be lost (but not only after 3 minutes),
# so we need to the remote commands to be sure about states
end_time = time.time() + self.timeout
while time.time() < end_time:
try:
# Connect
sock_con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_con.settimeout(self.connection_timeout)
sock_con.connect((self.ip_address, self.port))
# Authenticate
sock_con.send(self.auth)
sock_con.recv(1024)
sock_con.recv(1024)
# Send command
if opt != '':
command += str(opt)
sock_con.send(str.encode(command.ljust(8) + '\r'))
status = bytes.decode(sock_con.recv(1024)).strip()
except (OSError, socket.error) as exp:
time.sleep(0.1)
if time.time() >= end_time:
raise exp
else:
sock_con.close()
# Sometimes the status is empty so
# We need to retry
if status != u'':
break
if status == "OK":
return True
elif status == "ERR":
return False
else:
try:
return int(status)
except ValueError:
return status
|
[
"def",
"_send_command_raw",
"(",
"self",
",",
"command",
",",
"opt",
"=",
"''",
")",
":",
"# According to the documentation:",
"# http://files.sharpusa.com/Downloads/ForHome/",
"# HomeEntertainment/LCDTVs/Manuals/tel_man_LC40_46_52_60LE830U.pdf",
"# Page 58 - Communication conditions for IP",
"# The connection could be lost (but not only after 3 minutes),",
"# so we need to the remote commands to be sure about states",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"timeout",
"while",
"time",
".",
"time",
"(",
")",
"<",
"end_time",
":",
"try",
":",
"# Connect",
"sock_con",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock_con",
".",
"settimeout",
"(",
"self",
".",
"connection_timeout",
")",
"sock_con",
".",
"connect",
"(",
"(",
"self",
".",
"ip_address",
",",
"self",
".",
"port",
")",
")",
"# Authenticate",
"sock_con",
".",
"send",
"(",
"self",
".",
"auth",
")",
"sock_con",
".",
"recv",
"(",
"1024",
")",
"sock_con",
".",
"recv",
"(",
"1024",
")",
"# Send command",
"if",
"opt",
"!=",
"''",
":",
"command",
"+=",
"str",
"(",
"opt",
")",
"sock_con",
".",
"send",
"(",
"str",
".",
"encode",
"(",
"command",
".",
"ljust",
"(",
"8",
")",
"+",
"'\\r'",
")",
")",
"status",
"=",
"bytes",
".",
"decode",
"(",
"sock_con",
".",
"recv",
"(",
"1024",
")",
")",
".",
"strip",
"(",
")",
"except",
"(",
"OSError",
",",
"socket",
".",
"error",
")",
"as",
"exp",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"if",
"time",
".",
"time",
"(",
")",
">=",
"end_time",
":",
"raise",
"exp",
"else",
":",
"sock_con",
".",
"close",
"(",
")",
"# Sometimes the status is empty so",
"# We need to retry",
"if",
"status",
"!=",
"u''",
":",
"break",
"if",
"status",
"==",
"\"OK\"",
":",
"return",
"True",
"elif",
"status",
"==",
"\"ERR\"",
":",
"return",
"False",
"else",
":",
"try",
":",
"return",
"int",
"(",
"status",
")",
"except",
"ValueError",
":",
"return",
"status"
] |
Description:
The TV doesn't handle long running connections very well,
so we open a new connection every time.
There might be a better way to do this,
but it's pretty quick and resilient.
Returns:
If a value is being requested ( opt2 is "?" ),
then the return value is returned.
If a value is being set,
it returns True for "OK" or False for "ERR"
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L37-L95
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.info
|
def info(self):
"""
Description:
Returns dict of information about the TV
name, model, version
"""
return {"name": self._send_command('name'),
"model": self._send_command('model'),
"version": self._send_command('version'),
"ip_version": self._send_command('ip_version')
}
|
python
|
def info(self):
"""
Description:
Returns dict of information about the TV
name, model, version
"""
return {"name": self._send_command('name'),
"model": self._send_command('model'),
"version": self._send_command('version'),
"ip_version": self._send_command('ip_version')
}
|
[
"def",
"info",
"(",
"self",
")",
":",
"return",
"{",
"\"name\"",
":",
"self",
".",
"_send_command",
"(",
"'name'",
")",
",",
"\"model\"",
":",
"self",
".",
"_send_command",
"(",
"'model'",
")",
",",
"\"version\"",
":",
"self",
".",
"_send_command",
"(",
"'version'",
")",
",",
"\"ip_version\"",
":",
"self",
".",
"_send_command",
"(",
"'ip_version'",
")",
"}"
] |
Description:
Returns dict of information about the TV
name, model, version
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L115-L127
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.get_input_list
|
def get_input_list(self):
"""
Description:
Get input list
Returns an ordered list of all available input keys and names
"""
inputs = [' '] * len(self.command['input'])
for key in self.command['input']:
inputs[self.command['input'][key]['order']] = {"key":key, "name":self.command['input'][key]['name']}
return inputs
|
python
|
def get_input_list(self):
"""
Description:
Get input list
Returns an ordered list of all available input keys and names
"""
inputs = [' '] * len(self.command['input'])
for key in self.command['input']:
inputs[self.command['input'][key]['order']] = {"key":key, "name":self.command['input'][key]['name']}
return inputs
|
[
"def",
"get_input_list",
"(",
"self",
")",
":",
"inputs",
"=",
"[",
"' '",
"]",
"*",
"len",
"(",
"self",
".",
"command",
"[",
"'input'",
"]",
")",
"for",
"key",
"in",
"self",
".",
"command",
"[",
"'input'",
"]",
":",
"inputs",
"[",
"self",
".",
"command",
"[",
"'input'",
"]",
"[",
"key",
"]",
"[",
"'order'",
"]",
"]",
"=",
"{",
"\"key\"",
":",
"key",
",",
"\"name\"",
":",
"self",
".",
"command",
"[",
"'input'",
"]",
"[",
"key",
"]",
"[",
"'name'",
"]",
"}",
"return",
"inputs"
] |
Description:
Get input list
Returns an ordered list of all available input keys and names
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L158-L169
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.input
|
def input(self, opt):
"""
Description:
Set the input
Call with no arguments to get current setting
Arguments:
opt: string
Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1")
"""
for key in self.command['input']:
if (key == opt) or (self.command['input'][key]['name'] == opt):
return self._send_command(['input', key, 'command'])
return False
|
python
|
def input(self, opt):
"""
Description:
Set the input
Call with no arguments to get current setting
Arguments:
opt: string
Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1")
"""
for key in self.command['input']:
if (key == opt) or (self.command['input'][key]['name'] == opt):
return self._send_command(['input', key, 'command'])
return False
|
[
"def",
"input",
"(",
"self",
",",
"opt",
")",
":",
"for",
"key",
"in",
"self",
".",
"command",
"[",
"'input'",
"]",
":",
"if",
"(",
"key",
"==",
"opt",
")",
"or",
"(",
"self",
".",
"command",
"[",
"'input'",
"]",
"[",
"key",
"]",
"[",
"'name'",
"]",
"==",
"opt",
")",
":",
"return",
"self",
".",
"_send_command",
"(",
"[",
"'input'",
",",
"key",
",",
"'command'",
"]",
")",
"return",
"False"
] |
Description:
Set the input
Call with no arguments to get current setting
Arguments:
opt: string
Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1")
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L171-L186
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.digital_channel_air
|
def digital_channel_air(self, opt1='?', opt2='?'):
"""
Description:
Change Channel (Digital)
Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY)
Arguments:
opt1: integer
1-99: Major Channel
opt2: integer (optional)
1-99: Minor Channel
"""
if opt1 == '?':
parameter = '?'
elif opt2 == '?':
parameter = str(opt1).rjust(4, "0")
else:
parameter = '{:02d}{:02d}'.format(opt1, opt2)
return self._send_command('digital_channel_air', parameter)
|
python
|
def digital_channel_air(self, opt1='?', opt2='?'):
"""
Description:
Change Channel (Digital)
Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY)
Arguments:
opt1: integer
1-99: Major Channel
opt2: integer (optional)
1-99: Minor Channel
"""
if opt1 == '?':
parameter = '?'
elif opt2 == '?':
parameter = str(opt1).rjust(4, "0")
else:
parameter = '{:02d}{:02d}'.format(opt1, opt2)
return self._send_command('digital_channel_air', parameter)
|
[
"def",
"digital_channel_air",
"(",
"self",
",",
"opt1",
"=",
"'?'",
",",
"opt2",
"=",
"'?'",
")",
":",
"if",
"opt1",
"==",
"'?'",
":",
"parameter",
"=",
"'?'",
"elif",
"opt2",
"==",
"'?'",
":",
"parameter",
"=",
"str",
"(",
"opt1",
")",
".",
"rjust",
"(",
"4",
",",
"\"0\"",
")",
"else",
":",
"parameter",
"=",
"'{:02d}{:02d}'",
".",
"format",
"(",
"opt1",
",",
"opt2",
")",
"return",
"self",
".",
"_send_command",
"(",
"'digital_channel_air'",
",",
"parameter",
")"
] |
Description:
Change Channel (Digital)
Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY)
Arguments:
opt1: integer
1-99: Major Channel
opt2: integer (optional)
1-99: Minor Channel
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L330-L349
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.digital_channel_cable
|
def digital_channel_cable(self, opt1='?', opt2=0):
"""
Description:
Change Channel (Digital)
Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY)
Arguments:
opt1: integer
1-999: Major Channel
opt2: integer (optional)
0-999: Minor Channel
"""
if opt1 == '?':
parameter = '?'
elif self.command['digital_channel_cable_minor'] == '':
parameter = str(opt1).rjust(4, "0")
else:
self._send_command('digital_channel_cable_minor', str(opt1).rjust(3, "0"))
parameter = str(opt2).rjust(3, "0")
return self._send_command('digital_channel_cable_major', parameter)
|
python
|
def digital_channel_cable(self, opt1='?', opt2=0):
"""
Description:
Change Channel (Digital)
Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY)
Arguments:
opt1: integer
1-999: Major Channel
opt2: integer (optional)
0-999: Minor Channel
"""
if opt1 == '?':
parameter = '?'
elif self.command['digital_channel_cable_minor'] == '':
parameter = str(opt1).rjust(4, "0")
else:
self._send_command('digital_channel_cable_minor', str(opt1).rjust(3, "0"))
parameter = str(opt2).rjust(3, "0")
return self._send_command('digital_channel_cable_major', parameter)
|
[
"def",
"digital_channel_cable",
"(",
"self",
",",
"opt1",
"=",
"'?'",
",",
"opt2",
"=",
"0",
")",
":",
"if",
"opt1",
"==",
"'?'",
":",
"parameter",
"=",
"'?'",
"elif",
"self",
".",
"command",
"[",
"'digital_channel_cable_minor'",
"]",
"==",
"''",
":",
"parameter",
"=",
"str",
"(",
"opt1",
")",
".",
"rjust",
"(",
"4",
",",
"\"0\"",
")",
"else",
":",
"self",
".",
"_send_command",
"(",
"'digital_channel_cable_minor'",
",",
"str",
"(",
"opt1",
")",
".",
"rjust",
"(",
"3",
",",
"\"0\"",
")",
")",
"parameter",
"=",
"str",
"(",
"opt2",
")",
".",
"rjust",
"(",
"3",
",",
"\"0\"",
")",
"return",
"self",
".",
"_send_command",
"(",
"'digital_channel_cable_major'",
",",
"parameter",
")"
] |
Description:
Change Channel (Digital)
Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY)
Arguments:
opt1: integer
1-999: Major Channel
opt2: integer (optional)
0-999: Minor Channel
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L351-L371
|
train
|
jmoore987/sharp_aquos_rc
|
sharp_aquos_rc/tv.py
|
TV.get_remote_button_list
|
def get_remote_button_list(self):
"""
Description:
Get remote button list
Returns an list of all available remote buttons
"""
remote_buttons = []
for key in self.command['remote']:
if self.command['remote'][key] != '':
remote_buttons.append(key)
return remote_buttons
|
python
|
def get_remote_button_list(self):
"""
Description:
Get remote button list
Returns an list of all available remote buttons
"""
remote_buttons = []
for key in self.command['remote']:
if self.command['remote'][key] != '':
remote_buttons.append(key)
return remote_buttons
|
[
"def",
"get_remote_button_list",
"(",
"self",
")",
":",
"remote_buttons",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"command",
"[",
"'remote'",
"]",
":",
"if",
"self",
".",
"command",
"[",
"'remote'",
"]",
"[",
"key",
"]",
"!=",
"''",
":",
"remote_buttons",
".",
"append",
"(",
"key",
")",
"return",
"remote_buttons"
] |
Description:
Get remote button list
Returns an list of all available remote buttons
|
[
"Description",
":"
] |
9a5a1140241a866150dea2d26555680dc8e7f057
|
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L387-L399
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
Animation.check_results
|
def check_results(tmp_):
"""Return a 3 tuple for something."""
# TODO: Fix this to work with more meaningful names
if tmp_['t'] > 0:
if tmp_['l'] > 0:
if tmp_['rr'] > 0 or tmp_['ra'] > 1:
print 1, 3, tmp_
return 3
elif tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 2, 3, tmp_
return 3
elif tmp_['mr'] > 0 or tmp_['ma'] > 1:
print 3, 2, tmp_
return 2
if tmp_['cr'] > 1 or tmp_['ca'] > 2:
print 4, 2, tmp_
return 2
if tmp_['mr'] > 0 or tmp_['ma'] > 1:
if tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 6, 0, tmp_
return 0
if tmp_['rr'] > 1 or tmp_['ra'] > 2:
print 7, 0, tmp_
return 0
if tmp_['sr'] > 1 or tmp_['sa'] > 2:
print 8, 0, tmp_
return 0
if tmp_['l'] > 0:
if tmp_['rr'] > 0 or tmp_['ra'] > 1:
print 9, 2, tmp_
return 2
if tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 10, 0, tmp_
return 0
return -1
|
python
|
def check_results(tmp_):
"""Return a 3 tuple for something."""
# TODO: Fix this to work with more meaningful names
if tmp_['t'] > 0:
if tmp_['l'] > 0:
if tmp_['rr'] > 0 or tmp_['ra'] > 1:
print 1, 3, tmp_
return 3
elif tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 2, 3, tmp_
return 3
elif tmp_['mr'] > 0 or tmp_['ma'] > 1:
print 3, 2, tmp_
return 2
if tmp_['cr'] > 1 or tmp_['ca'] > 2:
print 4, 2, tmp_
return 2
if tmp_['mr'] > 0 or tmp_['ma'] > 1:
if tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 6, 0, tmp_
return 0
if tmp_['rr'] > 1 or tmp_['ra'] > 2:
print 7, 0, tmp_
return 0
if tmp_['sr'] > 1 or tmp_['sa'] > 2:
print 8, 0, tmp_
return 0
if tmp_['l'] > 0:
if tmp_['rr'] > 0 or tmp_['ra'] > 1:
print 9, 2, tmp_
return 2
if tmp_['cr'] > 0 or tmp_['ca'] > 1:
print 10, 0, tmp_
return 0
return -1
|
[
"def",
"check_results",
"(",
"tmp_",
")",
":",
"# TODO: Fix this to work with more meaningful names",
"if",
"tmp_",
"[",
"'t'",
"]",
">",
"0",
":",
"if",
"tmp_",
"[",
"'l'",
"]",
">",
"0",
":",
"if",
"tmp_",
"[",
"'rr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ra'",
"]",
">",
"1",
":",
"print",
"1",
",",
"3",
",",
"tmp_",
"return",
"3",
"elif",
"tmp_",
"[",
"'cr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ca'",
"]",
">",
"1",
":",
"print",
"2",
",",
"3",
",",
"tmp_",
"return",
"3",
"elif",
"tmp_",
"[",
"'mr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ma'",
"]",
">",
"1",
":",
"print",
"3",
",",
"2",
",",
"tmp_",
"return",
"2",
"if",
"tmp_",
"[",
"'cr'",
"]",
">",
"1",
"or",
"tmp_",
"[",
"'ca'",
"]",
">",
"2",
":",
"print",
"4",
",",
"2",
",",
"tmp_",
"return",
"2",
"if",
"tmp_",
"[",
"'mr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ma'",
"]",
">",
"1",
":",
"if",
"tmp_",
"[",
"'cr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ca'",
"]",
">",
"1",
":",
"print",
"6",
",",
"0",
",",
"tmp_",
"return",
"0",
"if",
"tmp_",
"[",
"'rr'",
"]",
">",
"1",
"or",
"tmp_",
"[",
"'ra'",
"]",
">",
"2",
":",
"print",
"7",
",",
"0",
",",
"tmp_",
"return",
"0",
"if",
"tmp_",
"[",
"'sr'",
"]",
">",
"1",
"or",
"tmp_",
"[",
"'sa'",
"]",
">",
"2",
":",
"print",
"8",
",",
"0",
",",
"tmp_",
"return",
"0",
"if",
"tmp_",
"[",
"'l'",
"]",
">",
"0",
":",
"if",
"tmp_",
"[",
"'rr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ra'",
"]",
">",
"1",
":",
"print",
"9",
",",
"2",
",",
"tmp_",
"return",
"2",
"if",
"tmp_",
"[",
"'cr'",
"]",
">",
"0",
"or",
"tmp_",
"[",
"'ca'",
"]",
">",
"1",
":",
"print",
"10",
",",
"0",
",",
"tmp_",
"return",
"0",
"return",
"-",
"1"
] |
Return a 3 tuple for something.
|
[
"Return",
"a",
"3",
"tuple",
"for",
"something",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L28-L62
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
Animation._check_animation
|
def _check_animation(self, last, last_level, gen):
"""Internal helper function to check the animation."""
tmp_ = Counter()
results = Counter()
name, level, block = last, last_level, last
others = False
while name in self.ANIMATION and level >= last_level:
if name in self.LOOP:
if block != last:
count = self.check_results(tmp_)
if count > -1:
results[count] += 1
tmp_.clear()
tmp_['last'] += 1
for attribute in ('costume', 'orientation', 'position', 'size'):
if (name, 'relative') in self.BLOCKMAPPING[attribute]:
tmp_[(attribute, 'relative')] += 1
elif (name, 'absolute') in self.BLOCKMAPPING[attribute]:
tmp_[(attribute, 'absolute')] += 1
if name in self.TIMING:
tmp_['timing'] += 1
last_level = level
name, level, block = next(gen, ('', 0, ''))
# allow some exceptions
if name not in self.ANIMATION and name != '':
if not others:
if block.type.shape != 'stack':
last_level = level
(name, level, block) = next(gen, ('', 0, ''))
others = True
count = self.check_results(tmp_)
if count > -1:
results[count] += 1
return gen, results
|
python
|
def _check_animation(self, last, last_level, gen):
"""Internal helper function to check the animation."""
tmp_ = Counter()
results = Counter()
name, level, block = last, last_level, last
others = False
while name in self.ANIMATION and level >= last_level:
if name in self.LOOP:
if block != last:
count = self.check_results(tmp_)
if count > -1:
results[count] += 1
tmp_.clear()
tmp_['last'] += 1
for attribute in ('costume', 'orientation', 'position', 'size'):
if (name, 'relative') in self.BLOCKMAPPING[attribute]:
tmp_[(attribute, 'relative')] += 1
elif (name, 'absolute') in self.BLOCKMAPPING[attribute]:
tmp_[(attribute, 'absolute')] += 1
if name in self.TIMING:
tmp_['timing'] += 1
last_level = level
name, level, block = next(gen, ('', 0, ''))
# allow some exceptions
if name not in self.ANIMATION and name != '':
if not others:
if block.type.shape != 'stack':
last_level = level
(name, level, block) = next(gen, ('', 0, ''))
others = True
count = self.check_results(tmp_)
if count > -1:
results[count] += 1
return gen, results
|
[
"def",
"_check_animation",
"(",
"self",
",",
"last",
",",
"last_level",
",",
"gen",
")",
":",
"tmp_",
"=",
"Counter",
"(",
")",
"results",
"=",
"Counter",
"(",
")",
"name",
",",
"level",
",",
"block",
"=",
"last",
",",
"last_level",
",",
"last",
"others",
"=",
"False",
"while",
"name",
"in",
"self",
".",
"ANIMATION",
"and",
"level",
">=",
"last_level",
":",
"if",
"name",
"in",
"self",
".",
"LOOP",
":",
"if",
"block",
"!=",
"last",
":",
"count",
"=",
"self",
".",
"check_results",
"(",
"tmp_",
")",
"if",
"count",
">",
"-",
"1",
":",
"results",
"[",
"count",
"]",
"+=",
"1",
"tmp_",
".",
"clear",
"(",
")",
"tmp_",
"[",
"'last'",
"]",
"+=",
"1",
"for",
"attribute",
"in",
"(",
"'costume'",
",",
"'orientation'",
",",
"'position'",
",",
"'size'",
")",
":",
"if",
"(",
"name",
",",
"'relative'",
")",
"in",
"self",
".",
"BLOCKMAPPING",
"[",
"attribute",
"]",
":",
"tmp_",
"[",
"(",
"attribute",
",",
"'relative'",
")",
"]",
"+=",
"1",
"elif",
"(",
"name",
",",
"'absolute'",
")",
"in",
"self",
".",
"BLOCKMAPPING",
"[",
"attribute",
"]",
":",
"tmp_",
"[",
"(",
"attribute",
",",
"'absolute'",
")",
"]",
"+=",
"1",
"if",
"name",
"in",
"self",
".",
"TIMING",
":",
"tmp_",
"[",
"'timing'",
"]",
"+=",
"1",
"last_level",
"=",
"level",
"name",
",",
"level",
",",
"block",
"=",
"next",
"(",
"gen",
",",
"(",
"''",
",",
"0",
",",
"''",
")",
")",
"# allow some exceptions",
"if",
"name",
"not",
"in",
"self",
".",
"ANIMATION",
"and",
"name",
"!=",
"''",
":",
"if",
"not",
"others",
":",
"if",
"block",
".",
"type",
".",
"shape",
"!=",
"'stack'",
":",
"last_level",
"=",
"level",
"(",
"name",
",",
"level",
",",
"block",
")",
"=",
"next",
"(",
"gen",
",",
"(",
"''",
",",
"0",
",",
"''",
")",
")",
"others",
"=",
"True",
"count",
"=",
"self",
".",
"check_results",
"(",
"tmp_",
")",
"if",
"count",
">",
"-",
"1",
":",
"results",
"[",
"count",
"]",
"+=",
"1",
"return",
"gen",
",",
"results"
] |
Internal helper function to check the animation.
|
[
"Internal",
"helper",
"function",
"to",
"check",
"the",
"animation",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L64-L99
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
Animation.analyze
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the Animation plugin."""
results = Counter()
for script in self.iter_scripts(scratch):
gen = self.iter_blocks(script.blocks)
name = 'start'
level = None
while name != '':
if name in self.ANIMATION:
gen, count = self._check_animation(name, level, gen)
results.update(count)
name, level, _ = next(gen, ('', 0, ''))
return {'animation': results}
|
python
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the Animation plugin."""
results = Counter()
for script in self.iter_scripts(scratch):
gen = self.iter_blocks(script.blocks)
name = 'start'
level = None
while name != '':
if name in self.ANIMATION:
gen, count = self._check_animation(name, level, gen)
results.update(count)
name, level, _ = next(gen, ('', 0, ''))
return {'animation': results}
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"Counter",
"(",
")",
"for",
"script",
"in",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
":",
"gen",
"=",
"self",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
"name",
"=",
"'start'",
"level",
"=",
"None",
"while",
"name",
"!=",
"''",
":",
"if",
"name",
"in",
"self",
".",
"ANIMATION",
":",
"gen",
",",
"count",
"=",
"self",
".",
"_check_animation",
"(",
"name",
",",
"level",
",",
"gen",
")",
"results",
".",
"update",
"(",
"count",
")",
"name",
",",
"level",
",",
"_",
"=",
"next",
"(",
"gen",
",",
"(",
"''",
",",
"0",
",",
"''",
")",
")",
"return",
"{",
"'animation'",
":",
"results",
"}"
] |
Run and return the results from the Animation plugin.
|
[
"Run",
"and",
"return",
"the",
"results",
"from",
"the",
"Animation",
"plugin",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L101-L113
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
BroadcastReceive.get_receive
|
def get_receive(self, script_list):
"""Return a list of received events contained in script_list."""
events = defaultdict(set)
for script in script_list:
if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE:
event = script.blocks[0].args[0].lower()
events[event].add(script)
return events
|
python
|
def get_receive(self, script_list):
"""Return a list of received events contained in script_list."""
events = defaultdict(set)
for script in script_list:
if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE:
event = script.blocks[0].args[0].lower()
events[event].add(script)
return events
|
[
"def",
"get_receive",
"(",
"self",
",",
"script_list",
")",
":",
"events",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"script",
"in",
"script_list",
":",
"if",
"self",
".",
"script_start_type",
"(",
"script",
")",
"==",
"self",
".",
"HAT_WHEN_I_RECEIVE",
":",
"event",
"=",
"script",
".",
"blocks",
"[",
"0",
"]",
".",
"args",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"events",
"[",
"event",
"]",
".",
"add",
"(",
"script",
")",
"return",
"events"
] |
Return a list of received events contained in script_list.
|
[
"Return",
"a",
"list",
"of",
"received",
"events",
"contained",
"in",
"script_list",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L120-L127
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
BroadcastReceive.analyze
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the BroadcastReceive plugin."""
all_scripts = list(self.iter_scripts(scratch))
results = defaultdict(set)
broadcast = dict((x, self.get_broadcast_events(x)) # Events by script
for x in all_scripts)
correct = self.get_receive(all_scripts)
results['never broadcast'] = set(correct.keys())
for script, events in broadcast.items():
for event in events.keys():
if event is True: # Remove dynamic broadcasts
results['dynamic broadcast'].add(script.morph.name)
del events[event]
elif event in correct:
results['never broadcast'].discard(event)
else:
results['never received'].add(event)
# remove events from correct dict that were never broadcast
for event in correct.keys():
if event in results['never broadcast']:
del correct[event]
# Find scripts that have more than one broadcast event on any possible
# execution path through the program
# TODO: Permit mutually exclusive broadcasts
for events in broadcast.values():
if len(events) > 1:
for event in events:
if event in correct:
results['parallel broadcasts'].add(event)
del correct[event]
# Find events that have two (or more) receivers in which one of the
# receivers has a "delay" block
for event, scripts in correct.items():
if len(scripts) > 1:
for script in scripts:
for _, _, block in self.iter_blocks(script.blocks):
if block.type.shape == 'stack':
results['multiple receivers with delay'].add(event)
if event in correct:
del correct[event]
results['success'] = set(correct.keys())
return {'broadcast': results}
|
python
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the BroadcastReceive plugin."""
all_scripts = list(self.iter_scripts(scratch))
results = defaultdict(set)
broadcast = dict((x, self.get_broadcast_events(x)) # Events by script
for x in all_scripts)
correct = self.get_receive(all_scripts)
results['never broadcast'] = set(correct.keys())
for script, events in broadcast.items():
for event in events.keys():
if event is True: # Remove dynamic broadcasts
results['dynamic broadcast'].add(script.morph.name)
del events[event]
elif event in correct:
results['never broadcast'].discard(event)
else:
results['never received'].add(event)
# remove events from correct dict that were never broadcast
for event in correct.keys():
if event in results['never broadcast']:
del correct[event]
# Find scripts that have more than one broadcast event on any possible
# execution path through the program
# TODO: Permit mutually exclusive broadcasts
for events in broadcast.values():
if len(events) > 1:
for event in events:
if event in correct:
results['parallel broadcasts'].add(event)
del correct[event]
# Find events that have two (or more) receivers in which one of the
# receivers has a "delay" block
for event, scripts in correct.items():
if len(scripts) > 1:
for script in scripts:
for _, _, block in self.iter_blocks(script.blocks):
if block.type.shape == 'stack':
results['multiple receivers with delay'].add(event)
if event in correct:
del correct[event]
results['success'] = set(correct.keys())
return {'broadcast': results}
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"all_scripts",
"=",
"list",
"(",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
")",
"results",
"=",
"defaultdict",
"(",
"set",
")",
"broadcast",
"=",
"dict",
"(",
"(",
"x",
",",
"self",
".",
"get_broadcast_events",
"(",
"x",
")",
")",
"# Events by script",
"for",
"x",
"in",
"all_scripts",
")",
"correct",
"=",
"self",
".",
"get_receive",
"(",
"all_scripts",
")",
"results",
"[",
"'never broadcast'",
"]",
"=",
"set",
"(",
"correct",
".",
"keys",
"(",
")",
")",
"for",
"script",
",",
"events",
"in",
"broadcast",
".",
"items",
"(",
")",
":",
"for",
"event",
"in",
"events",
".",
"keys",
"(",
")",
":",
"if",
"event",
"is",
"True",
":",
"# Remove dynamic broadcasts",
"results",
"[",
"'dynamic broadcast'",
"]",
".",
"add",
"(",
"script",
".",
"morph",
".",
"name",
")",
"del",
"events",
"[",
"event",
"]",
"elif",
"event",
"in",
"correct",
":",
"results",
"[",
"'never broadcast'",
"]",
".",
"discard",
"(",
"event",
")",
"else",
":",
"results",
"[",
"'never received'",
"]",
".",
"add",
"(",
"event",
")",
"# remove events from correct dict that were never broadcast",
"for",
"event",
"in",
"correct",
".",
"keys",
"(",
")",
":",
"if",
"event",
"in",
"results",
"[",
"'never broadcast'",
"]",
":",
"del",
"correct",
"[",
"event",
"]",
"# Find scripts that have more than one broadcast event on any possible",
"# execution path through the program",
"# TODO: Permit mutually exclusive broadcasts",
"for",
"events",
"in",
"broadcast",
".",
"values",
"(",
")",
":",
"if",
"len",
"(",
"events",
")",
">",
"1",
":",
"for",
"event",
"in",
"events",
":",
"if",
"event",
"in",
"correct",
":",
"results",
"[",
"'parallel broadcasts'",
"]",
".",
"add",
"(",
"event",
")",
"del",
"correct",
"[",
"event",
"]",
"# Find events that have two (or more) receivers in which one of the",
"# receivers has a \"delay\" block",
"for",
"event",
",",
"scripts",
"in",
"correct",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"scripts",
")",
">",
"1",
":",
"for",
"script",
"in",
"scripts",
":",
"for",
"_",
",",
"_",
",",
"block",
"in",
"self",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
":",
"if",
"block",
".",
"type",
".",
"shape",
"==",
"'stack'",
":",
"results",
"[",
"'multiple receivers with delay'",
"]",
".",
"add",
"(",
"event",
")",
"if",
"event",
"in",
"correct",
":",
"del",
"correct",
"[",
"event",
"]",
"results",
"[",
"'success'",
"]",
"=",
"set",
"(",
"correct",
".",
"keys",
"(",
")",
")",
"return",
"{",
"'broadcast'",
":",
"results",
"}"
] |
Run and return the results from the BroadcastReceive plugin.
|
[
"Run",
"and",
"return",
"the",
"results",
"from",
"the",
"BroadcastReceive",
"plugin",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L129-L175
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
SaySoundSync.analyze
|
def analyze(self, scratch, **kwargs):
"""Categorize instances of attempted say and sound synchronization."""
errors = Counter()
for script in self.iter_scripts(scratch):
prev_name, prev_depth, prev_block = '', 0, script.blocks[0]
gen = self.iter_blocks(script.blocks)
for name, depth, block in gen:
if prev_depth == depth:
if prev_name in self.SAY_THINK:
if name == 'play sound %s until done':
if not self.is_blank(prev_block.args[0]):
errors += self.check(gen)
# TODO: What about play sound?
elif prev_name in self.SAY_THINK_DURATION and \
'play sound %s' in name:
errors['1'] += 1
elif prev_name == 'play sound %s':
if name in self.SAY_THINK:
errors[self.INCORRECT] += 1
elif name in self.SAY_THINK_DURATION:
if self.is_blank(block.args[0]):
errors[self.ERROR] += 1
else:
errors[self.HACKISH] += 1
elif prev_name == 'play sound %s until done' and \
name in self.ALL_SAY_THINK:
if not self.is_blank(block.args[0]):
errors[self.INCORRECT] += 1
# TODO: Should there be an else clause here?
prev_name, prev_depth, prev_block = name, depth, block
return {'sound': errors}
|
python
|
def analyze(self, scratch, **kwargs):
"""Categorize instances of attempted say and sound synchronization."""
errors = Counter()
for script in self.iter_scripts(scratch):
prev_name, prev_depth, prev_block = '', 0, script.blocks[0]
gen = self.iter_blocks(script.blocks)
for name, depth, block in gen:
if prev_depth == depth:
if prev_name in self.SAY_THINK:
if name == 'play sound %s until done':
if not self.is_blank(prev_block.args[0]):
errors += self.check(gen)
# TODO: What about play sound?
elif prev_name in self.SAY_THINK_DURATION and \
'play sound %s' in name:
errors['1'] += 1
elif prev_name == 'play sound %s':
if name in self.SAY_THINK:
errors[self.INCORRECT] += 1
elif name in self.SAY_THINK_DURATION:
if self.is_blank(block.args[0]):
errors[self.ERROR] += 1
else:
errors[self.HACKISH] += 1
elif prev_name == 'play sound %s until done' and \
name in self.ALL_SAY_THINK:
if not self.is_blank(block.args[0]):
errors[self.INCORRECT] += 1
# TODO: Should there be an else clause here?
prev_name, prev_depth, prev_block = name, depth, block
return {'sound': errors}
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"Counter",
"(",
")",
"for",
"script",
"in",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
":",
"prev_name",
",",
"prev_depth",
",",
"prev_block",
"=",
"''",
",",
"0",
",",
"script",
".",
"blocks",
"[",
"0",
"]",
"gen",
"=",
"self",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
"for",
"name",
",",
"depth",
",",
"block",
"in",
"gen",
":",
"if",
"prev_depth",
"==",
"depth",
":",
"if",
"prev_name",
"in",
"self",
".",
"SAY_THINK",
":",
"if",
"name",
"==",
"'play sound %s until done'",
":",
"if",
"not",
"self",
".",
"is_blank",
"(",
"prev_block",
".",
"args",
"[",
"0",
"]",
")",
":",
"errors",
"+=",
"self",
".",
"check",
"(",
"gen",
")",
"# TODO: What about play sound?",
"elif",
"prev_name",
"in",
"self",
".",
"SAY_THINK_DURATION",
"and",
"'play sound %s'",
"in",
"name",
":",
"errors",
"[",
"'1'",
"]",
"+=",
"1",
"elif",
"prev_name",
"==",
"'play sound %s'",
":",
"if",
"name",
"in",
"self",
".",
"SAY_THINK",
":",
"errors",
"[",
"self",
".",
"INCORRECT",
"]",
"+=",
"1",
"elif",
"name",
"in",
"self",
".",
"SAY_THINK_DURATION",
":",
"if",
"self",
".",
"is_blank",
"(",
"block",
".",
"args",
"[",
"0",
"]",
")",
":",
"errors",
"[",
"self",
".",
"ERROR",
"]",
"+=",
"1",
"else",
":",
"errors",
"[",
"self",
".",
"HACKISH",
"]",
"+=",
"1",
"elif",
"prev_name",
"==",
"'play sound %s until done'",
"and",
"name",
"in",
"self",
".",
"ALL_SAY_THINK",
":",
"if",
"not",
"self",
".",
"is_blank",
"(",
"block",
".",
"args",
"[",
"0",
"]",
")",
":",
"errors",
"[",
"self",
".",
"INCORRECT",
"]",
"+=",
"1",
"# TODO: Should there be an else clause here?",
"prev_name",
",",
"prev_depth",
",",
"prev_block",
"=",
"name",
",",
"depth",
",",
"block",
"return",
"{",
"'sound'",
":",
"errors",
"}"
] |
Categorize instances of attempted say and sound synchronization.
|
[
"Categorize",
"instances",
"of",
"attempted",
"say",
"and",
"sound",
"synchronization",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L203-L233
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/checks.py
|
SaySoundSync.check
|
def check(self, gen):
"""Check that the last part of the chain matches.
TODO: Fix to handle the following situation that appears to not work
say 'message 1'
play sound until done
say 'message 2'
say 'message 3'
play sound until done
say ''
"""
retval = Counter()
name, _, block = next(gen, ('', 0, ''))
if name in self.SAY_THINK:
if self.is_blank(block.args[0]):
retval[self.CORRECT] += 1
else:
name, _, block = next(gen, ('', 0, ''))
if name == 'play sound %s until done':
# Increment the correct count because we have at least
# one successful instance
retval[self.CORRECT] += 1
# This block represents the beginning of a second
retval += self.check(gen)
else:
retval[self.INCORRECT] += 1
else:
retval[self.INCORRECT] += 1
return retval
|
python
|
def check(self, gen):
"""Check that the last part of the chain matches.
TODO: Fix to handle the following situation that appears to not work
say 'message 1'
play sound until done
say 'message 2'
say 'message 3'
play sound until done
say ''
"""
retval = Counter()
name, _, block = next(gen, ('', 0, ''))
if name in self.SAY_THINK:
if self.is_blank(block.args[0]):
retval[self.CORRECT] += 1
else:
name, _, block = next(gen, ('', 0, ''))
if name == 'play sound %s until done':
# Increment the correct count because we have at least
# one successful instance
retval[self.CORRECT] += 1
# This block represents the beginning of a second
retval += self.check(gen)
else:
retval[self.INCORRECT] += 1
else:
retval[self.INCORRECT] += 1
return retval
|
[
"def",
"check",
"(",
"self",
",",
"gen",
")",
":",
"retval",
"=",
"Counter",
"(",
")",
"name",
",",
"_",
",",
"block",
"=",
"next",
"(",
"gen",
",",
"(",
"''",
",",
"0",
",",
"''",
")",
")",
"if",
"name",
"in",
"self",
".",
"SAY_THINK",
":",
"if",
"self",
".",
"is_blank",
"(",
"block",
".",
"args",
"[",
"0",
"]",
")",
":",
"retval",
"[",
"self",
".",
"CORRECT",
"]",
"+=",
"1",
"else",
":",
"name",
",",
"_",
",",
"block",
"=",
"next",
"(",
"gen",
",",
"(",
"''",
",",
"0",
",",
"''",
")",
")",
"if",
"name",
"==",
"'play sound %s until done'",
":",
"# Increment the correct count because we have at least",
"# one successful instance",
"retval",
"[",
"self",
".",
"CORRECT",
"]",
"+=",
"1",
"# This block represents the beginning of a second",
"retval",
"+=",
"self",
".",
"check",
"(",
"gen",
")",
"else",
":",
"retval",
"[",
"self",
".",
"INCORRECT",
"]",
"+=",
"1",
"else",
":",
"retval",
"[",
"self",
".",
"INCORRECT",
"]",
"+=",
"1",
"return",
"retval"
] |
Check that the last part of the chain matches.
TODO: Fix to handle the following situation that appears to not work
say 'message 1'
play sound until done
say 'message 2'
say 'message 3'
play sound until done
say ''
|
[
"Check",
"that",
"the",
"last",
"part",
"of",
"the",
"chain",
"matches",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L235-L265
|
train
|
scalative/haas
|
haas/result.py
|
_format_exception
|
def _format_exception(err, is_failure, stdout=None, stderr=None):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and _is_relevant_tb_level(tb):
tb = tb.tb_next
if is_failure:
# Skip assert*() traceback levels
length = _count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
encoding = locale.getpreferredencoding()
msgLines = [_decode(line, encoding) for line in msgLines]
if stdout:
if not stdout.endswith('\n'):
stdout += '\n'
msgLines.append(STDOUT_LINE % stdout)
if stderr:
if not stderr.endswith('\n'):
stderr += '\n'
msgLines.append(STDERR_LINE % stderr)
return ''.join(msgLines)
|
python
|
def _format_exception(err, is_failure, stdout=None, stderr=None):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and _is_relevant_tb_level(tb):
tb = tb.tb_next
if is_failure:
# Skip assert*() traceback levels
length = _count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
encoding = locale.getpreferredencoding()
msgLines = [_decode(line, encoding) for line in msgLines]
if stdout:
if not stdout.endswith('\n'):
stdout += '\n'
msgLines.append(STDOUT_LINE % stdout)
if stderr:
if not stderr.endswith('\n'):
stderr += '\n'
msgLines.append(STDERR_LINE % stderr)
return ''.join(msgLines)
|
[
"def",
"_format_exception",
"(",
"err",
",",
"is_failure",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"exctype",
",",
"value",
",",
"tb",
"=",
"err",
"# Skip test runner traceback levels",
"while",
"tb",
"and",
"_is_relevant_tb_level",
"(",
"tb",
")",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"if",
"is_failure",
":",
"# Skip assert*() traceback levels",
"length",
"=",
"_count_relevant_tb_levels",
"(",
"tb",
")",
"msgLines",
"=",
"traceback",
".",
"format_exception",
"(",
"exctype",
",",
"value",
",",
"tb",
",",
"length",
")",
"else",
":",
"msgLines",
"=",
"traceback",
".",
"format_exception",
"(",
"exctype",
",",
"value",
",",
"tb",
")",
"encoding",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"msgLines",
"=",
"[",
"_decode",
"(",
"line",
",",
"encoding",
")",
"for",
"line",
"in",
"msgLines",
"]",
"if",
"stdout",
":",
"if",
"not",
"stdout",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"stdout",
"+=",
"'\\n'",
"msgLines",
".",
"append",
"(",
"STDOUT_LINE",
"%",
"stdout",
")",
"if",
"stderr",
":",
"if",
"not",
"stderr",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"stderr",
"+=",
"'\\n'",
"msgLines",
".",
"append",
"(",
"STDERR_LINE",
"%",
"stderr",
")",
"return",
"''",
".",
"join",
"(",
"msgLines",
")"
] |
Converts a sys.exc_info()-style tuple of values into a string.
|
[
"Converts",
"a",
"sys",
".",
"exc_info",
"()",
"-",
"style",
"tuple",
"of",
"values",
"into",
"a",
"string",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L76-L101
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector._setup_stdout
|
def _setup_stdout(self):
"""Hook stdout and stderr if buffering is enabled.
"""
if self.buffer:
if self._stderr_buffer is None:
self._stderr_buffer = StringIO()
self._stdout_buffer = StringIO()
sys.stdout = self._stdout_buffer
sys.stderr = self._stderr_buffer
|
python
|
def _setup_stdout(self):
"""Hook stdout and stderr if buffering is enabled.
"""
if self.buffer:
if self._stderr_buffer is None:
self._stderr_buffer = StringIO()
self._stdout_buffer = StringIO()
sys.stdout = self._stdout_buffer
sys.stderr = self._stderr_buffer
|
[
"def",
"_setup_stdout",
"(",
"self",
")",
":",
"if",
"self",
".",
"buffer",
":",
"if",
"self",
".",
"_stderr_buffer",
"is",
"None",
":",
"self",
".",
"_stderr_buffer",
"=",
"StringIO",
"(",
")",
"self",
".",
"_stdout_buffer",
"=",
"StringIO",
"(",
")",
"sys",
".",
"stdout",
"=",
"self",
".",
"_stdout_buffer",
"sys",
".",
"stderr",
"=",
"self",
".",
"_stderr_buffer"
] |
Hook stdout and stderr if buffering is enabled.
|
[
"Hook",
"stdout",
"and",
"stderr",
"if",
"buffering",
"is",
"enabled",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L365-L374
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector._restore_stdout
|
def _restore_stdout(self):
"""Unhook stdout and stderr if buffering is enabled.
"""
if self.buffer:
if self._mirror_output:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
|
python
|
def _restore_stdout(self):
"""Unhook stdout and stderr if buffering is enabled.
"""
if self.buffer:
if self._mirror_output:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
|
[
"def",
"_restore_stdout",
"(",
"self",
")",
":",
"if",
"self",
".",
"buffer",
":",
"if",
"self",
".",
"_mirror_output",
":",
"output",
"=",
"sys",
".",
"stdout",
".",
"getvalue",
"(",
")",
"error",
"=",
"sys",
".",
"stderr",
".",
"getvalue",
"(",
")",
"if",
"output",
":",
"if",
"not",
"output",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"output",
"+=",
"'\\n'",
"self",
".",
"_original_stdout",
".",
"write",
"(",
"STDOUT_LINE",
"%",
"output",
")",
"if",
"error",
":",
"if",
"not",
"error",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"error",
"+=",
"'\\n'",
"self",
".",
"_original_stderr",
".",
"write",
"(",
"STDERR_LINE",
"%",
"error",
")",
"sys",
".",
"stdout",
"=",
"self",
".",
"_original_stdout",
"sys",
".",
"stderr",
"=",
"self",
".",
"_original_stderr",
"self",
".",
"_stdout_buffer",
".",
"seek",
"(",
"0",
")",
"self",
".",
"_stdout_buffer",
".",
"truncate",
"(",
")",
"self",
".",
"_stderr_buffer",
".",
"seek",
"(",
"0",
")",
"self",
".",
"_stderr_buffer",
".",
"truncate",
"(",
")"
] |
Unhook stdout and stderr if buffering is enabled.
|
[
"Unhook",
"stdout",
"and",
"stderr",
"if",
"buffering",
"is",
"enabled",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L376-L398
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.add_result_handler
|
def add_result_handler(self, handler):
"""Register a new result handler.
"""
self._result_handlers.append(handler)
# Reset sorted handlers
if self._sorted_handlers:
self._sorted_handlers = None
|
python
|
def add_result_handler(self, handler):
"""Register a new result handler.
"""
self._result_handlers.append(handler)
# Reset sorted handlers
if self._sorted_handlers:
self._sorted_handlers = None
|
[
"def",
"add_result_handler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_result_handlers",
".",
"append",
"(",
"handler",
")",
"# Reset sorted handlers",
"if",
"self",
".",
"_sorted_handlers",
":",
"self",
".",
"_sorted_handlers",
"=",
"None"
] |
Register a new result handler.
|
[
"Register",
"a",
"new",
"result",
"handler",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L404-L411
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.add_result
|
def add_result(self, result):
"""Add an already-constructed :class:`~.TestResult` to this
:class:`~.ResultCollector`.
This may be used when collecting results created by other
ResultCollectors (e.g. in subprocesses).
"""
for handler in self._handlers:
handler(result)
if self._successful and result.status not in _successful_results:
self._successful = False
|
python
|
def add_result(self, result):
"""Add an already-constructed :class:`~.TestResult` to this
:class:`~.ResultCollector`.
This may be used when collecting results created by other
ResultCollectors (e.g. in subprocesses).
"""
for handler in self._handlers:
handler(result)
if self._successful and result.status not in _successful_results:
self._successful = False
|
[
"def",
"add_result",
"(",
"self",
",",
"result",
")",
":",
"for",
"handler",
"in",
"self",
".",
"_handlers",
":",
"handler",
"(",
"result",
")",
"if",
"self",
".",
"_successful",
"and",
"result",
".",
"status",
"not",
"in",
"_successful_results",
":",
"self",
".",
"_successful",
"=",
"False"
] |
Add an already-constructed :class:`~.TestResult` to this
:class:`~.ResultCollector`.
This may be used when collecting results created by other
ResultCollectors (e.g. in subprocesses).
|
[
"Add",
"an",
"already",
"-",
"constructed",
":",
"class",
":",
"~",
".",
"TestResult",
"to",
"this",
":",
"class",
":",
"~",
".",
"ResultCollector",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L462-L473
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector._handle_result
|
def _handle_result(self, test, status, exception=None, message=None):
"""Create a :class:`~.TestResult` and add it to this
:class:`~ResultCollector`.
Parameters
----------
test : unittest.TestCase
The test that this result will represent.
status : haas.result.TestCompletionStatus
The status of the test.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
message : str
Optional message associated with the result (e.g. skip
reason).
"""
if self.buffer:
stderr = self._stderr_buffer.getvalue()
stdout = self._stdout_buffer.getvalue()
else:
stderr = stdout = None
started_time = self._test_timing.get(self._testcase_to_key(test))
if started_time is None and isinstance(test, ErrorHolder):
started_time = datetime.utcnow()
elif started_time is None:
raise RuntimeError(
'Missing test start! Please report this error as a bug in '
'haas.')
completion_time = datetime.utcnow()
duration = TestDuration(started_time, completion_time)
result = TestResult.from_test_case(
test,
status,
duration=duration,
exception=exception,
message=message,
stdout=stdout,
stderr=stderr,
)
self.add_result(result)
return result
|
python
|
def _handle_result(self, test, status, exception=None, message=None):
"""Create a :class:`~.TestResult` and add it to this
:class:`~ResultCollector`.
Parameters
----------
test : unittest.TestCase
The test that this result will represent.
status : haas.result.TestCompletionStatus
The status of the test.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
message : str
Optional message associated with the result (e.g. skip
reason).
"""
if self.buffer:
stderr = self._stderr_buffer.getvalue()
stdout = self._stdout_buffer.getvalue()
else:
stderr = stdout = None
started_time = self._test_timing.get(self._testcase_to_key(test))
if started_time is None and isinstance(test, ErrorHolder):
started_time = datetime.utcnow()
elif started_time is None:
raise RuntimeError(
'Missing test start! Please report this error as a bug in '
'haas.')
completion_time = datetime.utcnow()
duration = TestDuration(started_time, completion_time)
result = TestResult.from_test_case(
test,
status,
duration=duration,
exception=exception,
message=message,
stdout=stdout,
stderr=stderr,
)
self.add_result(result)
return result
|
[
"def",
"_handle_result",
"(",
"self",
",",
"test",
",",
"status",
",",
"exception",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"if",
"self",
".",
"buffer",
":",
"stderr",
"=",
"self",
".",
"_stderr_buffer",
".",
"getvalue",
"(",
")",
"stdout",
"=",
"self",
".",
"_stdout_buffer",
".",
"getvalue",
"(",
")",
"else",
":",
"stderr",
"=",
"stdout",
"=",
"None",
"started_time",
"=",
"self",
".",
"_test_timing",
".",
"get",
"(",
"self",
".",
"_testcase_to_key",
"(",
"test",
")",
")",
"if",
"started_time",
"is",
"None",
"and",
"isinstance",
"(",
"test",
",",
"ErrorHolder",
")",
":",
"started_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"elif",
"started_time",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Missing test start! Please report this error as a bug in '",
"'haas.'",
")",
"completion_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"duration",
"=",
"TestDuration",
"(",
"started_time",
",",
"completion_time",
")",
"result",
"=",
"TestResult",
".",
"from_test_case",
"(",
"test",
",",
"status",
",",
"duration",
"=",
"duration",
",",
"exception",
"=",
"exception",
",",
"message",
"=",
"message",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
",",
")",
"self",
".",
"add_result",
"(",
"result",
")",
"return",
"result"
] |
Create a :class:`~.TestResult` and add it to this
:class:`~ResultCollector`.
Parameters
----------
test : unittest.TestCase
The test that this result will represent.
status : haas.result.TestCompletionStatus
The status of the test.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
message : str
Optional message associated with the result (e.g. skip
reason).
|
[
"Create",
"a",
":",
"class",
":",
"~",
".",
"TestResult",
"and",
"add",
"it",
"to",
"this",
":",
"class",
":",
"~ResultCollector",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L475-L518
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.addError
|
def addError(self, test, exception):
"""Register that a test ended in an error.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.error, exception=exception)
self.errors.append(result)
self._mirror_output = True
|
python
|
def addError(self, test, exception):
"""Register that a test ended in an error.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.error, exception=exception)
self.errors.append(result)
self._mirror_output = True
|
[
"def",
"addError",
"(",
"self",
",",
"test",
",",
"exception",
")",
":",
"result",
"=",
"self",
".",
"_handle_result",
"(",
"test",
",",
"TestCompletionStatus",
".",
"error",
",",
"exception",
"=",
"exception",
")",
"self",
".",
"errors",
".",
"append",
"(",
"result",
")",
"self",
".",
"_mirror_output",
"=",
"True"
] |
Register that a test ended in an error.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
|
[
"Register",
"that",
"a",
"test",
"ended",
"in",
"an",
"error",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L521-L535
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.addFailure
|
def addFailure(self, test, exception):
"""Register that a test ended with a failure.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.failure, exception=exception)
self.failures.append(result)
self._mirror_output = True
|
python
|
def addFailure(self, test, exception):
"""Register that a test ended with a failure.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.failure, exception=exception)
self.failures.append(result)
self._mirror_output = True
|
[
"def",
"addFailure",
"(",
"self",
",",
"test",
",",
"exception",
")",
":",
"result",
"=",
"self",
".",
"_handle_result",
"(",
"test",
",",
"TestCompletionStatus",
".",
"failure",
",",
"exception",
"=",
"exception",
")",
"self",
".",
"failures",
".",
"append",
"(",
"result",
")",
"self",
".",
"_mirror_output",
"=",
"True"
] |
Register that a test ended with a failure.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
|
[
"Register",
"that",
"a",
"test",
"ended",
"with",
"a",
"failure",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L538-L552
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.addSkip
|
def addSkip(self, test, reason):
"""Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped.
"""
result = self._handle_result(
test, TestCompletionStatus.skipped, message=reason)
self.skipped.append(result)
|
python
|
def addSkip(self, test, reason):
"""Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped.
"""
result = self._handle_result(
test, TestCompletionStatus.skipped, message=reason)
self.skipped.append(result)
|
[
"def",
"addSkip",
"(",
"self",
",",
"test",
",",
"reason",
")",
":",
"result",
"=",
"self",
".",
"_handle_result",
"(",
"test",
",",
"TestCompletionStatus",
".",
"skipped",
",",
"message",
"=",
"reason",
")",
"self",
".",
"skipped",
".",
"append",
"(",
"result",
")"
] |
Register that a test that was skipped.
Parameters
----------
test : unittest.TestCase
The test that has completed.
reason : str
The reason the test was skipped.
|
[
"Register",
"that",
"a",
"test",
"that",
"was",
"skipped",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L565-L578
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.addExpectedFailure
|
def addExpectedFailure(self, test, exception):
"""Register that a test that failed and was expected to fail.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.expected_failure, exception=exception)
self.expectedFailures.append(result)
|
python
|
def addExpectedFailure(self, test, exception):
"""Register that a test that failed and was expected to fail.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
"""
result = self._handle_result(
test, TestCompletionStatus.expected_failure, exception=exception)
self.expectedFailures.append(result)
|
[
"def",
"addExpectedFailure",
"(",
"self",
",",
"test",
",",
"exception",
")",
":",
"result",
"=",
"self",
".",
"_handle_result",
"(",
"test",
",",
"TestCompletionStatus",
".",
"expected_failure",
",",
"exception",
"=",
"exception",
")",
"self",
".",
"expectedFailures",
".",
"append",
"(",
"result",
")"
] |
Register that a test that failed and was expected to fail.
Parameters
----------
test : unittest.TestCase
The test that has completed.
exception : tuple
``exc_info`` tuple ``(type, value, traceback)``.
|
[
"Register",
"that",
"a",
"test",
"that",
"failed",
"and",
"was",
"expected",
"to",
"fail",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L580-L593
|
train
|
scalative/haas
|
haas/result.py
|
ResultCollector.addUnexpectedSuccess
|
def addUnexpectedSuccess(self, test):
"""Register a test that passed unexpectedly.
Parameters
----------
test : unittest.TestCase
The test that has completed.
"""
result = self._handle_result(
test, TestCompletionStatus.unexpected_success)
self.unexpectedSuccesses.append(result)
|
python
|
def addUnexpectedSuccess(self, test):
"""Register a test that passed unexpectedly.
Parameters
----------
test : unittest.TestCase
The test that has completed.
"""
result = self._handle_result(
test, TestCompletionStatus.unexpected_success)
self.unexpectedSuccesses.append(result)
|
[
"def",
"addUnexpectedSuccess",
"(",
"self",
",",
"test",
")",
":",
"result",
"=",
"self",
".",
"_handle_result",
"(",
"test",
",",
"TestCompletionStatus",
".",
"unexpected_success",
")",
"self",
".",
"unexpectedSuccesses",
".",
"append",
"(",
"result",
")"
] |
Register a test that passed unexpectedly.
Parameters
----------
test : unittest.TestCase
The test that has completed.
|
[
"Register",
"a",
"test",
"that",
"passed",
"unexpectedly",
"."
] |
72c05216a2a80e5ee94d9cd8d05ed2b188725027
|
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L596-L607
|
train
|
timgabets/bpc8583
|
bpc8583/terminal.py
|
Terminal.set_terminal_key
|
def set_terminal_key(self, encrypted_key):
"""
Change the terminal key. The encrypted_key is a hex string.
encrypted_key is expected to be encrypted under master key
"""
if encrypted_key:
try:
new_key = bytes.fromhex(encrypted_key)
if len(self.terminal_key) != len(new_key):
# The keys must have equal length
return False
self.terminal_key = self.tmk_cipher.decrypt(new_key)
self.store_terminal_key(raw2str(self.terminal_key))
self.tpk_cipher = DES3.new(self.terminal_key, DES3.MODE_ECB)
self.print_keys()
return True
except ValueError:
return False
return False
|
python
|
def set_terminal_key(self, encrypted_key):
"""
Change the terminal key. The encrypted_key is a hex string.
encrypted_key is expected to be encrypted under master key
"""
if encrypted_key:
try:
new_key = bytes.fromhex(encrypted_key)
if len(self.terminal_key) != len(new_key):
# The keys must have equal length
return False
self.terminal_key = self.tmk_cipher.decrypt(new_key)
self.store_terminal_key(raw2str(self.terminal_key))
self.tpk_cipher = DES3.new(self.terminal_key, DES3.MODE_ECB)
self.print_keys()
return True
except ValueError:
return False
return False
|
[
"def",
"set_terminal_key",
"(",
"self",
",",
"encrypted_key",
")",
":",
"if",
"encrypted_key",
":",
"try",
":",
"new_key",
"=",
"bytes",
".",
"fromhex",
"(",
"encrypted_key",
")",
"if",
"len",
"(",
"self",
".",
"terminal_key",
")",
"!=",
"len",
"(",
"new_key",
")",
":",
"# The keys must have equal length",
"return",
"False",
"self",
".",
"terminal_key",
"=",
"self",
".",
"tmk_cipher",
".",
"decrypt",
"(",
"new_key",
")",
"self",
".",
"store_terminal_key",
"(",
"raw2str",
"(",
"self",
".",
"terminal_key",
")",
")",
"self",
".",
"tpk_cipher",
"=",
"DES3",
".",
"new",
"(",
"self",
".",
"terminal_key",
",",
"DES3",
".",
"MODE_ECB",
")",
"self",
".",
"print_keys",
"(",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"return",
"False"
] |
Change the terminal key. The encrypted_key is a hex string.
encrypted_key is expected to be encrypted under master key
|
[
"Change",
"the",
"terminal",
"key",
".",
"The",
"encrypted_key",
"is",
"a",
"hex",
"string",
".",
"encrypted_key",
"is",
"expected",
"to",
"be",
"encrypted",
"under",
"master",
"key"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L144-L166
|
train
|
timgabets/bpc8583
|
bpc8583/terminal.py
|
Terminal.get_encrypted_pin
|
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
pinblock = bytes.fromhex(get_pinblock(clear_pin, card_number))
#print('PIN block: {}'.format(raw2str(pinblock)))
except TypeError:
return ''
encrypted_pinblock = self.tpk_cipher.encrypt(pinblock)
return raw2str(encrypted_pinblock)
else:
print('Unsupported PIN Block format')
return ''
|
python
|
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
pinblock = bytes.fromhex(get_pinblock(clear_pin, card_number))
#print('PIN block: {}'.format(raw2str(pinblock)))
except TypeError:
return ''
encrypted_pinblock = self.tpk_cipher.encrypt(pinblock)
return raw2str(encrypted_pinblock)
else:
print('Unsupported PIN Block format')
return ''
|
[
"def",
"get_encrypted_pin",
"(",
"self",
",",
"clear_pin",
",",
"card_number",
")",
":",
"if",
"not",
"self",
".",
"terminal_key",
":",
"print",
"(",
"'Terminal key is not set'",
")",
"return",
"''",
"if",
"self",
".",
"pinblock_format",
"==",
"'01'",
":",
"try",
":",
"pinblock",
"=",
"bytes",
".",
"fromhex",
"(",
"get_pinblock",
"(",
"clear_pin",
",",
"card_number",
")",
")",
"#print('PIN block: {}'.format(raw2str(pinblock)))",
"except",
"TypeError",
":",
"return",
"''",
"encrypted_pinblock",
"=",
"self",
".",
"tpk_cipher",
".",
"encrypt",
"(",
"pinblock",
")",
"return",
"raw2str",
"(",
"encrypted_pinblock",
")",
"else",
":",
"print",
"(",
"'Unsupported PIN Block format'",
")",
"return",
"''"
] |
Get PIN block in ISO 0 format, encrypted with the terminal key
|
[
"Get",
"PIN",
"block",
"in",
"ISO",
"0",
"format",
"encrypted",
"with",
"the",
"terminal",
"key"
] |
1b8e95d73ad273ad9d11bff40d1af3f06f0f3503
|
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L176-L196
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_url
|
def is_url(string, allowed_schemes=None):
"""
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
"""
if not is_full_string(string):
return False
valid = bool(URL_RE.search(string))
if allowed_schemes:
return valid and any([string.startswith(s) for s in allowed_schemes])
return valid
|
python
|
def is_url(string, allowed_schemes=None):
"""
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
"""
if not is_full_string(string):
return False
valid = bool(URL_RE.search(string))
if allowed_schemes:
return valid and any([string.startswith(s) for s in allowed_schemes])
return valid
|
[
"def",
"is_url",
"(",
"string",
",",
"allowed_schemes",
"=",
"None",
")",
":",
"if",
"not",
"is_full_string",
"(",
"string",
")",
":",
"return",
"False",
"valid",
"=",
"bool",
"(",
"URL_RE",
".",
"search",
"(",
"string",
")",
")",
"if",
"allowed_schemes",
":",
"return",
"valid",
"and",
"any",
"(",
"[",
"string",
".",
"startswith",
"(",
"s",
")",
"for",
"s",
"in",
"allowed_schemes",
"]",
")",
"return",
"valid"
] |
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
|
[
"Check",
"if",
"a",
"string",
"is",
"a",
"valid",
"url",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L184-L198
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_credit_card
|
def is_credit_card(string, card_type=None):
"""
Checks if a string is a valid credit card number.
If card type is provided then it checks that specific type,
otherwise any known credit card number will be accepted.
:param string: String to check.
:type string: str
:param card_type: Card type.
:type card_type: str
Can be one of these:
* VISA
* MASTERCARD
* AMERICAN_EXPRESS
* DINERS_CLUB
* DISCOVER
* JCB
or None. Default to None (any card).
:return: True if credit card, false otherwise.
:rtype: bool
"""
if not is_full_string(string):
return False
if card_type:
if card_type not in CREDIT_CARDS:
raise KeyError(
'Invalid card type "{}". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys()))
)
return bool(CREDIT_CARDS[card_type].search(string))
for c in CREDIT_CARDS:
if CREDIT_CARDS[c].search(string):
return True
return False
|
python
|
def is_credit_card(string, card_type=None):
"""
Checks if a string is a valid credit card number.
If card type is provided then it checks that specific type,
otherwise any known credit card number will be accepted.
:param string: String to check.
:type string: str
:param card_type: Card type.
:type card_type: str
Can be one of these:
* VISA
* MASTERCARD
* AMERICAN_EXPRESS
* DINERS_CLUB
* DISCOVER
* JCB
or None. Default to None (any card).
:return: True if credit card, false otherwise.
:rtype: bool
"""
if not is_full_string(string):
return False
if card_type:
if card_type not in CREDIT_CARDS:
raise KeyError(
'Invalid card type "{}". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys()))
)
return bool(CREDIT_CARDS[card_type].search(string))
for c in CREDIT_CARDS:
if CREDIT_CARDS[c].search(string):
return True
return False
|
[
"def",
"is_credit_card",
"(",
"string",
",",
"card_type",
"=",
"None",
")",
":",
"if",
"not",
"is_full_string",
"(",
"string",
")",
":",
"return",
"False",
"if",
"card_type",
":",
"if",
"card_type",
"not",
"in",
"CREDIT_CARDS",
":",
"raise",
"KeyError",
"(",
"'Invalid card type \"{}\". Valid types are: {}'",
".",
"format",
"(",
"card_type",
",",
"', '",
".",
"join",
"(",
"CREDIT_CARDS",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"bool",
"(",
"CREDIT_CARDS",
"[",
"card_type",
"]",
".",
"search",
"(",
"string",
")",
")",
"for",
"c",
"in",
"CREDIT_CARDS",
":",
"if",
"CREDIT_CARDS",
"[",
"c",
"]",
".",
"search",
"(",
"string",
")",
":",
"return",
"True",
"return",
"False"
] |
Checks if a string is a valid credit card number.
If card type is provided then it checks that specific type,
otherwise any known credit card number will be accepted.
:param string: String to check.
:type string: str
:param card_type: Card type.
:type card_type: str
Can be one of these:
* VISA
* MASTERCARD
* AMERICAN_EXPRESS
* DINERS_CLUB
* DISCOVER
* JCB
or None. Default to None (any card).
:return: True if credit card, false otherwise.
:rtype: bool
|
[
"Checks",
"if",
"a",
"string",
"is",
"a",
"valid",
"credit",
"card",
"number",
".",
"If",
"card",
"type",
"is",
"provided",
"then",
"it",
"checks",
"that",
"specific",
"type",
"otherwise",
"any",
"known",
"credit",
"card",
"number",
"will",
"be",
"accepted",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L223-L259
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_snake_case
|
def is_snake_case(string, separator='_'):
"""
Checks if a string is formatted as snake case.
A string is considered snake case when:
* it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \
and optionally numbers ([0-9])
* it does not start/end with an underscore (or provided separator)
* it does not start with a number
:param string: String to test.
:type string: str
:param separator: String to use as separator.
:type separator: str
:return: True for a snake case string, false otherwise.
:rtype: bool
"""
if is_full_string(string):
re_map = {
'_': SNAKE_CASE_TEST_RE,
'-': SNAKE_CASE_TEST_DASH_RE
}
re_template = '^[a-z]+([a-z\d]+{sign}|{sign}[a-z\d]+)+[a-z\d]+$'
r = re_map.get(separator, re.compile(re_template.format(sign=re.escape(separator))))
return bool(r.search(string))
return False
|
python
|
def is_snake_case(string, separator='_'):
"""
Checks if a string is formatted as snake case.
A string is considered snake case when:
* it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \
and optionally numbers ([0-9])
* it does not start/end with an underscore (or provided separator)
* it does not start with a number
:param string: String to test.
:type string: str
:param separator: String to use as separator.
:type separator: str
:return: True for a snake case string, false otherwise.
:rtype: bool
"""
if is_full_string(string):
re_map = {
'_': SNAKE_CASE_TEST_RE,
'-': SNAKE_CASE_TEST_DASH_RE
}
re_template = '^[a-z]+([a-z\d]+{sign}|{sign}[a-z\d]+)+[a-z\d]+$'
r = re_map.get(separator, re.compile(re_template.format(sign=re.escape(separator))))
return bool(r.search(string))
return False
|
[
"def",
"is_snake_case",
"(",
"string",
",",
"separator",
"=",
"'_'",
")",
":",
"if",
"is_full_string",
"(",
"string",
")",
":",
"re_map",
"=",
"{",
"'_'",
":",
"SNAKE_CASE_TEST_RE",
",",
"'-'",
":",
"SNAKE_CASE_TEST_DASH_RE",
"}",
"re_template",
"=",
"'^[a-z]+([a-z\\d]+{sign}|{sign}[a-z\\d]+)+[a-z\\d]+$'",
"r",
"=",
"re_map",
".",
"get",
"(",
"separator",
",",
"re",
".",
"compile",
"(",
"re_template",
".",
"format",
"(",
"sign",
"=",
"re",
".",
"escape",
"(",
"separator",
")",
")",
")",
")",
"return",
"bool",
"(",
"r",
".",
"search",
"(",
"string",
")",
")",
"return",
"False"
] |
Checks if a string is formatted as snake case.
A string is considered snake case when:
* it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \
and optionally numbers ([0-9])
* it does not start/end with an underscore (or provided separator)
* it does not start with a number
:param string: String to test.
:type string: str
:param separator: String to use as separator.
:type separator: str
:return: True for a snake case string, false otherwise.
:rtype: bool
|
[
"Checks",
"if",
"a",
"string",
"is",
"formatted",
"as",
"snake",
"case",
".",
"A",
"string",
"is",
"considered",
"snake",
"case",
"when",
":"
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L280-L306
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_json
|
def is_json(string):
"""
Check if a string is a valid json.
:param string: String to check.
:type string: str
:return: True if json, false otherwise
:rtype: bool
"""
if not is_full_string(string):
return False
if bool(JSON_WRAPPER_RE.search(string)):
try:
return isinstance(json.loads(string), dict)
except (TypeError, ValueError, OverflowError):
return False
return False
|
python
|
def is_json(string):
"""
Check if a string is a valid json.
:param string: String to check.
:type string: str
:return: True if json, false otherwise
:rtype: bool
"""
if not is_full_string(string):
return False
if bool(JSON_WRAPPER_RE.search(string)):
try:
return isinstance(json.loads(string), dict)
except (TypeError, ValueError, OverflowError):
return False
return False
|
[
"def",
"is_json",
"(",
"string",
")",
":",
"if",
"not",
"is_full_string",
"(",
"string",
")",
":",
"return",
"False",
"if",
"bool",
"(",
"JSON_WRAPPER_RE",
".",
"search",
"(",
"string",
")",
")",
":",
"try",
":",
"return",
"isinstance",
"(",
"json",
".",
"loads",
"(",
"string",
")",
",",
"dict",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"OverflowError",
")",
":",
"return",
"False",
"return",
"False"
] |
Check if a string is a valid json.
:param string: String to check.
:type string: str
:return: True if json, false otherwise
:rtype: bool
|
[
"Check",
"if",
"a",
"string",
"is",
"a",
"valid",
"json",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L309-L325
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_palindrome
|
def is_palindrome(string, strict=True):
"""
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).
:param string: String to check.
:type string: str
:param strict: True if white spaces matter (default), false otherwise.
:type strict: bool
:return: True if the string is a palindrome (like "otto", or "i topi non avevano nipoti" if strict=False),
False otherwise
"""
if is_full_string(string):
if strict:
return reverse(string) == string
return is_palindrome(SPACES_RE.sub('', string))
return False
|
python
|
def is_palindrome(string, strict=True):
"""
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).
:param string: String to check.
:type string: str
:param strict: True if white spaces matter (default), false otherwise.
:type strict: bool
:return: True if the string is a palindrome (like "otto", or "i topi non avevano nipoti" if strict=False),
False otherwise
"""
if is_full_string(string):
if strict:
return reverse(string) == string
return is_palindrome(SPACES_RE.sub('', string))
return False
|
[
"def",
"is_palindrome",
"(",
"string",
",",
"strict",
"=",
"True",
")",
":",
"if",
"is_full_string",
"(",
"string",
")",
":",
"if",
"strict",
":",
"return",
"reverse",
"(",
"string",
")",
"==",
"string",
"return",
"is_palindrome",
"(",
"SPACES_RE",
".",
"sub",
"(",
"''",
",",
"string",
")",
")",
"return",
"False"
] |
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).
:param string: String to check.
:type string: str
:param strict: True if white spaces matter (default), false otherwise.
:type strict: bool
:return: True if the string is a palindrome (like "otto", or "i topi non avevano nipoti" if strict=False),
False otherwise
|
[
"Checks",
"if",
"the",
"string",
"is",
"a",
"palindrome",
"(",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Palindrome",
")",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L352-L367
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_pangram
|
def is_pangram(string):
"""
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram).
:param string: String to check.
:type string: str
:return: True if the string is a pangram, False otherwise.
"""
return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset(letters_set)
|
python
|
def is_pangram(string):
"""
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram).
:param string: String to check.
:type string: str
:return: True if the string is a pangram, False otherwise.
"""
return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset(letters_set)
|
[
"def",
"is_pangram",
"(",
"string",
")",
":",
"return",
"is_full_string",
"(",
"string",
")",
"and",
"set",
"(",
"SPACES_RE",
".",
"sub",
"(",
"''",
",",
"string",
")",
")",
".",
"issuperset",
"(",
"letters_set",
")"
] |
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram).
:param string: String to check.
:type string: str
:return: True if the string is a pangram, False otherwise.
|
[
"Checks",
"if",
"the",
"string",
"is",
"a",
"pangram",
"(",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Pangram",
")",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L370-L378
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
is_slug
|
def is_slug(string, sign='-'):
"""
Checks if a given string is a slug.
:param string: String to check.
:type string: str
:param sign: Join sign used by the slug.
:type sign: str
:return: True if slug, false otherwise.
"""
if not is_full_string(string):
return False
rex = r'^([a-z\d]+' + re.escape(sign) + r'?)*[a-z\d]$'
return re.match(rex, string) is not None
|
python
|
def is_slug(string, sign='-'):
"""
Checks if a given string is a slug.
:param string: String to check.
:type string: str
:param sign: Join sign used by the slug.
:type sign: str
:return: True if slug, false otherwise.
"""
if not is_full_string(string):
return False
rex = r'^([a-z\d]+' + re.escape(sign) + r'?)*[a-z\d]$'
return re.match(rex, string) is not None
|
[
"def",
"is_slug",
"(",
"string",
",",
"sign",
"=",
"'-'",
")",
":",
"if",
"not",
"is_full_string",
"(",
"string",
")",
":",
"return",
"False",
"rex",
"=",
"r'^([a-z\\d]+'",
"+",
"re",
".",
"escape",
"(",
"sign",
")",
"+",
"r'?)*[a-z\\d]$'",
"return",
"re",
".",
"match",
"(",
"rex",
",",
"string",
")",
"is",
"not",
"None"
] |
Checks if a given string is a slug.
:param string: String to check.
:type string: str
:param sign: Join sign used by the slug.
:type sign: str
:return: True if slug, false otherwise.
|
[
"Checks",
"if",
"a",
"given",
"string",
"is",
"a",
"slug",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L392-L405
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
camel_case_to_snake
|
def camel_case_to_snake(string, separator='_'):
"""
Convert a camel case string into a snake case one.
(The original string is returned if is not a valid camel case string)
:param string: String to convert.
:type string: str
:param separator: Sign to use as separator.
:type separator: str
:return: Converted string.
:rtype: str
"""
if not is_string(string):
raise TypeError('Expected string')
if not is_camel_case(string):
return string
return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, string).lower()
|
python
|
def camel_case_to_snake(string, separator='_'):
"""
Convert a camel case string into a snake case one.
(The original string is returned if is not a valid camel case string)
:param string: String to convert.
:type string: str
:param separator: Sign to use as separator.
:type separator: str
:return: Converted string.
:rtype: str
"""
if not is_string(string):
raise TypeError('Expected string')
if not is_camel_case(string):
return string
return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, string).lower()
|
[
"def",
"camel_case_to_snake",
"(",
"string",
",",
"separator",
"=",
"'_'",
")",
":",
"if",
"not",
"is_string",
"(",
"string",
")",
":",
"raise",
"TypeError",
"(",
"'Expected string'",
")",
"if",
"not",
"is_camel_case",
"(",
"string",
")",
":",
"return",
"string",
"return",
"CAMEL_CASE_REPLACE_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
"+",
"separator",
",",
"string",
")",
".",
"lower",
"(",
")"
] |
Convert a camel case string into a snake case one.
(The original string is returned if is not a valid camel case string)
:param string: String to convert.
:type string: str
:param separator: Sign to use as separator.
:type separator: str
:return: Converted string.
:rtype: str
|
[
"Convert",
"a",
"camel",
"case",
"string",
"into",
"a",
"snake",
"case",
"one",
".",
"(",
"The",
"original",
"string",
"is",
"returned",
"if",
"is",
"not",
"a",
"valid",
"camel",
"case",
"string",
")"
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L453-L469
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
snake_case_to_camel
|
def snake_case_to_camel(string, upper_case_first=True, separator='_'):
"""
Convert a snake case string into a camel case one.
(The original string is returned if is not a valid snake case string)
:param string: String to convert.
:type string: str
:param upper_case_first: True to turn the first letter into uppercase (default).
:type upper_case_first: bool
:param separator: Sign to use as separator (default to "_").
:type separator: str
:return: Converted string
:rtype: str
"""
if not is_string(string):
raise TypeError('Expected string')
if not is_snake_case(string, separator):
return string
re_map = {
'_': SNAKE_CASE_REPLACE_RE,
'-': SNAKE_CASE_REPLACE_DASH_RE
}
r = re_map.get(separator, re.compile('({sign})([a-z\d])'.format(sign=re.escape(separator))))
string = r.sub(lambda m: m.group(2).upper(), string)
if upper_case_first:
return string[0].upper() + string[1:]
return string
|
python
|
def snake_case_to_camel(string, upper_case_first=True, separator='_'):
"""
Convert a snake case string into a camel case one.
(The original string is returned if is not a valid snake case string)
:param string: String to convert.
:type string: str
:param upper_case_first: True to turn the first letter into uppercase (default).
:type upper_case_first: bool
:param separator: Sign to use as separator (default to "_").
:type separator: str
:return: Converted string
:rtype: str
"""
if not is_string(string):
raise TypeError('Expected string')
if not is_snake_case(string, separator):
return string
re_map = {
'_': SNAKE_CASE_REPLACE_RE,
'-': SNAKE_CASE_REPLACE_DASH_RE
}
r = re_map.get(separator, re.compile('({sign})([a-z\d])'.format(sign=re.escape(separator))))
string = r.sub(lambda m: m.group(2).upper(), string)
if upper_case_first:
return string[0].upper() + string[1:]
return string
|
[
"def",
"snake_case_to_camel",
"(",
"string",
",",
"upper_case_first",
"=",
"True",
",",
"separator",
"=",
"'_'",
")",
":",
"if",
"not",
"is_string",
"(",
"string",
")",
":",
"raise",
"TypeError",
"(",
"'Expected string'",
")",
"if",
"not",
"is_snake_case",
"(",
"string",
",",
"separator",
")",
":",
"return",
"string",
"re_map",
"=",
"{",
"'_'",
":",
"SNAKE_CASE_REPLACE_RE",
",",
"'-'",
":",
"SNAKE_CASE_REPLACE_DASH_RE",
"}",
"r",
"=",
"re_map",
".",
"get",
"(",
"separator",
",",
"re",
".",
"compile",
"(",
"'({sign})([a-z\\d])'",
".",
"format",
"(",
"sign",
"=",
"re",
".",
"escape",
"(",
"separator",
")",
")",
")",
")",
"string",
"=",
"r",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"2",
")",
".",
"upper",
"(",
")",
",",
"string",
")",
"if",
"upper_case_first",
":",
"return",
"string",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"string",
"[",
"1",
":",
"]",
"return",
"string"
] |
Convert a snake case string into a camel case one.
(The original string is returned if is not a valid snake case string)
:param string: String to convert.
:type string: str
:param upper_case_first: True to turn the first letter into uppercase (default).
:type upper_case_first: bool
:param separator: Sign to use as separator (default to "_").
:type separator: str
:return: Converted string
:rtype: str
|
[
"Convert",
"a",
"snake",
"case",
"string",
"into",
"a",
"camel",
"case",
"one",
".",
"(",
"The",
"original",
"string",
"is",
"returned",
"if",
"is",
"not",
"a",
"valid",
"snake",
"case",
"string",
")"
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L472-L498
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
shuffle
|
def shuffle(string):
"""
Return a new string containing shuffled items.
:param string: String to shuffle
:type string: str
:return: Shuffled string
:rtype: str
"""
s = sorted(string) # turn the string into a list of chars
random.shuffle(s) # shuffle the list
return ''.join(s)
|
python
|
def shuffle(string):
"""
Return a new string containing shuffled items.
:param string: String to shuffle
:type string: str
:return: Shuffled string
:rtype: str
"""
s = sorted(string) # turn the string into a list of chars
random.shuffle(s) # shuffle the list
return ''.join(s)
|
[
"def",
"shuffle",
"(",
"string",
")",
":",
"s",
"=",
"sorted",
"(",
"string",
")",
"# turn the string into a list of chars",
"random",
".",
"shuffle",
"(",
"s",
")",
"# shuffle the list",
"return",
"''",
".",
"join",
"(",
"s",
")"
] |
Return a new string containing shuffled items.
:param string: String to shuffle
:type string: str
:return: Shuffled string
:rtype: str
|
[
"Return",
"a",
"new",
"string",
"containing",
"shuffled",
"items",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L511-L522
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
strip_html
|
def strip_html(string, keep_tag_content=False):
"""
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
:return: String with html removed.
:rtype: str
"""
r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE
return r.sub('', string)
|
python
|
def strip_html(string, keep_tag_content=False):
"""
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
:return: String with html removed.
:rtype: str
"""
r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE
return r.sub('', string)
|
[
"def",
"strip_html",
"(",
"string",
",",
"keep_tag_content",
"=",
"False",
")",
":",
"r",
"=",
"HTML_TAG_ONLY_RE",
"if",
"keep_tag_content",
"else",
"HTML_RE",
"return",
"r",
".",
"sub",
"(",
"''",
",",
"string",
")"
] |
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
:return: String with html removed.
:rtype: str
|
[
"Remove",
"html",
"code",
"contained",
"into",
"the",
"given",
"string",
"."
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L525-L537
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
prettify
|
def prettify(string):
"""
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following:
- String cannot start or end with spaces
- String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".")
- Arithmetic operators (+, -, /, \*, =) must have one, and only one space before and after themselves
- The first letter after a dot, an exclamation or a question mark must be uppercase
- One, and only one space should follow a dot, an exclamation or a question mark
- Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \
after quotes (foo" bar"baz -> foo "bar" baz)
- Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \
after brackets ("foo(bar )baz" -> "foo (bar) baz")
- Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%")
- Saxon genitive is correct ("Dave' s dog" -> "Dave's dog")
:param string: String to manipulate
:return: Prettified string.
:rtype: str
"""
def remove_duplicates(regex_match):
return regex_match.group(1)[0]
def uppercase_first_letter_after_sign(regex_match):
match = regex_match.group(1)
return match[:-1] + match[2].upper()
def ensure_right_space_only(regex_match):
return regex_match.group(1).strip() + ' '
def ensure_left_space_only(regex_match):
return ' ' + regex_match.group(1).strip()
def ensure_spaces_around(regex_match):
return ' ' + regex_match.group(1).strip() + ' '
def remove_internal_spaces(regex_match):
return regex_match.group(1).strip()
def fix_saxon_genitive(regex_match):
return regex_match.group(1).replace(' ', '') + ' '
p = PRETTIFY_RE['DUPLICATES'].sub(remove_duplicates, string)
p = PRETTIFY_RE['RIGHT_SPACE'].sub(ensure_right_space_only, p)
p = PRETTIFY_RE['LEFT_SPACE'].sub(ensure_left_space_only, p)
p = PRETTIFY_RE['SPACES_AROUND'].sub(ensure_spaces_around, p)
p = PRETTIFY_RE['SPACES_INSIDE'].sub(remove_internal_spaces, p)
p = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(uppercase_first_letter_after_sign, p)
p = PRETTIFY_RE['SAXON_GENITIVE'].sub(fix_saxon_genitive, p)
p = p.strip()
try:
return p[0].capitalize() + p[1:]
except IndexError:
return p
|
python
|
def prettify(string):
"""
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following:
- String cannot start or end with spaces
- String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".")
- Arithmetic operators (+, -, /, \*, =) must have one, and only one space before and after themselves
- The first letter after a dot, an exclamation or a question mark must be uppercase
- One, and only one space should follow a dot, an exclamation or a question mark
- Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \
after quotes (foo" bar"baz -> foo "bar" baz)
- Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \
after brackets ("foo(bar )baz" -> "foo (bar) baz")
- Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%")
- Saxon genitive is correct ("Dave' s dog" -> "Dave's dog")
:param string: String to manipulate
:return: Prettified string.
:rtype: str
"""
def remove_duplicates(regex_match):
return regex_match.group(1)[0]
def uppercase_first_letter_after_sign(regex_match):
match = regex_match.group(1)
return match[:-1] + match[2].upper()
def ensure_right_space_only(regex_match):
return regex_match.group(1).strip() + ' '
def ensure_left_space_only(regex_match):
return ' ' + regex_match.group(1).strip()
def ensure_spaces_around(regex_match):
return ' ' + regex_match.group(1).strip() + ' '
def remove_internal_spaces(regex_match):
return regex_match.group(1).strip()
def fix_saxon_genitive(regex_match):
return regex_match.group(1).replace(' ', '') + ' '
p = PRETTIFY_RE['DUPLICATES'].sub(remove_duplicates, string)
p = PRETTIFY_RE['RIGHT_SPACE'].sub(ensure_right_space_only, p)
p = PRETTIFY_RE['LEFT_SPACE'].sub(ensure_left_space_only, p)
p = PRETTIFY_RE['SPACES_AROUND'].sub(ensure_spaces_around, p)
p = PRETTIFY_RE['SPACES_INSIDE'].sub(remove_internal_spaces, p)
p = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(uppercase_first_letter_after_sign, p)
p = PRETTIFY_RE['SAXON_GENITIVE'].sub(fix_saxon_genitive, p)
p = p.strip()
try:
return p[0].capitalize() + p[1:]
except IndexError:
return p
|
[
"def",
"prettify",
"(",
"string",
")",
":",
"def",
"remove_duplicates",
"(",
"regex_match",
")",
":",
"return",
"regex_match",
".",
"group",
"(",
"1",
")",
"[",
"0",
"]",
"def",
"uppercase_first_letter_after_sign",
"(",
"regex_match",
")",
":",
"match",
"=",
"regex_match",
".",
"group",
"(",
"1",
")",
"return",
"match",
"[",
":",
"-",
"1",
"]",
"+",
"match",
"[",
"2",
"]",
".",
"upper",
"(",
")",
"def",
"ensure_right_space_only",
"(",
"regex_match",
")",
":",
"return",
"regex_match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"+",
"' '",
"def",
"ensure_left_space_only",
"(",
"regex_match",
")",
":",
"return",
"' '",
"+",
"regex_match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"def",
"ensure_spaces_around",
"(",
"regex_match",
")",
":",
"return",
"' '",
"+",
"regex_match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"+",
"' '",
"def",
"remove_internal_spaces",
"(",
"regex_match",
")",
":",
"return",
"regex_match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"def",
"fix_saxon_genitive",
"(",
"regex_match",
")",
":",
"return",
"regex_match",
".",
"group",
"(",
"1",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"+",
"' '",
"p",
"=",
"PRETTIFY_RE",
"[",
"'DUPLICATES'",
"]",
".",
"sub",
"(",
"remove_duplicates",
",",
"string",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'RIGHT_SPACE'",
"]",
".",
"sub",
"(",
"ensure_right_space_only",
",",
"p",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'LEFT_SPACE'",
"]",
".",
"sub",
"(",
"ensure_left_space_only",
",",
"p",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'SPACES_AROUND'",
"]",
".",
"sub",
"(",
"ensure_spaces_around",
",",
"p",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'SPACES_INSIDE'",
"]",
".",
"sub",
"(",
"remove_internal_spaces",
",",
"p",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'UPPERCASE_AFTER_SIGN'",
"]",
".",
"sub",
"(",
"uppercase_first_letter_after_sign",
",",
"p",
")",
"p",
"=",
"PRETTIFY_RE",
"[",
"'SAXON_GENITIVE'",
"]",
".",
"sub",
"(",
"fix_saxon_genitive",
",",
"p",
")",
"p",
"=",
"p",
".",
"strip",
"(",
")",
"try",
":",
"return",
"p",
"[",
"0",
"]",
".",
"capitalize",
"(",
")",
"+",
"p",
"[",
"1",
":",
"]",
"except",
"IndexError",
":",
"return",
"p"
] |
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following:
- String cannot start or end with spaces
- String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".")
- Arithmetic operators (+, -, /, \*, =) must have one, and only one space before and after themselves
- The first letter after a dot, an exclamation or a question mark must be uppercase
- One, and only one space should follow a dot, an exclamation or a question mark
- Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \
after quotes (foo" bar"baz -> foo "bar" baz)
- Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \
after brackets ("foo(bar )baz" -> "foo (bar) baz")
- Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%")
- Saxon genitive is correct ("Dave' s dog" -> "Dave's dog")
:param string: String to manipulate
:return: Prettified string.
:rtype: str
|
[
"Turns",
"an",
"ugly",
"text",
"string",
"into",
"a",
"beautiful",
"one",
"by",
"applying",
"a",
"regex",
"pipeline",
"which",
"ensures",
"the",
"following",
":"
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L540-L595
|
train
|
daveoncode/python-string-utils
|
string_utils.py
|
slugify
|
def slugify(string, sign='-'):
"""
Converts a string into a slug using provided join sign.
(**(This Is A "Test"!)** -> **this-is-a-test**)
:param string: String to convert.
:type string: str
:param sign: Sign used to join string tokens (default to "-").
:type sign: str
:return: Slugified string
"""
if not is_string(string):
raise TypeError('Expected string')
# unicode casting for python 2 (unicode is default for python 3)
try:
string = unicode(string, 'utf-8')
except NameError:
pass
# replace any character that is NOT letter or number with spaces
s = NO_LETTERS_OR_NUMBERS_RE.sub(' ', string.lower()).strip()
# replace spaces with join sign
s = SPACES_RE.sub(sign, s)
# normalize joins (remove duplicates)
s = re.sub(re.escape(sign) + r'+', sign, s)
# translate non-ascii signs
s = unicodedata.normalize('NFD', s).encode('ascii', 'ignore').decode('utf-8')
return s
|
python
|
def slugify(string, sign='-'):
"""
Converts a string into a slug using provided join sign.
(**(This Is A "Test"!)** -> **this-is-a-test**)
:param string: String to convert.
:type string: str
:param sign: Sign used to join string tokens (default to "-").
:type sign: str
:return: Slugified string
"""
if not is_string(string):
raise TypeError('Expected string')
# unicode casting for python 2 (unicode is default for python 3)
try:
string = unicode(string, 'utf-8')
except NameError:
pass
# replace any character that is NOT letter or number with spaces
s = NO_LETTERS_OR_NUMBERS_RE.sub(' ', string.lower()).strip()
# replace spaces with join sign
s = SPACES_RE.sub(sign, s)
# normalize joins (remove duplicates)
s = re.sub(re.escape(sign) + r'+', sign, s)
# translate non-ascii signs
s = unicodedata.normalize('NFD', s).encode('ascii', 'ignore').decode('utf-8')
return s
|
[
"def",
"slugify",
"(",
"string",
",",
"sign",
"=",
"'-'",
")",
":",
"if",
"not",
"is_string",
"(",
"string",
")",
":",
"raise",
"TypeError",
"(",
"'Expected string'",
")",
"# unicode casting for python 2 (unicode is default for python 3)",
"try",
":",
"string",
"=",
"unicode",
"(",
"string",
",",
"'utf-8'",
")",
"except",
"NameError",
":",
"pass",
"# replace any character that is NOT letter or number with spaces",
"s",
"=",
"NO_LETTERS_OR_NUMBERS_RE",
".",
"sub",
"(",
"' '",
",",
"string",
".",
"lower",
"(",
")",
")",
".",
"strip",
"(",
")",
"# replace spaces with join sign",
"s",
"=",
"SPACES_RE",
".",
"sub",
"(",
"sign",
",",
"s",
")",
"# normalize joins (remove duplicates)",
"s",
"=",
"re",
".",
"sub",
"(",
"re",
".",
"escape",
"(",
"sign",
")",
"+",
"r'+'",
",",
"sign",
",",
"s",
")",
"# translate non-ascii signs",
"s",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"s",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"s"
] |
Converts a string into a slug using provided join sign.
(**(This Is A "Test"!)** -> **this-is-a-test**)
:param string: String to convert.
:type string: str
:param sign: Sign used to join string tokens (default to "-").
:type sign: str
:return: Slugified string
|
[
"Converts",
"a",
"string",
"into",
"a",
"slug",
"using",
"provided",
"join",
"sign",
".",
"(",
"**",
"(",
"This",
"Is",
"A",
"Test",
"!",
")",
"**",
"-",
">",
"**",
"this",
"-",
"is",
"-",
"a",
"-",
"test",
"**",
")"
] |
5dfe43c26aeecd01941c598316eb4eb7005a1492
|
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L598-L630
|
train
|
vidartf/nbsphinx-link
|
nbsphinx_link/__init__.py
|
setup
|
def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'parallel_read_safe': True}
|
python
|
def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'parallel_read_safe': True}
|
[
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"setup_extension",
"(",
"'nbsphinx'",
")",
"app",
".",
"add_source_suffix",
"(",
"'.nblink'",
",",
"'linked_jupyter_notebook'",
")",
"app",
".",
"add_source_parser",
"(",
"LinkedNotebookParser",
")",
"app",
".",
"add_config_value",
"(",
"'nbsphinx_link_target_root'",
",",
"None",
",",
"rebuild",
"=",
"'env'",
")",
"return",
"{",
"'version'",
":",
"__version__",
",",
"'parallel_read_safe'",
":",
"True",
"}"
] |
Initialize Sphinx extension.
|
[
"Initialize",
"Sphinx",
"extension",
"."
] |
d64288606a8cc50461792dd3033f5ff081602afc
|
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L100-L107
|
train
|
vidartf/nbsphinx-link
|
nbsphinx_link/__init__.py
|
LinkedNotebookParser.parse
|
def parse(self, inputstring, document):
"""Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
"""
link = json.loads(inputstring)
env = document.settings.env
source_dir = os.path.dirname(env.doc2path(env.docname))
abs_path = os.path.normpath(os.path.join(source_dir, link['path']))
path = utils.relative_path(None, abs_path)
path = nodes.reprunicode(path)
document.settings.record_dependencies.add(path)
env.note_dependency(path)
target_root = env.config.nbsphinx_link_target_root
target = utils.relative_path(target_root, abs_path)
target = nodes.reprunicode(target).replace(os.path.sep, '/')
env.metadata[env.docname]['nbsphinx-link-target'] = target
# Copy parser from nbsphinx for our cutom format
try:
formats = env.config.nbsphinx_custom_formats
except AttributeError:
pass
else:
formats.setdefault(
'.nblink',
lambda s: nbformat.reads(s, as_version=_ipynbversion))
try:
include_file = io.FileInput(source_path=path, encoding='utf8')
except UnicodeEncodeError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n'
'Cannot encode input file path "%s" '
'(wrong locale?).' %
(env.docname, SafeString(path)))
except IOError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n%s.' %
(env.docname, ErrorString(error)))
try:
rawtext = include_file.read()
except UnicodeError as error:
raise NotebookError(u'Problem with linked notebook "%s":\n%s' %
(env.docname, ErrorString(error)))
return super(LinkedNotebookParser, self).parse(rawtext, document)
|
python
|
def parse(self, inputstring, document):
"""Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
"""
link = json.loads(inputstring)
env = document.settings.env
source_dir = os.path.dirname(env.doc2path(env.docname))
abs_path = os.path.normpath(os.path.join(source_dir, link['path']))
path = utils.relative_path(None, abs_path)
path = nodes.reprunicode(path)
document.settings.record_dependencies.add(path)
env.note_dependency(path)
target_root = env.config.nbsphinx_link_target_root
target = utils.relative_path(target_root, abs_path)
target = nodes.reprunicode(target).replace(os.path.sep, '/')
env.metadata[env.docname]['nbsphinx-link-target'] = target
# Copy parser from nbsphinx for our cutom format
try:
formats = env.config.nbsphinx_custom_formats
except AttributeError:
pass
else:
formats.setdefault(
'.nblink',
lambda s: nbformat.reads(s, as_version=_ipynbversion))
try:
include_file = io.FileInput(source_path=path, encoding='utf8')
except UnicodeEncodeError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n'
'Cannot encode input file path "%s" '
'(wrong locale?).' %
(env.docname, SafeString(path)))
except IOError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n%s.' %
(env.docname, ErrorString(error)))
try:
rawtext = include_file.read()
except UnicodeError as error:
raise NotebookError(u'Problem with linked notebook "%s":\n%s' %
(env.docname, ErrorString(error)))
return super(LinkedNotebookParser, self).parse(rawtext, document)
|
[
"def",
"parse",
"(",
"self",
",",
"inputstring",
",",
"document",
")",
":",
"link",
"=",
"json",
".",
"loads",
"(",
"inputstring",
")",
"env",
"=",
"document",
".",
"settings",
".",
"env",
"source_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"env",
".",
"doc2path",
"(",
"env",
".",
"docname",
")",
")",
"abs_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"link",
"[",
"'path'",
"]",
")",
")",
"path",
"=",
"utils",
".",
"relative_path",
"(",
"None",
",",
"abs_path",
")",
"path",
"=",
"nodes",
".",
"reprunicode",
"(",
"path",
")",
"document",
".",
"settings",
".",
"record_dependencies",
".",
"add",
"(",
"path",
")",
"env",
".",
"note_dependency",
"(",
"path",
")",
"target_root",
"=",
"env",
".",
"config",
".",
"nbsphinx_link_target_root",
"target",
"=",
"utils",
".",
"relative_path",
"(",
"target_root",
",",
"abs_path",
")",
"target",
"=",
"nodes",
".",
"reprunicode",
"(",
"target",
")",
".",
"replace",
"(",
"os",
".",
"path",
".",
"sep",
",",
"'/'",
")",
"env",
".",
"metadata",
"[",
"env",
".",
"docname",
"]",
"[",
"'nbsphinx-link-target'",
"]",
"=",
"target",
"# Copy parser from nbsphinx for our cutom format",
"try",
":",
"formats",
"=",
"env",
".",
"config",
".",
"nbsphinx_custom_formats",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"formats",
".",
"setdefault",
"(",
"'.nblink'",
",",
"lambda",
"s",
":",
"nbformat",
".",
"reads",
"(",
"s",
",",
"as_version",
"=",
"_ipynbversion",
")",
")",
"try",
":",
"include_file",
"=",
"io",
".",
"FileInput",
"(",
"source_path",
"=",
"path",
",",
"encoding",
"=",
"'utf8'",
")",
"except",
"UnicodeEncodeError",
"as",
"error",
":",
"raise",
"NotebookError",
"(",
"u'Problems with linked notebook \"%s\" path:\\n'",
"'Cannot encode input file path \"%s\" '",
"'(wrong locale?).'",
"%",
"(",
"env",
".",
"docname",
",",
"SafeString",
"(",
"path",
")",
")",
")",
"except",
"IOError",
"as",
"error",
":",
"raise",
"NotebookError",
"(",
"u'Problems with linked notebook \"%s\" path:\\n%s.'",
"%",
"(",
"env",
".",
"docname",
",",
"ErrorString",
"(",
"error",
")",
")",
")",
"try",
":",
"rawtext",
"=",
"include_file",
".",
"read",
"(",
")",
"except",
"UnicodeError",
"as",
"error",
":",
"raise",
"NotebookError",
"(",
"u'Problem with linked notebook \"%s\":\\n%s'",
"%",
"(",
"env",
".",
"docname",
",",
"ErrorString",
"(",
"error",
")",
")",
")",
"return",
"super",
"(",
"LinkedNotebookParser",
",",
"self",
")",
".",
"parse",
"(",
"rawtext",
",",
"document",
")"
] |
Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
|
[
"Parse",
"the",
"nblink",
"file",
"."
] |
d64288606a8cc50461792dd3033f5ff081602afc
|
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L48-L96
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/duplicate.py
|
DuplicateScripts.finalize
|
def finalize(self):
"""Output the duplicate scripts detected."""
if self.total_duplicate > 0:
print('{} duplicate scripts found'.format(self.total_duplicate))
for duplicate in self.list_duplicate:
print(duplicate)
|
python
|
def finalize(self):
"""Output the duplicate scripts detected."""
if self.total_duplicate > 0:
print('{} duplicate scripts found'.format(self.total_duplicate))
for duplicate in self.list_duplicate:
print(duplicate)
|
[
"def",
"finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"total_duplicate",
">",
"0",
":",
"print",
"(",
"'{} duplicate scripts found'",
".",
"format",
"(",
"self",
".",
"total_duplicate",
")",
")",
"for",
"duplicate",
"in",
"self",
".",
"list_duplicate",
":",
"print",
"(",
"duplicate",
")"
] |
Output the duplicate scripts detected.
|
[
"Output",
"the",
"duplicate",
"scripts",
"detected",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L17-L22
|
train
|
ucsb-cs-education/hairball
|
hairball/plugins/duplicate.py
|
DuplicateScripts.analyze
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the DuplicateScripts plugin.
Only takes into account scripts with more than 3 blocks.
"""
scripts_set = set()
for script in self.iter_scripts(scratch):
if script[0].type.text == 'define %s':
continue # Ignore user defined scripts
blocks_list = []
for name, _, _ in self.iter_blocks(script.blocks):
blocks_list.append(name)
blocks_tuple = tuple(blocks_list)
if blocks_tuple in scripts_set:
if len(blocks_list) > 3:
self.total_duplicate += 1
self.list_duplicate.append(blocks_list)
else:
scripts_set.add(blocks_tuple)
|
python
|
def analyze(self, scratch, **kwargs):
"""Run and return the results from the DuplicateScripts plugin.
Only takes into account scripts with more than 3 blocks.
"""
scripts_set = set()
for script in self.iter_scripts(scratch):
if script[0].type.text == 'define %s':
continue # Ignore user defined scripts
blocks_list = []
for name, _, _ in self.iter_blocks(script.blocks):
blocks_list.append(name)
blocks_tuple = tuple(blocks_list)
if blocks_tuple in scripts_set:
if len(blocks_list) > 3:
self.total_duplicate += 1
self.list_duplicate.append(blocks_list)
else:
scripts_set.add(blocks_tuple)
|
[
"def",
"analyze",
"(",
"self",
",",
"scratch",
",",
"*",
"*",
"kwargs",
")",
":",
"scripts_set",
"=",
"set",
"(",
")",
"for",
"script",
"in",
"self",
".",
"iter_scripts",
"(",
"scratch",
")",
":",
"if",
"script",
"[",
"0",
"]",
".",
"type",
".",
"text",
"==",
"'define %s'",
":",
"continue",
"# Ignore user defined scripts",
"blocks_list",
"=",
"[",
"]",
"for",
"name",
",",
"_",
",",
"_",
"in",
"self",
".",
"iter_blocks",
"(",
"script",
".",
"blocks",
")",
":",
"blocks_list",
".",
"append",
"(",
"name",
")",
"blocks_tuple",
"=",
"tuple",
"(",
"blocks_list",
")",
"if",
"blocks_tuple",
"in",
"scripts_set",
":",
"if",
"len",
"(",
"blocks_list",
")",
">",
"3",
":",
"self",
".",
"total_duplicate",
"+=",
"1",
"self",
".",
"list_duplicate",
".",
"append",
"(",
"blocks_list",
")",
"else",
":",
"scripts_set",
".",
"add",
"(",
"blocks_tuple",
")"
] |
Run and return the results from the DuplicateScripts plugin.
Only takes into account scripts with more than 3 blocks.
|
[
"Run",
"and",
"return",
"the",
"results",
"from",
"the",
"DuplicateScripts",
"plugin",
"."
] |
c6da8971f8a34e88ce401d36b51431715e1dff5b
|
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L24-L43
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
JsonRendererFactory._set_content_type
|
def _set_content_type(self, system):
""" Set response content type """
request = system.get('request')
if request:
response = request.response
ct = response.content_type
if ct == response.default_content_type:
response.content_type = 'application/json'
|
python
|
def _set_content_type(self, system):
""" Set response content type """
request = system.get('request')
if request:
response = request.response
ct = response.content_type
if ct == response.default_content_type:
response.content_type = 'application/json'
|
[
"def",
"_set_content_type",
"(",
"self",
",",
"system",
")",
":",
"request",
"=",
"system",
".",
"get",
"(",
"'request'",
")",
"if",
"request",
":",
"response",
"=",
"request",
".",
"response",
"ct",
"=",
"response",
".",
"content_type",
"if",
"ct",
"==",
"response",
".",
"default_content_type",
":",
"response",
".",
"content_type",
"=",
"'application/json'"
] |
Set response content type
|
[
"Set",
"response",
"content",
"type"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L35-L42
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
JsonRendererFactory._render_response
|
def _render_response(self, value, system):
""" Render a response """
view = system['view']
enc_class = getattr(view, '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return json.dumps(value, cls=enc_class)
|
python
|
def _render_response(self, value, system):
""" Render a response """
view = system['view']
enc_class = getattr(view, '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return json.dumps(value, cls=enc_class)
|
[
"def",
"_render_response",
"(",
"self",
",",
"value",
",",
"system",
")",
":",
"view",
"=",
"system",
"[",
"'view'",
"]",
"enc_class",
"=",
"getattr",
"(",
"view",
",",
"'_json_encoder'",
",",
"None",
")",
"if",
"enc_class",
"is",
"None",
":",
"enc_class",
"=",
"get_json_encoder",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"value",
",",
"cls",
"=",
"enc_class",
")"
] |
Render a response
|
[
"Render",
"a",
"response"
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L44-L50
|
train
|
ramses-tech/nefertari
|
nefertari/renderers.py
|
DefaultResponseRendererMixin._get_common_kwargs
|
def _get_common_kwargs(self, system):
""" Get kwargs common for all methods. """
enc_class = getattr(system['view'], '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return {
'request': system['request'],
'encoder': enc_class,
}
|
python
|
def _get_common_kwargs(self, system):
""" Get kwargs common for all methods. """
enc_class = getattr(system['view'], '_json_encoder', None)
if enc_class is None:
enc_class = get_json_encoder()
return {
'request': system['request'],
'encoder': enc_class,
}
|
[
"def",
"_get_common_kwargs",
"(",
"self",
",",
"system",
")",
":",
"enc_class",
"=",
"getattr",
"(",
"system",
"[",
"'view'",
"]",
",",
"'_json_encoder'",
",",
"None",
")",
"if",
"enc_class",
"is",
"None",
":",
"enc_class",
"=",
"get_json_encoder",
"(",
")",
"return",
"{",
"'request'",
":",
"system",
"[",
"'request'",
"]",
",",
"'encoder'",
":",
"enc_class",
",",
"}"
] |
Get kwargs common for all methods.
|
[
"Get",
"kwargs",
"common",
"for",
"all",
"methods",
"."
] |
c7caffe11576c11aa111adbdbadeff70ce66b1dd
|
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L86-L94
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.