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",
"(",... | 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... | 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... | [
"def",
"create",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"group",
",",
"type",
",",
"group_api",
")",
":",
"self",
".",
"__username",
"(",
"fname",
",",
"lname",
")",
"self",
".",
"client",
".",
"add",
"(",
"self",
".",
"__distinguished_name",
... | 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 r... | 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 r... | [
"def",
"find",
"(",
"self",
",",
"username",
")",
":",
"filter",
"=",
"[",
"'(uid={})'",
".",
"format",
"(",
"username",
")",
"]",
"results",
"=",
"self",
".",
"client",
".",
"search",
"(",
"filter",
")",
"if",
"len",
"(",
"results",
")",
"<",
"1",... | 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",
")",
":",
"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_lis... | 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_lis... | [
"def",
"__distinguished_name",
"(",
"self",
",",
"type",
",",
"fname",
"=",
"None",
",",
"lname",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"if",
"username",
"is",
"None",
":",
"uid",
"=",
"\"uid={}\"",
".",
"format",
"(",
"self",
".",
"us... | 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).... | 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).... | [
"def",
"__ldap_attr",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"type",
",",
"group",
",",
"group_api",
")",
":",
"return",
"{",
"'uid'",
":",
"str",
"(",
"self",
".",
"username",
")",
".",
"encode",
"(",
")",
",",
"'cn'",
":",
"' '",
".",
"j... | 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",
"(",
")",
":",
"salt",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"32",
")",
")",
"password",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"64",
")",
")",
"return",
"b64encode",
"(",
"sha1",
"... | 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",
")",
":",
"return",
"''",
".",
"join",
"(",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"x",
"in",
"range",
"(",
"length",
")",
")",
... | 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(cli... | 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(cli... | [
"def",
"create",
"(",
"config",
",",
"name",
",",
"group",
",",
"type",
")",
":",
"if",
"type",
"not",
"in",
"(",
"'user'",
",",
"'service'",
")",
":",
"raise",
"click",
".",
"BadOptionUsage",
"(",
"\"--type must be 'user' or 'service'\"",
")",
"client",
"... | 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):... | 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):... | [
"async",
"def",
"set_discovery_enabled",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/setup/bluetooth/discovery'",
"data",
"=",
"{",
"\"enable_discovery\"",
":",
"True",
"}",
"url",
"=",
"API",
".",
"format",
"(",
"ip",
"=",
"self",
".",
"_ipaddress",
",",
"en... | 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._devic... | 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._devic... | [
"async",
"def",
"scan_for_devices_multi_run",
"(",
"self",
",",
"runs",
"=",
"2",
")",
":",
"run",
"=",
"1",
"master",
"=",
"{",
"}",
"while",
"run",
"<",
"runs",
"+",
"1",
":",
"await",
"self",
".",
"scan_for_devices",
"(",
")",
"await",
"self",
"."... | 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.... | 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.... | [
"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 co... | 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 co... | [
"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
... | [
"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",... | 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
handl... | 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
handl... | [
"def",
"add_handler",
"(",
"self",
",",
"iface_name",
",",
"handler",
")",
":",
"if",
"self",
".",
"contract",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"self",
".",
"handlers",
"[",
"iface_name",
"]",
"=",
"handler",
"else",
":",
"raise",
"RpcE... | 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... | [
"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,... | 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,... | [
"def",
"set_filters",
"(",
"self",
",",
"filters",
")",
":",
"if",
"filters",
"==",
"None",
"or",
"isinstance",
"(",
"filters",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"self",
".",
"filters",
"=",
"filters",
"else",
":",
"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 | [
"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 di... | 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 di... | [
"def",
"call",
"(",
"self",
",",
"req",
",",
"props",
"=",
"None",
")",
":",
"resp",
"=",
"None",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Request: %s\"",
"%",
... | 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
Ap... | [
"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",
"Rp... | 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... | 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... | [
"def",
"_call",
"(",
"self",
",",
"context",
")",
":",
"req",
"=",
"context",
".",
"request",
"if",
"not",
"req",
".",
"has_key",
"(",
"\"method\"",
")",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. No 'method'.\"",
")",
"me... | 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
... | [
"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",
"t... | 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... | 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... | [
"def",
"request",
"(",
"self",
",",
"req",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"req",
")",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"self",
".",
"url",
",",
"data",
",",
"self",
".",
"headers",
")",
"f",
"=",
"self",
".",
"open... | 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... | 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... | [
"def",
"call",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"req",
"=",
"self",
".",
"to_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
"."... | 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
agai... | 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
agai... | [
"def",
"to_request",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"if",
"self",
".",
"validate_req",
":",
"self",
".",
"contract",
".",
"validate_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"method",
"="... | 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... | [
"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... | 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... | [
"def",
"to_result",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"if",
"resp",
".",
"has_key",
"(",
"\"error\"",
")",
":",
"e",
"=",
"resp",
"[",
"\"error\"",
"]",
"data",
"=",
"None",
"if",
"e",
".",
"has_key",
"(",
"\"... | 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 a... | [
"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` - Descripti... | 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` - Descripti... | [
"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_... | [
"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
... | 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
... | [
"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
... | [
"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):
retu... | 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):
retu... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"name",
"]",
"elif",
"self",
".",
"enums",
".",
"has_key",
"(",
"name",
")",
":",
"retur... | 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: ... | 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: ... | [
"def",
"struct",
"(",
"self",
",",
"struct_name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"struct_name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"struct_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAM... | 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 i... | 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 i... | [
"def",
"interface",
"(",
"self",
",",
"iface_name",
")",
":",
"if",
"self",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"return",
"self",
".",
"interfaces",
"[",
"iface_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
... | 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:
... | 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:
... | [
"def",
"validate",
"(",
"self",
",",
"expected_type",
",",
"is_array",
",",
"val",
")",
":",
"if",
"val",
"==",
"None",
":",
"if",
"expected_type",
".",
"optional",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"Value cannot ... | 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 ma... | [
"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 RpcExcepti... | 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 RpcExcepti... | [
"def",
"function",
"(",
"self",
",",
"func_name",
")",
":",
"if",
"self",
".",
"functions",
".",
"has_key",
"(",
"func_name",
")",
":",
"return",
"self",
".",
"functions",
"[",
"func_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FO... | 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
... | 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
... | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"in",
"self",
".",
"values",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"'%s' is not in enum: %s\"",
"%",
"(",
"val",
",",
"str",
"(",
"self",
".",
"va... | 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... | 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... | [
"def",
"field",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"fields",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"fields",
"[",
"name",
"]",
"elif",
"self",
".",
"extends",
":",
"if",
"not",
"self",
".",
"parent",
":... | 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... | [
"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 n... | 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 n... | [
"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",... | 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 valida... | [
"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.... | 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.... | [
"def",
"get_all_fields",
"(",
"self",
",",
"arr",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"arr",
".",
"append",
"(",
"v",
")",
"if",
"self",
".",
"extends",
":",
"parent",
"=",
"self",
".",
"con... | 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... | 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... | [
"def",
"validate_params",
"(",
"self",
",",
"params",
")",
":",
"plen",
"=",
"0",
"if",
"params",
"!=",
"None",
":",
"plen",
"=",
"len",
"(",
"params",
")",
"if",
"len",
"(",
"self",
".",
"params",
")",
"!=",
"plen",
":",
"vals",
"=",
"(",
"self"... | 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)
... | 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)
... | [
"def",
"validate_response",
"(",
"self",
",",
"resp",
")",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"contract",
".",
"validate",
"(",
"self",
".",
"returns",
",",
"self",
".",
"returns",
".",
"is_array",
",",
"resp",
")",
"if",
"not",
"ok",
":",
"v... | 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)
... | 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)
... | [
"def",
"submit",
"(",
"xml_root",
",",
"submit_config",
",",
"session",
",",
"dry_run",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"properties",
".",
"xunit_fill_testrun_id",
"(",
"xml_root",
",",
"kwargs",
".",
"get",
"(",
"\"testrun_id\"",
")",
")",
"if... | 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, ... | 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, ... | [
"def",
"submit_and_verify",
"(",
"xml_str",
"=",
"None",
",",
"xml_file",
"=",
"None",
",",
"xml_root",
"=",
"None",
",",
"config",
"=",
"None",
",",
"session",
"=",
"None",
",",
"dry_run",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"con... | 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]:
... | 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]:
... | [
"def",
"get_job_ids",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parsed_response",
":",
"return",
"None",
"try",
":",
"job_ids",
"=",
"self",
".",
"parsed_response",
"[",
"\"files\"",
"]",
"[",
"\"results.xml\"",
"]",
"[",
"\"job-ids\"",
"]",
"excep... | 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",
... | 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",
... | [
"def",
"validate_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"response",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"\"Failed to submit\"",
")",
"return",
"False",
"if",
"not",
"self",
".",
"response",
":",
"logger",
".",
"error",
"(",
"\"H... | 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 == "... | 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 == "... | [
"def",
"get_targets",
"(",
"self",
")",
":",
"if",
"self",
".",
"xml_root",
".",
"tag",
"==",
"\"testcases\"",
":",
"self",
".",
"submit_target",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"testcase_taget\"",
")",
"self",
".",
"queue_url",
"=",
"self... | 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.... | 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.... | [
"def",
"get_credentials",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"login",
"=",
"(",
"kwargs",
".",
"get",
"(",
"\"user\"",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"\"POLARION_USERNAME\"",
")",
"or",
"self",
".",
"config",
".",
"get",
"... | 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_n... | 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_n... | [
"def",
"e_164",
"(",
"msisdn",
":",
"str",
")",
"->",
"str",
":",
"number",
"=",
"phonenumbers",
".",
"parse",
"(",
"\"+{}\"",
".",
"format",
"(",
"msisdn",
".",
"lstrip",
"(",
"\"+\"",
")",
")",
",",
"None",
")",
"return",
"phonenumbers",
".",
"form... | 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 pa... | 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 pa... | [
"def",
"loadFile",
"(",
"self",
",",
"filePath",
")",
":",
"self",
".",
"_filePath",
"=",
"filePath",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"!=",
"QProcess",
".",
"Running",
":",
"self",
".",
"_kill",
"(",
")",
"self",
".",
"_run",
"(... | 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._f... | 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._f... | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"==",
"QProcess",
".",
"Running",
":",
"if",
"self",
".",
"isPlaying",
"is",
"False",
":",
"self",
".",
"_execute",
"(",
"\"pause\"",
")",
"self",
".",
"_chan... | 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",
"*"... | 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"]... | 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"]... | [
"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\"",
"]",
":",
"i... | 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']:
... | 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']:
... | [
"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 <sp... | 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</... | 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</... | [
"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",
"... | 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 i... | 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 i... | [
"def",
"to_sections",
"(",
"idl_parsed",
")",
":",
"sections",
"=",
"[",
"]",
"for",
"entity",
"in",
"idl_parsed",
":",
"if",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"comment\"",
":",
"sections",
".",
"append",
"(",
"to_section",
"(",
"entity",
"[",
"\"v... | 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... | 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... | [
"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... | 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.... | 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.... | [
"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",
"(",
... | 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... | 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... | [
"def",
"get_args",
"(",
"args",
",",
"kwargs",
",",
"arg_names",
")",
":",
"n_args",
"=",
"len",
"(",
"arg_names",
")",
"if",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
">",
"n_args",
":",
"raise",
"MoultScannerError",
"(",
"'Too many arg... | 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 vari... | 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 vari... | [
"def",
"ast_scan_file",
"(",
"filename",
",",
"re_fallback",
"=",
"True",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"try",
":",
"root",
"=",
"ast",
".",
"parse",
"(",
"fp",
".",
"read",
"... | 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':
... | 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':
... | [
"def",
"dump",
"(",
"d",
",",
"fmt",
"=",
"'json'",
",",
"stream",
"=",
"None",
")",
":",
"if",
"fmt",
"==",
"'json'",
":",
"return",
"_dump_json",
"(",
"d",
",",
"stream",
"=",
"stream",
")",
"elif",
"fmt",
"==",
"'yaml'",
":",
"return",
"yaml",
... | 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:
... | 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:
... | [
"def",
"inline_for_model",
"(",
"model",
",",
"variants",
"=",
"[",
"]",
",",
"inline_args",
"=",
"{",
"}",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"ModelBase",
")",
":",
"raise",
"ValueError",
"(",
"\"inline_for_model requires it's argument to... | 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... | 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... | [
"def",
"initialize_mpi",
"(",
"mpi",
"=",
"False",
")",
":",
"if",
"mpi",
":",
"import",
"mpi4py",
".",
"MPI",
"comm",
"=",
"mpi4py",
".",
"MPI",
".",
"COMM_WORLD",
"rank",
"=",
"comm",
".",
"Get_rank",
"(",
")",
"size",
"=",
"comm",
".",
"Get_size",... | 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,
... | 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,
... | [
"def",
"create_ports",
"(",
"port",
",",
"mpi",
",",
"rank",
")",
":",
"if",
"port",
"==",
"\"random\"",
"or",
"port",
"is",
"None",
":",
"ports",
"=",
"{",
"}",
"else",
":",
"port",
"=",
"int",
"(",
"port",
")",
"ports",
"=",
"{",
"\"REQ\"",
":"... | 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... | 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... | [
"def",
"import_from_string",
"(",
"full_class_name",
")",
":",
"s",
"=",
"full_class_name",
".",
"split",
"(",
"'.'",
")",
"class_name",
"=",
"s",
"[",
"-",
"1",
"]",
"module_name",
"=",
"full_class_name",
"[",
":",
"-",
"len",
"(",
"class_name",
")",
"-... | 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... | 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... | [
"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_c... | 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",
")",
":",
"result",
"=",
"requests",
".",
"post",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"metadata",
")",
")",
"logger",
".",
"deb... | 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\"",
"]",
"result",
"=",
"requests",
".",
"delete",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
"+",
"\"/\"",
"+",
... | 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... | 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... | [
"def",
"create_sockets",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"ports",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"poller",
"=",
"zmq",
".",
"Poller",
"(",
")",
"rep",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"REP",
")",
... | 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 ... | 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 ... | [
"def",
"run",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"model",
"configfile",
"=",
"self",
".",
"configfile",
"interval",
"=",
"self",
".",
"interval",
"sockets",
"=",
"self",
".",
"sockets",
"model",
".",
"initialize",
"(",
"configfile",
")",
... | 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... | 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... | [
"def",
"calc_basics",
"(",
"width",
"=",
"-",
"1",
",",
"length",
"=",
"-",
"1",
",",
"height",
"=",
"2.4",
",",
"prevailing_wind",
"=",
"2.8",
")",
":",
"if",
"width",
"==",
"-",
"1",
":",
"width",
"=",
"int",
"(",
"input",
"(",
"'enter building w... | 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... | 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... | [
"def",
"bld_rafter_deflection",
"(",
"length",
"=",
"-",
"9",
",",
"force",
"=",
"-",
"9",
",",
"E_mod_elasticity",
"=",
"-",
"9",
",",
"I_moment_of_intertia",
"=",
"-",
"9",
")",
":",
"if",
"length",
"==",
"-",
"9",
":",
"length",
"=",
"float",
"(",... | 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 == ... | 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 == ... | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"\"election_date\"",
"]",
")",
"kwargs",
"=",
"{",
"\"race__office__body\"",
":",
"obj... | 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",
... | 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 ... | 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 ... | [
"def",
"update",
"(",
"self",
")",
":",
"for",
"channel",
"in",
"self",
".",
"channels",
":",
"channel",
".",
"update",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_project_dict",
"[",
"\"channels\"",
"]",
")",
")",
":",
"ch... | 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",
".",
"... | 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(... | 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(... | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ddate'",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"output",
"="... | 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.ArgumentEx... | 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.ArgumentEx... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--chan'",
",",
"'--channel'",
",",
"action",
"=",
"arguments",
"."... | 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'",
... | 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",
"=",
"'app... | 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
""... | 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
""... | [
"def",
"main",
"(",
")",
":",
"character1",
"=",
"Character",
"(",
"'Albogh'",
",",
"str",
"=",
"4",
",",
"int",
"=",
"7",
",",
"sta",
"=",
"50",
")",
"character2",
"=",
"Character",
"(",
"'Zoltor'",
",",
"str",
"=",
"6",
",",
"int",
"=",
"6",
... | 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",
"succeed... | 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
... | 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
... | [
"def",
"fight",
"(",
"self",
",",
"moves",
"=",
"10",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"moves",
")",
":",
"result",
",",
"dmg",
"=",
"self",
".",
"calc_move",
"(",
"self",
".",
"c1",
",",
"self",
".",
"c2",
")",
"print",
"(... | 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:
... | 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:
... | [
"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 rec... | 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 rec... | [
"def",
"estimate_completion",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"!=",
"build_states",
".",
"BUILDING",
":",
"defer",
".",
"returnValue",
"(",
"self",
".",
"completed",
")",
"avg_delta",
"=",
"yield",
"self",
".",
"connection",
".",
"getAve... | 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:
... | [
"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()
... | 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()
... | [
"def",
"target",
"(",
"self",
")",
":",
"task",
"=",
"yield",
"self",
".",
"task",
"(",
")",
"if",
"not",
"task",
":",
"yield",
"defer",
".",
"succeed",
"(",
"None",
")",
"defer",
".",
"returnValue",
"(",
"None",
")",
"defer",
".",
"returnValue",
"... | 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 ... | 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 ... | [
"def",
"task",
"(",
"self",
")",
":",
"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.e... | 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.e... | [
"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",
... | 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()
... | 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()
... | [
"def",
"get_override_winner",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"election",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"division",
"=",
"obj",
".",
"election",
".",
"division",
".",
"parent... | 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_ele... | 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_ele... | [
"def",
"get_override_votes",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"meta\"",
")",
":",
"if",
"obj",
".",
"meta",
".",
"override_ap_votes",
":",
"all_votes",
"=",
"None",
"for",
"ce",
"in",
"obj",
".",
"candidate_elections... | 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 = publi... | 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 = publi... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"publication",
":",
"publication",
"=",
"self",
".",
"publication",
"if",
"not",
"self",
".",
"title",
":",
"self",
".",
"title",
"=",
"publication",
".",... | 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 function... | 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 function... | [
"def",
"execute",
"(",
"self",
",",
"context",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"total_benchmark",
"=",
"Benchmark",
"(",
")",
"self",
".",
"context",
"=",
"context",
"or",
"Context",
"(",
")",
"if",
"sel... | 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 exa... | [
"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, stde... | 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, stde... | [
"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",
"."... | 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... | 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... | [
"def",
"_setup",
"(",
"self",
")",
":",
"\"Resets the state and prepares for running the example.\"",
"self",
".",
"example",
".",
"error",
"=",
"None",
"self",
".",
"example",
".",
"traceback",
"=",
"''",
"c",
"=",
"Context",
"(",
"parent",
"=",
"self",
".",
... | 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_successe... | 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_successe... | [
"def",
"_execute_example_group",
"(",
"self",
")",
":",
"\"Handles the execution of Example Group\"",
"for",
"example",
"in",
"self",
".",
"example",
":",
"runner",
"=",
"self",
".",
"__class__",
"(",
"example",
",",
"self",
".",
"formatter",
")",
"runner",
".",... | 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:
s... | 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:
s... | [
"def",
"_execute_example",
"(",
"self",
")",
":",
"\"Handles the execution of the Example\"",
"test_benchmark",
"=",
"Benchmark",
"(",
")",
"try",
":",
"with",
"Registry",
"(",
")",
",",
"test_benchmark",
":",
"if",
"accepts_arg",
"(",
"self",
".",
"example",
".... | 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",
")",
":",
"\"Handles the restoration of any potential global state set.\"",
"self",
".",
"example",
".",
"after",
"(",
"self",
".",
"context",
")",
"if",
"self",
".",
"is_root_runner",
":",
"run",
".",
"after_all",
".",
"execute",
... | 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... | 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... | [
"def",
"pypy_json_encode",
"(",
"value",
",",
"pretty",
"=",
"False",
")",
":",
"global",
"_dealing_with_problem",
"if",
"pretty",
":",
"return",
"pretty_json",
"(",
"value",
")",
"try",
":",
"_buffer",
"=",
"UnicodeBuilder",
"(",
"2048",
")",
"_value2json",
... | 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 = ... | 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 = ... | [
"def",
"problem_serializing",
"(",
"value",
",",
"e",
"=",
"None",
")",
":",
"from",
"mo_logs",
"import",
"Log",
"try",
":",
"typename",
"=",
"type",
"(",
"value",
")",
".",
"__name__",
"except",
"Exception",
":",
"typename",
"=",
"\"<error getting name>\"",... | 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",
"... | 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,... | 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,... | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"curr",
"=",
"datetime",
".",
"now",
"(",
")",
"uptime",
"=",
"args",
"[",
"'handler'",
"]",
".",
"uptime",
"load_avg",
"=",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",... | 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",
")",
"retur... | 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.