repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
djaodjin/djaodjin-deployutils | deployutils/apps/django/mixins.py | DateRangeMixin.get_queryset | def get_queryset(self):
"""
Implements date range filtering on ``created_at``
"""
kwargs = {}
if self.start_at:
kwargs.update({'%s__gte' % self.date_field: self.start_at})
return super(DateRangeMixin, self).get_queryset().filter(**kwargs) | python | def get_queryset(self):
"""
Implements date range filtering on ``created_at``
"""
kwargs = {}
if self.start_at:
kwargs.update({'%s__gte' % self.date_field: self.start_at})
return super(DateRangeMixin, self).get_queryset().filter(**kwargs) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"start_at",
":",
"kwargs",
".",
"update",
"(",
"{",
"'%s__gte'",
"%",
"self",
".",
"date_field",
":",
"self",
".",
"start_at",
"}",
")",
"return",
"super",
"(",
"DateRangeMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")"
]
| Implements date range filtering on ``created_at`` | [
"Implements",
"date",
"range",
"filtering",
"on",
"created_at"
]
| a0fe3cf3030dbbf09025c69ce75a69b326565dd8 | https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/mixins.py#L238-L245 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.create | def create(self, fname, lname, group, type, group_api):
"""Create an LDAP User."""
self.__username(fname, lname)
self.client.add(
self.__distinguished_name(type, fname=fname, lname=lname),
API.__object_class(),
self.__ldap_attr(fname, lname, type, group, group_api)) | python | def create(self, fname, lname, group, type, group_api):
"""Create an LDAP User."""
self.__username(fname, lname)
self.client.add(
self.__distinguished_name(type, fname=fname, lname=lname),
API.__object_class(),
self.__ldap_attr(fname, lname, type, group, group_api)) | [
"def",
"create",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"group",
",",
"type",
",",
"group_api",
")",
":",
"self",
".",
"__username",
"(",
"fname",
",",
"lname",
")",
"self",
".",
"client",
".",
"add",
"(",
"self",
".",
"__distinguished_name",
"(",
"type",
",",
"fname",
"=",
"fname",
",",
"lname",
"=",
"lname",
")",
",",
"API",
".",
"__object_class",
"(",
")",
",",
"self",
".",
"__ldap_attr",
"(",
"fname",
",",
"lname",
",",
"type",
",",
"group",
",",
"group_api",
")",
")"
]
| Create an LDAP User. | [
"Create",
"an",
"LDAP",
"User",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L24-L30 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.show | def show(self, username):
"""Return a specific user's info in LDIF format."""
filter = ['(objectclass=posixAccount)', "(uid={})".format(username)]
return self.client.search(filter) | python | def show(self, username):
"""Return a specific user's info in LDIF format."""
filter = ['(objectclass=posixAccount)', "(uid={})".format(username)]
return self.client.search(filter) | [
"def",
"show",
"(",
"self",
",",
"username",
")",
":",
"filter",
"=",
"[",
"'(objectclass=posixAccount)'",
",",
"\"(uid={})\"",
".",
"format",
"(",
"username",
")",
"]",
"return",
"self",
".",
"client",
".",
"search",
"(",
"filter",
")"
]
| Return a specific user's info in LDIF format. | [
"Return",
"a",
"specific",
"user",
"s",
"info",
"in",
"LDIF",
"format",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L41-L44 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.find | def find(self, username):
"""
Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
Multiple users returned by LDAP
"""
filter = ['(uid={})'.format(username)]
results = self.client.search(filter)
if len(results) < 1:
raise ldap_tools.exceptions.NoUserFound(
'User ({}) not found'.format(username))
return # pragma: no cover
elif len(results) > 1:
raise ldap_tools.exceptions.TooManyResults(
'Multiple users found. Please narrow your search.')
return # pragma: no cover
else:
return results | python | def find(self, username):
"""
Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
Multiple users returned by LDAP
"""
filter = ['(uid={})'.format(username)]
results = self.client.search(filter)
if len(results) < 1:
raise ldap_tools.exceptions.NoUserFound(
'User ({}) not found'.format(username))
return # pragma: no cover
elif len(results) > 1:
raise ldap_tools.exceptions.TooManyResults(
'Multiple users found. Please narrow your search.')
return # pragma: no cover
else:
return results | [
"def",
"find",
"(",
"self",
",",
"username",
")",
":",
"filter",
"=",
"[",
"'(uid={})'",
".",
"format",
"(",
"username",
")",
"]",
"results",
"=",
"self",
".",
"client",
".",
"search",
"(",
"filter",
")",
"if",
"len",
"(",
"results",
")",
"<",
"1",
":",
"raise",
"ldap_tools",
".",
"exceptions",
".",
"NoUserFound",
"(",
"'User ({}) not found'",
".",
"format",
"(",
"username",
")",
")",
"return",
"# pragma: no cover",
"elif",
"len",
"(",
"results",
")",
">",
"1",
":",
"raise",
"ldap_tools",
".",
"exceptions",
".",
"TooManyResults",
"(",
"'Multiple users found. Please narrow your search.'",
")",
"return",
"# pragma: no cover",
"else",
":",
"return",
"results"
]
| Find user with given username.
Args:
username Username of the user to search for
Raises:
ldap_tools.exceptions.NoUserFound: No users returned by LDAP
ldap_tools.exceptions.TooManyResults:
Multiple users returned by LDAP | [
"Find",
"user",
"with",
"given",
"username",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L46-L71 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.__username | def __username(self, fname, lname): # pragma: no cover
"""Convert first name + last name into first.last style username."""
self.username = '.'.join([i.lower() for i in [fname, lname]]) | python | def __username(self, fname, lname): # pragma: no cover
"""Convert first name + last name into first.last style username."""
self.username = '.'.join([i.lower() for i in [fname, lname]]) | [
"def",
"__username",
"(",
"self",
",",
"fname",
",",
"lname",
")",
":",
"# pragma: no cover",
"self",
".",
"username",
"=",
"'.'",
".",
"join",
"(",
"[",
"i",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"[",
"fname",
",",
"lname",
"]",
"]",
")"
]
| Convert first name + last name into first.last style username. | [
"Convert",
"first",
"name",
"+",
"last",
"name",
"into",
"first",
".",
"last",
"style",
"username",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L73-L75 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.__distinguished_name | def __distinguished_name(self, type, fname=None, lname=None,
username=None): # pragma: no cover
"""Assemble the DN of the user."""
if username is None:
uid = "uid={}".format(self.username)
else:
uid = "uid={}".format(username)
dn_list = [
uid,
"ou={}".format(self.__organizational_unit(type)),
self.client.basedn,
]
return ','.join(dn_list) | python | def __distinguished_name(self, type, fname=None, lname=None,
username=None): # pragma: no cover
"""Assemble the DN of the user."""
if username is None:
uid = "uid={}".format(self.username)
else:
uid = "uid={}".format(username)
dn_list = [
uid,
"ou={}".format(self.__organizational_unit(type)),
self.client.basedn,
]
return ','.join(dn_list) | [
"def",
"__distinguished_name",
"(",
"self",
",",
"type",
",",
"fname",
"=",
"None",
",",
"lname",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"# pragma: no cover",
"if",
"username",
"is",
"None",
":",
"uid",
"=",
"\"uid={}\"",
".",
"format",
"(",
"self",
".",
"username",
")",
"else",
":",
"uid",
"=",
"\"uid={}\"",
".",
"format",
"(",
"username",
")",
"dn_list",
"=",
"[",
"uid",
",",
"\"ou={}\"",
".",
"format",
"(",
"self",
".",
"__organizational_unit",
"(",
"type",
")",
")",
",",
"self",
".",
"client",
".",
"basedn",
",",
"]",
"return",
"','",
".",
"join",
"(",
"dn_list",
")"
]
| Assemble the DN of the user. | [
"Assemble",
"the",
"DN",
"of",
"the",
"user",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L77-L91 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.__ldap_attr | def __ldap_attr(self, fname, lname, type, group,
group_api): # pragma: no cover
"""User LDAP attributes."""
return {
'uid':
str(self.username).encode(),
'cn':
' '.join([fname, lname]).encode(),
'sn':
str(lname).encode(),
'givenname':
str(fname).encode(),
'homedirectory':
os.path.join(os.path.sep, 'home', self.username).encode(),
'loginshell':
os.path.join(os.path.sep, 'bin', 'bash').encode(),
'mail':
'@'.join([self.username, self.client.mail_domain]).encode(),
'uidnumber':
self.__uidnumber(type),
'gidnumber':
API.__gidnumber(group, group_api),
'userpassword':
str('{SSHA}' + API.__create_password().decode()).encode(),
} | python | def __ldap_attr(self, fname, lname, type, group,
group_api): # pragma: no cover
"""User LDAP attributes."""
return {
'uid':
str(self.username).encode(),
'cn':
' '.join([fname, lname]).encode(),
'sn':
str(lname).encode(),
'givenname':
str(fname).encode(),
'homedirectory':
os.path.join(os.path.sep, 'home', self.username).encode(),
'loginshell':
os.path.join(os.path.sep, 'bin', 'bash').encode(),
'mail':
'@'.join([self.username, self.client.mail_domain]).encode(),
'uidnumber':
self.__uidnumber(type),
'gidnumber':
API.__gidnumber(group, group_api),
'userpassword':
str('{SSHA}' + API.__create_password().decode()).encode(),
} | [
"def",
"__ldap_attr",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"type",
",",
"group",
",",
"group_api",
")",
":",
"# pragma: no cover",
"return",
"{",
"'uid'",
":",
"str",
"(",
"self",
".",
"username",
")",
".",
"encode",
"(",
")",
",",
"'cn'",
":",
"' '",
".",
"join",
"(",
"[",
"fname",
",",
"lname",
"]",
")",
".",
"encode",
"(",
")",
",",
"'sn'",
":",
"str",
"(",
"lname",
")",
".",
"encode",
"(",
")",
",",
"'givenname'",
":",
"str",
"(",
"fname",
")",
".",
"encode",
"(",
")",
",",
"'homedirectory'",
":",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"sep",
",",
"'home'",
",",
"self",
".",
"username",
")",
".",
"encode",
"(",
")",
",",
"'loginshell'",
":",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"sep",
",",
"'bin'",
",",
"'bash'",
")",
".",
"encode",
"(",
")",
",",
"'mail'",
":",
"'@'",
".",
"join",
"(",
"[",
"self",
".",
"username",
",",
"self",
".",
"client",
".",
"mail_domain",
"]",
")",
".",
"encode",
"(",
")",
",",
"'uidnumber'",
":",
"self",
".",
"__uidnumber",
"(",
"type",
")",
",",
"'gidnumber'",
":",
"API",
".",
"__gidnumber",
"(",
"group",
",",
"group_api",
")",
",",
"'userpassword'",
":",
"str",
"(",
"'{SSHA}'",
"+",
"API",
".",
"__create_password",
"(",
")",
".",
"decode",
"(",
")",
")",
".",
"encode",
"(",
")",
",",
"}"
]
| User LDAP attributes. | [
"User",
"LDAP",
"attributes",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L93-L117 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.__create_password | def __create_password(): # pragma: no cover
"""Create a password for the user."""
salt = b64encode(API.__generate_string(32))
password = b64encode(API.__generate_string(64))
return b64encode(sha1(password + salt).digest()) | python | def __create_password(): # pragma: no cover
"""Create a password for the user."""
salt = b64encode(API.__generate_string(32))
password = b64encode(API.__generate_string(64))
return b64encode(sha1(password + salt).digest()) | [
"def",
"__create_password",
"(",
")",
":",
"# pragma: no cover",
"salt",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"32",
")",
")",
"password",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"64",
")",
")",
"return",
"b64encode",
"(",
"sha1",
"(",
"password",
"+",
"salt",
")",
".",
"digest",
"(",
")",
")"
]
| Create a password for the user. | [
"Create",
"a",
"password",
"for",
"the",
"user",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L135-L139 | train |
carta/ldap_tools | src/ldap_tools/user.py | API.__generate_string | def __generate_string(length): # pragma: no cover
"""Generate a string for password creation."""
return ''.join(
SystemRandom().choice(string.ascii_letters + string.digits)
for x in range(length)).encode() | python | def __generate_string(length): # pragma: no cover
"""Generate a string for password creation."""
return ''.join(
SystemRandom().choice(string.ascii_letters + string.digits)
for x in range(length)).encode() | [
"def",
"__generate_string",
"(",
"length",
")",
":",
"# pragma: no cover",
"return",
"''",
".",
"join",
"(",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"x",
"in",
"range",
"(",
"length",
")",
")",
".",
"encode",
"(",
")"
]
| Generate a string for password creation. | [
"Generate",
"a",
"string",
"for",
"password",
"creation",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L141-L145 | train |
carta/ldap_tools | src/ldap_tools/user.py | CLI.create | def create(config, name, group, type):
"""Create an LDAP user."""
if type not in ('user', 'service'):
raise click.BadOptionUsage("--type must be 'user' or 'service'")
client = Client()
client.prepare_connection()
user_api = API(client)
group_api = GroupApi(client)
user_api.create(name[0], name[1], group, type, group_api) | python | def create(config, name, group, type):
"""Create an LDAP user."""
if type not in ('user', 'service'):
raise click.BadOptionUsage("--type must be 'user' or 'service'")
client = Client()
client.prepare_connection()
user_api = API(client)
group_api = GroupApi(client)
user_api.create(name[0], name[1], group, type, group_api) | [
"def",
"create",
"(",
"config",
",",
"name",
",",
"group",
",",
"type",
")",
":",
"if",
"type",
"not",
"in",
"(",
"'user'",
",",
"'service'",
")",
":",
"raise",
"click",
".",
"BadOptionUsage",
"(",
"\"--type must be 'user' or 'service'\"",
")",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"group_api",
"=",
"GroupApi",
"(",
"client",
")",
"user_api",
".",
"create",
"(",
"name",
"[",
"0",
"]",
",",
"name",
"[",
"1",
"]",
",",
"group",
",",
"type",
",",
"group_api",
")"
]
| Create an LDAP user. | [
"Create",
"an",
"LDAP",
"user",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L184-L192 | train |
carta/ldap_tools | src/ldap_tools/user.py | CLI.index | def index(config):
"""Display user info in LDIF format."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.index()) | python | def index(config):
"""Display user info in LDIF format."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.index()) | [
"def",
"index",
"(",
"config",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"CLI",
".",
"show_user",
"(",
"user_api",
".",
"index",
"(",
")",
")"
]
| Display user info in LDIF format. | [
"Display",
"user",
"info",
"in",
"LDIF",
"format",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L213-L218 | train |
carta/ldap_tools | src/ldap_tools/user.py | CLI.show | def show(config, username):
"""Display a specific user."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.show(username)) | python | def show(config, username):
"""Display a specific user."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.show(username)) | [
"def",
"show",
"(",
"config",
",",
"username",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"CLI",
".",
"show_user",
"(",
"user_api",
".",
"show",
"(",
"username",
")",
")"
]
| Display a specific user. | [
"Display",
"a",
"specific",
"user",
"."
]
| 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L224-L229 | train |
ludeeus/GHLocalApi | ghlocalapi/bluetooth.py | Bluetooth.set_discovery_enabled | async def set_discovery_enabled(self):
"""Enable bluetooth discoverablility."""
endpoint = '/setup/bluetooth/discovery'
data = {"enable_discovery": True}
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):
response = await self._session.post(url,
headers=HEADERS,
data=json.dumps(data))
_LOGGER.debug(response.status)
except (asyncio.TimeoutError,
aiohttp.ClientError, socket.gaierror) as error:
_LOGGER.error('Error connecting to %s - %s', self._ipaddress, error) | python | async def set_discovery_enabled(self):
"""Enable bluetooth discoverablility."""
endpoint = '/setup/bluetooth/discovery'
data = {"enable_discovery": True}
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):
response = await self._session.post(url,
headers=HEADERS,
data=json.dumps(data))
_LOGGER.debug(response.status)
except (asyncio.TimeoutError,
aiohttp.ClientError, socket.gaierror) as error:
_LOGGER.error('Error connecting to %s - %s', self._ipaddress, error) | [
"async",
"def",
"set_discovery_enabled",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/setup/bluetooth/discovery'",
"data",
"=",
"{",
"\"enable_discovery\"",
":",
"True",
"}",
"url",
"=",
"API",
".",
"format",
"(",
"ip",
"=",
"self",
".",
"_ipaddress",
",",
"endpoint",
"=",
"endpoint",
")",
"try",
":",
"async",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
":",
"response",
"=",
"await",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"HEADERS",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"response",
".",
"status",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
",",
"socket",
".",
"gaierror",
")",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"'Error connecting to %s - %s'",
",",
"self",
".",
"_ipaddress",
",",
"error",
")"
]
| Enable bluetooth discoverablility. | [
"Enable",
"bluetooth",
"discoverablility",
"."
]
| 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/bluetooth.py#L43-L56 | train |
ludeeus/GHLocalApi | ghlocalapi/bluetooth.py | Bluetooth.scan_for_devices_multi_run | async def scan_for_devices_multi_run(self, runs=2):
"""Scan for devices multiple times."""
run = 1
master = {}
while run < runs + 1:
await self.scan_for_devices()
await self.get_scan_result()
if master is None:
for device in self._devices:
mac = device['mac_address']
master[mac] = {}
master[mac]['rssi'] = device['rssi']
master[mac]['device_class'] = device['device_class']
master[mac]['name'] = device['name']
master[mac]['device_type'] = device['device_type']
master[mac]['count'] = 1
else:
for device in self._devices:
mac = device['mac_address']
if master.get(mac, False):
master[mac]['rssi'] = device['rssi']
master[mac]['count'] = str(1 + 1)
else:
master[mac] = {}
master[mac]['rssi'] = device['rssi']
master[mac]['device_class'] = device['device_class']
master[mac]['name'] = device['name']
master[mac]['device_type'] = device['device_type']
master[mac]['count'] = 1
run = run + 1
result = []
for device in master:
if int(master[device]['count']) > 1:
result.append(master[device])
self._devices = result | python | async def scan_for_devices_multi_run(self, runs=2):
"""Scan for devices multiple times."""
run = 1
master = {}
while run < runs + 1:
await self.scan_for_devices()
await self.get_scan_result()
if master is None:
for device in self._devices:
mac = device['mac_address']
master[mac] = {}
master[mac]['rssi'] = device['rssi']
master[mac]['device_class'] = device['device_class']
master[mac]['name'] = device['name']
master[mac]['device_type'] = device['device_type']
master[mac]['count'] = 1
else:
for device in self._devices:
mac = device['mac_address']
if master.get(mac, False):
master[mac]['rssi'] = device['rssi']
master[mac]['count'] = str(1 + 1)
else:
master[mac] = {}
master[mac]['rssi'] = device['rssi']
master[mac]['device_class'] = device['device_class']
master[mac]['name'] = device['name']
master[mac]['device_type'] = device['device_type']
master[mac]['count'] = 1
run = run + 1
result = []
for device in master:
if int(master[device]['count']) > 1:
result.append(master[device])
self._devices = result | [
"async",
"def",
"scan_for_devices_multi_run",
"(",
"self",
",",
"runs",
"=",
"2",
")",
":",
"run",
"=",
"1",
"master",
"=",
"{",
"}",
"while",
"run",
"<",
"runs",
"+",
"1",
":",
"await",
"self",
".",
"scan_for_devices",
"(",
")",
"await",
"self",
".",
"get_scan_result",
"(",
")",
"if",
"master",
"is",
"None",
":",
"for",
"device",
"in",
"self",
".",
"_devices",
":",
"mac",
"=",
"device",
"[",
"'mac_address'",
"]",
"master",
"[",
"mac",
"]",
"=",
"{",
"}",
"master",
"[",
"mac",
"]",
"[",
"'rssi'",
"]",
"=",
"device",
"[",
"'rssi'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'device_class'",
"]",
"=",
"device",
"[",
"'device_class'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'name'",
"]",
"=",
"device",
"[",
"'name'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'device_type'",
"]",
"=",
"device",
"[",
"'device_type'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'count'",
"]",
"=",
"1",
"else",
":",
"for",
"device",
"in",
"self",
".",
"_devices",
":",
"mac",
"=",
"device",
"[",
"'mac_address'",
"]",
"if",
"master",
".",
"get",
"(",
"mac",
",",
"False",
")",
":",
"master",
"[",
"mac",
"]",
"[",
"'rssi'",
"]",
"=",
"device",
"[",
"'rssi'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'count'",
"]",
"=",
"str",
"(",
"1",
"+",
"1",
")",
"else",
":",
"master",
"[",
"mac",
"]",
"=",
"{",
"}",
"master",
"[",
"mac",
"]",
"[",
"'rssi'",
"]",
"=",
"device",
"[",
"'rssi'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'device_class'",
"]",
"=",
"device",
"[",
"'device_class'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'name'",
"]",
"=",
"device",
"[",
"'name'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'device_type'",
"]",
"=",
"device",
"[",
"'device_type'",
"]",
"master",
"[",
"mac",
"]",
"[",
"'count'",
"]",
"=",
"1",
"run",
"=",
"run",
"+",
"1",
"result",
"=",
"[",
"]",
"for",
"device",
"in",
"master",
":",
"if",
"int",
"(",
"master",
"[",
"device",
"]",
"[",
"'count'",
"]",
")",
">",
"1",
":",
"result",
".",
"append",
"(",
"master",
"[",
"device",
"]",
")",
"self",
".",
"_devices",
"=",
"result"
]
| Scan for devices multiple times. | [
"Scan",
"for",
"devices",
"multiple",
"times",
"."
]
| 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/bluetooth.py#L103-L137 | train |
coopernurse/barrister | barrister/runtime.py | contract_from_file | def contract_from_file(fname):
"""
Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load
"""
f = open(fname)
j = f.read()
f.close()
return Contract(json.loads(j)) | python | def contract_from_file(fname):
"""
Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load
"""
f = open(fname)
j = f.read()
f.close()
return Contract(json.loads(j)) | [
"def",
"contract_from_file",
"(",
"fname",
")",
":",
"f",
"=",
"open",
"(",
"fname",
")",
"j",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"Contract",
"(",
"json",
".",
"loads",
"(",
"j",
")",
")"
]
| Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load | [
"Loads",
"a",
"Barrister",
"IDL",
"JSON",
"from",
"the",
"given",
"file",
"and",
"returns",
"a",
"Contract",
"class"
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L27-L38 | train |
coopernurse/barrister | barrister/runtime.py | RequestContext.get_prop | def get_prop(self, key, default_val=None):
"""
Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props
"""
if self.props.has_key(key):
return self.props[key]
else:
return default_val | python | def get_prop(self, key, default_val=None):
"""
Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props
"""
if self.props.has_key(key):
return self.props[key]
else:
return default_val | [
"def",
"get_prop",
"(",
"self",
",",
"key",
",",
"default_val",
"=",
"None",
")",
":",
"if",
"self",
".",
"props",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"self",
".",
"props",
"[",
"key",
"]",
"else",
":",
"return",
"default_val"
]
| Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props | [
"Returns",
"a",
"property",
"set",
"on",
"the",
"context",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L146-L159 | train |
coopernurse/barrister | barrister/runtime.py | RequestContext.set_error | def set_error(self, code, msg, data=None):
"""
Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error code
msg
String description of the error
data
Optional additional info about the error. Should be a primitive, or a list or
dict of primitives to avoid serialization issues.
"""
self.error = err_response(self.request["id"], code, msg, data) | python | def set_error(self, code, msg, data=None):
"""
Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error code
msg
String description of the error
data
Optional additional info about the error. Should be a primitive, or a list or
dict of primitives to avoid serialization issues.
"""
self.error = err_response(self.request["id"], code, msg, data) | [
"def",
"set_error",
"(",
"self",
",",
"code",
",",
"msg",
",",
"data",
"=",
"None",
")",
":",
"self",
".",
"error",
"=",
"err_response",
"(",
"self",
".",
"request",
"[",
"\"id\"",
"]",
",",
"code",
",",
"msg",
",",
"data",
")"
]
| Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error code
msg
String description of the error
data
Optional additional info about the error. Should be a primitive, or a list or
dict of primitives to avoid serialization issues. | [
"Set",
"an",
"error",
"on",
"this",
"request",
"which",
"will",
"prevent",
"request",
"execution",
".",
"Should",
"only",
"be",
"called",
"from",
"pre",
"hook",
"methods",
".",
"If",
"called",
"from",
"a",
"post",
"hook",
"this",
"operation",
"will",
"be",
"ignored",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L161-L176 | train |
coopernurse/barrister | barrister/runtime.py | Server.add_handler | def add_handler(self, iface_name, handler):
"""
Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handler
Instance of a class that implements all functions defined on the interface
"""
if self.contract.has_interface(iface_name):
self.handlers[iface_name] = handler
else:
raise RpcException(ERR_INVALID_REQ, "Unknown interface: '%s'", iface_name) | python | def add_handler(self, iface_name, handler):
"""
Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handler
Instance of a class that implements all functions defined on the interface
"""
if self.contract.has_interface(iface_name):
self.handlers[iface_name] = handler
else:
raise RpcException(ERR_INVALID_REQ, "Unknown interface: '%s'", iface_name) | [
"def",
"add_handler",
"(",
"self",
",",
"iface_name",
",",
"handler",
")",
":",
"if",
"self",
".",
"contract",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"self",
".",
"handlers",
"[",
"iface_name",
"]",
"=",
"handler",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_REQ",
",",
"\"Unknown interface: '%s'\"",
",",
"iface_name",
")"
]
| Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handler
Instance of a class that implements all functions defined on the interface | [
"Associates",
"the",
"given",
"handler",
"with",
"the",
"interface",
"name",
".",
"If",
"the",
"interface",
"does",
"not",
"exist",
"in",
"the",
"Contract",
"an",
"RpcException",
"is",
"raised",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L235-L249 | train |
coopernurse/barrister | barrister/runtime.py | Server.set_filters | def set_filters(self, filters):
"""
Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter
"""
if filters == None or isinstance(filters, (tuple, list)):
self.filters = filters
else:
self.filters = [ filters ] | python | def set_filters(self, filters):
"""
Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter
"""
if filters == None or isinstance(filters, (tuple, list)):
self.filters = filters
else:
self.filters = [ filters ] | [
"def",
"set_filters",
"(",
"self",
",",
"filters",
")",
":",
"if",
"filters",
"==",
"None",
"or",
"isinstance",
"(",
"filters",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"self",
".",
"filters",
"=",
"filters",
"else",
":",
"self",
".",
"filters",
"=",
"[",
"filters",
"]"
]
| Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter | [
"Sets",
"the",
"filters",
"for",
"the",
"server",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L251-L263 | train |
coopernurse/barrister | barrister/runtime.py | Server.call | def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of dicts, or a single dict.
props
Application defined properties to set on RequestContext for use with filters.
For example: authentication headers. Must be a dict.
"""
resp = None
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Request: %s" % str(req))
if isinstance(req, list):
if len(req) < 1:
resp = err_response(None, ERR_INVALID_REQ, "Invalid Request. Empty batch.")
else:
resp = [ ]
for r in req:
resp.append(self._call_and_format(r, props))
else:
resp = self._call_and_format(req, props)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Response: %s" % str(resp))
return resp | python | def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of dicts, or a single dict.
props
Application defined properties to set on RequestContext for use with filters.
For example: authentication headers. Must be a dict.
"""
resp = None
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Request: %s" % str(req))
if isinstance(req, list):
if len(req) < 1:
resp = err_response(None, ERR_INVALID_REQ, "Invalid Request. Empty batch.")
else:
resp = [ ]
for r in req:
resp.append(self._call_and_format(r, props))
else:
resp = self._call_and_format(req, props)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Response: %s" % str(resp))
return resp | [
"def",
"call",
"(",
"self",
",",
"req",
",",
"props",
"=",
"None",
")",
":",
"resp",
"=",
"None",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Request: %s\"",
"%",
"str",
"(",
"req",
")",
")",
"if",
"isinstance",
"(",
"req",
",",
"list",
")",
":",
"if",
"len",
"(",
"req",
")",
"<",
"1",
":",
"resp",
"=",
"err_response",
"(",
"None",
",",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. Empty batch.\"",
")",
"else",
":",
"resp",
"=",
"[",
"]",
"for",
"r",
"in",
"req",
":",
"resp",
".",
"append",
"(",
"self",
".",
"_call_and_format",
"(",
"r",
",",
"props",
")",
")",
"else",
":",
"resp",
"=",
"self",
".",
"_call_and_format",
"(",
"req",
",",
"props",
")",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Response: %s\"",
"%",
"str",
"(",
"resp",
")",
")",
"return",
"resp"
]
| Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of dicts, or a single dict.
props
Application defined properties to set on RequestContext for use with filters.
For example: authentication headers. Must be a dict. | [
"Executes",
"a",
"Barrister",
"request",
"and",
"returns",
"a",
"response",
".",
"If",
"the",
"request",
"is",
"a",
"list",
"then",
"the",
"response",
"will",
"also",
"be",
"a",
"list",
".",
"If",
"the",
"request",
"is",
"an",
"empty",
"list",
"a",
"RpcException",
"is",
"raised",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L284-L313 | train |
coopernurse/barrister | barrister/runtime.py | Server._call | def _call(self, context):
"""
Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler.
:Parameter:
req
A dict representing a valid JSON-RPC 2.0 request. 'method' must be provided.
"""
req = context.request
if not req.has_key("method"):
raise RpcException(ERR_INVALID_REQ, "Invalid Request. No 'method'.")
method = req["method"]
if method == "barrister-idl":
return self.contract.idl_parsed
iface_name, func_name = unpack_method(method)
if self.handlers.has_key(iface_name):
iface_impl = self.handlers[iface_name]
func = getattr(iface_impl, func_name)
if func:
if req.has_key("params"):
params = req["params"]
else:
params = [ ]
if self.validate_req:
self.contract.validate_request(iface_name, func_name, params)
if hasattr(iface_impl, "barrister_pre"):
pre_hook = getattr(iface_impl, "barrister_pre")
pre_hook(context, params)
if params:
result = func(*params)
else:
result = func()
if self.validate_resp:
self.contract.validate_response(iface_name, func_name, result)
return result
else:
msg = "Method '%s' not found" % (method)
raise RpcException(ERR_METHOD_NOT_FOUND, msg)
else:
msg = "No implementation of '%s' found" % (iface_name)
raise RpcException(ERR_METHOD_NOT_FOUND, msg) | python | def _call(self, context):
"""
Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler.
:Parameter:
req
A dict representing a valid JSON-RPC 2.0 request. 'method' must be provided.
"""
req = context.request
if not req.has_key("method"):
raise RpcException(ERR_INVALID_REQ, "Invalid Request. No 'method'.")
method = req["method"]
if method == "barrister-idl":
return self.contract.idl_parsed
iface_name, func_name = unpack_method(method)
if self.handlers.has_key(iface_name):
iface_impl = self.handlers[iface_name]
func = getattr(iface_impl, func_name)
if func:
if req.has_key("params"):
params = req["params"]
else:
params = [ ]
if self.validate_req:
self.contract.validate_request(iface_name, func_name, params)
if hasattr(iface_impl, "barrister_pre"):
pre_hook = getattr(iface_impl, "barrister_pre")
pre_hook(context, params)
if params:
result = func(*params)
else:
result = func()
if self.validate_resp:
self.contract.validate_response(iface_name, func_name, result)
return result
else:
msg = "Method '%s' not found" % (method)
raise RpcException(ERR_METHOD_NOT_FOUND, msg)
else:
msg = "No implementation of '%s' found" % (iface_name)
raise RpcException(ERR_METHOD_NOT_FOUND, msg) | [
"def",
"_call",
"(",
"self",
",",
"context",
")",
":",
"req",
"=",
"context",
".",
"request",
"if",
"not",
"req",
".",
"has_key",
"(",
"\"method\"",
")",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. No 'method'.\"",
")",
"method",
"=",
"req",
"[",
"\"method\"",
"]",
"if",
"method",
"==",
"\"barrister-idl\"",
":",
"return",
"self",
".",
"contract",
".",
"idl_parsed",
"iface_name",
",",
"func_name",
"=",
"unpack_method",
"(",
"method",
")",
"if",
"self",
".",
"handlers",
".",
"has_key",
"(",
"iface_name",
")",
":",
"iface_impl",
"=",
"self",
".",
"handlers",
"[",
"iface_name",
"]",
"func",
"=",
"getattr",
"(",
"iface_impl",
",",
"func_name",
")",
"if",
"func",
":",
"if",
"req",
".",
"has_key",
"(",
"\"params\"",
")",
":",
"params",
"=",
"req",
"[",
"\"params\"",
"]",
"else",
":",
"params",
"=",
"[",
"]",
"if",
"self",
".",
"validate_req",
":",
"self",
".",
"contract",
".",
"validate_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"if",
"hasattr",
"(",
"iface_impl",
",",
"\"barrister_pre\"",
")",
":",
"pre_hook",
"=",
"getattr",
"(",
"iface_impl",
",",
"\"barrister_pre\"",
")",
"pre_hook",
"(",
"context",
",",
"params",
")",
"if",
"params",
":",
"result",
"=",
"func",
"(",
"*",
"params",
")",
"else",
":",
"result",
"=",
"func",
"(",
")",
"if",
"self",
".",
"validate_resp",
":",
"self",
".",
"contract",
".",
"validate_response",
"(",
"iface_name",
",",
"func_name",
",",
"result",
")",
"return",
"result",
"else",
":",
"msg",
"=",
"\"Method '%s' not found\"",
"%",
"(",
"method",
")",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FOUND",
",",
"msg",
")",
"else",
":",
"msg",
"=",
"\"No implementation of '%s' found\"",
"%",
"(",
"iface_name",
")",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FOUND",
",",
"msg",
")"
]
| Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler.
:Parameter:
req
A dict representing a valid JSON-RPC 2.0 request. 'method' must be provided. | [
"Executes",
"a",
"single",
"request",
"against",
"a",
"handler",
".",
"If",
"the",
"req",
".",
"method",
"==",
"barrister",
"-",
"idl",
"the",
"Contract",
"IDL",
"JSON",
"structure",
"is",
"returned",
".",
"Otherwise",
"the",
"method",
"is",
"resolved",
"to",
"a",
"handler",
"based",
"on",
"the",
"interface",
"name",
"and",
"the",
"appropriate",
"function",
"is",
"called",
"on",
"the",
"handler",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L364-L414 | train |
coopernurse/barrister | barrister/runtime.py | HttpTransport.request | def request(self, req):
"""
Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request
"""
data = json.dumps(req)
req = urllib2.Request(self.url, data, self.headers)
f = self.opener.open(req)
resp = f.read()
f.close()
return json.loads(resp) | python | def request(self, req):
"""
Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request
"""
data = json.dumps(req)
req = urllib2.Request(self.url, data, self.headers)
f = self.opener.open(req)
resp = f.read()
f.close()
return json.loads(resp) | [
"def",
"request",
"(",
"self",
",",
"req",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"req",
")",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"self",
".",
"url",
",",
"data",
",",
"self",
".",
"headers",
")",
"f",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"resp",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"resp",
")"
]
| Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request | [
"Makes",
"a",
"request",
"against",
"the",
"server",
"and",
"returns",
"the",
"deserialized",
"result",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L444-L457 | train |
coopernurse/barrister | barrister/runtime.py | Client.call | def call(self, iface_name, func_name, params):
"""
Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function
"""
req = self.to_request(iface_name, func_name, params)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Request: %s" % str(req))
resp = self.transport.request(req)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Response: %s" % str(resp))
return self.to_result(iface_name, func_name, resp) | python | def call(self, iface_name, func_name, params):
"""
Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function
"""
req = self.to_request(iface_name, func_name, params)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Request: %s" % str(req))
resp = self.transport.request(req)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Response: %s" % str(resp))
return self.to_result(iface_name, func_name, resp) | [
"def",
"call",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"req",
"=",
"self",
".",
"to_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Request: %s\"",
"%",
"str",
"(",
"req",
")",
")",
"resp",
"=",
"self",
".",
"transport",
".",
"request",
"(",
"req",
")",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Response: %s\"",
"%",
"str",
"(",
"resp",
")",
")",
"return",
"self",
".",
"to_result",
"(",
"iface_name",
",",
"func_name",
",",
"resp",
")"
]
| Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function | [
"Makes",
"a",
"single",
"RPC",
"request",
"and",
"returns",
"the",
"result",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L543-L561 | train |
coopernurse/barrister | barrister/runtime.py | Client.to_request | def to_request(self, iface_name, func_name, params):
"""
Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
against the expected types for the function and a RpcException raised if they are
invalid.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function
"""
if self.validate_req:
self.contract.validate_request(iface_name, func_name, params)
method = "%s.%s" % (iface_name, func_name)
reqid = self.id_gen()
return { "jsonrpc": "2.0", "id": reqid, "method": method, "params": params } | python | def to_request(self, iface_name, func_name, params):
"""
Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
against the expected types for the function and a RpcException raised if they are
invalid.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function
"""
if self.validate_req:
self.contract.validate_request(iface_name, func_name, params)
method = "%s.%s" % (iface_name, func_name)
reqid = self.id_gen()
return { "jsonrpc": "2.0", "id": reqid, "method": method, "params": params } | [
"def",
"to_request",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"if",
"self",
".",
"validate_req",
":",
"self",
".",
"contract",
".",
"validate_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"method",
"=",
"\"%s.%s\"",
"%",
"(",
"iface_name",
",",
"func_name",
")",
"reqid",
"=",
"self",
".",
"id_gen",
"(",
")",
"return",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"reqid",
",",
"\"method\"",
":",
"method",
",",
"\"params\"",
":",
"params",
"}"
]
| Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
against the expected types for the function and a RpcException raised if they are
invalid.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function | [
"Converts",
"the",
"arguments",
"to",
"a",
"JSON",
"-",
"RPC",
"request",
"dict",
".",
"The",
"id",
"field",
"is",
"populated",
"using",
"the",
"id_gen",
"function",
"passed",
"to",
"the",
"Client",
"constructor",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L563-L585 | train |
coopernurse/barrister | barrister/runtime.py | Client.to_result | def to_result(self, iface_name, func_name, resp):
"""
Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is validated
against the expected return type for the function and a RpcException raised if it is
invalid.
:Parameters:
iface_name
Interface name that was called
func_name
Function that was called on the interface
resp
Dict formatted as a JSON-RPC response
"""
if resp.has_key("error"):
e = resp["error"]
data = None
if e.has_key("data"):
data = e["data"]
raise RpcException(e["code"], e["message"], data)
result = resp["result"]
if self.validate_resp:
self.contract.validate_response(iface_name, func_name, result)
return result | python | def to_result(self, iface_name, func_name, resp):
"""
Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is validated
against the expected return type for the function and a RpcException raised if it is
invalid.
:Parameters:
iface_name
Interface name that was called
func_name
Function that was called on the interface
resp
Dict formatted as a JSON-RPC response
"""
if resp.has_key("error"):
e = resp["error"]
data = None
if e.has_key("data"):
data = e["data"]
raise RpcException(e["code"], e["message"], data)
result = resp["result"]
if self.validate_resp:
self.contract.validate_response(iface_name, func_name, result)
return result | [
"def",
"to_result",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"if",
"resp",
".",
"has_key",
"(",
"\"error\"",
")",
":",
"e",
"=",
"resp",
"[",
"\"error\"",
"]",
"data",
"=",
"None",
"if",
"e",
".",
"has_key",
"(",
"\"data\"",
")",
":",
"data",
"=",
"e",
"[",
"\"data\"",
"]",
"raise",
"RpcException",
"(",
"e",
"[",
"\"code\"",
"]",
",",
"e",
"[",
"\"message\"",
"]",
",",
"data",
")",
"result",
"=",
"resp",
"[",
"\"result\"",
"]",
"if",
"self",
".",
"validate_resp",
":",
"self",
".",
"contract",
".",
"validate_response",
"(",
"iface_name",
",",
"func_name",
",",
"result",
")",
"return",
"result"
]
| Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is validated
against the expected return type for the function and a RpcException raised if it is
invalid.
:Parameters:
iface_name
Interface name that was called
func_name
Function that was called on the interface
resp
Dict formatted as a JSON-RPC response | [
"Takes",
"a",
"JSON",
"-",
"RPC",
"response",
"and",
"checks",
"for",
"an",
"error",
"slot",
".",
"If",
"it",
"exists",
"a",
"RpcException",
"is",
"raised",
".",
"If",
"no",
"error",
"slot",
"exists",
"the",
"result",
"slot",
"is",
"returned",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L587-L616 | train |
coopernurse/barrister | barrister/runtime.py | Contract.validate_request | def validate_request(self, iface_name, func_name, params):
"""
Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
params
List of params to validate against this function
"""
self.interface(iface_name).function(func_name).validate_params(params) | python | def validate_request(self, iface_name, func_name, params):
"""
Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
params
List of params to validate against this function
"""
self.interface(iface_name).function(func_name).validate_params(params) | [
"def",
"validate_request",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"self",
".",
"interface",
"(",
"iface_name",
")",
".",
"function",
"(",
"func_name",
")",
".",
"validate_params",
"(",
"params",
")"
]
| Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
params
List of params to validate against this function | [
"Validates",
"that",
"the",
"given",
"params",
"match",
"the",
"expected",
"length",
"and",
"types",
"for",
"this",
"interface",
"and",
"function",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L786-L804 | train |
coopernurse/barrister | barrister/runtime.py | Contract.validate_response | def validate_response(self, iface_name, func_name, resp):
"""
Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
resp
Result from calling the function
"""
self.interface(iface_name).function(func_name).validate_response(resp) | python | def validate_response(self, iface_name, func_name, resp):
"""
Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
resp
Result from calling the function
"""
self.interface(iface_name).function(func_name).validate_response(resp) | [
"def",
"validate_response",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"self",
".",
"interface",
"(",
"iface_name",
")",
".",
"function",
"(",
"func_name",
")",
".",
"validate_response",
"(",
"resp",
")"
]
| Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
func_name
Name of function
resp
Result from calling the function | [
"Validates",
"that",
"the",
"response",
"matches",
"the",
"return",
"type",
"for",
"the",
"function"
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L806-L823 | train |
coopernurse/barrister | barrister/runtime.py | Contract.get | def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
return self.structs[name]
elif self.enums.has_key(name):
return self.enums[name]
elif self.interfaces.has_key(name):
return self.interfaces[name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown entity: '%s'" % name) | python | def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
return self.structs[name]
elif self.enums.has_key(name):
return self.enums[name]
elif self.interfaces.has_key(name):
return self.interfaces[name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown entity: '%s'" % name) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"name",
"]",
"elif",
"self",
".",
"enums",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"enums",
"[",
"name",
"]",
"elif",
"self",
".",
"interfaces",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"interfaces",
"[",
"name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
"\"Unknown entity: '%s'\"",
"%",
"name",
")"
]
| Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return | [
"Returns",
"the",
"struct",
"enum",
"or",
"interface",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"elements",
"match",
"that",
"name",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L825-L841 | train |
coopernurse/barrister | barrister/runtime.py | Contract.struct | def struct(self, struct_name):
"""
Returns the struct with the given name, or raises RpcException if no struct matches
"""
if self.structs.has_key(struct_name):
return self.structs[struct_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown struct: '%s'", struct_name) | python | def struct(self, struct_name):
"""
Returns the struct with the given name, or raises RpcException if no struct matches
"""
if self.structs.has_key(struct_name):
return self.structs[struct_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown struct: '%s'", struct_name) | [
"def",
"struct",
"(",
"self",
",",
"struct_name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"struct_name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"struct_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
"\"Unknown struct: '%s'\"",
",",
"struct_name",
")"
]
| Returns the struct with the given name, or raises RpcException if no struct matches | [
"Returns",
"the",
"struct",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"struct",
"matches"
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L843-L850 | train |
coopernurse/barrister | barrister/runtime.py | Contract.interface | def interface(self, iface_name):
"""
Returns the interface with the given name, or raises RpcException if no interface matches
"""
if self.has_interface(iface_name):
return self.interfaces[iface_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown interface: '%s'", iface_name) | python | def interface(self, iface_name):
"""
Returns the interface with the given name, or raises RpcException if no interface matches
"""
if self.has_interface(iface_name):
return self.interfaces[iface_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown interface: '%s'", iface_name) | [
"def",
"interface",
"(",
"self",
",",
"iface_name",
")",
":",
"if",
"self",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"return",
"self",
".",
"interfaces",
"[",
"iface_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
"\"Unknown interface: '%s'\"",
",",
"iface_name",
")"
]
| Returns the interface with the given name, or raises RpcException if no interface matches | [
"Returns",
"the",
"interface",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"interface",
"matches"
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L858-L865 | train |
coopernurse/barrister | barrister/runtime.py | Contract.validate | def validate(self, expected_type, is_array, val):
"""
Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
expected_type
string name of the type expected. This may be a Barrister primitive, or a user defined type.
is_array
If True then require that the val be a list
val
Value to validate against the expected type
"""
if val == None:
if expected_type.optional:
return True, None
else:
return False, "Value cannot be null"
elif is_array:
if not isinstance(val, list):
return self._type_err(val, "list")
else:
for v in val:
ok, msg = self.validate(expected_type, False, v)
if not ok:
return ok, msg
elif expected_type.type == "int":
if not isinstance(val, (long, int)):
return self._type_err(val, "int")
elif expected_type.type == "float":
if not isinstance(val, (float, int, long)):
return self._type_err(val, "float")
elif expected_type.type == "bool":
if not isinstance(val, bool):
return self._type_err(val, "bool")
elif expected_type.type == "string":
if not isinstance(val, (str, unicode)):
return self._type_err(val, "string")
else:
return self.get(expected_type.type).validate(val)
return True, None | python | def validate(self, expected_type, is_array, val):
"""
Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
expected_type
string name of the type expected. This may be a Barrister primitive, or a user defined type.
is_array
If True then require that the val be a list
val
Value to validate against the expected type
"""
if val == None:
if expected_type.optional:
return True, None
else:
return False, "Value cannot be null"
elif is_array:
if not isinstance(val, list):
return self._type_err(val, "list")
else:
for v in val:
ok, msg = self.validate(expected_type, False, v)
if not ok:
return ok, msg
elif expected_type.type == "int":
if not isinstance(val, (long, int)):
return self._type_err(val, "int")
elif expected_type.type == "float":
if not isinstance(val, (float, int, long)):
return self._type_err(val, "float")
elif expected_type.type == "bool":
if not isinstance(val, bool):
return self._type_err(val, "bool")
elif expected_type.type == "string":
if not isinstance(val, (str, unicode)):
return self._type_err(val, "string")
else:
return self.get(expected_type.type).validate(val)
return True, None | [
"def",
"validate",
"(",
"self",
",",
"expected_type",
",",
"is_array",
",",
"val",
")",
":",
"if",
"val",
"==",
"None",
":",
"if",
"expected_type",
".",
"optional",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"Value cannot be null\"",
"elif",
"is_array",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"return",
"self",
".",
"_type_err",
"(",
"val",
",",
"\"list\"",
")",
"else",
":",
"for",
"v",
"in",
"val",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"validate",
"(",
"expected_type",
",",
"False",
",",
"v",
")",
"if",
"not",
"ok",
":",
"return",
"ok",
",",
"msg",
"elif",
"expected_type",
".",
"type",
"==",
"\"int\"",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"long",
",",
"int",
")",
")",
":",
"return",
"self",
".",
"_type_err",
"(",
"val",
",",
"\"int\"",
")",
"elif",
"expected_type",
".",
"type",
"==",
"\"float\"",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"float",
",",
"int",
",",
"long",
")",
")",
":",
"return",
"self",
".",
"_type_err",
"(",
"val",
",",
"\"float\"",
")",
"elif",
"expected_type",
".",
"type",
"==",
"\"bool\"",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"bool",
")",
":",
"return",
"self",
".",
"_type_err",
"(",
"val",
",",
"\"bool\"",
")",
"elif",
"expected_type",
".",
"type",
"==",
"\"string\"",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"self",
".",
"_type_err",
"(",
"val",
",",
"\"string\"",
")",
"else",
":",
"return",
"self",
".",
"get",
"(",
"expected_type",
".",
"type",
")",
".",
"validate",
"(",
"val",
")",
"return",
"True",
",",
"None"
]
| Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
expected_type
string name of the type expected. This may be a Barrister primitive, or a user defined type.
is_array
If True then require that the val be a list
val
Value to validate against the expected type | [
"Validates",
"that",
"the",
"expected",
"type",
"matches",
"the",
"value"
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L867-L911 | train |
coopernurse/barrister | barrister/runtime.py | Interface.function | def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcException(ERR_METHOD_NOT_FOUND,
"%s: Unknown function: '%s'", self.name, func_name) | python | def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcException(ERR_METHOD_NOT_FOUND,
"%s: Unknown function: '%s'", self.name, func_name) | [
"def",
"function",
"(",
"self",
",",
"func_name",
")",
":",
"if",
"self",
".",
"functions",
".",
"has_key",
"(",
"func_name",
")",
":",
"return",
"self",
".",
"functions",
"[",
"func_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FOUND",
",",
"\"%s: Unknown function: '%s'\"",
",",
"self",
".",
"name",
",",
"func_name",
")"
]
| Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches. | [
"Returns",
"the",
"Function",
"instance",
"associated",
"with",
"the",
"given",
"func_name",
"or",
"raises",
"a",
"RpcException",
"if",
"no",
"function",
"matches",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L937-L946 | train |
coopernurse/barrister | barrister/runtime.py | Enum.validate | def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Should be a string.
"""
if val in self.values:
return True, None
else:
return False, "'%s' is not in enum: %s" % (val, str(self.values)) | python | def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Should be a string.
"""
if val in self.values:
return True, None
else:
return False, "'%s' is not in enum: %s" % (val, str(self.values)) | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"in",
"self",
".",
"values",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"'%s' is not in enum: %s\"",
"%",
"(",
"val",
",",
"str",
"(",
"self",
".",
"values",
")",
")"
]
| Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Should be a string. | [
"Validates",
"that",
"the",
"val",
"is",
"in",
"the",
"list",
"of",
"values",
"for",
"this",
"Enum",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L966-L982 | train |
coopernurse/barrister | barrister/runtime.py | Struct.field | def field(self, name):
"""
Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters:
name
string name of field to lookup
"""
if self.fields.has_key(name):
return self.fields[name]
elif self.extends:
if not self.parent:
self.parent = self.contract.struct(self.extends)
return self.parent.field(name)
else:
return None | python | def field(self, name):
"""
Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters:
name
string name of field to lookup
"""
if self.fields.has_key(name):
return self.fields[name]
elif self.extends:
if not self.parent:
self.parent = self.contract.struct(self.extends)
return self.parent.field(name)
else:
return None | [
"def",
"field",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"fields",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"fields",
"[",
"name",
"]",
"elif",
"self",
".",
"extends",
":",
"if",
"not",
"self",
".",
"parent",
":",
"self",
".",
"parent",
"=",
"self",
".",
"contract",
".",
"struct",
"(",
"self",
".",
"extends",
")",
"return",
"self",
".",
"parent",
".",
"field",
"(",
"name",
")",
"else",
":",
"return",
"None"
]
| Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters:
name
string name of field to lookup | [
"Returns",
"the",
"field",
"on",
"this",
"struct",
"with",
"the",
"given",
"name",
".",
"Will",
"try",
"to",
"find",
"this",
"name",
"on",
"all",
"ancestors",
"if",
"this",
"struct",
"extends",
"another",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1007-L1026 | train |
coopernurse/barrister | barrister/runtime.py | Struct.validate | def validate(self, val):
"""
Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Must be a dict
"""
if type(val) is not dict:
return False, "%s is not a dict" % (str(val))
for k, v in val.items():
field = self.field(k)
if field:
ok, msg = self.contract.validate(field, field.is_array, v)
if not ok:
return False, "field '%s': %s" % (field.name, msg)
else:
return False, "field '%s' not found in struct %s" % (k, self.name)
all_fields = self.get_all_fields([])
for field in all_fields:
if not val.has_key(field.name) and not field.optional:
return False, "field '%s' missing from: %s" % (field.name, str(val))
return True, None | python | def validate(self, val):
"""
Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Must be a dict
"""
if type(val) is not dict:
return False, "%s is not a dict" % (str(val))
for k, v in val.items():
field = self.field(k)
if field:
ok, msg = self.contract.validate(field, field.is_array, v)
if not ok:
return False, "field '%s': %s" % (field.name, msg)
else:
return False, "field '%s' not found in struct %s" % (k, self.name)
all_fields = self.get_all_fields([])
for field in all_fields:
if not val.has_key(field.name) and not field.optional:
return False, "field '%s' missing from: %s" % (field.name, str(val))
return True, None | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"type",
"(",
"val",
")",
"is",
"not",
"dict",
":",
"return",
"False",
",",
"\"%s is not a dict\"",
"%",
"(",
"str",
"(",
"val",
")",
")",
"for",
"k",
",",
"v",
"in",
"val",
".",
"items",
"(",
")",
":",
"field",
"=",
"self",
".",
"field",
"(",
"k",
")",
"if",
"field",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"contract",
".",
"validate",
"(",
"field",
",",
"field",
".",
"is_array",
",",
"v",
")",
"if",
"not",
"ok",
":",
"return",
"False",
",",
"\"field '%s': %s\"",
"%",
"(",
"field",
".",
"name",
",",
"msg",
")",
"else",
":",
"return",
"False",
",",
"\"field '%s' not found in struct %s\"",
"%",
"(",
"k",
",",
"self",
".",
"name",
")",
"all_fields",
"=",
"self",
".",
"get_all_fields",
"(",
"[",
"]",
")",
"for",
"field",
"in",
"all_fields",
":",
"if",
"not",
"val",
".",
"has_key",
"(",
"field",
".",
"name",
")",
"and",
"not",
"field",
".",
"optional",
":",
"return",
"False",
",",
"\"field '%s' missing from: %s\"",
"%",
"(",
"field",
".",
"name",
",",
"str",
"(",
"val",
")",
")",
"return",
"True",
",",
"None"
]
| Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Must be a dict | [
"Validates",
"that",
"the",
"val",
"matches",
"the",
"expected",
"fields",
"for",
"this",
"struct",
".",
"val",
"must",
"be",
"a",
"dict",
"and",
"must",
"contain",
"only",
"fields",
"represented",
"by",
"this",
"struct",
"and",
"its",
"ancestors",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1028-L1060 | train |
coopernurse/barrister | barrister/runtime.py | Struct.get_all_fields | def get_all_fields(self, arr):
"""
Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation.
"""
for k, v in self.fields.items():
arr.append(v)
if self.extends:
parent = self.contract.get(self.extends)
if parent:
return parent.get_all_fields(arr)
return arr | python | def get_all_fields(self, arr):
"""
Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation.
"""
for k, v in self.fields.items():
arr.append(v)
if self.extends:
parent = self.contract.get(self.extends)
if parent:
return parent.get_all_fields(arr)
return arr | [
"def",
"get_all_fields",
"(",
"self",
",",
"arr",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"arr",
".",
"append",
"(",
"v",
")",
"if",
"self",
".",
"extends",
":",
"parent",
"=",
"self",
".",
"contract",
".",
"get",
"(",
"self",
".",
"extends",
")",
"if",
"parent",
":",
"return",
"parent",
".",
"get_all_fields",
"(",
"arr",
")",
"return",
"arr"
]
| Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation. | [
"Returns",
"a",
"list",
"containing",
"this",
"struct",
"s",
"fields",
"and",
"all",
"the",
"fields",
"of",
"its",
"ancestors",
".",
"Used",
"during",
"validation",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1062-L1075 | train |
coopernurse/barrister | barrister/runtime.py | Function.validate_params | def validate_params(self, params):
"""
Validates params against expected types for this function.
Raises RpcException if the params are invalid.
"""
plen = 0
if params != None:
plen = len(params)
if len(self.params) != plen:
vals = (self.full_name, len(self.params), plen)
msg = "Function '%s' expects %d param(s). %d given." % vals
raise RpcException(ERR_INVALID_PARAMS, msg)
if params != None:
i = 0
for p in self.params:
self._validate_param(p, params[i])
i += 1 | python | def validate_params(self, params):
"""
Validates params against expected types for this function.
Raises RpcException if the params are invalid.
"""
plen = 0
if params != None:
plen = len(params)
if len(self.params) != plen:
vals = (self.full_name, len(self.params), plen)
msg = "Function '%s' expects %d param(s). %d given." % vals
raise RpcException(ERR_INVALID_PARAMS, msg)
if params != None:
i = 0
for p in self.params:
self._validate_param(p, params[i])
i += 1 | [
"def",
"validate_params",
"(",
"self",
",",
"params",
")",
":",
"plen",
"=",
"0",
"if",
"params",
"!=",
"None",
":",
"plen",
"=",
"len",
"(",
"params",
")",
"if",
"len",
"(",
"self",
".",
"params",
")",
"!=",
"plen",
":",
"vals",
"=",
"(",
"self",
".",
"full_name",
",",
"len",
"(",
"self",
".",
"params",
")",
",",
"plen",
")",
"msg",
"=",
"\"Function '%s' expects %d param(s). %d given.\"",
"%",
"vals",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
"msg",
")",
"if",
"params",
"!=",
"None",
":",
"i",
"=",
"0",
"for",
"p",
"in",
"self",
".",
"params",
":",
"self",
".",
"_validate_param",
"(",
"p",
",",
"params",
"[",
"i",
"]",
")",
"i",
"+=",
"1"
]
| Validates params against expected types for this function.
Raises RpcException if the params are invalid. | [
"Validates",
"params",
"against",
"expected",
"types",
"for",
"this",
"function",
".",
"Raises",
"RpcException",
"if",
"the",
"params",
"are",
"invalid",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1102-L1120 | train |
coopernurse/barrister | barrister/runtime.py | Function.validate_response | def validate_response(self, resp):
"""
Validates resp against expected return type for this function.
Raises RpcException if the response is invalid.
"""
ok, msg = self.contract.validate(self.returns,
self.returns.is_array, resp)
if not ok:
vals = (self.full_name, str(resp), msg)
msg = "Function '%s' invalid response: '%s'. %s" % vals
raise RpcException(ERR_INVALID_RESP, msg) | python | def validate_response(self, resp):
"""
Validates resp against expected return type for this function.
Raises RpcException if the response is invalid.
"""
ok, msg = self.contract.validate(self.returns,
self.returns.is_array, resp)
if not ok:
vals = (self.full_name, str(resp), msg)
msg = "Function '%s' invalid response: '%s'. %s" % vals
raise RpcException(ERR_INVALID_RESP, msg) | [
"def",
"validate_response",
"(",
"self",
",",
"resp",
")",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"contract",
".",
"validate",
"(",
"self",
".",
"returns",
",",
"self",
".",
"returns",
".",
"is_array",
",",
"resp",
")",
"if",
"not",
"ok",
":",
"vals",
"=",
"(",
"self",
".",
"full_name",
",",
"str",
"(",
"resp",
")",
",",
"msg",
")",
"msg",
"=",
"\"Function '%s' invalid response: '%s'. %s\"",
"%",
"vals",
"raise",
"RpcException",
"(",
"ERR_INVALID_RESP",
",",
"msg",
")"
]
| Validates resp against expected return type for this function.
Raises RpcException if the response is invalid. | [
"Validates",
"resp",
"against",
"expected",
"return",
"type",
"for",
"this",
"function",
".",
"Raises",
"RpcException",
"if",
"the",
"response",
"is",
"invalid",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1122-L1132 | train |
mkoura/dump2polarion | dump2polarion/submit.py | submit | def submit(xml_root, submit_config, session, dry_run=None, **kwargs):
"""Submits data to the Polarion Importer."""
properties.xunit_fill_testrun_id(xml_root, kwargs.get("testrun_id"))
if dry_run is not None:
properties.set_dry_run(xml_root, dry_run)
xml_input = utils.etree_to_string(xml_root)
logger.info("Submitting data to %s", submit_config.submit_target)
files = {"file": ("results.xml", xml_input)}
try:
response = session.post(submit_config.submit_target, files=files)
# pylint: disable=broad-except
except Exception as err:
logger.error(err)
response = None
return SubmitResponse(response) | python | def submit(xml_root, submit_config, session, dry_run=None, **kwargs):
"""Submits data to the Polarion Importer."""
properties.xunit_fill_testrun_id(xml_root, kwargs.get("testrun_id"))
if dry_run is not None:
properties.set_dry_run(xml_root, dry_run)
xml_input = utils.etree_to_string(xml_root)
logger.info("Submitting data to %s", submit_config.submit_target)
files = {"file": ("results.xml", xml_input)}
try:
response = session.post(submit_config.submit_target, files=files)
# pylint: disable=broad-except
except Exception as err:
logger.error(err)
response = None
return SubmitResponse(response) | [
"def",
"submit",
"(",
"xml_root",
",",
"submit_config",
",",
"session",
",",
"dry_run",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"properties",
".",
"xunit_fill_testrun_id",
"(",
"xml_root",
",",
"kwargs",
".",
"get",
"(",
"\"testrun_id\"",
")",
")",
"if",
"dry_run",
"is",
"not",
"None",
":",
"properties",
".",
"set_dry_run",
"(",
"xml_root",
",",
"dry_run",
")",
"xml_input",
"=",
"utils",
".",
"etree_to_string",
"(",
"xml_root",
")",
"logger",
".",
"info",
"(",
"\"Submitting data to %s\"",
",",
"submit_config",
".",
"submit_target",
")",
"files",
"=",
"{",
"\"file\"",
":",
"(",
"\"results.xml\"",
",",
"xml_input",
")",
"}",
"try",
":",
"response",
"=",
"session",
".",
"post",
"(",
"submit_config",
".",
"submit_target",
",",
"files",
"=",
"files",
")",
"# pylint: disable=broad-except",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"err",
")",
"response",
"=",
"None",
"return",
"SubmitResponse",
"(",
"response",
")"
]
| Submits data to the Polarion Importer. | [
"Submits",
"data",
"to",
"the",
"Polarion",
"Importer",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L153-L169 | train |
mkoura/dump2polarion | dump2polarion/submit.py | submit_and_verify | def submit_and_verify(
xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs
):
"""Submits data to the Polarion Importer and checks that it was imported."""
try:
config = config or configuration.get_config()
xml_root = _get_xml_root(xml_root, xml_str, xml_file)
submit_config = SubmitConfig(xml_root, config, **kwargs)
session = session or utils.get_session(submit_config.credentials, config)
submit_response = submit(xml_root, submit_config, session, dry_run=dry_run, **kwargs)
except Dump2PolarionException as err:
logger.error(err)
return None
valid_response = submit_response.validate_response()
if not valid_response or kwargs.get("no_verify"):
return submit_response.response
response = verify_submit(
session,
submit_config.queue_url,
submit_config.log_url,
submit_response.job_ids,
timeout=kwargs.get("verify_timeout"),
log_file=kwargs.get("log_file"),
)
return response | python | def submit_and_verify(
xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs
):
"""Submits data to the Polarion Importer and checks that it was imported."""
try:
config = config or configuration.get_config()
xml_root = _get_xml_root(xml_root, xml_str, xml_file)
submit_config = SubmitConfig(xml_root, config, **kwargs)
session = session or utils.get_session(submit_config.credentials, config)
submit_response = submit(xml_root, submit_config, session, dry_run=dry_run, **kwargs)
except Dump2PolarionException as err:
logger.error(err)
return None
valid_response = submit_response.validate_response()
if not valid_response or kwargs.get("no_verify"):
return submit_response.response
response = verify_submit(
session,
submit_config.queue_url,
submit_config.log_url,
submit_response.job_ids,
timeout=kwargs.get("verify_timeout"),
log_file=kwargs.get("log_file"),
)
return response | [
"def",
"submit_and_verify",
"(",
"xml_str",
"=",
"None",
",",
"xml_file",
"=",
"None",
",",
"xml_root",
"=",
"None",
",",
"config",
"=",
"None",
",",
"session",
"=",
"None",
",",
"dry_run",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"config",
"=",
"config",
"or",
"configuration",
".",
"get_config",
"(",
")",
"xml_root",
"=",
"_get_xml_root",
"(",
"xml_root",
",",
"xml_str",
",",
"xml_file",
")",
"submit_config",
"=",
"SubmitConfig",
"(",
"xml_root",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
"session",
"=",
"session",
"or",
"utils",
".",
"get_session",
"(",
"submit_config",
".",
"credentials",
",",
"config",
")",
"submit_response",
"=",
"submit",
"(",
"xml_root",
",",
"submit_config",
",",
"session",
",",
"dry_run",
"=",
"dry_run",
",",
"*",
"*",
"kwargs",
")",
"except",
"Dump2PolarionException",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"err",
")",
"return",
"None",
"valid_response",
"=",
"submit_response",
".",
"validate_response",
"(",
")",
"if",
"not",
"valid_response",
"or",
"kwargs",
".",
"get",
"(",
"\"no_verify\"",
")",
":",
"return",
"submit_response",
".",
"response",
"response",
"=",
"verify_submit",
"(",
"session",
",",
"submit_config",
".",
"queue_url",
",",
"submit_config",
".",
"log_url",
",",
"submit_response",
".",
"job_ids",
",",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"\"verify_timeout\"",
")",
",",
"log_file",
"=",
"kwargs",
".",
"get",
"(",
"\"log_file\"",
")",
",",
")",
"return",
"response"
]
| Submits data to the Polarion Importer and checks that it was imported. | [
"Submits",
"data",
"to",
"the",
"Polarion",
"Importer",
"and",
"checks",
"that",
"it",
"was",
"imported",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L173-L200 | train |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitResponse.get_job_ids | def get_job_ids(self):
"""Returns job IDs of the import."""
if not self.parsed_response:
return None
try:
job_ids = self.parsed_response["files"]["results.xml"]["job-ids"]
except KeyError:
return None
if not job_ids or job_ids == [0]:
return None
return job_ids | python | def get_job_ids(self):
"""Returns job IDs of the import."""
if not self.parsed_response:
return None
try:
job_ids = self.parsed_response["files"]["results.xml"]["job-ids"]
except KeyError:
return None
if not job_ids or job_ids == [0]:
return None
return job_ids | [
"def",
"get_job_ids",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parsed_response",
":",
"return",
"None",
"try",
":",
"job_ids",
"=",
"self",
".",
"parsed_response",
"[",
"\"files\"",
"]",
"[",
"\"results.xml\"",
"]",
"[",
"\"job-ids\"",
"]",
"except",
"KeyError",
":",
"return",
"None",
"if",
"not",
"job_ids",
"or",
"job_ids",
"==",
"[",
"0",
"]",
":",
"return",
"None",
"return",
"job_ids"
]
| Returns job IDs of the import. | [
"Returns",
"job",
"IDs",
"of",
"the",
"import",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L35-L45 | train |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitResponse.validate_response | def validate_response(self):
"""Checks that the response is valid and import succeeded."""
if self.response is None:
logger.error("Failed to submit")
return False
if not self.response:
logger.error(
"HTTP status %d: failed to submit to %s",
self.response.status_code,
self.response.url,
)
return False
if not self.parsed_response:
logger.error("Submit to %s failed, invalid response received", self.response.url)
return False
error_message = self.get_error_message()
if error_message:
logger.error("Submit to %s failed with error", self.response.url)
logger.debug("Error message: %s", error_message)
return False
if not self.job_ids:
logger.error("Submit to %s failed to get job id", self.response.url)
return False
logger.info("Results received by the Importer (HTTP status %d)", self.response.status_code)
logger.info("Job IDs: %s", self.job_ids)
return True | python | def validate_response(self):
"""Checks that the response is valid and import succeeded."""
if self.response is None:
logger.error("Failed to submit")
return False
if not self.response:
logger.error(
"HTTP status %d: failed to submit to %s",
self.response.status_code,
self.response.url,
)
return False
if not self.parsed_response:
logger.error("Submit to %s failed, invalid response received", self.response.url)
return False
error_message = self.get_error_message()
if error_message:
logger.error("Submit to %s failed with error", self.response.url)
logger.debug("Error message: %s", error_message)
return False
if not self.job_ids:
logger.error("Submit to %s failed to get job id", self.response.url)
return False
logger.info("Results received by the Importer (HTTP status %d)", self.response.status_code)
logger.info("Job IDs: %s", self.job_ids)
return True | [
"def",
"validate_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"response",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"\"Failed to submit\"",
")",
"return",
"False",
"if",
"not",
"self",
".",
"response",
":",
"logger",
".",
"error",
"(",
"\"HTTP status %d: failed to submit to %s\"",
",",
"self",
".",
"response",
".",
"status_code",
",",
"self",
".",
"response",
".",
"url",
",",
")",
"return",
"False",
"if",
"not",
"self",
".",
"parsed_response",
":",
"logger",
".",
"error",
"(",
"\"Submit to %s failed, invalid response received\"",
",",
"self",
".",
"response",
".",
"url",
")",
"return",
"False",
"error_message",
"=",
"self",
".",
"get_error_message",
"(",
")",
"if",
"error_message",
":",
"logger",
".",
"error",
"(",
"\"Submit to %s failed with error\"",
",",
"self",
".",
"response",
".",
"url",
")",
"logger",
".",
"debug",
"(",
"\"Error message: %s\"",
",",
"error_message",
")",
"return",
"False",
"if",
"not",
"self",
".",
"job_ids",
":",
"logger",
".",
"error",
"(",
"\"Submit to %s failed to get job id\"",
",",
"self",
".",
"response",
".",
"url",
")",
"return",
"False",
"logger",
".",
"info",
"(",
"\"Results received by the Importer (HTTP status %d)\"",
",",
"self",
".",
"response",
".",
"status_code",
")",
"logger",
".",
"info",
"(",
"\"Job IDs: %s\"",
",",
"self",
".",
"job_ids",
")",
"return",
"True"
]
| Checks that the response is valid and import succeeded. | [
"Checks",
"that",
"the",
"response",
"is",
"valid",
"and",
"import",
"succeeded",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L53-L84 | train |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitConfig.get_targets | def get_targets(self):
"""Sets targets."""
if self.xml_root.tag == "testcases":
self.submit_target = self.config.get("testcase_taget")
self.queue_url = self.config.get("testcase_queue")
self.log_url = self.config.get("testcase_log")
elif self.xml_root.tag == "testsuites":
self.submit_target = self.config.get("xunit_target")
self.queue_url = self.config.get("xunit_queue")
self.log_url = self.config.get("xunit_log")
elif self.xml_root.tag == "requirements":
self.submit_target = self.config.get("requirement_target")
self.queue_url = self.config.get("requirement_queue")
self.log_url = self.config.get("requirement_log")
else:
raise Dump2PolarionException("Failed to submit to Polarion - submit target not found") | python | def get_targets(self):
"""Sets targets."""
if self.xml_root.tag == "testcases":
self.submit_target = self.config.get("testcase_taget")
self.queue_url = self.config.get("testcase_queue")
self.log_url = self.config.get("testcase_log")
elif self.xml_root.tag == "testsuites":
self.submit_target = self.config.get("xunit_target")
self.queue_url = self.config.get("xunit_queue")
self.log_url = self.config.get("xunit_log")
elif self.xml_root.tag == "requirements":
self.submit_target = self.config.get("requirement_target")
self.queue_url = self.config.get("requirement_queue")
self.log_url = self.config.get("requirement_log")
else:
raise Dump2PolarionException("Failed to submit to Polarion - submit target not found") | [
"def",
"get_targets",
"(",
"self",
")",
":",
"if",
"self",
".",
"xml_root",
".",
"tag",
"==",
"\"testcases\"",
":",
"self",
".",
"submit_target",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"testcase_taget\"",
")",
"self",
".",
"queue_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"testcase_queue\"",
")",
"self",
".",
"log_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"testcase_log\"",
")",
"elif",
"self",
".",
"xml_root",
".",
"tag",
"==",
"\"testsuites\"",
":",
"self",
".",
"submit_target",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"xunit_target\"",
")",
"self",
".",
"queue_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"xunit_queue\"",
")",
"self",
".",
"log_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"xunit_log\"",
")",
"elif",
"self",
".",
"xml_root",
".",
"tag",
"==",
"\"requirements\"",
":",
"self",
".",
"submit_target",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"requirement_target\"",
")",
"self",
".",
"queue_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"requirement_queue\"",
")",
"self",
".",
"log_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"requirement_log\"",
")",
"else",
":",
"raise",
"Dump2PolarionException",
"(",
"\"Failed to submit to Polarion - submit target not found\"",
")"
]
| Sets targets. | [
"Sets",
"targets",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L109-L124 | train |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitConfig.get_credentials | def get_credentials(self, **kwargs):
"""Sets credentails."""
login = (
kwargs.get("user") or os.environ.get("POLARION_USERNAME") or self.config.get("username")
)
pwd = (
kwargs.get("password")
or os.environ.get("POLARION_PASSWORD")
or self.config.get("password")
)
if not all([login, pwd]):
raise Dump2PolarionException("Failed to submit to Polarion - missing credentials")
self.credentials = (login, pwd) | python | def get_credentials(self, **kwargs):
"""Sets credentails."""
login = (
kwargs.get("user") or os.environ.get("POLARION_USERNAME") or self.config.get("username")
)
pwd = (
kwargs.get("password")
or os.environ.get("POLARION_PASSWORD")
or self.config.get("password")
)
if not all([login, pwd]):
raise Dump2PolarionException("Failed to submit to Polarion - missing credentials")
self.credentials = (login, pwd) | [
"def",
"get_credentials",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"login",
"=",
"(",
"kwargs",
".",
"get",
"(",
"\"user\"",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"\"POLARION_USERNAME\"",
")",
"or",
"self",
".",
"config",
".",
"get",
"(",
"\"username\"",
")",
")",
"pwd",
"=",
"(",
"kwargs",
".",
"get",
"(",
"\"password\"",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"\"POLARION_PASSWORD\"",
")",
"or",
"self",
".",
"config",
".",
"get",
"(",
"\"password\"",
")",
")",
"if",
"not",
"all",
"(",
"[",
"login",
",",
"pwd",
"]",
")",
":",
"raise",
"Dump2PolarionException",
"(",
"\"Failed to submit to Polarion - missing credentials\"",
")",
"self",
".",
"credentials",
"=",
"(",
"login",
",",
"pwd",
")"
]
| Sets credentails. | [
"Sets",
"credentails",
"."
]
| f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L126-L140 | train |
praekeltfoundation/seed-message-sender | message_sender/formatters.py | e_164 | def e_164(msisdn: str) -> str:
"""
Returns the msisdn in E.164 international format.
"""
# Phonenumbers library requires the + to identify the country, so we add it if it
# does not already exist
number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) | python | def e_164(msisdn: str) -> str:
"""
Returns the msisdn in E.164 international format.
"""
# Phonenumbers library requires the + to identify the country, so we add it if it
# does not already exist
number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) | [
"def",
"e_164",
"(",
"msisdn",
":",
"str",
")",
"->",
"str",
":",
"# Phonenumbers library requires the + to identify the country, so we add it if it",
"# does not already exist",
"number",
"=",
"phonenumbers",
".",
"parse",
"(",
"\"+{}\"",
".",
"format",
"(",
"msisdn",
".",
"lstrip",
"(",
"\"+\"",
")",
")",
",",
"None",
")",
"return",
"phonenumbers",
".",
"format_number",
"(",
"number",
",",
"phonenumbers",
".",
"PhoneNumberFormat",
".",
"E164",
")"
]
| Returns the msisdn in E.164 international format. | [
"Returns",
"the",
"msisdn",
"in",
"E",
".",
"164",
"international",
"format",
"."
]
| 257b01635171b9dbe1f5f13baa810c971bb2620e | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/formatters.py#L31-L38 | train |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.loadFile | def loadFile(self, filePath):
"""Loads a file"""
self._filePath = filePath
if self._proc.state() != QProcess.Running:
self._kill()
self._run(self._filePath)
else:
self._execute("pausing_keep_force pt_step 1")
self._execute("get_property pause")
self._execute("loadfile \"%s\"" % self._filePath)
self._data.reset()
self.videoDataChanged.emit(False)
self._changePlayingState(True) | python | def loadFile(self, filePath):
"""Loads a file"""
self._filePath = filePath
if self._proc.state() != QProcess.Running:
self._kill()
self._run(self._filePath)
else:
self._execute("pausing_keep_force pt_step 1")
self._execute("get_property pause")
self._execute("loadfile \"%s\"" % self._filePath)
self._data.reset()
self.videoDataChanged.emit(False)
self._changePlayingState(True) | [
"def",
"loadFile",
"(",
"self",
",",
"filePath",
")",
":",
"self",
".",
"_filePath",
"=",
"filePath",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"!=",
"QProcess",
".",
"Running",
":",
"self",
".",
"_kill",
"(",
")",
"self",
".",
"_run",
"(",
"self",
".",
"_filePath",
")",
"else",
":",
"self",
".",
"_execute",
"(",
"\"pausing_keep_force pt_step 1\"",
")",
"self",
".",
"_execute",
"(",
"\"get_property pause\"",
")",
"self",
".",
"_execute",
"(",
"\"loadfile \\\"%s\\\"\"",
"%",
"self",
".",
"_filePath",
")",
"self",
".",
"_data",
".",
"reset",
"(",
")",
"self",
".",
"videoDataChanged",
".",
"emit",
"(",
"False",
")",
"self",
".",
"_changePlayingState",
"(",
"True",
")"
]
| Loads a file | [
"Loads",
"a",
"file"
]
| 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L107-L121 | train |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.play | def play(self):
"""Starts a playback"""
if self._proc.state() == QProcess.Running:
if self.isPlaying is False:
self._execute("pause")
self._changePlayingState(True)
elif self._filePath is not None:
self._kill()
self._run(self._filePath)
self._changePlayingState(True) | python | def play(self):
"""Starts a playback"""
if self._proc.state() == QProcess.Running:
if self.isPlaying is False:
self._execute("pause")
self._changePlayingState(True)
elif self._filePath is not None:
self._kill()
self._run(self._filePath)
self._changePlayingState(True) | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"==",
"QProcess",
".",
"Running",
":",
"if",
"self",
".",
"isPlaying",
"is",
"False",
":",
"self",
".",
"_execute",
"(",
"\"pause\"",
")",
"self",
".",
"_changePlayingState",
"(",
"True",
")",
"elif",
"self",
".",
"_filePath",
"is",
"not",
"None",
":",
"self",
".",
"_kill",
"(",
")",
"self",
".",
"_run",
"(",
"self",
".",
"_filePath",
")",
"self",
".",
"_changePlayingState",
"(",
"True",
")"
]
| Starts a playback | [
"Starts",
"a",
"playback"
]
| 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L123-L132 | train |
davidfokkema/artist | demo/demo_fourier_with_legend.py | fourier | def fourier(x, N):
"""Fourier approximation with N terms"""
term = 0.
for n in range(1, N, 2):
term += (1. / n) * math.sin(n * math.pi * x / L)
return (4. / (math.pi)) * term | python | def fourier(x, N):
"""Fourier approximation with N terms"""
term = 0.
for n in range(1, N, 2):
term += (1. / n) * math.sin(n * math.pi * x / L)
return (4. / (math.pi)) * term | [
"def",
"fourier",
"(",
"x",
",",
"N",
")",
":",
"term",
"=",
"0.",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"N",
",",
"2",
")",
":",
"term",
"+=",
"(",
"1.",
"/",
"n",
")",
"*",
"math",
".",
"sin",
"(",
"n",
"*",
"math",
".",
"pi",
"*",
"x",
"/",
"L",
")",
"return",
"(",
"4.",
"/",
"(",
"math",
".",
"pi",
")",
")",
"*",
"term"
]
| Fourier approximation with N terms | [
"Fourier",
"approximation",
"with",
"N",
"terms"
]
| 26ae7987522622710f2910980770c50012fda47d | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/demo/demo_fourier_with_legend.py#L26-L32 | train |
coopernurse/barrister | barrister/docco.py | parse_enum | def parse_enum(enum):
"""
Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values'
"""
docs = enum['comment']
code = '<span class="k">enum</span> <span class="gs">%s</span> {\n' % enum['name']
for v in enum["values"]:
if v['comment']:
for line in v['comment'].split("\n"):
code += ' <span class="c1">// %s</span>\n' % line
code += ' <span class="nv">%s</span>\n' % v['value']
code += "}"
return to_section(docs, code) | python | def parse_enum(enum):
"""
Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values'
"""
docs = enum['comment']
code = '<span class="k">enum</span> <span class="gs">%s</span> {\n' % enum['name']
for v in enum["values"]:
if v['comment']:
for line in v['comment'].split("\n"):
code += ' <span class="c1">// %s</span>\n' % line
code += ' <span class="nv">%s</span>\n' % v['value']
code += "}"
return to_section(docs, code) | [
"def",
"parse_enum",
"(",
"enum",
")",
":",
"docs",
"=",
"enum",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">enum</span> <span class=\"gs\">%s</span> {\\n'",
"%",
"enum",
"[",
"'name'",
"]",
"for",
"v",
"in",
"enum",
"[",
"\"values\"",
"]",
":",
"if",
"v",
"[",
"'comment'",
"]",
":",
"for",
"line",
"in",
"v",
"[",
"'comment'",
"]",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"code",
"+=",
"' <span class=\"c1\">// %s</span>\\n'",
"%",
"line",
"code",
"+=",
"' <span class=\"nv\">%s</span>\\n'",
"%",
"v",
"[",
"'value'",
"]",
"code",
"+=",
"\"}\"",
"return",
"to_section",
"(",
"docs",
",",
"code",
")"
]
| Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"enum",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L293-L310 | train |
coopernurse/barrister | barrister/docco.py | parse_struct | def parse_struct(s):
"""
Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields'
"""
docs = s['comment']
code = '<span class="k">struct</span> <span class="gs">%s</span>' % s['name']
if s['extends']:
code += ' extends <span class="gs">%s</span>' % s['extends']
code += ' {\n'
namelen = 0
typelen = 0
for v in s["fields"]:
tlen = len(format_type(v, includeOptional=False))
if len(v['name']) > namelen:
namelen = len(v['name'])
if tlen > typelen:
typelen = tlen
namelen += 1
typelen += 1
formatstr = ' <span class="nv">%s</span><span class="kt">%s %s</span>\n'
i = 0
for v in s["fields"]:
if v.has_key('comment') and v['comment']:
if i > 0: code += "\n"
for line in v['comment'].split("\n"):
code += ' <span class="c1">// %s</span>\n' % line
opt = ""
if v.has_key('optional') and v['optional'] == True:
opt = " [optional]"
code += formatstr % (string.ljust(v['name'], namelen), string.ljust(format_type(v, includeOptional=False), typelen), opt)
i += 1
code += "}"
return to_section(docs, code) | python | def parse_struct(s):
"""
Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields'
"""
docs = s['comment']
code = '<span class="k">struct</span> <span class="gs">%s</span>' % s['name']
if s['extends']:
code += ' extends <span class="gs">%s</span>' % s['extends']
code += ' {\n'
namelen = 0
typelen = 0
for v in s["fields"]:
tlen = len(format_type(v, includeOptional=False))
if len(v['name']) > namelen:
namelen = len(v['name'])
if tlen > typelen:
typelen = tlen
namelen += 1
typelen += 1
formatstr = ' <span class="nv">%s</span><span class="kt">%s %s</span>\n'
i = 0
for v in s["fields"]:
if v.has_key('comment') and v['comment']:
if i > 0: code += "\n"
for line in v['comment'].split("\n"):
code += ' <span class="c1">// %s</span>\n' % line
opt = ""
if v.has_key('optional') and v['optional'] == True:
opt = " [optional]"
code += formatstr % (string.ljust(v['name'], namelen), string.ljust(format_type(v, includeOptional=False), typelen), opt)
i += 1
code += "}"
return to_section(docs, code) | [
"def",
"parse_struct",
"(",
"s",
")",
":",
"docs",
"=",
"s",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">struct</span> <span class=\"gs\">%s</span>'",
"%",
"s",
"[",
"'name'",
"]",
"if",
"s",
"[",
"'extends'",
"]",
":",
"code",
"+=",
"' extends <span class=\"gs\">%s</span>'",
"%",
"s",
"[",
"'extends'",
"]",
"code",
"+=",
"' {\\n'",
"namelen",
"=",
"0",
"typelen",
"=",
"0",
"for",
"v",
"in",
"s",
"[",
"\"fields\"",
"]",
":",
"tlen",
"=",
"len",
"(",
"format_type",
"(",
"v",
",",
"includeOptional",
"=",
"False",
")",
")",
"if",
"len",
"(",
"v",
"[",
"'name'",
"]",
")",
">",
"namelen",
":",
"namelen",
"=",
"len",
"(",
"v",
"[",
"'name'",
"]",
")",
"if",
"tlen",
">",
"typelen",
":",
"typelen",
"=",
"tlen",
"namelen",
"+=",
"1",
"typelen",
"+=",
"1",
"formatstr",
"=",
"' <span class=\"nv\">%s</span><span class=\"kt\">%s %s</span>\\n'",
"i",
"=",
"0",
"for",
"v",
"in",
"s",
"[",
"\"fields\"",
"]",
":",
"if",
"v",
".",
"has_key",
"(",
"'comment'",
")",
"and",
"v",
"[",
"'comment'",
"]",
":",
"if",
"i",
">",
"0",
":",
"code",
"+=",
"\"\\n\"",
"for",
"line",
"in",
"v",
"[",
"'comment'",
"]",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"code",
"+=",
"' <span class=\"c1\">// %s</span>\\n'",
"%",
"line",
"opt",
"=",
"\"\"",
"if",
"v",
".",
"has_key",
"(",
"'optional'",
")",
"and",
"v",
"[",
"'optional'",
"]",
"==",
"True",
":",
"opt",
"=",
"\" [optional]\"",
"code",
"+=",
"formatstr",
"%",
"(",
"string",
".",
"ljust",
"(",
"v",
"[",
"'name'",
"]",
",",
"namelen",
")",
",",
"string",
".",
"ljust",
"(",
"format_type",
"(",
"v",
",",
"includeOptional",
"=",
"False",
")",
",",
"typelen",
")",
",",
"opt",
")",
"i",
"+=",
"1",
"code",
"+=",
"\"}\"",
"return",
"to_section",
"(",
"docs",
",",
"code",
")"
]
| Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"struct",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L312-L352 | train |
coopernurse/barrister | barrister/docco.py | parse_interface | def parse_interface(iface):
"""
Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params'
"""
sections = [ ]
docs = iface['comment']
code = '<span class="k">interface</span> <span class="gs">%s</span> {\n' % iface['name']
for v in iface["functions"]:
func_code = ' <span class="nf">%s</span>(' % v['name']
i = 0
for p in v["params"]:
if i == 0: i = 1
else: func_code += ", "
func_code += '<span class="na">%s</span> <span class="kt">%s</span>' % (p['name'], format_type(p))
func_code += ') <span class="kt">%s</span>\n' % format_type(v['returns'])
if v.has_key('comment') and v['comment']:
if code:
sections.append(to_section(docs, code))
docs = v['comment']
code = func_code
else:
code += func_code
code += "}"
sections.append(to_section(docs, code))
return sections | python | def parse_interface(iface):
"""
Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params'
"""
sections = [ ]
docs = iface['comment']
code = '<span class="k">interface</span> <span class="gs">%s</span> {\n' % iface['name']
for v in iface["functions"]:
func_code = ' <span class="nf">%s</span>(' % v['name']
i = 0
for p in v["params"]:
if i == 0: i = 1
else: func_code += ", "
func_code += '<span class="na">%s</span> <span class="kt">%s</span>' % (p['name'], format_type(p))
func_code += ') <span class="kt">%s</span>\n' % format_type(v['returns'])
if v.has_key('comment') and v['comment']:
if code:
sections.append(to_section(docs, code))
docs = v['comment']
code = func_code
else:
code += func_code
code += "}"
sections.append(to_section(docs, code))
return sections | [
"def",
"parse_interface",
"(",
"iface",
")",
":",
"sections",
"=",
"[",
"]",
"docs",
"=",
"iface",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">interface</span> <span class=\"gs\">%s</span> {\\n'",
"%",
"iface",
"[",
"'name'",
"]",
"for",
"v",
"in",
"iface",
"[",
"\"functions\"",
"]",
":",
"func_code",
"=",
"' <span class=\"nf\">%s</span>('",
"%",
"v",
"[",
"'name'",
"]",
"i",
"=",
"0",
"for",
"p",
"in",
"v",
"[",
"\"params\"",
"]",
":",
"if",
"i",
"==",
"0",
":",
"i",
"=",
"1",
"else",
":",
"func_code",
"+=",
"\", \"",
"func_code",
"+=",
"'<span class=\"na\">%s</span> <span class=\"kt\">%s</span>'",
"%",
"(",
"p",
"[",
"'name'",
"]",
",",
"format_type",
"(",
"p",
")",
")",
"func_code",
"+=",
"') <span class=\"kt\">%s</span>\\n'",
"%",
"format_type",
"(",
"v",
"[",
"'returns'",
"]",
")",
"if",
"v",
".",
"has_key",
"(",
"'comment'",
")",
"and",
"v",
"[",
"'comment'",
"]",
":",
"if",
"code",
":",
"sections",
".",
"append",
"(",
"to_section",
"(",
"docs",
",",
"code",
")",
")",
"docs",
"=",
"v",
"[",
"'comment'",
"]",
"code",
"=",
"func_code",
"else",
":",
"code",
"+=",
"func_code",
"code",
"+=",
"\"}\"",
"sections",
".",
"append",
"(",
"to_section",
"(",
"docs",
",",
"code",
")",
")",
"return",
"sections"
]
| Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"interface",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L354-L383 | train |
coopernurse/barrister | barrister/docco.py | to_sections | def to_sections(idl_parsed):
"""
Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL
"""
sections = []
for entity in idl_parsed:
if entity["type"] == "comment":
sections.append(to_section(entity["value"], ""))
elif entity["type"] == "enum":
sections.append(parse_enum(entity))
elif entity["type"] == "struct":
sections.append(parse_struct(entity))
elif entity["type"] == "interface":
sections.extend(parse_interface(entity))
return sections | python | def to_sections(idl_parsed):
"""
Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL
"""
sections = []
for entity in idl_parsed:
if entity["type"] == "comment":
sections.append(to_section(entity["value"], ""))
elif entity["type"] == "enum":
sections.append(parse_enum(entity))
elif entity["type"] == "struct":
sections.append(parse_struct(entity))
elif entity["type"] == "interface":
sections.extend(parse_interface(entity))
return sections | [
"def",
"to_sections",
"(",
"idl_parsed",
")",
":",
"sections",
"=",
"[",
"]",
"for",
"entity",
"in",
"idl_parsed",
":",
"if",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"comment\"",
":",
"sections",
".",
"append",
"(",
"to_section",
"(",
"entity",
"[",
"\"value\"",
"]",
",",
"\"\"",
")",
")",
"elif",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"enum\"",
":",
"sections",
".",
"append",
"(",
"parse_enum",
"(",
"entity",
")",
")",
"elif",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"struct\"",
":",
"sections",
".",
"append",
"(",
"parse_struct",
"(",
"entity",
")",
")",
"elif",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"interface\"",
":",
"sections",
".",
"extend",
"(",
"parse_interface",
"(",
"entity",
")",
")",
"return",
"sections"
]
| Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL | [
"Iterates",
"through",
"elements",
"in",
"idl_parsed",
"list",
"and",
"returns",
"a",
"list",
"of",
"section",
"dicts",
".",
"Currently",
"elements",
"of",
"type",
"comment",
"enum",
"struct",
"and",
"interface",
"are",
"processed",
"."
]
| 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L411-L430 | train |
PythonOptimizers/cygenja | cygenja/treemap/location_descriptor.py | LocationDescriptor.sub_location | def sub_location(self, nbr):
"""
Return a given sub location, 0-based.
Args:
nbr:
Returns:
"""
assert nbr > -1, "Sub location number must be greater or equal to 0!"
assert nbr < self.nbr_of_sub_locations() - 1, "Sub location number must be lower than %d!" % self.nbr_of_sub_locations() - 1
return self._locations_list[nbr] | python | def sub_location(self, nbr):
"""
Return a given sub location, 0-based.
Args:
nbr:
Returns:
"""
assert nbr > -1, "Sub location number must be greater or equal to 0!"
assert nbr < self.nbr_of_sub_locations() - 1, "Sub location number must be lower than %d!" % self.nbr_of_sub_locations() - 1
return self._locations_list[nbr] | [
"def",
"sub_location",
"(",
"self",
",",
"nbr",
")",
":",
"assert",
"nbr",
">",
"-",
"1",
",",
"\"Sub location number must be greater or equal to 0!\"",
"assert",
"nbr",
"<",
"self",
".",
"nbr_of_sub_locations",
"(",
")",
"-",
"1",
",",
"\"Sub location number must be lower than %d!\"",
"%",
"self",
".",
"nbr_of_sub_locations",
"(",
")",
"-",
"1",
"return",
"self",
".",
"_locations_list",
"[",
"nbr",
"]"
]
| Return a given sub location, 0-based.
Args:
nbr:
Returns: | [
"Return",
"a",
"given",
"sub",
"location",
"0",
"-",
"based",
"."
]
| a9ef91cdfa8452beeeec4f050f928b830379f91c | https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/location_descriptor.py#L119-L130 | train |
PythonOptimizers/cygenja | cygenja/treemap/location_descriptor.py | LocationDescriptor.get_locations_list | def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.nbr_of_sub_locations()
try:
return self._locations_list[lower_bound:real_upper_bound]
except:
return list() | python | def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.nbr_of_sub_locations()
try:
return self._locations_list[lower_bound:real_upper_bound]
except:
return list() | [
"def",
"get_locations_list",
"(",
"self",
",",
"lower_bound",
"=",
"0",
",",
"upper_bound",
"=",
"None",
")",
":",
"real_upper_bound",
"=",
"upper_bound",
"if",
"upper_bound",
"is",
"None",
":",
"real_upper_bound",
"=",
"self",
".",
"nbr_of_sub_locations",
"(",
")",
"try",
":",
"return",
"self",
".",
"_locations_list",
"[",
"lower_bound",
":",
"real_upper_bound",
"]",
"except",
":",
"return",
"list",
"(",
")"
]
| Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns: | [
"Return",
"the",
"internal",
"location",
"list",
"."
]
| a9ef91cdfa8452beeeec4f050f928b830379f91c | https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/location_descriptor.py#L132-L149 | train |
tweekmonster/moult | moult/ast_scanner.py | get_args | def get_args(args, kwargs, arg_names):
'''Get arguments as a dict.
'''
n_args = len(arg_names)
if len(args) + len(kwargs) > n_args:
raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args))
out_args = {}
for i, a in enumerate(args):
out_args[arg_names[i]] = a
for a in arg_names:
if a not in out_args:
out_args[a] = None
out_args.update(kwargs)
return out_args | python | def get_args(args, kwargs, arg_names):
'''Get arguments as a dict.
'''
n_args = len(arg_names)
if len(args) + len(kwargs) > n_args:
raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args))
out_args = {}
for i, a in enumerate(args):
out_args[arg_names[i]] = a
for a in arg_names:
if a not in out_args:
out_args[a] = None
out_args.update(kwargs)
return out_args | [
"def",
"get_args",
"(",
"args",
",",
"kwargs",
",",
"arg_names",
")",
":",
"n_args",
"=",
"len",
"(",
"arg_names",
")",
"if",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
">",
"n_args",
":",
"raise",
"MoultScannerError",
"(",
"'Too many arguments supplied. Expected: {}'",
".",
"format",
"(",
"n_args",
")",
")",
"out_args",
"=",
"{",
"}",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"args",
")",
":",
"out_args",
"[",
"arg_names",
"[",
"i",
"]",
"]",
"=",
"a",
"for",
"a",
"in",
"arg_names",
":",
"if",
"a",
"not",
"in",
"out_args",
":",
"out_args",
"[",
"a",
"]",
"=",
"None",
"out_args",
".",
"update",
"(",
"kwargs",
")",
"return",
"out_args"
]
| Get arguments as a dict. | [
"Get",
"arguments",
"as",
"a",
"dict",
"."
]
| 38d3a3b9002336219897ebe263ca1d8dcadbecf5 | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L123-L139 | train |
tweekmonster/moult | moult/ast_scanner.py | ast_scan_file | def ast_scan_file(filename, re_fallback=True):
'''Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with variables instead of strings.
'''
try:
with io.open(filename, 'rb') as fp:
try:
root = ast.parse(fp.read(), filename=filename)
except (SyntaxError, IndentationError):
if re_fallback:
log.debug('Falling back to regex scanner')
return _ast_scan_file_re(filename)
else:
log.error('Could not parse file: %s', filename)
log.info('Exception:', exc_info=True)
return None, None
log.debug('Starting AST Scan: %s', filename)
ast_visitor.reset(filename)
ast_visitor.visit(root)
log.debug('Project path: %s', ast_visitor.import_root)
return ast_visitor.scope, ast_visitor.imports
except IOError:
log.warn('Could not open file: %s', filename)
return None, None | python | def ast_scan_file(filename, re_fallback=True):
'''Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with variables instead of strings.
'''
try:
with io.open(filename, 'rb') as fp:
try:
root = ast.parse(fp.read(), filename=filename)
except (SyntaxError, IndentationError):
if re_fallback:
log.debug('Falling back to regex scanner')
return _ast_scan_file_re(filename)
else:
log.error('Could not parse file: %s', filename)
log.info('Exception:', exc_info=True)
return None, None
log.debug('Starting AST Scan: %s', filename)
ast_visitor.reset(filename)
ast_visitor.visit(root)
log.debug('Project path: %s', ast_visitor.import_root)
return ast_visitor.scope, ast_visitor.imports
except IOError:
log.warn('Could not open file: %s', filename)
return None, None | [
"def",
"ast_scan_file",
"(",
"filename",
",",
"re_fallback",
"=",
"True",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"try",
":",
"root",
"=",
"ast",
".",
"parse",
"(",
"fp",
".",
"read",
"(",
")",
",",
"filename",
"=",
"filename",
")",
"except",
"(",
"SyntaxError",
",",
"IndentationError",
")",
":",
"if",
"re_fallback",
":",
"log",
".",
"debug",
"(",
"'Falling back to regex scanner'",
")",
"return",
"_ast_scan_file_re",
"(",
"filename",
")",
"else",
":",
"log",
".",
"error",
"(",
"'Could not parse file: %s'",
",",
"filename",
")",
"log",
".",
"info",
"(",
"'Exception:'",
",",
"exc_info",
"=",
"True",
")",
"return",
"None",
",",
"None",
"log",
".",
"debug",
"(",
"'Starting AST Scan: %s'",
",",
"filename",
")",
"ast_visitor",
".",
"reset",
"(",
"filename",
")",
"ast_visitor",
".",
"visit",
"(",
"root",
")",
"log",
".",
"debug",
"(",
"'Project path: %s'",
",",
"ast_visitor",
".",
"import_root",
")",
"return",
"ast_visitor",
".",
"scope",
",",
"ast_visitor",
".",
"imports",
"except",
"IOError",
":",
"log",
".",
"warn",
"(",
"'Could not open file: %s'",
",",
"filename",
")",
"return",
"None",
",",
"None"
]
| Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with variables instead of strings. | [
"Scans",
"a",
"file",
"for",
"imports",
"using",
"AST",
"."
]
| 38d3a3b9002336219897ebe263ca1d8dcadbecf5 | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L291-L319 | train |
DavidMStraub/pylha | pylha/export.py | dump | def dump(d, fmt='json', stream=None):
"""Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string
"""
if fmt == 'json':
return _dump_json(d, stream=stream)
elif fmt == 'yaml':
return yaml.dump(d, stream)
elif fmt == 'lha':
s = _dump_lha(d)
if stream is None:
return s
else:
return stream.write(s) | python | def dump(d, fmt='json', stream=None):
"""Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string
"""
if fmt == 'json':
return _dump_json(d, stream=stream)
elif fmt == 'yaml':
return yaml.dump(d, stream)
elif fmt == 'lha':
s = _dump_lha(d)
if stream is None:
return s
else:
return stream.write(s) | [
"def",
"dump",
"(",
"d",
",",
"fmt",
"=",
"'json'",
",",
"stream",
"=",
"None",
")",
":",
"if",
"fmt",
"==",
"'json'",
":",
"return",
"_dump_json",
"(",
"d",
",",
"stream",
"=",
"stream",
")",
"elif",
"fmt",
"==",
"'yaml'",
":",
"return",
"yaml",
".",
"dump",
"(",
"d",
",",
"stream",
")",
"elif",
"fmt",
"==",
"'lha'",
":",
"s",
"=",
"_dump_lha",
"(",
"d",
")",
"if",
"stream",
"is",
"None",
":",
"return",
"s",
"else",
":",
"return",
"stream",
".",
"write",
"(",
"s",
")"
]
| Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string | [
"Serialize",
"structured",
"data",
"into",
"a",
"stream",
"in",
"JSON",
"YAML",
"or",
"LHA",
"format",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
]
| 8d65074609321e5eaf97fe962c56f6d79a3ad2b6 | https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/export.py#L13-L30 | train |
mintchaos/django_inlines | django_inlines/inlines.py | inline_for_model | def inline_for_model(model, variants=[], inline_args={}):
"""
A shortcut function to produce ModelInlines for django models
"""
if not isinstance(model, ModelBase):
raise ValueError("inline_for_model requires it's argument to be a Django Model")
d = dict(model=model)
if variants:
d['variants'] = variants
if inline_args:
d['args'] = inline_args
class_name = "%sInline" % model._meta.module_name.capitalize()
return type(class_name, (ModelInline,), d) | python | def inline_for_model(model, variants=[], inline_args={}):
"""
A shortcut function to produce ModelInlines for django models
"""
if not isinstance(model, ModelBase):
raise ValueError("inline_for_model requires it's argument to be a Django Model")
d = dict(model=model)
if variants:
d['variants'] = variants
if inline_args:
d['args'] = inline_args
class_name = "%sInline" % model._meta.module_name.capitalize()
return type(class_name, (ModelInline,), d) | [
"def",
"inline_for_model",
"(",
"model",
",",
"variants",
"=",
"[",
"]",
",",
"inline_args",
"=",
"{",
"}",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"ModelBase",
")",
":",
"raise",
"ValueError",
"(",
"\"inline_for_model requires it's argument to be a Django Model\"",
")",
"d",
"=",
"dict",
"(",
"model",
"=",
"model",
")",
"if",
"variants",
":",
"d",
"[",
"'variants'",
"]",
"=",
"variants",
"if",
"inline_args",
":",
"d",
"[",
"'args'",
"]",
"=",
"inline_args",
"class_name",
"=",
"\"%sInline\"",
"%",
"model",
".",
"_meta",
".",
"module_name",
".",
"capitalize",
"(",
")",
"return",
"type",
"(",
"class_name",
",",
"(",
"ModelInline",
",",
")",
",",
"d",
")"
]
| A shortcut function to produce ModelInlines for django models | [
"A",
"shortcut",
"function",
"to",
"produce",
"ModelInlines",
"for",
"django",
"models"
]
| 1912e508d04884713a6c44a068c21fbd217d478a | https://github.com/mintchaos/django_inlines/blob/1912e508d04884713a6c44a068c21fbd217d478a/django_inlines/inlines.py#L68-L81 | train |
openearth/mmi-python | mmi/runner.py | Runner.initialize_mpi | def initialize_mpi(mpi=False):
"""initialize mpi settings"""
if mpi:
import mpi4py.MPI
comm = mpi4py.MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
else:
comm = None
rank = 0
size = 1
return {
"comm": comm,
"rank": rank,
"size": size,
"mode": mpi
} | python | def initialize_mpi(mpi=False):
"""initialize mpi settings"""
if mpi:
import mpi4py.MPI
comm = mpi4py.MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
else:
comm = None
rank = 0
size = 1
return {
"comm": comm,
"rank": rank,
"size": size,
"mode": mpi
} | [
"def",
"initialize_mpi",
"(",
"mpi",
"=",
"False",
")",
":",
"if",
"mpi",
":",
"import",
"mpi4py",
".",
"MPI",
"comm",
"=",
"mpi4py",
".",
"MPI",
".",
"COMM_WORLD",
"rank",
"=",
"comm",
".",
"Get_rank",
"(",
")",
"size",
"=",
"comm",
".",
"Get_size",
"(",
")",
"else",
":",
"comm",
"=",
"None",
"rank",
"=",
"0",
"size",
"=",
"1",
"return",
"{",
"\"comm\"",
":",
"comm",
",",
"\"rank\"",
":",
"rank",
",",
"\"size\"",
":",
"size",
",",
"\"mode\"",
":",
"mpi",
"}"
]
| initialize mpi settings | [
"initialize",
"mpi",
"settings"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L73-L89 | train |
openearth/mmi-python | mmi/runner.py | Runner.create_ports | def create_ports(port, mpi, rank):
"""create a list of ports for the current rank"""
if port == "random" or port is None:
# ports will be filled in using random binding
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
"PUSH": port + 1,
"SUB": port + 2
}
# if we want to communicate with separate domains
# we have to setup a socket for each of them
if mpi == 'all':
# use a socket for each rank rank
for port in ports:
ports[port] += (rank * 3)
return ports | python | def create_ports(port, mpi, rank):
"""create a list of ports for the current rank"""
if port == "random" or port is None:
# ports will be filled in using random binding
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
"PUSH": port + 1,
"SUB": port + 2
}
# if we want to communicate with separate domains
# we have to setup a socket for each of them
if mpi == 'all':
# use a socket for each rank rank
for port in ports:
ports[port] += (rank * 3)
return ports | [
"def",
"create_ports",
"(",
"port",
",",
"mpi",
",",
"rank",
")",
":",
"if",
"port",
"==",
"\"random\"",
"or",
"port",
"is",
"None",
":",
"# ports will be filled in using random binding",
"ports",
"=",
"{",
"}",
"else",
":",
"port",
"=",
"int",
"(",
"port",
")",
"ports",
"=",
"{",
"\"REQ\"",
":",
"port",
"+",
"0",
",",
"\"PUSH\"",
":",
"port",
"+",
"1",
",",
"\"SUB\"",
":",
"port",
"+",
"2",
"}",
"# if we want to communicate with separate domains",
"# we have to setup a socket for each of them",
"if",
"mpi",
"==",
"'all'",
":",
"# use a socket for each rank rank",
"for",
"port",
"in",
"ports",
":",
"ports",
"[",
"port",
"]",
"+=",
"(",
"rank",
"*",
"3",
")",
"return",
"ports"
]
| create a list of ports for the current rank | [
"create",
"a",
"list",
"of",
"ports",
"for",
"the",
"current",
"rank"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L92-L110 | train |
openearth/mmi-python | mmi/runner.py | Runner.import_from_string | def import_from_string(full_class_name):
"""return a class based on it's full class name"""
s = full_class_name.split('.')
class_name = s[-1]
module_name = full_class_name[:-len(class_name)-1]
module = importlib.import_module(module_name)
# the class, it's common to spell with k as class is reserved
klass = getattr(module, class_name)
return klass | python | def import_from_string(full_class_name):
"""return a class based on it's full class name"""
s = full_class_name.split('.')
class_name = s[-1]
module_name = full_class_name[:-len(class_name)-1]
module = importlib.import_module(module_name)
# the class, it's common to spell with k as class is reserved
klass = getattr(module, class_name)
return klass | [
"def",
"import_from_string",
"(",
"full_class_name",
")",
":",
"s",
"=",
"full_class_name",
".",
"split",
"(",
"'.'",
")",
"class_name",
"=",
"s",
"[",
"-",
"1",
"]",
"module_name",
"=",
"full_class_name",
"[",
":",
"-",
"len",
"(",
"class_name",
")",
"-",
"1",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"# the class, it's common to spell with k as class is reserved",
"klass",
"=",
"getattr",
"(",
"module",
",",
"class_name",
")",
"return",
"klass"
]
| return a class based on it's full class name | [
"return",
"a",
"class",
"based",
"on",
"it",
"s",
"full",
"class",
"name"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L113-L121 | train |
openearth/mmi-python | mmi/runner.py | Runner.create_bmi_model | def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class = self.import_from_string(bmi_class)
try:
"""most models use engine as a first argument"""
model = wrapper_class(
engine,
**wrapper_kwargs
)
except TypeError as e:
"""but old python engines are engines, so they don't, but they should """
logger.warn(
'Model wrapper %s does not accept engine as a first argument',
wrapper_class
)
model = wrapper_class(
**wrapper_kwargs
)
return model | python | def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class = self.import_from_string(bmi_class)
try:
"""most models use engine as a first argument"""
model = wrapper_class(
engine,
**wrapper_kwargs
)
except TypeError as e:
"""but old python engines are engines, so they don't, but they should """
logger.warn(
'Model wrapper %s does not accept engine as a first argument',
wrapper_class
)
model = wrapper_class(
**wrapper_kwargs
)
return model | [
"def",
"create_bmi_model",
"(",
"self",
",",
"engine",
",",
"bmi_class",
"=",
"None",
",",
"wrapper_kwargs",
"=",
"None",
")",
":",
"if",
"wrapper_kwargs",
"is",
"None",
":",
"wrapper_kwargs",
"=",
"{",
"}",
"if",
"bmi_class",
"is",
"None",
":",
"wrapper_class",
"=",
"bmi",
".",
"wrapper",
".",
"BMIWrapper",
"else",
":",
"wrapper_class",
"=",
"self",
".",
"import_from_string",
"(",
"bmi_class",
")",
"try",
":",
"\"\"\"most models use engine as a first argument\"\"\"",
"model",
"=",
"wrapper_class",
"(",
"engine",
",",
"*",
"*",
"wrapper_kwargs",
")",
"except",
"TypeError",
"as",
"e",
":",
"\"\"\"but old python engines are engines, so they don't, but they should \"\"\"",
"logger",
".",
"warn",
"(",
"'Model wrapper %s does not accept engine as a first argument'",
",",
"wrapper_class",
")",
"model",
"=",
"wrapper_class",
"(",
"*",
"*",
"wrapper_kwargs",
")",
"return",
"model"
]
| initialize a bmi mode using an optional class | [
"initialize",
"a",
"bmi",
"mode",
"using",
"an",
"optional",
"class"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L123-L146 | train |
openearth/mmi-python | mmi/runner.py | Runner.register | def register(self):
"""register model at tracking server"""
# connect to tracker
result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
logger.debug("registered at server %s: %s", self.tracker, result)
self.metadata["tracker"] = result.json() | python | def register(self):
"""register model at tracking server"""
# connect to tracker
result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
logger.debug("registered at server %s: %s", self.tracker, result)
self.metadata["tracker"] = result.json() | [
"def",
"register",
"(",
"self",
")",
":",
"# connect to tracker",
"result",
"=",
"requests",
".",
"post",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"metadata",
")",
")",
"logger",
".",
"debug",
"(",
"\"registered at server %s: %s\"",
",",
"self",
".",
"tracker",
",",
"result",
")",
"self",
".",
"metadata",
"[",
"\"tracker\"",
"]",
"=",
"result",
".",
"json",
"(",
")"
]
| register model at tracking server | [
"register",
"model",
"at",
"tracking",
"server"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L148-L153 | train |
openearth/mmi-python | mmi/runner.py | Runner.unregister | def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracker, 'models' + "/" + uuid))
logger.debug("unregistered at server %s with %s: %s", self.tracker, uuid, result) | python | def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracker, 'models' + "/" + uuid))
logger.debug("unregistered at server %s with %s: %s", self.tracker, uuid, result) | [
"def",
"unregister",
"(",
"self",
")",
":",
"uuid",
"=",
"self",
".",
"metadata",
"[",
"\"tracker\"",
"]",
"[",
"\"uuid\"",
"]",
"# connect to server",
"result",
"=",
"requests",
".",
"delete",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
"+",
"\"/\"",
"+",
"uuid",
")",
")",
"logger",
".",
"debug",
"(",
"\"unregistered at server %s with %s: %s\"",
",",
"self",
".",
"tracker",
",",
"uuid",
",",
"result",
")"
]
| unregister model at tracking server | [
"unregister",
"model",
"at",
"tracking",
"server"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L155-L160 | train |
openearth/mmi-python | mmi/runner.py | Runner.create_sockets | def create_sockets(self):
"""create zmq sockets"""
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
# Socket to handle init data
rep = context.socket(zmq.REP)
# this was inconsequent: here REQ is for the client, we reply with REP.
# PULL and PUB is seen from here, not from the client.
# Is now renamed to PUSH and SUB: everything is seen from outside.
if "REQ" in ports:
rep.bind(
"tcp://*:{port}".format(port=ports["REQ"])
)
else:
ports["REQ"] = rep.bind_to_random_port(
"tcp://*"
)
pull = context.socket(zmq.PULL)
if "PUSH" in ports:
pull.bind(
"tcp://*:{port}".format(port=ports["PUSH"])
)
else:
ports["PUSH"] = pull.bind_to_random_port(
"tcp://*"
)
# for sending model messages
pub = context.socket(zmq.PUB)
if "SUB" in ports:
pub.bind(
"tcp://*:{port}".format(port=ports["SUB"])
)
else:
ports["SUB"] = pub.bind_to_random_port(
"tcp://*"
)
poller.register(rep, zmq.POLLIN)
poller.register(pull, zmq.POLLIN)
sockets = dict(
poller=poller,
rep=rep,
pull=pull,
pub=pub
)
return sockets | python | def create_sockets(self):
"""create zmq sockets"""
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
# Socket to handle init data
rep = context.socket(zmq.REP)
# this was inconsequent: here REQ is for the client, we reply with REP.
# PULL and PUB is seen from here, not from the client.
# Is now renamed to PUSH and SUB: everything is seen from outside.
if "REQ" in ports:
rep.bind(
"tcp://*:{port}".format(port=ports["REQ"])
)
else:
ports["REQ"] = rep.bind_to_random_port(
"tcp://*"
)
pull = context.socket(zmq.PULL)
if "PUSH" in ports:
pull.bind(
"tcp://*:{port}".format(port=ports["PUSH"])
)
else:
ports["PUSH"] = pull.bind_to_random_port(
"tcp://*"
)
# for sending model messages
pub = context.socket(zmq.PUB)
if "SUB" in ports:
pub.bind(
"tcp://*:{port}".format(port=ports["SUB"])
)
else:
ports["SUB"] = pub.bind_to_random_port(
"tcp://*"
)
poller.register(rep, zmq.POLLIN)
poller.register(pull, zmq.POLLIN)
sockets = dict(
poller=poller,
rep=rep,
pull=pull,
pub=pub
)
return sockets | [
"def",
"create_sockets",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"ports",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"poller",
"=",
"zmq",
".",
"Poller",
"(",
")",
"# Socket to handle init data",
"rep",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"REP",
")",
"# this was inconsequent: here REQ is for the client, we reply with REP.",
"# PULL and PUB is seen from here, not from the client.",
"# Is now renamed to PUSH and SUB: everything is seen from outside.",
"if",
"\"REQ\"",
"in",
"ports",
":",
"rep",
".",
"bind",
"(",
"\"tcp://*:{port}\"",
".",
"format",
"(",
"port",
"=",
"ports",
"[",
"\"REQ\"",
"]",
")",
")",
"else",
":",
"ports",
"[",
"\"REQ\"",
"]",
"=",
"rep",
".",
"bind_to_random_port",
"(",
"\"tcp://*\"",
")",
"pull",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"PULL",
")",
"if",
"\"PUSH\"",
"in",
"ports",
":",
"pull",
".",
"bind",
"(",
"\"tcp://*:{port}\"",
".",
"format",
"(",
"port",
"=",
"ports",
"[",
"\"PUSH\"",
"]",
")",
")",
"else",
":",
"ports",
"[",
"\"PUSH\"",
"]",
"=",
"pull",
".",
"bind_to_random_port",
"(",
"\"tcp://*\"",
")",
"# for sending model messages",
"pub",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"PUB",
")",
"if",
"\"SUB\"",
"in",
"ports",
":",
"pub",
".",
"bind",
"(",
"\"tcp://*:{port}\"",
".",
"format",
"(",
"port",
"=",
"ports",
"[",
"\"SUB\"",
"]",
")",
")",
"else",
":",
"ports",
"[",
"\"SUB\"",
"]",
"=",
"pub",
".",
"bind_to_random_port",
"(",
"\"tcp://*\"",
")",
"poller",
".",
"register",
"(",
"rep",
",",
"zmq",
".",
"POLLIN",
")",
"poller",
".",
"register",
"(",
"pull",
",",
"zmq",
".",
"POLLIN",
")",
"sockets",
"=",
"dict",
"(",
"poller",
"=",
"poller",
",",
"rep",
"=",
"rep",
",",
"pull",
"=",
"pull",
",",
"pub",
"=",
"pub",
")",
"return",
"sockets"
]
| create zmq sockets | [
"create",
"zmq",
"sockets"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L329-L381 | train |
openearth/mmi-python | mmi/runner.py | Runner.run | def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in pause mode, waiting for requests"
)
else:
logger.info("model started and initialized, running")
if self.tracker:
self.register()
atexit.register(self.unregister)
self.process_incoming()
# Keep on counting indefinitely
counter = itertools.count()
logger.info("Entering timeloop...")
for i in counter:
while model.state == "pause":
# keep waiting for messages when paused
# process_incoming should set model.state to play
self.process_incoming()
else:
# otherwise process messages once and continue
self.process_incoming()
if model.state == "quit":
break
# lookup dt or use -1 (default)
dt = model.get_time_step() or -1
model.update(dt)
# check counter, if not a multiple of interval, skip this step
if i % interval:
continue
for key in self.output_vars:
value = model.get_var(key)
metadata = {'name': key, 'iteration': i}
# 4ms for 1M doubles
logger.debug("sending {}".format(metadata))
if 'pub' in sockets:
send_array(sockets['pub'], value, metadata=metadata)
logger.info("Finalizing...")
model.finalize() | python | def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in pause mode, waiting for requests"
)
else:
logger.info("model started and initialized, running")
if self.tracker:
self.register()
atexit.register(self.unregister)
self.process_incoming()
# Keep on counting indefinitely
counter = itertools.count()
logger.info("Entering timeloop...")
for i in counter:
while model.state == "pause":
# keep waiting for messages when paused
# process_incoming should set model.state to play
self.process_incoming()
else:
# otherwise process messages once and continue
self.process_incoming()
if model.state == "quit":
break
# lookup dt or use -1 (default)
dt = model.get_time_step() or -1
model.update(dt)
# check counter, if not a multiple of interval, skip this step
if i % interval:
continue
for key in self.output_vars:
value = model.get_var(key)
metadata = {'name': key, 'iteration': i}
# 4ms for 1M doubles
logger.debug("sending {}".format(metadata))
if 'pub' in sockets:
send_array(sockets['pub'], value, metadata=metadata)
logger.info("Finalizing...")
model.finalize() | [
"def",
"run",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"model",
"configfile",
"=",
"self",
".",
"configfile",
"interval",
"=",
"self",
".",
"interval",
"sockets",
"=",
"self",
".",
"sockets",
"model",
".",
"initialize",
"(",
"configfile",
")",
"if",
"model",
".",
"state",
"==",
"'pause'",
":",
"logger",
".",
"info",
"(",
"\"model initialized and started in pause mode, waiting for requests\"",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"model started and initialized, running\"",
")",
"if",
"self",
".",
"tracker",
":",
"self",
".",
"register",
"(",
")",
"atexit",
".",
"register",
"(",
"self",
".",
"unregister",
")",
"self",
".",
"process_incoming",
"(",
")",
"# Keep on counting indefinitely",
"counter",
"=",
"itertools",
".",
"count",
"(",
")",
"logger",
".",
"info",
"(",
"\"Entering timeloop...\"",
")",
"for",
"i",
"in",
"counter",
":",
"while",
"model",
".",
"state",
"==",
"\"pause\"",
":",
"# keep waiting for messages when paused",
"# process_incoming should set model.state to play",
"self",
".",
"process_incoming",
"(",
")",
"else",
":",
"# otherwise process messages once and continue",
"self",
".",
"process_incoming",
"(",
")",
"if",
"model",
".",
"state",
"==",
"\"quit\"",
":",
"break",
"# lookup dt or use -1 (default)",
"dt",
"=",
"model",
".",
"get_time_step",
"(",
")",
"or",
"-",
"1",
"model",
".",
"update",
"(",
"dt",
")",
"# check counter, if not a multiple of interval, skip this step",
"if",
"i",
"%",
"interval",
":",
"continue",
"for",
"key",
"in",
"self",
".",
"output_vars",
":",
"value",
"=",
"model",
".",
"get_var",
"(",
"key",
")",
"metadata",
"=",
"{",
"'name'",
":",
"key",
",",
"'iteration'",
":",
"i",
"}",
"# 4ms for 1M doubles",
"logger",
".",
"debug",
"(",
"\"sending {}\"",
".",
"format",
"(",
"metadata",
")",
")",
"if",
"'pub'",
"in",
"sockets",
":",
"send_array",
"(",
"sockets",
"[",
"'pub'",
"]",
",",
"value",
",",
"metadata",
"=",
"metadata",
")",
"logger",
".",
"info",
"(",
"\"Finalizing...\"",
")",
"model",
".",
"finalize",
"(",
")"
]
| run the model | [
"run",
"the",
"model"
]
| a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L383-L436 | train |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/calc_building_design.py | calc_basics | def calc_basics(width=-1, length=-1, height=2.4, prevailing_wind=2.8):
"""
calculate various aspects of the structure
"""
if width == -1:
width = int(input('enter building width : '))
if length == -1:
length = int(input('enter building length : '))
res = {}
res['area'] = width * length
res['perim'] = 2 * width + 2 * length
res['roof_cladding'] = res['area']
res['wall_cladding'] = res['perim'] * height
pprint(res)
return res | python | def calc_basics(width=-1, length=-1, height=2.4, prevailing_wind=2.8):
"""
calculate various aspects of the structure
"""
if width == -1:
width = int(input('enter building width : '))
if length == -1:
length = int(input('enter building length : '))
res = {}
res['area'] = width * length
res['perim'] = 2 * width + 2 * length
res['roof_cladding'] = res['area']
res['wall_cladding'] = res['perim'] * height
pprint(res)
return res | [
"def",
"calc_basics",
"(",
"width",
"=",
"-",
"1",
",",
"length",
"=",
"-",
"1",
",",
"height",
"=",
"2.4",
",",
"prevailing_wind",
"=",
"2.8",
")",
":",
"if",
"width",
"==",
"-",
"1",
":",
"width",
"=",
"int",
"(",
"input",
"(",
"'enter building width : '",
")",
")",
"if",
"length",
"==",
"-",
"1",
":",
"length",
"=",
"int",
"(",
"input",
"(",
"'enter building length : '",
")",
")",
"res",
"=",
"{",
"}",
"res",
"[",
"'area'",
"]",
"=",
"width",
"*",
"length",
"res",
"[",
"'perim'",
"]",
"=",
"2",
"*",
"width",
"+",
"2",
"*",
"length",
"res",
"[",
"'roof_cladding'",
"]",
"=",
"res",
"[",
"'area'",
"]",
"res",
"[",
"'wall_cladding'",
"]",
"=",
"res",
"[",
"'perim'",
"]",
"*",
"height",
"pprint",
"(",
"res",
")",
"return",
"res"
]
| calculate various aspects of the structure | [
"calculate",
"various",
"aspects",
"of",
"the",
"structure"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/calc_building_design.py#L29-L44 | train |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/calc_building_design.py | bld_rafter_deflection | def bld_rafter_deflection(length=-9, force=-9, E_mod_elasticity=-9, I_moment_of_intertia=-9):
"""
calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course
"""
if length == -9:
length = float(input('enter rafter length : '))
if force == -9:
force = float(input('enter Force or weight applied to roof : '))
if E_mod_elasticity == -9:
E_mod_elasticity = float(input('enter modulus of elasticity x10**5 (Steel beam example=2.1) : '))
if I_moment_of_intertia == -9:
I_moment_of_intertia = float(input('enter members "moment of intertia x10**6" (for Steel beam 410UB53.7=188 ) :'))
res = {}
res['max deflection - centre load'] = (1 * force * (length ** 3)) / (48 * (E_mod_elasticity * 10**5) * (I_moment_of_intertia * 10**6))
res['max deflection - distrib load'] = (5 * force * (length ** 4)) / (384 * (E_mod_elasticity * 10**5) * (I_moment_of_intertia * 10**6))
pprint(res)
return res | python | def bld_rafter_deflection(length=-9, force=-9, E_mod_elasticity=-9, I_moment_of_intertia=-9):
"""
calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course
"""
if length == -9:
length = float(input('enter rafter length : '))
if force == -9:
force = float(input('enter Force or weight applied to roof : '))
if E_mod_elasticity == -9:
E_mod_elasticity = float(input('enter modulus of elasticity x10**5 (Steel beam example=2.1) : '))
if I_moment_of_intertia == -9:
I_moment_of_intertia = float(input('enter members "moment of intertia x10**6" (for Steel beam 410UB53.7=188 ) :'))
res = {}
res['max deflection - centre load'] = (1 * force * (length ** 3)) / (48 * (E_mod_elasticity * 10**5) * (I_moment_of_intertia * 10**6))
res['max deflection - distrib load'] = (5 * force * (length ** 4)) / (384 * (E_mod_elasticity * 10**5) * (I_moment_of_intertia * 10**6))
pprint(res)
return res | [
"def",
"bld_rafter_deflection",
"(",
"length",
"=",
"-",
"9",
",",
"force",
"=",
"-",
"9",
",",
"E_mod_elasticity",
"=",
"-",
"9",
",",
"I_moment_of_intertia",
"=",
"-",
"9",
")",
":",
"if",
"length",
"==",
"-",
"9",
":",
"length",
"=",
"float",
"(",
"input",
"(",
"'enter rafter length : '",
")",
")",
"if",
"force",
"==",
"-",
"9",
":",
"force",
"=",
"float",
"(",
"input",
"(",
"'enter Force or weight applied to roof : '",
")",
")",
"if",
"E_mod_elasticity",
"==",
"-",
"9",
":",
"E_mod_elasticity",
"=",
"float",
"(",
"input",
"(",
"'enter modulus of elasticity x10**5 (Steel beam example=2.1) : '",
")",
")",
"if",
"I_moment_of_intertia",
"==",
"-",
"9",
":",
"I_moment_of_intertia",
"=",
"float",
"(",
"input",
"(",
"'enter members \"moment of intertia x10**6\" (for Steel beam 410UB53.7=188 ) :'",
")",
")",
"res",
"=",
"{",
"}",
"res",
"[",
"'max deflection - centre load'",
"]",
"=",
"(",
"1",
"*",
"force",
"*",
"(",
"length",
"**",
"3",
")",
")",
"/",
"(",
"48",
"*",
"(",
"E_mod_elasticity",
"*",
"10",
"**",
"5",
")",
"*",
"(",
"I_moment_of_intertia",
"*",
"10",
"**",
"6",
")",
")",
"res",
"[",
"'max deflection - distrib load'",
"]",
"=",
"(",
"5",
"*",
"force",
"*",
"(",
"length",
"**",
"4",
")",
")",
"/",
"(",
"384",
"*",
"(",
"E_mod_elasticity",
"*",
"10",
"**",
"5",
")",
"*",
"(",
"I_moment_of_intertia",
"*",
"10",
"**",
"6",
")",
")",
"pprint",
"(",
"res",
")",
"return",
"res"
]
| calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course | [
"calculate",
"rafter",
"deflections",
"-",
"see",
"test_calc_building_design",
".",
"py",
"for",
"Sample",
"values",
"for",
"equations",
"below",
"from",
"Structures",
"II",
"course"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/calc_building_design.py#L47-L72 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/body.py | BodySerializer.get_parties | def get_parties(self, obj):
"""All parties."""
return PartySerializer(Party.objects.all(), many=True).data | python | def get_parties(self, obj):
"""All parties."""
return PartySerializer(Party.objects.all(), many=True).data | [
"def",
"get_parties",
"(",
"self",
",",
"obj",
")",
":",
"return",
"PartySerializer",
"(",
"Party",
".",
"objects",
".",
"all",
"(",
")",
",",
"many",
"=",
"True",
")",
".",
"data"
]
| All parties. | [
"All",
"parties",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/body.py#L55-L57 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/body.py | BodySerializer.get_elections | def get_elections(self, obj):
"""All elections held on an election day."""
election_day = ElectionDay.objects.get(
date=self.context["election_date"]
)
kwargs = {"race__office__body": obj, "election_day": election_day}
if self.context.get("division") and obj.slug == "senate":
kwargs["division"] = self.context["division"]
elif self.context.get("division") and obj.slug == "house":
kwargs["division__parent"] = self.context["division"]
if obj.slug == "house" and not self.context.get("division"):
kwargs["race__special"] = False
elections = Election.objects.filter(**kwargs)
return ElectionSerializer(elections, many=True).data | python | def get_elections(self, obj):
"""All elections held on an election day."""
election_day = ElectionDay.objects.get(
date=self.context["election_date"]
)
kwargs = {"race__office__body": obj, "election_day": election_day}
if self.context.get("division") and obj.slug == "senate":
kwargs["division"] = self.context["division"]
elif self.context.get("division") and obj.slug == "house":
kwargs["division__parent"] = self.context["division"]
if obj.slug == "house" and not self.context.get("division"):
kwargs["race__special"] = False
elections = Election.objects.filter(**kwargs)
return ElectionSerializer(elections, many=True).data | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"\"election_date\"",
"]",
")",
"kwargs",
"=",
"{",
"\"race__office__body\"",
":",
"obj",
",",
"\"election_day\"",
":",
"election_day",
"}",
"if",
"self",
".",
"context",
".",
"get",
"(",
"\"division\"",
")",
"and",
"obj",
".",
"slug",
"==",
"\"senate\"",
":",
"kwargs",
"[",
"\"division\"",
"]",
"=",
"self",
".",
"context",
"[",
"\"division\"",
"]",
"elif",
"self",
".",
"context",
".",
"get",
"(",
"\"division\"",
")",
"and",
"obj",
".",
"slug",
"==",
"\"house\"",
":",
"kwargs",
"[",
"\"division__parent\"",
"]",
"=",
"self",
".",
"context",
"[",
"\"division\"",
"]",
"if",
"obj",
".",
"slug",
"==",
"\"house\"",
"and",
"not",
"self",
".",
"context",
".",
"get",
"(",
"\"division\"",
")",
":",
"kwargs",
"[",
"\"race__special\"",
"]",
"=",
"False",
"elections",
"=",
"Election",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")",
"return",
"ElectionSerializer",
"(",
"elections",
",",
"many",
"=",
"True",
")",
".",
"data"
]
| All elections held on an election day. | [
"All",
"elections",
"held",
"on",
"an",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/body.py#L59-L75 | train |
jmbeach/KEP.py | src/keppy/project.py | Project.parse_channels | def parse_channels(self):
"""Creates an array of Channel objects from the project"""
channels = []
for channel in self._project_dict["channels"]:
channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list))
return channels | python | def parse_channels(self):
"""Creates an array of Channel objects from the project"""
channels = []
for channel in self._project_dict["channels"]:
channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list))
return channels | [
"def",
"parse_channels",
"(",
"self",
")",
":",
"channels",
"=",
"[",
"]",
"for",
"channel",
"in",
"self",
".",
"_project_dict",
"[",
"\"channels\"",
"]",
":",
"channels",
".",
"append",
"(",
"Channel",
"(",
"channel",
",",
"self",
".",
"_is_sixteen_bit",
",",
"self",
".",
"_ignore_list",
")",
")",
"return",
"channels"
]
| Creates an array of Channel objects from the project | [
"Creates",
"an",
"array",
"of",
"Channel",
"objects",
"from",
"the",
"project"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/project.py#L20-L25 | train |
jmbeach/KEP.py | src/keppy/project.py | Project.update | def update(self):
"""Updates the dictionary of the project"""
for channel in self.channels:
channel.update()
for i in range(len(self._project_dict["channels"])):
channel_dict = self._project_dict["channels"][i]
for channel in self.channels:
if channel.name == channel_dict["common.ALLTYPES_NAME"]:
self._project_dict["channels"][i] = channel.as_dict() | python | def update(self):
"""Updates the dictionary of the project"""
for channel in self.channels:
channel.update()
for i in range(len(self._project_dict["channels"])):
channel_dict = self._project_dict["channels"][i]
for channel in self.channels:
if channel.name == channel_dict["common.ALLTYPES_NAME"]:
self._project_dict["channels"][i] = channel.as_dict() | [
"def",
"update",
"(",
"self",
")",
":",
"for",
"channel",
"in",
"self",
".",
"channels",
":",
"channel",
".",
"update",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_project_dict",
"[",
"\"channels\"",
"]",
")",
")",
":",
"channel_dict",
"=",
"self",
".",
"_project_dict",
"[",
"\"channels\"",
"]",
"[",
"i",
"]",
"for",
"channel",
"in",
"self",
".",
"channels",
":",
"if",
"channel",
".",
"name",
"==",
"channel_dict",
"[",
"\"common.ALLTYPES_NAME\"",
"]",
":",
"self",
".",
"_project_dict",
"[",
"\"channels\"",
"]",
"[",
"i",
"]",
"=",
"channel",
".",
"as_dict",
"(",
")"
]
| Updates the dictionary of the project | [
"Updates",
"the",
"dictionary",
"of",
"the",
"project"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/project.py#L32-L40 | train |
tjcsl/cslbot | cslbot/commands/distro.py | cmd | def cmd(send, *_):
"""Gets a random distro.
Syntax: {command}
"""
url = get('http://distrowatch.com/random.php').url
match = re.search('=(.*)', url)
if match:
send(match.group(1))
else:
send("no distro found") | python | def cmd(send, *_):
"""Gets a random distro.
Syntax: {command}
"""
url = get('http://distrowatch.com/random.php').url
match = re.search('=(.*)', url)
if match:
send(match.group(1))
else:
send("no distro found") | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"url",
"=",
"get",
"(",
"'http://distrowatch.com/random.php'",
")",
".",
"url",
"match",
"=",
"re",
".",
"search",
"(",
"'=(.*)'",
",",
"url",
")",
"if",
"match",
":",
"send",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"send",
"(",
"\"no distro found\"",
")"
]
| Gets a random distro.
Syntax: {command} | [
"Gets",
"a",
"random",
"distro",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/distro.py#L26-L37 | train |
tjcsl/cslbot | cslbot/commands/ddate.py | cmd | def cmd(send, *_):
"""Returns the Discordian date.
Syntax: {command}
"""
try:
output = subprocess.check_output(['ddate'], universal_newlines=True)
except subprocess.CalledProcessError:
output = 'Today is the day you install ddate!'
for line in output.splitlines():
send(line) | python | def cmd(send, *_):
"""Returns the Discordian date.
Syntax: {command}
"""
try:
output = subprocess.check_output(['ddate'], universal_newlines=True)
except subprocess.CalledProcessError:
output = 'Today is the day you install ddate!'
for line in output.splitlines():
send(line) | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ddate'",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"output",
"=",
"'Today is the day you install ddate!'",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"send",
"(",
"line",
")"
]
| Returns the Discordian date.
Syntax: {command} | [
"Returns",
"the",
"Discordian",
"date",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/ddate.py#L24-L35 | train |
tjcsl/cslbot | cslbot/commands/mode.py | cmd | def cmd(send, msg, args):
"""Sets a mode.
Syntax: {command} [--chan <chan>] <mode>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--chan', '--channel', action=arguments.ChanParser)
try:
cmdargs, extra = parser.parse_known_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['target']
mode = " ".join(extra)
if not mode:
send('Please specify a mode.')
elif target == 'private':
send("Modes don't work in a PM!")
else:
with args['handler'].data_lock:
if target not in args['handler'].channels:
send("Bot not in channel %s" % target)
elif args['botnick'] not in args['handler'].opers[target]:
send("Bot must be opped in channel %s" % target)
else:
args['handler'].connection.mode(target, mode)
if args['target'] != args['config']['core']['ctrlchan']:
send("Mode \"%s\" on %s by %s" % (mode, target, args['nick']), target=args['config']['core']['ctrlchan']) | python | def cmd(send, msg, args):
"""Sets a mode.
Syntax: {command} [--chan <chan>] <mode>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--chan', '--channel', action=arguments.ChanParser)
try:
cmdargs, extra = parser.parse_known_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['target']
mode = " ".join(extra)
if not mode:
send('Please specify a mode.')
elif target == 'private':
send("Modes don't work in a PM!")
else:
with args['handler'].data_lock:
if target not in args['handler'].channels:
send("Bot not in channel %s" % target)
elif args['botnick'] not in args['handler'].opers[target]:
send("Bot must be opped in channel %s" % target)
else:
args['handler'].connection.mode(target, mode)
if args['target'] != args['config']['core']['ctrlchan']:
send("Mode \"%s\" on %s by %s" % (mode, target, args['nick']), target=args['config']['core']['ctrlchan']) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--chan'",
",",
"'--channel'",
",",
"action",
"=",
"arguments",
".",
"ChanParser",
")",
"try",
":",
"cmdargs",
",",
"extra",
"=",
"parser",
".",
"parse_known_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"target",
"=",
"cmdargs",
".",
"channels",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"cmdargs",
",",
"'channels'",
")",
"else",
"args",
"[",
"'target'",
"]",
"mode",
"=",
"\" \"",
".",
"join",
"(",
"extra",
")",
"if",
"not",
"mode",
":",
"send",
"(",
"'Please specify a mode.'",
")",
"elif",
"target",
"==",
"'private'",
":",
"send",
"(",
"\"Modes don't work in a PM!\"",
")",
"else",
":",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"if",
"target",
"not",
"in",
"args",
"[",
"'handler'",
"]",
".",
"channels",
":",
"send",
"(",
"\"Bot not in channel %s\"",
"%",
"target",
")",
"elif",
"args",
"[",
"'botnick'",
"]",
"not",
"in",
"args",
"[",
"'handler'",
"]",
".",
"opers",
"[",
"target",
"]",
":",
"send",
"(",
"\"Bot must be opped in channel %s\"",
"%",
"target",
")",
"else",
":",
"args",
"[",
"'handler'",
"]",
".",
"connection",
".",
"mode",
"(",
"target",
",",
"mode",
")",
"if",
"args",
"[",
"'target'",
"]",
"!=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
":",
"send",
"(",
"\"Mode \\\"%s\\\" on %s by %s\"",
"%",
"(",
"mode",
",",
"target",
",",
"args",
"[",
"'nick'",
"]",
")",
",",
"target",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
")"
]
| Sets a mode.
Syntax: {command} [--chan <chan>] <mode> | [
"Sets",
"a",
"mode",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/mode.py#L23-L51 | train |
davisagli/eye | eye/views.py | as_json | def as_json(context):
"""Return an object's representation as JSON"""
info = {
'info': cgi.escape(pprint.pformat(context.context)),
}
return Response(content_type='application/json', body=json.dumps(info)) | python | def as_json(context):
"""Return an object's representation as JSON"""
info = {
'info': cgi.escape(pprint.pformat(context.context)),
}
return Response(content_type='application/json', body=json.dumps(info)) | [
"def",
"as_json",
"(",
"context",
")",
":",
"info",
"=",
"{",
"'info'",
":",
"cgi",
".",
"escape",
"(",
"pprint",
".",
"pformat",
"(",
"context",
".",
"context",
")",
")",
",",
"}",
"return",
"Response",
"(",
"content_type",
"=",
"'application/json'",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"info",
")",
")"
]
| Return an object's representation as JSON | [
"Return",
"an",
"object",
"s",
"representation",
"as",
"JSON"
]
| 4007b6b490ac667c8423c6cc789b303e93f9d03d | https://github.com/davisagli/eye/blob/4007b6b490ac667c8423c6cc789b303e93f9d03d/eye/views.py#L8-L13 | train |
davisagli/eye | eye/views.py | as_tree | def as_tree(context):
"""Return info about an object's members as JSON"""
tree = _build_tree(context, 2, 1)
if type(tree) == dict:
tree = [tree]
return Response(content_type='application/json', body=json.dumps(tree)) | python | def as_tree(context):
"""Return info about an object's members as JSON"""
tree = _build_tree(context, 2, 1)
if type(tree) == dict:
tree = [tree]
return Response(content_type='application/json', body=json.dumps(tree)) | [
"def",
"as_tree",
"(",
"context",
")",
":",
"tree",
"=",
"_build_tree",
"(",
"context",
",",
"2",
",",
"1",
")",
"if",
"type",
"(",
"tree",
")",
"==",
"dict",
":",
"tree",
"=",
"[",
"tree",
"]",
"return",
"Response",
"(",
"content_type",
"=",
"'application/json'",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"tree",
")",
")"
]
| Return info about an object's members as JSON | [
"Return",
"info",
"about",
"an",
"object",
"s",
"members",
"as",
"JSON"
]
| 4007b6b490ac667c8423c6cc789b303e93f9d03d | https://github.com/davisagli/eye/blob/4007b6b490ac667c8423c6cc789b303e93f9d03d/eye/views.py#L16-L23 | train |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/game_rpg_simulation1.py | main | def main():
"""
Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another players
character
character
stats
world
locations
"""
character1 = Character('Albogh', str=4,int=7,sta=50)
character2 = Character('Zoltor', str=6,int=6,sta=70)
print('PLAYER1 [start]:', character1)
print('PLAYER2 [start]:', character2)
b = Battle(character1, character2)
print(b)
print('PLAYER1 [end]:', character1)
print('PLAYER2 [end]:', character2) | python | def main():
"""
Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another players
character
character
stats
world
locations
"""
character1 = Character('Albogh', str=4,int=7,sta=50)
character2 = Character('Zoltor', str=6,int=6,sta=70)
print('PLAYER1 [start]:', character1)
print('PLAYER2 [start]:', character2)
b = Battle(character1, character2)
print(b)
print('PLAYER1 [end]:', character1)
print('PLAYER2 [end]:', character2) | [
"def",
"main",
"(",
")",
":",
"character1",
"=",
"Character",
"(",
"'Albogh'",
",",
"str",
"=",
"4",
",",
"int",
"=",
"7",
",",
"sta",
"=",
"50",
")",
"character2",
"=",
"Character",
"(",
"'Zoltor'",
",",
"str",
"=",
"6",
",",
"int",
"=",
"6",
",",
"sta",
"=",
"70",
")",
"print",
"(",
"'PLAYER1 [start]:'",
",",
"character1",
")",
"print",
"(",
"'PLAYER2 [start]:'",
",",
"character2",
")",
"b",
"=",
"Battle",
"(",
"character1",
",",
"character2",
")",
"print",
"(",
"b",
")",
"print",
"(",
"'PLAYER1 [end]:'",
",",
"character1",
")",
"print",
"(",
"'PLAYER2 [end]:'",
",",
"character2",
")"
]
| Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another players
character
character
stats
world
locations | [
"Prototype",
"to",
"see",
"how",
"an",
"RPG",
"simulation",
"might",
"be",
"used",
"in",
"the",
"AIKIF",
"framework",
".",
"The",
"idea",
"is",
"to",
"build",
"a",
"simple",
"character",
"and",
"run",
"a",
"simulation",
"to",
"see",
"how",
"it",
"succeeds",
"in",
"a",
"random",
"world",
"against",
"another",
"players",
"character",
"character",
"stats",
"world",
"locations"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/game_rpg_simulation1.py#L7-L28 | train |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/game_rpg_simulation1.py | Battle.fight | def fight(self, moves=10):
"""
runs a series of fights
"""
for i in range(1, moves):
# player 1
result, dmg = self.calc_move(self.c1, self.c2)
print (self.c1.name + ' ' + result + ' for ' + str(dmg))
self.c1.sta = self.c1.sta - dmg
if self.is_character_dead(self.c1):
print(self.c1.name + ' has died')
return
# player 2
result, dmg = self.calc_move(self.c2, self.c1)
print (self.c2.name + ' ' + result + ' for ' + str(dmg))
self.c2.sta = self.c2.sta - dmg
if self.is_character_dead(self.c2):
print(self.c2.name + ' has died')
return | python | def fight(self, moves=10):
"""
runs a series of fights
"""
for i in range(1, moves):
# player 1
result, dmg = self.calc_move(self.c1, self.c2)
print (self.c1.name + ' ' + result + ' for ' + str(dmg))
self.c1.sta = self.c1.sta - dmg
if self.is_character_dead(self.c1):
print(self.c1.name + ' has died')
return
# player 2
result, dmg = self.calc_move(self.c2, self.c1)
print (self.c2.name + ' ' + result + ' for ' + str(dmg))
self.c2.sta = self.c2.sta - dmg
if self.is_character_dead(self.c2):
print(self.c2.name + ' has died')
return | [
"def",
"fight",
"(",
"self",
",",
"moves",
"=",
"10",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"moves",
")",
":",
"# player 1",
"result",
",",
"dmg",
"=",
"self",
".",
"calc_move",
"(",
"self",
".",
"c1",
",",
"self",
".",
"c2",
")",
"print",
"(",
"self",
".",
"c1",
".",
"name",
"+",
"' '",
"+",
"result",
"+",
"' for '",
"+",
"str",
"(",
"dmg",
")",
")",
"self",
".",
"c1",
".",
"sta",
"=",
"self",
".",
"c1",
".",
"sta",
"-",
"dmg",
"if",
"self",
".",
"is_character_dead",
"(",
"self",
".",
"c1",
")",
":",
"print",
"(",
"self",
".",
"c1",
".",
"name",
"+",
"' has died'",
")",
"return",
"# player 2",
"result",
",",
"dmg",
"=",
"self",
".",
"calc_move",
"(",
"self",
".",
"c2",
",",
"self",
".",
"c1",
")",
"print",
"(",
"self",
".",
"c2",
".",
"name",
"+",
"' '",
"+",
"result",
"+",
"' for '",
"+",
"str",
"(",
"dmg",
")",
")",
"self",
".",
"c2",
".",
"sta",
"=",
"self",
".",
"c2",
".",
"sta",
"-",
"dmg",
"if",
"self",
".",
"is_character_dead",
"(",
"self",
".",
"c2",
")",
":",
"print",
"(",
"self",
".",
"c2",
".",
"name",
"+",
"' has died'",
")",
"return"
]
| runs a series of fights | [
"runs",
"a",
"series",
"of",
"fights"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/game_rpg_simulation1.py#L72-L90 | train |
ktdreyer/txkoji | txkoji/build.py | Build.duration | def duration(self):
"""
Return a timedelta for this build.
Measure the time between this build's start and end time, or "now"
if the build has not yet finished.
:returns: timedelta object
"""
if self.completion_ts:
end = self.completed
else:
end = datetime.utcnow()
return end - self.started | python | def duration(self):
"""
Return a timedelta for this build.
Measure the time between this build's start and end time, or "now"
if the build has not yet finished.
:returns: timedelta object
"""
if self.completion_ts:
end = self.completed
else:
end = datetime.utcnow()
return end - self.started | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"completion_ts",
":",
"end",
"=",
"self",
".",
"completed",
"else",
":",
"end",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"end",
"-",
"self",
".",
"started"
]
| Return a timedelta for this build.
Measure the time between this build's start and end time, or "now"
if the build has not yet finished.
:returns: timedelta object | [
"Return",
"a",
"timedelta",
"for",
"this",
"build",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/build.py#L32-L45 | train |
ktdreyer/txkoji | txkoji/build.py | Build.estimate_completion | def estimate_completion(self):
"""
Estimate completion time for a build.
This calls getAverageBuildDuration on the hub for this package. This
value is a very rough guess, an average for all completed builds in the
system.
For now this is better than nothing, but I'm recording a few thoughts
here for posterity:
A more advanced implementation of for estimating build times would
track unique averages per build target. Early releases of Ceph "Hammer"
versions would build much more quickly than newer Ceph releases like
"Mimic", and the current method simply averages all of them.
Also, different Koji build targets can have different arches. When we
build ceph in "newarch" side tags, those build times are wildly beyond
the average, but they influence this average too, subtly throwing it
off for the x86-only builds that I care about.
:returns: deferred that when fired returns a datetime object for the
estimated or actual datetime.
"""
if self.state != build_states.BUILDING:
# Build is already complete. Return the exact completion time:
defer.returnValue(self.completed)
avg_delta = yield self.connection.getAverageBuildDuration(self.name)
est_completion = self.started + avg_delta
defer.returnValue(est_completion) | python | def estimate_completion(self):
"""
Estimate completion time for a build.
This calls getAverageBuildDuration on the hub for this package. This
value is a very rough guess, an average for all completed builds in the
system.
For now this is better than nothing, but I'm recording a few thoughts
here for posterity:
A more advanced implementation of for estimating build times would
track unique averages per build target. Early releases of Ceph "Hammer"
versions would build much more quickly than newer Ceph releases like
"Mimic", and the current method simply averages all of them.
Also, different Koji build targets can have different arches. When we
build ceph in "newarch" side tags, those build times are wildly beyond
the average, but they influence this average too, subtly throwing it
off for the x86-only builds that I care about.
:returns: deferred that when fired returns a datetime object for the
estimated or actual datetime.
"""
if self.state != build_states.BUILDING:
# Build is already complete. Return the exact completion time:
defer.returnValue(self.completed)
avg_delta = yield self.connection.getAverageBuildDuration(self.name)
est_completion = self.started + avg_delta
defer.returnValue(est_completion) | [
"def",
"estimate_completion",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"!=",
"build_states",
".",
"BUILDING",
":",
"# Build is already complete. Return the exact completion time:",
"defer",
".",
"returnValue",
"(",
"self",
".",
"completed",
")",
"avg_delta",
"=",
"yield",
"self",
".",
"connection",
".",
"getAverageBuildDuration",
"(",
"self",
".",
"name",
")",
"est_completion",
"=",
"self",
".",
"started",
"+",
"avg_delta",
"defer",
".",
"returnValue",
"(",
"est_completion",
")"
]
| Estimate completion time for a build.
This calls getAverageBuildDuration on the hub for this package. This
value is a very rough guess, an average for all completed builds in the
system.
For now this is better than nothing, but I'm recording a few thoughts
here for posterity:
A more advanced implementation of for estimating build times would
track unique averages per build target. Early releases of Ceph "Hammer"
versions would build much more quickly than newer Ceph releases like
"Mimic", and the current method simply averages all of them.
Also, different Koji build targets can have different arches. When we
build ceph in "newarch" side tags, those build times are wildly beyond
the average, but they influence this average too, subtly throwing it
off for the x86-only builds that I care about.
:returns: deferred that when fired returns a datetime object for the
estimated or actual datetime. | [
"Estimate",
"completion",
"time",
"for",
"a",
"build",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/build.py#L59-L88 | train |
ktdreyer/txkoji | txkoji/build.py | Build.target | def target(self):
"""
Find the target name for this build.
:returns: deferred that when fired returns the build task's target
name. If we could not determine the build task, or the task's
target, return None.
"""
task = yield self.task()
if not task:
yield defer.succeed(None)
defer.returnValue(None)
defer.returnValue(task.target) | python | def target(self):
"""
Find the target name for this build.
:returns: deferred that when fired returns the build task's target
name. If we could not determine the build task, or the task's
target, return None.
"""
task = yield self.task()
if not task:
yield defer.succeed(None)
defer.returnValue(None)
defer.returnValue(task.target) | [
"def",
"target",
"(",
"self",
")",
":",
"task",
"=",
"yield",
"self",
".",
"task",
"(",
")",
"if",
"not",
"task",
":",
"yield",
"defer",
".",
"succeed",
"(",
"None",
")",
"defer",
".",
"returnValue",
"(",
"None",
")",
"defer",
".",
"returnValue",
"(",
"task",
".",
"target",
")"
]
| Find the target name for this build.
:returns: deferred that when fired returns the build task's target
name. If we could not determine the build task, or the task's
target, return None. | [
"Find",
"the",
"target",
"name",
"for",
"this",
"build",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/build.py#L118-L130 | train |
ktdreyer/txkoji | txkoji/build.py | Build.task | def task(self):
"""
Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build.
"""
# If we have no .task_id, this is a no-op to return None.
if not self.task_id:
return defer.succeed(None)
return self.connection.getTaskInfo(self.task_id) | python | def task(self):
"""
Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build.
"""
# If we have no .task_id, this is a no-op to return None.
if not self.task_id:
return defer.succeed(None)
return self.connection.getTaskInfo(self.task_id) | [
"def",
"task",
"(",
"self",
")",
":",
"# If we have no .task_id, this is a no-op to return None.",
"if",
"not",
"self",
".",
"task_id",
":",
"return",
"defer",
".",
"succeed",
"(",
"None",
")",
"return",
"self",
".",
"connection",
".",
"getTaskInfo",
"(",
"self",
".",
"task_id",
")"
]
| Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build. | [
"Find",
"the",
"task",
"for",
"this",
"build",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/build.py#L132-L144 | train |
ktdreyer/txkoji | txkoji/build.py | Build.task_id | def task_id(self):
"""
Hack to return a task ID for a build, including container CG builds.
We have something for this in Brewweb, but not yet for upstream Koji:
https://pagure.io/koji/issue/215
"""
if self['task_id']:
return self['task_id']
if self.extra and 'container_koji_task_id' in self.extra:
return self.extra['container_koji_task_id'] | python | def task_id(self):
"""
Hack to return a task ID for a build, including container CG builds.
We have something for this in Brewweb, but not yet for upstream Koji:
https://pagure.io/koji/issue/215
"""
if self['task_id']:
return self['task_id']
if self.extra and 'container_koji_task_id' in self.extra:
return self.extra['container_koji_task_id'] | [
"def",
"task_id",
"(",
"self",
")",
":",
"if",
"self",
"[",
"'task_id'",
"]",
":",
"return",
"self",
"[",
"'task_id'",
"]",
"if",
"self",
".",
"extra",
"and",
"'container_koji_task_id'",
"in",
"self",
".",
"extra",
":",
"return",
"self",
".",
"extra",
"[",
"'container_koji_task_id'",
"]"
]
| Hack to return a task ID for a build, including container CG builds.
We have something for this in Brewweb, but not yet for upstream Koji:
https://pagure.io/koji/issue/215 | [
"Hack",
"to",
"return",
"a",
"task",
"ID",
"for",
"a",
"build",
"including",
"container",
"CG",
"builds",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/build.py#L147-L157 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election.py | PersonSerializer.get_images | def get_images(self, obj):
"""Object of images serialized by tag name."""
return {str(i.tag): i.image.url for i in obj.images.all()} | python | def get_images(self, obj):
"""Object of images serialized by tag name."""
return {str(i.tag): i.image.url for i in obj.images.all()} | [
"def",
"get_images",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"str",
"(",
"i",
".",
"tag",
")",
":",
"i",
".",
"image",
".",
"url",
"for",
"i",
"in",
"obj",
".",
"images",
".",
"all",
"(",
")",
"}"
]
| Object of images serialized by tag name. | [
"Object",
"of",
"images",
"serialized",
"by",
"tag",
"name",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election.py#L102-L104 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election.py | CandidateElectionSerializer.get_override_winner | def get_override_winner(self, obj):
"""Winner marked in backend."""
if obj.election.division.level.name == DivisionLevel.DISTRICT:
division = obj.election.division.parent
else:
division = obj.election.division
vote = obj.votes.filter(division=division).first()
return vote.winning if vote else False | python | def get_override_winner(self, obj):
"""Winner marked in backend."""
if obj.election.division.level.name == DivisionLevel.DISTRICT:
division = obj.election.division.parent
else:
division = obj.election.division
vote = obj.votes.filter(division=division).first()
return vote.winning if vote else False | [
"def",
"get_override_winner",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"election",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"division",
"=",
"obj",
".",
"election",
".",
"division",
".",
"parent",
"else",
":",
"division",
"=",
"obj",
".",
"election",
".",
"division",
"vote",
"=",
"obj",
".",
"votes",
".",
"filter",
"(",
"division",
"=",
"division",
")",
".",
"first",
"(",
")",
"return",
"vote",
".",
"winning",
"if",
"vote",
"else",
"False"
]
| Winner marked in backend. | [
"Winner",
"marked",
"in",
"backend",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election.py#L128-L136 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election.py | ElectionSerializer.get_override_votes | def get_override_votes(self, obj):
"""
Votes entered into backend.
Only used if ``override_ap_votes = True``.
"""
if hasattr(obj, "meta"): # TODO: REVISIT THIS
if obj.meta.override_ap_votes:
all_votes = None
for ce in obj.candidate_elections.all():
if all_votes:
all_votes = all_votes | ce.votes.all()
else:
all_votes = ce.votes.all()
return VotesSerializer(all_votes, many=True).data
return False | python | def get_override_votes(self, obj):
"""
Votes entered into backend.
Only used if ``override_ap_votes = True``.
"""
if hasattr(obj, "meta"): # TODO: REVISIT THIS
if obj.meta.override_ap_votes:
all_votes = None
for ce in obj.candidate_elections.all():
if all_votes:
all_votes = all_votes | ce.votes.all()
else:
all_votes = ce.votes.all()
return VotesSerializer(all_votes, many=True).data
return False | [
"def",
"get_override_votes",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"meta\"",
")",
":",
"# TODO: REVISIT THIS",
"if",
"obj",
".",
"meta",
".",
"override_ap_votes",
":",
"all_votes",
"=",
"None",
"for",
"ce",
"in",
"obj",
".",
"candidate_elections",
".",
"all",
"(",
")",
":",
"if",
"all_votes",
":",
"all_votes",
"=",
"all_votes",
"|",
"ce",
".",
"votes",
".",
"all",
"(",
")",
"else",
":",
"all_votes",
"=",
"ce",
".",
"votes",
".",
"all",
"(",
")",
"return",
"VotesSerializer",
"(",
"all_votes",
",",
"many",
"=",
"True",
")",
".",
"data",
"return",
"False"
]
| Votes entered into backend.
Only used if ``override_ap_votes = True``. | [
"Votes",
"entered",
"into",
"backend",
".",
"Only",
"used",
"if",
"override_ap_votes",
"=",
"True",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election.py#L191-L205 | train |
mfcovington/djangocms-lab-carousel | cms_lab_carousel/models.py | Slide.save | def save(self, *args, **kwargs):
"""
Before saving, if slide is for a publication, use publication info
for slide's title, subtitle, description.
"""
if self.publication:
publication = self.publication
if not self.title:
self.title = publication.title
if not self.subtitle:
first_author = publication.first_author
if first_author == publication.last_author:
authors = first_author
else:
authors = '{} et al.'.format(first_author)
self.subtitle = '{}, {} ({})'.format(authors,
publication.journal, publication.year)
if not self.description:
self.description = publication.abstract
if self.publication.year and not self.pk:
delta = timezone.now() - self.publish_datetime
if self.publish_datetime <= timezone.now() and delta.days == 0:
self.publish_datetime = datetime.datetime(
year=int(self.publication.year),
month=int(self.publication.month or 1),
day=int(self.publication.day or 1),
)
super().save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Before saving, if slide is for a publication, use publication info
for slide's title, subtitle, description.
"""
if self.publication:
publication = self.publication
if not self.title:
self.title = publication.title
if not self.subtitle:
first_author = publication.first_author
if first_author == publication.last_author:
authors = first_author
else:
authors = '{} et al.'.format(first_author)
self.subtitle = '{}, {} ({})'.format(authors,
publication.journal, publication.year)
if not self.description:
self.description = publication.abstract
if self.publication.year and not self.pk:
delta = timezone.now() - self.publish_datetime
if self.publish_datetime <= timezone.now() and delta.days == 0:
self.publish_datetime = datetime.datetime(
year=int(self.publication.year),
month=int(self.publication.month or 1),
day=int(self.publication.day or 1),
)
super().save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"publication",
":",
"publication",
"=",
"self",
".",
"publication",
"if",
"not",
"self",
".",
"title",
":",
"self",
".",
"title",
"=",
"publication",
".",
"title",
"if",
"not",
"self",
".",
"subtitle",
":",
"first_author",
"=",
"publication",
".",
"first_author",
"if",
"first_author",
"==",
"publication",
".",
"last_author",
":",
"authors",
"=",
"first_author",
"else",
":",
"authors",
"=",
"'{} et al.'",
".",
"format",
"(",
"first_author",
")",
"self",
".",
"subtitle",
"=",
"'{}, {} ({})'",
".",
"format",
"(",
"authors",
",",
"publication",
".",
"journal",
",",
"publication",
".",
"year",
")",
"if",
"not",
"self",
".",
"description",
":",
"self",
".",
"description",
"=",
"publication",
".",
"abstract",
"if",
"self",
".",
"publication",
".",
"year",
"and",
"not",
"self",
".",
"pk",
":",
"delta",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"self",
".",
"publish_datetime",
"if",
"self",
".",
"publish_datetime",
"<=",
"timezone",
".",
"now",
"(",
")",
"and",
"delta",
".",
"days",
"==",
"0",
":",
"self",
".",
"publish_datetime",
"=",
"datetime",
".",
"datetime",
"(",
"year",
"=",
"int",
"(",
"self",
".",
"publication",
".",
"year",
")",
",",
"month",
"=",
"int",
"(",
"self",
".",
"publication",
".",
"month",
"or",
"1",
")",
",",
"day",
"=",
"int",
"(",
"self",
".",
"publication",
".",
"day",
"or",
"1",
")",
",",
")",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Before saving, if slide is for a publication, use publication info
for slide's title, subtitle, description. | [
"Before",
"saving",
"if",
"slide",
"is",
"for",
"a",
"publication",
"use",
"publication",
"info",
"for",
"slide",
"s",
"title",
"subtitle",
"description",
"."
]
| 1f8e43df3d20cd28f090d0c2b780ad01705db41f | https://github.com/mfcovington/djangocms-lab-carousel/blob/1f8e43df3d20cd28f090d0c2b780ad01705db41f/cms_lab_carousel/models.py#L238-L273 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner.execute | def execute(self, context=None, stdout=None, stderr=None):
"""Does all the work of running an example.
This includes:
- building up the context.
- capturing stdout & stderr
- execute before functions
- run example, catching any exceptions
- execute after functions
- record the results & timings to formatter and original example object
"""
total_benchmark = Benchmark()
self.context = context or Context()
if self._is_collection():
self.stdout = sys.stdout
self.stderr = sys.stderr
else:
self.stdout = stdout or StringIO()
self.stderr = stderr or StringIO()
self._record_start_example(self.formatter)
try:
with total_benchmark, Replace(sys, 'stdout', self.stdout), Replace(sys, 'stderr', self.stderr):
self._setup()
self._execute()
self._teardown()
except Exception as e:
self.example.error = e
self.example.traceback = sys.exc_info()[2] #traceback.format_exc()
finally:
self.example.real_time = total_benchmark.total_time
self._record_end_example(self.formatter)
self.context = None
self.example.stdout = self.stdout
self.example.stderr = self.stderr
return self.example.error is None | python | def execute(self, context=None, stdout=None, stderr=None):
"""Does all the work of running an example.
This includes:
- building up the context.
- capturing stdout & stderr
- execute before functions
- run example, catching any exceptions
- execute after functions
- record the results & timings to formatter and original example object
"""
total_benchmark = Benchmark()
self.context = context or Context()
if self._is_collection():
self.stdout = sys.stdout
self.stderr = sys.stderr
else:
self.stdout = stdout or StringIO()
self.stderr = stderr or StringIO()
self._record_start_example(self.formatter)
try:
with total_benchmark, Replace(sys, 'stdout', self.stdout), Replace(sys, 'stderr', self.stderr):
self._setup()
self._execute()
self._teardown()
except Exception as e:
self.example.error = e
self.example.traceback = sys.exc_info()[2] #traceback.format_exc()
finally:
self.example.real_time = total_benchmark.total_time
self._record_end_example(self.formatter)
self.context = None
self.example.stdout = self.stdout
self.example.stderr = self.stderr
return self.example.error is None | [
"def",
"execute",
"(",
"self",
",",
"context",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"total_benchmark",
"=",
"Benchmark",
"(",
")",
"self",
".",
"context",
"=",
"context",
"or",
"Context",
"(",
")",
"if",
"self",
".",
"_is_collection",
"(",
")",
":",
"self",
".",
"stdout",
"=",
"sys",
".",
"stdout",
"self",
".",
"stderr",
"=",
"sys",
".",
"stderr",
"else",
":",
"self",
".",
"stdout",
"=",
"stdout",
"or",
"StringIO",
"(",
")",
"self",
".",
"stderr",
"=",
"stderr",
"or",
"StringIO",
"(",
")",
"self",
".",
"_record_start_example",
"(",
"self",
".",
"formatter",
")",
"try",
":",
"with",
"total_benchmark",
",",
"Replace",
"(",
"sys",
",",
"'stdout'",
",",
"self",
".",
"stdout",
")",
",",
"Replace",
"(",
"sys",
",",
"'stderr'",
",",
"self",
".",
"stderr",
")",
":",
"self",
".",
"_setup",
"(",
")",
"self",
".",
"_execute",
"(",
")",
"self",
".",
"_teardown",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"example",
".",
"error",
"=",
"e",
"self",
".",
"example",
".",
"traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"#traceback.format_exc()",
"finally",
":",
"self",
".",
"example",
".",
"real_time",
"=",
"total_benchmark",
".",
"total_time",
"self",
".",
"_record_end_example",
"(",
"self",
".",
"formatter",
")",
"self",
".",
"context",
"=",
"None",
"self",
".",
"example",
".",
"stdout",
"=",
"self",
".",
"stdout",
"self",
".",
"example",
".",
"stderr",
"=",
"self",
".",
"stderr",
"return",
"self",
".",
"example",
".",
"error",
"is",
"None"
]
| Does all the work of running an example.
This includes:
- building up the context.
- capturing stdout & stderr
- execute before functions
- run example, catching any exceptions
- execute after functions
- record the results & timings to formatter and original example object | [
"Does",
"all",
"the",
"work",
"of",
"running",
"an",
"example",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L30-L64 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner.run | def run(self, context=None, stdout=None, stderr=None):
"Like execute, but records a skip if the should_skip method returns True."
if self.should_skip():
self._record_skipped_example(self.formatter)
self.num_skipped += 1
else:
self.execute(context, stdout, stderr)
return self.num_successes, self.num_failures, self.num_skipped | python | def run(self, context=None, stdout=None, stderr=None):
"Like execute, but records a skip if the should_skip method returns True."
if self.should_skip():
self._record_skipped_example(self.formatter)
self.num_skipped += 1
else:
self.execute(context, stdout, stderr)
return self.num_successes, self.num_failures, self.num_skipped | [
"def",
"run",
"(",
"self",
",",
"context",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"if",
"self",
".",
"should_skip",
"(",
")",
":",
"self",
".",
"_record_skipped_example",
"(",
"self",
".",
"formatter",
")",
"self",
".",
"num_skipped",
"+=",
"1",
"else",
":",
"self",
".",
"execute",
"(",
"context",
",",
"stdout",
",",
"stderr",
")",
"return",
"self",
".",
"num_successes",
",",
"self",
".",
"num_failures",
",",
"self",
".",
"num_skipped"
]
| Like execute, but records a skip if the should_skip method returns True. | [
"Like",
"execute",
"but",
"records",
"a",
"skip",
"if",
"the",
"should_skip",
"method",
"returns",
"True",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L66-L73 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner._setup | def _setup(self):
"Resets the state and prepares for running the example."
self.example.error = None
self.example.traceback = ''
# inject function contexts from parent functions
c = Context(parent=self.context)
#for parent in reversed(self.example.parents):
# c._update_properties(locals_from_function(parent))
self.context = c
if self.is_root_runner:
run.before_all.execute(self.context)
self.example.before(self.context) | python | def _setup(self):
"Resets the state and prepares for running the example."
self.example.error = None
self.example.traceback = ''
# inject function contexts from parent functions
c = Context(parent=self.context)
#for parent in reversed(self.example.parents):
# c._update_properties(locals_from_function(parent))
self.context = c
if self.is_root_runner:
run.before_all.execute(self.context)
self.example.before(self.context) | [
"def",
"_setup",
"(",
"self",
")",
":",
"self",
".",
"example",
".",
"error",
"=",
"None",
"self",
".",
"example",
".",
"traceback",
"=",
"''",
"# inject function contexts from parent functions",
"c",
"=",
"Context",
"(",
"parent",
"=",
"self",
".",
"context",
")",
"#for parent in reversed(self.example.parents):",
"# c._update_properties(locals_from_function(parent))",
"self",
".",
"context",
"=",
"c",
"if",
"self",
".",
"is_root_runner",
":",
"run",
".",
"before_all",
".",
"execute",
"(",
"self",
".",
"context",
")",
"self",
".",
"example",
".",
"before",
"(",
"self",
".",
"context",
")"
]
| Resets the state and prepares for running the example. | [
"Resets",
"the",
"state",
"and",
"prepares",
"for",
"running",
"the",
"example",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L76-L87 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner._execute_example_group | def _execute_example_group(self):
"Handles the execution of Example Group"
for example in self.example:
runner = self.__class__(example, self.formatter)
runner.is_root_runner = False
successes, failures, skipped = runner.run(self.context)
self.num_successes += successes
self.num_failures += failures
self.num_skipped += skipped | python | def _execute_example_group(self):
"Handles the execution of Example Group"
for example in self.example:
runner = self.__class__(example, self.formatter)
runner.is_root_runner = False
successes, failures, skipped = runner.run(self.context)
self.num_successes += successes
self.num_failures += failures
self.num_skipped += skipped | [
"def",
"_execute_example_group",
"(",
"self",
")",
":",
"for",
"example",
"in",
"self",
".",
"example",
":",
"runner",
"=",
"self",
".",
"__class__",
"(",
"example",
",",
"self",
".",
"formatter",
")",
"runner",
".",
"is_root_runner",
"=",
"False",
"successes",
",",
"failures",
",",
"skipped",
"=",
"runner",
".",
"run",
"(",
"self",
".",
"context",
")",
"self",
".",
"num_successes",
"+=",
"successes",
"self",
".",
"num_failures",
"+=",
"failures",
"self",
".",
"num_skipped",
"+=",
"skipped"
]
| Handles the execution of Example Group | [
"Handles",
"the",
"execution",
"of",
"Example",
"Group"
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L110-L118 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner._execute_example | def _execute_example(self):
"Handles the execution of the Example"
test_benchmark = Benchmark()
try:
with Registry(), test_benchmark:
if accepts_arg(self.example.testfn):
self.example.testfn(self.context)
else:
self.context.inject_into_self(self.example.testfn)
self.example.testfn()
self.num_successes += 1
except KeyboardInterrupt:
# bubble interrupt for canceling spec execution
raise
except:
raise
self.num_failures += 1
finally:
self.example.user_time = test_benchmark.total_time | python | def _execute_example(self):
"Handles the execution of the Example"
test_benchmark = Benchmark()
try:
with Registry(), test_benchmark:
if accepts_arg(self.example.testfn):
self.example.testfn(self.context)
else:
self.context.inject_into_self(self.example.testfn)
self.example.testfn()
self.num_successes += 1
except KeyboardInterrupt:
# bubble interrupt for canceling spec execution
raise
except:
raise
self.num_failures += 1
finally:
self.example.user_time = test_benchmark.total_time | [
"def",
"_execute_example",
"(",
"self",
")",
":",
"test_benchmark",
"=",
"Benchmark",
"(",
")",
"try",
":",
"with",
"Registry",
"(",
")",
",",
"test_benchmark",
":",
"if",
"accepts_arg",
"(",
"self",
".",
"example",
".",
"testfn",
")",
":",
"self",
".",
"example",
".",
"testfn",
"(",
"self",
".",
"context",
")",
"else",
":",
"self",
".",
"context",
".",
"inject_into_self",
"(",
"self",
".",
"example",
".",
"testfn",
")",
"self",
".",
"example",
".",
"testfn",
"(",
")",
"self",
".",
"num_successes",
"+=",
"1",
"except",
"KeyboardInterrupt",
":",
"# bubble interrupt for canceling spec execution",
"raise",
"except",
":",
"raise",
"self",
".",
"num_failures",
"+=",
"1",
"finally",
":",
"self",
".",
"example",
".",
"user_time",
"=",
"test_benchmark",
".",
"total_time"
]
| Handles the execution of the Example | [
"Handles",
"the",
"execution",
"of",
"the",
"Example"
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L120-L138 | train |
jeffh/describe | describe/spec/runners.py | ExampleRunner._teardown | def _teardown(self):
"Handles the restoration of any potential global state set."
self.example.after(self.context)
if self.is_root_runner:
run.after_all.execute(self.context)
#self.context = self.context._parent
self.has_ran = True | python | def _teardown(self):
"Handles the restoration of any potential global state set."
self.example.after(self.context)
if self.is_root_runner:
run.after_all.execute(self.context)
#self.context = self.context._parent
self.has_ran = True | [
"def",
"_teardown",
"(",
"self",
")",
":",
"self",
".",
"example",
".",
"after",
"(",
"self",
".",
"context",
")",
"if",
"self",
".",
"is_root_runner",
":",
"run",
".",
"after_all",
".",
"execute",
"(",
"self",
".",
"context",
")",
"#self.context = self.context._parent",
"self",
".",
"has_ran",
"=",
"True"
]
| Handles the restoration of any potential global state set. | [
"Handles",
"the",
"restoration",
"of",
"any",
"potential",
"global",
"state",
"set",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/runners.py#L140-L146 | train |
klahnakoski/mo-json | mo_json/encoder.py | pypy_json_encode | def pypy_json_encode(value, pretty=False):
"""
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
"""
global _dealing_with_problem
if pretty:
return pretty_json(value)
try:
_buffer = UnicodeBuilder(2048)
_value2json(value, _buffer)
output = _buffer.build()
return output
except Exception as e:
# THE PRETTY JSON WILL PROVIDE MORE DETAIL ABOUT THE SERIALIZATION CONCERNS
from mo_logs import Log
if _dealing_with_problem:
Log.error("Serialization of JSON problems", e)
else:
Log.warning("Serialization of JSON problems", e)
_dealing_with_problem = True
try:
return pretty_json(value)
except Exception as f:
Log.error("problem serializing object", f)
finally:
_dealing_with_problem = False | python | def pypy_json_encode(value, pretty=False):
"""
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
"""
global _dealing_with_problem
if pretty:
return pretty_json(value)
try:
_buffer = UnicodeBuilder(2048)
_value2json(value, _buffer)
output = _buffer.build()
return output
except Exception as e:
# THE PRETTY JSON WILL PROVIDE MORE DETAIL ABOUT THE SERIALIZATION CONCERNS
from mo_logs import Log
if _dealing_with_problem:
Log.error("Serialization of JSON problems", e)
else:
Log.warning("Serialization of JSON problems", e)
_dealing_with_problem = True
try:
return pretty_json(value)
except Exception as f:
Log.error("problem serializing object", f)
finally:
_dealing_with_problem = False | [
"def",
"pypy_json_encode",
"(",
"value",
",",
"pretty",
"=",
"False",
")",
":",
"global",
"_dealing_with_problem",
"if",
"pretty",
":",
"return",
"pretty_json",
"(",
"value",
")",
"try",
":",
"_buffer",
"=",
"UnicodeBuilder",
"(",
"2048",
")",
"_value2json",
"(",
"value",
",",
"_buffer",
")",
"output",
"=",
"_buffer",
".",
"build",
"(",
")",
"return",
"output",
"except",
"Exception",
"as",
"e",
":",
"# THE PRETTY JSON WILL PROVIDE MORE DETAIL ABOUT THE SERIALIZATION CONCERNS",
"from",
"mo_logs",
"import",
"Log",
"if",
"_dealing_with_problem",
":",
"Log",
".",
"error",
"(",
"\"Serialization of JSON problems\"",
",",
"e",
")",
"else",
":",
"Log",
".",
"warning",
"(",
"\"Serialization of JSON problems\"",
",",
"e",
")",
"_dealing_with_problem",
"=",
"True",
"try",
":",
"return",
"pretty_json",
"(",
"value",
")",
"except",
"Exception",
"as",
"f",
":",
"Log",
".",
"error",
"(",
"\"problem serializing object\"",
",",
"f",
")",
"finally",
":",
"_dealing_with_problem",
"=",
"False"
]
| pypy DOES NOT OPTIMIZE GENERATOR CODE WELL | [
"pypy",
"DOES",
"NOT",
"OPTIMIZE",
"GENERATOR",
"CODE",
"WELL"
]
| 0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f | https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/encoder.py#L69-L96 | train |
klahnakoski/mo-json | mo_json/encoder.py | problem_serializing | def problem_serializing(value, e=None):
"""
THROW ERROR ABOUT SERIALIZING
"""
from mo_logs import Log
try:
typename = type(value).__name__
except Exception:
typename = "<error getting name>"
try:
rep = text_type(repr(value))
except Exception as _:
rep = None
if rep == None:
Log.error(
"Problem turning value of type {{type}} to json",
type=typename,
cause=e
)
else:
Log.error(
"Problem turning value ({{value}}) of type {{type}} to json",
value=rep,
type=typename,
cause=e
) | python | def problem_serializing(value, e=None):
"""
THROW ERROR ABOUT SERIALIZING
"""
from mo_logs import Log
try:
typename = type(value).__name__
except Exception:
typename = "<error getting name>"
try:
rep = text_type(repr(value))
except Exception as _:
rep = None
if rep == None:
Log.error(
"Problem turning value of type {{type}} to json",
type=typename,
cause=e
)
else:
Log.error(
"Problem turning value ({{value}}) of type {{type}} to json",
value=rep,
type=typename,
cause=e
) | [
"def",
"problem_serializing",
"(",
"value",
",",
"e",
"=",
"None",
")",
":",
"from",
"mo_logs",
"import",
"Log",
"try",
":",
"typename",
"=",
"type",
"(",
"value",
")",
".",
"__name__",
"except",
"Exception",
":",
"typename",
"=",
"\"<error getting name>\"",
"try",
":",
"rep",
"=",
"text_type",
"(",
"repr",
"(",
"value",
")",
")",
"except",
"Exception",
"as",
"_",
":",
"rep",
"=",
"None",
"if",
"rep",
"==",
"None",
":",
"Log",
".",
"error",
"(",
"\"Problem turning value of type {{type}} to json\"",
",",
"type",
"=",
"typename",
",",
"cause",
"=",
"e",
")",
"else",
":",
"Log",
".",
"error",
"(",
"\"Problem turning value ({{value}}) of type {{type}} to json\"",
",",
"value",
"=",
"rep",
",",
"type",
"=",
"typename",
",",
"cause",
"=",
"e",
")"
]
| THROW ERROR ABOUT SERIALIZING | [
"THROW",
"ERROR",
"ABOUT",
"SERIALIZING"
]
| 0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f | https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/encoder.py#L421-L449 | train |
klahnakoski/mo-json | mo_json/encoder.py | unicode_key | def unicode_key(key):
"""
CONVERT PROPERTY VALUE TO QUOTED NAME OF SAME
"""
if not isinstance(key, (text_type, binary_type)):
from mo_logs import Log
Log.error("{{key|quote}} is not a valid key", key=key)
return quote(text_type(key)) | python | def unicode_key(key):
"""
CONVERT PROPERTY VALUE TO QUOTED NAME OF SAME
"""
if not isinstance(key, (text_type, binary_type)):
from mo_logs import Log
Log.error("{{key|quote}} is not a valid key", key=key)
return quote(text_type(key)) | [
"def",
"unicode_key",
"(",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"from",
"mo_logs",
"import",
"Log",
"Log",
".",
"error",
"(",
"\"{{key|quote}} is not a valid key\"",
",",
"key",
"=",
"key",
")",
"return",
"quote",
"(",
"text_type",
"(",
"key",
")",
")"
]
| CONVERT PROPERTY VALUE TO QUOTED NAME OF SAME | [
"CONVERT",
"PROPERTY",
"VALUE",
"TO",
"QUOTED",
"NAME",
"OF",
"SAME"
]
| 0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f | https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/encoder.py#L490-L497 | train |
tjcsl/cslbot | cslbot/commands/uptime.py | cmd | def cmd(send, _, args):
"""Shows the bot's uptime.
Syntax: {command}
"""
curr = datetime.now()
uptime = args['handler'].uptime
load_avg = ', '.join([str(x) for x in os.getloadavg()])
starttime = curr - uptime['start']
reloaded = curr - uptime['reloaded']
send("Time since start: %s, load average: %s" % (starttime, load_avg))
send("Time since reload: %s" % reloaded) | python | def cmd(send, _, args):
"""Shows the bot's uptime.
Syntax: {command}
"""
curr = datetime.now()
uptime = args['handler'].uptime
load_avg = ', '.join([str(x) for x in os.getloadavg()])
starttime = curr - uptime['start']
reloaded = curr - uptime['reloaded']
send("Time since start: %s, load average: %s" % (starttime, load_avg))
send("Time since reload: %s" % reloaded) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"curr",
"=",
"datetime",
".",
"now",
"(",
")",
"uptime",
"=",
"args",
"[",
"'handler'",
"]",
".",
"uptime",
"load_avg",
"=",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"os",
".",
"getloadavg",
"(",
")",
"]",
")",
"starttime",
"=",
"curr",
"-",
"uptime",
"[",
"'start'",
"]",
"reloaded",
"=",
"curr",
"-",
"uptime",
"[",
"'reloaded'",
"]",
"send",
"(",
"\"Time since start: %s, load average: %s\"",
"%",
"(",
"starttime",
",",
"load_avg",
")",
")",
"send",
"(",
"\"Time since reload: %s\"",
"%",
"reloaded",
")"
]
| Shows the bot's uptime.
Syntax: {command} | [
"Shows",
"the",
"bot",
"s",
"uptime",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/uptime.py#L25-L37 | train |
marrow/util | marrow/util/context/cwd.py | pcwd | def pcwd(func):
"""A decorator to provide the functionality of the
PreserveWorkingDirectory context manager for functions and methods."""
@wraps(func)
def inner(*args, **kw):
with PreserveWorkingDirectory():
return func(*args, **kw)
return inner | python | def pcwd(func):
"""A decorator to provide the functionality of the
PreserveWorkingDirectory context manager for functions and methods."""
@wraps(func)
def inner(*args, **kw):
with PreserveWorkingDirectory():
return func(*args, **kw)
return inner | [
"def",
"pcwd",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"with",
"PreserveWorkingDirectory",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"inner"
]
| A decorator to provide the functionality of the
PreserveWorkingDirectory context manager for functions and methods. | [
"A",
"decorator",
"to",
"provide",
"the",
"functionality",
"of",
"the",
"PreserveWorkingDirectory",
"context",
"manager",
"for",
"functions",
"and",
"methods",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/cwd.py#L32-L41 | train |
tjcsl/cslbot | cslbot/commands/sha512.py | cmd | def cmd(send, msg, _):
"""SHA512 hashes something.
Syntax: {command} <msg>
"""
msg = msg.encode('utf-8')
send(hashlib.sha512(msg).hexdigest()) | python | def cmd(send, msg, _):
"""SHA512 hashes something.
Syntax: {command} <msg>
"""
msg = msg.encode('utf-8')
send(hashlib.sha512(msg).hexdigest()) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'utf-8'",
")",
"send",
"(",
"hashlib",
".",
"sha512",
"(",
"msg",
")",
".",
"hexdigest",
"(",
")",
")"
]
| SHA512 hashes something.
Syntax: {command} <msg> | [
"SHA512",
"hashes",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/sha512.py#L24-L31 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.