id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
246,400 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
set_json
|
def set_json(domain, action, filename=False, record=False):
"""Convert text file to JSON.
Arguments:
domain: domain name of updating target
action: True ; for PUT/POST HTTP method
False; for DELETE HTTP method
filename: text file of bulk updating (default is False)
record: json record of updating single record (default is False)
"""
o = JSONConverter(domain)
if filename:
# for 'bulk_create/bulk_delete'
with open(filename, 'r') as f:
o.separate_input_file(f)
for item in o.separated_list:
o.read_records(item.splitlines())
o.generata_data(action)
elif record:
# for 'create/delete'
o.read_records(record)
o.generata_data(action)
return o.dict_records
|
python
|
def set_json(domain, action, filename=False, record=False):
"""Convert text file to JSON.
Arguments:
domain: domain name of updating target
action: True ; for PUT/POST HTTP method
False; for DELETE HTTP method
filename: text file of bulk updating (default is False)
record: json record of updating single record (default is False)
"""
o = JSONConverter(domain)
if filename:
# for 'bulk_create/bulk_delete'
with open(filename, 'r') as f:
o.separate_input_file(f)
for item in o.separated_list:
o.read_records(item.splitlines())
o.generata_data(action)
elif record:
# for 'create/delete'
o.read_records(record)
o.generata_data(action)
return o.dict_records
|
[
"def",
"set_json",
"(",
"domain",
",",
"action",
",",
"filename",
"=",
"False",
",",
"record",
"=",
"False",
")",
":",
"o",
"=",
"JSONConverter",
"(",
"domain",
")",
"if",
"filename",
":",
"# for 'bulk_create/bulk_delete'",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"o",
".",
"separate_input_file",
"(",
"f",
")",
"for",
"item",
"in",
"o",
".",
"separated_list",
":",
"o",
".",
"read_records",
"(",
"item",
".",
"splitlines",
"(",
")",
")",
"o",
".",
"generata_data",
"(",
"action",
")",
"elif",
"record",
":",
"# for 'create/delete'",
"o",
".",
"read_records",
"(",
"record",
")",
"o",
".",
"generata_data",
"(",
"action",
")",
"return",
"o",
".",
"dict_records"
] |
Convert text file to JSON.
Arguments:
domain: domain name of updating target
action: True ; for PUT/POST HTTP method
False; for DELETE HTTP method
filename: text file of bulk updating (default is False)
record: json record of updating single record (default is False)
|
[
"Convert",
"text",
"file",
"to",
"JSON",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L50-L76
|
246,401 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
get_record_params
|
def get_record_params(args):
"""Get record parameters from command options.
Argument:
args: arguments object
"""
name, rtype, content, ttl, priority = (
args.name, args.rtype, args.content, args.ttl, args.priority)
return name, rtype, content, ttl, priority
|
python
|
def get_record_params(args):
"""Get record parameters from command options.
Argument:
args: arguments object
"""
name, rtype, content, ttl, priority = (
args.name, args.rtype, args.content, args.ttl, args.priority)
return name, rtype, content, ttl, priority
|
[
"def",
"get_record_params",
"(",
"args",
")",
":",
"name",
",",
"rtype",
",",
"content",
",",
"ttl",
",",
"priority",
"=",
"(",
"args",
".",
"name",
",",
"args",
".",
"rtype",
",",
"args",
".",
"content",
",",
"args",
".",
"ttl",
",",
"args",
".",
"priority",
")",
"return",
"name",
",",
"rtype",
",",
"content",
",",
"ttl",
",",
"priority"
] |
Get record parameters from command options.
Argument:
args: arguments object
|
[
"Get",
"record",
"parameters",
"from",
"command",
"options",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L109-L118
|
246,402 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
create
|
def create(args):
"""Create records.
Argument:
args: arguments object
"""
# for PUT HTTP method
action = True
if ((args.__dict__.get('domain') and args.__dict__.get('name')
and args.__dict__.get('rtype') and args.__dict__.get('content'))):
# for create sub-command
domain = args.domain
o = JSONConverter(domain)
name, rtype, content, ttl, priority = get_record_params(args)
record_dict = o.set_record(name, rtype, content, ttl, priority)
json = set_json(domain, action, record=record_dict)
else:
# for bulk_create sub-command
if args.__dict__.get('domain'):
domain = args.domain
else:
domain = check_infile(args.infile)
json = set_json(domain, action, filename=args.infile)
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.create_records(args.server, token, domain, json)
if args.auto_update_soa == 'True':
update_soa_serial(args)
|
python
|
def create(args):
"""Create records.
Argument:
args: arguments object
"""
# for PUT HTTP method
action = True
if ((args.__dict__.get('domain') and args.__dict__.get('name')
and args.__dict__.get('rtype') and args.__dict__.get('content'))):
# for create sub-command
domain = args.domain
o = JSONConverter(domain)
name, rtype, content, ttl, priority = get_record_params(args)
record_dict = o.set_record(name, rtype, content, ttl, priority)
json = set_json(domain, action, record=record_dict)
else:
# for bulk_create sub-command
if args.__dict__.get('domain'):
domain = args.domain
else:
domain = check_infile(args.infile)
json = set_json(domain, action, filename=args.infile)
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.create_records(args.server, token, domain, json)
if args.auto_update_soa == 'True':
update_soa_serial(args)
|
[
"def",
"create",
"(",
"args",
")",
":",
"# for PUT HTTP method",
"action",
"=",
"True",
"if",
"(",
"(",
"args",
".",
"__dict__",
".",
"get",
"(",
"'domain'",
")",
"and",
"args",
".",
"__dict__",
".",
"get",
"(",
"'name'",
")",
"and",
"args",
".",
"__dict__",
".",
"get",
"(",
"'rtype'",
")",
"and",
"args",
".",
"__dict__",
".",
"get",
"(",
"'content'",
")",
")",
")",
":",
"# for create sub-command",
"domain",
"=",
"args",
".",
"domain",
"o",
"=",
"JSONConverter",
"(",
"domain",
")",
"name",
",",
"rtype",
",",
"content",
",",
"ttl",
",",
"priority",
"=",
"get_record_params",
"(",
"args",
")",
"record_dict",
"=",
"o",
".",
"set_record",
"(",
"name",
",",
"rtype",
",",
"content",
",",
"ttl",
",",
"priority",
")",
"json",
"=",
"set_json",
"(",
"domain",
",",
"action",
",",
"record",
"=",
"record_dict",
")",
"else",
":",
"# for bulk_create sub-command",
"if",
"args",
".",
"__dict__",
".",
"get",
"(",
"'domain'",
")",
":",
"domain",
"=",
"args",
".",
"domain",
"else",
":",
"domain",
"=",
"check_infile",
"(",
"args",
".",
"infile",
")",
"json",
"=",
"set_json",
"(",
"domain",
",",
"action",
",",
"filename",
"=",
"args",
".",
"infile",
")",
"password",
"=",
"get_password",
"(",
"args",
")",
"token",
"=",
"connect",
".",
"get_token",
"(",
"args",
".",
"username",
",",
"password",
",",
"args",
".",
"server",
")",
"processing",
".",
"create_records",
"(",
"args",
".",
"server",
",",
"token",
",",
"domain",
",",
"json",
")",
"if",
"args",
".",
"auto_update_soa",
"==",
"'True'",
":",
"update_soa_serial",
"(",
"args",
")"
] |
Create records.
Argument:
args: arguments object
|
[
"Create",
"records",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L173-L208
|
246,403 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
set_option
|
def set_option(prs, keyword, required=False):
"""Set options of command line.
Arguments:
prs: parser object of argparse
keyword: processing keyword
required: True is required option (default is False)
"""
if keyword == 'server':
prs.add_argument(
'-s', dest='server', required=True,
help='specify TonicDNS Server hostname or IP address')
if keyword == 'username':
prs.add_argument('-u', dest='username', required=True,
help='TonicDNS username')
if keyword == 'password':
group = prs.add_mutually_exclusive_group(required=True)
group.add_argument('-p', dest='password',
help='TonicDNS password')
group.add_argument('-P', action='store_true',
help='TonicDNS password prompt')
if keyword == 'infile':
prs.add_argument('infile', action='store',
help='pre-converted text file')
if keyword == 'domain':
prs.add_argument('--domain', action='store', required=True,
help='create record with specify domain')
prs.add_argument('--name', action='store', required=True,
help='specify with domain option')
prs.add_argument('--rtype', action='store', required=True,
help='specify with domain option')
prs.add_argument('--content', action='store', required=True,
help='specify with domain option')
prs.add_argument('--ttl', action='store', default='3600',
help='specify with domain option, default 3600')
prs.add_argument('--priority', action='store', default=False,
help='specify with domain and '
'rtype options as MX|SRV')
if keyword == 'update':
prs.add_argument('--new-type', action='store',
help='specify new value with domain option')
prs.add_argument('--new-content', action='store',
help='specify new value with domain option')
prs.add_argument('--new-ttl', action='store',
help='specify new value with domain option')
prs.add_argument('--new-priority', action='store',
help='specify new value with domain option')
if keyword == 'template':
msg = 'specify template identifier'
if required:
prs.add_argument('--template', action='store',
required=True, help=msg)
else:
prs.add_argument('--template', action='store',
help=msg)
if keyword == 'search':
prs.add_argument('--search', action='store',
help='partial match search or refine search.\
latter syntax is "name,rtype,content"')
|
python
|
def set_option(prs, keyword, required=False):
"""Set options of command line.
Arguments:
prs: parser object of argparse
keyword: processing keyword
required: True is required option (default is False)
"""
if keyword == 'server':
prs.add_argument(
'-s', dest='server', required=True,
help='specify TonicDNS Server hostname or IP address')
if keyword == 'username':
prs.add_argument('-u', dest='username', required=True,
help='TonicDNS username')
if keyword == 'password':
group = prs.add_mutually_exclusive_group(required=True)
group.add_argument('-p', dest='password',
help='TonicDNS password')
group.add_argument('-P', action='store_true',
help='TonicDNS password prompt')
if keyword == 'infile':
prs.add_argument('infile', action='store',
help='pre-converted text file')
if keyword == 'domain':
prs.add_argument('--domain', action='store', required=True,
help='create record with specify domain')
prs.add_argument('--name', action='store', required=True,
help='specify with domain option')
prs.add_argument('--rtype', action='store', required=True,
help='specify with domain option')
prs.add_argument('--content', action='store', required=True,
help='specify with domain option')
prs.add_argument('--ttl', action='store', default='3600',
help='specify with domain option, default 3600')
prs.add_argument('--priority', action='store', default=False,
help='specify with domain and '
'rtype options as MX|SRV')
if keyword == 'update':
prs.add_argument('--new-type', action='store',
help='specify new value with domain option')
prs.add_argument('--new-content', action='store',
help='specify new value with domain option')
prs.add_argument('--new-ttl', action='store',
help='specify new value with domain option')
prs.add_argument('--new-priority', action='store',
help='specify new value with domain option')
if keyword == 'template':
msg = 'specify template identifier'
if required:
prs.add_argument('--template', action='store',
required=True, help=msg)
else:
prs.add_argument('--template', action='store',
help=msg)
if keyword == 'search':
prs.add_argument('--search', action='store',
help='partial match search or refine search.\
latter syntax is "name,rtype,content"')
|
[
"def",
"set_option",
"(",
"prs",
",",
"keyword",
",",
"required",
"=",
"False",
")",
":",
"if",
"keyword",
"==",
"'server'",
":",
"prs",
".",
"add_argument",
"(",
"'-s'",
",",
"dest",
"=",
"'server'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'specify TonicDNS Server hostname or IP address'",
")",
"if",
"keyword",
"==",
"'username'",
":",
"prs",
".",
"add_argument",
"(",
"'-u'",
",",
"dest",
"=",
"'username'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'TonicDNS username'",
")",
"if",
"keyword",
"==",
"'password'",
":",
"group",
"=",
"prs",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"'-p'",
",",
"dest",
"=",
"'password'",
",",
"help",
"=",
"'TonicDNS password'",
")",
"group",
".",
"add_argument",
"(",
"'-P'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'TonicDNS password prompt'",
")",
"if",
"keyword",
"==",
"'infile'",
":",
"prs",
".",
"add_argument",
"(",
"'infile'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'pre-converted text file'",
")",
"if",
"keyword",
"==",
"'domain'",
":",
"prs",
".",
"add_argument",
"(",
"'--domain'",
",",
"action",
"=",
"'store'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'create record with specify domain'",
")",
"prs",
".",
"add_argument",
"(",
"'--name'",
",",
"action",
"=",
"'store'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'specify with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--rtype'",
",",
"action",
"=",
"'store'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'specify with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--content'",
",",
"action",
"=",
"'store'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'specify with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--ttl'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"'3600'",
",",
"help",
"=",
"'specify with domain option, default 3600'",
")",
"prs",
".",
"add_argument",
"(",
"'--priority'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'specify with domain and '",
"'rtype options as MX|SRV'",
")",
"if",
"keyword",
"==",
"'update'",
":",
"prs",
".",
"add_argument",
"(",
"'--new-type'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'specify new value with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--new-content'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'specify new value with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--new-ttl'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'specify new value with domain option'",
")",
"prs",
".",
"add_argument",
"(",
"'--new-priority'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'specify new value with domain option'",
")",
"if",
"keyword",
"==",
"'template'",
":",
"msg",
"=",
"'specify template identifier'",
"if",
"required",
":",
"prs",
".",
"add_argument",
"(",
"'--template'",
",",
"action",
"=",
"'store'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"msg",
")",
"else",
":",
"prs",
".",
"add_argument",
"(",
"'--template'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"msg",
")",
"if",
"keyword",
"==",
"'search'",
":",
"prs",
".",
"add_argument",
"(",
"'--search'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'partial match search or refine search.\\\n latter syntax is \"name,rtype,content\"'",
")"
] |
Set options of command line.
Arguments:
prs: parser object of argparse
keyword: processing keyword
required: True is required option (default is False)
|
[
"Set",
"options",
"of",
"command",
"line",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L416-L482
|
246,404 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
conn_options
|
def conn_options(prs, conn):
"""Set options of connecting to TonicDNS API server
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
if conn.get('server') and conn.get('username') and conn.get('password'):
prs.set_defaults(server=conn.get('server'),
username=conn.get('username'),
password=conn.get('password'))
elif conn.get('server') and conn.get('username'):
prs.set_defaults(server=conn.get('server'),
username=conn.get('username'))
if conn.get('auto_update_soa'):
prs.set_defaults(auto_update_soa=conn.get('auto_update_soa'))
else:
prs.set_defaults(auto_update_soa=False)
if not conn.get('server'):
set_option(prs, 'server')
if not conn.get('username'):
set_option(prs, 'username')
if not conn.get('password'):
set_option(prs, 'password')
|
python
|
def conn_options(prs, conn):
"""Set options of connecting to TonicDNS API server
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
if conn.get('server') and conn.get('username') and conn.get('password'):
prs.set_defaults(server=conn.get('server'),
username=conn.get('username'),
password=conn.get('password'))
elif conn.get('server') and conn.get('username'):
prs.set_defaults(server=conn.get('server'),
username=conn.get('username'))
if conn.get('auto_update_soa'):
prs.set_defaults(auto_update_soa=conn.get('auto_update_soa'))
else:
prs.set_defaults(auto_update_soa=False)
if not conn.get('server'):
set_option(prs, 'server')
if not conn.get('username'):
set_option(prs, 'username')
if not conn.get('password'):
set_option(prs, 'password')
|
[
"def",
"conn_options",
"(",
"prs",
",",
"conn",
")",
":",
"if",
"conn",
".",
"get",
"(",
"'server'",
")",
"and",
"conn",
".",
"get",
"(",
"'username'",
")",
"and",
"conn",
".",
"get",
"(",
"'password'",
")",
":",
"prs",
".",
"set_defaults",
"(",
"server",
"=",
"conn",
".",
"get",
"(",
"'server'",
")",
",",
"username",
"=",
"conn",
".",
"get",
"(",
"'username'",
")",
",",
"password",
"=",
"conn",
".",
"get",
"(",
"'password'",
")",
")",
"elif",
"conn",
".",
"get",
"(",
"'server'",
")",
"and",
"conn",
".",
"get",
"(",
"'username'",
")",
":",
"prs",
".",
"set_defaults",
"(",
"server",
"=",
"conn",
".",
"get",
"(",
"'server'",
")",
",",
"username",
"=",
"conn",
".",
"get",
"(",
"'username'",
")",
")",
"if",
"conn",
".",
"get",
"(",
"'auto_update_soa'",
")",
":",
"prs",
".",
"set_defaults",
"(",
"auto_update_soa",
"=",
"conn",
".",
"get",
"(",
"'auto_update_soa'",
")",
")",
"else",
":",
"prs",
".",
"set_defaults",
"(",
"auto_update_soa",
"=",
"False",
")",
"if",
"not",
"conn",
".",
"get",
"(",
"'server'",
")",
":",
"set_option",
"(",
"prs",
",",
"'server'",
")",
"if",
"not",
"conn",
".",
"get",
"(",
"'username'",
")",
":",
"set_option",
"(",
"prs",
",",
"'username'",
")",
"if",
"not",
"conn",
".",
"get",
"(",
"'password'",
")",
":",
"set_option",
"(",
"prs",
",",
"'password'",
")"
] |
Set options of connecting to TonicDNS API server
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
|
[
"Set",
"options",
"of",
"connecting",
"to",
"TonicDNS",
"API",
"server"
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L485-L512
|
246,405 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
parse_options
|
def parse_options():
"""Define sub-commands and command line options."""
server, username, password, auto_update_soa = False, False, False, False
prs = argparse.ArgumentParser(description='usage')
prs.add_argument('-v', '--version', action='version',
version=__version__)
if os.environ.get('HOME'):
config_file = os.environ.get('HOME') + '/.tdclirc'
if os.path.isfile(config_file):
(server, username,
password, auto_update_soa) = check_config(config_file)
conn = dict(server=server, username=username,
password=password, auto_update_soa=auto_update_soa)
subprs = prs.add_subparsers(help='commands')
# Convert and print JSON
parse_show(subprs)
# Retrieve records
parse_get(subprs, conn)
# Create record
parse_create(subprs, conn)
# Create bulk_records
parse_bulk_create(subprs, conn)
# Delete record
parse_delete(subprs, conn)
# Delete bulk_records
parse_bulk_delete(subprs, conn)
# Update a record
parse_update(subprs, conn)
# Update SOA serial
parse_update_soa(subprs, conn)
# Create zone
parse_create_zone(subprs, conn)
# Delete zone
parse_delete_zone(subprs, conn)
# Retrieve template
parse_get_tmpl(subprs, conn)
# Delete template
parse_delete_tmpl(subprs, conn)
args = prs.parse_args()
return args
|
python
|
def parse_options():
"""Define sub-commands and command line options."""
server, username, password, auto_update_soa = False, False, False, False
prs = argparse.ArgumentParser(description='usage')
prs.add_argument('-v', '--version', action='version',
version=__version__)
if os.environ.get('HOME'):
config_file = os.environ.get('HOME') + '/.tdclirc'
if os.path.isfile(config_file):
(server, username,
password, auto_update_soa) = check_config(config_file)
conn = dict(server=server, username=username,
password=password, auto_update_soa=auto_update_soa)
subprs = prs.add_subparsers(help='commands')
# Convert and print JSON
parse_show(subprs)
# Retrieve records
parse_get(subprs, conn)
# Create record
parse_create(subprs, conn)
# Create bulk_records
parse_bulk_create(subprs, conn)
# Delete record
parse_delete(subprs, conn)
# Delete bulk_records
parse_bulk_delete(subprs, conn)
# Update a record
parse_update(subprs, conn)
# Update SOA serial
parse_update_soa(subprs, conn)
# Create zone
parse_create_zone(subprs, conn)
# Delete zone
parse_delete_zone(subprs, conn)
# Retrieve template
parse_get_tmpl(subprs, conn)
# Delete template
parse_delete_tmpl(subprs, conn)
args = prs.parse_args()
return args
|
[
"def",
"parse_options",
"(",
")",
":",
"server",
",",
"username",
",",
"password",
",",
"auto_update_soa",
"=",
"False",
",",
"False",
",",
"False",
",",
"False",
"prs",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'usage'",
")",
"prs",
".",
"add_argument",
"(",
"'-v'",
",",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"__version__",
")",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
")",
":",
"config_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
")",
"+",
"'/.tdclirc'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_file",
")",
":",
"(",
"server",
",",
"username",
",",
"password",
",",
"auto_update_soa",
")",
"=",
"check_config",
"(",
"config_file",
")",
"conn",
"=",
"dict",
"(",
"server",
"=",
"server",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"auto_update_soa",
"=",
"auto_update_soa",
")",
"subprs",
"=",
"prs",
".",
"add_subparsers",
"(",
"help",
"=",
"'commands'",
")",
"# Convert and print JSON",
"parse_show",
"(",
"subprs",
")",
"# Retrieve records",
"parse_get",
"(",
"subprs",
",",
"conn",
")",
"# Create record",
"parse_create",
"(",
"subprs",
",",
"conn",
")",
"# Create bulk_records",
"parse_bulk_create",
"(",
"subprs",
",",
"conn",
")",
"# Delete record",
"parse_delete",
"(",
"subprs",
",",
"conn",
")",
"# Delete bulk_records",
"parse_bulk_delete",
"(",
"subprs",
",",
"conn",
")",
"# Update a record",
"parse_update",
"(",
"subprs",
",",
"conn",
")",
"# Update SOA serial",
"parse_update_soa",
"(",
"subprs",
",",
"conn",
")",
"# Create zone",
"parse_create_zone",
"(",
"subprs",
",",
"conn",
")",
"# Delete zone",
"parse_delete_zone",
"(",
"subprs",
",",
"conn",
")",
"# Retrieve template",
"parse_get_tmpl",
"(",
"subprs",
",",
"conn",
")",
"# Delete template",
"parse_delete_tmpl",
"(",
"subprs",
",",
"conn",
")",
"args",
"=",
"prs",
".",
"parse_args",
"(",
")",
"return",
"args"
] |
Define sub-commands and command line options.
|
[
"Define",
"sub",
"-",
"commands",
"and",
"command",
"line",
"options",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L515-L571
|
246,406 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
parse_create
|
def parse_create(prs, conn):
"""Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_create = prs.add_parser(
'create', help='create record of specific zone')
set_option(prs_create, 'domain')
conn_options(prs_create, conn)
prs_create.set_defaults(func=create)
|
python
|
def parse_create(prs, conn):
"""Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_create = prs.add_parser(
'create', help='create record of specific zone')
set_option(prs_create, 'domain')
conn_options(prs_create, conn)
prs_create.set_defaults(func=create)
|
[
"def",
"parse_create",
"(",
"prs",
",",
"conn",
")",
":",
"prs_create",
"=",
"prs",
".",
"add_parser",
"(",
"'create'",
",",
"help",
"=",
"'create record of specific zone'",
")",
"set_option",
"(",
"prs_create",
",",
"'domain'",
")",
"conn_options",
"(",
"prs_create",
",",
"conn",
")",
"prs_create",
".",
"set_defaults",
"(",
"func",
"=",
"create",
")"
] |
Create record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
|
[
"Create",
"record",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L604-L616
|
246,407 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
parse_bulk_create
|
def parse_bulk_create(prs, conn):
"""Create bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_create = prs.add_parser(
'bulk_create', help='create bulk records of specific zone')
set_option(prs_create, 'infile')
conn_options(prs_create, conn)
prs_create.add_argument('--domain', action='store',
help='create records with specify zone')
prs_create.set_defaults(func=create)
|
python
|
def parse_bulk_create(prs, conn):
"""Create bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_create = prs.add_parser(
'bulk_create', help='create bulk records of specific zone')
set_option(prs_create, 'infile')
conn_options(prs_create, conn)
prs_create.add_argument('--domain', action='store',
help='create records with specify zone')
prs_create.set_defaults(func=create)
|
[
"def",
"parse_bulk_create",
"(",
"prs",
",",
"conn",
")",
":",
"prs_create",
"=",
"prs",
".",
"add_parser",
"(",
"'bulk_create'",
",",
"help",
"=",
"'create bulk records of specific zone'",
")",
"set_option",
"(",
"prs_create",
",",
"'infile'",
")",
"conn_options",
"(",
"prs_create",
",",
"conn",
")",
"prs_create",
".",
"add_argument",
"(",
"'--domain'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'create records with specify zone'",
")",
"prs_create",
".",
"set_defaults",
"(",
"func",
"=",
"create",
")"
] |
Create bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
|
[
"Create",
"bulk_records",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L619-L633
|
246,408 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
parse_delete
|
def parse_delete(prs, conn):
"""Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'delete', help='delete a record of specific zone')
set_option(prs_delete, 'domain')
conn_options(prs_delete, conn)
prs_delete.set_defaults(func=delete)
|
python
|
def parse_delete(prs, conn):
"""Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'delete', help='delete a record of specific zone')
set_option(prs_delete, 'domain')
conn_options(prs_delete, conn)
prs_delete.set_defaults(func=delete)
|
[
"def",
"parse_delete",
"(",
"prs",
",",
"conn",
")",
":",
"prs_delete",
"=",
"prs",
".",
"add_parser",
"(",
"'delete'",
",",
"help",
"=",
"'delete a record of specific zone'",
")",
"set_option",
"(",
"prs_delete",
",",
"'domain'",
")",
"conn_options",
"(",
"prs_delete",
",",
"conn",
")",
"prs_delete",
".",
"set_defaults",
"(",
"func",
"=",
"delete",
")"
] |
Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
|
[
"Delete",
"record",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L636-L648
|
246,409 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
parse_bulk_delete
|
def parse_bulk_delete(prs, conn):
"""Delete bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'bulk_delete', help='delete bulk records of specific zone')
set_option(prs_delete, 'infile')
conn_options(prs_delete, conn)
prs_delete.add_argument('--domain', action='store',
help='delete records with specify zone')
prs_delete.set_defaults(func=delete)
|
python
|
def parse_bulk_delete(prs, conn):
"""Delete bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'bulk_delete', help='delete bulk records of specific zone')
set_option(prs_delete, 'infile')
conn_options(prs_delete, conn)
prs_delete.add_argument('--domain', action='store',
help='delete records with specify zone')
prs_delete.set_defaults(func=delete)
|
[
"def",
"parse_bulk_delete",
"(",
"prs",
",",
"conn",
")",
":",
"prs_delete",
"=",
"prs",
".",
"add_parser",
"(",
"'bulk_delete'",
",",
"help",
"=",
"'delete bulk records of specific zone'",
")",
"set_option",
"(",
"prs_delete",
",",
"'infile'",
")",
"conn_options",
"(",
"prs_delete",
",",
"conn",
")",
"prs_delete",
".",
"add_argument",
"(",
"'--domain'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'delete records with specify zone'",
")",
"prs_delete",
".",
"set_defaults",
"(",
"func",
"=",
"delete",
")"
] |
Delete bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
|
[
"Delete",
"bulk_records",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L651-L665
|
246,410 |
mkouhei/tonicdnscli
|
src/tonicdnscli/command.py
|
check_config
|
def check_config(filename):
"""Check configuration file of TonicDNS CLI.
Argument:
filename: config file name (default is ~/.tdclirc)
"""
conf = configparser.SafeConfigParser(allow_no_value=False)
conf.read(filename)
try:
server = conf.get('global', 'server')
except configparser.NoSectionError:
server = False
except configparser.NoOptionError:
server = False
try:
username = conf.get('auth', 'username')
except configparser.NoSectionError:
username = False
except configparser.NoOptionError:
username = False
try:
password = conf.get('auth', 'password')
except configparser.NoSectionError:
password = False
except configparser.NoOptionError:
password = False
try:
auto_update_soa = conf.get('global', 'soa_update')
except configparser.NoSectionError:
auto_update_soa = False
except configparser.NoOptionError:
auto_update_soa = False
return server, username, password, auto_update_soa
|
python
|
def check_config(filename):
"""Check configuration file of TonicDNS CLI.
Argument:
filename: config file name (default is ~/.tdclirc)
"""
conf = configparser.SafeConfigParser(allow_no_value=False)
conf.read(filename)
try:
server = conf.get('global', 'server')
except configparser.NoSectionError:
server = False
except configparser.NoOptionError:
server = False
try:
username = conf.get('auth', 'username')
except configparser.NoSectionError:
username = False
except configparser.NoOptionError:
username = False
try:
password = conf.get('auth', 'password')
except configparser.NoSectionError:
password = False
except configparser.NoOptionError:
password = False
try:
auto_update_soa = conf.get('global', 'soa_update')
except configparser.NoSectionError:
auto_update_soa = False
except configparser.NoOptionError:
auto_update_soa = False
return server, username, password, auto_update_soa
|
[
"def",
"check_config",
"(",
"filename",
")",
":",
"conf",
"=",
"configparser",
".",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"False",
")",
"conf",
".",
"read",
"(",
"filename",
")",
"try",
":",
"server",
"=",
"conf",
".",
"get",
"(",
"'global'",
",",
"'server'",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"server",
"=",
"False",
"except",
"configparser",
".",
"NoOptionError",
":",
"server",
"=",
"False",
"try",
":",
"username",
"=",
"conf",
".",
"get",
"(",
"'auth'",
",",
"'username'",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"username",
"=",
"False",
"except",
"configparser",
".",
"NoOptionError",
":",
"username",
"=",
"False",
"try",
":",
"password",
"=",
"conf",
".",
"get",
"(",
"'auth'",
",",
"'password'",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"password",
"=",
"False",
"except",
"configparser",
".",
"NoOptionError",
":",
"password",
"=",
"False",
"try",
":",
"auto_update_soa",
"=",
"conf",
".",
"get",
"(",
"'global'",
",",
"'soa_update'",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"auto_update_soa",
"=",
"False",
"except",
"configparser",
".",
"NoOptionError",
":",
"auto_update_soa",
"=",
"False",
"return",
"server",
",",
"username",
",",
"password",
",",
"auto_update_soa"
] |
Check configuration file of TonicDNS CLI.
Argument:
filename: config file name (default is ~/.tdclirc)
|
[
"Check",
"configuration",
"file",
"of",
"TonicDNS",
"CLI",
"."
] |
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
|
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L779-L813
|
246,411 |
etcher-be/elib_config
|
elib_config/_file/_config_example.py
|
write_example_config
|
def write_example_config(example_file_path: str):
"""
Writes an example config file using the config values declared so far
:param example_file_path: path to write to
"""
document = tomlkit.document()
for header_line in _get_header():
document.add(tomlkit.comment(header_line))
config_keys = _aggregate_config_values(ConfigValue.config_values)
_add_config_values_to_toml_object(document, config_keys)
_doc_as_str = document.as_string().replace(f'"{_NOT_SET}"', '')
with open(example_file_path, 'w') as stream:
stream.write(_doc_as_str)
|
python
|
def write_example_config(example_file_path: str):
"""
Writes an example config file using the config values declared so far
:param example_file_path: path to write to
"""
document = tomlkit.document()
for header_line in _get_header():
document.add(tomlkit.comment(header_line))
config_keys = _aggregate_config_values(ConfigValue.config_values)
_add_config_values_to_toml_object(document, config_keys)
_doc_as_str = document.as_string().replace(f'"{_NOT_SET}"', '')
with open(example_file_path, 'w') as stream:
stream.write(_doc_as_str)
|
[
"def",
"write_example_config",
"(",
"example_file_path",
":",
"str",
")",
":",
"document",
"=",
"tomlkit",
".",
"document",
"(",
")",
"for",
"header_line",
"in",
"_get_header",
"(",
")",
":",
"document",
".",
"add",
"(",
"tomlkit",
".",
"comment",
"(",
"header_line",
")",
")",
"config_keys",
"=",
"_aggregate_config_values",
"(",
"ConfigValue",
".",
"config_values",
")",
"_add_config_values_to_toml_object",
"(",
"document",
",",
"config_keys",
")",
"_doc_as_str",
"=",
"document",
".",
"as_string",
"(",
")",
".",
"replace",
"(",
"f'\"{_NOT_SET}\"'",
",",
"''",
")",
"with",
"open",
"(",
"example_file_path",
",",
"'w'",
")",
"as",
"stream",
":",
"stream",
".",
"write",
"(",
"_doc_as_str",
")"
] |
Writes an example config file using the config values declared so far
:param example_file_path: path to write to
|
[
"Writes",
"an",
"example",
"config",
"file",
"using",
"the",
"config",
"values",
"declared",
"so",
"far"
] |
5d8c839e84d70126620ab0186dc1f717e5868bd0
|
https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_file/_config_example.py#L71-L84
|
246,412 |
20c/xbahn
|
xbahn/api.py
|
Comm.prepare_message
|
def prepare_message(self, message):
"""
Prepares the message before sending it out
Returns:
- message.Message: the message
"""
message.meta.update(path=self.path)
for handler in self.handlers:
handler.outgoing(message, self)
return message
|
python
|
def prepare_message(self, message):
"""
Prepares the message before sending it out
Returns:
- message.Message: the message
"""
message.meta.update(path=self.path)
for handler in self.handlers:
handler.outgoing(message, self)
return message
|
[
"def",
"prepare_message",
"(",
"self",
",",
"message",
")",
":",
"message",
".",
"meta",
".",
"update",
"(",
"path",
"=",
"self",
".",
"path",
")",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"handler",
".",
"outgoing",
"(",
"message",
",",
"self",
")",
"return",
"message"
] |
Prepares the message before sending it out
Returns:
- message.Message: the message
|
[
"Prepares",
"the",
"message",
"before",
"sending",
"it",
"out"
] |
afb27b0576841338a366d7cac0200a782bd84be6
|
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L288-L301
|
246,413 |
20c/xbahn
|
xbahn/api.py
|
Comm.on_receive
|
def on_receive(self, message=None, wire=None, event_origin=None):
"""
event handler bound to the receive event of the
link the server is wired too.
Arguments:
- message (message.Message): incoming message
Keyword arguments:
- event_origin (connection.Link)
"""
self.trigger("before_call", message)
fn_name = message.data
pmsg = self.prepare_message
try:
for handler in self.handlers:
handler.incoming(message, self)
fn = self.get_function(fn_name, message.path)
except Exception as inst:
wire.respond(message, ErrorMessage(str(inst)))
return
if callable(fn) and getattr(fn, "exposed", False):
try:
r = fn(*message.args, **message.kwargs)
if isinstance(r,Message):
wire.respond(message, pmsg(r))
else:
wire.respond(message, pmsg(Message(r)))
except Exception as inst:
if self.debug:
wire.respond(message, pmsg(ErrorMessage(str(traceback.format_exc()))))
else:
wire.respond(message, pmsg(ErrorMessage(str(inst))))
else:
wire.respond(
message,
pmsg(
ErrorMessage("action '%s' not exposed on API (%s)" % (fn_name, self.__class__.__name__)))
)
self.trigger("after_call", message)
|
python
|
def on_receive(self, message=None, wire=None, event_origin=None):
"""
event handler bound to the receive event of the
link the server is wired too.
Arguments:
- message (message.Message): incoming message
Keyword arguments:
- event_origin (connection.Link)
"""
self.trigger("before_call", message)
fn_name = message.data
pmsg = self.prepare_message
try:
for handler in self.handlers:
handler.incoming(message, self)
fn = self.get_function(fn_name, message.path)
except Exception as inst:
wire.respond(message, ErrorMessage(str(inst)))
return
if callable(fn) and getattr(fn, "exposed", False):
try:
r = fn(*message.args, **message.kwargs)
if isinstance(r,Message):
wire.respond(message, pmsg(r))
else:
wire.respond(message, pmsg(Message(r)))
except Exception as inst:
if self.debug:
wire.respond(message, pmsg(ErrorMessage(str(traceback.format_exc()))))
else:
wire.respond(message, pmsg(ErrorMessage(str(inst))))
else:
wire.respond(
message,
pmsg(
ErrorMessage("action '%s' not exposed on API (%s)" % (fn_name, self.__class__.__name__)))
)
self.trigger("after_call", message)
|
[
"def",
"on_receive",
"(",
"self",
",",
"message",
"=",
"None",
",",
"wire",
"=",
"None",
",",
"event_origin",
"=",
"None",
")",
":",
"self",
".",
"trigger",
"(",
"\"before_call\"",
",",
"message",
")",
"fn_name",
"=",
"message",
".",
"data",
"pmsg",
"=",
"self",
".",
"prepare_message",
"try",
":",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"handler",
".",
"incoming",
"(",
"message",
",",
"self",
")",
"fn",
"=",
"self",
".",
"get_function",
"(",
"fn_name",
",",
"message",
".",
"path",
")",
"except",
"Exception",
"as",
"inst",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"ErrorMessage",
"(",
"str",
"(",
"inst",
")",
")",
")",
"return",
"if",
"callable",
"(",
"fn",
")",
"and",
"getattr",
"(",
"fn",
",",
"\"exposed\"",
",",
"False",
")",
":",
"try",
":",
"r",
"=",
"fn",
"(",
"*",
"message",
".",
"args",
",",
"*",
"*",
"message",
".",
"kwargs",
")",
"if",
"isinstance",
"(",
"r",
",",
"Message",
")",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"pmsg",
"(",
"r",
")",
")",
"else",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"pmsg",
"(",
"Message",
"(",
"r",
")",
")",
")",
"except",
"Exception",
"as",
"inst",
":",
"if",
"self",
".",
"debug",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"pmsg",
"(",
"ErrorMessage",
"(",
"str",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
")",
")",
"else",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"pmsg",
"(",
"ErrorMessage",
"(",
"str",
"(",
"inst",
")",
")",
")",
")",
"else",
":",
"wire",
".",
"respond",
"(",
"message",
",",
"pmsg",
"(",
"ErrorMessage",
"(",
"\"action '%s' not exposed on API (%s)\"",
"%",
"(",
"fn_name",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
")",
")",
"self",
".",
"trigger",
"(",
"\"after_call\"",
",",
"message",
")"
] |
event handler bound to the receive event of the
link the server is wired too.
Arguments:
- message (message.Message): incoming message
Keyword arguments:
- event_origin (connection.Link)
|
[
"event",
"handler",
"bound",
"to",
"the",
"receive",
"event",
"of",
"the",
"link",
"the",
"server",
"is",
"wired",
"too",
"."
] |
afb27b0576841338a366d7cac0200a782bd84be6
|
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L304-L350
|
246,414 |
20c/xbahn
|
xbahn/api.py
|
WidgetAwareServer.detach_remote
|
def detach_remote(self, id, name):
"""
destroy remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
"""
if name in self.widgets:
if id in self.widgets[name]:
del self.widgets[name]
|
python
|
def detach_remote(self, id, name):
"""
destroy remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
"""
if name in self.widgets:
if id in self.widgets[name]:
del self.widgets[name]
|
[
"def",
"detach_remote",
"(",
"self",
",",
"id",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"widgets",
":",
"if",
"id",
"in",
"self",
".",
"widgets",
"[",
"name",
"]",
":",
"del",
"self",
".",
"widgets",
"[",
"name",
"]"
] |
destroy remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
|
[
"destroy",
"remote",
"instance",
"of",
"widget"
] |
afb27b0576841338a366d7cac0200a782bd84be6
|
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L559-L570
|
246,415 |
20c/xbahn
|
xbahn/api.py
|
WidgetAwareServer.attach_remote
|
def attach_remote(self, id, name, **kwargs):
"""
create remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
Keyword Arguments:
- any further arguments you wish to pass
to the widget constructor
"""
client_id = id.split(".")[0]
widget = self.make_widget(
id,
name,
dispatcher=ProxyDispatcher(
self,
link=getattr(self.clients[client_id], "link", None)
),
**kwargs
)
self.store_widget(widget)
self.log_debug("Attached widget: %s" % id)
|
python
|
def attach_remote(self, id, name, **kwargs):
"""
create remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
Keyword Arguments:
- any further arguments you wish to pass
to the widget constructor
"""
client_id = id.split(".")[0]
widget = self.make_widget(
id,
name,
dispatcher=ProxyDispatcher(
self,
link=getattr(self.clients[client_id], "link", None)
),
**kwargs
)
self.store_widget(widget)
self.log_debug("Attached widget: %s" % id)
|
[
"def",
"attach_remote",
"(",
"self",
",",
"id",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"client_id",
"=",
"id",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"widget",
"=",
"self",
".",
"make_widget",
"(",
"id",
",",
"name",
",",
"dispatcher",
"=",
"ProxyDispatcher",
"(",
"self",
",",
"link",
"=",
"getattr",
"(",
"self",
".",
"clients",
"[",
"client_id",
"]",
",",
"\"link\"",
",",
"None",
")",
")",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"store_widget",
"(",
"widget",
")",
"self",
".",
"log_debug",
"(",
"\"Attached widget: %s\"",
"%",
"id",
")"
] |
create remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
Keyword Arguments:
- any further arguments you wish to pass
to the widget constructor
|
[
"create",
"remote",
"instance",
"of",
"widget"
] |
afb27b0576841338a366d7cac0200a782bd84be6
|
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L574-L600
|
246,416 |
20c/xbahn
|
xbahn/api.py
|
Widget.on_api_error
|
def on_api_error(self, error_status=None, message=None, event_origin=None):
"""
API error handling
"""
if message.meta["error"].find("Widget instance not found on server") > -1:
# widget is missing on the other side, try to re-attach
# then try again
error_status["retry"] = True
self.comm.attach_remote(
self.id,
self.remote_name,
remote_name=self.name,
**self.init_kwargs
)
|
python
|
def on_api_error(self, error_status=None, message=None, event_origin=None):
"""
API error handling
"""
if message.meta["error"].find("Widget instance not found on server") > -1:
# widget is missing on the other side, try to re-attach
# then try again
error_status["retry"] = True
self.comm.attach_remote(
self.id,
self.remote_name,
remote_name=self.name,
**self.init_kwargs
)
|
[
"def",
"on_api_error",
"(",
"self",
",",
"error_status",
"=",
"None",
",",
"message",
"=",
"None",
",",
"event_origin",
"=",
"None",
")",
":",
"if",
"message",
".",
"meta",
"[",
"\"error\"",
"]",
".",
"find",
"(",
"\"Widget instance not found on server\"",
")",
">",
"-",
"1",
":",
"# widget is missing on the other side, try to re-attach",
"# then try again",
"error_status",
"[",
"\"retry\"",
"]",
"=",
"True",
"self",
".",
"comm",
".",
"attach_remote",
"(",
"self",
".",
"id",
",",
"self",
".",
"remote_name",
",",
"remote_name",
"=",
"self",
".",
"name",
",",
"*",
"*",
"self",
".",
"init_kwargs",
")"
] |
API error handling
|
[
"API",
"error",
"handling"
] |
afb27b0576841338a366d7cac0200a782bd84be6
|
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L724-L738
|
246,417 |
eeue56/PyChat.js
|
pychatjs/server/connections.py
|
ChatConnection.write_message
|
def write_message(self, message):
""" Writes a message to this chat connection's handler """
logging.debug("Sending message {mes} to {usr}".format(mes=message, usr=self.id))
self.handler.write_message(message)
|
python
|
def write_message(self, message):
""" Writes a message to this chat connection's handler """
logging.debug("Sending message {mes} to {usr}".format(mes=message, usr=self.id))
self.handler.write_message(message)
|
[
"def",
"write_message",
"(",
"self",
",",
"message",
")",
":",
"logging",
".",
"debug",
"(",
"\"Sending message {mes} to {usr}\"",
".",
"format",
"(",
"mes",
"=",
"message",
",",
"usr",
"=",
"self",
".",
"id",
")",
")",
"self",
".",
"handler",
".",
"write_message",
"(",
"message",
")"
] |
Writes a message to this chat connection's handler
|
[
"Writes",
"a",
"message",
"to",
"this",
"chat",
"connection",
"s",
"handler"
] |
45056de6f988350c90a6dbe674459a4affde8abc
|
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L21-L24
|
246,418 |
eeue56/PyChat.js
|
pychatjs/server/connections.py
|
ChatConnection.join_room
|
def join_room(self, room_name):
""" Connects to a given room
If it does not exist it is created"""
logging.debug('Joining room {ro}'.format(ro=room_name))
for room in self.rooms:
if room.name == room_name:
room.add_user(self)
self._rooms[room_name] = room
room.welcome(self)
break
else:
room = Room(room_name)
self.rooms.append(room)
self._rooms[room_name] = room
room.add_user(self)
|
python
|
def join_room(self, room_name):
""" Connects to a given room
If it does not exist it is created"""
logging.debug('Joining room {ro}'.format(ro=room_name))
for room in self.rooms:
if room.name == room_name:
room.add_user(self)
self._rooms[room_name] = room
room.welcome(self)
break
else:
room = Room(room_name)
self.rooms.append(room)
self._rooms[room_name] = room
room.add_user(self)
|
[
"def",
"join_room",
"(",
"self",
",",
"room_name",
")",
":",
"logging",
".",
"debug",
"(",
"'Joining room {ro}'",
".",
"format",
"(",
"ro",
"=",
"room_name",
")",
")",
"for",
"room",
"in",
"self",
".",
"rooms",
":",
"if",
"room",
".",
"name",
"==",
"room_name",
":",
"room",
".",
"add_user",
"(",
"self",
")",
"self",
".",
"_rooms",
"[",
"room_name",
"]",
"=",
"room",
"room",
".",
"welcome",
"(",
"self",
")",
"break",
"else",
":",
"room",
"=",
"Room",
"(",
"room_name",
")",
"self",
".",
"rooms",
".",
"append",
"(",
"room",
")",
"self",
".",
"_rooms",
"[",
"room_name",
"]",
"=",
"room",
"room",
".",
"add_user",
"(",
"self",
")"
] |
Connects to a given room
If it does not exist it is created
|
[
"Connects",
"to",
"a",
"given",
"room",
"If",
"it",
"does",
"not",
"exist",
"it",
"is",
"created"
] |
45056de6f988350c90a6dbe674459a4affde8abc
|
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L26-L41
|
246,419 |
eeue56/PyChat.js
|
pychatjs/server/connections.py
|
ChatConnection.send_to_room
|
def send_to_room(self, message, room_name):
""" Sends a given message to a given room """
room = self.get_room(room_name)
if room is not None:
room.send_message(message)
|
python
|
def send_to_room(self, message, room_name):
""" Sends a given message to a given room """
room = self.get_room(room_name)
if room is not None:
room.send_message(message)
|
[
"def",
"send_to_room",
"(",
"self",
",",
"message",
",",
"room_name",
")",
":",
"room",
"=",
"self",
".",
"get_room",
"(",
"room_name",
")",
"if",
"room",
"is",
"not",
"None",
":",
"room",
".",
"send_message",
"(",
"message",
")"
] |
Sends a given message to a given room
|
[
"Sends",
"a",
"given",
"message",
"to",
"a",
"given",
"room"
] |
45056de6f988350c90a6dbe674459a4affde8abc
|
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L43-L48
|
246,420 |
eeue56/PyChat.js
|
pychatjs/server/connections.py
|
ChatConnection._send_to_all_rooms
|
def _send_to_all_rooms(self, message):
""" Send a message to all connected rooms """
for room in self._rooms.values():
room.send_message(message)
|
python
|
def _send_to_all_rooms(self, message):
""" Send a message to all connected rooms """
for room in self._rooms.values():
room.send_message(message)
|
[
"def",
"_send_to_all_rooms",
"(",
"self",
",",
"message",
")",
":",
"for",
"room",
"in",
"self",
".",
"_rooms",
".",
"values",
"(",
")",
":",
"room",
".",
"send_message",
"(",
"message",
")"
] |
Send a message to all connected rooms
|
[
"Send",
"a",
"message",
"to",
"all",
"connected",
"rooms"
] |
45056de6f988350c90a6dbe674459a4affde8abc
|
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L50-L53
|
246,421 |
eeue56/PyChat.js
|
pychatjs/server/connections.py
|
ChatConnection.close
|
def close(self):
""" Closes the connection by removing the user from all rooms """
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self)
|
python
|
def close(self):
""" Closes the connection by removing the user from all rooms """
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self)
|
[
"def",
"close",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"'Closing for user {user}'",
".",
"format",
"(",
"user",
"=",
"self",
".",
"id",
".",
"name",
")",
")",
"self",
".",
"id",
".",
"release_name",
"(",
")",
"for",
"room",
"in",
"self",
".",
"_rooms",
".",
"values",
"(",
")",
":",
"room",
".",
"disconnect",
"(",
"self",
")"
] |
Closes the connection by removing the user from all rooms
|
[
"Closes",
"the",
"connection",
"by",
"removing",
"the",
"user",
"from",
"all",
"rooms"
] |
45056de6f988350c90a6dbe674459a4affde8abc
|
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L55-L60
|
246,422 |
Ffisegydd/whatis
|
whatis/_type.py
|
get_parents
|
def get_parents(obj, **kwargs):
"""Return the MRO of an object. Do regex on each element to remove the "<class..." bit."""
num_of_mro = kwargs.get("num_of_mro", 5)
mro = getmro(obj.__class__)
mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]])
return "Hierarchy: {}".format(mro_string)
|
python
|
def get_parents(obj, **kwargs):
"""Return the MRO of an object. Do regex on each element to remove the "<class..." bit."""
num_of_mro = kwargs.get("num_of_mro", 5)
mro = getmro(obj.__class__)
mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]])
return "Hierarchy: {}".format(mro_string)
|
[
"def",
"get_parents",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"num_of_mro",
"=",
"kwargs",
".",
"get",
"(",
"\"num_of_mro\"",
",",
"5",
")",
"mro",
"=",
"getmro",
"(",
"obj",
".",
"__class__",
")",
"mro_string",
"=",
"', '",
".",
"join",
"(",
"[",
"extract_type",
"(",
"str",
"(",
"t",
")",
")",
"for",
"t",
"in",
"mro",
"[",
":",
"num_of_mro",
"]",
"]",
")",
"return",
"\"Hierarchy: {}\"",
".",
"format",
"(",
"mro_string",
")"
] |
Return the MRO of an object. Do regex on each element to remove the "<class..." bit.
|
[
"Return",
"the",
"MRO",
"of",
"an",
"object",
".",
"Do",
"regex",
"on",
"each",
"element",
"to",
"remove",
"the",
"<class",
"...",
"bit",
"."
] |
eef780ced61aae6d001aeeef7574e5e27e613583
|
https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_type.py#L17-L24
|
246,423 |
c0ntrol-x/p4rr0t007
|
p4rr0t007/lib/core.py
|
lpad
|
def lpad(s, N, char='\0'):
"""pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.rjust(N, char)
|
python
|
def lpad(s, N, char='\0'):
"""pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.rjust(N, char)
|
[
"def",
"lpad",
"(",
"s",
",",
"N",
",",
"char",
"=",
"'\\0'",
")",
":",
"assert",
"isinstance",
"(",
"char",
",",
"bytes",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
",",
"'char should be a string with length 1'",
"return",
"s",
".",
"rjust",
"(",
"N",
",",
"char",
")"
] |
pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
|
[
"pads",
"a",
"string",
"to",
"the",
"left",
"with",
"null",
"-",
"bytes",
"or",
"any",
"other",
"given",
"character",
"."
] |
6fe88ec1231a778b9f1d13bc61332581715d646e
|
https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/lib/core.py#L89-L99
|
246,424 |
c0ntrol-x/p4rr0t007
|
p4rr0t007/lib/core.py
|
rpad
|
def rpad(s, N, char='\0'):
"""pads a string to the right with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.ljust(N, char)
|
python
|
def rpad(s, N, char='\0'):
"""pads a string to the right with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.ljust(N, char)
|
[
"def",
"rpad",
"(",
"s",
",",
"N",
",",
"char",
"=",
"'\\0'",
")",
":",
"assert",
"isinstance",
"(",
"char",
",",
"bytes",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
",",
"'char should be a string with length 1'",
"return",
"s",
".",
"ljust",
"(",
"N",
",",
"char",
")"
] |
pads a string to the right with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
|
[
"pads",
"a",
"string",
"to",
"the",
"right",
"with",
"null",
"-",
"bytes",
"or",
"any",
"other",
"given",
"character",
"."
] |
6fe88ec1231a778b9f1d13bc61332581715d646e
|
https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/lib/core.py#L102-L112
|
246,425 |
c0ntrol-x/p4rr0t007
|
p4rr0t007/lib/core.py
|
xor
|
def xor(left, right):
"""xor 2 strings. They can be shorter than each other, in which case
the shortest will be padded with null bytes at its right.
:param left: a string to be the left side of the xor
:param right: a string to be the left side of the xor
"""
maxlength = max(map(len, (left, right)))
ileft = string_to_int(rpad(left, maxlength))
iright = string_to_int(rpad(right, maxlength))
xored = ileft ^ iright
return int_to_string(xored)
|
python
|
def xor(left, right):
"""xor 2 strings. They can be shorter than each other, in which case
the shortest will be padded with null bytes at its right.
:param left: a string to be the left side of the xor
:param right: a string to be the left side of the xor
"""
maxlength = max(map(len, (left, right)))
ileft = string_to_int(rpad(left, maxlength))
iright = string_to_int(rpad(right, maxlength))
xored = ileft ^ iright
return int_to_string(xored)
|
[
"def",
"xor",
"(",
"left",
",",
"right",
")",
":",
"maxlength",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"(",
"left",
",",
"right",
")",
")",
")",
"ileft",
"=",
"string_to_int",
"(",
"rpad",
"(",
"left",
",",
"maxlength",
")",
")",
"iright",
"=",
"string_to_int",
"(",
"rpad",
"(",
"right",
",",
"maxlength",
")",
")",
"xored",
"=",
"ileft",
"^",
"iright",
"return",
"int_to_string",
"(",
"xored",
")"
] |
xor 2 strings. They can be shorter than each other, in which case
the shortest will be padded with null bytes at its right.
:param left: a string to be the left side of the xor
:param right: a string to be the left side of the xor
|
[
"xor",
"2",
"strings",
".",
"They",
"can",
"be",
"shorter",
"than",
"each",
"other",
"in",
"which",
"case",
"the",
"shortest",
"will",
"be",
"padded",
"with",
"null",
"bytes",
"at",
"its",
"right",
"."
] |
6fe88ec1231a778b9f1d13bc61332581715d646e
|
https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/lib/core.py#L124-L136
|
246,426 |
c0ntrol-x/p4rr0t007
|
p4rr0t007/lib/core.py
|
slugify
|
def slugify(string, repchar='_'):
"""replaces all non-alphanumeric chars in the string with the given repchar.
:param string: the source string
:param repchar:
"""
slug_regex = re.compile(r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'.format(repchar))
strip_regex = re.compile(r'[{0}._-]+'.format(repchar))
transformations = [
lambda x: slug_regex.sub(repchar, x),
lambda x: strip_regex.sub(repchar, x),
lambda x: x.strip(repchar),
lambda x: x.lower(),
]
result = string
for process in transformations:
result = process(result)
return result
|
python
|
def slugify(string, repchar='_'):
"""replaces all non-alphanumeric chars in the string with the given repchar.
:param string: the source string
:param repchar:
"""
slug_regex = re.compile(r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'.format(repchar))
strip_regex = re.compile(r'[{0}._-]+'.format(repchar))
transformations = [
lambda x: slug_regex.sub(repchar, x),
lambda x: strip_regex.sub(repchar, x),
lambda x: x.strip(repchar),
lambda x: x.lower(),
]
result = string
for process in transformations:
result = process(result)
return result
|
[
"def",
"slugify",
"(",
"string",
",",
"repchar",
"=",
"'_'",
")",
":",
"slug_regex",
"=",
"re",
".",
"compile",
"(",
"r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'",
".",
"format",
"(",
"repchar",
")",
")",
"strip_regex",
"=",
"re",
".",
"compile",
"(",
"r'[{0}._-]+'",
".",
"format",
"(",
"repchar",
")",
")",
"transformations",
"=",
"[",
"lambda",
"x",
":",
"slug_regex",
".",
"sub",
"(",
"repchar",
",",
"x",
")",
",",
"lambda",
"x",
":",
"strip_regex",
".",
"sub",
"(",
"repchar",
",",
"x",
")",
",",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
"repchar",
")",
",",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
",",
"]",
"result",
"=",
"string",
"for",
"process",
"in",
"transformations",
":",
"result",
"=",
"process",
"(",
"result",
")",
"return",
"result"
] |
replaces all non-alphanumeric chars in the string with the given repchar.
:param string: the source string
:param repchar:
|
[
"replaces",
"all",
"non",
"-",
"alphanumeric",
"chars",
"in",
"the",
"string",
"with",
"the",
"given",
"repchar",
"."
] |
6fe88ec1231a778b9f1d13bc61332581715d646e
|
https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/lib/core.py#L304-L323
|
246,427 |
rackerlabs/rackspace-python-neutronclient
|
neutronclient/common/serializer.py
|
ActionDispatcher.dispatch
|
def dispatch(self, *args, **kwargs):
"""Find and call local method."""
action = kwargs.pop('action', 'default')
action_method = getattr(self, str(action), self.default)
return action_method(*args, **kwargs)
|
python
|
def dispatch(self, *args, **kwargs):
"""Find and call local method."""
action = kwargs.pop('action', 'default')
action_method = getattr(self, str(action), self.default)
return action_method(*args, **kwargs)
|
[
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"action",
"=",
"kwargs",
".",
"pop",
"(",
"'action'",
",",
"'default'",
")",
"action_method",
"=",
"getattr",
"(",
"self",
",",
"str",
"(",
"action",
")",
",",
"self",
".",
"default",
")",
"return",
"action_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Find and call local method.
|
[
"Find",
"and",
"call",
"local",
"method",
"."
] |
5a5009a8fe078e3aa1d582176669f1b28ab26bef
|
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/serializer.py#L33-L37
|
246,428 |
treycucco/bidon
|
bidon/configuration.py
|
Configuration.update
|
def update(self, **kwargs):
"""Creates or updates a property for the instance for each parameter."""
for key, value in kwargs.items():
setattr(self, key, value)
|
python
|
def update(self, **kwargs):
"""Creates or updates a property for the instance for each parameter."""
for key, value in kwargs.items():
setattr(self, key, value)
|
[
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")"
] |
Creates or updates a property for the instance for each parameter.
|
[
"Creates",
"or",
"updates",
"a",
"property",
"for",
"the",
"instance",
"for",
"each",
"parameter",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/configuration.py#L17-L20
|
246,429 |
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/utils/template.py
|
template_ds
|
def template_ds(basedir, varname, vars, lookup_fatal=True, depth=0):
''' templates a data structure by traversing it and substituting for other data structures '''
if isinstance(varname, basestring):
m = _varFind(basedir, varname, vars, lookup_fatal, depth)
if not m:
return varname
if m['start'] == 0 and m['end'] == len(varname):
if m['replacement'] is not None:
return template_ds(basedir, m['replacement'], vars, lookup_fatal, depth)
else:
return varname
else:
return template(basedir, varname, vars, lookup_fatal)
elif isinstance(varname, (list, tuple)):
return [template_ds(basedir, v, vars, lookup_fatal, depth) for v in varname]
elif isinstance(varname, dict):
d = {}
for (k, v) in varname.iteritems():
d[k] = template_ds(basedir, v, vars, lookup_fatal, depth)
return d
else:
return varname
|
python
|
def template_ds(basedir, varname, vars, lookup_fatal=True, depth=0):
''' templates a data structure by traversing it and substituting for other data structures '''
if isinstance(varname, basestring):
m = _varFind(basedir, varname, vars, lookup_fatal, depth)
if not m:
return varname
if m['start'] == 0 and m['end'] == len(varname):
if m['replacement'] is not None:
return template_ds(basedir, m['replacement'], vars, lookup_fatal, depth)
else:
return varname
else:
return template(basedir, varname, vars, lookup_fatal)
elif isinstance(varname, (list, tuple)):
return [template_ds(basedir, v, vars, lookup_fatal, depth) for v in varname]
elif isinstance(varname, dict):
d = {}
for (k, v) in varname.iteritems():
d[k] = template_ds(basedir, v, vars, lookup_fatal, depth)
return d
else:
return varname
|
[
"def",
"template_ds",
"(",
"basedir",
",",
"varname",
",",
"vars",
",",
"lookup_fatal",
"=",
"True",
",",
"depth",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"varname",
",",
"basestring",
")",
":",
"m",
"=",
"_varFind",
"(",
"basedir",
",",
"varname",
",",
"vars",
",",
"lookup_fatal",
",",
"depth",
")",
"if",
"not",
"m",
":",
"return",
"varname",
"if",
"m",
"[",
"'start'",
"]",
"==",
"0",
"and",
"m",
"[",
"'end'",
"]",
"==",
"len",
"(",
"varname",
")",
":",
"if",
"m",
"[",
"'replacement'",
"]",
"is",
"not",
"None",
":",
"return",
"template_ds",
"(",
"basedir",
",",
"m",
"[",
"'replacement'",
"]",
",",
"vars",
",",
"lookup_fatal",
",",
"depth",
")",
"else",
":",
"return",
"varname",
"else",
":",
"return",
"template",
"(",
"basedir",
",",
"varname",
",",
"vars",
",",
"lookup_fatal",
")",
"elif",
"isinstance",
"(",
"varname",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"template_ds",
"(",
"basedir",
",",
"v",
",",
"vars",
",",
"lookup_fatal",
",",
"depth",
")",
"for",
"v",
"in",
"varname",
"]",
"elif",
"isinstance",
"(",
"varname",
",",
"dict",
")",
":",
"d",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"varname",
".",
"iteritems",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"template_ds",
"(",
"basedir",
",",
"v",
",",
"vars",
",",
"lookup_fatal",
",",
"depth",
")",
"return",
"d",
"else",
":",
"return",
"varname"
] |
templates a data structure by traversing it and substituting for other data structures
|
[
"templates",
"a",
"data",
"structure",
"by",
"traversing",
"it",
"and",
"substituting",
"for",
"other",
"data",
"structures"
] |
977409929dd81322d886425cdced10608117d5d7
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/template.py#L219-L241
|
246,430 |
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/utils/template.py
|
template
|
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):
''' run a text buffer through the templating engine until it no longer changes '''
try:
text = text.decode('utf-8')
except UnicodeEncodeError:
pass # already unicode
text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists)
return text
|
python
|
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):
''' run a text buffer through the templating engine until it no longer changes '''
try:
text = text.decode('utf-8')
except UnicodeEncodeError:
pass # already unicode
text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists)
return text
|
[
"def",
"template",
"(",
"basedir",
",",
"text",
",",
"vars",
",",
"lookup_fatal",
"=",
"True",
",",
"expand_lists",
"=",
"False",
")",
":",
"try",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeEncodeError",
":",
"pass",
"# already unicode",
"text",
"=",
"varReplace",
"(",
"basedir",
",",
"unicode",
"(",
"text",
")",
",",
"vars",
",",
"lookup_fatal",
"=",
"lookup_fatal",
",",
"expand_lists",
"=",
"expand_lists",
")",
"return",
"text"
] |
run a text buffer through the templating engine until it no longer changes
|
[
"run",
"a",
"text",
"buffer",
"through",
"the",
"templating",
"engine",
"until",
"it",
"no",
"longer",
"changes"
] |
977409929dd81322d886425cdced10608117d5d7
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/template.py#L243-L251
|
246,431 |
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/utils/template.py
|
template_from_file
|
def template_from_file(basedir, path, vars):
''' run a file through the templating engine '''
from cirruscluster.ext.ansible import utils
realpath = utils.path_dwim(basedir, path)
loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
environment = jinja2.Environment(loader=loader, trim_blocks=True)
for filter_plugin in utils.plugins.filter_loader.all():
filters = filter_plugin.filters()
if not isinstance(filters, dict):
raise errors.AnsibleError("FilterModule.filters should return a dict.")
environment.filters.update(filters)
try:
data = codecs.open(realpath, encoding="utf8").read()
except UnicodeDecodeError:
raise errors.AnsibleError("unable to process as utf-8: %s" % realpath)
except:
raise errors.AnsibleError("unable to read %s" % realpath)
# Get jinja env overrides from template
if data.startswith(JINJA2_OVERRIDE):
eol = data.find('\n')
line = data[len(JINJA2_OVERRIDE):eol]
data = data[eol+1:]
for pair in line.split(','):
(key,val) = pair.split(':')
setattr(environment,key.strip(),val.strip())
environment.template_class = J2Template
t = environment.from_string(data)
vars = vars.copy()
try:
template_uid = pwd.getpwuid(os.stat(realpath).st_uid).pw_name
except:
template_uid = os.stat(realpath).st_uid
vars['template_host'] = os.uname()[1]
vars['template_path'] = realpath
vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(realpath))
vars['template_uid'] = template_uid
vars['template_fullpath'] = os.path.abspath(realpath)
vars['template_run_date'] = datetime.datetime.now()
managed_default = C.DEFAULT_MANAGED_STR
managed_str = managed_default.format(
host = vars['template_host'],
uid = vars['template_uid'],
file = vars['template_path']
)
vars['ansible_managed'] = time.strftime(managed_str,
time.localtime(os.path.getmtime(realpath)))
# This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars
# Ideally, this could use some API where setting shared=True and the object won't get
# passed through dict(o), but I have not found that yet.
res = jinja2.utils.concat(t.root_render_func(t.new_context(_jinja2_vars(basedir, vars, t.globals), shared=True)))
if data.endswith('\n') and not res.endswith('\n'):
res = res + '\n'
return template(basedir, res, vars)
|
python
|
def template_from_file(basedir, path, vars):
''' run a file through the templating engine '''
from cirruscluster.ext.ansible import utils
realpath = utils.path_dwim(basedir, path)
loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
environment = jinja2.Environment(loader=loader, trim_blocks=True)
for filter_plugin in utils.plugins.filter_loader.all():
filters = filter_plugin.filters()
if not isinstance(filters, dict):
raise errors.AnsibleError("FilterModule.filters should return a dict.")
environment.filters.update(filters)
try:
data = codecs.open(realpath, encoding="utf8").read()
except UnicodeDecodeError:
raise errors.AnsibleError("unable to process as utf-8: %s" % realpath)
except:
raise errors.AnsibleError("unable to read %s" % realpath)
# Get jinja env overrides from template
if data.startswith(JINJA2_OVERRIDE):
eol = data.find('\n')
line = data[len(JINJA2_OVERRIDE):eol]
data = data[eol+1:]
for pair in line.split(','):
(key,val) = pair.split(':')
setattr(environment,key.strip(),val.strip())
environment.template_class = J2Template
t = environment.from_string(data)
vars = vars.copy()
try:
template_uid = pwd.getpwuid(os.stat(realpath).st_uid).pw_name
except:
template_uid = os.stat(realpath).st_uid
vars['template_host'] = os.uname()[1]
vars['template_path'] = realpath
vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(realpath))
vars['template_uid'] = template_uid
vars['template_fullpath'] = os.path.abspath(realpath)
vars['template_run_date'] = datetime.datetime.now()
managed_default = C.DEFAULT_MANAGED_STR
managed_str = managed_default.format(
host = vars['template_host'],
uid = vars['template_uid'],
file = vars['template_path']
)
vars['ansible_managed'] = time.strftime(managed_str,
time.localtime(os.path.getmtime(realpath)))
# This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars
# Ideally, this could use some API where setting shared=True and the object won't get
# passed through dict(o), but I have not found that yet.
res = jinja2.utils.concat(t.root_render_func(t.new_context(_jinja2_vars(basedir, vars, t.globals), shared=True)))
if data.endswith('\n') and not res.endswith('\n'):
res = res + '\n'
return template(basedir, res, vars)
|
[
"def",
"template_from_file",
"(",
"basedir",
",",
"path",
",",
"vars",
")",
":",
"from",
"cirruscluster",
".",
"ext",
".",
"ansible",
"import",
"utils",
"realpath",
"=",
"utils",
".",
"path_dwim",
"(",
"basedir",
",",
"path",
")",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"[",
"basedir",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"realpath",
")",
"]",
")",
"environment",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"loader",
",",
"trim_blocks",
"=",
"True",
")",
"for",
"filter_plugin",
"in",
"utils",
".",
"plugins",
".",
"filter_loader",
".",
"all",
"(",
")",
":",
"filters",
"=",
"filter_plugin",
".",
"filters",
"(",
")",
"if",
"not",
"isinstance",
"(",
"filters",
",",
"dict",
")",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"FilterModule.filters should return a dict.\"",
")",
"environment",
".",
"filters",
".",
"update",
"(",
"filters",
")",
"try",
":",
"data",
"=",
"codecs",
".",
"open",
"(",
"realpath",
",",
"encoding",
"=",
"\"utf8\"",
")",
".",
"read",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"unable to process as utf-8: %s\"",
"%",
"realpath",
")",
"except",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"unable to read %s\"",
"%",
"realpath",
")",
"# Get jinja env overrides from template",
"if",
"data",
".",
"startswith",
"(",
"JINJA2_OVERRIDE",
")",
":",
"eol",
"=",
"data",
".",
"find",
"(",
"'\\n'",
")",
"line",
"=",
"data",
"[",
"len",
"(",
"JINJA2_OVERRIDE",
")",
":",
"eol",
"]",
"data",
"=",
"data",
"[",
"eol",
"+",
"1",
":",
"]",
"for",
"pair",
"in",
"line",
".",
"split",
"(",
"','",
")",
":",
"(",
"key",
",",
"val",
")",
"=",
"pair",
".",
"split",
"(",
"':'",
")",
"setattr",
"(",
"environment",
",",
"key",
".",
"strip",
"(",
")",
",",
"val",
".",
"strip",
"(",
")",
")",
"environment",
".",
"template_class",
"=",
"J2Template",
"t",
"=",
"environment",
".",
"from_string",
"(",
"data",
")",
"vars",
"=",
"vars",
".",
"copy",
"(",
")",
"try",
":",
"template_uid",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"stat",
"(",
"realpath",
")",
".",
"st_uid",
")",
".",
"pw_name",
"except",
":",
"template_uid",
"=",
"os",
".",
"stat",
"(",
"realpath",
")",
".",
"st_uid",
"vars",
"[",
"'template_host'",
"]",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"1",
"]",
"vars",
"[",
"'template_path'",
"]",
"=",
"realpath",
"vars",
"[",
"'template_mtime'",
"]",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"realpath",
")",
")",
"vars",
"[",
"'template_uid'",
"]",
"=",
"template_uid",
"vars",
"[",
"'template_fullpath'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"realpath",
")",
"vars",
"[",
"'template_run_date'",
"]",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"managed_default",
"=",
"C",
".",
"DEFAULT_MANAGED_STR",
"managed_str",
"=",
"managed_default",
".",
"format",
"(",
"host",
"=",
"vars",
"[",
"'template_host'",
"]",
",",
"uid",
"=",
"vars",
"[",
"'template_uid'",
"]",
",",
"file",
"=",
"vars",
"[",
"'template_path'",
"]",
")",
"vars",
"[",
"'ansible_managed'",
"]",
"=",
"time",
".",
"strftime",
"(",
"managed_str",
",",
"time",
".",
"localtime",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"realpath",
")",
")",
")",
"# This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars",
"# Ideally, this could use some API where setting shared=True and the object won't get",
"# passed through dict(o), but I have not found that yet.",
"res",
"=",
"jinja2",
".",
"utils",
".",
"concat",
"(",
"t",
".",
"root_render_func",
"(",
"t",
".",
"new_context",
"(",
"_jinja2_vars",
"(",
"basedir",
",",
"vars",
",",
"t",
".",
"globals",
")",
",",
"shared",
"=",
"True",
")",
")",
")",
"if",
"data",
".",
"endswith",
"(",
"'\\n'",
")",
"and",
"not",
"res",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"res",
"=",
"res",
"+",
"'\\n'",
"return",
"template",
"(",
"basedir",
",",
"res",
",",
"vars",
")"
] |
run a file through the templating engine
|
[
"run",
"a",
"file",
"through",
"the",
"templating",
"engine"
] |
977409929dd81322d886425cdced10608117d5d7
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/template.py#L311-L369
|
246,432 |
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/utils/template.py
|
_jinja2_vars.add_locals
|
def add_locals(self, locals):
'''
If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy.
'''
if locals is None:
return self
return _jinja2_vars(self.basedir, self.vars, self.globals, locals, *self.extras)
|
python
|
def add_locals(self, locals):
'''
If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy.
'''
if locals is None:
return self
return _jinja2_vars(self.basedir, self.vars, self.globals, locals, *self.extras)
|
[
"def",
"add_locals",
"(",
"self",
",",
"locals",
")",
":",
"if",
"locals",
"is",
"None",
":",
"return",
"self",
"return",
"_jinja2_vars",
"(",
"self",
".",
"basedir",
",",
"self",
".",
"vars",
",",
"self",
".",
"globals",
",",
"locals",
",",
"*",
"self",
".",
"extras",
")"
] |
If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy.
|
[
"If",
"locals",
"are",
"provided",
"create",
"a",
"copy",
"of",
"self",
"containing",
"those",
"locals",
"in",
"addition",
"to",
"what",
"is",
"already",
"in",
"this",
"variable",
"proxy",
"."
] |
977409929dd81322d886425cdced10608117d5d7
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/template.py#L292-L299
|
246,433 |
alexhayes/django-toolkit
|
django_toolkit/templatetags/cache_helpers.py
|
expire_cache
|
def expire_cache(fragment_name, *args):
"""
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
"""
cache_key = make_template_fragment_key(fragment_name, args)
cache.delete(cache_key)
|
python
|
def expire_cache(fragment_name, *args):
"""
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
"""
cache_key = make_template_fragment_key(fragment_name, args)
cache.delete(cache_key)
|
[
"def",
"expire_cache",
"(",
"fragment_name",
",",
"*",
"args",
")",
":",
"cache_key",
"=",
"make_template_fragment_key",
"(",
"fragment_name",
",",
"args",
")",
"cache",
".",
"delete",
"(",
"cache_key",
")"
] |
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
|
[
"Expire",
"a",
"cache",
"item",
"."
] |
b64106392fad596defc915b8235fe6e1d0013b5b
|
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/templatetags/cache_helpers.py#L8-L18
|
246,434 |
FujiMakoto/IPS-Vagrant
|
ips_vagrant/installer/V_4_1_3_2.py
|
Installer.start
|
def start(self):
"""
Start the installation wizard
"""
self.log.debug('Starting the installation process')
self.browser.open(self.url)
self.system_check()
|
python
|
def start(self):
"""
Start the installation wizard
"""
self.log.debug('Starting the installation process')
self.browser.open(self.url)
self.system_check()
|
[
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Starting the installation process'",
")",
"self",
".",
"browser",
".",
"open",
"(",
"self",
".",
"url",
")",
"self",
".",
"system_check",
"(",
")"
] |
Start the installation wizard
|
[
"Start",
"the",
"installation",
"wizard"
] |
7b1d6d095034dd8befb026d9315ecc6494d52269
|
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L13-L21
|
246,435 |
FujiMakoto/IPS-Vagrant
|
ips_vagrant/installer/V_4_1_3_2.py
|
Installer.admin
|
def admin(self):
"""
Provide admin login credentials
"""
self._check_title(self.browser.title())
self.browser.select_form(nr=0)
# Get the admin credentials
prompted = []
user = self.ctx.config.get('User', 'AdminUser')
if not user:
user = click.prompt('Admin display name')
prompted.append('user')
password = self.ctx.config.get('User', 'AdminPass')
if not password:
password = click.prompt('Admin password', hide_input=True, confirmation_prompt='Confirm admin password')
prompted.append('password')
email = self.ctx.config.get('User', 'AdminEmail')
if not email:
email = click.prompt('Admin email')
prompted.append('email')
self.browser.form[self.FIELD_ADMIN_USER] = user
self.browser.form[self.FIELD_ADMIN_PASS] = password
self.browser.form[self.FIELD_ADMIN_PASS_CONFIRM] = password
self.browser.form[self.FIELD_ADMIN_EMAIL] = email
p = Echo('Submitting admin information...')
self.browser.submit()
p.done()
if len(prompted) >= 3:
save = click.confirm('Would you like to save and use these admin credentials for future installations?')
if save:
self.log.info('Saving admin login credentials')
self.ctx.config.set('User', 'AdminUser', user)
self.ctx.config.set('User', 'AdminPass', password)
self.ctx.config.set('User', 'AdminEmail', email)
with open(self.ctx.config_path, 'wb') as cf:
self.ctx.config.write(cf)
self.install()
|
python
|
def admin(self):
"""
Provide admin login credentials
"""
self._check_title(self.browser.title())
self.browser.select_form(nr=0)
# Get the admin credentials
prompted = []
user = self.ctx.config.get('User', 'AdminUser')
if not user:
user = click.prompt('Admin display name')
prompted.append('user')
password = self.ctx.config.get('User', 'AdminPass')
if not password:
password = click.prompt('Admin password', hide_input=True, confirmation_prompt='Confirm admin password')
prompted.append('password')
email = self.ctx.config.get('User', 'AdminEmail')
if not email:
email = click.prompt('Admin email')
prompted.append('email')
self.browser.form[self.FIELD_ADMIN_USER] = user
self.browser.form[self.FIELD_ADMIN_PASS] = password
self.browser.form[self.FIELD_ADMIN_PASS_CONFIRM] = password
self.browser.form[self.FIELD_ADMIN_EMAIL] = email
p = Echo('Submitting admin information...')
self.browser.submit()
p.done()
if len(prompted) >= 3:
save = click.confirm('Would you like to save and use these admin credentials for future installations?')
if save:
self.log.info('Saving admin login credentials')
self.ctx.config.set('User', 'AdminUser', user)
self.ctx.config.set('User', 'AdminPass', password)
self.ctx.config.set('User', 'AdminEmail', email)
with open(self.ctx.config_path, 'wb') as cf:
self.ctx.config.write(cf)
self.install()
|
[
"def",
"admin",
"(",
"self",
")",
":",
"self",
".",
"_check_title",
"(",
"self",
".",
"browser",
".",
"title",
"(",
")",
")",
"self",
".",
"browser",
".",
"select_form",
"(",
"nr",
"=",
"0",
")",
"# Get the admin credentials",
"prompted",
"=",
"[",
"]",
"user",
"=",
"self",
".",
"ctx",
".",
"config",
".",
"get",
"(",
"'User'",
",",
"'AdminUser'",
")",
"if",
"not",
"user",
":",
"user",
"=",
"click",
".",
"prompt",
"(",
"'Admin display name'",
")",
"prompted",
".",
"append",
"(",
"'user'",
")",
"password",
"=",
"self",
".",
"ctx",
".",
"config",
".",
"get",
"(",
"'User'",
",",
"'AdminPass'",
")",
"if",
"not",
"password",
":",
"password",
"=",
"click",
".",
"prompt",
"(",
"'Admin password'",
",",
"hide_input",
"=",
"True",
",",
"confirmation_prompt",
"=",
"'Confirm admin password'",
")",
"prompted",
".",
"append",
"(",
"'password'",
")",
"email",
"=",
"self",
".",
"ctx",
".",
"config",
".",
"get",
"(",
"'User'",
",",
"'AdminEmail'",
")",
"if",
"not",
"email",
":",
"email",
"=",
"click",
".",
"prompt",
"(",
"'Admin email'",
")",
"prompted",
".",
"append",
"(",
"'email'",
")",
"self",
".",
"browser",
".",
"form",
"[",
"self",
".",
"FIELD_ADMIN_USER",
"]",
"=",
"user",
"self",
".",
"browser",
".",
"form",
"[",
"self",
".",
"FIELD_ADMIN_PASS",
"]",
"=",
"password",
"self",
".",
"browser",
".",
"form",
"[",
"self",
".",
"FIELD_ADMIN_PASS_CONFIRM",
"]",
"=",
"password",
"self",
".",
"browser",
".",
"form",
"[",
"self",
".",
"FIELD_ADMIN_EMAIL",
"]",
"=",
"email",
"p",
"=",
"Echo",
"(",
"'Submitting admin information...'",
")",
"self",
".",
"browser",
".",
"submit",
"(",
")",
"p",
".",
"done",
"(",
")",
"if",
"len",
"(",
"prompted",
")",
">=",
"3",
":",
"save",
"=",
"click",
".",
"confirm",
"(",
"'Would you like to save and use these admin credentials for future installations?'",
")",
"if",
"save",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Saving admin login credentials'",
")",
"self",
".",
"ctx",
".",
"config",
".",
"set",
"(",
"'User'",
",",
"'AdminUser'",
",",
"user",
")",
"self",
".",
"ctx",
".",
"config",
".",
"set",
"(",
"'User'",
",",
"'AdminPass'",
",",
"password",
")",
"self",
".",
"ctx",
".",
"config",
".",
"set",
"(",
"'User'",
",",
"'AdminEmail'",
",",
"email",
")",
"with",
"open",
"(",
"self",
".",
"ctx",
".",
"config_path",
",",
"'wb'",
")",
"as",
"cf",
":",
"self",
".",
"ctx",
".",
"config",
".",
"write",
"(",
"cf",
")",
"self",
".",
"install",
"(",
")"
] |
Provide admin login credentials
|
[
"Provide",
"admin",
"login",
"credentials"
] |
7b1d6d095034dd8befb026d9315ecc6494d52269
|
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L23-L65
|
246,436 |
FujiMakoto/IPS-Vagrant
|
ips_vagrant/installer/V_4_1_3_2.py
|
Installer._start_install
|
def _start_install(self):
"""
Start the installation
"""
self._check_title(self.browser.title())
continue_link = next(self.browser.links(text_regex='Start Installation'))
self.browser.follow_link(continue_link)
|
python
|
def _start_install(self):
"""
Start the installation
"""
self._check_title(self.browser.title())
continue_link = next(self.browser.links(text_regex='Start Installation'))
self.browser.follow_link(continue_link)
|
[
"def",
"_start_install",
"(",
"self",
")",
":",
"self",
".",
"_check_title",
"(",
"self",
".",
"browser",
".",
"title",
"(",
")",
")",
"continue_link",
"=",
"next",
"(",
"self",
".",
"browser",
".",
"links",
"(",
"text_regex",
"=",
"'Start Installation'",
")",
")",
"self",
".",
"browser",
".",
"follow_link",
"(",
"continue_link",
")"
] |
Start the installation
|
[
"Start",
"the",
"installation"
] |
7b1d6d095034dd8befb026d9315ecc6494d52269
|
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L67-L73
|
246,437 |
FujiMakoto/IPS-Vagrant
|
ips_vagrant/installer/V_4_1_3_2.py
|
Installer.install
|
def install(self):
"""
Run the actual installation
"""
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop until we get a redirect json response
while True:
mr_link = self._parse_response(mr_link, mr_j)
stage = self._get_stage(mr_j)
progress = self._get_progress(mr_j)
mr_j, mr_r = self._ajax(mr_link)
pbar.update(min([progress, 100]), stage) # NOTE: Response may return progress values above 100
# If we're done, finalize the installation and break
redirect = self._check_if_complete(mr_link, mr_j)
if redirect:
pbar.finish()
break
p = Echo('Finalizing...')
mr_r = self._request(redirect, raise_request=False)
p.done()
# Install developer tools
if self.site.in_dev:
DevToolsInstaller(self.ctx, self.site).install()
# Get the link to our community homepage
self._finalize(mr_r)
|
python
|
def install(self):
"""
Run the actual installation
"""
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop until we get a redirect json response
while True:
mr_link = self._parse_response(mr_link, mr_j)
stage = self._get_stage(mr_j)
progress = self._get_progress(mr_j)
mr_j, mr_r = self._ajax(mr_link)
pbar.update(min([progress, 100]), stage) # NOTE: Response may return progress values above 100
# If we're done, finalize the installation and break
redirect = self._check_if_complete(mr_link, mr_j)
if redirect:
pbar.finish()
break
p = Echo('Finalizing...')
mr_r = self._request(redirect, raise_request=False)
p.done()
# Install developer tools
if self.site.in_dev:
DevToolsInstaller(self.ctx, self.site).install()
# Get the link to our community homepage
self._finalize(mr_r)
|
[
"def",
"install",
"(",
"self",
")",
":",
"self",
".",
"_start_install",
"(",
")",
"mr_link",
"=",
"self",
".",
"_get_mr_link",
"(",
")",
"# Set up the progress bar",
"pbar",
"=",
"ProgressBar",
"(",
"100",
",",
"'Running installation...'",
")",
"pbar",
".",
"start",
"(",
")",
"mr_j",
",",
"mr_r",
"=",
"self",
".",
"_ajax",
"(",
"mr_link",
")",
"# Loop until we get a redirect json response",
"while",
"True",
":",
"mr_link",
"=",
"self",
".",
"_parse_response",
"(",
"mr_link",
",",
"mr_j",
")",
"stage",
"=",
"self",
".",
"_get_stage",
"(",
"mr_j",
")",
"progress",
"=",
"self",
".",
"_get_progress",
"(",
"mr_j",
")",
"mr_j",
",",
"mr_r",
"=",
"self",
".",
"_ajax",
"(",
"mr_link",
")",
"pbar",
".",
"update",
"(",
"min",
"(",
"[",
"progress",
",",
"100",
"]",
")",
",",
"stage",
")",
"# NOTE: Response may return progress values above 100",
"# If we're done, finalize the installation and break",
"redirect",
"=",
"self",
".",
"_check_if_complete",
"(",
"mr_link",
",",
"mr_j",
")",
"if",
"redirect",
":",
"pbar",
".",
"finish",
"(",
")",
"break",
"p",
"=",
"Echo",
"(",
"'Finalizing...'",
")",
"mr_r",
"=",
"self",
".",
"_request",
"(",
"redirect",
",",
"raise_request",
"=",
"False",
")",
"p",
".",
"done",
"(",
")",
"# Install developer tools",
"if",
"self",
".",
"site",
".",
"in_dev",
":",
"DevToolsInstaller",
"(",
"self",
".",
"ctx",
",",
"self",
".",
"site",
")",
".",
"install",
"(",
")",
"# Get the link to our community homepage",
"self",
".",
"_finalize",
"(",
"mr_r",
")"
] |
Run the actual installation
|
[
"Run",
"the",
"actual",
"installation"
] |
7b1d6d095034dd8befb026d9315ecc6494d52269
|
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L76-L113
|
246,438 |
redhog/pieshell
|
pieshell/pipe.py
|
pipe_cloexec
|
def pipe_cloexec():
"""Create a pipe with FDs set CLOEXEC."""
# Pipes' FDs are set CLOEXEC by default because we don't want them
# to be inherited by other subprocesses: the CLOEXEC flag is removed
# from the child's FDs by _dup2(), between fork() and exec().
# This is not atomic: we would need the pipe2() syscall for that.
r, w = os.pipe()
_set_cloexec_flag(r)
_set_cloexec_flag(w)
return r, w
|
python
|
def pipe_cloexec():
"""Create a pipe with FDs set CLOEXEC."""
# Pipes' FDs are set CLOEXEC by default because we don't want them
# to be inherited by other subprocesses: the CLOEXEC flag is removed
# from the child's FDs by _dup2(), between fork() and exec().
# This is not atomic: we would need the pipe2() syscall for that.
r, w = os.pipe()
_set_cloexec_flag(r)
_set_cloexec_flag(w)
return r, w
|
[
"def",
"pipe_cloexec",
"(",
")",
":",
"# Pipes' FDs are set CLOEXEC by default because we don't want them",
"# to be inherited by other subprocesses: the CLOEXEC flag is removed",
"# from the child's FDs by _dup2(), between fork() and exec().",
"# This is not atomic: we would need the pipe2() syscall for that.",
"r",
",",
"w",
"=",
"os",
".",
"pipe",
"(",
")",
"_set_cloexec_flag",
"(",
"r",
")",
"_set_cloexec_flag",
"(",
"w",
")",
"return",
"r",
",",
"w"
] |
Create a pipe with FDs set CLOEXEC.
|
[
"Create",
"a",
"pipe",
"with",
"FDs",
"set",
"CLOEXEC",
"."
] |
11cff3b93785ee4446f99b9134be20380edeb767
|
https://github.com/redhog/pieshell/blob/11cff3b93785ee4446f99b9134be20380edeb767/pieshell/pipe.py#L17-L26
|
246,439 |
naphatkrit/easyci
|
easyci/vcs/git.py
|
GitVcs.get_signature
|
def get_signature(self, base_commit=None):
"""Get the signature of the current state of the repository
TODO right now `get_signature` is an effectful process in that
it adds all untracked file to staging. This is the only way to get
accruate diff on new files. This is ok because we only use it on a
disposable copy of the repo.
Args:
base_commit - the base commit ('HEAD', sha, etc.)
Returns:
str
"""
if base_commit is None:
base_commit = 'HEAD'
self.run('add', '-A', self.path)
sha = self.run('rev-parse', '--verify', base_commit).strip()
diff = self.run('diff', sha).strip()
if len(diff) == 0:
try:
return self.get_signature(base_commit + '~1')
except CommandError:
pass
h = hashlib.sha1()
h.update(sha)
h.update(diff)
return h.hexdigest()
|
python
|
def get_signature(self, base_commit=None):
"""Get the signature of the current state of the repository
TODO right now `get_signature` is an effectful process in that
it adds all untracked file to staging. This is the only way to get
accruate diff on new files. This is ok because we only use it on a
disposable copy of the repo.
Args:
base_commit - the base commit ('HEAD', sha, etc.)
Returns:
str
"""
if base_commit is None:
base_commit = 'HEAD'
self.run('add', '-A', self.path)
sha = self.run('rev-parse', '--verify', base_commit).strip()
diff = self.run('diff', sha).strip()
if len(diff) == 0:
try:
return self.get_signature(base_commit + '~1')
except CommandError:
pass
h = hashlib.sha1()
h.update(sha)
h.update(diff)
return h.hexdigest()
|
[
"def",
"get_signature",
"(",
"self",
",",
"base_commit",
"=",
"None",
")",
":",
"if",
"base_commit",
"is",
"None",
":",
"base_commit",
"=",
"'HEAD'",
"self",
".",
"run",
"(",
"'add'",
",",
"'-A'",
",",
"self",
".",
"path",
")",
"sha",
"=",
"self",
".",
"run",
"(",
"'rev-parse'",
",",
"'--verify'",
",",
"base_commit",
")",
".",
"strip",
"(",
")",
"diff",
"=",
"self",
".",
"run",
"(",
"'diff'",
",",
"sha",
")",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"diff",
")",
"==",
"0",
":",
"try",
":",
"return",
"self",
".",
"get_signature",
"(",
"base_commit",
"+",
"'~1'",
")",
"except",
"CommandError",
":",
"pass",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"h",
".",
"update",
"(",
"sha",
")",
"h",
".",
"update",
"(",
"diff",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] |
Get the signature of the current state of the repository
TODO right now `get_signature` is an effectful process in that
it adds all untracked file to staging. This is the only way to get
accruate diff on new files. This is ok because we only use it on a
disposable copy of the repo.
Args:
base_commit - the base commit ('HEAD', sha, etc.)
Returns:
str
|
[
"Get",
"the",
"signature",
"of",
"the",
"current",
"state",
"of",
"the",
"repository"
] |
7aee8d7694fe4e2da42ce35b0f700bc840c8b95f
|
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/vcs/git.py#L82-L109
|
246,440 |
naphatkrit/easyci
|
easyci/vcs/git.py
|
GitVcs.install_hook
|
def install_hook(self, hook_name, hook_content):
"""Install the repository hook for this repo.
Args:
hook_name (str)
hook_content (str)
"""
hook_path = os.path.join(self.path, '.git/hooks', hook_name)
with open(hook_path, 'w') as f:
f.write(hook_content)
os.chmod(hook_path, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
|
python
|
def install_hook(self, hook_name, hook_content):
"""Install the repository hook for this repo.
Args:
hook_name (str)
hook_content (str)
"""
hook_path = os.path.join(self.path, '.git/hooks', hook_name)
with open(hook_path, 'w') as f:
f.write(hook_content)
os.chmod(hook_path, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)
|
[
"def",
"install_hook",
"(",
"self",
",",
"hook_name",
",",
"hook_content",
")",
":",
"hook_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'.git/hooks'",
",",
"hook_name",
")",
"with",
"open",
"(",
"hook_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"hook_content",
")",
"os",
".",
"chmod",
"(",
"hook_path",
",",
"stat",
".",
"S_IEXEC",
"|",
"stat",
".",
"S_IREAD",
"|",
"stat",
".",
"S_IWRITE",
")"
] |
Install the repository hook for this repo.
Args:
hook_name (str)
hook_content (str)
|
[
"Install",
"the",
"repository",
"hook",
"for",
"this",
"repo",
"."
] |
7aee8d7694fe4e2da42ce35b0f700bc840c8b95f
|
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/vcs/git.py#L111-L121
|
246,441 |
naphatkrit/easyci
|
easyci/vcs/git.py
|
GitVcs.get_ignored_files
|
def get_ignored_files(self):
"""Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list of ignored files. The paths are absolute.
"""
return [os.path.join(self.path, p) for p in
self.run('ls-files', '--ignored', '--exclude-standard',
'--others').strip().split()
]
|
python
|
def get_ignored_files(self):
"""Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list of ignored files. The paths are absolute.
"""
return [os.path.join(self.path, p) for p in
self.run('ls-files', '--ignored', '--exclude-standard',
'--others').strip().split()
]
|
[
"def",
"get_ignored_files",
"(",
"self",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"p",
")",
"for",
"p",
"in",
"self",
".",
"run",
"(",
"'ls-files'",
",",
"'--ignored'",
",",
"'--exclude-standard'",
",",
"'--others'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"]"
] |
Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list of ignored files. The paths are absolute.
|
[
"Returns",
"the",
"list",
"of",
"files",
"being",
"ignored",
"in",
"this",
"repository",
"."
] |
7aee8d7694fe4e2da42ce35b0f700bc840c8b95f
|
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/vcs/git.py#L123-L143
|
246,442 |
naphatkrit/easyci
|
easyci/vcs/git.py
|
GitVcs.path_is_ignored
|
def path_is_ignored(self, path):
"""Given a path, check if the path would be ignored.
Returns:
boolean
"""
try:
self.run('check-ignore', '--quiet', path)
except CommandError as e:
if e.retcode == 1:
# path is ignored
return False
else:
# fatal error
raise e
return True
|
python
|
def path_is_ignored(self, path):
"""Given a path, check if the path would be ignored.
Returns:
boolean
"""
try:
self.run('check-ignore', '--quiet', path)
except CommandError as e:
if e.retcode == 1:
# path is ignored
return False
else:
# fatal error
raise e
return True
|
[
"def",
"path_is_ignored",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"self",
".",
"run",
"(",
"'check-ignore'",
",",
"'--quiet'",
",",
"path",
")",
"except",
"CommandError",
"as",
"e",
":",
"if",
"e",
".",
"retcode",
"==",
"1",
":",
"# path is ignored",
"return",
"False",
"else",
":",
"# fatal error",
"raise",
"e",
"return",
"True"
] |
Given a path, check if the path would be ignored.
Returns:
boolean
|
[
"Given",
"a",
"path",
"check",
"if",
"the",
"path",
"would",
"be",
"ignored",
"."
] |
7aee8d7694fe4e2da42ce35b0f700bc840c8b95f
|
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/vcs/git.py#L155-L170
|
246,443 |
etgalloway/newtabmagic
|
newtabmagic.py
|
_get_object_pydoc_page_name
|
def _get_object_pydoc_page_name(obj):
"""Returns fully qualified name, including module name, except for the
built-in module."""
page_name = fullqualname.fullqualname(obj)
if page_name is not None:
page_name = _remove_builtin_prefix(page_name)
return page_name
|
python
|
def _get_object_pydoc_page_name(obj):
"""Returns fully qualified name, including module name, except for the
built-in module."""
page_name = fullqualname.fullqualname(obj)
if page_name is not None:
page_name = _remove_builtin_prefix(page_name)
return page_name
|
[
"def",
"_get_object_pydoc_page_name",
"(",
"obj",
")",
":",
"page_name",
"=",
"fullqualname",
".",
"fullqualname",
"(",
"obj",
")",
"if",
"page_name",
"is",
"not",
"None",
":",
"page_name",
"=",
"_remove_builtin_prefix",
"(",
"page_name",
")",
"return",
"page_name"
] |
Returns fully qualified name, including module name, except for the
built-in module.
|
[
"Returns",
"fully",
"qualified",
"name",
"including",
"module",
"name",
"except",
"for",
"the",
"built",
"-",
"in",
"module",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L242-L248
|
246,444 |
etgalloway/newtabmagic
|
newtabmagic.py
|
_remove_builtin_prefix
|
def _remove_builtin_prefix(name):
"""Strip name of builtin module from start of name."""
if name.startswith('builtins.'):
return name[len('builtins.'):]
elif name.startswith('__builtin__.'):
return name[len('__builtin__.'):]
return name
|
python
|
def _remove_builtin_prefix(name):
"""Strip name of builtin module from start of name."""
if name.startswith('builtins.'):
return name[len('builtins.'):]
elif name.startswith('__builtin__.'):
return name[len('__builtin__.'):]
return name
|
[
"def",
"_remove_builtin_prefix",
"(",
"name",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'builtins.'",
")",
":",
"return",
"name",
"[",
"len",
"(",
"'builtins.'",
")",
":",
"]",
"elif",
"name",
".",
"startswith",
"(",
"'__builtin__.'",
")",
":",
"return",
"name",
"[",
"len",
"(",
"'__builtin__.'",
")",
":",
"]",
"return",
"name"
] |
Strip name of builtin module from start of name.
|
[
"Strip",
"name",
"of",
"builtin",
"module",
"from",
"start",
"of",
"name",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L251-L257
|
246,445 |
etgalloway/newtabmagic
|
newtabmagic.py
|
_get_user_ns_object
|
def _get_user_ns_object(shell, path):
"""Get object from the user namespace, given a path containing
zero or more dots. Return None if the path is not valid.
"""
parts = path.split('.', 1)
name, attr = parts[0], parts[1:]
if name in shell.user_ns:
if attr:
try:
return _getattr(shell.user_ns[name], attr[0])
except AttributeError:
return None
else:
return shell.user_ns[name]
return None
|
python
|
def _get_user_ns_object(shell, path):
"""Get object from the user namespace, given a path containing
zero or more dots. Return None if the path is not valid.
"""
parts = path.split('.', 1)
name, attr = parts[0], parts[1:]
if name in shell.user_ns:
if attr:
try:
return _getattr(shell.user_ns[name], attr[0])
except AttributeError:
return None
else:
return shell.user_ns[name]
return None
|
[
"def",
"_get_user_ns_object",
"(",
"shell",
",",
"path",
")",
":",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"name",
",",
"attr",
"=",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
":",
"]",
"if",
"name",
"in",
"shell",
".",
"user_ns",
":",
"if",
"attr",
":",
"try",
":",
"return",
"_getattr",
"(",
"shell",
".",
"user_ns",
"[",
"name",
"]",
",",
"attr",
"[",
"0",
"]",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"return",
"shell",
".",
"user_ns",
"[",
"name",
"]",
"return",
"None"
] |
Get object from the user namespace, given a path containing
zero or more dots. Return None if the path is not valid.
|
[
"Get",
"object",
"from",
"the",
"user",
"namespace",
"given",
"a",
"path",
"containing",
"zero",
"or",
"more",
"dots",
".",
"Return",
"None",
"if",
"the",
"path",
"is",
"not",
"valid",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L260-L274
|
246,446 |
etgalloway/newtabmagic
|
newtabmagic.py
|
_stop_process
|
def _stop_process(p, name):
"""Stop process, by applying terminate and kill."""
# Based on code in IPython.core.magics.script.ScriptMagics.shebang
if p.poll() is not None:
print("{} is already stopped.".format(name))
return
p.terminate()
time.sleep(0.1)
if p.poll() is not None:
print("{} is terminated.".format(name))
return
p.kill()
print("{} is killed.".format(name))
|
python
|
def _stop_process(p, name):
"""Stop process, by applying terminate and kill."""
# Based on code in IPython.core.magics.script.ScriptMagics.shebang
if p.poll() is not None:
print("{} is already stopped.".format(name))
return
p.terminate()
time.sleep(0.1)
if p.poll() is not None:
print("{} is terminated.".format(name))
return
p.kill()
print("{} is killed.".format(name))
|
[
"def",
"_stop_process",
"(",
"p",
",",
"name",
")",
":",
"# Based on code in IPython.core.magics.script.ScriptMagics.shebang",
"if",
"p",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"print",
"(",
"\"{} is already stopped.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"p",
".",
"terminate",
"(",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"if",
"p",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"print",
"(",
"\"{} is terminated.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"p",
".",
"kill",
"(",
")",
"print",
"(",
"\"{} is killed.\"",
".",
"format",
"(",
"name",
")",
")"
] |
Stop process, by applying terminate and kill.
|
[
"Stop",
"process",
"by",
"applying",
"terminate",
"and",
"kill",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L285-L297
|
246,447 |
etgalloway/newtabmagic
|
newtabmagic.py
|
pydoc_cli_monkey_patched
|
def pydoc_cli_monkey_patched(port):
"""In Python 3, run pydoc.cli with builtins.input monkey-patched
so that pydoc can be run as a process.
"""
# Monkey-patch input so that input does not raise EOFError when
# called by pydoc.cli
def input(_): # pylint: disable=W0622
"""Monkey-patched version of builtins.input"""
while 1:
time.sleep(1.0)
import builtins
builtins.input = input
sys.argv += ["-p", port]
pydoc.cli()
|
python
|
def pydoc_cli_monkey_patched(port):
"""In Python 3, run pydoc.cli with builtins.input monkey-patched
so that pydoc can be run as a process.
"""
# Monkey-patch input so that input does not raise EOFError when
# called by pydoc.cli
def input(_): # pylint: disable=W0622
"""Monkey-patched version of builtins.input"""
while 1:
time.sleep(1.0)
import builtins
builtins.input = input
sys.argv += ["-p", port]
pydoc.cli()
|
[
"def",
"pydoc_cli_monkey_patched",
"(",
"port",
")",
":",
"# Monkey-patch input so that input does not raise EOFError when",
"# called by pydoc.cli",
"def",
"input",
"(",
"_",
")",
":",
"# pylint: disable=W0622",
"\"\"\"Monkey-patched version of builtins.input\"\"\"",
"while",
"1",
":",
"time",
".",
"sleep",
"(",
"1.0",
")",
"import",
"builtins",
"builtins",
".",
"input",
"=",
"input",
"sys",
".",
"argv",
"+=",
"[",
"\"-p\"",
",",
"port",
"]",
"pydoc",
".",
"cli",
"(",
")"
] |
In Python 3, run pydoc.cli with builtins.input monkey-patched
so that pydoc can be run as a process.
|
[
"In",
"Python",
"3",
"run",
"pydoc",
".",
"cli",
"with",
"builtins",
".",
"input",
"monkey",
"-",
"patched",
"so",
"that",
"pydoc",
"can",
"be",
"run",
"as",
"a",
"process",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L300-L315
|
246,448 |
etgalloway/newtabmagic
|
newtabmagic.py
|
start_server_background
|
def start_server_background(port):
"""Start the newtab server as a background process."""
if sys.version_info[0] == 2:
lines = ('import pydoc\n'
'pydoc.serve({port})')
cell = lines.format(port=port)
else:
# The location of newtabmagic (normally $IPYTHONDIR/extensions)
# needs to be added to sys.path.
path = repr(os.path.dirname(os.path.realpath(__file__)))
lines = ('import sys\n'
'sys.path.append({path})\n'
'import newtabmagic\n'
'newtabmagic.pydoc_cli_monkey_patched({port})')
cell = lines.format(path=path, port=port)
# Use script cell magic so that shutting down IPython stops
# the server process.
line = "python --proc proc --bg --err error --out output"
ip = get_ipython()
ip.run_cell_magic("script", line, cell)
return ip.user_ns['proc']
|
python
|
def start_server_background(port):
"""Start the newtab server as a background process."""
if sys.version_info[0] == 2:
lines = ('import pydoc\n'
'pydoc.serve({port})')
cell = lines.format(port=port)
else:
# The location of newtabmagic (normally $IPYTHONDIR/extensions)
# needs to be added to sys.path.
path = repr(os.path.dirname(os.path.realpath(__file__)))
lines = ('import sys\n'
'sys.path.append({path})\n'
'import newtabmagic\n'
'newtabmagic.pydoc_cli_monkey_patched({port})')
cell = lines.format(path=path, port=port)
# Use script cell magic so that shutting down IPython stops
# the server process.
line = "python --proc proc --bg --err error --out output"
ip = get_ipython()
ip.run_cell_magic("script", line, cell)
return ip.user_ns['proc']
|
[
"def",
"start_server_background",
"(",
"port",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"lines",
"=",
"(",
"'import pydoc\\n'",
"'pydoc.serve({port})'",
")",
"cell",
"=",
"lines",
".",
"format",
"(",
"port",
"=",
"port",
")",
"else",
":",
"# The location of newtabmagic (normally $IPYTHONDIR/extensions)",
"# needs to be added to sys.path.",
"path",
"=",
"repr",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
")",
"lines",
"=",
"(",
"'import sys\\n'",
"'sys.path.append({path})\\n'",
"'import newtabmagic\\n'",
"'newtabmagic.pydoc_cli_monkey_patched({port})'",
")",
"cell",
"=",
"lines",
".",
"format",
"(",
"path",
"=",
"path",
",",
"port",
"=",
"port",
")",
"# Use script cell magic so that shutting down IPython stops",
"# the server process.",
"line",
"=",
"\"python --proc proc --bg --err error --out output\"",
"ip",
"=",
"get_ipython",
"(",
")",
"ip",
".",
"run_cell_magic",
"(",
"\"script\"",
",",
"line",
",",
"cell",
")",
"return",
"ip",
".",
"user_ns",
"[",
"'proc'",
"]"
] |
Start the newtab server as a background process.
|
[
"Start",
"the",
"newtab",
"server",
"as",
"a",
"background",
"process",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L318-L341
|
246,449 |
etgalloway/newtabmagic
|
newtabmagic.py
|
_port_not_in_use
|
def _port_not_in_use():
"""Use the port 0 trick to find a port not in use."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 0
s.bind(('', port))
_, port = s.getsockname()
return port
|
python
|
def _port_not_in_use():
"""Use the port 0 trick to find a port not in use."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 0
s.bind(('', port))
_, port = s.getsockname()
return port
|
[
"def",
"_port_not_in_use",
"(",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"port",
"=",
"0",
"s",
".",
"bind",
"(",
"(",
"''",
",",
"port",
")",
")",
"_",
",",
"port",
"=",
"s",
".",
"getsockname",
"(",
")",
"return",
"port"
] |
Use the port 0 trick to find a port not in use.
|
[
"Use",
"the",
"port",
"0",
"trick",
"to",
"find",
"a",
"port",
"not",
"in",
"use",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L344-L350
|
246,450 |
etgalloway/newtabmagic
|
newtabmagic.py
|
ServerProcess.start
|
def start(self):
"""Start server if not previously started."""
msg = ''
if not self.running():
if self._port == 0:
self._port = _port_not_in_use()
self._process = start_server_background(self._port)
else:
msg = 'Server already started\n'
msg += 'Server running at {}'.format(self.url())
print(msg)
|
python
|
def start(self):
"""Start server if not previously started."""
msg = ''
if not self.running():
if self._port == 0:
self._port = _port_not_in_use()
self._process = start_server_background(self._port)
else:
msg = 'Server already started\n'
msg += 'Server running at {}'.format(self.url())
print(msg)
|
[
"def",
"start",
"(",
"self",
")",
":",
"msg",
"=",
"''",
"if",
"not",
"self",
".",
"running",
"(",
")",
":",
"if",
"self",
".",
"_port",
"==",
"0",
":",
"self",
".",
"_port",
"=",
"_port_not_in_use",
"(",
")",
"self",
".",
"_process",
"=",
"start_server_background",
"(",
"self",
".",
"_port",
")",
"else",
":",
"msg",
"=",
"'Server already started\\n'",
"msg",
"+=",
"'Server running at {}'",
".",
"format",
"(",
"self",
".",
"url",
"(",
")",
")",
"print",
"(",
"msg",
")"
] |
Start server if not previously started.
|
[
"Start",
"server",
"if",
"not",
"previously",
"started",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L173-L183
|
246,451 |
etgalloway/newtabmagic
|
newtabmagic.py
|
ServerProcess.read
|
def read(self):
"""Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode()
else:
out = ''
err = ''
return out, err
|
python
|
def read(self):
"""Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode()
else:
out = ''
err = ''
return out, err
|
[
"def",
"read",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
"and",
"self",
".",
"_process",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"err",
"=",
"ip",
".",
"user_ns",
"[",
"'error'",
"]",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"out",
"=",
"ip",
".",
"user_ns",
"[",
"'output'",
"]",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"else",
":",
"out",
"=",
"''",
"err",
"=",
"''",
"return",
"out",
",",
"err"
] |
Read stdout and stdout pipes if process is no longer running.
|
[
"Read",
"stdout",
"and",
"stdout",
"pipes",
"if",
"process",
"is",
"no",
"longer",
"running",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L185-L194
|
246,452 |
etgalloway/newtabmagic
|
newtabmagic.py
|
ServerProcess.stop
|
def stop(self):
"""Stop server process."""
msg = ''
if self._process:
_stop_process(self._process, 'Server process')
else:
msg += 'Server not started.\n'
if msg:
print(msg, end='')
|
python
|
def stop(self):
"""Stop server process."""
msg = ''
if self._process:
_stop_process(self._process, 'Server process')
else:
msg += 'Server not started.\n'
if msg:
print(msg, end='')
|
[
"def",
"stop",
"(",
"self",
")",
":",
"msg",
"=",
"''",
"if",
"self",
".",
"_process",
":",
"_stop_process",
"(",
"self",
".",
"_process",
",",
"'Server process'",
")",
"else",
":",
"msg",
"+=",
"'Server not started.\\n'",
"if",
"msg",
":",
"print",
"(",
"msg",
",",
"end",
"=",
"''",
")"
] |
Stop server process.
|
[
"Stop",
"server",
"process",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L196-L205
|
246,453 |
etgalloway/newtabmagic
|
newtabmagic.py
|
ServerProcess.show
|
def show(self):
"""Show state."""
msg = ''
if self._process:
msg += 'server pid: {}\n'.format(self._process.pid)
msg += 'server poll: {}\n'.format(self._process.poll())
msg += 'server running: {}\n'.format(self.running())
msg += 'server port: {}\n'.format(self._port)
msg += 'server root url: {}\n'.format(self.url())
print(msg, end='')
|
python
|
def show(self):
"""Show state."""
msg = ''
if self._process:
msg += 'server pid: {}\n'.format(self._process.pid)
msg += 'server poll: {}\n'.format(self._process.poll())
msg += 'server running: {}\n'.format(self.running())
msg += 'server port: {}\n'.format(self._port)
msg += 'server root url: {}\n'.format(self.url())
print(msg, end='')
|
[
"def",
"show",
"(",
"self",
")",
":",
"msg",
"=",
"''",
"if",
"self",
".",
"_process",
":",
"msg",
"+=",
"'server pid: {}\\n'",
".",
"format",
"(",
"self",
".",
"_process",
".",
"pid",
")",
"msg",
"+=",
"'server poll: {}\\n'",
".",
"format",
"(",
"self",
".",
"_process",
".",
"poll",
"(",
")",
")",
"msg",
"+=",
"'server running: {}\\n'",
".",
"format",
"(",
"self",
".",
"running",
"(",
")",
")",
"msg",
"+=",
"'server port: {}\\n'",
".",
"format",
"(",
"self",
".",
"_port",
")",
"msg",
"+=",
"'server root url: {}\\n'",
".",
"format",
"(",
"self",
".",
"url",
"(",
")",
")",
"print",
"(",
"msg",
",",
"end",
"=",
"''",
")"
] |
Show state.
|
[
"Show",
"state",
"."
] |
7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6
|
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L211-L220
|
246,454 |
mqopen/mqreceive
|
mqreceive/receiving.py
|
BrokerThreadManager.start
|
def start(self):
"""!
Start all receiving threads.
"""
if self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already running")
self.isThreadsRunning = True
for client in self.clients:
threading.Thread(target = client).start()
|
python
|
def start(self):
"""!
Start all receiving threads.
"""
if self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already running")
self.isThreadsRunning = True
for client in self.clients:
threading.Thread(target = client).start()
|
[
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"isThreadsRunning",
":",
"raise",
"ThreadManagerException",
"(",
"\"Broker threads are already running\"",
")",
"self",
".",
"isThreadsRunning",
"=",
"True",
"for",
"client",
"in",
"self",
".",
"clients",
":",
"threading",
".",
"Thread",
"(",
"target",
"=",
"client",
")",
".",
"start",
"(",
")"
] |
!
Start all receiving threads.
|
[
"!",
"Start",
"all",
"receiving",
"threads",
"."
] |
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
|
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/receiving.py#L50-L58
|
246,455 |
mqopen/mqreceive
|
mqreceive/receiving.py
|
BrokerThreadManager.stop
|
def stop(self):
"""!
Stop all receving threads.
"""
if not self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already stopped")
self.isThreadsRunning = False
for client in self.clients:
client.stop()
|
python
|
def stop(self):
"""!
Stop all receving threads.
"""
if not self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already stopped")
self.isThreadsRunning = False
for client in self.clients:
client.stop()
|
[
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isThreadsRunning",
":",
"raise",
"ThreadManagerException",
"(",
"\"Broker threads are already stopped\"",
")",
"self",
".",
"isThreadsRunning",
"=",
"False",
"for",
"client",
"in",
"self",
".",
"clients",
":",
"client",
".",
"stop",
"(",
")"
] |
!
Stop all receving threads.
|
[
"!",
"Stop",
"all",
"receving",
"threads",
"."
] |
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
|
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/receiving.py#L60-L68
|
246,456 |
mqopen/mqreceive
|
mqreceive/receiving.py
|
BrokerReceiver.onConnect
|
def onConnect(self, client, userdata, flags, rc):
"""!
The callback for when the client receives a CONNACK response from the server.
@param client
@param userdata
@param flags
@param rc
"""
for sub in self.subsciption:
(result, mid) = self.client.subscribe(sub)
|
python
|
def onConnect(self, client, userdata, flags, rc):
"""!
The callback for when the client receives a CONNACK response from the server.
@param client
@param userdata
@param flags
@param rc
"""
for sub in self.subsciption:
(result, mid) = self.client.subscribe(sub)
|
[
"def",
"onConnect",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"flags",
",",
"rc",
")",
":",
"for",
"sub",
"in",
"self",
".",
"subsciption",
":",
"(",
"result",
",",
"mid",
")",
"=",
"self",
".",
"client",
".",
"subscribe",
"(",
"sub",
")"
] |
!
The callback for when the client receives a CONNACK response from the server.
@param client
@param userdata
@param flags
@param rc
|
[
"!",
"The",
"callback",
"for",
"when",
"the",
"client",
"receives",
"a",
"CONNACK",
"response",
"from",
"the",
"server",
"."
] |
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
|
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/receiving.py#L151-L161
|
246,457 |
mqopen/mqreceive
|
mqreceive/receiving.py
|
BrokerReceiver.onMessage
|
def onMessage(self, client, userdata, msg):
"""!
The callback for when a PUBLISH message is received from the server.
@param client
@param userdata
@param msg
"""
dataIdentifier = DataIdentifier(self.broker, msg.topic)
self.dataHandler.onNewData(dataIdentifier, msg.payload)
|
python
|
def onMessage(self, client, userdata, msg):
"""!
The callback for when a PUBLISH message is received from the server.
@param client
@param userdata
@param msg
"""
dataIdentifier = DataIdentifier(self.broker, msg.topic)
self.dataHandler.onNewData(dataIdentifier, msg.payload)
|
[
"def",
"onMessage",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"msg",
")",
":",
"dataIdentifier",
"=",
"DataIdentifier",
"(",
"self",
".",
"broker",
",",
"msg",
".",
"topic",
")",
"self",
".",
"dataHandler",
".",
"onNewData",
"(",
"dataIdentifier",
",",
"msg",
".",
"payload",
")"
] |
!
The callback for when a PUBLISH message is received from the server.
@param client
@param userdata
@param msg
|
[
"!",
"The",
"callback",
"for",
"when",
"a",
"PUBLISH",
"message",
"is",
"received",
"from",
"the",
"server",
"."
] |
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
|
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/receiving.py#L172-L181
|
246,458 |
mqopen/mqreceive
|
mqreceive/receiving.py
|
BrokerReceiverIDManager.createReceiverID
|
def createReceiverID(self):
"""!
Create new receiver ID.
@return Receiver ID.
"""
_receiverID = self.receiverCounter
self.receiverCounter += 1
return BrokerReceiverID(self.hostname, self.pid, _receiverID)
|
python
|
def createReceiverID(self):
"""!
Create new receiver ID.
@return Receiver ID.
"""
_receiverID = self.receiverCounter
self.receiverCounter += 1
return BrokerReceiverID(self.hostname, self.pid, _receiverID)
|
[
"def",
"createReceiverID",
"(",
"self",
")",
":",
"_receiverID",
"=",
"self",
".",
"receiverCounter",
"self",
".",
"receiverCounter",
"+=",
"1",
"return",
"BrokerReceiverID",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"pid",
",",
"_receiverID",
")"
] |
!
Create new receiver ID.
@return Receiver ID.
|
[
"!",
"Create",
"new",
"receiver",
"ID",
"."
] |
cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf
|
https://github.com/mqopen/mqreceive/blob/cb35b5d0ab89a9af4217ab88ab9e8953c80d10bf/mqreceive/receiving.py#L282-L290
|
246,459 |
ionata/dj-core-drf
|
dj_core_drf/metadata.py
|
ModelChoicesMetadata.determine_actions
|
def determine_actions(self, request, view):
"""Allow all allowed methods"""
from rest_framework.generics import GenericAPIView
actions = {}
excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'}
for method in set(view.allowed_methods) - excluded_methods:
view.request = clone_request(request, method)
try:
if isinstance(view, GenericAPIView):
has_object = view.lookup_url_kwarg or view.lookup_field in view.kwargs
elif method in {'PUT', 'POST'}:
has_object = method in {'PUT'}
else:
continue
# Test global permissions
if hasattr(view, 'check_permissions'):
view.check_permissions(view.request)
# Test object permissions
if has_object and hasattr(view, 'get_object'):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
# If user has appropriate permissions for the view, include
# appropriate metadata about the fields that should be supplied.
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions
|
python
|
def determine_actions(self, request, view):
"""Allow all allowed methods"""
from rest_framework.generics import GenericAPIView
actions = {}
excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'}
for method in set(view.allowed_methods) - excluded_methods:
view.request = clone_request(request, method)
try:
if isinstance(view, GenericAPIView):
has_object = view.lookup_url_kwarg or view.lookup_field in view.kwargs
elif method in {'PUT', 'POST'}:
has_object = method in {'PUT'}
else:
continue
# Test global permissions
if hasattr(view, 'check_permissions'):
view.check_permissions(view.request)
# Test object permissions
if has_object and hasattr(view, 'get_object'):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
# If user has appropriate permissions for the view, include
# appropriate metadata about the fields that should be supplied.
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions
|
[
"def",
"determine_actions",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"from",
"rest_framework",
".",
"generics",
"import",
"GenericAPIView",
"actions",
"=",
"{",
"}",
"excluded_methods",
"=",
"{",
"'HEAD'",
",",
"'OPTIONS'",
",",
"'PATCH'",
",",
"'DELETE'",
"}",
"for",
"method",
"in",
"set",
"(",
"view",
".",
"allowed_methods",
")",
"-",
"excluded_methods",
":",
"view",
".",
"request",
"=",
"clone_request",
"(",
"request",
",",
"method",
")",
"try",
":",
"if",
"isinstance",
"(",
"view",
",",
"GenericAPIView",
")",
":",
"has_object",
"=",
"view",
".",
"lookup_url_kwarg",
"or",
"view",
".",
"lookup_field",
"in",
"view",
".",
"kwargs",
"elif",
"method",
"in",
"{",
"'PUT'",
",",
"'POST'",
"}",
":",
"has_object",
"=",
"method",
"in",
"{",
"'PUT'",
"}",
"else",
":",
"continue",
"# Test global permissions",
"if",
"hasattr",
"(",
"view",
",",
"'check_permissions'",
")",
":",
"view",
".",
"check_permissions",
"(",
"view",
".",
"request",
")",
"# Test object permissions",
"if",
"has_object",
"and",
"hasattr",
"(",
"view",
",",
"'get_object'",
")",
":",
"view",
".",
"get_object",
"(",
")",
"except",
"(",
"exceptions",
".",
"APIException",
",",
"PermissionDenied",
",",
"Http404",
")",
":",
"pass",
"else",
":",
"# If user has appropriate permissions for the view, include",
"# appropriate metadata about the fields that should be supplied.",
"serializer",
"=",
"view",
".",
"get_serializer",
"(",
")",
"actions",
"[",
"method",
"]",
"=",
"self",
".",
"get_serializer_info",
"(",
"serializer",
")",
"finally",
":",
"view",
".",
"request",
"=",
"request",
"return",
"actions"
] |
Allow all allowed methods
|
[
"Allow",
"all",
"allowed",
"methods"
] |
c0fa709b8167d4888a3311fe3ebee1c6a288a7b0
|
https://github.com/ionata/dj-core-drf/blob/c0fa709b8167d4888a3311fe3ebee1c6a288a7b0/dj_core_drf/metadata.py#L29-L59
|
246,460 |
praekelt/vumi-http-api
|
vumi_http_api/resource.py
|
MsgCheckHelpers.is_within_content_length_limit
|
def is_within_content_length_limit(payload, api_config):
"""
Check that the message content is within the configured length limit.
"""
length_limit = api_config.get('content_length_limit')
if (length_limit is not None) and (payload["content"] is not None):
content_length = len(payload["content"])
if content_length > length_limit:
return "Payload content too long: %s > %s" % (
content_length, length_limit)
return None
|
python
|
def is_within_content_length_limit(payload, api_config):
"""
Check that the message content is within the configured length limit.
"""
length_limit = api_config.get('content_length_limit')
if (length_limit is not None) and (payload["content"] is not None):
content_length = len(payload["content"])
if content_length > length_limit:
return "Payload content too long: %s > %s" % (
content_length, length_limit)
return None
|
[
"def",
"is_within_content_length_limit",
"(",
"payload",
",",
"api_config",
")",
":",
"length_limit",
"=",
"api_config",
".",
"get",
"(",
"'content_length_limit'",
")",
"if",
"(",
"length_limit",
"is",
"not",
"None",
")",
"and",
"(",
"payload",
"[",
"\"content\"",
"]",
"is",
"not",
"None",
")",
":",
"content_length",
"=",
"len",
"(",
"payload",
"[",
"\"content\"",
"]",
")",
"if",
"content_length",
">",
"length_limit",
":",
"return",
"\"Payload content too long: %s > %s\"",
"%",
"(",
"content_length",
",",
"length_limit",
")",
"return",
"None"
] |
Check that the message content is within the configured length limit.
|
[
"Check",
"that",
"the",
"message",
"content",
"is",
"within",
"the",
"configured",
"length",
"limit",
"."
] |
0d7cf1cb71794c93272c19095cf8c37f4c250a59
|
https://github.com/praekelt/vumi-http-api/blob/0d7cf1cb71794c93272c19095cf8c37f4c250a59/vumi_http_api/resource.py#L105-L115
|
246,461 |
ardydedase/pycouchbase
|
couchbase-python-cffi/couchbase_ffi/executors.py
|
get_option
|
def get_option(name, key_options, global_options, default=None):
"""
Search the key-specific options and the global options for a given
setting. Either dictionary may be None.
This will first search the key settings and then the global settings.
:param name: The setting to search for
:param key_options: The item specific settings
:param global_options: General method parameters
:return: The option, if found, or None
"""
if key_options:
try:
return key_options[name]
except KeyError:
pass
if global_options:
try:
return global_options[name]
except KeyError:
pass
return default
|
python
|
def get_option(name, key_options, global_options, default=None):
"""
Search the key-specific options and the global options for a given
setting. Either dictionary may be None.
This will first search the key settings and then the global settings.
:param name: The setting to search for
:param key_options: The item specific settings
:param global_options: General method parameters
:return: The option, if found, or None
"""
if key_options:
try:
return key_options[name]
except KeyError:
pass
if global_options:
try:
return global_options[name]
except KeyError:
pass
return default
|
[
"def",
"get_option",
"(",
"name",
",",
"key_options",
",",
"global_options",
",",
"default",
"=",
"None",
")",
":",
"if",
"key_options",
":",
"try",
":",
"return",
"key_options",
"[",
"name",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"global_options",
":",
"try",
":",
"return",
"global_options",
"[",
"name",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"default"
] |
Search the key-specific options and the global options for a given
setting. Either dictionary may be None.
This will first search the key settings and then the global settings.
:param name: The setting to search for
:param key_options: The item specific settings
:param global_options: General method parameters
:return: The option, if found, or None
|
[
"Search",
"the",
"key",
"-",
"specific",
"options",
"and",
"the",
"global",
"options",
"for",
"a",
"given",
"setting",
".",
"Either",
"dictionary",
"may",
"be",
"None",
"."
] |
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
|
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/executors.py#L71-L94
|
246,462 |
ardydedase/pycouchbase
|
couchbase-python-cffi/couchbase_ffi/executors.py
|
set_quiet
|
def set_quiet(mres, parent, global_options):
"""
Sets the 'quiet' property on the MultiResult
"""
quiet = global_options.get('quiet')
if quiet is not None:
mres._quiet = quiet
else:
mres._quiet = parent.quiet
|
python
|
def set_quiet(mres, parent, global_options):
"""
Sets the 'quiet' property on the MultiResult
"""
quiet = global_options.get('quiet')
if quiet is not None:
mres._quiet = quiet
else:
mres._quiet = parent.quiet
|
[
"def",
"set_quiet",
"(",
"mres",
",",
"parent",
",",
"global_options",
")",
":",
"quiet",
"=",
"global_options",
".",
"get",
"(",
"'quiet'",
")",
"if",
"quiet",
"is",
"not",
"None",
":",
"mres",
".",
"_quiet",
"=",
"quiet",
"else",
":",
"mres",
".",
"_quiet",
"=",
"parent",
".",
"quiet"
] |
Sets the 'quiet' property on the MultiResult
|
[
"Sets",
"the",
"quiet",
"property",
"on",
"the",
"MultiResult"
] |
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
|
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/executors.py#L97-L105
|
246,463 |
ardydedase/pycouchbase
|
couchbase-python-cffi/couchbase_ffi/executors.py
|
get_cas
|
def get_cas(key_options, global_options, item):
"""
Get the CAS from various inputs. This will properly honor
the ``ignore_cas`` flag, if present.
:param key_options: Key specific options
:param global_options: Global options
:param item: The item
:return: The cas, or 0 if no cas
"""
if item:
ign_cas = get_option('ignore_cas', key_options, globals(), False)
return 0 if ign_cas else item.cas
else:
try:
cas = key_options['cas']
except KeyError:
try:
cas = global_options['cas']
except KeyError:
return 0
if not cas:
return 0
return cas
|
python
|
def get_cas(key_options, global_options, item):
"""
Get the CAS from various inputs. This will properly honor
the ``ignore_cas`` flag, if present.
:param key_options: Key specific options
:param global_options: Global options
:param item: The item
:return: The cas, or 0 if no cas
"""
if item:
ign_cas = get_option('ignore_cas', key_options, globals(), False)
return 0 if ign_cas else item.cas
else:
try:
cas = key_options['cas']
except KeyError:
try:
cas = global_options['cas']
except KeyError:
return 0
if not cas:
return 0
return cas
|
[
"def",
"get_cas",
"(",
"key_options",
",",
"global_options",
",",
"item",
")",
":",
"if",
"item",
":",
"ign_cas",
"=",
"get_option",
"(",
"'ignore_cas'",
",",
"key_options",
",",
"globals",
"(",
")",
",",
"False",
")",
"return",
"0",
"if",
"ign_cas",
"else",
"item",
".",
"cas",
"else",
":",
"try",
":",
"cas",
"=",
"key_options",
"[",
"'cas'",
"]",
"except",
"KeyError",
":",
"try",
":",
"cas",
"=",
"global_options",
"[",
"'cas'",
"]",
"except",
"KeyError",
":",
"return",
"0",
"if",
"not",
"cas",
":",
"return",
"0",
"return",
"cas"
] |
Get the CAS from various inputs. This will properly honor
the ``ignore_cas`` flag, if present.
:param key_options: Key specific options
:param global_options: Global options
:param item: The item
:return: The cas, or 0 if no cas
|
[
"Get",
"the",
"CAS",
"from",
"various",
"inputs",
".",
"This",
"will",
"properly",
"honor",
"the",
"ignore_cas",
"flag",
"if",
"present",
"."
] |
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
|
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/executors.py#L108-L131
|
246,464 |
roaet/eh
|
eh/cli.py
|
main
|
def main(context, subject, debug, no_colors):
"""
Eh is a terminal program that will provide you with
quick reminders about a subject.
To get started run: eh help
To figure out what eh knows about run: eh list
To update the list of subjects: eh update
Note:
Eh will make a directory in your userhome called .eh
where it will store downloaded subjects.
"""
eho = Eh(debug, no_colors)
if subject == 'list':
eho.subject_list()
exit(0)
if subject == 'update':
eho.update_subject_repo()
exit(0)
eho.run(subject)
exit(0)
|
python
|
def main(context, subject, debug, no_colors):
"""
Eh is a terminal program that will provide you with
quick reminders about a subject.
To get started run: eh help
To figure out what eh knows about run: eh list
To update the list of subjects: eh update
Note:
Eh will make a directory in your userhome called .eh
where it will store downloaded subjects.
"""
eho = Eh(debug, no_colors)
if subject == 'list':
eho.subject_list()
exit(0)
if subject == 'update':
eho.update_subject_repo()
exit(0)
eho.run(subject)
exit(0)
|
[
"def",
"main",
"(",
"context",
",",
"subject",
",",
"debug",
",",
"no_colors",
")",
":",
"eho",
"=",
"Eh",
"(",
"debug",
",",
"no_colors",
")",
"if",
"subject",
"==",
"'list'",
":",
"eho",
".",
"subject_list",
"(",
")",
"exit",
"(",
"0",
")",
"if",
"subject",
"==",
"'update'",
":",
"eho",
".",
"update_subject_repo",
"(",
")",
"exit",
"(",
"0",
")",
"eho",
".",
"run",
"(",
"subject",
")",
"exit",
"(",
"0",
")"
] |
Eh is a terminal program that will provide you with
quick reminders about a subject.
To get started run: eh help
To figure out what eh knows about run: eh list
To update the list of subjects: eh update
Note:
Eh will make a directory in your userhome called .eh
where it will store downloaded subjects.
|
[
"Eh",
"is",
"a",
"terminal",
"program",
"that",
"will",
"provide",
"you",
"with",
"quick",
"reminders",
"about",
"a",
"subject",
"."
] |
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
|
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/cli.py#L167-L191
|
246,465 |
JHowell45/helium-cli
|
helium/utility_functions/json_functions.py
|
store_data
|
def store_data(data):
"""Use this function to store data in a JSON file.
This function is used for loading up a JSON file and appending additional
data to the JSON file.
:param data: the data to add to the JSON file.
:type data: dict
"""
with open(url_json_path) as json_file:
try:
json_file_data = load(json_file)
json_file_data.update(data)
except (AttributeError, JSONDecodeError):
json_file_data = data
with open(url_json_path, 'w') as json_file:
dump(json_file_data, json_file, indent=4, sort_keys=True)
|
python
|
def store_data(data):
"""Use this function to store data in a JSON file.
This function is used for loading up a JSON file and appending additional
data to the JSON file.
:param data: the data to add to the JSON file.
:type data: dict
"""
with open(url_json_path) as json_file:
try:
json_file_data = load(json_file)
json_file_data.update(data)
except (AttributeError, JSONDecodeError):
json_file_data = data
with open(url_json_path, 'w') as json_file:
dump(json_file_data, json_file, indent=4, sort_keys=True)
|
[
"def",
"store_data",
"(",
"data",
")",
":",
"with",
"open",
"(",
"url_json_path",
")",
"as",
"json_file",
":",
"try",
":",
"json_file_data",
"=",
"load",
"(",
"json_file",
")",
"json_file_data",
".",
"update",
"(",
"data",
")",
"except",
"(",
"AttributeError",
",",
"JSONDecodeError",
")",
":",
"json_file_data",
"=",
"data",
"with",
"open",
"(",
"url_json_path",
",",
"'w'",
")",
"as",
"json_file",
":",
"dump",
"(",
"json_file_data",
",",
"json_file",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
] |
Use this function to store data in a JSON file.
This function is used for loading up a JSON file and appending additional
data to the JSON file.
:param data: the data to add to the JSON file.
:type data: dict
|
[
"Use",
"this",
"function",
"to",
"store",
"data",
"in",
"a",
"JSON",
"file",
"."
] |
8decc2f410a17314440eeed411a4b19dd4b4e780
|
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/utility_functions/json_functions.py#L10-L26
|
246,466 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.default_to_hashed_rows
|
def default_to_hashed_rows(self, default=None):
""" Gets the current setting with no parameters, sets it if a boolean is passed in
:param default: the value to set
:return: the current value, or new value if default is set to True or False
"""
if default is not None:
self._default_to_hashed_rows = (default is True)
return self._default_to_hashed_rows
|
python
|
def default_to_hashed_rows(self, default=None):
""" Gets the current setting with no parameters, sets it if a boolean is passed in
:param default: the value to set
:return: the current value, or new value if default is set to True or False
"""
if default is not None:
self._default_to_hashed_rows = (default is True)
return self._default_to_hashed_rows
|
[
"def",
"default_to_hashed_rows",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"self",
".",
"_default_to_hashed_rows",
"=",
"(",
"default",
"is",
"True",
")",
"return",
"self",
".",
"_default_to_hashed_rows"
] |
Gets the current setting with no parameters, sets it if a boolean is passed in
:param default: the value to set
:return: the current value, or new value if default is set to True or False
|
[
"Gets",
"the",
"current",
"setting",
"with",
"no",
"parameters",
"sets",
"it",
"if",
"a",
"boolean",
"is",
"passed",
"in"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L40-L49
|
246,467 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix._add_dict_row
|
def _add_dict_row(self, feature_dict, key=None):
""" Add a dict row to the matrix
:param str key: key used when rows is a dict rather than an array
:param dict feature_dict: a dictionary of features and weights
"""
self._update_internal_column_state(set(feature_dict.keys()))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self._rows[self._row_name_idx[key]] = feature_dict
return
else:
self._row_name_idx[key] = len(self._rows)
self._row_name_list.append(key)
self._rows.append(feature_dict)
|
python
|
def _add_dict_row(self, feature_dict, key=None):
""" Add a dict row to the matrix
:param str key: key used when rows is a dict rather than an array
:param dict feature_dict: a dictionary of features and weights
"""
self._update_internal_column_state(set(feature_dict.keys()))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self._rows[self._row_name_idx[key]] = feature_dict
return
else:
self._row_name_idx[key] = len(self._rows)
self._row_name_list.append(key)
self._rows.append(feature_dict)
|
[
"def",
"_add_dict_row",
"(",
"self",
",",
"feature_dict",
",",
"key",
"=",
"None",
")",
":",
"self",
".",
"_update_internal_column_state",
"(",
"set",
"(",
"feature_dict",
".",
"keys",
"(",
")",
")",
")",
"# reset the row memoization",
"self",
".",
"_row_memo",
"=",
"{",
"}",
"if",
"key",
"is",
"not",
"None",
":",
"if",
"key",
"in",
"self",
".",
"_row_name_idx",
":",
"self",
".",
"_rows",
"[",
"self",
".",
"_row_name_idx",
"[",
"key",
"]",
"]",
"=",
"feature_dict",
"return",
"else",
":",
"self",
".",
"_row_name_idx",
"[",
"key",
"]",
"=",
"len",
"(",
"self",
".",
"_rows",
")",
"self",
".",
"_row_name_list",
".",
"append",
"(",
"key",
")",
"self",
".",
"_rows",
".",
"append",
"(",
"feature_dict",
")"
] |
Add a dict row to the matrix
:param str key: key used when rows is a dict rather than an array
:param dict feature_dict: a dictionary of features and weights
|
[
"Add",
"a",
"dict",
"row",
"to",
"the",
"matrix"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L61-L80
|
246,468 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix._add_list_row
|
def _add_list_row(self, feature_list, key=None):
""" Add a list row to the matrix
:param str key: key used when rows is a dict rather than an array
:param feature_list: a list of features in the same order as column_names
:raise IndexError: if the list doesnt match the expected number of columns
"""
if len(feature_list) > len(self._column_name_list):
raise IndexError("Input list must have %s columns or less" % len(self._column_name_list))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self._rows[self._row_name_idx[key]] = feature_list
return
else:
self._row_name_idx[key] = len(self._rows)
self._row_name_list.append(key)
self._rows.append(feature_list)
|
python
|
def _add_list_row(self, feature_list, key=None):
""" Add a list row to the matrix
:param str key: key used when rows is a dict rather than an array
:param feature_list: a list of features in the same order as column_names
:raise IndexError: if the list doesnt match the expected number of columns
"""
if len(feature_list) > len(self._column_name_list):
raise IndexError("Input list must have %s columns or less" % len(self._column_name_list))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self._rows[self._row_name_idx[key]] = feature_list
return
else:
self._row_name_idx[key] = len(self._rows)
self._row_name_list.append(key)
self._rows.append(feature_list)
|
[
"def",
"_add_list_row",
"(",
"self",
",",
"feature_list",
",",
"key",
"=",
"None",
")",
":",
"if",
"len",
"(",
"feature_list",
")",
">",
"len",
"(",
"self",
".",
"_column_name_list",
")",
":",
"raise",
"IndexError",
"(",
"\"Input list must have %s columns or less\"",
"%",
"len",
"(",
"self",
".",
"_column_name_list",
")",
")",
"# reset the row memoization",
"self",
".",
"_row_memo",
"=",
"{",
"}",
"if",
"key",
"is",
"not",
"None",
":",
"if",
"key",
"in",
"self",
".",
"_row_name_idx",
":",
"self",
".",
"_rows",
"[",
"self",
".",
"_row_name_idx",
"[",
"key",
"]",
"]",
"=",
"feature_list",
"return",
"else",
":",
"self",
".",
"_row_name_idx",
"[",
"key",
"]",
"=",
"len",
"(",
"self",
".",
"_rows",
")",
"self",
".",
"_row_name_list",
".",
"append",
"(",
"key",
")",
"self",
".",
"_rows",
".",
"append",
"(",
"feature_list",
")"
] |
Add a list row to the matrix
:param str key: key used when rows is a dict rather than an array
:param feature_list: a list of features in the same order as column_names
:raise IndexError: if the list doesnt match the expected number of columns
|
[
"Add",
"a",
"list",
"row",
"to",
"the",
"matrix"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L82-L104
|
246,469 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.add_row
|
def add_row(self, list_or_dict, key=None):
""" Adds a list or dict as a row in the FVM data structure
:param str key: key used when rows is a dict rather than an array
:param list_or_dict: a feature list or dict
"""
if isinstance(list_or_dict, list):
self._add_list_row(list_or_dict, key)
else:
self._add_dict_row(list_or_dict, key)
|
python
|
def add_row(self, list_or_dict, key=None):
""" Adds a list or dict as a row in the FVM data structure
:param str key: key used when rows is a dict rather than an array
:param list_or_dict: a feature list or dict
"""
if isinstance(list_or_dict, list):
self._add_list_row(list_or_dict, key)
else:
self._add_dict_row(list_or_dict, key)
|
[
"def",
"add_row",
"(",
"self",
",",
"list_or_dict",
",",
"key",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"list_or_dict",
",",
"list",
")",
":",
"self",
".",
"_add_list_row",
"(",
"list_or_dict",
",",
"key",
")",
"else",
":",
"self",
".",
"_add_dict_row",
"(",
"list_or_dict",
",",
"key",
")"
] |
Adds a list or dict as a row in the FVM data structure
:param str key: key used when rows is a dict rather than an array
:param list_or_dict: a feature list or dict
|
[
"Adds",
"a",
"list",
"or",
"dict",
"as",
"a",
"row",
"in",
"the",
"FVM",
"data",
"structure"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L143-L152
|
246,470 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.extend_rows
|
def extend_rows(self, list_or_dict):
""" Add multiple rows at once
:param list_or_dict: a 2 dimensional structure for adding multiple rows at once
:return:
"""
if isinstance(list_or_dict, list):
for r in list_or_dict:
self.add_row(r)
else:
for k,r in list_or_dict.iteritems():
self.add_row(r, k)
|
python
|
def extend_rows(self, list_or_dict):
""" Add multiple rows at once
:param list_or_dict: a 2 dimensional structure for adding multiple rows at once
:return:
"""
if isinstance(list_or_dict, list):
for r in list_or_dict:
self.add_row(r)
else:
for k,r in list_or_dict.iteritems():
self.add_row(r, k)
|
[
"def",
"extend_rows",
"(",
"self",
",",
"list_or_dict",
")",
":",
"if",
"isinstance",
"(",
"list_or_dict",
",",
"list",
")",
":",
"for",
"r",
"in",
"list_or_dict",
":",
"self",
".",
"add_row",
"(",
"r",
")",
"else",
":",
"for",
"k",
",",
"r",
"in",
"list_or_dict",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"add_row",
"(",
"r",
",",
"k",
")"
] |
Add multiple rows at once
:param list_or_dict: a 2 dimensional structure for adding multiple rows at once
:return:
|
[
"Add",
"multiple",
"rows",
"at",
"once"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L154-L165
|
246,471 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.get_row_list
|
def get_row_list(self, row_idx):
""" get a feature vector for the nth row
:param row_idx: which row
:return: a list of feature values, ordered by column_names
"""
try:
row = self._rows[row_idx]
except TypeError:
row = self._rows[self._row_name_idx[row_idx]]
if isinstance(row, list):
extra = [ self._default_value ] * (len(self._column_name_list) - len(row))
return row + extra
else:
if row_idx not in self._row_memo:
self._row_memo[row_idx] = [ row[k] if k in row else self._default_value for k in self._column_name_list ]
return self._row_memo[row_idx]
|
python
|
def get_row_list(self, row_idx):
""" get a feature vector for the nth row
:param row_idx: which row
:return: a list of feature values, ordered by column_names
"""
try:
row = self._rows[row_idx]
except TypeError:
row = self._rows[self._row_name_idx[row_idx]]
if isinstance(row, list):
extra = [ self._default_value ] * (len(self._column_name_list) - len(row))
return row + extra
else:
if row_idx not in self._row_memo:
self._row_memo[row_idx] = [ row[k] if k in row else self._default_value for k in self._column_name_list ]
return self._row_memo[row_idx]
|
[
"def",
"get_row_list",
"(",
"self",
",",
"row_idx",
")",
":",
"try",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"row_idx",
"]",
"except",
"TypeError",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"self",
".",
"_row_name_idx",
"[",
"row_idx",
"]",
"]",
"if",
"isinstance",
"(",
"row",
",",
"list",
")",
":",
"extra",
"=",
"[",
"self",
".",
"_default_value",
"]",
"*",
"(",
"len",
"(",
"self",
".",
"_column_name_list",
")",
"-",
"len",
"(",
"row",
")",
")",
"return",
"row",
"+",
"extra",
"else",
":",
"if",
"row_idx",
"not",
"in",
"self",
".",
"_row_memo",
":",
"self",
".",
"_row_memo",
"[",
"row_idx",
"]",
"=",
"[",
"row",
"[",
"k",
"]",
"if",
"k",
"in",
"row",
"else",
"self",
".",
"_default_value",
"for",
"k",
"in",
"self",
".",
"_column_name_list",
"]",
"return",
"self",
".",
"_row_memo",
"[",
"row_idx",
"]"
] |
get a feature vector for the nth row
:param row_idx: which row
:return: a list of feature values, ordered by column_names
|
[
"get",
"a",
"feature",
"vector",
"for",
"the",
"nth",
"row"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L184-L204
|
246,472 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.get_row_dict
|
def get_row_dict(self, row_idx):
""" Return a dictionary representation for a matrix row
:param row_idx: which row
:return: a dict of feature keys/values, not including ones which are the default value
"""
try:
row = self._rows[row_idx]
except TypeError:
row = self._rows[self._row_name_idx[row_idx]]
if isinstance(row, dict):
return row
else:
if row_idx not in self._row_memo:
self._row_memo[row_idx] = dict((self._column_name_list[idx], v) for idx, v in enumerate(row) if v != self._default_value)
return self._row_memo[row_idx]
|
python
|
def get_row_dict(self, row_idx):
""" Return a dictionary representation for a matrix row
:param row_idx: which row
:return: a dict of feature keys/values, not including ones which are the default value
"""
try:
row = self._rows[row_idx]
except TypeError:
row = self._rows[self._row_name_idx[row_idx]]
if isinstance(row, dict):
return row
else:
if row_idx not in self._row_memo:
self._row_memo[row_idx] = dict((self._column_name_list[idx], v) for idx, v in enumerate(row) if v != self._default_value)
return self._row_memo[row_idx]
|
[
"def",
"get_row_dict",
"(",
"self",
",",
"row_idx",
")",
":",
"try",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"row_idx",
"]",
"except",
"TypeError",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"self",
".",
"_row_name_idx",
"[",
"row_idx",
"]",
"]",
"if",
"isinstance",
"(",
"row",
",",
"dict",
")",
":",
"return",
"row",
"else",
":",
"if",
"row_idx",
"not",
"in",
"self",
".",
"_row_memo",
":",
"self",
".",
"_row_memo",
"[",
"row_idx",
"]",
"=",
"dict",
"(",
"(",
"self",
".",
"_column_name_list",
"[",
"idx",
"]",
",",
"v",
")",
"for",
"idx",
",",
"v",
"in",
"enumerate",
"(",
"row",
")",
"if",
"v",
"!=",
"self",
".",
"_default_value",
")",
"return",
"self",
".",
"_row_memo",
"[",
"row_idx",
"]"
] |
Return a dictionary representation for a matrix row
:param row_idx: which row
:return: a dict of feature keys/values, not including ones which are the default value
|
[
"Return",
"a",
"dictionary",
"representation",
"for",
"a",
"matrix",
"row"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L206-L225
|
246,473 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.get_matrix
|
def get_matrix(self):
""" Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
"""
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])
|
python
|
def get_matrix(self):
""" Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
"""
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])
|
[
"def",
"get_matrix",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"get_row_list",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"row_count",
"(",
")",
")",
"]",
")"
] |
Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
|
[
"Use",
"numpy",
"to",
"create",
"a",
"real",
"matrix",
"object",
"from",
"the",
"data"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L227-L232
|
246,474 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.transpose
|
def transpose(self):
""" Create a matrix, transpose it, and then create a new FVM
:raise NotImplementedError: if all existing rows aren't keyed
:return: a new FVM rotated from self
"""
if len(self._row_name_list) != len(self._rows):
raise NotImplementedError("You can't rotate a FVM that doesn't have all rows keyed")
fvm = FeatureVectorMatrix(default_value=self._default_value, default_to_hashed_rows=self._default_to_hashed_rows)
fvm._update_internal_column_state(self._row_name_list)
for idx, r in enumerate(self.get_matrix().transpose()):
fvm.add_row(r.tolist(), self._column_name_list[idx])
return fvm
|
python
|
def transpose(self):
""" Create a matrix, transpose it, and then create a new FVM
:raise NotImplementedError: if all existing rows aren't keyed
:return: a new FVM rotated from self
"""
if len(self._row_name_list) != len(self._rows):
raise NotImplementedError("You can't rotate a FVM that doesn't have all rows keyed")
fvm = FeatureVectorMatrix(default_value=self._default_value, default_to_hashed_rows=self._default_to_hashed_rows)
fvm._update_internal_column_state(self._row_name_list)
for idx, r in enumerate(self.get_matrix().transpose()):
fvm.add_row(r.tolist(), self._column_name_list[idx])
return fvm
|
[
"def",
"transpose",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_row_name_list",
")",
"!=",
"len",
"(",
"self",
".",
"_rows",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"You can't rotate a FVM that doesn't have all rows keyed\"",
")",
"fvm",
"=",
"FeatureVectorMatrix",
"(",
"default_value",
"=",
"self",
".",
"_default_value",
",",
"default_to_hashed_rows",
"=",
"self",
".",
"_default_to_hashed_rows",
")",
"fvm",
".",
"_update_internal_column_state",
"(",
"self",
".",
"_row_name_list",
")",
"for",
"idx",
",",
"r",
"in",
"enumerate",
"(",
"self",
".",
"get_matrix",
"(",
")",
".",
"transpose",
"(",
")",
")",
":",
"fvm",
".",
"add_row",
"(",
"r",
".",
"tolist",
"(",
")",
",",
"self",
".",
"_column_name_list",
"[",
"idx",
"]",
")",
"return",
"fvm"
] |
Create a matrix, transpose it, and then create a new FVM
:raise NotImplementedError: if all existing rows aren't keyed
:return: a new FVM rotated from self
|
[
"Create",
"a",
"matrix",
"transpose",
"it",
"and",
"then",
"create",
"a",
"new",
"FVM"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L234-L248
|
246,475 |
talentpair/featurevectormatrix
|
featurevectormatrix/__init__.py
|
FeatureVectorMatrix.keys
|
def keys(self):
""" Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys
"""
if len(self._row_name_list) != len(self._rows):
raise NotImplementedError("You can't get row keys for a FVM that doesn't have all rows keyed")
return self.row_names()
|
python
|
def keys(self):
""" Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys
"""
if len(self._row_name_list) != len(self._rows):
raise NotImplementedError("You can't get row keys for a FVM that doesn't have all rows keyed")
return self.row_names()
|
[
"def",
"keys",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_row_name_list",
")",
"!=",
"len",
"(",
"self",
".",
"_rows",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"You can't get row keys for a FVM that doesn't have all rows keyed\"",
")",
"return",
"self",
".",
"row_names",
"(",
")"
] |
Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys
|
[
"Returns",
"all",
"row",
"keys"
] |
1327026f7e46138947ba55433c11a85bca1adc5d
|
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L250-L259
|
246,476 |
dossier/dossier.fc
|
python/dossier/fc/exceptions.py
|
uni
|
def uni(key):
'''as a crutch, we allow str-type keys, but they really should be
unicode.
'''
if isinstance(key, str):
logger.warn('assuming utf8 on: %r', key)
return unicode(key, 'utf-8')
elif isinstance(key, unicode):
return key
else:
raise NonUnicodeKeyError(key)
|
python
|
def uni(key):
'''as a crutch, we allow str-type keys, but they really should be
unicode.
'''
if isinstance(key, str):
logger.warn('assuming utf8 on: %r', key)
return unicode(key, 'utf-8')
elif isinstance(key, unicode):
return key
else:
raise NonUnicodeKeyError(key)
|
[
"def",
"uni",
"(",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"logger",
".",
"warn",
"(",
"'assuming utf8 on: %r'",
",",
"key",
")",
"return",
"unicode",
"(",
"key",
",",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"key",
",",
"unicode",
")",
":",
"return",
"key",
"else",
":",
"raise",
"NonUnicodeKeyError",
"(",
"key",
")"
] |
as a crutch, we allow str-type keys, but they really should be
unicode.
|
[
"as",
"a",
"crutch",
"we",
"allow",
"str",
"-",
"type",
"keys",
"but",
"they",
"really",
"should",
"be",
"unicode",
"."
] |
3e969d0cb2592fc06afc1c849d2b22283450b5e2
|
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/exceptions.py#L54-L65
|
246,477 |
markomanninen/abnum
|
romanize/romanizer.py
|
romanizer.convert
|
def convert(self, string, preprocess = None):
"""
Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return:
"""
string = unicode(preprocess(string) if preprocess else string, encoding="utf-8")
if self.regex:
return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode('utf-8')
else:
return string
|
python
|
def convert(self, string, preprocess = None):
"""
Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return:
"""
string = unicode(preprocess(string) if preprocess else string, encoding="utf-8")
if self.regex:
return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode('utf-8')
else:
return string
|
[
"def",
"convert",
"(",
"self",
",",
"string",
",",
"preprocess",
"=",
"None",
")",
":",
"string",
"=",
"unicode",
"(",
"preprocess",
"(",
"string",
")",
"if",
"preprocess",
"else",
"string",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"if",
"self",
".",
"regex",
":",
"return",
"self",
".",
"regex",
".",
"sub",
"(",
"lambda",
"x",
":",
"self",
".",
"substitutes",
"[",
"x",
".",
"group",
"(",
")",
"]",
",",
"string",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"string"
] |
Swap characters from a script to transliteration and vice versa.
Optionally sanitize string by using preprocess function.
:param preprocess:
:param string:
:return:
|
[
"Swap",
"characters",
"from",
"a",
"script",
"to",
"transliteration",
"and",
"vice",
"versa",
".",
"Optionally",
"sanitize",
"string",
"by",
"using",
"preprocess",
"function",
"."
] |
9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99
|
https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/romanize/romanizer.py#L28-L41
|
246,478 |
openbermuda/ripl
|
ripl/caption.py
|
SlideShow.create_image
|
def create_image(self, image_file, caption):
""" Create an image with a caption """
suffix = 'png'
if image_file:
img = Image.open(os.path.join(self.gallery, image_file))
width, height = img.size
ratio = width/WIDTH
img = img.resize((int(width // ratio),
int(height // ratio)),
Image.ANTIALIAS)
else:
img = Image.new('RGB', (WIDTH, HEIGHT), 'black')
image = self.add_caption(img, caption)
image = img
return image
|
python
|
def create_image(self, image_file, caption):
""" Create an image with a caption """
suffix = 'png'
if image_file:
img = Image.open(os.path.join(self.gallery, image_file))
width, height = img.size
ratio = width/WIDTH
img = img.resize((int(width // ratio),
int(height // ratio)),
Image.ANTIALIAS)
else:
img = Image.new('RGB', (WIDTH, HEIGHT), 'black')
image = self.add_caption(img, caption)
image = img
return image
|
[
"def",
"create_image",
"(",
"self",
",",
"image_file",
",",
"caption",
")",
":",
"suffix",
"=",
"'png'",
"if",
"image_file",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"gallery",
",",
"image_file",
")",
")",
"width",
",",
"height",
"=",
"img",
".",
"size",
"ratio",
"=",
"width",
"/",
"WIDTH",
"img",
"=",
"img",
".",
"resize",
"(",
"(",
"int",
"(",
"width",
"//",
"ratio",
")",
",",
"int",
"(",
"height",
"//",
"ratio",
")",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"else",
":",
"img",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"(",
"WIDTH",
",",
"HEIGHT",
")",
",",
"'black'",
")",
"image",
"=",
"self",
".",
"add_caption",
"(",
"img",
",",
"caption",
")",
"image",
"=",
"img",
"return",
"image"
] |
Create an image with a caption
|
[
"Create",
"an",
"image",
"with",
"a",
"caption"
] |
4886b1a697e4b81c2202db9cb977609e034f8e70
|
https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/caption.py#L65-L81
|
246,479 |
openbermuda/ripl
|
ripl/caption.py
|
SlideShow.add_caption
|
def add_caption(self, image, caption, colour=None):
""" Add a caption to the image """
if colour is None:
colour = "white"
width, height = image.size
draw = ImageDraw.Draw(image)
draw.font = self.font
draw.font = self.font
draw.text((width // 10, height//20), caption,
fill=colour)
return image
|
python
|
def add_caption(self, image, caption, colour=None):
""" Add a caption to the image """
if colour is None:
colour = "white"
width, height = image.size
draw = ImageDraw.Draw(image)
draw.font = self.font
draw.font = self.font
draw.text((width // 10, height//20), caption,
fill=colour)
return image
|
[
"def",
"add_caption",
"(",
"self",
",",
"image",
",",
"caption",
",",
"colour",
"=",
"None",
")",
":",
"if",
"colour",
"is",
"None",
":",
"colour",
"=",
"\"white\"",
"width",
",",
"height",
"=",
"image",
".",
"size",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"draw",
".",
"font",
"=",
"self",
".",
"font",
"draw",
".",
"font",
"=",
"self",
".",
"font",
"draw",
".",
"text",
"(",
"(",
"width",
"//",
"10",
",",
"height",
"//",
"20",
")",
",",
"caption",
",",
"fill",
"=",
"colour",
")",
"return",
"image"
] |
Add a caption to the image
|
[
"Add",
"a",
"caption",
"to",
"the",
"image"
] |
4886b1a697e4b81c2202db9cb977609e034f8e70
|
https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/caption.py#L105-L120
|
246,480 |
Cologler/fsoopify-python
|
fsoopify/paths.py
|
Path.from_caller_file
|
def from_caller_file():
'''return a `Path` from the path of caller file'''
import inspect
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
filename = calframe[1].filename
if not os.path.isfile(filename):
raise RuntimeError('caller is not a file')
return Path(filename)
|
python
|
def from_caller_file():
'''return a `Path` from the path of caller file'''
import inspect
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
filename = calframe[1].filename
if not os.path.isfile(filename):
raise RuntimeError('caller is not a file')
return Path(filename)
|
[
"def",
"from_caller_file",
"(",
")",
":",
"import",
"inspect",
"curframe",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"calframe",
"=",
"inspect",
".",
"getouterframes",
"(",
"curframe",
",",
"2",
")",
"filename",
"=",
"calframe",
"[",
"1",
"]",
".",
"filename",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"RuntimeError",
"(",
"'caller is not a file'",
")",
"return",
"Path",
"(",
"filename",
")"
] |
return a `Path` from the path of caller file
|
[
"return",
"a",
"Path",
"from",
"the",
"path",
"of",
"caller",
"file"
] |
83d45f16ae9abdea4fcc829373c32df501487dda
|
https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/paths.py#L152-L160
|
246,481 |
Cologler/fsoopify-python
|
fsoopify/paths.py
|
Path.from_caller_module_root
|
def from_caller_module_root():
'''return a `Path` from module root which include the caller'''
import inspect
all_stack = list(inspect.stack())
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
module = inspect.getmodule(calframe[1].frame)
if not module:
raise RuntimeError('caller is not a module')
root_module_name = module.__name__.partition('.')[0]
fullpath = sys.modules[root_module_name].__file__
return Path(fullpath)
|
python
|
def from_caller_module_root():
'''return a `Path` from module root which include the caller'''
import inspect
all_stack = list(inspect.stack())
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
module = inspect.getmodule(calframe[1].frame)
if not module:
raise RuntimeError('caller is not a module')
root_module_name = module.__name__.partition('.')[0]
fullpath = sys.modules[root_module_name].__file__
return Path(fullpath)
|
[
"def",
"from_caller_module_root",
"(",
")",
":",
"import",
"inspect",
"all_stack",
"=",
"list",
"(",
"inspect",
".",
"stack",
"(",
")",
")",
"curframe",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"calframe",
"=",
"inspect",
".",
"getouterframes",
"(",
"curframe",
",",
"2",
")",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"calframe",
"[",
"1",
"]",
".",
"frame",
")",
"if",
"not",
"module",
":",
"raise",
"RuntimeError",
"(",
"'caller is not a module'",
")",
"root_module_name",
"=",
"module",
".",
"__name__",
".",
"partition",
"(",
"'.'",
")",
"[",
"0",
"]",
"fullpath",
"=",
"sys",
".",
"modules",
"[",
"root_module_name",
"]",
".",
"__file__",
"return",
"Path",
"(",
"fullpath",
")"
] |
return a `Path` from module root which include the caller
|
[
"return",
"a",
"Path",
"from",
"module",
"root",
"which",
"include",
"the",
"caller"
] |
83d45f16ae9abdea4fcc829373c32df501487dda
|
https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/paths.py#L163-L174
|
246,482 |
abe-winter/pg13-py
|
pg13/pool_psyco.py
|
PgPoolPsyco.commitreturn
|
def commitreturn(self,qstring,vals=()):
"commit and return result. This is intended for sql UPDATE ... RETURNING"
with self.withcur() as cur:
cur.execute(qstring,vals)
return cur.fetchone()
|
python
|
def commitreturn(self,qstring,vals=()):
"commit and return result. This is intended for sql UPDATE ... RETURNING"
with self.withcur() as cur:
cur.execute(qstring,vals)
return cur.fetchone()
|
[
"def",
"commitreturn",
"(",
"self",
",",
"qstring",
",",
"vals",
"=",
"(",
")",
")",
":",
"with",
"self",
".",
"withcur",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"qstring",
",",
"vals",
")",
"return",
"cur",
".",
"fetchone",
"(",
")"
] |
commit and return result. This is intended for sql UPDATE ... RETURNING
|
[
"commit",
"and",
"return",
"result",
".",
"This",
"is",
"intended",
"for",
"sql",
"UPDATE",
"...",
"RETURNING"
] |
c78806f99f35541a8756987e86edca3438aa97f5
|
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pool_psyco.py#L35-L39
|
246,483 |
jmgilman/Neolib
|
neolib/pyamf/remoting/gateway/django.py
|
DjangoGateway.getResponse
|
def getResponse(self, http_request, request):
"""
Processes the AMF request, returning an AMF response.
@param http_request: The underlying HTTP Request.
@type http_request: U{HTTPRequest<http://docs.djangoproject.com
/en/dev/ref/request-response/#httprequest-objects>}
@param request: The AMF Request.
@type request: L{Envelope<pyamf.remoting.Envelope>}
@rtype: L{Envelope<pyamf.remoting.Envelope>}
"""
response = remoting.Envelope(request.amfVersion)
for name, message in request:
http_request.amf_request = message
processor = self.getProcessor(message)
response[name] = processor(message, http_request=http_request)
return response
|
python
|
def getResponse(self, http_request, request):
"""
Processes the AMF request, returning an AMF response.
@param http_request: The underlying HTTP Request.
@type http_request: U{HTTPRequest<http://docs.djangoproject.com
/en/dev/ref/request-response/#httprequest-objects>}
@param request: The AMF Request.
@type request: L{Envelope<pyamf.remoting.Envelope>}
@rtype: L{Envelope<pyamf.remoting.Envelope>}
"""
response = remoting.Envelope(request.amfVersion)
for name, message in request:
http_request.amf_request = message
processor = self.getProcessor(message)
response[name] = processor(message, http_request=http_request)
return response
|
[
"def",
"getResponse",
"(",
"self",
",",
"http_request",
",",
"request",
")",
":",
"response",
"=",
"remoting",
".",
"Envelope",
"(",
"request",
".",
"amfVersion",
")",
"for",
"name",
",",
"message",
"in",
"request",
":",
"http_request",
".",
"amf_request",
"=",
"message",
"processor",
"=",
"self",
".",
"getProcessor",
"(",
"message",
")",
"response",
"[",
"name",
"]",
"=",
"processor",
"(",
"message",
",",
"http_request",
"=",
"http_request",
")",
"return",
"response"
] |
Processes the AMF request, returning an AMF response.
@param http_request: The underlying HTTP Request.
@type http_request: U{HTTPRequest<http://docs.djangoproject.com
/en/dev/ref/request-response/#httprequest-objects>}
@param request: The AMF Request.
@type request: L{Envelope<pyamf.remoting.Envelope>}
@rtype: L{Envelope<pyamf.remoting.Envelope>}
|
[
"Processes",
"the",
"AMF",
"request",
"returning",
"an",
"AMF",
"response",
"."
] |
228fafeaed0f3195676137732384a14820ae285c
|
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/gateway/django.py#L66-L85
|
246,484 |
frejanordsiek/GeminiMotorDrive
|
GeminiMotorDrive/__init__.py
|
get_driver
|
def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
----------
driver : str, optional
The driver to communicate to the particular driver with, which
includes the hardware connection and possibly the communications
protocol. The only driver currently supported is the
``'ASCII_RS232'`` driver which corresponds to
``drivers.ASCII_RS232``.
*args : additional positional arguments
Additional positional arguments to pass onto the constructor for
the driver.
**keywords : additional keyword arguments
Additional keyword arguments to pass onto the constructor for
the driver.
Returns
-------
drivers : drivers
The connected drivers class that is connected to the drive.
Raises
------
NotImplementedError
If the `driver` is not supported.
See Also
--------
drivers
drivers.ASCII_RS232
"""
if driver.upper() == 'ASCII_RS232':
return drivers.ASCII_RS232(*args, **keywords)
else:
raise NotImplementedError('Driver not supported: '
+ str(driver))
|
python
|
def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
----------
driver : str, optional
The driver to communicate to the particular driver with, which
includes the hardware connection and possibly the communications
protocol. The only driver currently supported is the
``'ASCII_RS232'`` driver which corresponds to
``drivers.ASCII_RS232``.
*args : additional positional arguments
Additional positional arguments to pass onto the constructor for
the driver.
**keywords : additional keyword arguments
Additional keyword arguments to pass onto the constructor for
the driver.
Returns
-------
drivers : drivers
The connected drivers class that is connected to the drive.
Raises
------
NotImplementedError
If the `driver` is not supported.
See Also
--------
drivers
drivers.ASCII_RS232
"""
if driver.upper() == 'ASCII_RS232':
return drivers.ASCII_RS232(*args, **keywords)
else:
raise NotImplementedError('Driver not supported: '
+ str(driver))
|
[
"def",
"get_driver",
"(",
"driver",
"=",
"'ASCII_RS232'",
",",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
":",
"if",
"driver",
".",
"upper",
"(",
")",
"==",
"'ASCII_RS232'",
":",
"return",
"drivers",
".",
"ASCII_RS232",
"(",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Driver not supported: '",
"+",
"str",
"(",
"driver",
")",
")"
] |
Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
----------
driver : str, optional
The driver to communicate to the particular driver with, which
includes the hardware connection and possibly the communications
protocol. The only driver currently supported is the
``'ASCII_RS232'`` driver which corresponds to
``drivers.ASCII_RS232``.
*args : additional positional arguments
Additional positional arguments to pass onto the constructor for
the driver.
**keywords : additional keyword arguments
Additional keyword arguments to pass onto the constructor for
the driver.
Returns
-------
drivers : drivers
The connected drivers class that is connected to the drive.
Raises
------
NotImplementedError
If the `driver` is not supported.
See Also
--------
drivers
drivers.ASCII_RS232
|
[
"Gets",
"a",
"driver",
"for",
"a",
"Parker",
"Motion",
"Gemini",
"drive",
"."
] |
8de347ffb91228fbfe3832098b4996fa0141d8f1
|
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L41-L85
|
246,485 |
frejanordsiek/GeminiMotorDrive
|
GeminiMotorDrive/__init__.py
|
GeminiG6._get_parameter
|
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
value : bool, int, or float
The value of the specified parameter.
Raises
------
TypeError
If 'tp' is not an allowed type (``bool``, ``int``,
``float``).
CommandError
If the command to retrieve the parameter returned an error.
ValueError
If the value returned to the drive cannot be converted to
the proper type.
See Also
--------
_set_parameter : Set a parameter.
"""
# Raise a TypeError if tp isn't one of the valid types.
if tp not in (bool, int, float):
raise TypeError('Only supports bool, int, and float; not '
+ str(tp))
# Sending a command of name queries the state for that
# parameter. The response will have name preceeded by an '*' and
# then followed by a number which will have to be converted.
response = self.driver.send_command(name, timeout=timeout,
immediate=True,
max_retries=max_retries)
# If the response has an error, there are no response lines, or
# the first response line isn't '*'+name; then there was an
# error and an exception needs to be thrown.
if self.driver.command_error(response) \
or len(response[4]) == 0 \
or not response[4][0].startswith('*' + name):
raise CommandError('Couldn''t retrieve parameter '
+ name)
# Extract the string representation of the value, which is after
# the '*'+name.
value_str = response[4][0][(len(name)+1):]
# Convert the value string to the appropriate type and return
# it. Throw an error if it is not supported.
if tp == bool:
return (value_str == '1')
elif tp == int:
return int(value_str)
elif tp == float:
return float(value_str)
|
python
|
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
value : bool, int, or float
The value of the specified parameter.
Raises
------
TypeError
If 'tp' is not an allowed type (``bool``, ``int``,
``float``).
CommandError
If the command to retrieve the parameter returned an error.
ValueError
If the value returned to the drive cannot be converted to
the proper type.
See Also
--------
_set_parameter : Set a parameter.
"""
# Raise a TypeError if tp isn't one of the valid types.
if tp not in (bool, int, float):
raise TypeError('Only supports bool, int, and float; not '
+ str(tp))
# Sending a command of name queries the state for that
# parameter. The response will have name preceeded by an '*' and
# then followed by a number which will have to be converted.
response = self.driver.send_command(name, timeout=timeout,
immediate=True,
max_retries=max_retries)
# If the response has an error, there are no response lines, or
# the first response line isn't '*'+name; then there was an
# error and an exception needs to be thrown.
if self.driver.command_error(response) \
or len(response[4]) == 0 \
or not response[4][0].startswith('*' + name):
raise CommandError('Couldn''t retrieve parameter '
+ name)
# Extract the string representation of the value, which is after
# the '*'+name.
value_str = response[4][0][(len(name)+1):]
# Convert the value string to the appropriate type and return
# it. Throw an error if it is not supported.
if tp == bool:
return (value_str == '1')
elif tp == int:
return int(value_str)
elif tp == float:
return float(value_str)
|
[
"def",
"_get_parameter",
"(",
"self",
",",
"name",
",",
"tp",
",",
"timeout",
"=",
"1.0",
",",
"max_retries",
"=",
"2",
")",
":",
"# Raise a TypeError if tp isn't one of the valid types.",
"if",
"tp",
"not",
"in",
"(",
"bool",
",",
"int",
",",
"float",
")",
":",
"raise",
"TypeError",
"(",
"'Only supports bool, int, and float; not '",
"+",
"str",
"(",
"tp",
")",
")",
"# Sending a command of name queries the state for that",
"# parameter. The response will have name preceeded by an '*' and",
"# then followed by a number which will have to be converted.",
"response",
"=",
"self",
".",
"driver",
".",
"send_command",
"(",
"name",
",",
"timeout",
"=",
"timeout",
",",
"immediate",
"=",
"True",
",",
"max_retries",
"=",
"max_retries",
")",
"# If the response has an error, there are no response lines, or",
"# the first response line isn't '*'+name; then there was an",
"# error and an exception needs to be thrown.",
"if",
"self",
".",
"driver",
".",
"command_error",
"(",
"response",
")",
"or",
"len",
"(",
"response",
"[",
"4",
"]",
")",
"==",
"0",
"or",
"not",
"response",
"[",
"4",
"]",
"[",
"0",
"]",
".",
"startswith",
"(",
"'*'",
"+",
"name",
")",
":",
"raise",
"CommandError",
"(",
"'Couldn'",
"'t retrieve parameter '",
"+",
"name",
")",
"# Extract the string representation of the value, which is after",
"# the '*'+name.",
"value_str",
"=",
"response",
"[",
"4",
"]",
"[",
"0",
"]",
"[",
"(",
"len",
"(",
"name",
")",
"+",
"1",
")",
":",
"]",
"# Convert the value string to the appropriate type and return",
"# it. Throw an error if it is not supported.",
"if",
"tp",
"==",
"bool",
":",
"return",
"(",
"value_str",
"==",
"'1'",
")",
"elif",
"tp",
"==",
"int",
":",
"return",
"int",
"(",
"value_str",
")",
"elif",
"tp",
"==",
"float",
":",
"return",
"float",
"(",
"value_str",
")"
] |
Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
value : bool, int, or float
The value of the specified parameter.
Raises
------
TypeError
If 'tp' is not an allowed type (``bool``, ``int``,
``float``).
CommandError
If the command to retrieve the parameter returned an error.
ValueError
If the value returned to the drive cannot be converted to
the proper type.
See Also
--------
_set_parameter : Set a parameter.
|
[
"Gets",
"the",
"specified",
"drive",
"parameter",
"."
] |
8de347ffb91228fbfe3832098b4996fa0141d8f1
|
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L145-L219
|
246,486 |
frejanordsiek/GeminiMotorDrive
|
GeminiMotorDrive/__init__.py
|
GeminiG6._set_parameter
|
def _set_parameter(self, name, value, tp, timeout=1.0,
max_retries=2):
""" Sets the specified drive parameter.
Sets a parameter on the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to set. It is always the command to
set it when followed by the value.
value : bool, int, or float
Value to set the parameter to.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
success : bool
Whether the last attempt to set the parameter was successful
(``True``) or not (``False`` meaning it had an error).
See Also
--------
_get_parameter : Get a parameter.
"""
# Return False if tp isn't one of the valid types.
if tp not in (bool, int, float):
return False
# Convert value to the string that the drive will expect. value
# must first be converted to the proper type before getting
# converted to str in the usual fasion. As bools need to be a
# '1' or a '0', it must be converted to int before going through
# str.
if tp == bool:
value_str = str(int(bool(value)))
elif tp == int:
value_str = str(int(value))
elif tp == float:
value_str = str(float(value))
# Immediately set the named parameter of the drive. The command
# is just the parameter name followed by the value string.
response = self.driver.send_command(name+value_str, \
timeout=timeout, immediate=True, max_retries=max_retries)
# Return whether the setting was successful or not.
return not self.driver.command_error(response)
|
python
|
def _set_parameter(self, name, value, tp, timeout=1.0,
max_retries=2):
""" Sets the specified drive parameter.
Sets a parameter on the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to set. It is always the command to
set it when followed by the value.
value : bool, int, or float
Value to set the parameter to.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
success : bool
Whether the last attempt to set the parameter was successful
(``True``) or not (``False`` meaning it had an error).
See Also
--------
_get_parameter : Get a parameter.
"""
# Return False if tp isn't one of the valid types.
if tp not in (bool, int, float):
return False
# Convert value to the string that the drive will expect. value
# must first be converted to the proper type before getting
# converted to str in the usual fasion. As bools need to be a
# '1' or a '0', it must be converted to int before going through
# str.
if tp == bool:
value_str = str(int(bool(value)))
elif tp == int:
value_str = str(int(value))
elif tp == float:
value_str = str(float(value))
# Immediately set the named parameter of the drive. The command
# is just the parameter name followed by the value string.
response = self.driver.send_command(name+value_str, \
timeout=timeout, immediate=True, max_retries=max_retries)
# Return whether the setting was successful or not.
return not self.driver.command_error(response)
|
[
"def",
"_set_parameter",
"(",
"self",
",",
"name",
",",
"value",
",",
"tp",
",",
"timeout",
"=",
"1.0",
",",
"max_retries",
"=",
"2",
")",
":",
"# Return False if tp isn't one of the valid types.",
"if",
"tp",
"not",
"in",
"(",
"bool",
",",
"int",
",",
"float",
")",
":",
"return",
"False",
"# Convert value to the string that the drive will expect. value",
"# must first be converted to the proper type before getting",
"# converted to str in the usual fasion. As bools need to be a",
"# '1' or a '0', it must be converted to int before going through",
"# str.",
"if",
"tp",
"==",
"bool",
":",
"value_str",
"=",
"str",
"(",
"int",
"(",
"bool",
"(",
"value",
")",
")",
")",
"elif",
"tp",
"==",
"int",
":",
"value_str",
"=",
"str",
"(",
"int",
"(",
"value",
")",
")",
"elif",
"tp",
"==",
"float",
":",
"value_str",
"=",
"str",
"(",
"float",
"(",
"value",
")",
")",
"# Immediately set the named parameter of the drive. The command",
"# is just the parameter name followed by the value string.",
"response",
"=",
"self",
".",
"driver",
".",
"send_command",
"(",
"name",
"+",
"value_str",
",",
"timeout",
"=",
"timeout",
",",
"immediate",
"=",
"True",
",",
"max_retries",
"=",
"max_retries",
")",
"# Return whether the setting was successful or not.",
"return",
"not",
"self",
".",
"driver",
".",
"command_error",
"(",
"response",
")"
] |
Sets the specified drive parameter.
Sets a parameter on the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to set. It is always the command to
set it when followed by the value.
value : bool, int, or float
Value to set the parameter to.
tp : type {bool, int, float}
The type of the parameter.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
success : bool
Whether the last attempt to set the parameter was successful
(``True``) or not (``False`` meaning it had an error).
See Also
--------
_get_parameter : Get a parameter.
|
[
"Sets",
"the",
"specified",
"drive",
"parameter",
"."
] |
8de347ffb91228fbfe3832098b4996fa0141d8f1
|
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L221-L278
|
246,487 |
frejanordsiek/GeminiMotorDrive
|
GeminiMotorDrive/__init__.py
|
GeminiG6.get_program
|
def get_program(self, n, timeout=2.0, max_retries=2):
""" Get a program from the drive.
Gets program 'n' from the drive and returns its commands.
Parameters
----------
n : int
Which program to get.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the program. The
trailing 'END' is removed. Empty if there was an error.
Notes
-----
The command sent to the drive is '!TPROG PROGn'.
See Also
--------
set_program_profile : Sets a program or profile.
run_program_profile : Runs a program or profile.
"""
# Send the 'TPROG PROGn' command to read the program.
response = self.driver.send_command( \
'TPROG PROG' + str(int(n)), timeout=timeout, \
immediate=True, max_retries=max_retries)
# If there was an error, then return empty. Otherwise, return
# the response lines but strip the leading '*' first and the
# 'END' at the end of the list.
if self.driver.command_error(response) \
or len(response[4]) == 0:
return []
else:
if '*END' in response[4]:
response[4].remove('*END')
return [line[1:] for line in response[4]]
|
python
|
def get_program(self, n, timeout=2.0, max_retries=2):
""" Get a program from the drive.
Gets program 'n' from the drive and returns its commands.
Parameters
----------
n : int
Which program to get.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the program. The
trailing 'END' is removed. Empty if there was an error.
Notes
-----
The command sent to the drive is '!TPROG PROGn'.
See Also
--------
set_program_profile : Sets a program or profile.
run_program_profile : Runs a program or profile.
"""
# Send the 'TPROG PROGn' command to read the program.
response = self.driver.send_command( \
'TPROG PROG' + str(int(n)), timeout=timeout, \
immediate=True, max_retries=max_retries)
# If there was an error, then return empty. Otherwise, return
# the response lines but strip the leading '*' first and the
# 'END' at the end of the list.
if self.driver.command_error(response) \
or len(response[4]) == 0:
return []
else:
if '*END' in response[4]:
response[4].remove('*END')
return [line[1:] for line in response[4]]
|
[
"def",
"get_program",
"(",
"self",
",",
"n",
",",
"timeout",
"=",
"2.0",
",",
"max_retries",
"=",
"2",
")",
":",
"# Send the 'TPROG PROGn' command to read the program.",
"response",
"=",
"self",
".",
"driver",
".",
"send_command",
"(",
"'TPROG PROG'",
"+",
"str",
"(",
"int",
"(",
"n",
")",
")",
",",
"timeout",
"=",
"timeout",
",",
"immediate",
"=",
"True",
",",
"max_retries",
"=",
"max_retries",
")",
"# If there was an error, then return empty. Otherwise, return",
"# the response lines but strip the leading '*' first and the",
"# 'END' at the end of the list.",
"if",
"self",
".",
"driver",
".",
"command_error",
"(",
"response",
")",
"or",
"len",
"(",
"response",
"[",
"4",
"]",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"if",
"'*END'",
"in",
"response",
"[",
"4",
"]",
":",
"response",
"[",
"4",
"]",
".",
"remove",
"(",
"'*END'",
")",
"return",
"[",
"line",
"[",
"1",
":",
"]",
"for",
"line",
"in",
"response",
"[",
"4",
"]",
"]"
] |
Get a program from the drive.
Gets program 'n' from the drive and returns its commands.
Parameters
----------
n : int
Which program to get.
timeout : number, optional
Optional timeout in seconds to use when reading the
response. A negative value or ``None`` indicates that the
an infinite timeout should be used.
max_retries : int, optional
Maximum number of retries to do per command in the case of
errors.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the program. The
trailing 'END' is removed. Empty if there was an error.
Notes
-----
The command sent to the drive is '!TPROG PROGn'.
See Also
--------
set_program_profile : Sets a program or profile.
run_program_profile : Runs a program or profile.
|
[
"Get",
"a",
"program",
"from",
"the",
"drive",
"."
] |
8de347ffb91228fbfe3832098b4996fa0141d8f1
|
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L433-L480
|
246,488 |
frejanordsiek/GeminiMotorDrive
|
GeminiMotorDrive/__init__.py
|
GeminiG6.motion_commanded
|
def motion_commanded(self):
""" Whether motion is commanded or not.
``bool``
Can't be set.
Notes
-----
It is the value of the first bit of the 'TAS' command.
"""
rsp = self.driver.send_command('TAS', immediate=True)
if self.driver.command_error(rsp) or len(rsp[4]) != 1 \
or rsp[4][0][0:4] != '*TAS':
return False
else:
return (rsp[4][0][4] == '1')
|
python
|
def motion_commanded(self):
""" Whether motion is commanded or not.
``bool``
Can't be set.
Notes
-----
It is the value of the first bit of the 'TAS' command.
"""
rsp = self.driver.send_command('TAS', immediate=True)
if self.driver.command_error(rsp) or len(rsp[4]) != 1 \
or rsp[4][0][0:4] != '*TAS':
return False
else:
return (rsp[4][0][4] == '1')
|
[
"def",
"motion_commanded",
"(",
"self",
")",
":",
"rsp",
"=",
"self",
".",
"driver",
".",
"send_command",
"(",
"'TAS'",
",",
"immediate",
"=",
"True",
")",
"if",
"self",
".",
"driver",
".",
"command_error",
"(",
"rsp",
")",
"or",
"len",
"(",
"rsp",
"[",
"4",
"]",
")",
"!=",
"1",
"or",
"rsp",
"[",
"4",
"]",
"[",
"0",
"]",
"[",
"0",
":",
"4",
"]",
"!=",
"'*TAS'",
":",
"return",
"False",
"else",
":",
"return",
"(",
"rsp",
"[",
"4",
"]",
"[",
"0",
"]",
"[",
"4",
"]",
"==",
"'1'",
")"
] |
Whether motion is commanded or not.
``bool``
Can't be set.
Notes
-----
It is the value of the first bit of the 'TAS' command.
|
[
"Whether",
"motion",
"is",
"commanded",
"or",
"not",
"."
] |
8de347ffb91228fbfe3832098b4996fa0141d8f1
|
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L750-L767
|
246,489 |
jldantas/libmft
|
libmft/util/functions.py
|
apply_fixup_array
|
def apply_fixup_array(bin_view, fx_offset, fx_count, entry_size):
'''This function reads the fixup array and apply the correct values
to the underlying binary stream. This function changes the bin_view
in memory.
Args:
bin_view (memoryview of bytearray) - The binary stream
fx_offset (int) - Offset to the fixup array
fx_count (int) - Number of elements in the fixup array
entry_size (int) - Size of the MFT entry
'''
fx_array = bin_view[fx_offset:fx_offset+(2 * fx_count)]
#the array is composed of the signature + substitutions, so fix that
fx_len = fx_count - 1
#we can infer the sector size based on the entry size
sector_size = int(entry_size / fx_len)
index = 1
position = (sector_size * index) - 2
while (position <= entry_size):
if bin_view[position:position+2].tobytes() == fx_array[:2].tobytes():
#the replaced part must always match the signature!
bin_view[position:position+2] = fx_array[index * 2:(index * 2) + 2]
else:
_MOD_LOGGER.error("Error applying the fixup array")
raise FixUpError(f"Signature {fx_array[:2].tobytes()} does not match {bin_view[position:position+2].tobytes()} at offset {position}.")
index += 1
position = (sector_size * index) - 2
_MOD_LOGGER.info("Fix up array applied successfully.")
|
python
|
def apply_fixup_array(bin_view, fx_offset, fx_count, entry_size):
'''This function reads the fixup array and apply the correct values
to the underlying binary stream. This function changes the bin_view
in memory.
Args:
bin_view (memoryview of bytearray) - The binary stream
fx_offset (int) - Offset to the fixup array
fx_count (int) - Number of elements in the fixup array
entry_size (int) - Size of the MFT entry
'''
fx_array = bin_view[fx_offset:fx_offset+(2 * fx_count)]
#the array is composed of the signature + substitutions, so fix that
fx_len = fx_count - 1
#we can infer the sector size based on the entry size
sector_size = int(entry_size / fx_len)
index = 1
position = (sector_size * index) - 2
while (position <= entry_size):
if bin_view[position:position+2].tobytes() == fx_array[:2].tobytes():
#the replaced part must always match the signature!
bin_view[position:position+2] = fx_array[index * 2:(index * 2) + 2]
else:
_MOD_LOGGER.error("Error applying the fixup array")
raise FixUpError(f"Signature {fx_array[:2].tobytes()} does not match {bin_view[position:position+2].tobytes()} at offset {position}.")
index += 1
position = (sector_size * index) - 2
_MOD_LOGGER.info("Fix up array applied successfully.")
|
[
"def",
"apply_fixup_array",
"(",
"bin_view",
",",
"fx_offset",
",",
"fx_count",
",",
"entry_size",
")",
":",
"fx_array",
"=",
"bin_view",
"[",
"fx_offset",
":",
"fx_offset",
"+",
"(",
"2",
"*",
"fx_count",
")",
"]",
"#the array is composed of the signature + substitutions, so fix that",
"fx_len",
"=",
"fx_count",
"-",
"1",
"#we can infer the sector size based on the entry size",
"sector_size",
"=",
"int",
"(",
"entry_size",
"/",
"fx_len",
")",
"index",
"=",
"1",
"position",
"=",
"(",
"sector_size",
"*",
"index",
")",
"-",
"2",
"while",
"(",
"position",
"<=",
"entry_size",
")",
":",
"if",
"bin_view",
"[",
"position",
":",
"position",
"+",
"2",
"]",
".",
"tobytes",
"(",
")",
"==",
"fx_array",
"[",
":",
"2",
"]",
".",
"tobytes",
"(",
")",
":",
"#the replaced part must always match the signature!",
"bin_view",
"[",
"position",
":",
"position",
"+",
"2",
"]",
"=",
"fx_array",
"[",
"index",
"*",
"2",
":",
"(",
"index",
"*",
"2",
")",
"+",
"2",
"]",
"else",
":",
"_MOD_LOGGER",
".",
"error",
"(",
"\"Error applying the fixup array\"",
")",
"raise",
"FixUpError",
"(",
"f\"Signature {fx_array[:2].tobytes()} does not match {bin_view[position:position+2].tobytes()} at offset {position}.\"",
")",
"index",
"+=",
"1",
"position",
"=",
"(",
"sector_size",
"*",
"index",
")",
"-",
"2",
"_MOD_LOGGER",
".",
"info",
"(",
"\"Fix up array applied successfully.\"",
")"
] |
This function reads the fixup array and apply the correct values
to the underlying binary stream. This function changes the bin_view
in memory.
Args:
bin_view (memoryview of bytearray) - The binary stream
fx_offset (int) - Offset to the fixup array
fx_count (int) - Number of elements in the fixup array
entry_size (int) - Size of the MFT entry
|
[
"This",
"function",
"reads",
"the",
"fixup",
"array",
"and",
"apply",
"the",
"correct",
"values",
"to",
"the",
"underlying",
"binary",
"stream",
".",
"This",
"function",
"changes",
"the",
"bin_view",
"in",
"memory",
"."
] |
65a988605fe7663b788bd81dcb52c0a4eaad1549
|
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/util/functions.py#L46-L73
|
246,490 |
jldantas/libmft
|
libmft/util/functions.py
|
get_file_size
|
def get_file_size(file_object):
'''Returns the size, in bytes, of a file. Expects an object that supports
seek and tell methods.
Args:
file_object (file_object) - The object that represents the file
Returns:
(int): size of the file, in bytes'''
position = file_object.tell()
file_object.seek(0, 2)
file_size = file_object.tell()
file_object.seek(position, 0)
return file_size
|
python
|
def get_file_size(file_object):
'''Returns the size, in bytes, of a file. Expects an object that supports
seek and tell methods.
Args:
file_object (file_object) - The object that represents the file
Returns:
(int): size of the file, in bytes'''
position = file_object.tell()
file_object.seek(0, 2)
file_size = file_object.tell()
file_object.seek(position, 0)
return file_size
|
[
"def",
"get_file_size",
"(",
"file_object",
")",
":",
"position",
"=",
"file_object",
".",
"tell",
"(",
")",
"file_object",
".",
"seek",
"(",
"0",
",",
"2",
")",
"file_size",
"=",
"file_object",
".",
"tell",
"(",
")",
"file_object",
".",
"seek",
"(",
"position",
",",
"0",
")",
"return",
"file_size"
] |
Returns the size, in bytes, of a file. Expects an object that supports
seek and tell methods.
Args:
file_object (file_object) - The object that represents the file
Returns:
(int): size of the file, in bytes
|
[
"Returns",
"the",
"size",
"in",
"bytes",
"of",
"a",
"file",
".",
"Expects",
"an",
"object",
"that",
"supports",
"seek",
"and",
"tell",
"methods",
"."
] |
65a988605fe7663b788bd81dcb52c0a4eaad1549
|
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/util/functions.py#L87-L102
|
246,491 |
klen/muffin-jinja2
|
muffin_jinja2.py
|
Plugin.context_processor
|
def context_processor(self, func):
""" Decorate a given function to use as a context processor.
::
@app.ps.jinja2.context_processor
def my_context():
return {...}
"""
func = to_coroutine(func)
self.providers.append(func)
return func
|
python
|
def context_processor(self, func):
""" Decorate a given function to use as a context processor.
::
@app.ps.jinja2.context_processor
def my_context():
return {...}
"""
func = to_coroutine(func)
self.providers.append(func)
return func
|
[
"def",
"context_processor",
"(",
"self",
",",
"func",
")",
":",
"func",
"=",
"to_coroutine",
"(",
"func",
")",
"self",
".",
"providers",
".",
"append",
"(",
"func",
")",
"return",
"func"
] |
Decorate a given function to use as a context processor.
::
@app.ps.jinja2.context_processor
def my_context():
return {...}
|
[
"Decorate",
"a",
"given",
"function",
"to",
"use",
"as",
"a",
"context",
"processor",
"."
] |
0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2
|
https://github.com/klen/muffin-jinja2/blob/0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2/muffin_jinja2.py#L70-L80
|
246,492 |
klen/muffin-jinja2
|
muffin_jinja2.py
|
Plugin.register
|
def register(self, value):
""" Register function to globals. """
if self.env is None:
raise PluginException('The plugin must be installed to application.')
def wrapper(func):
name = func.__name__
if isinstance(value, str):
name = value
if callable(func):
self.env.globals[name] = func
return func
if callable(value):
return wrapper(value)
return wrapper
|
python
|
def register(self, value):
""" Register function to globals. """
if self.env is None:
raise PluginException('The plugin must be installed to application.')
def wrapper(func):
name = func.__name__
if isinstance(value, str):
name = value
if callable(func):
self.env.globals[name] = func
return func
if callable(value):
return wrapper(value)
return wrapper
|
[
"def",
"register",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"env",
"is",
"None",
":",
"raise",
"PluginException",
"(",
"'The plugin must be installed to application.'",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"name",
"=",
"value",
"if",
"callable",
"(",
"func",
")",
":",
"self",
".",
"env",
".",
"globals",
"[",
"name",
"]",
"=",
"func",
"return",
"func",
"if",
"callable",
"(",
"value",
")",
":",
"return",
"wrapper",
"(",
"value",
")",
"return",
"wrapper"
] |
Register function to globals.
|
[
"Register",
"function",
"to",
"globals",
"."
] |
0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2
|
https://github.com/klen/muffin-jinja2/blob/0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2/muffin_jinja2.py#L82-L98
|
246,493 |
klen/muffin-jinja2
|
muffin_jinja2.py
|
Plugin.filter
|
def filter(self, value):
""" Register function to filters. """
if self.env is None:
raise PluginException('The plugin must be installed to application.')
def wrapper(func):
name = func.__name__
if isinstance(value, str):
name = value
if callable(func):
self.env.filters[name] = func
return func
if callable(value):
return wrapper(value)
return wrapper
|
python
|
def filter(self, value):
""" Register function to filters. """
if self.env is None:
raise PluginException('The plugin must be installed to application.')
def wrapper(func):
name = func.__name__
if isinstance(value, str):
name = value
if callable(func):
self.env.filters[name] = func
return func
if callable(value):
return wrapper(value)
return wrapper
|
[
"def",
"filter",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"env",
"is",
"None",
":",
"raise",
"PluginException",
"(",
"'The plugin must be installed to application.'",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"name",
"=",
"value",
"if",
"callable",
"(",
"func",
")",
":",
"self",
".",
"env",
".",
"filters",
"[",
"name",
"]",
"=",
"func",
"return",
"func",
"if",
"callable",
"(",
"value",
")",
":",
"return",
"wrapper",
"(",
"value",
")",
"return",
"wrapper"
] |
Register function to filters.
|
[
"Register",
"function",
"to",
"filters",
"."
] |
0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2
|
https://github.com/klen/muffin-jinja2/blob/0458c9b4d88370de3ff8f0ef432ea888dd3a3dd2/muffin_jinja2.py#L100-L116
|
246,494 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.handle_event
|
def handle_event(self, event):
"""
An abstract method that must be overwritten by child classes used to handle events.
event - the event to be handled
returns true or false if the event could be handled here
default code is given for this method, however subclasses must still override this method to insure the subclass has the correct behavior.
"""
# loop through the handlers associated with the event type.
for h in self._events.get(event.type, []):
# Iterate through the handler's dictionary of event parameters
for k, v in h.params.items():
# get the value of event.k, if none, return v
if not v(getattr(event, k, v)):
break
else:
h.call_actions(event)
if self._logger is not None:
self._logger.debug("Handle event: {}.".format(event))
return True
return False
|
python
|
def handle_event(self, event):
"""
An abstract method that must be overwritten by child classes used to handle events.
event - the event to be handled
returns true or false if the event could be handled here
default code is given for this method, however subclasses must still override this method to insure the subclass has the correct behavior.
"""
# loop through the handlers associated with the event type.
for h in self._events.get(event.type, []):
# Iterate through the handler's dictionary of event parameters
for k, v in h.params.items():
# get the value of event.k, if none, return v
if not v(getattr(event, k, v)):
break
else:
h.call_actions(event)
if self._logger is not None:
self._logger.debug("Handle event: {}.".format(event))
return True
return False
|
[
"def",
"handle_event",
"(",
"self",
",",
"event",
")",
":",
"# loop through the handlers associated with the event type.",
"for",
"h",
"in",
"self",
".",
"_events",
".",
"get",
"(",
"event",
".",
"type",
",",
"[",
"]",
")",
":",
"# Iterate through the handler's dictionary of event parameters ",
"for",
"k",
",",
"v",
"in",
"h",
".",
"params",
".",
"items",
"(",
")",
":",
"# get the value of event.k, if none, return v",
"if",
"not",
"v",
"(",
"getattr",
"(",
"event",
",",
"k",
",",
"v",
")",
")",
":",
"break",
"else",
":",
"h",
".",
"call_actions",
"(",
"event",
")",
"if",
"self",
".",
"_logger",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Handle event: {}.\"",
".",
"format",
"(",
"event",
")",
")",
"return",
"True",
"return",
"False"
] |
An abstract method that must be overwritten by child classes used to handle events.
event - the event to be handled
returns true or false if the event could be handled here
default code is given for this method, however subclasses must still override this method to insure the subclass has the correct behavior.
|
[
"An",
"abstract",
"method",
"that",
"must",
"be",
"overwritten",
"by",
"child",
"classes",
"used",
"to",
"handle",
"events",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L32-L57
|
246,495 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.logger
|
def logger(self, logger):
"""Set the logger if is not None, and it is of type Logger."""
if logger is None or not isinstance(logger, Logger):
raise ValueError("Logger can not be set to None, and must be of type logging.Logger")
self._logger = logger
|
python
|
def logger(self, logger):
"""Set the logger if is not None, and it is of type Logger."""
if logger is None or not isinstance(logger, Logger):
raise ValueError("Logger can not be set to None, and must be of type logging.Logger")
self._logger = logger
|
[
"def",
"logger",
"(",
"self",
",",
"logger",
")",
":",
"if",
"logger",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"logger",
",",
"Logger",
")",
":",
"raise",
"ValueError",
"(",
"\"Logger can not be set to None, and must be of type logging.Logger\"",
")",
"self",
".",
"_logger",
"=",
"logger"
] |
Set the logger if is not None, and it is of type Logger.
|
[
"Set",
"the",
"logger",
"if",
"is",
"not",
"None",
"and",
"it",
"is",
"of",
"type",
"Logger",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L70-L75
|
246,496 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.add_handler
|
def add_handler(self, type, actions, **kwargs):
"""
Add an event handler to be processed by this session.
type - The type of the event (pygame.QUIT, pygame.KEYUP ETC).
actions - The methods which should be called when an event matching this specification is received.
more than one action can be tied to a single event. This allows for secondary actions to occur along side already existing actions such as the down errow in the List.
You can either pass the actions or action as a single parameter or as a list.
kwargs - An arbitrary number of parameters which must be satisfied in order for the event to match.
The keywords are directly matched with the instance variables found in the current event
Each value for kwargs can optionally be a lambda which must evaluate to True in order for the match to work.
Example:
session.add_handler(pygame.QUIT, session.do_quit)
session.add_handler(pygame.KEYDOWN, lambda: ao2.speak("You pressed the enter key."), key = pygame.K_RETURN)
"""
l = self._events.get(type, [])
h = Handler(self, type, kwargs, actions)
l.append(h)
self._events[type] = l
return h
|
python
|
def add_handler(self, type, actions, **kwargs):
"""
Add an event handler to be processed by this session.
type - The type of the event (pygame.QUIT, pygame.KEYUP ETC).
actions - The methods which should be called when an event matching this specification is received.
more than one action can be tied to a single event. This allows for secondary actions to occur along side already existing actions such as the down errow in the List.
You can either pass the actions or action as a single parameter or as a list.
kwargs - An arbitrary number of parameters which must be satisfied in order for the event to match.
The keywords are directly matched with the instance variables found in the current event
Each value for kwargs can optionally be a lambda which must evaluate to True in order for the match to work.
Example:
session.add_handler(pygame.QUIT, session.do_quit)
session.add_handler(pygame.KEYDOWN, lambda: ao2.speak("You pressed the enter key."), key = pygame.K_RETURN)
"""
l = self._events.get(type, [])
h = Handler(self, type, kwargs, actions)
l.append(h)
self._events[type] = l
return h
|
[
"def",
"add_handler",
"(",
"self",
",",
"type",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"l",
"=",
"self",
".",
"_events",
".",
"get",
"(",
"type",
",",
"[",
"]",
")",
"h",
"=",
"Handler",
"(",
"self",
",",
"type",
",",
"kwargs",
",",
"actions",
")",
"l",
".",
"append",
"(",
"h",
")",
"self",
".",
"_events",
"[",
"type",
"]",
"=",
"l",
"return",
"h"
] |
Add an event handler to be processed by this session.
type - The type of the event (pygame.QUIT, pygame.KEYUP ETC).
actions - The methods which should be called when an event matching this specification is received.
more than one action can be tied to a single event. This allows for secondary actions to occur along side already existing actions such as the down errow in the List.
You can either pass the actions or action as a single parameter or as a list.
kwargs - An arbitrary number of parameters which must be satisfied in order for the event to match.
The keywords are directly matched with the instance variables found in the current event
Each value for kwargs can optionally be a lambda which must evaluate to True in order for the match to work.
Example:
session.add_handler(pygame.QUIT, session.do_quit)
session.add_handler(pygame.KEYDOWN, lambda: ao2.speak("You pressed the enter key."), key = pygame.K_RETURN)
|
[
"Add",
"an",
"event",
"handler",
"to",
"be",
"processed",
"by",
"this",
"session",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L77-L101
|
246,497 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.remove_handler
|
def remove_handler(self, handler):
"""
Remove a handler from the list.
handler - The handler (as returned by add_handler) to remove.
Returns True on success, False otherwise.
"""
try:
self._events[handler.type].remove(handler)
return True
except ValueError:
return False
|
python
|
def remove_handler(self, handler):
"""
Remove a handler from the list.
handler - The handler (as returned by add_handler) to remove.
Returns True on success, False otherwise.
"""
try:
self._events[handler.type].remove(handler)
return True
except ValueError:
return False
|
[
"def",
"remove_handler",
"(",
"self",
",",
"handler",
")",
":",
"try",
":",
"self",
".",
"_events",
"[",
"handler",
".",
"type",
"]",
".",
"remove",
"(",
"handler",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] |
Remove a handler from the list.
handler - The handler (as returned by add_handler) to remove.
Returns True on success, False otherwise.
|
[
"Remove",
"a",
"handler",
"from",
"the",
"list",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L103-L115
|
246,498 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.add_keydown
|
def add_keydown(self, actions, **kwargs):
"""
Add a pygame.KEYDOWN event handler.
actions - The methods to be called when this key is pressed.
kwargs - The kwargs to be passed to self.add_handler.
See the documentation for self.add_handler for examples.
"""
return self.add_handler(pygame.KEYDOWN, actions, **kwargs)
|
python
|
def add_keydown(self, actions, **kwargs):
"""
Add a pygame.KEYDOWN event handler.
actions - The methods to be called when this key is pressed.
kwargs - The kwargs to be passed to self.add_handler.
See the documentation for self.add_handler for examples.
"""
return self.add_handler(pygame.KEYDOWN, actions, **kwargs)
|
[
"def",
"add_keydown",
"(",
"self",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"add_handler",
"(",
"pygame",
".",
"KEYDOWN",
",",
"actions",
",",
"*",
"*",
"kwargs",
")"
] |
Add a pygame.KEYDOWN event handler.
actions - The methods to be called when this key is pressed.
kwargs - The kwargs to be passed to self.add_handler.
See the documentation for self.add_handler for examples.
|
[
"Add",
"a",
"pygame",
".",
"KEYDOWN",
"event",
"handler",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L117-L127
|
246,499 |
tbreitenfeldt/invisible_ui
|
invisible_ui/events/eventManager.py
|
EventManager.add_keyup
|
def add_keyup(self, actions, **kwargs):
"""See the documentation for self.add_keydown."""
return self.add_handler(pygame.KEYUP, actions, **kwargs)
|
python
|
def add_keyup(self, actions, **kwargs):
"""See the documentation for self.add_keydown."""
return self.add_handler(pygame.KEYUP, actions, **kwargs)
|
[
"def",
"add_keyup",
"(",
"self",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"add_handler",
"(",
"pygame",
".",
"KEYUP",
",",
"actions",
",",
"*",
"*",
"kwargs",
")"
] |
See the documentation for self.add_keydown.
|
[
"See",
"the",
"documentation",
"for",
"self",
".",
"add_keydown",
"."
] |
1a6907bfa61bded13fa9fb83ec7778c0df84487f
|
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L129-L131
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.