repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/api.py | create_lock_file | def create_lock_file(path):
"""
Create lock file filled with :attr:`LOCK_FILE_CONTENT
<ftp.settings.LOCK_FILE_CONTENT>`.
Args:
path (str): Path to the lock file. Made from users home directory and
:attr:`LOCK_FILENAME <ftp.settings.LOCK_FILENAME>`.
"""
with open(path... | python | def create_lock_file(path):
"""
Create lock file filled with :attr:`LOCK_FILE_CONTENT
<ftp.settings.LOCK_FILE_CONTENT>`.
Args:
path (str): Path to the lock file. Made from users home directory and
:attr:`LOCK_FILENAME <ftp.settings.LOCK_FILENAME>`.
"""
with open(path... | [
"def",
"create_lock_file",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"settings",
".",
"LOCK_FILE_CONTENT",
")",
"passwd_reader",
".",
"set_permissions",
"(",
"path",
",",
"gid",
"=",
... | Create lock file filled with :attr:`LOCK_FILE_CONTENT
<ftp.settings.LOCK_FILE_CONTENT>`.
Args:
path (str): Path to the lock file. Made from users home directory and
:attr:`LOCK_FILENAME <ftp.settings.LOCK_FILENAME>`. | [
"Create",
"lock",
"file",
"filled",
"with",
":",
"attr",
":",
"LOCK_FILE_CONTENT",
"<ftp",
".",
"settings",
".",
"LOCK_FILE_CONTENT",
">",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/api.py#L91-L103 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/api.py | add_user | def add_user(username, password):
"""
Adds record to passwd-like file for ProFTPD, creates home directory and
sets permissions for important files.
Args:
username (str): User's name.
password (str): User's password.
"""
assert _is_valid_username(username), \
"Invalid... | python | def add_user(username, password):
"""
Adds record to passwd-like file for ProFTPD, creates home directory and
sets permissions for important files.
Args:
username (str): User's name.
password (str): User's password.
"""
assert _is_valid_username(username), \
"Invalid... | [
"def",
"add_user",
"(",
"username",
",",
"password",
")",
":",
"assert",
"_is_valid_username",
"(",
"username",
")",
",",
"\"Invalid format of username '%s'!\"",
"%",
"username",
"assert",
"username",
"not",
"in",
"passwd_reader",
".",
"load_users",
"(",
")",
",",... | Adds record to passwd-like file for ProFTPD, creates home directory and
sets permissions for important files.
Args:
username (str): User's name.
password (str): User's password. | [
"Adds",
"record",
"to",
"passwd",
"-",
"like",
"file",
"for",
"ProFTPD",
"creates",
"home",
"directory",
"and",
"sets",
"permissions",
"for",
"important",
"files",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/api.py#L107-L149 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/api.py | remove_user | def remove_user(username):
"""
Remove user, his home directory and so on..
Args:
username (str): User's name.
"""
users = passwd_reader.load_users()
assert username in users, "Username '%s' not found!" % username
# remove user from passwd file
del users[username]
passwd_re... | python | def remove_user(username):
"""
Remove user, his home directory and so on..
Args:
username (str): User's name.
"""
users = passwd_reader.load_users()
assert username in users, "Username '%s' not found!" % username
# remove user from passwd file
del users[username]
passwd_re... | [
"def",
"remove_user",
"(",
"username",
")",
":",
"users",
"=",
"passwd_reader",
".",
"load_users",
"(",
")",
"assert",
"username",
"in",
"users",
",",
"\"Username '%s' not found!\"",
"%",
"username",
"# remove user from passwd file",
"del",
"users",
"[",
"username",... | Remove user, his home directory and so on..
Args:
username (str): User's name. | [
"Remove",
"user",
"his",
"home",
"directory",
"and",
"so",
"on",
".."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/api.py#L153-L173 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/api.py | change_password | def change_password(username, new_password):
"""
Change password for given `username`.
Args:
username (str): User's name.
new_password (str): User's new password.
"""
assert username in passwd_reader.load_users(),\
"Username '%s' not found!" % username
sh.ftpasswd(
... | python | def change_password(username, new_password):
"""
Change password for given `username`.
Args:
username (str): User's name.
new_password (str): User's new password.
"""
assert username in passwd_reader.load_users(),\
"Username '%s' not found!" % username
sh.ftpasswd(
... | [
"def",
"change_password",
"(",
"username",
",",
"new_password",
")",
":",
"assert",
"username",
"in",
"passwd_reader",
".",
"load_users",
"(",
")",
",",
"\"Username '%s' not found!\"",
"%",
"username",
"sh",
".",
"ftpasswd",
"(",
"\"--change-password\"",
",",
"pas... | Change password for given `username`.
Args:
username (str): User's name.
new_password (str): User's new password. | [
"Change",
"password",
"for",
"given",
"username",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/api.py#L177-L197 |
crypto101/clarent | clarent/path.py | getDataPath | def getDataPath(_system=thisSystem, _FilePath=FilePath):
"""Gets an appropriate path for storing some local data, such as TLS
credentials.
If the path doesn't exist, it is created.
"""
if _system == "Windows":
pathName = "~/Crypto101/"
else:
pathName = "~/.crypto101/"
path... | python | def getDataPath(_system=thisSystem, _FilePath=FilePath):
"""Gets an appropriate path for storing some local data, such as TLS
credentials.
If the path doesn't exist, it is created.
"""
if _system == "Windows":
pathName = "~/Crypto101/"
else:
pathName = "~/.crypto101/"
path... | [
"def",
"getDataPath",
"(",
"_system",
"=",
"thisSystem",
",",
"_FilePath",
"=",
"FilePath",
")",
":",
"if",
"_system",
"==",
"\"Windows\"",
":",
"pathName",
"=",
"\"~/Crypto101/\"",
"else",
":",
"pathName",
"=",
"\"~/.crypto101/\"",
"path",
"=",
"_FilePath",
"... | Gets an appropriate path for storing some local data, such as TLS
credentials.
If the path doesn't exist, it is created. | [
"Gets",
"an",
"appropriate",
"path",
"for",
"storing",
"some",
"local",
"data",
"such",
"as",
"TLS",
"credentials",
"."
] | train | https://github.com/crypto101/clarent/blob/2b441d7933e85ee948cfb78506b7ca0a32e9588d/clarent/path.py#L12-L28 |
ludeeus/pycfdns | pycfdns/__init__.py | CloudflareUpdater.get_zoneID | def get_zoneID(self, headers, zone):
"""Get the zone id for the zone."""
zoneIDurl = self.BASE_URL + '?name=' + zone
zoneIDrequest = requests.get(zoneIDurl, headers=headers)
zoneID = zoneIDrequest.json()['result'][0]['id']
return zoneID | python | def get_zoneID(self, headers, zone):
"""Get the zone id for the zone."""
zoneIDurl = self.BASE_URL + '?name=' + zone
zoneIDrequest = requests.get(zoneIDurl, headers=headers)
zoneID = zoneIDrequest.json()['result'][0]['id']
return zoneID | [
"def",
"get_zoneID",
"(",
"self",
",",
"headers",
",",
"zone",
")",
":",
"zoneIDurl",
"=",
"self",
".",
"BASE_URL",
"+",
"'?name='",
"+",
"zone",
"zoneIDrequest",
"=",
"requests",
".",
"get",
"(",
"zoneIDurl",
",",
"headers",
"=",
"headers",
")",
"zoneID... | Get the zone id for the zone. | [
"Get",
"the",
"zone",
"id",
"for",
"the",
"zone",
"."
] | train | https://github.com/ludeeus/pycfdns/blob/0fd027be49d67250f85f2398d006a9409a7dae28/pycfdns/__init__.py#L26-L31 |
ludeeus/pycfdns | pycfdns/__init__.py | CloudflareUpdater.get_recordInfo | def get_recordInfo(self, headers, zoneID, zone, records):
"""Get the information of the records."""
if 'None' in records: #If ['None'] in record argument, query all.
recordQueryEnpoint = '/' + zoneID + '/dns_records&per_page=100'
recordUrl = self.BASE_URL + recordQueryEnpoint
... | python | def get_recordInfo(self, headers, zoneID, zone, records):
"""Get the information of the records."""
if 'None' in records: #If ['None'] in record argument, query all.
recordQueryEnpoint = '/' + zoneID + '/dns_records&per_page=100'
recordUrl = self.BASE_URL + recordQueryEnpoint
... | [
"def",
"get_recordInfo",
"(",
"self",
",",
"headers",
",",
"zoneID",
",",
"zone",
",",
"records",
")",
":",
"if",
"'None'",
"in",
"records",
":",
"#If ['None'] in record argument, query all.",
"recordQueryEnpoint",
"=",
"'/'",
"+",
"zoneID",
"+",
"'/dns_records&pe... | Get the information of the records. | [
"Get",
"the",
"information",
"of",
"the",
"records",
"."
] | train | https://github.com/ludeeus/pycfdns/blob/0fd027be49d67250f85f2398d006a9409a7dae28/pycfdns/__init__.py#L33-L67 |
ludeeus/pycfdns | pycfdns/__init__.py | CloudflareUpdater.update_records | def update_records(self, headers, zoneID, updateRecords):
"""Update DNS records."""
IP = requests.get(self.GET_EXT_IP_URL).text
message = True
errorsRecords = []
sucessRecords = []
for record in updateRecords:
updateEndpoint = '/' + zoneID + '/dns_records/' + ... | python | def update_records(self, headers, zoneID, updateRecords):
"""Update DNS records."""
IP = requests.get(self.GET_EXT_IP_URL).text
message = True
errorsRecords = []
sucessRecords = []
for record in updateRecords:
updateEndpoint = '/' + zoneID + '/dns_records/' + ... | [
"def",
"update_records",
"(",
"self",
",",
"headers",
",",
"zoneID",
",",
"updateRecords",
")",
":",
"IP",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"GET_EXT_IP_URL",
")",
".",
"text",
"message",
"=",
"True",
"errorsRecords",
"=",
"[",
"]",
"sucessR... | Update DNS records. | [
"Update",
"DNS",
"records",
"."
] | train | https://github.com/ludeeus/pycfdns/blob/0fd027be49d67250f85f2398d006a9409a7dae28/pycfdns/__init__.py#L69-L98 |
20tab/twentytab-utils | twentytab/admin.py | ButtonableModelAdmin.change_view | def change_view(self, request, object_id, form_url='', extra_context={}):
"""
It adds ButtonLinks and ButtonForms to extra_context used in the change_form template
"""
extra_context['buttons_link'] = self.buttons_link
extra_context['buttons_form'] = self.buttons_form
extr... | python | def change_view(self, request, object_id, form_url='', extra_context={}):
"""
It adds ButtonLinks and ButtonForms to extra_context used in the change_form template
"""
extra_context['buttons_link'] = self.buttons_link
extra_context['buttons_form'] = self.buttons_form
extr... | [
"def",
"change_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"form_url",
"=",
"''",
",",
"extra_context",
"=",
"{",
"}",
")",
":",
"extra_context",
"[",
"'buttons_link'",
"]",
"=",
"self",
".",
"buttons_link",
"extra_context",
"[",
"'buttons_for... | It adds ButtonLinks and ButtonForms to extra_context used in the change_form template | [
"It",
"adds",
"ButtonLinks",
"and",
"ButtonForms",
"to",
"extra_context",
"used",
"in",
"the",
"change_form",
"template"
] | train | https://github.com/20tab/twentytab-utils/blob/e02d55b1fd848c8e11ca9b7e97a5916780544d34/twentytab/admin.py#L61-L68 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/fault.py | FaultFromZSIException | def FaultFromZSIException(ex, actor=None):
'''Return a Fault object created from a ZSI exception object.
'''
mystr = getattr(ex, 'str', None) or str(ex)
mytrace = getattr(ex, 'trace', '')
elt = '''<ZSI:ParseFaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:ParseFaultDetail>
''... | python | def FaultFromZSIException(ex, actor=None):
'''Return a Fault object created from a ZSI exception object.
'''
mystr = getattr(ex, 'str', None) or str(ex)
mytrace = getattr(ex, 'trace', '')
elt = '''<ZSI:ParseFaultDetail>
<ZSI:string>%s</ZSI:string>
<ZSI:trace>%s</ZSI:trace>
</ZSI:ParseFaultDetail>
''... | [
"def",
"FaultFromZSIException",
"(",
"ex",
",",
"actor",
"=",
"None",
")",
":",
"mystr",
"=",
"getattr",
"(",
"ex",
",",
"'str'",
",",
"None",
")",
"or",
"str",
"(",
"ex",
")",
"mytrace",
"=",
"getattr",
"(",
"ex",
",",
"'trace'",
",",
"''",
")",
... | Return a Fault object created from a ZSI exception object. | [
"Return",
"a",
"Fault",
"object",
"created",
"from",
"a",
"ZSI",
"exception",
"object",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L195-L210 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/fault.py | FaultFromException | def FaultFromException(ex, inheader, tb=None, actor=None):
'''Return a Fault object created from a Python exception.
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Processing Failure</faultstring>
<detail>
<ZSI:FaultDetail>
<ZSI:string></ZSI:string>
... | python | def FaultFromException(ex, inheader, tb=None, actor=None):
'''Return a Fault object created from a Python exception.
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Processing Failure</faultstring>
<detail>
<ZSI:FaultDetail>
<ZSI:string></ZSI:string>
... | [
"def",
"FaultFromException",
"(",
"ex",
",",
"inheader",
",",
"tb",
"=",
"None",
",",
"actor",
"=",
"None",
")",
":",
"tracetext",
"=",
"None",
"if",
"tb",
":",
"try",
":",
"lines",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'%s:%d:%s'",
"%",
"(",
"name... | Return a Fault object created from a Python exception.
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Processing Failure</faultstring>
<detail>
<ZSI:FaultDetail>
<ZSI:string></ZSI:string>
<ZSI:trace></ZSI:trace>
</ZSI:FaultDetail>
</... | [
"Return",
"a",
"Fault",
"object",
"created",
"from",
"a",
"Python",
"exception",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L213-L247 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/fault.py | FaultFromFaultMessage | def FaultFromFaultMessage(ps):
'''Parse the message as a fault.
'''
pyobj = ps.Parse(FaultType.typecode)
if pyobj.detail == None: detailany = None
else: detailany = pyobj.detail.any
return Fault(pyobj.faultcode, pyobj.faultstring,
pyobj.faultactor, detailany) | python | def FaultFromFaultMessage(ps):
'''Parse the message as a fault.
'''
pyobj = ps.Parse(FaultType.typecode)
if pyobj.detail == None: detailany = None
else: detailany = pyobj.detail.any
return Fault(pyobj.faultcode, pyobj.faultstring,
pyobj.faultactor, detailany) | [
"def",
"FaultFromFaultMessage",
"(",
"ps",
")",
":",
"pyobj",
"=",
"ps",
".",
"Parse",
"(",
"FaultType",
".",
"typecode",
")",
"if",
"pyobj",
".",
"detail",
"==",
"None",
":",
"detailany",
"=",
"None",
"else",
":",
"detailany",
"=",
"pyobj",
".",
"deta... | Parse the message as a fault. | [
"Parse",
"the",
"message",
"as",
"a",
"fault",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L250-L259 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/fault.py | Fault.serialize | def serialize(self, sw):
'''Serialize the object.'''
detail = None
if self.detail is not None:
detail = Detail()
detail.any = self.detail
pyobj = FaultType(self.code, self.string, self.actor, detail)
sw.serialize(pyobj, typed=False) | python | def serialize(self, sw):
'''Serialize the object.'''
detail = None
if self.detail is not None:
detail = Detail()
detail.any = self.detail
pyobj = FaultType(self.code, self.string, self.actor, detail)
sw.serialize(pyobj, typed=False) | [
"def",
"serialize",
"(",
"self",
",",
"sw",
")",
":",
"detail",
"=",
"None",
"if",
"self",
".",
"detail",
"is",
"not",
"None",
":",
"detail",
"=",
"Detail",
"(",
")",
"detail",
".",
"any",
"=",
"self",
".",
"detail",
"pyobj",
"=",
"FaultType",
"(",... | Serialize the object. | [
"Serialize",
"the",
"object",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/fault.py#L148-L156 |
nefarioustim/parker | parker/parser.py | parse | def parse(page_to_parse):
"""Return a parse of page.content. Wraps PyQuery."""
global _parsed
if not isinstance(page_to_parse, page.Page):
raise TypeError("parser.parse requires a parker.Page object.")
if page_to_parse.content is None:
raise ValueError("parser.parse requires a fetched p... | python | def parse(page_to_parse):
"""Return a parse of page.content. Wraps PyQuery."""
global _parsed
if not isinstance(page_to_parse, page.Page):
raise TypeError("parser.parse requires a parker.Page object.")
if page_to_parse.content is None:
raise ValueError("parser.parse requires a fetched p... | [
"def",
"parse",
"(",
"page_to_parse",
")",
":",
"global",
"_parsed",
"if",
"not",
"isinstance",
"(",
"page_to_parse",
",",
"page",
".",
"Page",
")",
":",
"raise",
"TypeError",
"(",
"\"parser.parse requires a parker.Page object.\"",
")",
"if",
"page_to_parse",
".",... | Return a parse of page.content. Wraps PyQuery. | [
"Return",
"a",
"parse",
"of",
"page",
".",
"content",
".",
"Wraps",
"PyQuery",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/parser.py#L11-L29 |
ludeeus/pylaunches | pylaunches/common.py | CommonFunctions.api_call | async def api_call(self, endpoint):
"""Call the API."""
data = None
if self.session is None:
self.session = aiohttp.ClientSession()
try:
async with async_timeout.timeout(5, loop=self.loop):
response = await self.session.get(endpoint, headers=HEADER... | python | async def api_call(self, endpoint):
"""Call the API."""
data = None
if self.session is None:
self.session = aiohttp.ClientSession()
try:
async with async_timeout.timeout(5, loop=self.loop):
response = await self.session.get(endpoint, headers=HEADER... | [
"async",
"def",
"api_call",
"(",
"self",
",",
"endpoint",
")",
":",
"data",
"=",
"None",
"if",
"self",
".",
"session",
"is",
"None",
":",
"self",
".",
"session",
"=",
"aiohttp",
".",
"ClientSession",
"(",
")",
"try",
":",
"async",
"with",
"async_timeou... | Call the API. | [
"Call",
"the",
"API",
"."
] | train | https://github.com/ludeeus/pylaunches/blob/6cc449a9f734cbf789e561564b500a5dca93fe82/pylaunches/common.py#L22-L33 |
ludeeus/pylaunches | pylaunches/common.py | CommonFunctions.sort_data | async def sort_data(self, data, sort_key, reverse=False):
"""Sort dataset."""
sorted_data = []
lines = sorted(data, key=lambda k: k[sort_key], reverse=reverse)
for line in lines:
sorted_data.append(line)
return sorted_data | python | async def sort_data(self, data, sort_key, reverse=False):
"""Sort dataset."""
sorted_data = []
lines = sorted(data, key=lambda k: k[sort_key], reverse=reverse)
for line in lines:
sorted_data.append(line)
return sorted_data | [
"async",
"def",
"sort_data",
"(",
"self",
",",
"data",
",",
"sort_key",
",",
"reverse",
"=",
"False",
")",
":",
"sorted_data",
"=",
"[",
"]",
"lines",
"=",
"sorted",
"(",
"data",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
"sort_key",
"]",
",",
... | Sort dataset. | [
"Sort",
"dataset",
"."
] | train | https://github.com/ludeeus/pylaunches/blob/6cc449a9f734cbf789e561564b500a5dca93fe82/pylaunches/common.py#L35-L41 |
ludeeus/pylaunches | pylaunches/common.py | CommonFunctions.iso | async def iso(self, source):
"""Convert to timestamp."""
from datetime import datetime
unix_timestamp = int(source)
return datetime.fromtimestamp(unix_timestamp).isoformat() | python | async def iso(self, source):
"""Convert to timestamp."""
from datetime import datetime
unix_timestamp = int(source)
return datetime.fromtimestamp(unix_timestamp).isoformat() | [
"async",
"def",
"iso",
"(",
"self",
",",
"source",
")",
":",
"from",
"datetime",
"import",
"datetime",
"unix_timestamp",
"=",
"int",
"(",
"source",
")",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"unix_timestamp",
")",
".",
"isoformat",
"(",
")"
] | Convert to timestamp. | [
"Convert",
"to",
"timestamp",
"."
] | train | https://github.com/ludeeus/pylaunches/blob/6cc449a9f734cbf789e561564b500a5dca93fe82/pylaunches/common.py#L43-L47 |
collectiveacuity/labPack | labpack/records/settings.py | load_settings | def load_settings(file_path, module_name='', secret_key=''):
''' a method to load data from json valid files
:param file_path: string with path to settings file
:param module_name: [optional] string with name of module containing file path
:param secret_key: [optional] string with key to decrypt... | python | def load_settings(file_path, module_name='', secret_key=''):
''' a method to load data from json valid files
:param file_path: string with path to settings file
:param module_name: [optional] string with name of module containing file path
:param secret_key: [optional] string with key to decrypt... | [
"def",
"load_settings",
"(",
"file_path",
",",
"module_name",
"=",
"''",
",",
"secret_key",
"=",
"''",
")",
":",
"# validate inputs\r",
"title",
"=",
"'load_settings'",
"try",
":",
"_path_arg",
"=",
"'%s(file_path=%s)'",
"%",
"(",
"title",
",",
"str",
"(",
"... | a method to load data from json valid files
:param file_path: string with path to settings file
:param module_name: [optional] string with name of module containing file path
:param secret_key: [optional] string with key to decrypt drep file
:return: dictionary with settings data | [
"a",
"method",
"to",
"load",
"data",
"from",
"json",
"valid",
"files",
":",
"param",
"file_path",
":",
"string",
"with",
"path",
"to",
"settings",
"file",
":",
"param",
"module_name",
":",
"[",
"optional",
"]",
"string",
"with",
"name",
"of",
"module",
"... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L5-L101 |
collectiveacuity/labPack | labpack/records/settings.py | save_settings | def save_settings(file_path, record_details, overwrite=False, secret_key=''):
''' a method to save dictionary typed data to a local file
:param file_path: string with path to settings file
:param record_details: dictionary with record details
:param overwrite: [optional] boolean to overwrite exi... | python | def save_settings(file_path, record_details, overwrite=False, secret_key=''):
''' a method to save dictionary typed data to a local file
:param file_path: string with path to settings file
:param record_details: dictionary with record details
:param overwrite: [optional] boolean to overwrite exi... | [
"def",
"save_settings",
"(",
"file_path",
",",
"record_details",
",",
"overwrite",
"=",
"False",
",",
"secret_key",
"=",
"''",
")",
":",
"# validate inputs\r",
"title",
"=",
"'save_settings'",
"try",
":",
"_path_arg",
"=",
"'%s(file_path=%s)'",
"%",
"(",
"title"... | a method to save dictionary typed data to a local file
:param file_path: string with path to settings file
:param record_details: dictionary with record details
:param overwrite: [optional] boolean to overwrite existing file data
:param secret_key: [optional] string with key to decrypt drep file
... | [
"a",
"method",
"to",
"save",
"dictionary",
"typed",
"data",
"to",
"a",
"local",
"file",
":",
"param",
"file_path",
":",
"string",
"with",
"path",
"to",
"settings",
"file",
":",
"param",
"record_details",
":",
"dictionary",
"with",
"record",
"details",
":",
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L103-L196 |
collectiveacuity/labPack | labpack/records/settings.py | _remove_settings | def _remove_settings(_file_path, _retry_count=10, _remove_dir=False):
'''
a helper method for removing settings file
:param _file_path: string with path to file to remove
:param _retry_count: integer with number of attempts before error is raised
:param _remove_dir: [optional] ... | python | def _remove_settings(_file_path, _retry_count=10, _remove_dir=False):
'''
a helper method for removing settings file
:param _file_path: string with path to file to remove
:param _retry_count: integer with number of attempts before error is raised
:param _remove_dir: [optional] ... | [
"def",
"_remove_settings",
"(",
"_file_path",
",",
"_retry_count",
"=",
"10",
",",
"_remove_dir",
"=",
"False",
")",
":",
"import",
"os",
"from",
"time",
"import",
"sleep",
"count",
"=",
"0",
"while",
"True",
":",
"try",
":",
"os",
".",
"remove",
"(",
... | a helper method for removing settings file
:param _file_path: string with path to file to remove
:param _retry_count: integer with number of attempts before error is raised
:param _remove_dir: [optional] boolean to remove empty parent directories
:return: None | [
"a",
"helper",
"method",
"for",
"removing",
"settings",
"file",
":",
"param",
"_file_path",
":",
"string",
"with",
"path",
"to",
"file",
"to",
"remove",
":",
"param",
"_retry_count",
":",
"integer",
"with",
"number",
"of",
"attempts",
"before",
"error",
"is"... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L198-L231 |
collectiveacuity/labPack | labpack/records/settings.py | remove_settings | def remove_settings(file_path, retry_count=10, remove_dir=False):
'''
a method to remove a file using a child process
http://www.petercollingridge.co.uk/blog/running-multiple-processes-python
https://docs.python.org/3.5/library/multiprocessing.html
:param file_path: string wit... | python | def remove_settings(file_path, retry_count=10, remove_dir=False):
'''
a method to remove a file using a child process
http://www.petercollingridge.co.uk/blog/running-multiple-processes-python
https://docs.python.org/3.5/library/multiprocessing.html
:param file_path: string wit... | [
"def",
"remove_settings",
"(",
"file_path",
",",
"retry_count",
"=",
"10",
",",
"remove_dir",
"=",
"False",
")",
":",
"# validate inputs\r",
"title",
"=",
"'remove_settings'",
"try",
":",
"_path_arg",
"=",
"'%s(file_path=%s)'",
"%",
"(",
"title",
",",
"str",
"... | a method to remove a file using a child process
http://www.petercollingridge.co.uk/blog/running-multiple-processes-python
https://docs.python.org/3.5/library/multiprocessing.html
:param file_path: string with path to file to remove
:param retry_count: integer with number of attempts to r... | [
"a",
"method",
"to",
"remove",
"a",
"file",
"using",
"a",
"child",
"process",
"http",
":",
"//",
"www",
".",
"petercollingridge",
".",
"co",
".",
"uk",
"/",
"blog",
"/",
"running",
"-",
"multiple",
"-",
"processes",
"-",
"python",
"https",
":",
"//",
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L233-L261 |
collectiveacuity/labPack | labpack/records/settings.py | ingest_environ | def ingest_environ(model_path=''):
''' a method to convert environment variables to a python dictionary
:param model_path: [optional] string with path to jsonmodel of data to ingest
:return: dictionary with environmental variables
NOTE: if a model is provided, then only those fields in the m... | python | def ingest_environ(model_path=''):
''' a method to convert environment variables to a python dictionary
:param model_path: [optional] string with path to jsonmodel of data to ingest
:return: dictionary with environmental variables
NOTE: if a model is provided, then only those fields in the m... | [
"def",
"ingest_environ",
"(",
"model_path",
"=",
"''",
")",
":",
"# convert environment variables into json typed data\r",
"from",
"os",
"import",
"environ",
",",
"path",
"typed_dict",
"=",
"{",
"}",
"environ_variables",
"=",
"dict",
"(",
"environ",
")",
"for",
"k... | a method to convert environment variables to a python dictionary
:param model_path: [optional] string with path to jsonmodel of data to ingest
:return: dictionary with environmental variables
NOTE: if a model is provided, then only those fields in the model will be
added to the output ... | [
"a",
"method",
"to",
"convert",
"environment",
"variables",
"to",
"a",
"python",
"dictionary",
":",
"param",
"model_path",
":",
"[",
"optional",
"]",
"string",
"with",
"path",
"to",
"jsonmodel",
"of",
"data",
"to",
"ingest",
":",
"return",
":",
"dictionary",... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L263-L317 |
collectiveacuity/labPack | labpack/records/settings.py | compile_settings | def compile_settings(model_path, file_path, ignore_errors=False):
''' a method to compile configuration values from different sources
NOTE: method searches the environment variables, a local
configuration path and the default values for a jsonmodel
object for valid ... | python | def compile_settings(model_path, file_path, ignore_errors=False):
''' a method to compile configuration values from different sources
NOTE: method searches the environment variables, a local
configuration path and the default values for a jsonmodel
object for valid ... | [
"def",
"compile_settings",
"(",
"model_path",
",",
"file_path",
",",
"ignore_errors",
"=",
"False",
")",
":",
"# construct configuration model and default details\r",
"from",
"jsonmodel",
".",
"validators",
"import",
"jsonModel",
"config_model",
"=",
"jsonModel",
"(",
"... | a method to compile configuration values from different sources
NOTE: method searches the environment variables, a local
configuration path and the default values for a jsonmodel
object for valid configuration values. if an environmental
variable or key in... | [
"a",
"method",
"to",
"compile",
"configuration",
"values",
"from",
"different",
"sources",
"NOTE",
":",
"method",
"searches",
"the",
"environment",
"variables",
"a",
"local",
"configuration",
"path",
"and",
"the",
"default",
"values",
"for",
"a",
"jsonmodel",
"o... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L319-L386 |
jgoodlet/punter | punter/api.py | search | def search(api_key, query, offset=0, type='personal'):
"""Get a list of email addresses for the provided domain.
The type of search executed will vary depending on the query provided.
Currently this query is restricted to either domain searches, in which
the email addresses (and other bits) for the dom... | python | def search(api_key, query, offset=0, type='personal'):
"""Get a list of email addresses for the provided domain.
The type of search executed will vary depending on the query provided.
Currently this query is restricted to either domain searches, in which
the email addresses (and other bits) for the dom... | [
"def",
"search",
"(",
"api_key",
",",
"query",
",",
"offset",
"=",
"0",
",",
"type",
"=",
"'personal'",
")",
":",
"if",
"not",
"isinstance",
"(",
"api_key",
",",
"str",
")",
":",
"raise",
"InvalidAPIKeyException",
"(",
"'API key must be a string'",
")",
"i... | Get a list of email addresses for the provided domain.
The type of search executed will vary depending on the query provided.
Currently this query is restricted to either domain searches, in which
the email addresses (and other bits) for the domain are returned, or
searches for an email address. The la... | [
"Get",
"a",
"list",
"of",
"email",
"addresses",
"for",
"the",
"provided",
"domain",
"."
] | train | https://github.com/jgoodlet/punter/blob/605ee52a1e5019b360dd643f4bf6861aefa93812/punter/api.py#L10-L38 |
LesPatamechanix/patalib | src/patalib/clinamen.py | Clinamen.generate_clinamen | def generate_clinamen(self, input_word, list_of_dict_words, swerve):
""" Generate a clinamen. Here we
looks for words via the damerau levenshtein distance
with a distance of 2.
"""
results = []
selected_list = []
for i in list_of_dict_words: #produce a subset fo... | python | def generate_clinamen(self, input_word, list_of_dict_words, swerve):
""" Generate a clinamen. Here we
looks for words via the damerau levenshtein distance
with a distance of 2.
"""
results = []
selected_list = []
for i in list_of_dict_words: #produce a subset fo... | [
"def",
"generate_clinamen",
"(",
"self",
",",
"input_word",
",",
"list_of_dict_words",
",",
"swerve",
")",
":",
"results",
"=",
"[",
"]",
"selected_list",
"=",
"[",
"]",
"for",
"i",
"in",
"list_of_dict_words",
":",
"#produce a subset for efficency",
"if",
"len",... | Generate a clinamen. Here we
looks for words via the damerau levenshtein distance
with a distance of 2. | [
"Generate",
"a",
"clinamen",
".",
"Here",
"we",
"looks",
"for",
"words",
"via",
"the",
"damerau",
"levenshtein",
"distance",
"with",
"a",
"distance",
"of",
"2",
"."
] | train | https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/clinamen.py#L8-L25 |
LesPatamechanix/patalib | src/patalib/clinamen.py | Clinamen.damerau_levenshtein_distance | def damerau_levenshtein_distance(self, s1, s2):
""" Dervied algorithm from the following website:
https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/
Gives us the distance between two words.
"""
d = {}
lenstr1 = len(s1)
lenstr2 = len(s2... | python | def damerau_levenshtein_distance(self, s1, s2):
""" Dervied algorithm from the following website:
https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/
Gives us the distance between two words.
"""
d = {}
lenstr1 = len(s1)
lenstr2 = len(s2... | [
"def",
"damerau_levenshtein_distance",
"(",
"self",
",",
"s1",
",",
"s2",
")",
":",
"d",
"=",
"{",
"}",
"lenstr1",
"=",
"len",
"(",
"s1",
")",
"lenstr2",
"=",
"len",
"(",
"s2",
")",
"for",
"i",
"in",
"xrange",
"(",
"-",
"1",
",",
"lenstr1",
"+",
... | Dervied algorithm from the following website:
https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/
Gives us the distance between two words. | [
"Dervied",
"algorithm",
"from",
"the",
"following",
"website",
":",
"https",
":",
"//",
"www",
".",
"guyrutenberg",
".",
"com",
"/",
"2008",
"/",
"12",
"/",
"15",
"/",
"damerau",
"-",
"levenshtein",
"-",
"distance",
"-",
"in",
"-",
"python",
"/",
"Give... | train | https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/clinamen.py#L28-L55 |
stephanepechard/projy | projy/templates/ProjyTemplateTemplate.py | ProjyTemplateTemplate.substitutes | def substitutes(self):
""" Return the substitutions for the templating replacements. """
substitute_dict = dict(
project = self.project_name,
template = self.project_name + 'Template',
file = self.project_name + 'FileTemplate',
)
return substitute_dict | python | def substitutes(self):
""" Return the substitutions for the templating replacements. """
substitute_dict = dict(
project = self.project_name,
template = self.project_name + 'Template',
file = self.project_name + 'FileTemplate',
)
return substitute_dict | [
"def",
"substitutes",
"(",
"self",
")",
":",
"substitute_dict",
"=",
"dict",
"(",
"project",
"=",
"self",
".",
"project_name",
",",
"template",
"=",
"self",
".",
"project_name",
"+",
"'Template'",
",",
"file",
"=",
"self",
".",
"project_name",
"+",
"'FileT... | Return the substitutions for the templating replacements. | [
"Return",
"the",
"substitutions",
"for",
"the",
"templating",
"replacements",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplateTemplate.py#L28-L35 |
chairbender/fantasy-football-auction | fantasy_football_auction/auction.py | Auction.tick | def tick(self):
"""
Advances time in the game. Use this once all "choices" have been submitted for the current
game state using the other methods.
"""
if self.state == AuctionState.NOMINATE:
# if no nominee submitted, exception
if self.nominee is None:
... | python | def tick(self):
"""
Advances time in the game. Use this once all "choices" have been submitted for the current
game state using the other methods.
"""
if self.state == AuctionState.NOMINATE:
# if no nominee submitted, exception
if self.nominee is None:
... | [
"def",
"tick",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"AuctionState",
".",
"NOMINATE",
":",
"# if no nominee submitted, exception",
"if",
"self",
".",
"nominee",
"is",
"None",
":",
"raise",
"InvalidActionError",
"(",
"\"Tick was invoked during no... | Advances time in the game. Use this once all "choices" have been submitted for the current
game state using the other methods. | [
"Advances",
"time",
"in",
"the",
"game",
".",
"Use",
"this",
"once",
"all",
"choices",
"have",
"been",
"submitted",
"for",
"the",
"current",
"game",
"state",
"using",
"the",
"other",
"methods",
"."
] | train | https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/auction.py#L129-L177 |
chairbender/fantasy-football-auction | fantasy_football_auction/auction.py | Auction.place_bid | def place_bid(self, owner_id, bid):
"""
Submits a bid for this tick for current player. This is not a guarantee that it will be accepted!
If other players submit a higher bid this same tick, the bid won't be counted. Try again next tick if it's not
too high!
:param int owner_id: ... | python | def place_bid(self, owner_id, bid):
"""
Submits a bid for this tick for current player. This is not a guarantee that it will be accepted!
If other players submit a higher bid this same tick, the bid won't be counted. Try again next tick if it's not
too high!
:param int owner_id: ... | [
"def",
"place_bid",
"(",
"self",
",",
"owner_id",
",",
"bid",
")",
":",
"if",
"self",
".",
"state",
"!=",
"AuctionState",
".",
"BID",
":",
"raise",
"InvalidActionError",
"(",
"\"Bid was attempted, but it is not currently time to submit bids.\"",
")",
"elif",
"self",... | Submits a bid for this tick for current player. This is not a guarantee that it will be accepted!
If other players submit a higher bid this same tick, the bid won't be counted. Try again next tick if it's not
too high!
:param int owner_id: id of owner who is submitting the bid
:param int... | [
"Submits",
"a",
"bid",
"for",
"this",
"tick",
"for",
"current",
"player",
".",
"This",
"is",
"not",
"a",
"guarantee",
"that",
"it",
"will",
"be",
"accepted!",
"If",
"other",
"players",
"submit",
"a",
"higher",
"bid",
"this",
"same",
"tick",
"the",
"bid",... | train | https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/auction.py#L179-L202 |
chairbender/fantasy-football-auction | fantasy_football_auction/auction.py | Auction.nominate | def nominate(self, owner_id, player_idx, bid):
"""
Nominates the player for auctioning.
:param int owner_id: index of the owner who is nominating
:param int player_idx: index of the player to nominate in the players list
:param int bid: starting bid
:raise InvalidAction... | python | def nominate(self, owner_id, player_idx, bid):
"""
Nominates the player for auctioning.
:param int owner_id: index of the owner who is nominating
:param int player_idx: index of the player to nominate in the players list
:param int bid: starting bid
:raise InvalidAction... | [
"def",
"nominate",
"(",
"self",
",",
"owner_id",
",",
"player_idx",
",",
"bid",
")",
":",
"owner",
"=",
"self",
".",
"owners",
"[",
"owner_id",
"]",
"nominated_player",
"=",
"self",
".",
"players",
"[",
"player_idx",
"]",
"if",
"self",
".",
"state",
"!... | Nominates the player for auctioning.
:param int owner_id: index of the owner who is nominating
:param int player_idx: index of the player to nominate in the players list
:param int bid: starting bid
:raise InvalidActionError: if the action is not allowed according to the rules. See the... | [
"Nominates",
"the",
"player",
"for",
"auctioning",
"."
] | train | https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/auction.py#L204-L247 |
sassoo/goldman | goldman/resources/oauth_ropc.py | Resource.on_post | def on_post(self, req, resp):
""" Validate the access token request for spec compliance
The spec also dictates the JSON based error response
on failure & is handled in this responder.
"""
grant_type = req.get_param('grant_type')
password = req.get_param('password')
... | python | def on_post(self, req, resp):
""" Validate the access token request for spec compliance
The spec also dictates the JSON based error response
on failure & is handled in this responder.
"""
grant_type = req.get_param('grant_type')
password = req.get_param('password')
... | [
"def",
"on_post",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"grant_type",
"=",
"req",
".",
"get_param",
"(",
"'grant_type'",
")",
"password",
"=",
"req",
".",
"get_param",
"(",
"'password'",
")",
"username",
"=",
"req",
".",
"get_param",
"(",
"'u... | Validate the access token request for spec compliance
The spec also dictates the JSON based error response
on failure & is handled in this responder. | [
"Validate",
"the",
"access",
"token",
"request",
"for",
"spec",
"compliance"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/oauth_ropc.py#L52-L97 |
LesPatamechanix/patalib | src/patalib/anomaly.py | Anomaly.generate_anomaly | def generate_anomaly(self, input_word, list_of_dict_words, num):
""" Generate an anomaly. This is done
via a Psuedo-random number generator.
"""
results = []
for i in range(0,num):
index = randint(0,len(list_of_dict_words)-1)
name = list_of_dict_words[ind... | python | def generate_anomaly(self, input_word, list_of_dict_words, num):
""" Generate an anomaly. This is done
via a Psuedo-random number generator.
"""
results = []
for i in range(0,num):
index = randint(0,len(list_of_dict_words)-1)
name = list_of_dict_words[ind... | [
"def",
"generate_anomaly",
"(",
"self",
",",
"input_word",
",",
"list_of_dict_words",
",",
"num",
")",
":",
"results",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num",
")",
":",
"index",
"=",
"randint",
"(",
"0",
",",
"len",
"(",
"li... | Generate an anomaly. This is done
via a Psuedo-random number generator. | [
"Generate",
"an",
"anomaly",
".",
"This",
"is",
"done",
"via",
"a",
"Psuedo",
"-",
"random",
"number",
"generator",
"."
] | train | https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/anomaly.py#L9-L23 |
glue-viz/echo | echo/qt/connect.py | connect_checkable_button | def connect_checkable_button(instance, prop, widget):
"""
Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : Q... | python | def connect_checkable_button(instance, prop, widget):
"""
Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : Q... | [
"def",
"connect_checkable_button",
"(",
"instance",
",",
"prop",
",",
"widget",
")",
":",
"add_callback",
"(",
"instance",
",",
"prop",
",",
"widget",
".",
"setChecked",
")",
"widget",
".",
"toggled",
".",
"connect",
"(",
"partial",
"(",
"setattr",
",",
"i... | Connect a boolean callback property with a Qt button widget.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should implement th... | [
"Connect",
"a",
"boolean",
"callback",
"property",
"with",
"a",
"Qt",
"button",
"widget",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L20-L36 |
glue-viz/echo | echo/qt/connect.py | connect_text | def connect_text(instance, prop, widget):
"""
Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWid... | python | def connect_text(instance, prop, widget):
"""
Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWid... | [
"def",
"connect_text",
"(",
"instance",
",",
"prop",
",",
"widget",
")",
":",
"def",
"update_prop",
"(",
")",
":",
"val",
"=",
"widget",
".",
"text",
"(",
")",
"setattr",
"(",
"instance",
",",
"prop",
",",
"val",
")",
"def",
"update_widget",
"(",
"va... | Connect a string callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should impl... | [
"Connect",
"a",
"string",
"callback",
"property",
"with",
"a",
"Qt",
"widget",
"containing",
"text",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L39-L74 |
glue-viz/echo | echo/qt/connect.py | connect_combo_data | def connect_combo_data(instance, prop, widget):
"""
Connect a callback property with a QComboBox widget based on the userData.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
wi... | python | def connect_combo_data(instance, prop, widget):
"""
Connect a callback property with a QComboBox widget based on the userData.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
wi... | [
"def",
"connect_combo_data",
"(",
"instance",
",",
"prop",
",",
"widget",
")",
":",
"def",
"update_widget",
"(",
"value",
")",
":",
"try",
":",
"idx",
"=",
"_find_combo_data",
"(",
"widget",
",",
"value",
")",
"except",
"ValueError",
":",
"if",
"value",
... | Connect a callback property with a QComboBox widget based on the userData.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QComboBox
The combo box to connect.
See ... | [
"Connect",
"a",
"callback",
"property",
"with",
"a",
"QComboBox",
"widget",
"based",
"on",
"the",
"userData",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L77-L114 |
glue-viz/echo | echo/qt/connect.py | connect_combo_text | def connect_combo_text(instance, prop, widget):
"""
Connect a callback property with a QComboBox widget based on the text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget... | python | def connect_combo_text(instance, prop, widget):
"""
Connect a callback property with a QComboBox widget based on the text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget... | [
"def",
"connect_combo_text",
"(",
"instance",
",",
"prop",
",",
"widget",
")",
":",
"def",
"update_widget",
"(",
"value",
")",
":",
"try",
":",
"idx",
"=",
"_find_combo_text",
"(",
"widget",
",",
"value",
")",
"except",
"ValueError",
":",
"if",
"value",
... | Connect a callback property with a QComboBox widget based on the text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QComboBox
The combo box to connect.
See Also... | [
"Connect",
"a",
"callback",
"property",
"with",
"a",
"QComboBox",
"widget",
"based",
"on",
"the",
"text",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L117-L154 |
glue-viz/echo | echo/qt/connect.py | connect_float_text | def connect_float_text(instance, prop, widget, fmt="{:g}"):
"""
Connect a numerical callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback proper... | python | def connect_float_text(instance, prop, widget, fmt="{:g}"):
"""
Connect a numerical callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback proper... | [
"def",
"connect_float_text",
"(",
"instance",
",",
"prop",
",",
"widget",
",",
"fmt",
"=",
"\"{:g}\"",
")",
":",
"if",
"callable",
"(",
"fmt",
")",
":",
"format_func",
"=",
"fmt",
"else",
":",
"def",
"format_func",
"(",
"x",
")",
":",
"return",
"fmt",
... | Connect a numerical callback property with a Qt widget containing text.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This should i... | [
"Connect",
"a",
"numerical",
"callback",
"property",
"with",
"a",
"Qt",
"widget",
"containing",
"text",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L157-L200 |
glue-viz/echo | echo/qt/connect.py | connect_value | def connect_value(instance, prop, widget, value_range=None, log=False):
"""
Connect a numerical callback property with a Qt widget representing a value.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of th... | python | def connect_value(instance, prop, widget, value_range=None, log=False):
"""
Connect a numerical callback property with a Qt widget representing a value.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of th... | [
"def",
"connect_value",
"(",
"instance",
",",
"prop",
",",
"widget",
",",
"value_range",
"=",
"None",
",",
"log",
"=",
"False",
")",
":",
"if",
"log",
":",
"if",
"value_range",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"log option can only be set if v... | Connect a numerical callback property with a Qt widget representing a value.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of the callback property
widget : QtWidget
The Qt widget to connect. This sho... | [
"Connect",
"a",
"numerical",
"callback",
"property",
"with",
"a",
"Qt",
"widget",
"representing",
"a",
"value",
"."
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L203-L253 |
glue-viz/echo | echo/qt/connect.py | connect_button | def connect_button(instance, prop, widget):
"""
Connect a button with a callback method
Parameters
----------
instance : object
The class instance that the callback method is attached to
prop : str
The name of the callback method
widget : QtWidget
The Qt widget to co... | python | def connect_button(instance, prop, widget):
"""
Connect a button with a callback method
Parameters
----------
instance : object
The class instance that the callback method is attached to
prop : str
The name of the callback method
widget : QtWidget
The Qt widget to co... | [
"def",
"connect_button",
"(",
"instance",
",",
"prop",
",",
"widget",
")",
":",
"widget",
".",
"clicked",
".",
"connect",
"(",
"getattr",
"(",
"instance",
",",
"prop",
")",
")"
] | Connect a button with a callback method
Parameters
----------
instance : object
The class instance that the callback method is attached to
prop : str
The name of the callback method
widget : QtWidget
The Qt widget to connect. This should implement the ``clicked`` method | [
"Connect",
"a",
"button",
"with",
"a",
"callback",
"method"
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L256-L269 |
glue-viz/echo | echo/qt/connect.py | _find_combo_data | def _find_combo_data(widget, value):
"""
Returns the index in a combo box where itemData == value
Raises a ValueError if data is not found
"""
# Here we check that the result is True, because some classes may overload
# == and return other kinds of objects whether true or false.
for idx in ... | python | def _find_combo_data(widget, value):
"""
Returns the index in a combo box where itemData == value
Raises a ValueError if data is not found
"""
# Here we check that the result is True, because some classes may overload
# == and return other kinds of objects whether true or false.
for idx in ... | [
"def",
"_find_combo_data",
"(",
"widget",
",",
"value",
")",
":",
"# Here we check that the result is True, because some classes may overload",
"# == and return other kinds of objects whether true or false.",
"for",
"idx",
"in",
"range",
"(",
"widget",
".",
"count",
"(",
")",
... | Returns the index in a combo box where itemData == value
Raises a ValueError if data is not found | [
"Returns",
"the",
"index",
"in",
"a",
"combo",
"box",
"where",
"itemData",
"==",
"value"
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L272-L284 |
glue-viz/echo | echo/qt/connect.py | _find_combo_text | def _find_combo_text(widget, value):
"""
Returns the index in a combo box where text == value
Raises a ValueError if data is not found
"""
i = widget.findText(value)
if i == -1:
raise ValueError("%s not found in combo box" % value)
else:
return i | python | def _find_combo_text(widget, value):
"""
Returns the index in a combo box where text == value
Raises a ValueError if data is not found
"""
i = widget.findText(value)
if i == -1:
raise ValueError("%s not found in combo box" % value)
else:
return i | [
"def",
"_find_combo_text",
"(",
"widget",
",",
"value",
")",
":",
"i",
"=",
"widget",
".",
"findText",
"(",
"value",
")",
"if",
"i",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"%s not found in combo box\"",
"%",
"value",
")",
"else",
":",
"return... | Returns the index in a combo box where text == value
Raises a ValueError if data is not found | [
"Returns",
"the",
"index",
"in",
"a",
"combo",
"box",
"where",
"text",
"==",
"value"
] | train | https://github.com/glue-viz/echo/blob/6ad54cc5e869de27c34e8716f2619ddc640f08fe/echo/qt/connect.py#L287-L297 |
Garito/ySanic | ySanic/__init__.py | ySanic.factory | async def factory(self, request, path = "/", as_ = None):
"""
The user will ask for /path/to/the/parent/new/member-list
Where member-list is the list where the parent saves the children order
So in the test model MinimalMongoTree the only factory will be /new/children
"""
counter, time = perf_co... | python | async def factory(self, request, path = "/", as_ = None):
"""
The user will ask for /path/to/the/parent/new/member-list
Where member-list is the list where the parent saves the children order
So in the test model MinimalMongoTree the only factory will be /new/children
"""
counter, time = perf_co... | [
"async",
"def",
"factory",
"(",
"self",
",",
"request",
",",
"path",
"=",
"\"/\"",
",",
"as_",
"=",
"None",
")",
":",
"counter",
",",
"time",
"=",
"perf_counter",
"(",
")",
",",
"process_time",
"(",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
... | The user will ask for /path/to/the/parent/new/member-list
Where member-list is the list where the parent saves the children order
So in the test model MinimalMongoTree the only factory will be /new/children | [
"The",
"user",
"will",
"ask",
"for",
"/",
"path",
"/",
"to",
"/",
"the",
"/",
"parent",
"/",
"new",
"/",
"member",
"-",
"list",
"Where",
"member",
"-",
"list",
"is",
"the",
"list",
"where",
"the",
"parent",
"saves",
"the",
"children",
"order",
"So",
... | train | https://github.com/Garito/ySanic/blob/4a8728f48c5833077be4ab049b1ebe83c99c943e/ySanic/__init__.py#L206-L232 |
twidi/py-dataql | dataql/utils.py | class_repr | def class_repr(value):
"""Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
Example
-------
>>> from datetime import date
>>> class_rep... | python | def class_repr(value):
"""Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
Example
-------
>>> from datetime import date
>>> class_rep... | [
"def",
"class_repr",
"(",
"value",
")",
":",
"klass",
"=",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"type",
")",
":",
"klass",
"=",
"klass",
".",
"__class__",
"return",
"'.'",
".",
"join",
"(",
"[",
"klass",
".",
"__module__",
",",
"kla... | Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
Example
-------
>>> from datetime import date
>>> class_repr(date)
'datetime.date'
... | [
"Returns",
"a",
"representation",
"of",
"the",
"value",
"class",
"."
] | train | https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/utils.py#L7-L31 |
mbodenhamer/syn | syn/base_utils/rand.py | rand_str | def rand_str(min_char=MIN_CHR, max_char=MAX_CHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, func=chr, **kwargs):
'''For values in the (extended) ASCII range, regardless of Python version.
'''
l = randint(min_len, max_len)
ret = ''
for k in xrange(l):
ret += func(randint(min_char,... | python | def rand_str(min_char=MIN_CHR, max_char=MAX_CHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, func=chr, **kwargs):
'''For values in the (extended) ASCII range, regardless of Python version.
'''
l = randint(min_len, max_len)
ret = ''
for k in xrange(l):
ret += func(randint(min_char,... | [
"def",
"rand_str",
"(",
"min_char",
"=",
"MIN_CHR",
",",
"max_char",
"=",
"MAX_CHR",
",",
"min_len",
"=",
"MIN_STRLEN",
",",
"max_len",
"=",
"MAX_STRLEN",
",",
"func",
"=",
"chr",
",",
"*",
"*",
"kwargs",
")",
":",
"l",
"=",
"randint",
"(",
"min_len",
... | For values in the (extended) ASCII range, regardless of Python version. | [
"For",
"values",
"in",
"the",
"(",
"extended",
")",
"ASCII",
"range",
"regardless",
"of",
"Python",
"version",
"."
] | train | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/rand.py#L85-L94 |
mbodenhamer/syn | syn/base_utils/rand.py | rand_unicode | def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, **kwargs):
'''For values in the unicode range, regardless of Python version.
'''
from syn.five import unichr
return unicode(rand_str(min_char, max_char, min_len, max_len, unichr)) | python | def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, **kwargs):
'''For values in the unicode range, regardless of Python version.
'''
from syn.five import unichr
return unicode(rand_str(min_char, max_char, min_len, max_len, unichr)) | [
"def",
"rand_unicode",
"(",
"min_char",
"=",
"MIN_UNICHR",
",",
"max_char",
"=",
"MAX_UNICHR",
",",
"min_len",
"=",
"MIN_STRLEN",
",",
"max_len",
"=",
"MAX_STRLEN",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"syn",
".",
"five",
"import",
"unichr",
"return"... | For values in the unicode range, regardless of Python version. | [
"For",
"values",
"in",
"the",
"unicode",
"range",
"regardless",
"of",
"Python",
"version",
"."
] | train | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/rand.py#L96-L101 |
GemHQ/round-py | round/users.py | Users.create | def create(self, email, device_name, passphrase=None,
api_token=None, redirect_uri=None, **kwargs):
"""Create a new User object and add it to this Users collection.
In addition to creating a user, this call will create a device for that
user, whose device_token will be returned f... | python | def create(self, email, device_name, passphrase=None,
api_token=None, redirect_uri=None, **kwargs):
"""Create a new User object and add it to this Users collection.
In addition to creating a user, this call will create a device for that
user, whose device_token will be returned f... | [
"def",
"create",
"(",
"self",
",",
"email",
",",
"device_name",
",",
"passphrase",
"=",
"None",
",",
"api_token",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"passphrase",
"and",
"u'default_wallet'",
"no... | Create a new User object and add it to this Users collection.
In addition to creating a user, this call will create a device for that
user, whose device_token will be returned from this call. Store the
device_token, as it's required to complete Gem-Device authentication
after the user a... | [
"Create",
"a",
"new",
"User",
"object",
"and",
"add",
"it",
"to",
"this",
"Users",
"collection",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L20-L97 |
GemHQ/round-py | round/users.py | User.wallet | def wallet(self):
"""Fetch and return this user's default (only) Wallet."""
if not hasattr(self, '_wallet'):
wallet_resource = self.resource.default_wallet.get()
self._wallet = Wallet(wallet_resource, self.client)
return self._wallet | python | def wallet(self):
"""Fetch and return this user's default (only) Wallet."""
if not hasattr(self, '_wallet'):
wallet_resource = self.resource.default_wallet.get()
self._wallet = Wallet(wallet_resource, self.client)
return self._wallet | [
"def",
"wallet",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_wallet'",
")",
":",
"wallet_resource",
"=",
"self",
".",
"resource",
".",
"default_wallet",
".",
"get",
"(",
")",
"self",
".",
"_wallet",
"=",
"Wallet",
"(",
"wallet_r... | Fetch and return this user's default (only) Wallet. | [
"Fetch",
"and",
"return",
"this",
"user",
"s",
"default",
"(",
"only",
")",
"Wallet",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L140-L145 |
GemHQ/round-py | round/users.py | User.subscriptions | def subscriptions(self):
"""Fetch and return Subscriptions associated with this user."""
if not hasattr(self, '_subscriptions'):
subscriptions_resource = self.resource.subscriptions
self._subscriptions = Subscriptions(
subscriptions_resource, self.client)
... | python | def subscriptions(self):
"""Fetch and return Subscriptions associated with this user."""
if not hasattr(self, '_subscriptions'):
subscriptions_resource = self.resource.subscriptions
self._subscriptions = Subscriptions(
subscriptions_resource, self.client)
... | [
"def",
"subscriptions",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_subscriptions'",
")",
":",
"subscriptions_resource",
"=",
"self",
".",
"resource",
".",
"subscriptions",
"self",
".",
"_subscriptions",
"=",
"Subscriptions",
"(",
"subs... | Fetch and return Subscriptions associated with this user. | [
"Fetch",
"and",
"return",
"Subscriptions",
"associated",
"with",
"this",
"user",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L148-L154 |
GemHQ/round-py | round/users.py | User.verify_mfa | def verify_mfa(self, mfa_token):
"""Verify an SMS or TOTP MFA token for this user.
Args:
mfa_token (str): An alphanumeric code from either a User's TOTP
application or sent to them via SMS.
Returns:
True if the mfa_token is valid, False otherwise.
"""
... | python | def verify_mfa(self, mfa_token):
"""Verify an SMS or TOTP MFA token for this user.
Args:
mfa_token (str): An alphanumeric code from either a User's TOTP
application or sent to them via SMS.
Returns:
True if the mfa_token is valid, False otherwise.
"""
... | [
"def",
"verify_mfa",
"(",
"self",
",",
"mfa_token",
")",
":",
"response",
"=",
"self",
".",
"resource",
".",
"verify_mfa",
"(",
"{",
"'mfa_token'",
":",
"mfa_token",
"}",
")",
"return",
"(",
"response",
"[",
"'valid'",
"]",
"==",
"True",
"or",
"response"... | Verify an SMS or TOTP MFA token for this user.
Args:
mfa_token (str): An alphanumeric code from either a User's TOTP
application or sent to them via SMS.
Returns:
True if the mfa_token is valid, False otherwise. | [
"Verify",
"an",
"SMS",
"or",
"TOTP",
"MFA",
"token",
"for",
"this",
"user",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/users.py#L160-L171 |
prestontimmons/django-synctool | synctool/functions.py | reset_sequence | def reset_sequence(app_label):
"""
Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table.
"""
puts("Resetting primary key sequence for {0}".format(app_label))
cursor = connection.cursor()
cmd = get_reset_command(app... | python | def reset_sequence(app_label):
"""
Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table.
"""
puts("Resetting primary key sequence for {0}".format(app_label))
cursor = connection.cursor()
cmd = get_reset_command(app... | [
"def",
"reset_sequence",
"(",
"app_label",
")",
":",
"puts",
"(",
"\"Resetting primary key sequence for {0}\"",
".",
"format",
"(",
"app_label",
")",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cmd",
"=",
"get_reset_command",
"(",
"app_label",
")... | Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table. | [
"Reset",
"the",
"primary",
"key",
"sequence",
"for",
"the",
"tables",
"in",
"an",
"application",
".",
"This",
"is",
"necessary",
"if",
"any",
"local",
"edits",
"have",
"happened",
"to",
"the",
"table",
"."
] | train | https://github.com/prestontimmons/django-synctool/blob/bfacaacd3a4f98facd524e16c0ce2b3ab2ef30a7/synctool/functions.py#L77-L87 |
rpuntaie/stpl | stpl/stpl.py | BaseTemplate.search | def search(cls, name, lookup=None):
""" Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. """
for spath in lookup:
spath = os.path.abspath(spath) + os.sep
fname = os.path.abspath(os.path.join(spath, name))
... | python | def search(cls, name, lookup=None):
""" Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. """
for spath in lookup:
spath = os.path.abspath(spath) + os.sep
fname = os.path.abspath(os.path.join(spath, name))
... | [
"def",
"search",
"(",
"cls",
",",
"name",
",",
"lookup",
"=",
"None",
")",
":",
"for",
"spath",
"in",
"lookup",
":",
"spath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"spath",
")",
"+",
"os",
".",
"sep",
"fname",
"=",
"os",
".",
"path",
"."... | Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. | [
"Search",
"name",
"in",
"all",
"directories",
"specified",
"in",
"lookup",
".",
"First",
"without",
"then",
"with",
"common",
"extensions",
".",
"Return",
"first",
"hit",
"."
] | train | https://github.com/rpuntaie/stpl/blob/c2f47c260c59e5ccbae35642e396ac5c02e309f2/stpl/stpl.py#L138-L149 |
radjkarl/fancyTools | fancytools/pystructure/fallbackPackage.py | fallbackPackage | def fallbackPackage(package_name, fallback_package_name):
'''
if an import cannot be resolved
import from fallback package
example:
from [package_name].doesnt_exist import Foo
results in
from [fallback_package_name].doesnt_exist import Foo
'''
importer = Finder(packag... | python | def fallbackPackage(package_name, fallback_package_name):
'''
if an import cannot be resolved
import from fallback package
example:
from [package_name].doesnt_exist import Foo
results in
from [fallback_package_name].doesnt_exist import Foo
'''
importer = Finder(packag... | [
"def",
"fallbackPackage",
"(",
"package_name",
",",
"fallback_package_name",
")",
":",
"importer",
"=",
"Finder",
"(",
"package_name",
",",
"fallback_package_name",
")",
"sys",
".",
"meta_path",
".",
"append",
"(",
"importer",
")"
] | if an import cannot be resolved
import from fallback package
example:
from [package_name].doesnt_exist import Foo
results in
from [fallback_package_name].doesnt_exist import Foo | [
"if",
"an",
"import",
"cannot",
"be",
"resolved",
"import",
"from",
"fallback",
"package",
"example",
":",
"from",
"[",
"package_name",
"]",
".",
"doesnt_exist",
"import",
"Foo",
"results",
"in",
"from",
"[",
"fallback_package_name",
"]",
".",
"doesnt_exist",
... | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/pystructure/fallbackPackage.py#L40-L53 |
veltzer/pytconf | config/helpers.py | array_indented | def array_indented(level, l, quote_char='\'', comma_after=False):
# type: (int, List[str], str, bool) -> str
"""
return an array indented according to indent level
:param level:
:param l:
:param quote_char:
:param comma_after:
:return:
"""
out = "[\n"
for x in l:
out ... | python | def array_indented(level, l, quote_char='\'', comma_after=False):
# type: (int, List[str], str, bool) -> str
"""
return an array indented according to indent level
:param level:
:param l:
:param quote_char:
:param comma_after:
:return:
"""
out = "[\n"
for x in l:
out ... | [
"def",
"array_indented",
"(",
"level",
",",
"l",
",",
"quote_char",
"=",
"'\\''",
",",
"comma_after",
"=",
"False",
")",
":",
"# type: (int, List[str], str, bool) -> str",
"out",
"=",
"\"[\\n\"",
"for",
"x",
"in",
"l",
":",
"out",
"+=",
"(",
"(",
"(",
"lev... | return an array indented according to indent level
:param level:
:param l:
:param quote_char:
:param comma_after:
:return: | [
"return",
"an",
"array",
"indented",
"according",
"to",
"indent",
"level",
":",
"param",
"level",
":",
":",
"param",
"l",
":",
":",
"param",
"quote_char",
":",
":",
"param",
"comma_after",
":",
":",
"return",
":"
] | train | https://github.com/veltzer/pytconf/blob/8dee43ace35d0dd2ab1105fb94057f650393360f/config/helpers.py#L9-L25 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._validate_install | def _validate_install(self):
''' a method to validate docker is installed '''
from subprocess import check_output, STDOUT
sys_command = 'docker --help'
try:
check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8')
# call(sys_command, stdout=o... | python | def _validate_install(self):
''' a method to validate docker is installed '''
from subprocess import check_output, STDOUT
sys_command = 'docker --help'
try:
check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8')
# call(sys_command, stdout=o... | [
"def",
"_validate_install",
"(",
"self",
")",
":",
"from",
"subprocess",
"import",
"check_output",
",",
"STDOUT",
"sys_command",
"=",
"'docker --help'",
"try",
":",
"check_output",
"(",
"sys_command",
",",
"shell",
"=",
"True",
",",
"stderr",
"=",
"STDOUT",
")... | a method to validate docker is installed | [
"a",
"method",
"to",
"validate",
"docker",
"is",
"installed"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L104-L116 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._validate_virtualbox | def _validate_virtualbox(self):
'''
a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running
'''
# validate operating system
if self.localhost.os.sysname != 'Windows':
return Fal... | python | def _validate_virtualbox(self):
'''
a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running
'''
# validate operating system
if self.localhost.os.sysname != 'Windows':
return Fal... | [
"def",
"_validate_virtualbox",
"(",
"self",
")",
":",
"# validate operating system\r",
"if",
"self",
".",
"localhost",
".",
"os",
".",
"sysname",
"!=",
"'Windows'",
":",
"return",
"False",
"win_release",
"=",
"float",
"(",
"self",
".",
"localhost",
".",
"os",
... | a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running | [
"a",
"method",
"to",
"validate",
"that",
"virtualbox",
"is",
"running",
"on",
"Win",
"7",
"/",
"8",
"machines",
":",
"return",
":",
"boolean",
"indicating",
"whether",
"virtualbox",
"is",
"running"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L118-L156 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._set_virtualbox | def _set_virtualbox(self):
'''
a method to set virtualbox environment variables for docker-machine
:return: True
'''
from os import environ
if not environ.get('DOCKER_CERT_PATH'):
import re
sys_command = 'docke... | python | def _set_virtualbox(self):
'''
a method to set virtualbox environment variables for docker-machine
:return: True
'''
from os import environ
if not environ.get('DOCKER_CERT_PATH'):
import re
sys_command = 'docke... | [
"def",
"_set_virtualbox",
"(",
"self",
")",
":",
"from",
"os",
"import",
"environ",
"if",
"not",
"environ",
".",
"get",
"(",
"'DOCKER_CERT_PATH'",
")",
":",
"import",
"re",
"sys_command",
"=",
"'docker-machine env %s'",
"%",
"self",
".",
"vbox",
"cmd_output",
... | a method to set virtualbox environment variables for docker-machine
:return: True | [
"a",
"method",
"to",
"set",
"virtualbox",
"environment",
"variables",
"for",
"docker",
"-",
"machine",
":",
"return",
":",
"True"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L158-L181 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._images | def _images(self, sys_output):
''' a helper method for parsing docker image output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
image_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
for i in... | python | def _images(self, sys_output):
''' a helper method for parsing docker image output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
image_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
for i in... | [
"def",
"_images",
"(",
"self",
",",
"sys_output",
")",
":",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"'\\t|\\s{2,}'",
")",
"image_list",
"=",
"[",
"]",
"output_lines",
"=",
"sys_output",
".",
"split",
"(",
"'\\n'",
")",
"column_header... | a helper method for parsing docker image output | [
"a",
"helper",
"method",
"for",
"parsing",
"docker",
"image",
"output"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L183-L200 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._ps | def _ps(self, sys_output):
''' a helper method for parsing docker ps output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
container_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
... | python | def _ps(self, sys_output):
''' a helper method for parsing docker ps output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
container_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
... | [
"def",
"_ps",
"(",
"self",
",",
"sys_output",
")",
":",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"'\\t|\\s{2,}'",
")",
"container_list",
"=",
"[",
"]",
"output_lines",
"=",
"sys_output",
".",
"split",
"(",
"'\\n'",
")",
"column_header... | a helper method for parsing docker ps output | [
"a",
"helper",
"method",
"for",
"parsing",
"docker",
"ps",
"output"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L202-L226 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient._synopsis | def _synopsis(self, container_settings, container_status=''):
''' a helper method for summarizing container settings '''
# compose default response
settings = {
'container_status': container_settings['State']['Status'],
'container_exit': container_settings['State... | python | def _synopsis(self, container_settings, container_status=''):
''' a helper method for summarizing container settings '''
# compose default response
settings = {
'container_status': container_settings['State']['Status'],
'container_exit': container_settings['State... | [
"def",
"_synopsis",
"(",
"self",
",",
"container_settings",
",",
"container_status",
"=",
"''",
")",
":",
"# compose default response\r",
"settings",
"=",
"{",
"'container_status'",
":",
"container_settings",
"[",
"'State'",
"]",
"[",
"'Status'",
"]",
",",
"'conta... | a helper method for summarizing container settings | [
"a",
"helper",
"method",
"for",
"summarizing",
"container",
"settings"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L228-L283 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.images | def images(self):
'''
a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE':... | python | def images(self):
'''
a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE':... | [
"def",
"images",
"(",
"self",
")",
":",
"sys_command",
"=",
"'docker images'",
"sys_output",
"=",
"self",
".",
"command",
"(",
"sys_command",
")",
"image_list",
"=",
"self",
".",
"_images",
"(",
"sys_output",
")",
"return",
"image_list"
] | a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE': '302.7 MB',
'REPOSITORY': 'test1... | [
"a",
"method",
"to",
"list",
"the",
"local",
"docker",
"images",
":",
"return",
":",
"list",
"of",
"dictionaries",
"with",
"available",
"image",
"fields",
"[",
"{",
"CREATED",
":",
"7",
"days",
"ago",
"TAG",
":",
"latest",
"IMAGE",
"ID",
":",
"2298fbaac1... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L285-L305 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.ps | def ps(self):
'''
a method to list the local active docker containers
:return: list of dictionaries with active container fields
[{
'CREATED': '6 minutes ago',
'NAMES': 'flask',
'PORTS': '0.0.0.0:5000->5000/tcp',
... | python | def ps(self):
'''
a method to list the local active docker containers
:return: list of dictionaries with active container fields
[{
'CREATED': '6 minutes ago',
'NAMES': 'flask',
'PORTS': '0.0.0.0:5000->5000/tcp',
... | [
"def",
"ps",
"(",
"self",
")",
":",
"sys_command",
"=",
"'docker ps -a'",
"sys_output",
"=",
"self",
".",
"command",
"(",
"sys_command",
")",
"container_list",
"=",
"self",
".",
"_ps",
"(",
"sys_output",
")",
"return",
"container_list"
] | a method to list the local active docker containers
:return: list of dictionaries with active container fields
[{
'CREATED': '6 minutes ago',
'NAMES': 'flask',
'PORTS': '0.0.0.0:5000->5000/tcp',
'CONTAINER ID': '38eb0bbeb2e5',
... | [
"a",
"method",
"to",
"list",
"the",
"local",
"active",
"docker",
"containers",
":",
"return",
":",
"list",
"of",
"dictionaries",
"with",
"active",
"container",
"fields",
"[",
"{",
"CREATED",
":",
"6",
"minutes",
"ago",
"NAMES",
":",
"flask",
"PORTS",
":",
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L307-L329 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.network_ls | def network_ls(self):
'''
a method to list the available networks
:return: list of dictionaries with docker network fields
[{
'NETWORK ID': '3007476acfe5',
'NAME': 'bridge',
'DRIVER': 'bridge',
'SCOPE':... | python | def network_ls(self):
'''
a method to list the available networks
:return: list of dictionaries with docker network fields
[{
'NETWORK ID': '3007476acfe5',
'NAME': 'bridge',
'DRIVER': 'bridge',
'SCOPE':... | [
"def",
"network_ls",
"(",
"self",
")",
":",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"'\\t|\\s{2,}'",
")",
"network_list",
"=",
"[",
"]",
"sys_command",
"=",
"'docker network ls'",
"output_lines",
"=",
"self",
".",
"command",
"(",
"sys_... | a method to list the available networks
:return: list of dictionaries with docker network fields
[{
'NETWORK ID': '3007476acfe5',
'NAME': 'bridge',
'DRIVER': 'bridge',
'SCOPE': 'local'
}] | [
"a",
"method",
"to",
"list",
"the",
"available",
"networks",
":",
"return",
":",
"list",
"of",
"dictionaries",
"with",
"docker",
"network",
"fields",
"[",
"{",
"NETWORK",
"ID",
":",
"3007476acfe5",
"NAME",
":",
"bridge",
"DRIVER",
":",
"bridge",
"SCOPE",
"... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L331-L362 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.inspect_container | def inspect_container(self, container_alias):
'''
a method to retrieve the settings of a container
:param container_alias: string with name or id of container
:return: dictionary of settings of container
{ TOO MANY TO LIST }
'''
titl... | python | def inspect_container(self, container_alias):
'''
a method to retrieve the settings of a container
:param container_alias: string with name or id of container
:return: dictionary of settings of container
{ TOO MANY TO LIST }
'''
titl... | [
"def",
"inspect_container",
"(",
"self",
",",
"container_alias",
")",
":",
"title",
"=",
"'%s.inspect_container'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'container_alias'",
":",
"container_alias",
"}",
"for... | a method to retrieve the settings of a container
:param container_alias: string with name or id of container
:return: dictionary of settings of container
{ TOO MANY TO LIST } | [
"a",
"method",
"to",
"retrieve",
"the",
"settings",
"of",
"a",
"container",
":",
"param",
"container_alias",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"container",
":",
"return",
":",
"dictionary",
"of",
"settings",
"of",
"container",
"{",
"TOO",
"M... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L364-L391 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.inspect_image | def inspect_image(self, image_name, image_tag=''):
'''
a method to retrieve the settings of an image
:param image_name: string with name or id of image
:param image_tag: [optional] string with tag associated with image
:return: dictionary of settings of imag... | python | def inspect_image(self, image_name, image_tag=''):
'''
a method to retrieve the settings of an image
:param image_name: string with name or id of image
:param image_tag: [optional] string with tag associated with image
:return: dictionary of settings of imag... | [
"def",
"inspect_image",
"(",
"self",
",",
"image_name",
",",
"image_tag",
"=",
"''",
")",
":",
"title",
"=",
"'%s.inspect_image'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'image_name'",
":",
"image_name",... | a method to retrieve the settings of an image
:param image_name: string with name or id of image
:param image_tag: [optional] string with tag associated with image
:return: dictionary of settings of image
{ TOO MANY TO LIST } | [
"a",
"method",
"to",
"retrieve",
"the",
"settings",
"of",
"an",
"image",
":",
"param",
"image_name",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"image",
":",
"param",
"image_tag",
":",
"[",
"optional",
"]",
"string",
"with",
"tag",
"associated",
"w... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L393-L428 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.rm | def rm(self, container_alias):
'''
a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id
'''
title = '%s.rm' % self.__class__.__name__
# validate inputs
... | python | def rm(self, container_alias):
'''
a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id
'''
title = '%s.rm' % self.__class__.__name__
# validate inputs
... | [
"def",
"rm",
"(",
"self",
",",
"container_alias",
")",
":",
"title",
"=",
"'%s.rm'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'container_alias'",
":",
"container_alias",
"}",
"for",
"key",
",",
"value",
... | a method to remove an active container
:param container_alias: string with name or id of container
:return: string with container id | [
"a",
"method",
"to",
"remove",
"an",
"active",
"container",
":",
"param",
"container_alias",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"container",
":",
"return",
":",
"string",
"with",
"container",
"id"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L430-L453 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.ip | def ip(self):
'''
a method to retrieve the ip of system running docker
:return: string with ip address of system
'''
if self.localhost.os.sysname == 'Windows' and float(self.localhost.os.release) < 10:
sys_cmd = 'docker-machine ip %s' % self.vbox
... | python | def ip(self):
'''
a method to retrieve the ip of system running docker
:return: string with ip address of system
'''
if self.localhost.os.sysname == 'Windows' and float(self.localhost.os.release) < 10:
sys_cmd = 'docker-machine ip %s' % self.vbox
... | [
"def",
"ip",
"(",
"self",
")",
":",
"if",
"self",
".",
"localhost",
".",
"os",
".",
"sysname",
"==",
"'Windows'",
"and",
"float",
"(",
"self",
".",
"localhost",
".",
"os",
".",
"release",
")",
"<",
"10",
":",
"sys_cmd",
"=",
"'docker-machine ip %s'",
... | a method to retrieve the ip of system running docker
:return: string with ip address of system | [
"a",
"method",
"to",
"retrieve",
"the",
"ip",
"of",
"system",
"running",
"docker",
":",
"return",
":",
"string",
"with",
"ip",
"address",
"of",
"system"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L480-L494 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.command | def command(self, sys_command):
'''
a method to run a system command in a separate shell
:param sys_command: string with docker command
:return: string output from docker
'''
title = '%s.command' % self.__class__.__name__
# validate inputs
... | python | def command(self, sys_command):
'''
a method to run a system command in a separate shell
:param sys_command: string with docker command
:return: string output from docker
'''
title = '%s.command' % self.__class__.__name__
# validate inputs
... | [
"def",
"command",
"(",
"self",
",",
"sys_command",
")",
":",
"title",
"=",
"'%s.command'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'sys_command'",
":",
"sys_command",
"}",
"for",
"key",
",",
"value",
... | a method to run a system command in a separate shell
:param sys_command: string with docker command
:return: string output from docker | [
"a",
"method",
"to",
"run",
"a",
"system",
"command",
"in",
"a",
"separate",
"shell",
":",
"param",
"sys_command",
":",
"string",
"with",
"docker",
"command",
":",
"return",
":",
"string",
"output",
"from",
"docker"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L537-L562 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.synopsis | def synopsis(self, container_alias):
'''
a method to summarize key configuration settings required for docker compose
:param container_alias: string with name or id of container
:return: dictionary with values required for module configurations
'''
title =... | python | def synopsis(self, container_alias):
'''
a method to summarize key configuration settings required for docker compose
:param container_alias: string with name or id of container
:return: dictionary with values required for module configurations
'''
title =... | [
"def",
"synopsis",
"(",
"self",
",",
"container_alias",
")",
":",
"title",
"=",
"'%s.synopsis'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'container_alias'",
":",
"container_alias",
"}",
"for",
"key",
",",... | a method to summarize key configuration settings required for docker compose
:param container_alias: string with name or id of container
:return: dictionary with values required for module configurations | [
"a",
"method",
"to",
"summarize",
"key",
"configuration",
"settings",
"required",
"for",
"docker",
"compose",
":",
"param",
"container_alias",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"container",
":",
"return",
":",
"dictionary",
"with",
"values",
"re... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L564-L589 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.enter | def enter(self, container_alias):
'''
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
'''
title = '%s.enter' % self.__class__.__name__
# validate inputs
... | python | def enter(self, container_alias):
'''
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
'''
title = '%s.enter' % self.__class__.__name__
# validate inputs
... | [
"def",
"enter",
"(",
"self",
",",
"container_alias",
")",
":",
"title",
"=",
"'%s.enter'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'container_alias'",
":",
"container_alias",
"}",
"for",
"key",
",",
"va... | a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None | [
"a",
"method",
"to",
"open",
"up",
"a",
"terminal",
"inside",
"a",
"running",
"container",
":",
"param",
"container_alias",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"container",
":",
"return",
":",
"None"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L591-L617 |
collectiveacuity/labPack | labpack/platforms/docker.py | dockerClient.run | def run(self, image_name, container_alias, image_tag='', environmental_variables=None, mapped_ports=None, mounted_volumes=None, start_command='', network_name='', run_flags=''):
'''
a method to start a local container
:param image_name: string with name or id of image
:param... | python | def run(self, image_name, container_alias, image_tag='', environmental_variables=None, mapped_ports=None, mounted_volumes=None, start_command='', network_name='', run_flags=''):
'''
a method to start a local container
:param image_name: string with name or id of image
:param... | [
"def",
"run",
"(",
"self",
",",
"image_name",
",",
"container_alias",
",",
"image_tag",
"=",
"''",
",",
"environmental_variables",
"=",
"None",
",",
"mapped_ports",
"=",
"None",
",",
"mounted_volumes",
"=",
"None",
",",
"start_command",
"=",
"''",
",",
"netw... | a method to start a local container
:param image_name: string with name or id of image
:param container_alias: string with name to assign to container
:param image_tag: [optional] string with tag assigned to image
:param environmental_variables: [optional] dictionary of envvar fiel... | [
"a",
"method",
"to",
"start",
"a",
"local",
"container",
":",
"param",
"image_name",
":",
"string",
"with",
"name",
"or",
"id",
"of",
"image",
":",
"param",
"container_alias",
":",
"string",
"with",
"name",
"to",
"assign",
"to",
"container",
":",
"param",
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L619-L747 |
ikalnytskyi/dooku | dooku/itertools.py | chunk_by | def chunk_by(n, iterable, fillvalue=None):
"""
Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chun... | python | def chunk_by(n, iterable, fillvalue=None):
"""
Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chun... | [
"def",
"chunk_by",
"(",
"n",
",",
"iterable",
",",
"fillvalue",
"=",
"None",
")",
":",
"args",
"=",
"[",
"iter",
"(",
"iterable",
")",
"]",
"*",
"n",
"return",
"zip_longest",
"(",
"*",
"args",
",",
"fillvalue",
"=",
"fillvalue",
")"
] | Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chunk size number
:param iterable: (iterator) an input ... | [
"Iterate",
"over",
"a",
"given",
"iterable",
"by",
"n",
"elements",
"at",
"a",
"time",
"."
] | train | https://github.com/ikalnytskyi/dooku/blob/77e6c82c9c41211c86ee36ae5e591d477945fedf/dooku/itertools.py#L20-L37 |
pip-services3-python/pip-services3-components-python | pip_services3_components/config/ConfigReader.py | ConfigReader.configure | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
parameters = config.get_section("parameters")
if len(parameters) > 0:
self._parameters = parameters | python | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
parameters = config.get_section("parameters")
if len(parameters) > 0:
self._parameters = parameters | [
"def",
"configure",
"(",
"self",
",",
"config",
")",
":",
"parameters",
"=",
"config",
".",
"get_section",
"(",
"\"parameters\"",
")",
"if",
"len",
"(",
"parameters",
")",
">",
"0",
":",
"self",
".",
"_parameters",
"=",
"parameters"
] | Configures component by passing configuration parameters.
:param config: configuration parameters to be set. | [
"Configures",
"component",
"by",
"passing",
"configuration",
"parameters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/config/ConfigReader.py#L35-L43 |
pip-services3-python/pip-services3-components-python | pip_services3_components/config/ConfigReader.py | ConfigReader._parameterize | def _parameterize(self, config, parameters):
"""
Parameterized configuration template given as string with dynamic parameters.
:param config: a string with configuration template to be parameterized
:param parameters: dynamic parameters to inject into the template
:return: a p... | python | def _parameterize(self, config, parameters):
"""
Parameterized configuration template given as string with dynamic parameters.
:param config: a string with configuration template to be parameterized
:param parameters: dynamic parameters to inject into the template
:return: a p... | [
"def",
"_parameterize",
"(",
"self",
",",
"config",
",",
"parameters",
")",
":",
"parameters",
"=",
"self",
".",
"_parameters",
".",
"override",
"(",
"parameters",
")",
"return",
"pystache",
".",
"render",
"(",
"config",
",",
"parameters",
")"
] | Parameterized configuration template given as string with dynamic parameters.
:param config: a string with configuration template to be parameterized
:param parameters: dynamic parameters to inject into the template
:return: a parameterized configuration string. | [
"Parameterized",
"configuration",
"template",
"given",
"as",
"string",
"with",
"dynamic",
"parameters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/config/ConfigReader.py#L58-L69 |
toastdriven/alligator | alligator/gator.py | Gator.build_backend | def build_backend(self, conn_string):
"""
Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecti... | python | def build_backend(self, conn_string):
"""
Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecti... | [
"def",
"build_backend",
"(",
"self",
",",
"conn_string",
")",
":",
"backend_name",
",",
"_",
"=",
"conn_string",
".",
"split",
"(",
"':'",
",",
"1",
")",
"backend_path",
"=",
"'alligator.backends.{}_backend'",
".",
"format",
"(",
"backend_name",
")",
"client_c... | Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecting to the queue. Passed along
to the backend.
... | [
"Given",
"a",
"DSN",
"returns",
"an",
"instantiated",
"backend",
"class",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L51-L70 |
toastdriven/alligator | alligator/gator.py | Gator.push | def push(self, task, func, *args, **kwargs):
"""
Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
... | python | def push(self, task, func, *args, **kwargs):
"""
Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
... | [
"def",
"push",
"(",
"self",
",",
"task",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task",
".",
"to_call",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"task",
".",
"serialize",
"(",
")",
"... | Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
If the ``Task`` has the ``async = False`` option, the task wil... | [
"Pushes",
"a",
"configured",
"task",
"onto",
"the",
"queue",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L80-L123 |
toastdriven/alligator | alligator/gator.py | Gator.pop | def pop(self):
"""
Pops a task off the front of the queue & runs it.
Typically, you'll favor using a ``Worker`` to handle processing the
queue (to constantly consume). However, if you need to custom-process
the queue in-order, this method is useful.
Ex::
# ... | python | def pop(self):
"""
Pops a task off the front of the queue & runs it.
Typically, you'll favor using a ``Worker`` to handle processing the
queue (to constantly consume). However, if you need to custom-process
the queue in-order, this method is useful.
Ex::
# ... | [
"def",
"pop",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"backend",
".",
"pop",
"(",
"self",
".",
"queue_name",
")",
"if",
"data",
":",
"task",
"=",
"self",
".",
"task_class",
".",
"deserialize",
"(",
"data",
")",
"return",
"self",
".",
"exec... | Pops a task off the front of the queue & runs it.
Typically, you'll favor using a ``Worker`` to handle processing the
queue (to constantly consume). However, if you need to custom-process
the queue in-order, this method is useful.
Ex::
# Tasks were previously added, maybe ... | [
"Pops",
"a",
"task",
"off",
"the",
"front",
"of",
"the",
"queue",
"&",
"runs",
"it",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L125-L145 |
toastdriven/alligator | alligator/gator.py | Gator.get | def get(self, task_id):
"""
Gets a specific task, by ``task_id`` off the queue & runs it.
Using this is not as performant (because it has to search the queue),
but can be useful if you need to specifically handle a task *right now*.
Ex::
# Tasks were previously add... | python | def get(self, task_id):
"""
Gets a specific task, by ``task_id`` off the queue & runs it.
Using this is not as performant (because it has to search the queue),
but can be useful if you need to specifically handle a task *right now*.
Ex::
# Tasks were previously add... | [
"def",
"get",
"(",
"self",
",",
"task_id",
")",
":",
"data",
"=",
"self",
".",
"backend",
".",
"get",
"(",
"self",
".",
"queue_name",
",",
"task_id",
")",
"if",
"data",
":",
"task",
"=",
"self",
".",
"task_class",
".",
"deserialize",
"(",
"data",
"... | Gets a specific task, by ``task_id`` off the queue & runs it.
Using this is not as performant (because it has to search the queue),
but can be useful if you need to specifically handle a task *right now*.
Ex::
# Tasks were previously added, maybe by a different process or
... | [
"Gets",
"a",
"specific",
"task",
"by",
"task_id",
"off",
"the",
"queue",
"&",
"runs",
"it",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L147-L169 |
toastdriven/alligator | alligator/gator.py | Gator.cancel | def cancel(self, task_id):
"""
Takes an existing task & cancels it before it is processed.
Returns the canceled task, as that could be useful in creating a new
task.
Ex::
task = gator.task(add, 18, 9)
# Whoops, didn't mean to do that.
gator... | python | def cancel(self, task_id):
"""
Takes an existing task & cancels it before it is processed.
Returns the canceled task, as that could be useful in creating a new
task.
Ex::
task = gator.task(add, 18, 9)
# Whoops, didn't mean to do that.
gator... | [
"def",
"cancel",
"(",
"self",
",",
"task_id",
")",
":",
"data",
"=",
"self",
".",
"backend",
".",
"get",
"(",
"self",
".",
"queue_name",
",",
"task_id",
")",
"if",
"data",
":",
"task",
"=",
"self",
".",
"task_class",
".",
"deserialize",
"(",
"data",
... | Takes an existing task & cancels it before it is processed.
Returns the canceled task, as that could be useful in creating a new
task.
Ex::
task = gator.task(add, 18, 9)
# Whoops, didn't mean to do that.
gator.cancel(task.task_id)
:param task_id: ... | [
"Takes",
"an",
"existing",
"task",
"&",
"cancels",
"it",
"before",
"it",
"is",
"processed",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L171-L195 |
toastdriven/alligator | alligator/gator.py | Gator.execute | def execute(self, task):
"""
Given a task instance, this runs it.
This includes handling retries & re-raising exceptions.
Ex::
task = Task(async=False, retries=5)
task.to_call(add, 101, 35)
finished_task = gator.execute(task)
:param task_id... | python | def execute(self, task):
"""
Given a task instance, this runs it.
This includes handling retries & re-raising exceptions.
Ex::
task = Task(async=False, retries=5)
task.to_call(add, 101, 35)
finished_task = gator.execute(task)
:param task_id... | [
"def",
"execute",
"(",
"self",
",",
"task",
")",
":",
"try",
":",
"return",
"task",
".",
"run",
"(",
")",
"except",
"Exception",
":",
"if",
"task",
".",
"retries",
">",
"0",
":",
"task",
".",
"retries",
"-=",
"1",
"task",
".",
"to_retrying",
"(",
... | Given a task instance, this runs it.
This includes handling retries & re-raising exceptions.
Ex::
task = Task(async=False, retries=5)
task.to_call(add, 101, 35)
finished_task = gator.execute(task)
:param task_id: The identifier of the task to process
... | [
"Given",
"a",
"task",
"instance",
"this",
"runs",
"it",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L197-L232 |
toastdriven/alligator | alligator/gator.py | Gator.task | def task(self, func, *args, **kwargs):
"""
Pushes a task onto the queue.
This will instantiate a ``Gator.task_class`` instance, configure
the callable & its arguments, then push it onto the queue.
You'll typically want to use either this method or the ``Gator.options``
... | python | def task(self, func, *args, **kwargs):
"""
Pushes a task onto the queue.
This will instantiate a ``Gator.task_class`` instance, configure
the callable & its arguments, then push it onto the queue.
You'll typically want to use either this method or the ``Gator.options``
... | [
"def",
"task",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task",
"=",
"self",
".",
"task_class",
"(",
")",
"return",
"self",
".",
"push",
"(",
"task",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | Pushes a task onto the queue.
This will instantiate a ``Gator.task_class`` instance, configure
the callable & its arguments, then push it onto the queue.
You'll typically want to use either this method or the ``Gator.options``
context manager (if you need to configure the ``Task`` argu... | [
"Pushes",
"a",
"task",
"onto",
"the",
"queue",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L234-L261 |
toastdriven/alligator | alligator/gator.py | Options.task | def task(self, func, *args, **kwargs):
"""
Pushes a task onto the queue (with the specified options).
This will instantiate a ``Gator.task_class`` instance, configure the
task execution options, configure the callable & its arguments, then
push it onto the queue.
You'll... | python | def task(self, func, *args, **kwargs):
"""
Pushes a task onto the queue (with the specified options).
This will instantiate a ``Gator.task_class`` instance, configure the
task execution options, configure the callable & its arguments, then
push it onto the queue.
You'll... | [
"def",
"task",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task",
"=",
"self",
".",
"gator",
".",
"task_class",
"(",
"*",
"*",
"self",
".",
"task_kwargs",
")",
"return",
"self",
".",
"gator",
".",
"push",
"(",
... | Pushes a task onto the queue (with the specified options).
This will instantiate a ``Gator.task_class`` instance, configure the
task execution options, configure the callable & its arguments, then
push it onto the queue.
You'll typically call this method when specifying advanced option... | [
"Pushes",
"a",
"task",
"onto",
"the",
"queue",
"(",
"with",
"the",
"specified",
"options",
")",
"."
] | train | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/gator.py#L312-L334 |
ronaldguillen/wave | wave/fields.py | is_simple_callable | def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
function = inspect.isfunction(obj)
method = inspect.ismethod(obj)
if not (function or method):
return False
args, _, _, defaults = inspect.getargspec(obj)
len_args = len(args) if func... | python | def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
function = inspect.isfunction(obj)
method = inspect.ismethod(obj)
if not (function or method):
return False
args, _, _, defaults = inspect.getargspec(obj)
len_args = len(args) if func... | [
"def",
"is_simple_callable",
"(",
"obj",
")",
":",
"function",
"=",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"method",
"=",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
"if",
"not",
"(",
"function",
"or",
"method",
")",
":",
"return",
"False",
"a... | True if the object is a callable that takes no arguments. | [
"True",
"if",
"the",
"object",
"is",
"a",
"callable",
"that",
"takes",
"no",
"arguments",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L49-L62 |
ronaldguillen/wave | wave/fields.py | get_attribute | def get_attribute(instance, attrs):
"""
Similar to Python's built in `getattr(instance, attr)`,
but takes a list of nested attributes, instead of a single attribute.
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
if instance is None:
... | python | def get_attribute(instance, attrs):
"""
Similar to Python's built in `getattr(instance, attr)`,
but takes a list of nested attributes, instead of a single attribute.
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
if instance is None:
... | [
"def",
"get_attribute",
"(",
"instance",
",",
"attrs",
")",
":",
"for",
"attr",
"in",
"attrs",
":",
"if",
"instance",
"is",
"None",
":",
"# Break out early if we get `None` at any point in a nested lookup.",
"return",
"None",
"try",
":",
"if",
"isinstance",
"(",
"... | Similar to Python's built in `getattr(instance, attr)`,
but takes a list of nested attributes, instead of a single attribute.
Also accepts either attribute lookup on objects or dictionary lookups. | [
"Similar",
"to",
"Python",
"s",
"built",
"in",
"getattr",
"(",
"instance",
"attr",
")",
"but",
"takes",
"a",
"list",
"of",
"nested",
"attributes",
"instead",
"of",
"a",
"single",
"attribute",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L65-L92 |
ronaldguillen/wave | wave/fields.py | set_value | def set_value(dictionary, keys, value):
"""
Similar to Python's built in `dictionary[key] = value`,
but takes a list of nested keys instead of a single key.
set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
set_value({'a': 1}, ['x', 'y'], 2)... | python | def set_value(dictionary, keys, value):
"""
Similar to Python's built in `dictionary[key] = value`,
but takes a list of nested keys instead of a single key.
set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
set_value({'a': 1}, ['x', 'y'], 2)... | [
"def",
"set_value",
"(",
"dictionary",
",",
"keys",
",",
"value",
")",
":",
"if",
"not",
"keys",
":",
"dictionary",
".",
"update",
"(",
"value",
")",
"return",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"if",
"key",
"not",
"in",
"d... | Similar to Python's built in `dictionary[key] = value`,
but takes a list of nested keys instead of a single key.
set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} | [
"Similar",
"to",
"Python",
"s",
"built",
"in",
"dictionary",
"[",
"key",
"]",
"=",
"value",
"but",
"takes",
"a",
"list",
"of",
"nested",
"keys",
"instead",
"of",
"a",
"single",
"key",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L95-L113 |
ronaldguillen/wave | wave/fields.py | to_choices_dict | def to_choices_dict(choices):
"""
Convert choices into key/value dicts.
pairwise_choices([1]) -> {1: 1}
pairwise_choices([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'}
pairwise_choices([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2nd'}}
"""
# Allow single, paired or grouped ... | python | def to_choices_dict(choices):
"""
Convert choices into key/value dicts.
pairwise_choices([1]) -> {1: 1}
pairwise_choices([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'}
pairwise_choices([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2nd'}}
"""
# Allow single, paired or grouped ... | [
"def",
"to_choices_dict",
"(",
"choices",
")",
":",
"# Allow single, paired or grouped choices style:",
"# choices = [1, 2, 3]",
"# choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]",
"# choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')]",
"ret",
"=",
"OrderedDict",
... | Convert choices into key/value dicts.
pairwise_choices([1]) -> {1: 1}
pairwise_choices([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'}
pairwise_choices([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2nd'}} | [
"Convert",
"choices",
"into",
"key",
"/",
"value",
"dicts",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L116-L141 |
ronaldguillen/wave | wave/fields.py | flatten_choices_dict | def flatten_choices_dict(choices):
"""
Convert a group choices dict into a flat dict of choices.
flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
"""
ret = OrderedDict()
for key, value in choices.items():
... | python | def flatten_choices_dict(choices):
"""
Convert a group choices dict into a flat dict of choices.
flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
"""
ret = OrderedDict()
for key, value in choices.items():
... | [
"def",
"flatten_choices_dict",
"(",
"choices",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"choices",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"# grouped choices (category, s... | Convert a group choices dict into a flat dict of choices.
flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} | [
"Convert",
"a",
"group",
"choices",
"dict",
"into",
"a",
"flat",
"dict",
"of",
"choices",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L144-L160 |
ronaldguillen/wave | wave/fields.py | iter_options | def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
"""
Helper function for options and option groups in templates.
"""
class StartOptionGroup(object):
start_option_group = True
end_option_group = False
def __init__(self, label):
self.label = label
... | python | def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
"""
Helper function for options and option groups in templates.
"""
class StartOptionGroup(object):
start_option_group = True
end_option_group = False
def __init__(self, label):
self.label = label
... | [
"def",
"iter_options",
"(",
"grouped_choices",
",",
"cutoff",
"=",
"None",
",",
"cutoff_text",
"=",
"None",
")",
":",
"class",
"StartOptionGroup",
"(",
"object",
")",
":",
"start_option_group",
"=",
"True",
"end_option_group",
"=",
"False",
"def",
"__init__",
... | Helper function for options and option groups in templates. | [
"Helper",
"function",
"for",
"options",
"and",
"option",
"groups",
"in",
"templates",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L163-L207 |
ronaldguillen/wave | wave/fields.py | Field.get_value | def get_value(self, dictionary):
"""
Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value.
"""
if html.is_html_input(dictionary):
# HTML forms will represent empty fields as '', and cannot
... | python | def get_value(self, dictionary):
"""
Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value.
"""
if html.is_html_input(dictionary):
# HTML forms will represent empty fields as '', and cannot
... | [
"def",
"get_value",
"(",
"self",
",",
"dictionary",
")",
":",
"if",
"html",
".",
"is_html_input",
"(",
"dictionary",
")",
":",
"# HTML forms will represent empty fields as '', and cannot",
"# represent None or False values directly.",
"if",
"self",
".",
"field_name",
"not... | Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value. | [
"Given",
"the",
"*",
"incoming",
"*",
"primitive",
"data",
"return",
"the",
"value",
"for",
"this",
"field",
"that",
"should",
"be",
"validated",
"and",
"transformed",
"to",
"a",
"native",
"value",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L375-L397 |
ronaldguillen/wave | wave/fields.py | Field.get_attribute | def get_attribute(self, instance):
"""
Given the *outgoing* object instance, return the primitive value
that should be used for this field.
"""
try:
return get_attribute(instance, self.source_attrs)
except (KeyError, AttributeError) as exc:
if not ... | python | def get_attribute(self, instance):
"""
Given the *outgoing* object instance, return the primitive value
that should be used for this field.
"""
try:
return get_attribute(instance, self.source_attrs)
except (KeyError, AttributeError) as exc:
if not ... | [
"def",
"get_attribute",
"(",
"self",
",",
"instance",
")",
":",
"try",
":",
"return",
"get_attribute",
"(",
"instance",
",",
"self",
".",
"source_attrs",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"exc",
":",
"if",
"not",
"self",
"... | Given the *outgoing* object instance, return the primitive value
that should be used for this field. | [
"Given",
"the",
"*",
"outgoing",
"*",
"object",
"instance",
"return",
"the",
"primitive",
"value",
"that",
"should",
"be",
"used",
"for",
"this",
"field",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L399-L422 |
ronaldguillen/wave | wave/fields.py | Field.get_default | def get_default(self):
"""
Return the default value to use when validating data if no input
is provided for this field.
If a default has not been set for this field then this will simply
return `empty`, indicating that no value should be set in the
validated data for thi... | python | def get_default(self):
"""
Return the default value to use when validating data if no input
is provided for this field.
If a default has not been set for this field then this will simply
return `empty`, indicating that no value should be set in the
validated data for thi... | [
"def",
"get_default",
"(",
"self",
")",
":",
"if",
"self",
".",
"default",
"is",
"empty",
":",
"raise",
"SkipField",
"(",
")",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"default",
",",
"'set_context'",
... | Return the default value to use when validating data if no input
is provided for this field.
If a default has not been set for this field then this will simply
return `empty`, indicating that no value should be set in the
validated data for this field. | [
"Return",
"the",
"default",
"value",
"to",
"use",
"when",
"validating",
"data",
"if",
"no",
"input",
"is",
"provided",
"for",
"this",
"field",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L424-L439 |
ronaldguillen/wave | wave/fields.py | Field.validate_empty_values | def validate_empty_values(self, data):
"""
Validate empty values, and either:
* Raise `ValidationError`, indicating invalid data.
* Raise `SkipField`, indicating that the field should be ignored.
* Return (True, data), indicating an empty value that should be
returned ... | python | def validate_empty_values(self, data):
"""
Validate empty values, and either:
* Raise `ValidationError`, indicating invalid data.
* Raise `SkipField`, indicating that the field should be ignored.
* Return (True, data), indicating an empty value that should be
returned ... | [
"def",
"validate_empty_values",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"read_only",
":",
"return",
"(",
"True",
",",
"self",
".",
"get_default",
"(",
")",
")",
"if",
"data",
"is",
"empty",
":",
"if",
"getattr",
"(",
"self",
".",
"root... | Validate empty values, and either:
* Raise `ValidationError`, indicating invalid data.
* Raise `SkipField`, indicating that the field should be ignored.
* Return (True, data), indicating an empty value that should be
returned without any further validation being applied.
* Ret... | [
"Validate",
"empty",
"values",
"and",
"either",
":"
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L441-L467 |
ronaldguillen/wave | wave/fields.py | Field.run_validators | def run_validators(self, value):
"""
Test the given value against all the validators on the field,
and either raise a `ValidationError` or simply return.
"""
errors = []
for validator in self.validators:
if hasattr(validator, 'set_context'):
va... | python | def run_validators(self, value):
"""
Test the given value against all the validators on the field,
and either raise a `ValidationError` or simply return.
"""
errors = []
for validator in self.validators:
if hasattr(validator, 'set_context'):
va... | [
"def",
"run_validators",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"validator",
"in",
"self",
".",
"validators",
":",
"if",
"hasattr",
"(",
"validator",
",",
"'set_context'",
")",
":",
"validator",
".",
"set_context",
"(",
"sel... | Test the given value against all the validators on the field,
and either raise a `ValidationError` or simply return. | [
"Test",
"the",
"given",
"value",
"against",
"all",
"the",
"validators",
"on",
"the",
"field",
"and",
"either",
"raise",
"a",
"ValidationError",
"or",
"simply",
"return",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L486-L508 |
ronaldguillen/wave | wave/fields.py | Field.to_representation | def to_representation(self, value):
"""
Transform the *outgoing* native value into primitive data.
"""
raise NotImplementedError(
'{cls}.to_representation() must be implemented for field '
'{field_name}. If you do not need to support write operations '
... | python | def to_representation(self, value):
"""
Transform the *outgoing* native value into primitive data.
"""
raise NotImplementedError(
'{cls}.to_representation() must be implemented for field '
'{field_name}. If you do not need to support write operations '
... | [
"def",
"to_representation",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
"'{cls}.to_representation() must be implemented for field '",
"'{field_name}. If you do not need to support write operations '",
"'you probably want to subclass `ReadOnlyField` instead.'",... | Transform the *outgoing* native value into primitive data. | [
"Transform",
"the",
"*",
"outgoing",
"*",
"native",
"value",
"into",
"primitive",
"data",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L520-L531 |
ronaldguillen/wave | wave/fields.py | Field.fail | def fail(self, key, **kwargs):
"""
A helper method that simply raises a validation error.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, ke... | python | def fail(self, key, **kwargs):
"""
A helper method that simply raises a validation error.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, ke... | [
"def",
"fail",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"msg",
"=",
"self",
".",
"error_messages",
"[",
"key",
"]",
"except",
"KeyError",
":",
"class_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"msg",
"=",
... | A helper method that simply raises a validation error. | [
"A",
"helper",
"method",
"that",
"simply",
"raises",
"a",
"validation",
"error",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L533-L544 |
ronaldguillen/wave | wave/fields.py | Field.root | def root(self):
"""
Returns the top-level serializer for this field.
"""
root = self
while root.parent is not None:
root = root.parent
return root | python | def root(self):
"""
Returns the top-level serializer for this field.
"""
root = self
while root.parent is not None:
root = root.parent
return root | [
"def",
"root",
"(",
"self",
")",
":",
"root",
"=",
"self",
"while",
"root",
".",
"parent",
"is",
"not",
"None",
":",
"root",
"=",
"root",
".",
"parent",
"return",
"root"
] | Returns the top-level serializer for this field. | [
"Returns",
"the",
"top",
"-",
"level",
"serializer",
"for",
"this",
"field",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L547-L554 |
ronaldguillen/wave | wave/fields.py | DecimalField.to_internal_value | def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
instance.
"""
data = smart_text(data).strip()
if len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
value = decima... | python | def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
instance.
"""
data = smart_text(data).strip()
if len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
value = decima... | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"smart_text",
"(",
"data",
")",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"data",
")",
">",
"self",
".",
"MAX_STRING_LENGTH",
":",
"self",
".",
"fail",
"(",
"'max_string_lengt... | Validate that the input is a decimal number and return a Decimal
instance. | [
"Validate",
"that",
"the",
"input",
"is",
"a",
"decimal",
"number",
"and",
"return",
"a",
"Decimal",
"instance",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L917-L940 |
ronaldguillen/wave | wave/fields.py | DecimalField.validate_precision | def validate_precision(self, value):
"""
Ensure that there are no more than max_digits in the number, and no
more than decimal_places digits after the decimal point.
Override this method to disable the precision validation for input
values or to enhance it in any way you need to... | python | def validate_precision(self, value):
"""
Ensure that there are no more than max_digits in the number, and no
more than decimal_places digits after the decimal point.
Override this method to disable the precision validation for input
values or to enhance it in any way you need to... | [
"def",
"validate_precision",
"(",
"self",
",",
"value",
")",
":",
"sign",
",",
"digittuple",
",",
"exponent",
"=",
"value",
".",
"as_tuple",
"(",
")",
"if",
"exponent",
">=",
"0",
":",
"# 1234500.0",
"total_digits",
"=",
"len",
"(",
"digittuple",
")",
"+... | Ensure that there are no more than max_digits in the number, and no
more than decimal_places digits after the decimal point.
Override this method to disable the precision validation for input
values or to enhance it in any way you need to. | [
"Ensure",
"that",
"there",
"are",
"no",
"more",
"than",
"max_digits",
"in",
"the",
"number",
"and",
"no",
"more",
"than",
"decimal_places",
"digits",
"after",
"the",
"decimal",
"point",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L942-L975 |
ronaldguillen/wave | wave/fields.py | DecimalField.quantize | def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
context = decimal.getcontext().copy()
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context) | python | def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
context = decimal.getcontext().copy()
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context) | [
"def",
"quantize",
"(",
"self",
",",
"value",
")",
":",
"context",
"=",
"decimal",
".",
"getcontext",
"(",
")",
".",
"copy",
"(",
")",
"context",
".",
"prec",
"=",
"self",
".",
"max_digits",
"return",
"value",
".",
"quantize",
"(",
"decimal",
".",
"D... | Quantize the decimal value to the configured precision. | [
"Quantize",
"the",
"decimal",
"value",
"to",
"the",
"configured",
"precision",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L989-L997 |
ronaldguillen/wave | wave/fields.py | DateTimeField.enforce_timezone | def enforce_timezone(self, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
if (field_time... | python | def enforce_timezone(self, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
if (field_time... | [
"def",
"enforce_timezone",
"(",
"self",
",",
"value",
")",
":",
"field_timezone",
"=",
"getattr",
"(",
"self",
",",
"'timezone'",
",",
"self",
".",
"default_timezone",
"(",
")",
")",
"if",
"(",
"field_timezone",
"is",
"not",
"None",
")",
"and",
"not",
"t... | When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes. | [
"When",
"self",
".",
"default_timezone",
"is",
"None",
"always",
"return",
"naive",
"datetimes",
".",
"When",
"self",
".",
"default_timezone",
"is",
"not",
"None",
"always",
"return",
"aware",
"datetimes",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L1018-L1029 |
ronaldguillen/wave | wave/fields.py | ListField.to_internal_value | def to_internal_value(self, data):
"""
List of dicts of native values <- List of dicts of primitive datatypes.
"""
if html.is_html_input(data):
data = html.parse_html_list(data)
if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data... | python | def to_internal_value(self, data):
"""
List of dicts of native values <- List of dicts of primitive datatypes.
"""
if html.is_html_input(data):
data = html.parse_html_list(data)
if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data... | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"html",
".",
"is_html_input",
"(",
"data",
")",
":",
"data",
"=",
"html",
".",
"parse_html_list",
"(",
"data",
")",
"if",
"isinstance",
"(",
"data",
",",
"type",
"(",
"''",
")",
")... | List of dicts of native values <- List of dicts of primitive datatypes. | [
"List",
"of",
"dicts",
"of",
"native",
"values",
"<",
"-",
"List",
"of",
"dicts",
"of",
"primitive",
"datatypes",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L1466-L1476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.