repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
DaveMcEwan/ndim | ndim_arc.py | arc_length | def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0):
'''Return Euclidean length of arc.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
... | python | def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0):
'''Return Euclidean length of arc.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 0
assert l_angle == len(end_a)
for i in start_a:
assert isinstance(i, float)
... | [
"def",
"arc_length",
"(",
"start_a",
"=",
"[",
"0.0",
"]",
",",
"end_a",
"=",
"[",
"0.0",
"]",
",",
"radius",
"=",
"0.0",
")",
":",
"assert",
"isinstance",
"(",
"start_a",
",",
"list",
")",
"assert",
"isinstance",
"(",
"end_a",
",",
"list",
")",
"l... | Return Euclidean length of arc. | [
"Return",
"Euclidean",
"length",
"of",
"arc",
"."
] | train | https://github.com/DaveMcEwan/ndim/blob/f1ea023d3e597160fc1e9e11921de07af659f9d2/ndim_arc.py#L41-L61 |
alexkreimer/django-pagination | pagination/templatetags/pagination_tags.py | do_autopaginate | def do_autopaginate(parser, token):
"""
Splits the arguments to the autopaginate tag and formats them correctly.
"""
split = token.split_contents()
as_index = None
context_var = None
for i, bit in enumerate(split):
if bit == 'as':
as_index = i
break
if as_... | python | def do_autopaginate(parser, token):
"""
Splits the arguments to the autopaginate tag and formats them correctly.
"""
split = token.split_contents()
as_index = None
context_var = None
for i, bit in enumerate(split):
if bit == 'as':
as_index = i
break
if as_... | [
"def",
"do_autopaginate",
"(",
"parser",
",",
"token",
")",
":",
"split",
"=",
"token",
".",
"split_contents",
"(",
")",
"as_index",
"=",
"None",
"context_var",
"=",
"None",
"for",
"i",
",",
"bit",
"in",
"enumerate",
"(",
"split",
")",
":",
"if",
"bit"... | Splits the arguments to the autopaginate tag and formats them correctly. | [
"Splits",
"the",
"arguments",
"to",
"the",
"autopaginate",
"tag",
"and",
"formats",
"them",
"correctly",
"."
] | train | https://github.com/alexkreimer/django-pagination/blob/428e6b2277ed663fea7ce1a7006974d9f28d3ee5/pagination/templatetags/pagination_tags.py#L19-L53 |
alexkreimer/django-pagination | pagination/templatetags/pagination_tags.py | paginate | def paginate(context, window=DEFAULT_WINDOW):
"""
Renders the ``pagination/pagination.html`` template, resulting in a
Digg-like display of the available pages, given the current page. If there
are too many pages to be displayed before and after the current page, then
elipses will be used to indicat... | python | def paginate(context, window=DEFAULT_WINDOW):
"""
Renders the ``pagination/pagination.html`` template, resulting in a
Digg-like display of the available pages, given the current page. If there
are too many pages to be displayed before and after the current page, then
elipses will be used to indicat... | [
"def",
"paginate",
"(",
"context",
",",
"window",
"=",
"DEFAULT_WINDOW",
")",
":",
"try",
":",
"paginator",
"=",
"context",
"[",
"'paginator'",
"]",
"page_obj",
"=",
"context",
"[",
"'page_obj'",
"]",
"page_range",
"=",
"paginator",
".",
"page_range",
"# Fir... | Renders the ``pagination/pagination.html`` template, resulting in a
Digg-like display of the available pages, given the current page. If there
are too many pages to be displayed before and after the current page, then
elipses will be used to indicate the undisplayed gap between page numbers.
Requi... | [
"Renders",
"the",
"pagination",
"/",
"pagination",
".",
"html",
"template",
"resulting",
"in",
"a",
"Digg",
"-",
"like",
"display",
"of",
"the",
"available",
"pages",
"given",
"the",
"current",
"page",
".",
"If",
"there",
"are",
"too",
"many",
"pages",
"to... | train | https://github.com/alexkreimer/django-pagination/blob/428e6b2277ed663fea7ce1a7006974d9f28d3ee5/pagination/templatetags/pagination_tags.py#L107-L217 |
mayfield/shellish | shellish/command/__init__.py | linebuffered_stdout | def linebuffered_stdout():
""" Always line buffer stdout so pipes and redirects are CLI friendly. """
if sys.stdout.line_buffering:
return sys.stdout
orig = sys.stdout
new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors,
line_buffering=True)
new.mode... | python | def linebuffered_stdout():
""" Always line buffer stdout so pipes and redirects are CLI friendly. """
if sys.stdout.line_buffering:
return sys.stdout
orig = sys.stdout
new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors,
line_buffering=True)
new.mode... | [
"def",
"linebuffered_stdout",
"(",
")",
":",
"if",
"sys",
".",
"stdout",
".",
"line_buffering",
":",
"return",
"sys",
".",
"stdout",
"orig",
"=",
"sys",
".",
"stdout",
"new",
"=",
"type",
"(",
"orig",
")",
"(",
"orig",
".",
"buffer",
",",
"encoding",
... | Always line buffer stdout so pipes and redirects are CLI friendly. | [
"Always",
"line",
"buffer",
"stdout",
"so",
"pipes",
"and",
"redirects",
"are",
"CLI",
"friendly",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/__init__.py#L6-L14 |
mayfield/shellish | shellish/command/__init__.py | ignore_broken_pipe | def ignore_broken_pipe():
""" If a shellish program has redirected stdio it is subject to erroneous
"ignored" exceptions during the interpretor shutdown. This essentially
beats the interpretor to the punch by closing them early and ignoring any
broken pipe exceptions. """
for f in sys.stdin, sys.std... | python | def ignore_broken_pipe():
""" If a shellish program has redirected stdio it is subject to erroneous
"ignored" exceptions during the interpretor shutdown. This essentially
beats the interpretor to the punch by closing them early and ignoring any
broken pipe exceptions. """
for f in sys.stdin, sys.std... | [
"def",
"ignore_broken_pipe",
"(",
")",
":",
"for",
"f",
"in",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
":",
"try",
":",
"f",
".",
"close",
"(",
")",
"except",
"BrokenPipeError",
":",
"pass"
] | If a shellish program has redirected stdio it is subject to erroneous
"ignored" exceptions during the interpretor shutdown. This essentially
beats the interpretor to the punch by closing them early and ignoring any
broken pipe exceptions. | [
"If",
"a",
"shellish",
"program",
"has",
"redirected",
"stdio",
"it",
"is",
"subject",
"to",
"erroneous",
"ignored",
"exceptions",
"during",
"the",
"interpretor",
"shutdown",
".",
"This",
"essentially",
"beats",
"the",
"interpretor",
"to",
"the",
"punch",
"by",
... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/__init__.py#L19-L28 |
TAPPGuild/flask-bitjws | flask_bitjws.py | get_last_nonce | def get_last_nonce(app, key, nonce):
"""
This method is only an example! Replace it with a real nonce database.
:param str key: the public key the nonce belongs to
:param int nonce: the latest nonce
"""
if not hasattr(app, 'example_nonce_db'):
# store nonces as a pair {key: lastnonce}
... | python | def get_last_nonce(app, key, nonce):
"""
This method is only an example! Replace it with a real nonce database.
:param str key: the public key the nonce belongs to
:param int nonce: the latest nonce
"""
if not hasattr(app, 'example_nonce_db'):
# store nonces as a pair {key: lastnonce}
... | [
"def",
"get_last_nonce",
"(",
"app",
",",
"key",
",",
"nonce",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'example_nonce_db'",
")",
":",
"# store nonces as a pair {key: lastnonce}",
"app",
".",
"example_nonce_db",
"=",
"{",
"}",
"if",
"not",
"key",
... | This method is only an example! Replace it with a real nonce database.
:param str key: the public key the nonce belongs to
:param int nonce: the latest nonce | [
"This",
"method",
"is",
"only",
"an",
"example!",
"Replace",
"it",
"with",
"a",
"real",
"nonce",
"database",
"."
] | train | https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L16-L32 |
TAPPGuild/flask-bitjws | flask_bitjws.py | get_user_by_key | def get_user_by_key(app, key):
"""
This method is only an example! Replace it with a real user database.
:param str key: the public key the user belongs to
"""
if not hasattr(app, 'example_user_db'):
app.example_user_db = {}
if key in app.example_user_db:
return app.example_use... | python | def get_user_by_key(app, key):
"""
This method is only an example! Replace it with a real user database.
:param str key: the public key the user belongs to
"""
if not hasattr(app, 'example_user_db'):
app.example_user_db = {}
if key in app.example_user_db:
return app.example_use... | [
"def",
"get_user_by_key",
"(",
"app",
",",
"key",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'example_user_db'",
")",
":",
"app",
".",
"example_user_db",
"=",
"{",
"}",
"if",
"key",
"in",
"app",
".",
"example_user_db",
":",
"return",
"app",
".... | This method is only an example! Replace it with a real user database.
:param str key: the public key the user belongs to | [
"This",
"method",
"is",
"only",
"an",
"example!",
"Replace",
"it",
"with",
"a",
"real",
"user",
"database",
"."
] | train | https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L35-L46 |
TAPPGuild/flask-bitjws | flask_bitjws.py | load_jws_from_request | def load_jws_from_request(req):
"""
This function performs almost entirely bitjws authentication tasks.
If valid bitjws message and signature headers are found,
then the request will be assigned 'jws_header' and 'jws_payload' attributes.
:param req: The flask request to load the jwt claim set from.... | python | def load_jws_from_request(req):
"""
This function performs almost entirely bitjws authentication tasks.
If valid bitjws message and signature headers are found,
then the request will be assigned 'jws_header' and 'jws_payload' attributes.
:param req: The flask request to load the jwt claim set from.... | [
"def",
"load_jws_from_request",
"(",
"req",
")",
":",
"current_app",
".",
"logger",
".",
"info",
"(",
"\"loading request with headers: %s\"",
"%",
"req",
".",
"headers",
")",
"if",
"(",
"(",
"\"content-type\"",
"in",
"req",
".",
"headers",
"and",
"\"application/... | This function performs almost entirely bitjws authentication tasks.
If valid bitjws message and signature headers are found,
then the request will be assigned 'jws_header' and 'jws_payload' attributes.
:param req: The flask request to load the jwt claim set from. | [
"This",
"function",
"performs",
"almost",
"entirely",
"bitjws",
"authentication",
"tasks",
".",
"If",
"valid",
"bitjws",
"message",
"and",
"signature",
"headers",
"are",
"found",
"then",
"the",
"request",
"will",
"be",
"assigned",
"jws_header",
"and",
"jws_payload... | train | https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L52-L72 |
TAPPGuild/flask-bitjws | flask_bitjws.py | load_user_from_request | def load_user_from_request(req):
"""
Just like the Flask.login load_user_from_request
If you need to customize the user loading from your database,
the FlaskBitjws.get_user_by_key method is the one to modify.
:param req: The flask request to load a user based on.
"""
load_jws_from_request(... | python | def load_user_from_request(req):
"""
Just like the Flask.login load_user_from_request
If you need to customize the user loading from your database,
the FlaskBitjws.get_user_by_key method is the one to modify.
:param req: The flask request to load a user based on.
"""
load_jws_from_request(... | [
"def",
"load_user_from_request",
"(",
"req",
")",
":",
"load_jws_from_request",
"(",
"req",
")",
"if",
"not",
"hasattr",
"(",
"req",
",",
"'jws_header'",
")",
"or",
"req",
".",
"jws_header",
"is",
"None",
"or",
"not",
"'iat'",
"in",
"req",
".",
"jws_payloa... | Just like the Flask.login load_user_from_request
If you need to customize the user loading from your database,
the FlaskBitjws.get_user_by_key method is the one to modify.
:param req: The flask request to load a user based on. | [
"Just",
"like",
"the",
"Flask",
".",
"login",
"load_user_from_request"
] | train | https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L75-L104 |
TAPPGuild/flask-bitjws | flask_bitjws.py | FlaskBitjws.create_response | def create_response(self, payload):
"""
Create a signed bitjws response using the supplied payload.
The response content-type will be 'application/jose'.
:param payload: The response content. Must be json-serializable.
:return: The signed Response with headers.
:rtype: f... | python | def create_response(self, payload):
"""
Create a signed bitjws response using the supplied payload.
The response content-type will be 'application/jose'.
:param payload: The response content. Must be json-serializable.
:return: The signed Response with headers.
:rtype: f... | [
"def",
"create_response",
"(",
"self",
",",
"payload",
")",
":",
"signedmess",
"=",
"bitjws",
".",
"sign_serialize",
"(",
"self",
".",
"_privkey",
",",
"requrl",
"=",
"'/response'",
",",
"iat",
"=",
"time",
".",
"time",
"(",
")",
",",
"data",
"=",
"pay... | Create a signed bitjws response using the supplied payload.
The response content-type will be 'application/jose'.
:param payload: The response content. Must be json-serializable.
:return: The signed Response with headers.
:rtype: flask.Response | [
"Create",
"a",
"signed",
"bitjws",
"response",
"using",
"the",
"supplied",
"payload",
".",
"The",
"response",
"content",
"-",
"type",
"will",
"be",
"application",
"/",
"jose",
"."
] | train | https://github.com/TAPPGuild/flask-bitjws/blob/8f71b048a2d23c704ab1a84c3ee2f05914bb8347/flask_bitjws.py#L171-L182 |
ludwiktrammer/applamp | applamp/white.py | WhiteLight.fade_out | def fade_out(self, duration=3, group=0):
"""Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds)"""
self.on(group)
super(WhiteLight, self).fade_out(duration, group=group)
self.off(group) | python | def fade_out(self, duration=3, group=0):
"""Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds)"""
self.on(group)
super(WhiteLight, self).fade_out(duration, group=group)
self.off(group) | [
"def",
"fade_out",
"(",
"self",
",",
"duration",
"=",
"3",
",",
"group",
"=",
"0",
")",
":",
"self",
".",
"on",
"(",
"group",
")",
"super",
"(",
"WhiteLight",
",",
"self",
")",
".",
"fade_out",
"(",
"duration",
",",
"group",
"=",
"group",
")",
"s... | Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds) | [
"Turns",
"off",
"the",
"light",
"by",
"gradually",
"fading",
"it",
"out",
".",
"The",
"optional",
"duration",
"parameter",
"allows",
"for",
"control",
"of",
"the",
"fade",
"out",
"duration",
"(",
"in",
"seconds",
")"
] | train | https://github.com/ludwiktrammer/applamp/blob/90d7d463826f0c8dcd33dfdbc5efc9fa44b0b484/applamp/white.py#L60-L66 |
ludwiktrammer/applamp | applamp/white.py | WhiteLight.fade_in | def fade_in(self, duration=3, group=0):
"""Turns on the light by gradually fading it in.
The optional `duration` parameter allows for control
of the fade in duration (in seconds)"""
self.on(group)
super(WhiteLight, self).fade_in(duration, group=group) | python | def fade_in(self, duration=3, group=0):
"""Turns on the light by gradually fading it in.
The optional `duration` parameter allows for control
of the fade in duration (in seconds)"""
self.on(group)
super(WhiteLight, self).fade_in(duration, group=group) | [
"def",
"fade_in",
"(",
"self",
",",
"duration",
"=",
"3",
",",
"group",
"=",
"0",
")",
":",
"self",
".",
"on",
"(",
"group",
")",
"super",
"(",
"WhiteLight",
",",
"self",
")",
".",
"fade_in",
"(",
"duration",
",",
"group",
"=",
"group",
")"
] | Turns on the light by gradually fading it in.
The optional `duration` parameter allows for control
of the fade in duration (in seconds) | [
"Turns",
"on",
"the",
"light",
"by",
"gradually",
"fading",
"it",
"in",
".",
"The",
"optional",
"duration",
"parameter",
"allows",
"for",
"control",
"of",
"the",
"fade",
"in",
"duration",
"(",
"in",
"seconds",
")"
] | train | https://github.com/ludwiktrammer/applamp/blob/90d7d463826f0c8dcd33dfdbc5efc9fa44b0b484/applamp/white.py#L68-L73 |
mgbarrero/xbob.db.atvskeystroke | xbob/db/atvskeystroke/driver.py | dumplist | def dumplist(args):
"""Dumps lists of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects(
protocol=args.protocol,
purposes=args.purpose,
model_ids=(args.client,),
groups=args.group,
classes=args.sclass
)
output = sys.stdout
if args.s... | python | def dumplist(args):
"""Dumps lists of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects(
protocol=args.protocol,
purposes=args.purpose,
model_ids=(args.client,),
groups=args.group,
classes=args.sclass
)
output = sys.stdout
if args.s... | [
"def",
"dumplist",
"(",
"args",
")",
":",
"from",
".",
"query",
"import",
"Database",
"db",
"=",
"Database",
"(",
")",
"r",
"=",
"db",
".",
"objects",
"(",
"protocol",
"=",
"args",
".",
"protocol",
",",
"purposes",
"=",
"args",
".",
"purpose",
",",
... | Dumps lists of files based on your criteria | [
"Dumps",
"lists",
"of",
"files",
"based",
"on",
"your",
"criteria"
] | train | https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L23-L45 |
mgbarrero/xbob.db.atvskeystroke | xbob/db/atvskeystroke/driver.py | checkfiles | def checkfiles(args):
"""Checks existence of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects()
# go through all files, check if they are available on the filesystem
good = []
bad = []
for f in r:
if os.path.exists(f.make_path(args.directory, args.extensi... | python | def checkfiles(args):
"""Checks existence of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects()
# go through all files, check if they are available on the filesystem
good = []
bad = []
for f in r:
if os.path.exists(f.make_path(args.directory, args.extensi... | [
"def",
"checkfiles",
"(",
"args",
")",
":",
"from",
".",
"query",
"import",
"Database",
"db",
"=",
"Database",
"(",
")",
"r",
"=",
"db",
".",
"objects",
"(",
")",
"# go through all files, check if they are available on the filesystem",
"good",
"=",
"[",
"]",
"... | Checks existence of files based on your criteria | [
"Checks",
"existence",
"of",
"files",
"based",
"on",
"your",
"criteria"
] | train | https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L47-L76 |
mgbarrero/xbob.db.atvskeystroke | xbob/db/atvskeystroke/driver.py | reverse | def reverse(args):
"""Returns a list of file database identifiers given the path stems"""
from .query import Database
db = Database()
output = sys.stdout
if args.selftest:
from bob.db.utils import null
output = null()
r = db.reverse(args.path)
for f in r: output.write('%d\n' % f.id)
if not r... | python | def reverse(args):
"""Returns a list of file database identifiers given the path stems"""
from .query import Database
db = Database()
output = sys.stdout
if args.selftest:
from bob.db.utils import null
output = null()
r = db.reverse(args.path)
for f in r: output.write('%d\n' % f.id)
if not r... | [
"def",
"reverse",
"(",
"args",
")",
":",
"from",
".",
"query",
"import",
"Database",
"db",
"=",
"Database",
"(",
")",
"output",
"=",
"sys",
".",
"stdout",
"if",
"args",
".",
"selftest",
":",
"from",
"bob",
".",
"db",
".",
"utils",
"import",
"null",
... | Returns a list of file database identifiers given the path stems | [
"Returns",
"a",
"list",
"of",
"file",
"database",
"identifiers",
"given",
"the",
"path",
"stems"
] | train | https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L78-L94 |
mgbarrero/xbob.db.atvskeystroke | xbob/db/atvskeystroke/driver.py | path | def path(args):
"""Returns a list of fully formed paths or stems given some file id"""
from .query import Database
db = Database()
output = sys.stdout
if args.selftest:
from bob.db.utils import null
output = null()
r = db.paths(args.id, prefix=args.directory, suffix=args.extension)
for path in ... | python | def path(args):
"""Returns a list of fully formed paths or stems given some file id"""
from .query import Database
db = Database()
output = sys.stdout
if args.selftest:
from bob.db.utils import null
output = null()
r = db.paths(args.id, prefix=args.directory, suffix=args.extension)
for path in ... | [
"def",
"path",
"(",
"args",
")",
":",
"from",
".",
"query",
"import",
"Database",
"db",
"=",
"Database",
"(",
")",
"output",
"=",
"sys",
".",
"stdout",
"if",
"args",
".",
"selftest",
":",
"from",
"bob",
".",
"db",
".",
"utils",
"import",
"null",
"o... | Returns a list of fully formed paths or stems given some file id | [
"Returns",
"a",
"list",
"of",
"fully",
"formed",
"paths",
"or",
"stems",
"given",
"some",
"file",
"id"
] | train | https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/driver.py#L96-L112 |
timeyyy/apptools | peasoup/restart.py | Restarter.app_restart | def app_restart(cls):
'''
Restart a frozen esky app
Can also restart if the program is being run as a script
passes restarted as an argument to the restarted app
'''
logging.debug('In restarter')
executable = sys.executable.split(os.sep)[-1]
if os.name == ... | python | def app_restart(cls):
'''
Restart a frozen esky app
Can also restart if the program is being run as a script
passes restarted as an argument to the restarted app
'''
logging.debug('In restarter')
executable = sys.executable.split(os.sep)[-1]
if os.name == ... | [
"def",
"app_restart",
"(",
"cls",
")",
":",
"logging",
".",
"debug",
"(",
"'In restarter'",
")",
"executable",
"=",
"sys",
".",
"executable",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"-",
"1",
"]",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
... | Restart a frozen esky app
Can also restart if the program is being run as a script
passes restarted as an argument to the restarted app | [
"Restart",
"a",
"frozen",
"esky",
"app",
"Can",
"also",
"restart",
"if",
"the",
"program",
"is",
"being",
"run",
"as",
"a",
"script",
"passes",
"restarted",
"as",
"an",
"argument",
"to",
"the",
"restarted",
"app"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/restart.py#L20-L37 |
bioasp/ingranalyze | src/query.py | get_consistent_labelings | def get_consistent_labelings(instance,nmodels=0,exclude=[]):
'''
[consistent_labelings(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing consistent extensions of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
... | python | def get_consistent_labelings(instance,nmodels=0,exclude=[]):
'''
[consistent_labelings(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing consistent extensions of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
... | [
"def",
"get_consistent_labelings",
"(",
"instance",
",",
"nmodels",
"=",
"0",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"#inputs = get_reductions(instance)",
"inst",
"=",
"instance",
".",
"to_file",
"(",
")",
"prg",
"=",
"[",
"consistency_prg",
",",
"inst",
"... | [consistent_labelings(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing consistent extensions of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [nmod... | [
"[",
"consistent_labelings",
"(",
"instance",
"nmodels",
"exclude",
")",
"]",
"returns",
"a",
"list",
"containing",
"[",
"nmodels",
"]",
"TermSet",
"objects",
"representing",
"consistent",
"extensions",
"of",
"the",
"system",
"described",
"by",
"the",
"TermSet",
... | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L49-L65 |
bioasp/ingranalyze | src/query.py | get_minimal_inconsistent_cores | def get_minimal_inconsistent_cores(instance,nmodels=0,exclude=[]):
'''
[compute_mic(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing subset minimal inconsistent cores of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet o... | python | def get_minimal_inconsistent_cores(instance,nmodels=0,exclude=[]):
'''
[compute_mic(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing subset minimal inconsistent cores of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet o... | [
"def",
"get_minimal_inconsistent_cores",
"(",
"instance",
",",
"nmodels",
"=",
"0",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"inputs",
"=",
"get_reductions",
"(",
"instance",
")",
"prg",
"=",
"[",
"dyn_mic_prg",
",",
"inputs",
".",
"to_file",
"(",
")",
"... | [compute_mic(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing subset minimal inconsistent cores of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [n... | [
"[",
"compute_mic",
"(",
"instance",
"nmodels",
"exclude",
")",
"]",
"returns",
"a",
"list",
"containing",
"[",
"nmodels",
"]",
"TermSet",
"objects",
"representing",
"subset",
"minimal",
"inconsistent",
"cores",
"of",
"the",
"system",
"described",
"by",
"the",
... | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L68-L84 |
bioasp/ingranalyze | src/query.py | get_predictions_under_minimal_repair | def get_predictions_under_minimal_repair(instance, repair_options, optimum):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
repops = repair... | python | def get_predictions_under_minimal_repair(instance, repair_options, optimum):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
repops = repair... | [
"def",
"get_predictions_under_minimal_repair",
"(",
"instance",
",",
"repair_options",
",",
"optimum",
")",
":",
"inst",
"=",
"instance",
".",
"to_file",
"(",
")",
"repops",
"=",
"repair_options",
".",
"to_file",
"(",
")",
"prg",
"=",
"[",
"inst",
",",
"repo... | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | [
"Computes",
"the",
"set",
"of",
"signs",
"on",
"edges",
"/",
"vertices",
"that",
"can",
"be",
"cautiously",
"derived",
"from",
"[",
"instance",
"]",
"minus",
"those",
"that",
"are",
"a",
"direct",
"consequence",
"of",
"obs_",
"[",
"ev",
"]",
"label",
"pr... | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L178-L192 |
bioasp/ingranalyze | src/query.py | whatsnew | def whatsnew(instance,pred):
'''
[whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of t... | python | def whatsnew(instance,pred):
'''
[whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of t... | [
"def",
"whatsnew",
"(",
"instance",
",",
"pred",
")",
":",
"accu",
"=",
"TermSet",
"(",
"pred",
")",
"for",
"t",
"in",
"instance",
":",
"if",
"t",
".",
"pred",
"(",
")",
"==",
"'obs_vlabel'",
":",
"[",
"_",
",",
"e",
",",
"v",
",",
"s",
"]",
... | [whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of the observations. | [
"[",
"whatsnew",
"(",
"instance",
"pred",
")",
"]",
"is",
"a",
"TermSet",
"equal",
"to",
"[",
"pred",
"]",
"where",
"all",
"predicates",
"vlabel",
"and",
"elabel",
"which",
"have",
"a",
"corresponding",
"obs_vlabel",
"and",
"obs_elabel",
"in",
"[",
"instan... | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L198-L214 |
bioasp/ingranalyze | src/query.py | get_predictions_under_consistency | def get_predictions_under_consistency(instance):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
prg = [ prediction_prg, inst, exclude_sol(... | python | def get_predictions_under_consistency(instance):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
prg = [ prediction_prg, inst, exclude_sol(... | [
"def",
"get_predictions_under_consistency",
"(",
"instance",
")",
":",
"inst",
"=",
"instance",
".",
"to_file",
"(",
")",
"prg",
"=",
"[",
"prediction_prg",
",",
"inst",
",",
"exclude_sol",
"(",
"[",
"]",
")",
"]",
"solver",
"=",
"GringoClasp",
"(",
"clasp... | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | [
"Computes",
"the",
"set",
"of",
"signs",
"on",
"edges",
"/",
"vertices",
"that",
"can",
"be",
"cautiously",
"derived",
"from",
"[",
"instance",
"]",
"minus",
"those",
"that",
"are",
"a",
"direct",
"consequence",
"of",
"obs_",
"[",
"ev",
"]",
"label",
"pr... | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/query.py#L217-L229 |
unitedstack/steth | stetho/agent/drivers/iperf.py | IPerfDriver.start_server | def start_server(self, protocol='TCP', port=5001, mss=None, window=None):
"""iperf -s -D --mss mss
"""
cmd = ['iperf', '-s', '-p', str(port)]
if not cmp(protocol, 'UDP'):
cmd.append('-u')
if mss:
cmd.extend(['-M', str(mss)])
if window:
... | python | def start_server(self, protocol='TCP', port=5001, mss=None, window=None):
"""iperf -s -D --mss mss
"""
cmd = ['iperf', '-s', '-p', str(port)]
if not cmp(protocol, 'UDP'):
cmd.append('-u')
if mss:
cmd.extend(['-M', str(mss)])
if window:
... | [
"def",
"start_server",
"(",
"self",
",",
"protocol",
"=",
"'TCP'",
",",
"port",
"=",
"5001",
",",
"mss",
"=",
"None",
",",
"window",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'iperf'",
",",
"'-s'",
",",
"'-p'",
",",
"str",
"(",
"port",
")",
"]",
... | iperf -s -D --mss mss | [
"iperf",
"-",
"s",
"-",
"D",
"--",
"mss",
"mss"
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/drivers/iperf.py#L27-L40 |
unitedstack/steth | stetho/agent/drivers/iperf.py | IPerfDriver.start_client | def start_client(self, host, port=5001, protocol='TCP', timeout=5,
parallel=None, bandwidth=None):
"""iperf -D -c host -t 60
"""
cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)]
if not (protocol, 'UDP'):
cmd.append('-u')
if parall... | python | def start_client(self, host, port=5001, protocol='TCP', timeout=5,
parallel=None, bandwidth=None):
"""iperf -D -c host -t 60
"""
cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)]
if not (protocol, 'UDP'):
cmd.append('-u')
if parall... | [
"def",
"start_client",
"(",
"self",
",",
"host",
",",
"port",
"=",
"5001",
",",
"protocol",
"=",
"'TCP'",
",",
"timeout",
"=",
"5",
",",
"parallel",
"=",
"None",
",",
"bandwidth",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'iperf'",
",",
"'-c'",
",",... | iperf -D -c host -t 60 | [
"iperf",
"-",
"D",
"-",
"c",
"host",
"-",
"t",
"60"
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/drivers/iperf.py#L45-L67 |
codenerix/django-codenerix-extensions | codenerix_extensions/helpers.py | get_external_model | def get_external_model(class_object):
"""
Given a class (class_object), it locates the related model (throught the codenerix abstract class)
"""
class_abstract = class_object.CodenerixMeta.abstract
if class_abstract is not None:
for class_related in class_object._meta.related_objects:
... | python | def get_external_model(class_object):
"""
Given a class (class_object), it locates the related model (throught the codenerix abstract class)
"""
class_abstract = class_object.CodenerixMeta.abstract
if class_abstract is not None:
for class_related in class_object._meta.related_objects:
... | [
"def",
"get_external_model",
"(",
"class_object",
")",
":",
"class_abstract",
"=",
"class_object",
".",
"CodenerixMeta",
".",
"abstract",
"if",
"class_abstract",
"is",
"not",
"None",
":",
"for",
"class_related",
"in",
"class_object",
".",
"_meta",
".",
"related_ob... | Given a class (class_object), it locates the related model (throught the codenerix abstract class) | [
"Given",
"a",
"class",
"(",
"class_object",
")",
"it",
"locates",
"the",
"related",
"model",
"(",
"throught",
"the",
"codenerix",
"abstract",
"class",
")"
] | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/helpers.py#L29-L38 |
codenerix/django-codenerix-extensions | codenerix_extensions/helpers.py | get_external_method | def get_external_method(class_object, method_name, *args, **kwargs):
"""
Given a class (class_object), a name for a method (method_name) and its arguments,
it searchs for the method in the related model (throught the codenerix abstract class) and
it executes that method or return None if no method is fo... | python | def get_external_method(class_object, method_name, *args, **kwargs):
"""
Given a class (class_object), a name for a method (method_name) and its arguments,
it searchs for the method in the related model (throught the codenerix abstract class) and
it executes that method or return None if no method is fo... | [
"def",
"get_external_method",
"(",
"class_object",
",",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"related_model",
"=",
"get_external_model",
"(",
"class_object",
")",
"if",
"related_model",
"is",
"not",
"None",
":",
"f",
"=",
"geta... | Given a class (class_object), a name for a method (method_name) and its arguments,
it searchs for the method in the related model (throught the codenerix abstract class) and
it executes that method or return None if no method is found. | [
"Given",
"a",
"class",
"(",
"class_object",
")",
"a",
"name",
"for",
"a",
"method",
"(",
"method_name",
")",
"and",
"its",
"arguments",
"it",
"searchs",
"for",
"the",
"method",
"in",
"the",
"related",
"model",
"(",
"throught",
"the",
"codenerix",
"abstract... | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/helpers.py#L41-L55 |
codenerix/django-codenerix-extensions | codenerix_extensions/helpers.py | get_language_database | def get_language_database():
'''
Return the language to be used to search the database contents
'''
lang = None
language = get_language()
if language:
for x in settings.LANGUAGES_DATABASES:
if x.upper() == language.upper():
lang = language
brea... | python | def get_language_database():
'''
Return the language to be used to search the database contents
'''
lang = None
language = get_language()
if language:
for x in settings.LANGUAGES_DATABASES:
if x.upper() == language.upper():
lang = language
brea... | [
"def",
"get_language_database",
"(",
")",
":",
"lang",
"=",
"None",
"language",
"=",
"get_language",
"(",
")",
"if",
"language",
":",
"for",
"x",
"in",
"settings",
".",
"LANGUAGES_DATABASES",
":",
"if",
"x",
".",
"upper",
"(",
")",
"==",
"language",
".",... | Return the language to be used to search the database contents | [
"Return",
"the",
"language",
"to",
"be",
"used",
"to",
"search",
"the",
"database",
"contents"
] | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/helpers.py#L78-L92 |
shaypal5/pdutil | pdutil/display/display.py | df_string | def df_string(df, percentage_columns=(), format_map=None, **kwargs):
"""Return a nicely formatted string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign... | python | def df_string(df, percentage_columns=(), format_map=None, **kwargs):
"""Return a nicely formatted string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign... | [
"def",
"df_string",
"(",
"df",
",",
"percentage_columns",
"=",
"(",
")",
",",
"format_map",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"formatters_map",
"=",
"{",
"}",
"for",
"col",
",",
"dtype",
"in",
"df",
".",
"dtypes",
".",
"iteritems",
"(",... | Return a nicely formatted string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign.
Returns
-------
str
A nicely formatted string for the... | [
"Return",
"a",
"nicely",
"formatted",
"string",
"for",
"the",
"given",
"dataframe",
"."
] | train | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L9-L42 |
shaypal5/pdutil | pdutil/display/display.py | big_dataframe_setup | def big_dataframe_setup(): # pragma: no cover
"""Sets pandas to display really big data frames."""
pd.set_option('display.max_colwidth', sys.maxsize)
pd.set_option('max_colwidth', sys.maxsize)
# height has been deprecated.
# pd.set_option('display.height', sys.maxsize)
pd.set_option('display.m... | python | def big_dataframe_setup(): # pragma: no cover
"""Sets pandas to display really big data frames."""
pd.set_option('display.max_colwidth', sys.maxsize)
pd.set_option('max_colwidth', sys.maxsize)
# height has been deprecated.
# pd.set_option('display.height', sys.maxsize)
pd.set_option('display.m... | [
"def",
"big_dataframe_setup",
"(",
")",
":",
"# pragma: no cover",
"pd",
".",
"set_option",
"(",
"'display.max_colwidth'",
",",
"sys",
".",
"maxsize",
")",
"pd",
".",
"set_option",
"(",
"'max_colwidth'",
",",
"sys",
".",
"maxsize",
")",
"# height has been deprecat... | Sets pandas to display really big data frames. | [
"Sets",
"pandas",
"to",
"display",
"really",
"big",
"data",
"frames",
"."
] | train | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L45-L56 |
shaypal5/pdutil | pdutil/display/display.py | df_to_html | def df_to_html(df, percentage_columns=None): # pragma: no cover
"""Return a nicely formatted HTML code string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentag... | python | def df_to_html(df, percentage_columns=None): # pragma: no cover
"""Return a nicely formatted HTML code string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentag... | [
"def",
"df_to_html",
"(",
"df",
",",
"percentage_columns",
"=",
"None",
")",
":",
"# pragma: no cover",
"big_dataframe_setup",
"(",
")",
"try",
":",
"res",
"=",
"'<br><h2> {} </h2>'",
".",
"format",
"(",
"df",
".",
"name",
")",
"except",
"AttributeError",
":",... | Return a nicely formatted HTML code string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign.
Returns
-------
str
A nicely formatted stri... | [
"Return",
"a",
"nicely",
"formatted",
"HTML",
"code",
"string",
"for",
"the",
"given",
"dataframe",
"."
] | train | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/display/display.py#L80-L106 |
lapets/parts | parts/parts.py | parts | def parts(xs, number = None, length = None):
"""
Split a list into either the specified number of parts or
a number of parts each of the specified length. The elements
are distributed somewhat evenly among the parts if possible.
>>> list(parts([1,2,3,4,5,6,7], length=1))
[[1], [2], [3], [4], [5... | python | def parts(xs, number = None, length = None):
"""
Split a list into either the specified number of parts or
a number of parts each of the specified length. The elements
are distributed somewhat evenly among the parts if possible.
>>> list(parts([1,2,3,4,5,6,7], length=1))
[[1], [2], [3], [4], [5... | [
"def",
"parts",
"(",
"xs",
",",
"number",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"if",
"number",
"is",
"not",
"None",
"and",
"type",
"(",
"number",
")",
"is",
"not",
"int",
":",
"raise",
"PartsError",
"(",
"\"Number of parts must be an intege... | Split a list into either the specified number of parts or
a number of parts each of the specified length. The elements
are distributed somewhat evenly among the parts if possible.
>>> list(parts([1,2,3,4,5,6,7], length=1))
[[1], [2], [3], [4], [5], [6], [7]]
>>> list(parts([1,2,3,4,5,6,7], length=2... | [
"Split",
"a",
"list",
"into",
"either",
"the",
"specified",
"number",
"of",
"parts",
"or",
"a",
"number",
"of",
"parts",
"each",
"of",
"the",
"specified",
"length",
".",
"The",
"elements",
"are",
"distributed",
"somewhat",
"evenly",
"among",
"the",
"parts",
... | train | https://github.com/lapets/parts/blob/69add81e4ea14f7b85493f86d96663cdac05641e/parts/parts.py#L22-L139 |
veeti/decent | decent/validators.py | All | def All(*validators):
"""
Combines all the given validator callables into one, running all the
validators in sequence on the given value.
"""
@wraps(All)
def built(value):
for validator in validators:
value = validator(value)
return value
return built | python | def All(*validators):
"""
Combines all the given validator callables into one, running all the
validators in sequence on the given value.
"""
@wraps(All)
def built(value):
for validator in validators:
value = validator(value)
return value
return built | [
"def",
"All",
"(",
"*",
"validators",
")",
":",
"@",
"wraps",
"(",
"All",
")",
"def",
"built",
"(",
"value",
")",
":",
"for",
"validator",
"in",
"validators",
":",
"value",
"=",
"validator",
"(",
"value",
")",
"return",
"value",
"return",
"built"
] | Combines all the given validator callables into one, running all the
validators in sequence on the given value. | [
"Combines",
"all",
"the",
"given",
"validator",
"callables",
"into",
"one",
"running",
"all",
"the",
"validators",
"in",
"sequence",
"on",
"the",
"given",
"value",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L11-L21 |
veeti/decent | decent/validators.py | Any | def Any(*validators):
"""
Combines all the given validator callables into one, running the given
value through them in sequence until a valid result is given.
"""
@wraps(Any)
def built(value):
error = None
for validator in validators:
try:
return valid... | python | def Any(*validators):
"""
Combines all the given validator callables into one, running the given
value through them in sequence until a valid result is given.
"""
@wraps(Any)
def built(value):
error = None
for validator in validators:
try:
return valid... | [
"def",
"Any",
"(",
"*",
"validators",
")",
":",
"@",
"wraps",
"(",
"Any",
")",
"def",
"built",
"(",
"value",
")",
":",
"error",
"=",
"None",
"for",
"validator",
"in",
"validators",
":",
"try",
":",
"return",
"validator",
"(",
"value",
")",
"except",
... | Combines all the given validator callables into one, running the given
value through them in sequence until a valid result is given. | [
"Combines",
"all",
"the",
"given",
"validator",
"callables",
"into",
"one",
"running",
"the",
"given",
"value",
"through",
"them",
"in",
"sequence",
"until",
"a",
"valid",
"result",
"is",
"given",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L23-L37 |
veeti/decent | decent/validators.py | Maybe | def Maybe(validator):
"""
Wraps the given validator callable, only using it for the given value if it
is not ``None``.
"""
@wraps(Maybe)
def built(value):
if value != None:
return validator(value)
return built | python | def Maybe(validator):
"""
Wraps the given validator callable, only using it for the given value if it
is not ``None``.
"""
@wraps(Maybe)
def built(value):
if value != None:
return validator(value)
return built | [
"def",
"Maybe",
"(",
"validator",
")",
":",
"@",
"wraps",
"(",
"Maybe",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"value",
"!=",
"None",
":",
"return",
"validator",
"(",
"value",
")",
"return",
"built"
] | Wraps the given validator callable, only using it for the given value if it
is not ``None``. | [
"Wraps",
"the",
"given",
"validator",
"callable",
"only",
"using",
"it",
"for",
"the",
"given",
"value",
"if",
"it",
"is",
"not",
"None",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L39-L48 |
veeti/decent | decent/validators.py | Msg | def Msg(validator, message):
"""
Wraps the given validator callable, replacing any error messages raised.
"""
@wraps(Msg)
def built(value):
try:
return validator(value)
except Error as e:
e.message = message
raise e
return built | python | def Msg(validator, message):
"""
Wraps the given validator callable, replacing any error messages raised.
"""
@wraps(Msg)
def built(value):
try:
return validator(value)
except Error as e:
e.message = message
raise e
return built | [
"def",
"Msg",
"(",
"validator",
",",
"message",
")",
":",
"@",
"wraps",
"(",
"Msg",
")",
"def",
"built",
"(",
"value",
")",
":",
"try",
":",
"return",
"validator",
"(",
"value",
")",
"except",
"Error",
"as",
"e",
":",
"e",
".",
"message",
"=",
"m... | Wraps the given validator callable, replacing any error messages raised. | [
"Wraps",
"the",
"given",
"validator",
"callable",
"replacing",
"any",
"error",
"messages",
"raised",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L50-L61 |
veeti/decent | decent/validators.py | Default | def Default(default):
"""
Creates a validator callable that replaces ``None`` with the specified
default value.
"""
@wraps(Default)
def built(value):
if value == None:
return default
return value
return built | python | def Default(default):
"""
Creates a validator callable that replaces ``None`` with the specified
default value.
"""
@wraps(Default)
def built(value):
if value == None:
return default
return value
return built | [
"def",
"Default",
"(",
"default",
")",
":",
"@",
"wraps",
"(",
"Default",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"value",
"==",
"None",
":",
"return",
"default",
"return",
"value",
"return",
"built"
] | Creates a validator callable that replaces ``None`` with the specified
default value. | [
"Creates",
"a",
"validator",
"callable",
"that",
"replaces",
"None",
"with",
"the",
"specified",
"default",
"value",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L63-L73 |
veeti/decent | decent/validators.py | Eq | def Eq(value, message="Not equal to {!s}"):
"""
Creates a validator that compares the equality of the given value to
``value``.
A custom message can be specified with ``message``. It will be formatted
with ``value``.
"""
@wraps(Eq)
def built(_value):
if _value != value:
... | python | def Eq(value, message="Not equal to {!s}"):
"""
Creates a validator that compares the equality of the given value to
``value``.
A custom message can be specified with ``message``. It will be formatted
with ``value``.
"""
@wraps(Eq)
def built(_value):
if _value != value:
... | [
"def",
"Eq",
"(",
"value",
",",
"message",
"=",
"\"Not equal to {!s}\"",
")",
":",
"@",
"wraps",
"(",
"Eq",
")",
"def",
"built",
"(",
"_value",
")",
":",
"if",
"_value",
"!=",
"value",
":",
"raise",
"Error",
"(",
"message",
".",
"format",
"(",
"value... | Creates a validator that compares the equality of the given value to
``value``.
A custom message can be specified with ``message``. It will be formatted
with ``value``. | [
"Creates",
"a",
"validator",
"that",
"compares",
"the",
"equality",
"of",
"the",
"given",
"value",
"to",
"value",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L77-L90 |
veeti/decent | decent/validators.py | Type | def Type(expected, message="Not of type {}"):
"""
Creates a validator that compares the type of the given value to
``expected``. This is a direct type() equality check. Also see
``Instance``, which is an isinstance() check.
A custom message can be specified with ``message``.
"""
@wraps(Type... | python | def Type(expected, message="Not of type {}"):
"""
Creates a validator that compares the type of the given value to
``expected``. This is a direct type() equality check. Also see
``Instance``, which is an isinstance() check.
A custom message can be specified with ``message``.
"""
@wraps(Type... | [
"def",
"Type",
"(",
"expected",
",",
"message",
"=",
"\"Not of type {}\"",
")",
":",
"@",
"wraps",
"(",
"Type",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"!=",
"expected",
":",
"raise",
"Error",
"(",
"message",
"."... | Creates a validator that compares the type of the given value to
``expected``. This is a direct type() equality check. Also see
``Instance``, which is an isinstance() check.
A custom message can be specified with ``message``. | [
"Creates",
"a",
"validator",
"that",
"compares",
"the",
"type",
"of",
"the",
"given",
"value",
"to",
"expected",
".",
"This",
"is",
"a",
"direct",
"type",
"()",
"equality",
"check",
".",
"Also",
"see",
"Instance",
"which",
"is",
"an",
"isinstance",
"()",
... | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L92-L105 |
veeti/decent | decent/validators.py | Instance | def Instance(expected, message="Not an instance of {}"):
"""
Creates a validator that checks if the given value is an instance of
``expected``.
A custom message can be specified with ``message``.
"""
@wraps(Instance)
def built(value):
if not isinstance(value, expected):
... | python | def Instance(expected, message="Not an instance of {}"):
"""
Creates a validator that checks if the given value is an instance of
``expected``.
A custom message can be specified with ``message``.
"""
@wraps(Instance)
def built(value):
if not isinstance(value, expected):
... | [
"def",
"Instance",
"(",
"expected",
",",
"message",
"=",
"\"Not an instance of {}\"",
")",
":",
"@",
"wraps",
"(",
"Instance",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"expected",
")",
":",
"raise",
"Erro... | Creates a validator that checks if the given value is an instance of
``expected``.
A custom message can be specified with ``message``. | [
"Creates",
"a",
"validator",
"that",
"checks",
"if",
"the",
"given",
"value",
"is",
"an",
"instance",
"of",
"expected",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L107-L119 |
veeti/decent | decent/validators.py | Coerce | def Coerce(type, message="Not a valid {} value"):
"""
Creates a validator that attempts to coerce the given value to the
specified ``type``. Will raise an error if the coercion fails.
A custom message can be specified with ``message``.
"""
@wraps(Coerce)
def built(value):
try:
... | python | def Coerce(type, message="Not a valid {} value"):
"""
Creates a validator that attempts to coerce the given value to the
specified ``type``. Will raise an error if the coercion fails.
A custom message can be specified with ``message``.
"""
@wraps(Coerce)
def built(value):
try:
... | [
"def",
"Coerce",
"(",
"type",
",",
"message",
"=",
"\"Not a valid {} value\"",
")",
":",
"@",
"wraps",
"(",
"Coerce",
")",
"def",
"built",
"(",
"value",
")",
":",
"try",
":",
"return",
"type",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueE... | Creates a validator that attempts to coerce the given value to the
specified ``type``. Will raise an error if the coercion fails.
A custom message can be specified with ``message``. | [
"Creates",
"a",
"validator",
"that",
"attempts",
"to",
"coerce",
"the",
"given",
"value",
"to",
"the",
"specified",
"type",
".",
"Will",
"raise",
"an",
"error",
"if",
"the",
"coercion",
"fails",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L121-L134 |
veeti/decent | decent/validators.py | List | def List(validator):
"""
Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an er... | python | def List(validator):
"""
Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an er... | [
"def",
"List",
"(",
"validator",
")",
":",
"@",
"wraps",
"(",
"List",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"raise",
"Error",
"(",
"\"Must be a list\"",
")",
"invalid",
"=",
"I... | Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an error if
the input value is not... | [
"Creates",
"a",
"validator",
"that",
"runs",
"the",
"given",
"validator",
"on",
"every",
"item",
"in",
"a",
"list",
"or",
"other",
"collection",
".",
"The",
"validator",
"can",
"mutate",
"the",
"values",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L138-L167 |
veeti/decent | decent/validators.py | Boolean | def Boolean():
"""
Creates a validator that attempts to convert the given value to a boolean
or raises an error. The following rules are used:
``None`` is converted to ``False``.
``int`` values are ``True`` except for ``0``.
``str`` values converted in lower- and uppercase:
* ``y, yes, t... | python | def Boolean():
"""
Creates a validator that attempts to convert the given value to a boolean
or raises an error. The following rules are used:
``None`` is converted to ``False``.
``int`` values are ``True`` except for ``0``.
``str`` values converted in lower- and uppercase:
* ``y, yes, t... | [
"def",
"Boolean",
"(",
")",
":",
"@",
"wraps",
"(",
"Boolean",
")",
"def",
"built",
"(",
"value",
")",
":",
"# Already a boolean?",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"# None",
"if",
"value",
"==",
"None",
":",
... | Creates a validator that attempts to convert the given value to a boolean
or raises an error. The following rules are used:
``None`` is converted to ``False``.
``int`` values are ``True`` except for ``0``.
``str`` values converted in lower- and uppercase:
* ``y, yes, t, true``
* ``n, no, f, ... | [
"Creates",
"a",
"validator",
"that",
"attempts",
"to",
"convert",
"the",
"given",
"value",
"to",
"a",
"boolean",
"or",
"raises",
"an",
"error",
".",
"The",
"following",
"rules",
"are",
"used",
":"
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L171-L208 |
veeti/decent | decent/validators.py | Range | def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"):
"""
Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages... | python | def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"):
"""
Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages... | [
"def",
"Range",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"min_message",
"=",
"\"Must be at least {min}\"",
",",
"max_message",
"=",
"\"Must be at most {max}\"",
")",
":",
"@",
"wraps",
"(",
"Range",
")",
"def",
"built",
"(",
"value",
")",
":"... | Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages raised can be customized with ``min_message`` and
``max_message``. The ``min`` and ``max`` arguments are formatte... | [
"Creates",
"a",
"validator",
"that",
"checks",
"if",
"the",
"given",
"numeric",
"value",
"is",
"in",
"the",
"specified",
"range",
"inclusive",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L212-L231 |
veeti/decent | decent/validators.py | Length | def Length(min=None, max=None, min_message="Must have a length of at least {min}", max_message="Must have a length of at most {max}"):
"""
Creates a validator that checks if the given value's length is in the
specified range, inclusive. (Returns the original value.)
See :func:`.Range`.
"""
vali... | python | def Length(min=None, max=None, min_message="Must have a length of at least {min}", max_message="Must have a length of at most {max}"):
"""
Creates a validator that checks if the given value's length is in the
specified range, inclusive. (Returns the original value.)
See :func:`.Range`.
"""
vali... | [
"def",
"Length",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"min_message",
"=",
"\"Must have a length of at least {min}\"",
",",
"max_message",
"=",
"\"Must have a length of at most {max}\"",
")",
":",
"validator",
"=",
"Range",
"(",
"min",
",",
"max",... | Creates a validator that checks if the given value's length is in the
specified range, inclusive. (Returns the original value.)
See :func:`.Range`. | [
"Creates",
"a",
"validator",
"that",
"checks",
"if",
"the",
"given",
"value",
"s",
"length",
"is",
"in",
"the",
"specified",
"range",
"inclusive",
".",
"(",
"Returns",
"the",
"original",
"value",
".",
")"
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L233-L247 |
veeti/decent | decent/validators.py | NotEmpty | def NotEmpty():
"""
Creates a validator that validates the given string is not empty. Will
raise an error for non-string types.
"""
@wraps(NotEmpty)
def built(value):
if not isinstance(value, six.string_types) or not value:
raise Error("Must not be empty")
return valu... | python | def NotEmpty():
"""
Creates a validator that validates the given string is not empty. Will
raise an error for non-string types.
"""
@wraps(NotEmpty)
def built(value):
if not isinstance(value, six.string_types) or not value:
raise Error("Must not be empty")
return valu... | [
"def",
"NotEmpty",
"(",
")",
":",
"@",
"wraps",
"(",
"NotEmpty",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"value",
":",
"raise",
"Error",
"(",
"\"Must not... | Creates a validator that validates the given string is not empty. Will
raise an error for non-string types. | [
"Creates",
"a",
"validator",
"that",
"validates",
"the",
"given",
"string",
"is",
"not",
"empty",
".",
"Will",
"raise",
"an",
"error",
"for",
"non",
"-",
"string",
"types",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L286-L296 |
veeti/decent | decent/validators.py | Uuid | def Uuid(to_uuid=True):
"""
Creates a UUID validator. Will raise an error for non-string types and
non-UUID values.
The given value will be converted to an instance of ``uuid.UUID`` unless
``to_uuid`` is ``False``.
"""
@wraps(Uuid)
def built(value):
invalid = Error("Not a valid ... | python | def Uuid(to_uuid=True):
"""
Creates a UUID validator. Will raise an error for non-string types and
non-UUID values.
The given value will be converted to an instance of ``uuid.UUID`` unless
``to_uuid`` is ``False``.
"""
@wraps(Uuid)
def built(value):
invalid = Error("Not a valid ... | [
"def",
"Uuid",
"(",
"to_uuid",
"=",
"True",
")",
":",
"@",
"wraps",
"(",
"Uuid",
")",
"def",
"built",
"(",
"value",
")",
":",
"invalid",
"=",
"Error",
"(",
"\"Not a valid UUID\"",
")",
"if",
"isinstance",
"(",
"value",
",",
"uuid",
".",
"UUID",
")",
... | Creates a UUID validator. Will raise an error for non-string types and
non-UUID values.
The given value will be converted to an instance of ``uuid.UUID`` unless
``to_uuid`` is ``False``. | [
"Creates",
"a",
"UUID",
"validator",
".",
"Will",
"raise",
"an",
"error",
"for",
"non",
"-",
"string",
"types",
"and",
"non",
"-",
"UUID",
"values",
"."
] | train | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L300-L325 |
lionel/counterparts | counterparts.py | counterpart_found | def counterpart_found(string, counterpart, options, rc_so_far):
"""The sunny-day action is to echo the counterpart to stdout.
:param string: The lookup string (UNUSED)
:param counterpart: The counterpart that the string mapped to
:param options: ArgumentParser or equivalent to provide options.no_newli... | python | def counterpart_found(string, counterpart, options, rc_so_far):
"""The sunny-day action is to echo the counterpart to stdout.
:param string: The lookup string (UNUSED)
:param counterpart: The counterpart that the string mapped to
:param options: ArgumentParser or equivalent to provide options.no_newli... | [
"def",
"counterpart_found",
"(",
"string",
",",
"counterpart",
",",
"options",
",",
"rc_so_far",
")",
":",
"format",
"=",
"\"%s\"",
"if",
"options",
".",
"no_newline",
"else",
"\"%s\\n\"",
"sys",
".",
"stdout",
".",
"write",
"(",
"format",
"%",
"(",
"count... | The sunny-day action is to echo the counterpart to stdout.
:param string: The lookup string (UNUSED)
:param counterpart: The counterpart that the string mapped to
:param options: ArgumentParser or equivalent to provide options.no_newline
:param rc_so_far: Stays whatever value it was. | [
"The",
"sunny",
"-",
"day",
"action",
"is",
"to",
"echo",
"the",
"counterpart",
"to",
"stdout",
"."
] | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L186-L196 |
lionel/counterparts | counterparts.py | no_counterpart_found | def no_counterpart_found(string, options, rc_so_far):
"""Takes action determined by options.else_action. Unless told to
raise an exception, this function returns the errno that is supposed
to be returned in this case.
:param string: The lookup string.
:param options: ArgumentParser or equivalent t... | python | def no_counterpart_found(string, options, rc_so_far):
"""Takes action determined by options.else_action. Unless told to
raise an exception, this function returns the errno that is supposed
to be returned in this case.
:param string: The lookup string.
:param options: ArgumentParser or equivalent t... | [
"def",
"no_counterpart_found",
"(",
"string",
",",
"options",
",",
"rc_so_far",
")",
":",
"logger",
".",
"debug",
"(",
"\"options.else_action: %s\"",
",",
"options",
".",
"else_action",
")",
"if",
"options",
".",
"else_action",
"==",
"\"passthrough\"",
":",
"for... | Takes action determined by options.else_action. Unless told to
raise an exception, this function returns the errno that is supposed
to be returned in this case.
:param string: The lookup string.
:param options: ArgumentParser or equivalent to provide
options.else_action, options.else_errno, op... | [
"Takes",
"action",
"determined",
"by",
"options",
".",
"else_action",
".",
"Unless",
"told",
"to",
"raise",
"an",
"exception",
"this",
"function",
"returns",
"the",
"errno",
"that",
"is",
"supposed",
"to",
"be",
"returned",
"in",
"this",
"case",
"."
] | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L199-L222 |
lionel/counterparts | counterparts.py | get_counterpart_mapping | def get_counterpart_mapping(config_file=None, skip_home=False):
"""Initial part of a two-step lookup: First load the mapping
(CounterpartMapping) with this function. The mapping can then be
subscripted to look up specific counterparts' mappings. This way
is more efficient than calling map_counterpart ... | python | def get_counterpart_mapping(config_file=None, skip_home=False):
"""Initial part of a two-step lookup: First load the mapping
(CounterpartMapping) with this function. The mapping can then be
subscripted to look up specific counterparts' mappings. This way
is more efficient than calling map_counterpart ... | [
"def",
"get_counterpart_mapping",
"(",
"config_file",
"=",
"None",
",",
"skip_home",
"=",
"False",
")",
":",
"file_skip_list",
"=",
"(",
"[",
"ConfigFromFile",
".",
"home_rc_file_path",
"]",
"if",
"skip_home",
"else",
"[",
"]",
")",
"config",
"=",
"ConfigFromF... | Initial part of a two-step lookup: First load the mapping
(CounterpartMapping) with this function. The mapping can then be
subscripted to look up specific counterparts' mappings. This way
is more efficient than calling map_counterpart several times,
because it reads the config file(s) only once.
... | [
"Initial",
"part",
"of",
"a",
"two",
"-",
"step",
"lookup",
":",
"First",
"load",
"the",
"mapping",
"(",
"CounterpartMapping",
")",
"with",
"this",
"function",
".",
"The",
"mapping",
"can",
"then",
"be",
"subscripted",
"to",
"look",
"up",
"specific",
"coun... | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L225-L241 |
lionel/counterparts | counterparts.py | map_counterpart | def map_counterpart(string, config_file=None):
"""One-step look-up; returns a counterpart for the given string, as
determined from the config file(s) via ConfigFromFile.
config_file is read after ~/.counterc, if present, making its
values take precedence over those in ~/.counterc.
:param string: Th... | python | def map_counterpart(string, config_file=None):
"""One-step look-up; returns a counterpart for the given string, as
determined from the config file(s) via ConfigFromFile.
config_file is read after ~/.counterc, if present, making its
values take precedence over those in ~/.counterc.
:param string: Th... | [
"def",
"map_counterpart",
"(",
"string",
",",
"config_file",
"=",
"None",
")",
":",
"skip_home_flag",
"=",
"config_file",
"is",
"not",
"None",
"mapping",
"=",
"get_counterpart_mapping",
"(",
"config_file",
",",
"skip_home_flag",
")",
"return",
"mapping",
"[",
"s... | One-step look-up; returns a counterpart for the given string, as
determined from the config file(s) via ConfigFromFile.
config_file is read after ~/.counterc, if present, making its
values take precedence over those in ~/.counterc.
:param string: The string to find the counterpart of.
:param config... | [
"One",
"-",
"step",
"look",
"-",
"up",
";",
"returns",
"a",
"counterpart",
"for",
"the",
"given",
"string",
"as",
"determined",
"from",
"the",
"config",
"file",
"(",
"s",
")",
"via",
"ConfigFromFile",
".",
"config_file",
"is",
"read",
"after",
"~",
"/",
... | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L244-L258 |
lionel/counterparts | counterparts.py | _generate_input | def _generate_input(options):
"""First send strings from any given file, one string per line, sends
any strings provided on the command line.
:param options: ArgumentParser or equivalent to provide
options.input and options.strings.
:return: string
"""
if options.input:
fp = op... | python | def _generate_input(options):
"""First send strings from any given file, one string per line, sends
any strings provided on the command line.
:param options: ArgumentParser or equivalent to provide
options.input and options.strings.
:return: string
"""
if options.input:
fp = op... | [
"def",
"_generate_input",
"(",
"options",
")",
":",
"if",
"options",
".",
"input",
":",
"fp",
"=",
"open",
"(",
"options",
".",
"input",
")",
"if",
"options",
".",
"input",
"!=",
"\"-\"",
"else",
"sys",
".",
"stdin",
"for",
"string",
"in",
"fp",
".",... | First send strings from any given file, one string per line, sends
any strings provided on the command line.
:param options: ArgumentParser or equivalent to provide
options.input and options.strings.
:return: string | [
"First",
"send",
"strings",
"from",
"any",
"given",
"file",
"one",
"string",
"per",
"line",
"sends",
"any",
"strings",
"provided",
"on",
"the",
"command",
"line",
"."
] | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L261-L276 |
lionel/counterparts | counterparts.py | ConfigFromFile.register_options | def register_options(this_class, argparser):
"""This class method is called so that ConfigFromFile can tell the
command-line parser to register the options specific to the class.
:param this_class: Not used (required by @classmethod interface)
:param argparser: The argparser instance be... | python | def register_options(this_class, argparser):
"""This class method is called so that ConfigFromFile can tell the
command-line parser to register the options specific to the class.
:param this_class: Not used (required by @classmethod interface)
:param argparser: The argparser instance be... | [
"def",
"register_options",
"(",
"this_class",
",",
"argparser",
")",
":",
"default_path",
"=",
"this_class",
".",
"rc_file_basename",
"default_basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"default_path",
")",
"argparser",
".",
"add_argument",
"(",
"'... | This class method is called so that ConfigFromFile can tell the
command-line parser to register the options specific to the class.
:param this_class: Not used (required by @classmethod interface)
:param argparser: The argparser instance being prepared for use. | [
"This",
"class",
"method",
"is",
"called",
"so",
"that",
"ConfigFromFile",
"can",
"tell",
"the",
"command",
"-",
"line",
"parser",
"to",
"register",
"the",
"options",
"specific",
"to",
"the",
"class",
"."
] | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L127-L141 |
lionel/counterparts | counterparts.py | ConfigFromFile._check_and_handle_includes | def _check_and_handle_includes(self, from_file):
"""Look for an optional INCLUDE section in the given file path. If
the parser set `paths`, it is cleared so that they do not keep
showing up when additional files are parsed.
"""
logger.debug("Check/handle includes from %s", from... | python | def _check_and_handle_includes(self, from_file):
"""Look for an optional INCLUDE section in the given file path. If
the parser set `paths`, it is cleared so that they do not keep
showing up when additional files are parsed.
"""
logger.debug("Check/handle includes from %s", from... | [
"def",
"_check_and_handle_includes",
"(",
"self",
",",
"from_file",
")",
":",
"logger",
".",
"debug",
"(",
"\"Check/handle includes from %s\"",
",",
"from_file",
")",
"try",
":",
"paths",
"=",
"self",
".",
"_parser",
".",
"get",
"(",
"\"INCLUDE\"",
",",
"\"pat... | Look for an optional INCLUDE section in the given file path. If
the parser set `paths`, it is cleared so that they do not keep
showing up when additional files are parsed. | [
"Look",
"for",
"an",
"optional",
"INCLUDE",
"section",
"in",
"the",
"given",
"file",
"path",
".",
"If",
"the",
"parser",
"set",
"paths",
"it",
"is",
"cleared",
"so",
"that",
"they",
"do",
"not",
"keep",
"showing",
"up",
"when",
"additional",
"files",
"ar... | train | https://github.com/lionel/counterparts/blob/20db9852feff531f854972f76b412c442b2fafbf/counterparts.py#L143-L168 |
jalanb/pysyte | pysyte/imports.py | extract_imports | def extract_imports(script):
"""Extract all imports from a python script"""
if not os.path.isfile(script):
raise ValueError('Not a file: %s' % script)
parse_tree = parse_python(script)
result = find_imports(parse_tree)
result.path = script
return result | python | def extract_imports(script):
"""Extract all imports from a python script"""
if not os.path.isfile(script):
raise ValueError('Not a file: %s' % script)
parse_tree = parse_python(script)
result = find_imports(parse_tree)
result.path = script
return result | [
"def",
"extract_imports",
"(",
"script",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"script",
")",
":",
"raise",
"ValueError",
"(",
"'Not a file: %s'",
"%",
"script",
")",
"parse_tree",
"=",
"parse_python",
"(",
"script",
")",
"result",
... | Extract all imports from a python script | [
"Extract",
"all",
"imports",
"from",
"a",
"python",
"script"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/imports.py#L135-L142 |
cdeboever3/cdpybio | cdpybio/featureCounts.py | combine_counts | def combine_counts(
fns,
define_sample_name=None,
):
"""
Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featur... | python | def combine_counts(
fns,
define_sample_name=None,
):
"""
Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featur... | [
"def",
"combine_counts",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
",",
")",
":",
"counts",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"skiprows",
"=",
"1",
",",
"index_col",
"=",
"0"... | Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featureCounts output filenames to sample names.
If this is not provided... | [
"Combine",
"featureCounts",
"output",
"files",
"for",
"multiple",
"samples",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/featureCounts.py#L3-L35 |
fr33jc/bang | bang/providers/hpcloud/v12/__init__.py | fix_hp_addrs | def fix_hp_addrs(server):
"""
Works around hpcloud's peculiar "all ip addresses are returned as private
even though one is public" bug. This is also what the official hpfog gem
does in the ``Fog::Compute::HP::Server#public_ip_address`` method.
:param dict server: Contains the server ID, a list of... | python | def fix_hp_addrs(server):
"""
Works around hpcloud's peculiar "all ip addresses are returned as private
even though one is public" bug. This is also what the official hpfog gem
does in the ``Fog::Compute::HP::Server#public_ip_address`` method.
:param dict server: Contains the server ID, a list of... | [
"def",
"fix_hp_addrs",
"(",
"server",
")",
":",
"fixed",
"=",
"{",
"A",
".",
"server",
".",
"ID",
":",
"server",
"[",
"A",
".",
"server",
".",
"ID",
"]",
"}",
"both",
"=",
"server",
".",
"get",
"(",
"A",
".",
"server",
".",
"PRIVATE_IPS",
")",
... | Works around hpcloud's peculiar "all ip addresses are returned as private
even though one is public" bug. This is also what the official hpfog gem
does in the ``Fog::Compute::HP::Server#public_ip_address`` method.
:param dict server: Contains the server ID, a list of public IP addresses,
and a li... | [
"Works",
"around",
"hpcloud",
"s",
"peculiar",
"all",
"ip",
"addresses",
"are",
"returned",
"as",
"private",
"even",
"though",
"one",
"is",
"public",
"bug",
".",
"This",
"is",
"also",
"what",
"the",
"official",
"hpfog",
"gem",
"does",
"in",
"the",
"Fog",
... | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/v12/__init__.py#L22-L37 |
fr33jc/bang | bang/providers/hpcloud/v12/__init__.py | HPNova.find_servers | def find_servers(self, *args, **kwargs):
"""
Wraps :meth:`bang.providers.openstack.Nova.find_servers` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values.
"""
servers = super(HPNova, self).find_servers(*args, **kwarg... | python | def find_servers(self, *args, **kwargs):
"""
Wraps :meth:`bang.providers.openstack.Nova.find_servers` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values.
"""
servers = super(HPNova, self).find_servers(*args, **kwarg... | [
"def",
"find_servers",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"servers",
"=",
"super",
"(",
"HPNova",
",",
"self",
")",
".",
"find_servers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"map",
"(",
"fix_hp_ad... | Wraps :meth:`bang.providers.openstack.Nova.find_servers` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values. | [
"Wraps",
":",
"meth",
":",
"bang",
".",
"providers",
".",
"openstack",
".",
"Nova",
".",
"find_servers",
"to",
"apply",
"hpcloud",
"specialization",
"namely",
"pulling",
"IP",
"addresses",
"from",
"the",
"hpcloud",
"s",
"non",
"-",
"standard",
"return",
"val... | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/v12/__init__.py#L40-L48 |
fr33jc/bang | bang/providers/hpcloud/v12/__init__.py | HPNova.create_server | def create_server(self, *args, **kwargs):
"""
Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values.
"""
# hpcloud's management console stuffs all of its tags i... | python | def create_server(self, *args, **kwargs):
"""
Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values.
"""
# hpcloud's management console stuffs all of its tags i... | [
"def",
"create_server",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# hpcloud's management console stuffs all of its tags in a \"tags\" tag.",
"# populate it with the stack and role values here only at server",
"# creation time. what users do with it after serve... | Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values. | [
"Wraps",
":",
"meth",
":",
"bang",
".",
"providers",
".",
"openstack",
".",
"Nova",
".",
"create_server",
"to",
"apply",
"hpcloud",
"specialization",
"namely",
"pulling",
"IP",
"addresses",
"from",
"the",
"hpcloud",
"s",
"non",
"-",
"standard",
"return",
"va... | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/v12/__init__.py#L50-L71 |
fr33jc/bang | bang/deployers/default.py | ServerDeployer.add_to_inventory | def add_to_inventory(self):
"""Adds this server and its hostvars to the ansible inventory."""
self.stack.add_host(self.hostname, self.groups, self.hostvars) | python | def add_to_inventory(self):
"""Adds this server and its hostvars to the ansible inventory."""
self.stack.add_host(self.hostname, self.groups, self.hostvars) | [
"def",
"add_to_inventory",
"(",
"self",
")",
":",
"self",
".",
"stack",
".",
"add_host",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"groups",
",",
"self",
".",
"hostvars",
")"
] | Adds this server and its hostvars to the ansible inventory. | [
"Adds",
"this",
"server",
"and",
"its",
"hostvars",
"to",
"the",
"ansible",
"inventory",
"."
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/default.py#L45-L47 |
PRIArobotics/HedgehogUtils | hedgehog/utils/__init__.py | expect_all | def expect_all(a, b):
"""\
Asserts that two iterables contain the same values.
"""
assert all(_a == _b for _a, _b in zip_longest(a, b)) | python | def expect_all(a, b):
"""\
Asserts that two iterables contain the same values.
"""
assert all(_a == _b for _a, _b in zip_longest(a, b)) | [
"def",
"expect_all",
"(",
"a",
",",
"b",
")",
":",
"assert",
"all",
"(",
"_a",
"==",
"_b",
"for",
"_a",
",",
"_b",
"in",
"zip_longest",
"(",
"a",
",",
"b",
")",
")"
] | \
Asserts that two iterables contain the same values. | [
"\\",
"Asserts",
"that",
"two",
"iterables",
"contain",
"the",
"same",
"values",
"."
] | train | https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/__init__.py#L14-L18 |
PRIArobotics/HedgehogUtils | hedgehog/utils/__init__.py | coroutine | def coroutine(func):
"""
A decorator to wrap a generator function into a callable interface.
>>> @coroutine
... def sum(count):
... sum = 0
... for _ in range(0, count):
... # note that generator arguments are passed as a tuple, hence `num, = ...` instead... | python | def coroutine(func):
"""
A decorator to wrap a generator function into a callable interface.
>>> @coroutine
... def sum(count):
... sum = 0
... for _ in range(0, count):
... # note that generator arguments are passed as a tuple, hence `num, = ...` instead... | [
"def",
"coroutine",
"(",
"func",
")",
":",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"next",
"(",
"generator",
")",
"return",
"lambda",
"*",
... | A decorator to wrap a generator function into a callable interface.
>>> @coroutine
... def sum(count):
... sum = 0
... for _ in range(0, count):
... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...`
... ... | [
"A",
"decorator",
"to",
"wrap",
"a",
"generator",
"function",
"into",
"a",
"callable",
"interface",
"."
] | train | https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/__init__.py#L21-L103 |
timothyhahn/rui | rui/rui.py | World.add_entity | def add_entity(self, entity, second=False):
''' Add entity to world.
entity is of type Entity
'''
if not entity in self._entities:
if second:
self._entities.append(entity)
else:
entity.set_world(self)
else:
r... | python | def add_entity(self, entity, second=False):
''' Add entity to world.
entity is of type Entity
'''
if not entity in self._entities:
if second:
self._entities.append(entity)
else:
entity.set_world(self)
else:
r... | [
"def",
"add_entity",
"(",
"self",
",",
"entity",
",",
"second",
"=",
"False",
")",
":",
"if",
"not",
"entity",
"in",
"self",
".",
"_entities",
":",
"if",
"second",
":",
"self",
".",
"_entities",
".",
"append",
"(",
"entity",
")",
"else",
":",
"entity... | Add entity to world.
entity is of type Entity | [
"Add",
"entity",
"to",
"world",
".",
"entity",
"is",
"of",
"type",
"Entity"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L21-L31 |
timothyhahn/rui | rui/rui.py | World.add_system | def add_system(self, system):
'''
Add system to the world.
All systems will be processed on World.process()
system is of type System
'''
if system not in self._systems:
system.set_world(self)
self._systems.append(system)
else:
r... | python | def add_system(self, system):
'''
Add system to the world.
All systems will be processed on World.process()
system is of type System
'''
if system not in self._systems:
system.set_world(self)
self._systems.append(system)
else:
r... | [
"def",
"add_system",
"(",
"self",
",",
"system",
")",
":",
"if",
"system",
"not",
"in",
"self",
".",
"_systems",
":",
"system",
".",
"set_world",
"(",
"self",
")",
"self",
".",
"_systems",
".",
"append",
"(",
"system",
")",
"else",
":",
"raise",
"Dup... | Add system to the world.
All systems will be processed on World.process()
system is of type System | [
"Add",
"system",
"to",
"the",
"world",
".",
"All",
"systems",
"will",
"be",
"processed",
"on",
"World",
".",
"process",
"()",
"system",
"is",
"of",
"type",
"System"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L40-L50 |
timothyhahn/rui | rui/rui.py | World.register_entity_to_group | def register_entity_to_group(self, entity, group):
'''
Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group
'''
if entity in self._entities:
if gro... | python | def register_entity_to_group(self, entity, group):
'''
Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group
'''
if entity in self._entities:
if gro... | [
"def",
"register_entity_to_group",
"(",
"self",
",",
"entity",
",",
"group",
")",
":",
"if",
"entity",
"in",
"self",
".",
"_entities",
":",
"if",
"group",
"in",
"self",
".",
"_groups",
":",
"self",
".",
"_groups",
"[",
"group",
"]",
".",
"append",
"(",... | Add entity to a group.
If group does not exist, entity will be added as first member
entity is of type Entity
group is a string that is the name of the group | [
"Add",
"entity",
"to",
"a",
"group",
".",
"If",
"group",
"does",
"not",
"exist",
"entity",
"will",
"be",
"added",
"as",
"first",
"member",
"entity",
"is",
"of",
"type",
"Entity",
"group",
"is",
"a",
"string",
"that",
"is",
"the",
"name",
"of",
"the",
... | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L52-L65 |
timothyhahn/rui | rui/rui.py | World.deregister_entity_from_group | def deregister_entity_from_group(self, entity, group):
'''
Removes entity from group
'''
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) | python | def deregister_entity_from_group(self, entity, group):
'''
Removes entity from group
'''
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) | [
"def",
"deregister_entity_from_group",
"(",
"self",
",",
"entity",
",",
"group",
")",
":",
"if",
"entity",
"in",
"self",
".",
"_entities",
":",
"if",
"entity",
"in",
"self",
".",
"_groups",
"[",
"group",
"]",
":",
"self",
".",
"_groups",
"[",
"group",
... | Removes entity from group | [
"Removes",
"entity",
"from",
"group"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L67-L75 |
timothyhahn/rui | rui/rui.py | World.remove_entity | def remove_entity(self, entity, second=False):
'''
Removes entity from world and kills entity
'''
if entity in self._entities:
if second:
for group in self._groups.keys():
if entity in self._groups[group]:
self.dereg... | python | def remove_entity(self, entity, second=False):
'''
Removes entity from world and kills entity
'''
if entity in self._entities:
if second:
for group in self._groups.keys():
if entity in self._groups[group]:
self.dereg... | [
"def",
"remove_entity",
"(",
"self",
",",
"entity",
",",
"second",
"=",
"False",
")",
":",
"if",
"entity",
"in",
"self",
".",
"_entities",
":",
"if",
"second",
":",
"for",
"group",
"in",
"self",
".",
"_groups",
".",
"keys",
"(",
")",
":",
"if",
"en... | Removes entity from world and kills entity | [
"Removes",
"entity",
"from",
"world",
"and",
"kills",
"entity"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L84-L97 |
timothyhahn/rui | rui/rui.py | World.remove_system | def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
else:
raise UnmanagedSystemError(system) | python | def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
else:
raise UnmanagedSystemError(system) | [
"def",
"remove_system",
"(",
"self",
",",
"system",
")",
":",
"if",
"system",
"in",
"self",
".",
"_systems",
":",
"self",
".",
"_systems",
".",
"remove",
"(",
"system",
")",
"else",
":",
"raise",
"UnmanagedSystemError",
"(",
"system",
")"
] | Removes system from world and kills system | [
"Removes",
"system",
"from",
"world",
"and",
"kills",
"system"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L99-L106 |
timothyhahn/rui | rui/rui.py | World.get_entity_by_tag | def get_entity_by_tag(self, tag):
'''
Get entity by tag
tag is a string that is the tag of the Entity.
'''
matching_entities = list(filter(lambda entity: entity.get_tag() == tag,
self._entities))
if matching_entities:
re... | python | def get_entity_by_tag(self, tag):
'''
Get entity by tag
tag is a string that is the tag of the Entity.
'''
matching_entities = list(filter(lambda entity: entity.get_tag() == tag,
self._entities))
if matching_entities:
re... | [
"def",
"get_entity_by_tag",
"(",
"self",
",",
"tag",
")",
":",
"matching_entities",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"entity",
":",
"entity",
".",
"get_tag",
"(",
")",
"==",
"tag",
",",
"self",
".",
"_entities",
")",
")",
"if",
"matching_entiti... | Get entity by tag
tag is a string that is the tag of the Entity. | [
"Get",
"entity",
"by",
"tag",
"tag",
"is",
"a",
"string",
"that",
"is",
"the",
"tag",
"of",
"the",
"Entity",
"."
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L108-L118 |
timothyhahn/rui | rui/rui.py | World.get_entities_by_components | def get_entities_by_components(self, *components):
'''
Get entity by list of components
All members of components must be of type Component
'''
return list(filter(lambda entity:
set(components) <=
set(map(type, entity.get_comp... | python | def get_entities_by_components(self, *components):
'''
Get entity by list of components
All members of components must be of type Component
'''
return list(filter(lambda entity:
set(components) <=
set(map(type, entity.get_comp... | [
"def",
"get_entities_by_components",
"(",
"self",
",",
"*",
"components",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"entity",
":",
"set",
"(",
"components",
")",
"<=",
"set",
"(",
"map",
"(",
"type",
",",
"entity",
".",
"get_components",
... | Get entity by list of components
All members of components must be of type Component | [
"Get",
"entity",
"by",
"list",
"of",
"components",
"All",
"members",
"of",
"components",
"must",
"be",
"of",
"type",
"Component"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L120-L128 |
timothyhahn/rui | rui/rui.py | Entity.set_world | def set_world(self, world):
'''
Sets the world an entity belongs to.
Checks for tag conflicts before adding.
'''
if world.get_entity_by_tag(self._tag) and self._tag != '':
raise NonUniqueTagError(self._tag)
else:
self._world = world
wor... | python | def set_world(self, world):
'''
Sets the world an entity belongs to.
Checks for tag conflicts before adding.
'''
if world.get_entity_by_tag(self._tag) and self._tag != '':
raise NonUniqueTagError(self._tag)
else:
self._world = world
wor... | [
"def",
"set_world",
"(",
"self",
",",
"world",
")",
":",
"if",
"world",
".",
"get_entity_by_tag",
"(",
"self",
".",
"_tag",
")",
"and",
"self",
".",
"_tag",
"!=",
"''",
":",
"raise",
"NonUniqueTagError",
"(",
"self",
".",
"_tag",
")",
"else",
":",
"s... | Sets the world an entity belongs to.
Checks for tag conflicts before adding. | [
"Sets",
"the",
"world",
"an",
"entity",
"belongs",
"to",
".",
"Checks",
"for",
"tag",
"conflicts",
"before",
"adding",
"."
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L189-L198 |
timothyhahn/rui | rui/rui.py | Entity.set_tag | def set_tag(self, tag):
'''
Sets the tag.
If the Entity belongs to the world it will check for tag conflicts.
'''
if self._world:
if self._world.get_entity_by_tag(tag):
raise NonUniqueTagError(tag)
self._tag = tag | python | def set_tag(self, tag):
'''
Sets the tag.
If the Entity belongs to the world it will check for tag conflicts.
'''
if self._world:
if self._world.get_entity_by_tag(tag):
raise NonUniqueTagError(tag)
self._tag = tag | [
"def",
"set_tag",
"(",
"self",
",",
"tag",
")",
":",
"if",
"self",
".",
"_world",
":",
"if",
"self",
".",
"_world",
".",
"get_entity_by_tag",
"(",
"tag",
")",
":",
"raise",
"NonUniqueTagError",
"(",
"tag",
")",
"self",
".",
"_tag",
"=",
"tag"
] | Sets the tag.
If the Entity belongs to the world it will check for tag conflicts. | [
"Sets",
"the",
"tag",
".",
"If",
"the",
"Entity",
"belongs",
"to",
"the",
"world",
"it",
"will",
"check",
"for",
"tag",
"conflicts",
"."
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L215-L223 |
timothyhahn/rui | rui/rui.py | Entity.kill | def kill(self):
'''Kills Entity'''
if self._world:
self._world.remove_entity(self, True)
self._world = None
self._tag = None
self._uuid = None
self._components = None | python | def kill(self):
'''Kills Entity'''
if self._world:
self._world.remove_entity(self, True)
self._world = None
self._tag = None
self._uuid = None
self._components = None | [
"def",
"kill",
"(",
"self",
")",
":",
"if",
"self",
".",
"_world",
":",
"self",
".",
"_world",
".",
"remove_entity",
"(",
"self",
",",
"True",
")",
"self",
".",
"_world",
"=",
"None",
"self",
".",
"_tag",
"=",
"None",
"self",
".",
"_uuid",
"=",
"... | Kills Entity | [
"Kills",
"Entity"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L226-L233 |
timothyhahn/rui | rui/rui.py | Entity.add_component | def add_component(self, component):
'''
Adds a Component to an Entity
'''
if component not in self._components:
self._components.append(component)
else: # Replace Component
self._components[self._components.index(component)] = component | python | def add_component(self, component):
'''
Adds a Component to an Entity
'''
if component not in self._components:
self._components.append(component)
else: # Replace Component
self._components[self._components.index(component)] = component | [
"def",
"add_component",
"(",
"self",
",",
"component",
")",
":",
"if",
"component",
"not",
"in",
"self",
".",
"_components",
":",
"self",
".",
"_components",
".",
"append",
"(",
"component",
")",
"else",
":",
"# Replace Component",
"self",
".",
"_components"... | Adds a Component to an Entity | [
"Adds",
"a",
"Component",
"to",
"an",
"Entity"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L236-L243 |
timothyhahn/rui | rui/rui.py | Entity.get_component | def get_component(self, component_type):
'''
Gets component of component_type or returns None
'''
matching_components = list(filter(lambda component:
isinstance(component,
component_type),
... | python | def get_component(self, component_type):
'''
Gets component of component_type or returns None
'''
matching_components = list(filter(lambda component:
isinstance(component,
component_type),
... | [
"def",
"get_component",
"(",
"self",
",",
"component_type",
")",
":",
"matching_components",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"component",
":",
"isinstance",
"(",
"component",
",",
"component_type",
")",
",",
"self",
".",
"_components",
")",
")",
"... | Gets component of component_type or returns None | [
"Gets",
"component",
"of",
"component_type",
"or",
"returns",
"None"
] | train | https://github.com/timothyhahn/rui/blob/ac9f587fb486760d77332866c6e876f78a810f74/rui/rui.py#L246-L257 |
thespacedoctor/crowdedText | crowdedText/crowdedText.py | optimally_align_text | def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
direction='xy'):
"""
For all text objects find alignment that causes the least overlap with
points and other texts and apply it
"""
if ax is None:
ax = plt.gca()
if renderer is None:
r ... | python | def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
direction='xy'):
"""
For all text objects find alignment that causes the least overlap with
points and other texts and apply it
"""
if ax is None:
ax = plt.gca()
if renderer is None:
r ... | [
"def",
"optimally_align_text",
"(",
"x",
",",
"y",
",",
"texts",
",",
"expand",
",",
"renderer",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"direction",
"=",
"'xy'",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
... | For all text objects find alignment that causes the least overlap with
points and other texts and apply it | [
"For",
"all",
"text",
"objects",
"find",
"alignment",
"that",
"causes",
"the",
"least",
"overlap",
"with",
"points",
"and",
"other",
"texts",
"and",
"apply",
"it"
] | train | https://github.com/thespacedoctor/crowdedText/blob/9a2e756b165aab7b48b2fad975b6a17d1ef48965/crowdedText/crowdedText.py#L78-L118 |
thespacedoctor/crowdedText | crowdedText/crowdedText.py | adjust_text | def adjust_text(x, y, texts, ax=None, expand_text=(1.2, 1.2),
expand_points=(1.2, 1.2), autoalign=True, va='center',
ha='center', force_text=1., force_points=1.,
lim=100, precision=0, only_move={}, text_from_text=True,
text_from_points=True, save_steps=Fa... | python | def adjust_text(x, y, texts, ax=None, expand_text=(1.2, 1.2),
expand_points=(1.2, 1.2), autoalign=True, va='center',
ha='center', force_text=1., force_points=1.,
lim=100, precision=0, only_move={}, text_from_text=True,
text_from_points=True, save_steps=Fa... | [
"def",
"adjust_text",
"(",
"x",
",",
"y",
",",
"texts",
",",
"ax",
"=",
"None",
",",
"expand_text",
"=",
"(",
"1.2",
",",
"1.2",
")",
",",
"expand_points",
"=",
"(",
"1.2",
",",
"1.2",
")",
",",
"autoalign",
"=",
"True",
",",
"va",
"=",
"'center'... | Iteratively adjusts the locations of texts. First moves all texts that are
outside the axes limits inside. Then in each iteration moves all texts away
from each other and from points. In the end hides texts and substitutes
them with annotations to link them to the rescpective points.
Args:
x (s... | [
"Iteratively",
"adjusts",
"the",
"locations",
"of",
"texts",
".",
"First",
"moves",
"all",
"texts",
"that",
"are",
"outside",
"the",
"axes",
"limits",
"inside",
".",
"Then",
"in",
"each",
"iteration",
"moves",
"all",
"texts",
"away",
"from",
"each",
"other",... | train | https://github.com/thespacedoctor/crowdedText/blob/9a2e756b165aab7b48b2fad975b6a17d1ef48965/crowdedText/crowdedText.py#L243-L399 |
scivision/histutils | histutils/__init__.py | write_quota | def write_quota(outbytes: int, outfn: Path) -> Union[None, int]:
"""
aborts writing if not enough space on drive to write
"""
if not outfn:
return None
anch = Path(outfn).resolve().anchor
freeout = shutil.disk_usage(anch).free
if freeout < 10 * outbytes:
raise IOError(f'out... | python | def write_quota(outbytes: int, outfn: Path) -> Union[None, int]:
"""
aborts writing if not enough space on drive to write
"""
if not outfn:
return None
anch = Path(outfn).resolve().anchor
freeout = shutil.disk_usage(anch).free
if freeout < 10 * outbytes:
raise IOError(f'out... | [
"def",
"write_quota",
"(",
"outbytes",
":",
"int",
",",
"outfn",
":",
"Path",
")",
"->",
"Union",
"[",
"None",
",",
"int",
"]",
":",
"if",
"not",
"outfn",
":",
"return",
"None",
"anch",
"=",
"Path",
"(",
"outfn",
")",
".",
"resolve",
"(",
")",
".... | aborts writing if not enough space on drive to write | [
"aborts",
"writing",
"if",
"not",
"enough",
"space",
"on",
"drive",
"to",
"write"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L12-L26 |
scivision/histutils | histutils/__init__.py | sixteen2eight | def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray:
"""
scipy.misc.bytescale had bugs
inputs:
------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael Hirsch, Ph.D.
"""
... | python | def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray:
"""
scipy.misc.bytescale had bugs
inputs:
------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael Hirsch, Ph.D.
"""
... | [
"def",
"sixteen2eight",
"(",
"I",
":",
"np",
".",
"ndarray",
",",
"Clim",
":",
"tuple",
")",
"->",
"np",
".",
"ndarray",
":",
"Q",
"=",
"normframe",
"(",
"I",
",",
"Clim",
")",
"Q",
"*=",
"255",
"# stretch to [0,255] as a float",
"return",
"Q",
".",
... | scipy.misc.bytescale had bugs
inputs:
------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael Hirsch, Ph.D. | [
"scipy",
".",
"misc",
".",
"bytescale",
"had",
"bugs"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L29-L41 |
scivision/histutils | histutils/__init__.py | normframe | def normframe(I: np.ndarray, Clim: tuple) -> np.ndarray:
"""
inputs:
-------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
"""
Vmin = Clim[0]
Vmax = Clim[1]
# stretch to [0,1]
... | python | def normframe(I: np.ndarray, Clim: tuple) -> np.ndarray:
"""
inputs:
-------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
"""
Vmin = Clim[0]
Vmax = Clim[1]
# stretch to [0,1]
... | [
"def",
"normframe",
"(",
"I",
":",
"np",
".",
"ndarray",
",",
"Clim",
":",
"tuple",
")",
"->",
"np",
".",
"ndarray",
":",
"Vmin",
"=",
"Clim",
"[",
"0",
"]",
"Vmax",
"=",
"Clim",
"[",
"1",
"]",
"# stretch to [0,1]",
"return",
"(",
"I",
".",
"asty... | inputs:
-------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image | [
"inputs",
":",
"-------",
"I",
":",
"2",
"-",
"D",
"Numpy",
"array",
"of",
"grayscale",
"image",
"data",
"Clim",
":",
"length",
"2",
"of",
"tuple",
"or",
"numpy",
"1",
"-",
"D",
"array",
"specifying",
"lowest",
"and",
"highest",
"expected",
"values",
"... | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L44-L55 |
scivision/histutils | histutils/__init__.py | req2frame | def req2frame(req, N: int=0):
"""
output has to be numpy.arange for > comparison
"""
if req is None:
frame = np.arange(N, dtype=np.int64)
elif isinstance(req, int): # the user is specifying a step size
frame = np.arange(0, N, req, dtype=np.int64)
elif len(req) == 1:
fram... | python | def req2frame(req, N: int=0):
"""
output has to be numpy.arange for > comparison
"""
if req is None:
frame = np.arange(N, dtype=np.int64)
elif isinstance(req, int): # the user is specifying a step size
frame = np.arange(0, N, req, dtype=np.int64)
elif len(req) == 1:
fram... | [
"def",
"req2frame",
"(",
"req",
",",
"N",
":",
"int",
"=",
"0",
")",
":",
"if",
"req",
"is",
"None",
":",
"frame",
"=",
"np",
".",
"arange",
"(",
"N",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"elif",
"isinstance",
"(",
"req",
",",
"int",
"... | output has to be numpy.arange for > comparison | [
"output",
"has",
"to",
"be",
"numpy",
".",
"arange",
"for",
">",
"comparison"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L94-L113 |
scivision/histutils | histutils/__init__.py | dir2fn | def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
"""
if not ofn: # no output file desired
return None
ofn = Path(ofn).expanduse... | python | def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
"""
if not ofn: # no output file desired
return None
ofn = Path(ofn).expanduse... | [
"def",
"dir2fn",
"(",
"ofn",
",",
"ifn",
",",
"suffix",
")",
"->",
"Union",
"[",
"None",
",",
"Path",
"]",
":",
"if",
"not",
"ofn",
":",
"# no output file desired",
"return",
"None",
"ofn",
"=",
"Path",
"(",
"ofn",
")",
".",
"expanduser",
"(",
")",
... | ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5 | [
"ofn",
"=",
"filename",
"or",
"output",
"directory",
"to",
"create",
"filename",
"based",
"on",
"ifn",
"ifn",
"=",
"input",
"filename",
"(",
"don",
"t",
"overwrite!",
")",
"suffix",
"=",
"desired",
"file",
"extension",
"e",
".",
"g",
".",
".",
"h5"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L116-L140 |
scivision/histutils | histutils/__init__.py | setupimgh5 | def setupimgh5(f: Union[Path, h5py.File],
Nframetotal: int, Nrow: int, Ncol: int, dtype=np.uint16,
writemode='r+', key='/rawimg', cmdlog: str=None):
"""
f: HDF5 handle (or filename)
h: HDF5 dataset handle
"""
if isinstance(f, (str, Path)): # assume new HDF5 file wante... | python | def setupimgh5(f: Union[Path, h5py.File],
Nframetotal: int, Nrow: int, Ncol: int, dtype=np.uint16,
writemode='r+', key='/rawimg', cmdlog: str=None):
"""
f: HDF5 handle (or filename)
h: HDF5 dataset handle
"""
if isinstance(f, (str, Path)): # assume new HDF5 file wante... | [
"def",
"setupimgh5",
"(",
"f",
":",
"Union",
"[",
"Path",
",",
"h5py",
".",
"File",
"]",
",",
"Nframetotal",
":",
"int",
",",
"Nrow",
":",
"int",
",",
"Ncol",
":",
"int",
",",
"dtype",
"=",
"np",
".",
"uint16",
",",
"writemode",
"=",
"'r+'",
",",... | f: HDF5 handle (or filename)
h: HDF5 dataset handle | [
"f",
":",
"HDF5",
"handle",
"(",
"or",
"filename",
")"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L184-L223 |
scivision/histutils | histutils/__init__.py | vid2h5 | def vid2h5(data: np.ndarray, ut1, rawind, ticks, outfn: Path, P: dict, i: int=0,
Nfile: int=1, det=None, tstart=None, cmdlog: str=None):
assert outfn, 'must provide a filename to write'
outfn = Path(outfn).expanduser()
assert not outfn.is_dir(
), 'must provide FILEname, you provided director... | python | def vid2h5(data: np.ndarray, ut1, rawind, ticks, outfn: Path, P: dict, i: int=0,
Nfile: int=1, det=None, tstart=None, cmdlog: str=None):
assert outfn, 'must provide a filename to write'
outfn = Path(outfn).expanduser()
assert not outfn.is_dir(
), 'must provide FILEname, you provided director... | [
"def",
"vid2h5",
"(",
"data",
":",
"np",
".",
"ndarray",
",",
"ut1",
",",
"rawind",
",",
"ticks",
",",
"outfn",
":",
"Path",
",",
"P",
":",
"dict",
",",
"i",
":",
"int",
"=",
"0",
",",
"Nfile",
":",
"int",
"=",
"1",
",",
"det",
"=",
"None",
... | note if line wraps (>80 characters), this in-place update breaks. | [
"note",
"if",
"line",
"wraps",
"(",
">",
"80",
"characters",
")",
"this",
"in",
"-",
"place",
"update",
"breaks",
"."
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L226-L378 |
scivision/histutils | histutils/__init__.py | imgwriteincr | def imgwriteincr(fn: Path, imgs, imgslice):
"""
writes HDF5 huge image files in increments
"""
if isinstance(imgslice, int):
if imgslice and not (imgslice % 2000):
print(f'appending images {imgslice} to {fn}')
if isinstance(fn, Path):
# avoid accidental overwriting of so... | python | def imgwriteincr(fn: Path, imgs, imgslice):
"""
writes HDF5 huge image files in increments
"""
if isinstance(imgslice, int):
if imgslice and not (imgslice % 2000):
print(f'appending images {imgslice} to {fn}')
if isinstance(fn, Path):
# avoid accidental overwriting of so... | [
"def",
"imgwriteincr",
"(",
"fn",
":",
"Path",
",",
"imgs",
",",
"imgslice",
")",
":",
"if",
"isinstance",
"(",
"imgslice",
",",
"int",
")",
":",
"if",
"imgslice",
"and",
"not",
"(",
"imgslice",
"%",
"2000",
")",
":",
"print",
"(",
"f'appending images ... | writes HDF5 huge image files in increments | [
"writes",
"HDF5",
"huge",
"image",
"files",
"in",
"increments"
] | train | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/__init__.py#L381-L399 |
MacHu-GWU/pyknackhq-project | pyknackhq/js.py | load_js | def load_js(abspath, default=dict(), compress=False, enable_verbose=True):
"""Load Json from file. If file are not exists, returns ``default``.
:param abspath: File path. Use absolute path as much as you can. File
extension has to be ``.json`` or ``.gz``. (for compressed Json)
:type abspath: strin... | python | def load_js(abspath, default=dict(), compress=False, enable_verbose=True):
"""Load Json from file. If file are not exists, returns ``default``.
:param abspath: File path. Use absolute path as much as you can. File
extension has to be ``.json`` or ``.gz``. (for compressed Json)
:type abspath: strin... | [
"def",
"load_js",
"(",
"abspath",
",",
"default",
"=",
"dict",
"(",
")",
",",
"compress",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"abspath",
"=",
"str",
"(",
"abspath",
")",
"# try stringlize",
"if",
"compress",
":",
"# check extension ... | Load Json from file. If file are not exists, returns ``default``.
:param abspath: File path. Use absolute path as much as you can. File
extension has to be ``.json`` or ``.gz``. (for compressed Json)
:type abspath: string
:param default: (default dict()) If ``abspath`` not exists, return the
... | [
"Load",
"Json",
"from",
"file",
".",
"If",
"file",
"are",
"not",
"exists",
"returns",
"default",
"."
] | train | https://github.com/MacHu-GWU/pyknackhq-project/blob/dd937f24d7b0a351ba3818eb746c31b29a8cc341/pyknackhq/js.py#L52-L123 |
MacHu-GWU/pyknackhq-project | pyknackhq/js.py | dump_js | def dump_js(js, abspath,
fastmode=False, replace=False, compress=False, enable_verbose=True):
"""Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as``... | python | def dump_js(js, abspath,
fastmode=False, replace=False, compress=False, enable_verbose=True):
"""Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as``... | [
"def",
"dump_js",
"(",
"js",
",",
"abspath",
",",
"fastmode",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"compress",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"abspath",
"=",
"str",
"(",
"abspath",
")",
"# try stringlize",
"if",
... | Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
(for compressed json).
:type abspath: string
... | [
"Dump",
"Json",
"serializable",
"object",
"to",
"file",
".",
"Provides",
"multiple",
"choice",
"to",
"customize",
"the",
"behavior",
".",
":",
"param",
"js",
":",
"Serializable",
"python",
"object",
".",
":",
"type",
"js",
":",
"dict",
"or",
"list",
":",
... | train | https://github.com/MacHu-GWU/pyknackhq-project/blob/dd937f24d7b0a351ba3818eb746c31b29a8cc341/pyknackhq/js.py#L125-L258 |
MacHu-GWU/pyknackhq-project | pyknackhq/js.py | safe_dump_js | def safe_dump_js(js, abspath,
fastmode=False, compress=False, enable_verbose=True):
"""A stable version of dump_js, silently overwrite existing file.
When your program been interrupted, you lose nothing. Typically if your
program is interrupted by any reason, it only leaves a incomplete f... | python | def safe_dump_js(js, abspath,
fastmode=False, compress=False, enable_verbose=True):
"""A stable version of dump_js, silently overwrite existing file.
When your program been interrupted, you lose nothing. Typically if your
program is interrupted by any reason, it only leaves a incomplete f... | [
"def",
"safe_dump_js",
"(",
"js",
",",
"abspath",
",",
"fastmode",
"=",
"False",
",",
"compress",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"abspath",
"=",
"str",
"(",
"abspath",
")",
"# try stringlize",
"temp_abspath",
"=",
"\"%s.tmp\"",
... | A stable version of dump_js, silently overwrite existing file.
When your program been interrupted, you lose nothing. Typically if your
program is interrupted by any reason, it only leaves a incomplete file.
If you use replace=True, then you also lose your old file.
So a bettr way is to:
1... | [
"A",
"stable",
"version",
"of",
"dump_js",
"silently",
"overwrite",
"existing",
"file",
"."
] | train | https://github.com/MacHu-GWU/pyknackhq-project/blob/dd937f24d7b0a351ba3818eb746c31b29a8cc341/pyknackhq/js.py#L260-L335 |
political-memory/django-representatives | representatives/migrations/0017_auto_20160623_2201.py | migrate_constituencies | def migrate_constituencies(apps, schema_editor):
"""
Re-save constituencies to recompute fingerprints
"""
Constituency = apps.get_model("representatives", "Constituency")
for c in Constituency.objects.all():
c.save() | python | def migrate_constituencies(apps, schema_editor):
"""
Re-save constituencies to recompute fingerprints
"""
Constituency = apps.get_model("representatives", "Constituency")
for c in Constituency.objects.all():
c.save() | [
"def",
"migrate_constituencies",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Constituency",
"=",
"apps",
".",
"get_model",
"(",
"\"representatives\"",
",",
"\"Constituency\"",
")",
"for",
"c",
"in",
"Constituency",
".",
"objects",
".",
"all",
"(",
")",
":",
... | Re-save constituencies to recompute fingerprints | [
"Re",
"-",
"save",
"constituencies",
"to",
"recompute",
"fingerprints"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0017_auto_20160623_2201.py#L7-L13 |
mayfield/shellish | shellish/layout/tree.py | treeprint | def treeprint(data, render_only=False, file=None, **options):
""" Render a tree structure based on generic python containers. The keys
should be titles and the values are children of the node or None if it's
an empty leaf node; Primitives are valid leaf node labels too. E.g.
sample = {
... | python | def treeprint(data, render_only=False, file=None, **options):
""" Render a tree structure based on generic python containers. The keys
should be titles and the values are children of the node or None if it's
an empty leaf node; Primitives are valid leaf node labels too. E.g.
sample = {
... | [
"def",
"treeprint",
"(",
"data",
",",
"render_only",
"=",
"False",
",",
"file",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"def",
"getiter",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"abc",
".",
"Mapping",
... | Render a tree structure based on generic python containers. The keys
should be titles and the values are children of the node or None if it's
an empty leaf node; Primitives are valid leaf node labels too. E.g.
sample = {
"Leaf 1": None,
"Leaf 2": "I have a label on me",
... | [
"Render",
"a",
"tree",
"structure",
"based",
"on",
"generic",
"python",
"containers",
".",
"The",
"keys",
"should",
"be",
"titles",
"and",
"the",
"values",
"are",
"children",
"of",
"the",
"node",
"or",
"None",
"if",
"it",
"s",
"an",
"empty",
"leaf",
"nod... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/tree.py#L60-L116 |
marcosgabarda/django-belt | belt/commands.py | ProgressBarCommand.terminal_size | def terminal_size(self):
"""Gets the terminal columns size."""
try:
_, columns = os.popen('stty size', 'r').read().split()
return min(int(columns) - 10, 100)
except ValueError:
return self.default_terminal_size | python | def terminal_size(self):
"""Gets the terminal columns size."""
try:
_, columns = os.popen('stty size', 'r').read().split()
return min(int(columns) - 10, 100)
except ValueError:
return self.default_terminal_size | [
"def",
"terminal_size",
"(",
"self",
")",
":",
"try",
":",
"_",
",",
"columns",
"=",
"os",
".",
"popen",
"(",
"'stty size'",
",",
"'r'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
")",
"return",
"min",
"(",
"int",
"(",
"columns",
")",
"-",
... | Gets the terminal columns size. | [
"Gets",
"the",
"terminal",
"columns",
"size",
"."
] | train | https://github.com/marcosgabarda/django-belt/blob/81404604c4dff664b1520b01e1f638c9c6bab41b/belt/commands.py#L13-L19 |
marcosgabarda/django-belt | belt/commands.py | ProgressBarCommand.bar | def bar(self, progress):
"""Shows on the stdout the progress bar for the given progress."""
if not hasattr(self, "_limit") or not self._limit:
self._limit = self.terminal_size()
graph_progress = int(progress * self._limit)
self.stdout.write('\r', ending='')
progress_f... | python | def bar(self, progress):
"""Shows on the stdout the progress bar for the given progress."""
if not hasattr(self, "_limit") or not self._limit:
self._limit = self.terminal_size()
graph_progress = int(progress * self._limit)
self.stdout.write('\r', ending='')
progress_f... | [
"def",
"bar",
"(",
"self",
",",
"progress",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_limit\"",
")",
"or",
"not",
"self",
".",
"_limit",
":",
"self",
".",
"_limit",
"=",
"self",
".",
"terminal_size",
"(",
")",
"graph_progress",
"=",
"in... | Shows on the stdout the progress bar for the given progress. | [
"Shows",
"on",
"the",
"stdout",
"the",
"progress",
"bar",
"for",
"the",
"given",
"progress",
"."
] | train | https://github.com/marcosgabarda/django-belt/blob/81404604c4dff664b1520b01e1f638c9c6bab41b/belt/commands.py#L21-L32 |
francois-vincent/clingon | clingon/utils.py | auto_update_attrs_from_kwargs | def auto_update_attrs_from_kwargs(method):
""" this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the d... | python | def auto_update_attrs_from_kwargs(method):
""" this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the d... | [
"def",
"auto_update_attrs_from_kwargs",
"(",
"method",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# method signature introspection",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
"defaults",
"=",
"argspec",
... | this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the decorated method (typically __init__) | [
"this",
"decorator",
"will",
"update",
"the",
"attributes",
"of",
"an",
"instance",
"object",
"with",
"all",
"the",
"kwargs",
"of",
"the",
"decorated",
"method",
"updated",
"with",
"the",
"kwargs",
"of",
"the",
"actual",
"call",
".",
"This",
"saves",
"you",
... | train | https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/utils.py#L10-L34 |
sahid/warm | warm/components/__init__.py | SecurityGroup._Execute | def _Execute(self, options):
"""Handles security groups operations."""
whitelist = dict(
name=options["name"],
description=options.get("description", "<empty>"))
return self._agent.client.compute.security_groups.create(**whitelist) | python | def _Execute(self, options):
"""Handles security groups operations."""
whitelist = dict(
name=options["name"],
description=options.get("description", "<empty>"))
return self._agent.client.compute.security_groups.create(**whitelist) | [
"def",
"_Execute",
"(",
"self",
",",
"options",
")",
":",
"whitelist",
"=",
"dict",
"(",
"name",
"=",
"options",
"[",
"\"name\"",
"]",
",",
"description",
"=",
"options",
".",
"get",
"(",
"\"description\"",
",",
"\"<empty>\"",
")",
")",
"return",
"self",... | Handles security groups operations. | [
"Handles",
"security",
"groups",
"operations",
"."
] | train | https://github.com/sahid/warm/blob/baf1cb73c6769a556756b9078e60c96d4b1de2bd/warm/components/__init__.py#L167-L172 |
pwyliu/clancy | clancy/config.py | validate | def validate(args):
"""
Validate args
"""
provided = {key: val for key, val in args.iteritems() if val is not None}
schema = Schema({
'--user': And(str, len, Use(str.lower)),
'--server': And(str, len, Use(str.lower)),
'--cacert': os.path.isfile,
# ops
Optional... | python | def validate(args):
"""
Validate args
"""
provided = {key: val for key, val in args.iteritems() if val is not None}
schema = Schema({
'--user': And(str, len, Use(str.lower)),
'--server': And(str, len, Use(str.lower)),
'--cacert': os.path.isfile,
# ops
Optional... | [
"def",
"validate",
"(",
"args",
")",
":",
"provided",
"=",
"{",
"key",
":",
"val",
"for",
"key",
",",
"val",
"in",
"args",
".",
"iteritems",
"(",
")",
"if",
"val",
"is",
"not",
"None",
"}",
"schema",
"=",
"Schema",
"(",
"{",
"'--user'",
":",
"And... | Validate args | [
"Validate",
"args"
] | train | https://github.com/pwyliu/clancy/blob/cb15a5e2bb735ffce7a84b8413b04faa78c5039c/clancy/config.py#L23-L56 |
pwyliu/clancy | clancy/config.py | load_args | def load_args(args):
"""
Load a config file. Merges CLI args and validates.
"""
config = kaptan.Kaptan(handler='yaml')
conf_parent = os.path.expanduser('~')
conf_app = '.clancy'
conf_filename = 'config.yaml'
conf_dir = os.path.join(conf_parent, conf_app)
for loc in [os.curdir, conf_... | python | def load_args(args):
"""
Load a config file. Merges CLI args and validates.
"""
config = kaptan.Kaptan(handler='yaml')
conf_parent = os.path.expanduser('~')
conf_app = '.clancy'
conf_filename = 'config.yaml'
conf_dir = os.path.join(conf_parent, conf_app)
for loc in [os.curdir, conf_... | [
"def",
"load_args",
"(",
"args",
")",
":",
"config",
"=",
"kaptan",
".",
"Kaptan",
"(",
"handler",
"=",
"'yaml'",
")",
"conf_parent",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"conf_app",
"=",
"'.clancy'",
"conf_filename",
"=",
"'config... | Load a config file. Merges CLI args and validates. | [
"Load",
"a",
"config",
"file",
".",
"Merges",
"CLI",
"args",
"and",
"validates",
"."
] | train | https://github.com/pwyliu/clancy/blob/cb15a5e2bb735ffce7a84b8413b04faa78c5039c/clancy/config.py#L59-L87 |
rsalmaso/django-fluo | fluo/middleware/locale.py | get_default_language | def get_default_language(language_code=None):
"""
Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found
"""
if not language_code:
language_code = settings.LAN... | python | def get_default_language(language_code=None):
"""
Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found
"""
if not language_code:
language_code = settings.LAN... | [
"def",
"get_default_language",
"(",
"language_code",
"=",
"None",
")",
":",
"if",
"not",
"language_code",
":",
"language_code",
"=",
"settings",
".",
"LANGUAGE_CODE",
"languages",
"=",
"dict",
"(",
"settings",
".",
"LANGUAGES",
")",
".",
"keys",
"(",
")",
"#... | Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found | [
"Returns",
"default",
"language",
"depending",
"on",
"settings",
".",
"LANGUAGE_CODE",
"merged",
"with",
"best",
"match",
"from",
"settings",
".",
"LANGUAGES"
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/middleware/locale.py#L68-L93 |
luismasuelli/python-cantrips | cantrips/patterns/actions.py | Action.as_method | def as_method(self, docstring=""):
"""
Converts this action to a function or method.
An optional docstring may be passed.
"""
method = lambda obj, *args, **kwargs: self(obj, *args, **kwargs)
if docstring:
method.__doc__ = docstring
return method | python | def as_method(self, docstring=""):
"""
Converts this action to a function or method.
An optional docstring may be passed.
"""
method = lambda obj, *args, **kwargs: self(obj, *args, **kwargs)
if docstring:
method.__doc__ = docstring
return method | [
"def",
"as_method",
"(",
"self",
",",
"docstring",
"=",
"\"\"",
")",
":",
"method",
"=",
"lambda",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"self",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"docstring",
":",
... | Converts this action to a function or method.
An optional docstring may be passed. | [
"Converts",
"this",
"action",
"to",
"a",
"function",
"or",
"method",
".",
"An",
"optional",
"docstring",
"may",
"be",
"passed",
"."
] | train | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/patterns/actions.py#L12-L20 |
kmedian/illmat | illmat/illmat.py | illmat | def illmat(D, random_state=None):
"""Generate a <D x D> ill-conditioned correlation matrix
with random coefficients
Parameters:
-----------
D : int
Dimension of the matrix
Return:
-------
cmat : ndarray
DxD matrix with +1 as diagonal elements,
mirrored random nu... | python | def illmat(D, random_state=None):
"""Generate a <D x D> ill-conditioned correlation matrix
with random coefficients
Parameters:
-----------
D : int
Dimension of the matrix
Return:
-------
cmat : ndarray
DxD matrix with +1 as diagonal elements,
mirrored random nu... | [
"def",
"illmat",
"(",
"D",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"random_state",
":",
"np",
".",
"random",
".",
"seed",
"(",
"random_state",
")",
"uni",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"D",
",",
"D",
"... | Generate a <D x D> ill-conditioned correlation matrix
with random coefficients
Parameters:
-----------
D : int
Dimension of the matrix
Return:
-------
cmat : ndarray
DxD matrix with +1 as diagonal elements,
mirrored random numbers [-1,+1]. | [
"Generate",
"a",
"<D",
"x",
"D",
">",
"ill",
"-",
"conditioned",
"correlation",
"matrix",
"with",
"random",
"coefficients"
] | train | https://github.com/kmedian/illmat/blob/2755e7c7da67378a0fa38ed24ba040dbf0f645bd/illmat/illmat.py#L5-L29 |
jpablo128/simplystatic | simplystatic/s2page.py | Page._create | def _create(self, rawtitle):
"""Create a page with this title, if it doesn't exist.
This method first checks whether a page with the same slug
(sanitized name) exists_on_disk. If it does, it doesn't do antyhing.
Otherwise, the relevant attributes are created.
Nothing is written ... | python | def _create(self, rawtitle):
"""Create a page with this title, if it doesn't exist.
This method first checks whether a page with the same slug
(sanitized name) exists_on_disk. If it does, it doesn't do antyhing.
Otherwise, the relevant attributes are created.
Nothing is written ... | [
"def",
"_create",
"(",
"self",
",",
"rawtitle",
")",
":",
"slug",
"=",
"util",
".",
"make_slug",
"(",
"rawtitle",
")",
"if",
"self",
".",
"site",
".",
"page_exists_on_disk",
"(",
"slug",
")",
":",
"raise",
"ValueError",
"#print \"Attempted to create a page whi... | Create a page with this title, if it doesn't exist.
This method first checks whether a page with the same slug
(sanitized name) exists_on_disk. If it does, it doesn't do antyhing.
Otherwise, the relevant attributes are created.
Nothing is written to disc (to the source file). You must c... | [
"Create",
"a",
"page",
"with",
"this",
"title",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2page.py#L100-L129 |
jpablo128/simplystatic | simplystatic/s2page.py | Page.write | def write(self):
"""Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site.
"""
if not os.path.isdir(self._dirs['source_dir']):
... | python | def write(self):
"""Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site.
"""
if not os.path.isdir(self._dirs['source_dir']):
... | [
"def",
"write",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"_dirs",
"[",
"'source_dir'",
"]",
")",
":",
"os",
".",
"mkdir",
"(",
"self",
".",
"_dirs",
"[",
"'source_dir'",
"]",
")",
"fout",
"=",
"codecs... | Write the s2 page to the corresponding source file.
It always writes the (serialized) config first, and then the
content (normally markdown). The destination file is in the
source_dir of the site. | [
"Write",
"the",
"s2",
"page",
"to",
"the",
"corresponding",
"source",
"file",
"."
] | train | https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2page.py#L131-L148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.