id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
246,000
|
delfick/gitmit
|
gitmit/cache.py
|
get_all_cached_commit_times
|
def get_all_cached_commit_times(root_folder):
"""
Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all!
"""
result = []
location = cache_location(root_folder)
if os.path.exists(location):
try:
result = json.load(open(location))
except (TypeError, ValueError) as error:
log.warning("Failed to open gitmit cached commit_times\tlocation=%s\terror=%s", location, error)
else:
if type(result) is not list or not all(type(item) is dict for item in result):
log.warning("Gitmit cached commit_times needs to be a list of dictionaries\tlocation=%s\tgot=%s", location, type(result))
result = []
return result
|
python
|
def get_all_cached_commit_times(root_folder):
"""
Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all!
"""
result = []
location = cache_location(root_folder)
if os.path.exists(location):
try:
result = json.load(open(location))
except (TypeError, ValueError) as error:
log.warning("Failed to open gitmit cached commit_times\tlocation=%s\terror=%s", location, error)
else:
if type(result) is not list or not all(type(item) is dict for item in result):
log.warning("Gitmit cached commit_times needs to be a list of dictionaries\tlocation=%s\tgot=%s", location, type(result))
result = []
return result
|
[
"def",
"get_all_cached_commit_times",
"(",
"root_folder",
")",
":",
"result",
"=",
"[",
"]",
"location",
"=",
"cache_location",
"(",
"root_folder",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"try",
":",
"result",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"location",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"error",
":",
"log",
".",
"warning",
"(",
"\"Failed to open gitmit cached commit_times\\tlocation=%s\\terror=%s\"",
",",
"location",
",",
"error",
")",
"else",
":",
"if",
"type",
"(",
"result",
")",
"is",
"not",
"list",
"or",
"not",
"all",
"(",
"type",
"(",
"item",
")",
"is",
"dict",
"for",
"item",
"in",
"result",
")",
":",
"log",
".",
"warning",
"(",
"\"Gitmit cached commit_times needs to be a list of dictionaries\\tlocation=%s\\tgot=%s\"",
",",
"location",
",",
"type",
"(",
"result",
")",
")",
"result",
"=",
"[",
"]",
"return",
"result"
] |
Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all!
|
[
"Find",
"the",
"gitmit",
"cached",
"commit_times",
"and",
"return",
"them",
"if",
"they",
"are",
"the",
"right",
"shape",
"."
] |
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
|
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L20-L42
|
246,001
|
delfick/gitmit
|
gitmit/cache.py
|
get_cached_commit_times
|
def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in result:
if sorted(item.get("sorted_relpaths", [])) == sorted_relpaths and item.get("parent_dir") == parent_dir:
return item.get("commit"), item.get("commit_times")
return None, {}
|
python
|
def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in result:
if sorted(item.get("sorted_relpaths", [])) == sorted_relpaths and item.get("parent_dir") == parent_dir:
return item.get("commit"), item.get("commit_times")
return None, {}
|
[
"def",
"get_cached_commit_times",
"(",
"root_folder",
",",
"parent_dir",
",",
"sorted_relpaths",
")",
":",
"result",
"=",
"get_all_cached_commit_times",
"(",
"root_folder",
")",
"for",
"item",
"in",
"result",
":",
"if",
"sorted",
"(",
"item",
".",
"get",
"(",
"\"sorted_relpaths\"",
",",
"[",
"]",
")",
")",
"==",
"sorted_relpaths",
"and",
"item",
".",
"get",
"(",
"\"parent_dir\"",
")",
"==",
"parent_dir",
":",
"return",
"item",
".",
"get",
"(",
"\"commit\"",
")",
",",
"item",
".",
"get",
"(",
"\"commit_times\"",
")",
"return",
"None",
",",
"{",
"}"
] |
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
|
[
"Get",
"the",
"cached",
"commit",
"times",
"for",
"the",
"combination",
"of",
"this",
"parent_dir",
"and",
"relpaths"
] |
ae0aef14a06b25ad2811f8f47cc97e68a0910eae
|
https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L44-L56
|
246,002
|
slarse/pdfebc-core
|
pdfebc_core/email_utils.py
|
_attach_files
|
def _attach_files(filepaths, email_):
"""Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_.
"""
for filepath in filepaths:
base = os.path.basename(filepath)
with open(filepath, "rb") as file:
part = MIMEApplication(file.read(), Name=base)
part["Content-Disposition"] = 'attachment; filename="%s"' % base
email_.attach(part)
|
python
|
def _attach_files(filepaths, email_):
"""Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_.
"""
for filepath in filepaths:
base = os.path.basename(filepath)
with open(filepath, "rb") as file:
part = MIMEApplication(file.read(), Name=base)
part["Content-Disposition"] = 'attachment; filename="%s"' % base
email_.attach(part)
|
[
"def",
"_attach_files",
"(",
"filepaths",
",",
"email_",
")",
":",
"for",
"filepath",
"in",
"filepaths",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"file",
":",
"part",
"=",
"MIMEApplication",
"(",
"file",
".",
"read",
"(",
")",
",",
"Name",
"=",
"base",
")",
"part",
"[",
"\"Content-Disposition\"",
"]",
"=",
"'attachment; filename=\"%s\"'",
"%",
"base",
"email_",
".",
"attach",
"(",
"part",
")"
] |
Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_.
|
[
"Take",
"a",
"list",
"of",
"filepaths",
"and",
"attach",
"the",
"files",
"to",
"a",
"MIMEMultipart",
"."
] |
fc40857bc42365b7434714333e37d7a3487603a0
|
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L53-L65
|
246,003
|
slarse/pdfebc-core
|
pdfebc_core/email_utils.py
|
send_files_preconf
|
async def send_files_preconf(filepaths, config_path=CONFIG_PATH):
"""Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths.
"""
config = read_config(config_path)
subject = "PDF files from pdfebc"
message = ""
await send_with_attachments(subject, message, filepaths, config)
|
python
|
async def send_files_preconf(filepaths, config_path=CONFIG_PATH):
"""Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths.
"""
config = read_config(config_path)
subject = "PDF files from pdfebc"
message = ""
await send_with_attachments(subject, message, filepaths, config)
|
[
"async",
"def",
"send_files_preconf",
"(",
"filepaths",
",",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"config",
"=",
"read_config",
"(",
"config_path",
")",
"subject",
"=",
"\"PDF files from pdfebc\"",
"message",
"=",
"\"\"",
"await",
"send_with_attachments",
"(",
"subject",
",",
"message",
",",
"filepaths",
",",
"config",
")"
] |
Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths.
|
[
"Send",
"files",
"using",
"the",
"config",
".",
"ini",
"settings",
"."
] |
fc40857bc42365b7434714333e37d7a3487603a0
|
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L85-L94
|
246,004
|
pbrisk/unicum
|
unicum/linkedobject.py
|
LinkedObject.remove_link
|
def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in l:
if v in l[name]:
l[name].remove(v)
if not l[name]:
l.pop(name)
return self
|
python
|
def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in l:
if v in l[name]:
l[name].remove(v)
if not l[name]:
l.pop(name)
return self
|
[
"def",
"remove_link",
"(",
"self",
",",
"obj",
",",
"attr",
"=",
"None",
")",
":",
"name",
"=",
"repr",
"(",
"self",
")",
"if",
"not",
"name",
":",
"return",
"self",
"l",
"=",
"self",
".",
"__class__",
".",
"_get_links",
"(",
")",
"v",
"=",
"WeakAttrLink",
"(",
"None",
",",
"obj",
")",
"if",
"attr",
"is",
"None",
"else",
"WeakAttrLink",
"(",
"obj",
",",
"attr",
")",
"if",
"name",
"in",
"l",
":",
"if",
"v",
"in",
"l",
"[",
"name",
"]",
":",
"l",
"[",
"name",
"]",
".",
"remove",
"(",
"v",
")",
"if",
"not",
"l",
"[",
"name",
"]",
":",
"l",
".",
"pop",
"(",
"name",
")",
"return",
"self"
] |
removes link from obj.attr
|
[
"removes",
"link",
"from",
"obj",
".",
"attr"
] |
24bfa7355f36847a06646c58e9fd75bd3b689bfe
|
https://github.com/pbrisk/unicum/blob/24bfa7355f36847a06646c58e9fd75bd3b689bfe/unicum/linkedobject.py#L97-L111
|
246,005
|
minhhoit/yacms
|
yacms/blog/management/commands/import_blogger.py
|
Command.handle_import
|
def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get("blog_id")
if blog_id is None:
raise CommandError("Usage is import_blogger %s" % self.args)
try:
from gdata import service
except ImportError:
raise CommandError("Could not import the gdata library.")
blogger = service.GDataService()
blogger.service = "blogger"
blogger.server = "www.blogger.com"
start_index = 1
processed_posts = []
new_posts = 1
while new_posts:
new_posts = 0
query = service.Query()
query.feed = "/feeds/%s/posts/full" % blog_id
query.max_results = 500
query.start_index = start_index
try:
feed = blogger.Get(query.ToUri())
except service.RequestError as err:
message = "There was a service error. The response was: " \
"%(status)s %(reason)s - %(body)s" % err.message
raise CommandError(message, blogger.server + query.feed,
err.message["status"])
for (i, entry) in enumerate(feed.entry):
# this basically gets the unique post ID from the URL to itself
# and pulls the ID off the end.
post_id = entry.GetSelfLink().href.split("/")[-1]
# Skip duplicate posts. Important for the last query.
if post_id in processed_posts:
continue
title = entry.title.text
content = entry.content.text
# this strips off the time zone info off the end as we want UTC
clean_date = entry.published.text[:re.search(r"\.\d{3}",
entry.published.text).end()]
published_date = self.parse_datetime(clean_date)
# TODO - issues with content not generating correct <P> tags
tags = [tag.term for tag in entry.category]
post = self.add_post(title=title, content=content,
pub_date=published_date, tags=tags)
# get the comments from the post feed and then add them to
# the post details
comment_url = "/feeds/%s/%s/comments/full?max-results=1000"
comments = blogger.Get(comment_url % (blog_id, post_id))
for comment in comments.entry:
email = comment.author[0].email.text
author_name = comment.author[0].name.text
# Strip off the time zone info off the end as we want UTC
clean_date = comment.published.text[:re.search(r"\.\d{3}",
comment.published.text).end()]
comment_date = self.parse_datetime(clean_date)
website = ""
if comment.author[0].uri:
website = comment.author[0].uri.text
body = comment.content.text
# add the comment as a dict to the end of the comments list
self.add_comment(post=post, name=author_name, email=email,
body=body, website=website,
pub_date=comment_date)
processed_posts.append(post_id)
new_posts += 1
start_index += 500
|
python
|
def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get("blog_id")
if blog_id is None:
raise CommandError("Usage is import_blogger %s" % self.args)
try:
from gdata import service
except ImportError:
raise CommandError("Could not import the gdata library.")
blogger = service.GDataService()
blogger.service = "blogger"
blogger.server = "www.blogger.com"
start_index = 1
processed_posts = []
new_posts = 1
while new_posts:
new_posts = 0
query = service.Query()
query.feed = "/feeds/%s/posts/full" % blog_id
query.max_results = 500
query.start_index = start_index
try:
feed = blogger.Get(query.ToUri())
except service.RequestError as err:
message = "There was a service error. The response was: " \
"%(status)s %(reason)s - %(body)s" % err.message
raise CommandError(message, blogger.server + query.feed,
err.message["status"])
for (i, entry) in enumerate(feed.entry):
# this basically gets the unique post ID from the URL to itself
# and pulls the ID off the end.
post_id = entry.GetSelfLink().href.split("/")[-1]
# Skip duplicate posts. Important for the last query.
if post_id in processed_posts:
continue
title = entry.title.text
content = entry.content.text
# this strips off the time zone info off the end as we want UTC
clean_date = entry.published.text[:re.search(r"\.\d{3}",
entry.published.text).end()]
published_date = self.parse_datetime(clean_date)
# TODO - issues with content not generating correct <P> tags
tags = [tag.term for tag in entry.category]
post = self.add_post(title=title, content=content,
pub_date=published_date, tags=tags)
# get the comments from the post feed and then add them to
# the post details
comment_url = "/feeds/%s/%s/comments/full?max-results=1000"
comments = blogger.Get(comment_url % (blog_id, post_id))
for comment in comments.entry:
email = comment.author[0].email.text
author_name = comment.author[0].name.text
# Strip off the time zone info off the end as we want UTC
clean_date = comment.published.text[:re.search(r"\.\d{3}",
comment.published.text).end()]
comment_date = self.parse_datetime(clean_date)
website = ""
if comment.author[0].uri:
website = comment.author[0].uri.text
body = comment.content.text
# add the comment as a dict to the end of the comments list
self.add_comment(post=post, name=author_name, email=email,
body=body, website=website,
pub_date=comment_date)
processed_posts.append(post_id)
new_posts += 1
start_index += 500
|
[
"def",
"handle_import",
"(",
"self",
",",
"options",
")",
":",
"blog_id",
"=",
"options",
".",
"get",
"(",
"\"blog_id\"",
")",
"if",
"blog_id",
"is",
"None",
":",
"raise",
"CommandError",
"(",
"\"Usage is import_blogger %s\"",
"%",
"self",
".",
"args",
")",
"try",
":",
"from",
"gdata",
"import",
"service",
"except",
"ImportError",
":",
"raise",
"CommandError",
"(",
"\"Could not import the gdata library.\"",
")",
"blogger",
"=",
"service",
".",
"GDataService",
"(",
")",
"blogger",
".",
"service",
"=",
"\"blogger\"",
"blogger",
".",
"server",
"=",
"\"www.blogger.com\"",
"start_index",
"=",
"1",
"processed_posts",
"=",
"[",
"]",
"new_posts",
"=",
"1",
"while",
"new_posts",
":",
"new_posts",
"=",
"0",
"query",
"=",
"service",
".",
"Query",
"(",
")",
"query",
".",
"feed",
"=",
"\"/feeds/%s/posts/full\"",
"%",
"blog_id",
"query",
".",
"max_results",
"=",
"500",
"query",
".",
"start_index",
"=",
"start_index",
"try",
":",
"feed",
"=",
"blogger",
".",
"Get",
"(",
"query",
".",
"ToUri",
"(",
")",
")",
"except",
"service",
".",
"RequestError",
"as",
"err",
":",
"message",
"=",
"\"There was a service error. The response was: \"",
"\"%(status)s %(reason)s - %(body)s\"",
"%",
"err",
".",
"message",
"raise",
"CommandError",
"(",
"message",
",",
"blogger",
".",
"server",
"+",
"query",
".",
"feed",
",",
"err",
".",
"message",
"[",
"\"status\"",
"]",
")",
"for",
"(",
"i",
",",
"entry",
")",
"in",
"enumerate",
"(",
"feed",
".",
"entry",
")",
":",
"# this basically gets the unique post ID from the URL to itself",
"# and pulls the ID off the end.",
"post_id",
"=",
"entry",
".",
"GetSelfLink",
"(",
")",
".",
"href",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"# Skip duplicate posts. Important for the last query.",
"if",
"post_id",
"in",
"processed_posts",
":",
"continue",
"title",
"=",
"entry",
".",
"title",
".",
"text",
"content",
"=",
"entry",
".",
"content",
".",
"text",
"# this strips off the time zone info off the end as we want UTC",
"clean_date",
"=",
"entry",
".",
"published",
".",
"text",
"[",
":",
"re",
".",
"search",
"(",
"r\"\\.\\d{3}\"",
",",
"entry",
".",
"published",
".",
"text",
")",
".",
"end",
"(",
")",
"]",
"published_date",
"=",
"self",
".",
"parse_datetime",
"(",
"clean_date",
")",
"# TODO - issues with content not generating correct <P> tags",
"tags",
"=",
"[",
"tag",
".",
"term",
"for",
"tag",
"in",
"entry",
".",
"category",
"]",
"post",
"=",
"self",
".",
"add_post",
"(",
"title",
"=",
"title",
",",
"content",
"=",
"content",
",",
"pub_date",
"=",
"published_date",
",",
"tags",
"=",
"tags",
")",
"# get the comments from the post feed and then add them to",
"# the post details",
"comment_url",
"=",
"\"/feeds/%s/%s/comments/full?max-results=1000\"",
"comments",
"=",
"blogger",
".",
"Get",
"(",
"comment_url",
"%",
"(",
"blog_id",
",",
"post_id",
")",
")",
"for",
"comment",
"in",
"comments",
".",
"entry",
":",
"email",
"=",
"comment",
".",
"author",
"[",
"0",
"]",
".",
"email",
".",
"text",
"author_name",
"=",
"comment",
".",
"author",
"[",
"0",
"]",
".",
"name",
".",
"text",
"# Strip off the time zone info off the end as we want UTC",
"clean_date",
"=",
"comment",
".",
"published",
".",
"text",
"[",
":",
"re",
".",
"search",
"(",
"r\"\\.\\d{3}\"",
",",
"comment",
".",
"published",
".",
"text",
")",
".",
"end",
"(",
")",
"]",
"comment_date",
"=",
"self",
".",
"parse_datetime",
"(",
"clean_date",
")",
"website",
"=",
"\"\"",
"if",
"comment",
".",
"author",
"[",
"0",
"]",
".",
"uri",
":",
"website",
"=",
"comment",
".",
"author",
"[",
"0",
"]",
".",
"uri",
".",
"text",
"body",
"=",
"comment",
".",
"content",
".",
"text",
"# add the comment as a dict to the end of the comments list",
"self",
".",
"add_comment",
"(",
"post",
"=",
"post",
",",
"name",
"=",
"author_name",
",",
"email",
"=",
"email",
",",
"body",
"=",
"body",
",",
"website",
"=",
"website",
",",
"pub_date",
"=",
"comment_date",
")",
"processed_posts",
".",
"append",
"(",
"post_id",
")",
"new_posts",
"+=",
"1",
"start_index",
"+=",
"500"
] |
Gets posts from Blogger.
|
[
"Gets",
"posts",
"from",
"Blogger",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_blogger.py#L25-L113
|
246,006
|
fedora-infra/fmn.lib
|
fmn/lib/__init__.py
|
recipients
|
def recipients(preferences, message, valid_paths, config):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
rule_cache = dict()
results = defaultdict(list)
notified = set()
for preference in preferences:
user = preference['user']
context = preference['context']
if (user['openid'], context['name']) in notified:
continue
for filter in preference['filters']:
if matches(filter, message, valid_paths, rule_cache, config):
for detail_value in preference['detail_values']:
results[context['name']].append({
'user': user['openid'],
context['detail_name']: detail_value,
'filter_name': filter['name'],
'filter_id': filter['id'],
'filter_oneshot': filter['oneshot'],
'markup_messages': preference['markup_messages'],
'triggered_by_links': preference['triggered_by_links'],
'shorten_links': preference['shorten_links'],
'verbose': preference['verbose'],
})
notified.add((user['openid'], context['name']))
break
return results
|
python
|
def recipients(preferences, message, valid_paths, config):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
rule_cache = dict()
results = defaultdict(list)
notified = set()
for preference in preferences:
user = preference['user']
context = preference['context']
if (user['openid'], context['name']) in notified:
continue
for filter in preference['filters']:
if matches(filter, message, valid_paths, rule_cache, config):
for detail_value in preference['detail_values']:
results[context['name']].append({
'user': user['openid'],
context['detail_name']: detail_value,
'filter_name': filter['name'],
'filter_id': filter['id'],
'filter_oneshot': filter['oneshot'],
'markup_messages': preference['markup_messages'],
'triggered_by_links': preference['triggered_by_links'],
'shorten_links': preference['shorten_links'],
'verbose': preference['verbose'],
})
notified.add((user['openid'], context['name']))
break
return results
|
[
"def",
"recipients",
"(",
"preferences",
",",
"message",
",",
"valid_paths",
",",
"config",
")",
":",
"rule_cache",
"=",
"dict",
"(",
")",
"results",
"=",
"defaultdict",
"(",
"list",
")",
"notified",
"=",
"set",
"(",
")",
"for",
"preference",
"in",
"preferences",
":",
"user",
"=",
"preference",
"[",
"'user'",
"]",
"context",
"=",
"preference",
"[",
"'context'",
"]",
"if",
"(",
"user",
"[",
"'openid'",
"]",
",",
"context",
"[",
"'name'",
"]",
")",
"in",
"notified",
":",
"continue",
"for",
"filter",
"in",
"preference",
"[",
"'filters'",
"]",
":",
"if",
"matches",
"(",
"filter",
",",
"message",
",",
"valid_paths",
",",
"rule_cache",
",",
"config",
")",
":",
"for",
"detail_value",
"in",
"preference",
"[",
"'detail_values'",
"]",
":",
"results",
"[",
"context",
"[",
"'name'",
"]",
"]",
".",
"append",
"(",
"{",
"'user'",
":",
"user",
"[",
"'openid'",
"]",
",",
"context",
"[",
"'detail_name'",
"]",
":",
"detail_value",
",",
"'filter_name'",
":",
"filter",
"[",
"'name'",
"]",
",",
"'filter_id'",
":",
"filter",
"[",
"'id'",
"]",
",",
"'filter_oneshot'",
":",
"filter",
"[",
"'oneshot'",
"]",
",",
"'markup_messages'",
":",
"preference",
"[",
"'markup_messages'",
"]",
",",
"'triggered_by_links'",
":",
"preference",
"[",
"'triggered_by_links'",
"]",
",",
"'shorten_links'",
":",
"preference",
"[",
"'shorten_links'",
"]",
",",
"'verbose'",
":",
"preference",
"[",
"'verbose'",
"]",
",",
"}",
")",
"notified",
".",
"add",
"(",
"(",
"user",
"[",
"'openid'",
"]",
",",
"context",
"[",
"'name'",
"]",
")",
")",
"break",
"return",
"results"
] |
The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
|
[
"The",
"main",
"API",
"function",
"."
] |
3120725556153d07c1809530f0fadcf250439110
|
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L29-L64
|
246,007
|
fedora-infra/fmn.lib
|
fmn/lib/__init__.py
|
matches
|
def matches(filter, message, valid_paths, rule_cache, config):
""" Returns True if the given filter matches the given message. """
if not filter['rules']:
return False
for rule in filter['rules']:
fn = rule['fn']
negated = rule['negated']
arguments = rule['arguments']
rule_cache_key = rule['cache_key']
try:
if rule_cache_key not in rule_cache:
value = fn(config, message, **arguments)
if negated:
value = not value
rule_cache[rule_cache_key] = value
if not rule_cache[rule_cache_key]:
return False
except Exception as e:
log.exception(e)
# If something throws an exception then we do *not* have a match.
return False
# Then all rules matched on this filter..
return True
|
python
|
def matches(filter, message, valid_paths, rule_cache, config):
""" Returns True if the given filter matches the given message. """
if not filter['rules']:
return False
for rule in filter['rules']:
fn = rule['fn']
negated = rule['negated']
arguments = rule['arguments']
rule_cache_key = rule['cache_key']
try:
if rule_cache_key not in rule_cache:
value = fn(config, message, **arguments)
if negated:
value = not value
rule_cache[rule_cache_key] = value
if not rule_cache[rule_cache_key]:
return False
except Exception as e:
log.exception(e)
# If something throws an exception then we do *not* have a match.
return False
# Then all rules matched on this filter..
return True
|
[
"def",
"matches",
"(",
"filter",
",",
"message",
",",
"valid_paths",
",",
"rule_cache",
",",
"config",
")",
":",
"if",
"not",
"filter",
"[",
"'rules'",
"]",
":",
"return",
"False",
"for",
"rule",
"in",
"filter",
"[",
"'rules'",
"]",
":",
"fn",
"=",
"rule",
"[",
"'fn'",
"]",
"negated",
"=",
"rule",
"[",
"'negated'",
"]",
"arguments",
"=",
"rule",
"[",
"'arguments'",
"]",
"rule_cache_key",
"=",
"rule",
"[",
"'cache_key'",
"]",
"try",
":",
"if",
"rule_cache_key",
"not",
"in",
"rule_cache",
":",
"value",
"=",
"fn",
"(",
"config",
",",
"message",
",",
"*",
"*",
"arguments",
")",
"if",
"negated",
":",
"value",
"=",
"not",
"value",
"rule_cache",
"[",
"rule_cache_key",
"]",
"=",
"value",
"if",
"not",
"rule_cache",
"[",
"rule_cache_key",
"]",
":",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"# If something throws an exception then we do *not* have a match.",
"return",
"False",
"# Then all rules matched on this filter..",
"return",
"True"
] |
Returns True if the given filter matches the given message.
|
[
"Returns",
"True",
"if",
"the",
"given",
"filter",
"matches",
"the",
"given",
"message",
"."
] |
3120725556153d07c1809530f0fadcf250439110
|
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L67-L94
|
246,008
|
fedora-infra/fmn.lib
|
fmn/lib/__init__.py
|
load_preferences
|
def load_preferences(session, config, valid_paths,
cull_disabled=False, openid=None,
cull_backends=None):
""" Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
loads, practically, the whole database. However, if an openid string is
submitted, then only the preferences of that user are returned (and this is
less expensive).
"""
cull_backends = cull_backends or []
query = session.query(fmn.lib.models.Preference)
if openid:
query = query.filter(fmn.lib.models.Preference.openid==openid)
preferences = query.all()
return [
preference.__json__(reify=True)
for preference in preferences
if (
preference.context.name in config['fmn.backends']
and preference.context.name not in cull_backends
and (not cull_disabled or preference.enabled)
)
]
|
python
|
def load_preferences(session, config, valid_paths,
cull_disabled=False, openid=None,
cull_backends=None):
""" Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
loads, practically, the whole database. However, if an openid string is
submitted, then only the preferences of that user are returned (and this is
less expensive).
"""
cull_backends = cull_backends or []
query = session.query(fmn.lib.models.Preference)
if openid:
query = query.filter(fmn.lib.models.Preference.openid==openid)
preferences = query.all()
return [
preference.__json__(reify=True)
for preference in preferences
if (
preference.context.name in config['fmn.backends']
and preference.context.name not in cull_backends
and (not cull_disabled or preference.enabled)
)
]
|
[
"def",
"load_preferences",
"(",
"session",
",",
"config",
",",
"valid_paths",
",",
"cull_disabled",
"=",
"False",
",",
"openid",
"=",
"None",
",",
"cull_backends",
"=",
"None",
")",
":",
"cull_backends",
"=",
"cull_backends",
"or",
"[",
"]",
"query",
"=",
"session",
".",
"query",
"(",
"fmn",
".",
"lib",
".",
"models",
".",
"Preference",
")",
"if",
"openid",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"fmn",
".",
"lib",
".",
"models",
".",
"Preference",
".",
"openid",
"==",
"openid",
")",
"preferences",
"=",
"query",
".",
"all",
"(",
")",
"return",
"[",
"preference",
".",
"__json__",
"(",
"reify",
"=",
"True",
")",
"for",
"preference",
"in",
"preferences",
"if",
"(",
"preference",
".",
"context",
".",
"name",
"in",
"config",
"[",
"'fmn.backends'",
"]",
"and",
"preference",
".",
"context",
".",
"name",
"not",
"in",
"cull_backends",
"and",
"(",
"not",
"cull_disabled",
"or",
"preference",
".",
"enabled",
")",
")",
"]"
] |
Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
loads, practically, the whole database. However, if an openid string is
submitted, then only the preferences of that user are returned (and this is
less expensive).
|
[
"Every",
"rule",
"for",
"every",
"filter",
"for",
"every",
"context",
"for",
"every",
"user",
"."
] |
3120725556153d07c1809530f0fadcf250439110
|
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L97-L127
|
246,009
|
fedora-infra/fmn.lib
|
fmn/lib/__init__.py
|
load_rules
|
def load_rules(root='fmn.rules'):
""" Load the big list of allowed callable rules. """
module = __import__(root, fromlist=[root.split('.')[0]])
hinting_helpers = fmn.lib.hinting.__dict__.values()
rules = {}
for name in dir(module):
obj = getattr(module, name)
# Ignore non-callables.
if not callable(obj):
continue
# Ignore our decorator and its friends
if obj in hinting_helpers:
continue
doc = inspect.getdoc(obj)
# It's crazy, but inspect (stdlib!) doesn't return unicode objs on py2.
if doc and hasattr(doc, 'decode'):
doc = doc.decode('utf-8')
if doc:
# If we have a docstring, then mark it up beautifully for display
# in the web app.
# FWIW, this should probably be moved into fmn.web since nowhere
# else are we going to want HTML... we'll still want raw .rst.
title, doc_as_rst = doc.split('\n', 1)
doc = docutils.examples.html_parts(doc_as_rst)['body']
soup = bs4.BeautifulSoup(doc, 'html5lib')
doc_no_links = ''.join(map(six.text_type, strip_anchor_tags(soup)))
doc = markupsafe.Markup(doc)
doc_no_links = markupsafe.Markup(doc_no_links)
else:
title = "UNDOCUMENTED"
doc = "No docs for %s:%s %r" % (root, name, obj)
doc_no_links = doc
rules[name] = {
'func': obj,
'submodule': obj.__module__.split('.')[-1],
'title': title.strip(),
'doc': doc.strip(),
'doc-no-links': doc_no_links.strip(),
'args': inspect.getargspec(obj)[0],
'datanommer-hints': getattr(obj, 'hints', {}),
'hints-invertible': getattr(obj, 'hinting_invertible', True),
'hints-callable': getattr(obj, 'hinting_callable', None),
}
rules = OrderedDict(
sorted(rules.items(), key=lambda x: x[1]['title'])
)
return {root: rules}
|
python
|
def load_rules(root='fmn.rules'):
""" Load the big list of allowed callable rules. """
module = __import__(root, fromlist=[root.split('.')[0]])
hinting_helpers = fmn.lib.hinting.__dict__.values()
rules = {}
for name in dir(module):
obj = getattr(module, name)
# Ignore non-callables.
if not callable(obj):
continue
# Ignore our decorator and its friends
if obj in hinting_helpers:
continue
doc = inspect.getdoc(obj)
# It's crazy, but inspect (stdlib!) doesn't return unicode objs on py2.
if doc and hasattr(doc, 'decode'):
doc = doc.decode('utf-8')
if doc:
# If we have a docstring, then mark it up beautifully for display
# in the web app.
# FWIW, this should probably be moved into fmn.web since nowhere
# else are we going to want HTML... we'll still want raw .rst.
title, doc_as_rst = doc.split('\n', 1)
doc = docutils.examples.html_parts(doc_as_rst)['body']
soup = bs4.BeautifulSoup(doc, 'html5lib')
doc_no_links = ''.join(map(six.text_type, strip_anchor_tags(soup)))
doc = markupsafe.Markup(doc)
doc_no_links = markupsafe.Markup(doc_no_links)
else:
title = "UNDOCUMENTED"
doc = "No docs for %s:%s %r" % (root, name, obj)
doc_no_links = doc
rules[name] = {
'func': obj,
'submodule': obj.__module__.split('.')[-1],
'title': title.strip(),
'doc': doc.strip(),
'doc-no-links': doc_no_links.strip(),
'args': inspect.getargspec(obj)[0],
'datanommer-hints': getattr(obj, 'hints', {}),
'hints-invertible': getattr(obj, 'hinting_invertible', True),
'hints-callable': getattr(obj, 'hinting_callable', None),
}
rules = OrderedDict(
sorted(rules.items(), key=lambda x: x[1]['title'])
)
return {root: rules}
|
[
"def",
"load_rules",
"(",
"root",
"=",
"'fmn.rules'",
")",
":",
"module",
"=",
"__import__",
"(",
"root",
",",
"fromlist",
"=",
"[",
"root",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"]",
")",
"hinting_helpers",
"=",
"fmn",
".",
"lib",
".",
"hinting",
".",
"__dict__",
".",
"values",
"(",
")",
"rules",
"=",
"{",
"}",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
":",
"obj",
"=",
"getattr",
"(",
"module",
",",
"name",
")",
"# Ignore non-callables.",
"if",
"not",
"callable",
"(",
"obj",
")",
":",
"continue",
"# Ignore our decorator and its friends",
"if",
"obj",
"in",
"hinting_helpers",
":",
"continue",
"doc",
"=",
"inspect",
".",
"getdoc",
"(",
"obj",
")",
"# It's crazy, but inspect (stdlib!) doesn't return unicode objs on py2.",
"if",
"doc",
"and",
"hasattr",
"(",
"doc",
",",
"'decode'",
")",
":",
"doc",
"=",
"doc",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"doc",
":",
"# If we have a docstring, then mark it up beautifully for display",
"# in the web app.",
"# FWIW, this should probably be moved into fmn.web since nowhere",
"# else are we going to want HTML... we'll still want raw .rst.",
"title",
",",
"doc_as_rst",
"=",
"doc",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"doc",
"=",
"docutils",
".",
"examples",
".",
"html_parts",
"(",
"doc_as_rst",
")",
"[",
"'body'",
"]",
"soup",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"doc",
",",
"'html5lib'",
")",
"doc_no_links",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"six",
".",
"text_type",
",",
"strip_anchor_tags",
"(",
"soup",
")",
")",
")",
"doc",
"=",
"markupsafe",
".",
"Markup",
"(",
"doc",
")",
"doc_no_links",
"=",
"markupsafe",
".",
"Markup",
"(",
"doc_no_links",
")",
"else",
":",
"title",
"=",
"\"UNDOCUMENTED\"",
"doc",
"=",
"\"No docs for %s:%s %r\"",
"%",
"(",
"root",
",",
"name",
",",
"obj",
")",
"doc_no_links",
"=",
"doc",
"rules",
"[",
"name",
"]",
"=",
"{",
"'func'",
":",
"obj",
",",
"'submodule'",
":",
"obj",
".",
"__module__",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
",",
"'title'",
":",
"title",
".",
"strip",
"(",
")",
",",
"'doc'",
":",
"doc",
".",
"strip",
"(",
")",
",",
"'doc-no-links'",
":",
"doc_no_links",
".",
"strip",
"(",
")",
",",
"'args'",
":",
"inspect",
".",
"getargspec",
"(",
"obj",
")",
"[",
"0",
"]",
",",
"'datanommer-hints'",
":",
"getattr",
"(",
"obj",
",",
"'hints'",
",",
"{",
"}",
")",
",",
"'hints-invertible'",
":",
"getattr",
"(",
"obj",
",",
"'hinting_invertible'",
",",
"True",
")",
",",
"'hints-callable'",
":",
"getattr",
"(",
"obj",
",",
"'hinting_callable'",
",",
"None",
")",
",",
"}",
"rules",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"rules",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
"[",
"'title'",
"]",
")",
")",
"return",
"{",
"root",
":",
"rules",
"}"
] |
Load the big list of allowed callable rules.
|
[
"Load",
"the",
"big",
"list",
"of",
"allowed",
"callable",
"rules",
"."
] |
3120725556153d07c1809530f0fadcf250439110
|
https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L130-L187
|
246,010
|
TaurusOlson/fntools
|
fntools/fntools.py
|
use_with
|
def use_with(data, fn, *attrs):
"""Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
Usage::
>>> make_csv_row = lambda n, a, g: '%s,%d,%s' % (n, a, g)
>>> use_with(alice, make_csv_row, 'name', 'age', 'gender')
'Alice,30,F'
"""
args = [getattr(data, x) for x in attrs]
return fn(*args)
|
python
|
def use_with(data, fn, *attrs):
"""Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
Usage::
>>> make_csv_row = lambda n, a, g: '%s,%d,%s' % (n, a, g)
>>> use_with(alice, make_csv_row, 'name', 'age', 'gender')
'Alice,30,F'
"""
args = [getattr(data, x) for x in attrs]
return fn(*args)
|
[
"def",
"use_with",
"(",
"data",
",",
"fn",
",",
"*",
"attrs",
")",
":",
"args",
"=",
"[",
"getattr",
"(",
"data",
",",
"x",
")",
"for",
"x",
"in",
"attrs",
"]",
"return",
"fn",
"(",
"*",
"args",
")"
] |
Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
Usage::
>>> make_csv_row = lambda n, a, g: '%s,%d,%s' % (n, a, g)
>>> use_with(alice, make_csv_row, 'name', 'age', 'gender')
'Alice,30,F'
|
[
"Apply",
"a",
"function",
"on",
"the",
"attributes",
"of",
"the",
"data"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L26-L48
|
246,011
|
TaurusOlson/fntools
|
fntools/fntools.py
|
rmap
|
def rmap(fn, coll, is_iterable=None):
"""A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
"""
result = []
for x in coll:
if is_iterable is None:
is_iterable = isiterable
if is_iterable(x):
y = rmap(fn, x)
else:
y = fn(x)
result.append(y)
return result
|
python
|
def rmap(fn, coll, is_iterable=None):
"""A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
"""
result = []
for x in coll:
if is_iterable is None:
is_iterable = isiterable
if is_iterable(x):
y = rmap(fn, x)
else:
y = fn(x)
result.append(y)
return result
|
[
"def",
"rmap",
"(",
"fn",
",",
"coll",
",",
"is_iterable",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"coll",
":",
"if",
"is_iterable",
"is",
"None",
":",
"is_iterable",
"=",
"isiterable",
"if",
"is_iterable",
"(",
"x",
")",
":",
"y",
"=",
"rmap",
"(",
"fn",
",",
"x",
")",
"else",
":",
"y",
"=",
"fn",
"(",
"x",
")",
"result",
".",
"append",
"(",
"y",
")",
"return",
"result"
] |
A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
|
[
"A",
"recursive",
"map"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L129-L151
|
246,012
|
TaurusOlson/fntools
|
fntools/fntools.py
|
compose
|
def compose(*fns):
"""Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))
which means that the last function provided is the first to be applied.
"""
def compose2(f, g):
return lambda x: f(g(x))
return reduce(compose2, fns)
|
python
|
def compose(*fns):
"""Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))
which means that the last function provided is the first to be applied.
"""
def compose2(f, g):
return lambda x: f(g(x))
return reduce(compose2, fns)
|
[
"def",
"compose",
"(",
"*",
"fns",
")",
":",
"def",
"compose2",
"(",
"f",
",",
"g",
")",
":",
"return",
"lambda",
"x",
":",
"f",
"(",
"g",
"(",
"x",
")",
")",
"return",
"reduce",
"(",
"compose2",
",",
"fns",
")"
] |
Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))
which means that the last function provided is the first to be applied.
|
[
"Return",
"the",
"function",
"composed",
"with",
"the",
"given",
"functions"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L174-L192
|
246,013
|
TaurusOlson/fntools
|
fntools/fntools.py
|
groupby
|
def groupby(fn, coll):
"""Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']}
"""
d = collections.defaultdict(list)
for item in coll:
key = fn(item)
d[key].append(item)
return dict(d)
|
python
|
def groupby(fn, coll):
"""Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']}
"""
d = collections.defaultdict(list)
for item in coll:
key = fn(item)
d[key].append(item)
return dict(d)
|
[
"def",
"groupby",
"(",
"fn",
",",
"coll",
")",
":",
"d",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"coll",
":",
"key",
"=",
"fn",
"(",
"item",
")",
"d",
"[",
"key",
"]",
".",
"append",
"(",
"item",
")",
"return",
"dict",
"(",
"d",
")"
] |
Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']}
|
[
"Group",
"elements",
"in",
"sub",
"-",
"collections",
"by",
"fn"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L195-L210
|
246,014
|
TaurusOlson/fntools
|
fntools/fntools.py
|
reductions
|
def reductions(fn, seq, acc=None):
"""Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[11, 13, 16]
"""
indexes = xrange(len(seq))
if acc:
return map(lambda i: reduce(lambda x, y: fn(x, y), seq[:i+1], acc), indexes)
else:
return map(lambda i: reduce(lambda x, y: fn(x, y), seq[:i+1]), indexes)
|
python
|
def reductions(fn, seq, acc=None):
"""Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[11, 13, 16]
"""
indexes = xrange(len(seq))
if acc:
return map(lambda i: reduce(lambda x, y: fn(x, y), seq[:i+1], acc), indexes)
else:
return map(lambda i: reduce(lambda x, y: fn(x, y), seq[:i+1]), indexes)
|
[
"def",
"reductions",
"(",
"fn",
",",
"seq",
",",
"acc",
"=",
"None",
")",
":",
"indexes",
"=",
"xrange",
"(",
"len",
"(",
"seq",
")",
")",
"if",
"acc",
":",
"return",
"map",
"(",
"lambda",
"i",
":",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"fn",
"(",
"x",
",",
"y",
")",
",",
"seq",
"[",
":",
"i",
"+",
"1",
"]",
",",
"acc",
")",
",",
"indexes",
")",
"else",
":",
"return",
"map",
"(",
"lambda",
"i",
":",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"fn",
"(",
"x",
",",
"y",
")",
",",
"seq",
"[",
":",
"i",
"+",
"1",
"]",
")",
",",
"indexes",
")"
] |
Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[11, 13, 16]
|
[
"Return",
"the",
"intermediate",
"values",
"of",
"a",
"reduction"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L213-L232
|
246,015
|
TaurusOlson/fntools
|
fntools/fntools.py
|
split
|
def split(coll, factor):
"""Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>>> split(bands, styles)
{'classic': ['Debussy', 'Bach'], 'rock': ['Led Zeppelin', 'Metallica', 'Iron Maiden']}
"""
groups = groupby(lambda x: x[0], itertools.izip(factor, coll))
return dmap(lambda x: [y[1] for y in x], groups)
|
python
|
def split(coll, factor):
"""Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>>> split(bands, styles)
{'classic': ['Debussy', 'Bach'], 'rock': ['Led Zeppelin', 'Metallica', 'Iron Maiden']}
"""
groups = groupby(lambda x: x[0], itertools.izip(factor, coll))
return dmap(lambda x: [y[1] for y in x], groups)
|
[
"def",
"split",
"(",
"coll",
",",
"factor",
")",
":",
"groups",
"=",
"groupby",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
",",
"itertools",
".",
"izip",
"(",
"factor",
",",
"coll",
")",
")",
"return",
"dmap",
"(",
"lambda",
"x",
":",
"[",
"y",
"[",
"1",
"]",
"for",
"y",
"in",
"x",
"]",
",",
"groups",
")"
] |
Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>>> split(bands, styles)
{'classic': ['Debussy', 'Bach'], 'rock': ['Led Zeppelin', 'Metallica', 'Iron Maiden']}
|
[
"Split",
"a",
"collection",
"by",
"using",
"a",
"factor"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L235-L249
|
246,016
|
TaurusOlson/fntools
|
fntools/fntools.py
|
assoc
|
def assoc(_d, key, value):
"""Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': 'Holy Grail'}
>>> data
{}
.. note:: the original dictionary is not modified
"""
d = deepcopy(_d)
d[key] = value
return d
|
python
|
def assoc(_d, key, value):
"""Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': 'Holy Grail'}
>>> data
{}
.. note:: the original dictionary is not modified
"""
d = deepcopy(_d)
d[key] = value
return d
|
[
"def",
"assoc",
"(",
"_d",
",",
"key",
",",
"value",
")",
":",
"d",
"=",
"deepcopy",
"(",
"_d",
")",
"d",
"[",
"key",
"]",
"=",
"value",
"return",
"d"
] |
Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': 'Holy Grail'}
>>> data
{}
.. note:: the original dictionary is not modified
|
[
"Associate",
"a",
"key",
"with",
"a",
"value",
"in",
"a",
"dictionary"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L252-L272
|
246,017
|
TaurusOlson/fntools
|
fntools/fntools.py
|
pipe
|
def pipe(data, *fns):
"""Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43'
"""
return reduce(lambda acc, f: f(acc), fns, data)
|
python
|
def pipe(data, *fns):
"""Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43'
"""
return reduce(lambda acc, f: f(acc), fns, data)
|
[
"def",
"pipe",
"(",
"data",
",",
"*",
"fns",
")",
":",
"return",
"reduce",
"(",
"lambda",
"acc",
",",
"f",
":",
"f",
"(",
"acc",
")",
",",
"fns",
",",
"data",
")"
] |
Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43'
|
[
"Apply",
"functions",
"recursively",
"on",
"your",
"data"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L332-L344
|
246,018
|
TaurusOlson/fntools
|
fntools/fntools.py
|
update
|
def update(records, column, values):
"""Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> new_movies = update(movies, 'budget', lambda x: 2*x)
>>> [new_movies[i]['budget'] for i,_ in enumerate(movies)]
[800000.0, 8000000.0, 18000000.0]
>>> new_movies2 = update(movies, 'budget', (40, 400, 900))
>>> [new_movies2[i]['budget'] for i,_ in enumerate(movies)]
[40, 400, 900]
"""
new_records = deepcopy(records)
if values.__class__.__name__ == 'function':
for row in new_records:
row[column] = values(row[column])
elif isiterable(values):
for i, row in enumerate(new_records):
row[column] = values[i]
else:
msg = "You must provide a function or an iterable."
raise ValueError(msg)
return new_records
|
python
|
def update(records, column, values):
"""Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> new_movies = update(movies, 'budget', lambda x: 2*x)
>>> [new_movies[i]['budget'] for i,_ in enumerate(movies)]
[800000.0, 8000000.0, 18000000.0]
>>> new_movies2 = update(movies, 'budget', (40, 400, 900))
>>> [new_movies2[i]['budget'] for i,_ in enumerate(movies)]
[40, 400, 900]
"""
new_records = deepcopy(records)
if values.__class__.__name__ == 'function':
for row in new_records:
row[column] = values(row[column])
elif isiterable(values):
for i, row in enumerate(new_records):
row[column] = values[i]
else:
msg = "You must provide a function or an iterable."
raise ValueError(msg)
return new_records
|
[
"def",
"update",
"(",
"records",
",",
"column",
",",
"values",
")",
":",
"new_records",
"=",
"deepcopy",
"(",
"records",
")",
"if",
"values",
".",
"__class__",
".",
"__name__",
"==",
"'function'",
":",
"for",
"row",
"in",
"new_records",
":",
"row",
"[",
"column",
"]",
"=",
"values",
"(",
"row",
"[",
"column",
"]",
")",
"elif",
"isiterable",
"(",
"values",
")",
":",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"new_records",
")",
":",
"row",
"[",
"column",
"]",
"=",
"values",
"[",
"i",
"]",
"else",
":",
"msg",
"=",
"\"You must provide a function or an iterable.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"new_records"
] |
Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> new_movies = update(movies, 'budget', lambda x: 2*x)
>>> [new_movies[i]['budget'] for i,_ in enumerate(movies)]
[800000.0, 8000000.0, 18000000.0]
>>> new_movies2 = update(movies, 'budget', (40, 400, 900))
>>> [new_movies2[i]['budget'] for i,_ in enumerate(movies)]
[40, 400, 900]
|
[
"Update",
"the",
"column",
"of",
"records"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L408-L441
|
246,019
|
TaurusOlson/fntools
|
fntools/fntools.py
|
duplicates
|
def duplicates(coll):
"""Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
"""
return list(set(x for x in coll if coll.count(x) > 1))
|
python
|
def duplicates(coll):
"""Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
"""
return list(set(x for x in coll if coll.count(x) > 1))
|
[
"def",
"duplicates",
"(",
"coll",
")",
":",
"return",
"list",
"(",
"set",
"(",
"x",
"for",
"x",
"in",
"coll",
"if",
"coll",
".",
"count",
"(",
"x",
")",
">",
"1",
")",
")"
] |
Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
|
[
"Return",
"the",
"duplicated",
"items",
"in",
"the",
"given",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L446-L456
|
246,020
|
TaurusOlson/fntools
|
fntools/fntools.py
|
pluck
|
def pluck(record, *keys, **kwargs):
"""Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> pluck(d, 'name', 'color')
{'color': 'blue', 'name': 'Lancelot'}
The keyword 'default' allows to replace a ``None`` value::
>>> d = {'year': 2014, 'movie': 'Bilbo'}
>>> pluck(d, 'year', 'movie', 'nb_aliens', default=0)
{'movie': 'Bilbo', 'nb_aliens': 0, 'year': 2014}
"""
default = kwargs.get('default', None)
return reduce(lambda a, x: assoc(a, x, record.get(x, default)), keys, {})
|
python
|
def pluck(record, *keys, **kwargs):
"""Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> pluck(d, 'name', 'color')
{'color': 'blue', 'name': 'Lancelot'}
The keyword 'default' allows to replace a ``None`` value::
>>> d = {'year': 2014, 'movie': 'Bilbo'}
>>> pluck(d, 'year', 'movie', 'nb_aliens', default=0)
{'movie': 'Bilbo', 'nb_aliens': 0, 'year': 2014}
"""
default = kwargs.get('default', None)
return reduce(lambda a, x: assoc(a, x, record.get(x, default)), keys, {})
|
[
"def",
"pluck",
"(",
"record",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"x",
":",
"assoc",
"(",
"a",
",",
"x",
",",
"record",
".",
"get",
"(",
"x",
",",
"default",
")",
")",
",",
"keys",
",",
"{",
"}",
")"
] |
Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> pluck(d, 'name', 'color')
{'color': 'blue', 'name': 'Lancelot'}
The keyword 'default' allows to replace a ``None`` value::
>>> d = {'year': 2014, 'movie': 'Bilbo'}
>>> pluck(d, 'year', 'movie', 'nb_aliens', default=0)
{'movie': 'Bilbo', 'nb_aliens': 0, 'year': 2014}
|
[
"Return",
"the",
"record",
"with",
"the",
"selected",
"keys"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L460-L479
|
246,021
|
TaurusOlson/fntools
|
fntools/fntools.py
|
pluck_each
|
def pluck_each(records, columns):
"""Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> pluck_each(movies, ('title', 'year'))
[{'year': 1975, 'title': 'The Holy Grail'}, {'year': 1979, 'title': 'Life of Brian'}, {'year': 1983, 'title': 'The Meaning of Life'}]
"""
return [pluck(records[i], *columns) for i, _ in enumerate(records)]
|
python
|
def pluck_each(records, columns):
"""Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> pluck_each(movies, ('title', 'year'))
[{'year': 1975, 'title': 'The Holy Grail'}, {'year': 1979, 'title': 'Life of Brian'}, {'year': 1983, 'title': 'The Meaning of Life'}]
"""
return [pluck(records[i], *columns) for i, _ in enumerate(records)]
|
[
"def",
"pluck_each",
"(",
"records",
",",
"columns",
")",
":",
"return",
"[",
"pluck",
"(",
"records",
"[",
"i",
"]",
",",
"*",
"columns",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"records",
")",
"]"
] |
Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
... ]
>>> pluck_each(movies, ('title', 'year'))
[{'year': 1975, 'title': 'The Holy Grail'}, {'year': 1979, 'title': 'Life of Brian'}, {'year': 1983, 'title': 'The Meaning of Life'}]
|
[
"Return",
"the",
"records",
"with",
"the",
"selected",
"columns"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L482-L498
|
246,022
|
TaurusOlson/fntools
|
fntools/fntools.py
|
use
|
def use(data, attrs):
"""Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singer'))
['Metallica', None, 'James Hetfield']
With a non dict data structure::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
>>> use(alice, ('name', 'gender'))
['Alice', 'F']
"""
if isinstance(data, dict):
if not isiterable(attrs):
attrs = [attrs]
coll = map(data.get, attrs)
else:
coll = map(lambda x: getattr(data, x), attrs)
return coll
|
python
|
def use(data, attrs):
"""Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singer'))
['Metallica', None, 'James Hetfield']
With a non dict data structure::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
>>> use(alice, ('name', 'gender'))
['Alice', 'F']
"""
if isinstance(data, dict):
if not isiterable(attrs):
attrs = [attrs]
coll = map(data.get, attrs)
else:
coll = map(lambda x: getattr(data, x), attrs)
return coll
|
[
"def",
"use",
"(",
"data",
",",
"attrs",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"not",
"isiterable",
"(",
"attrs",
")",
":",
"attrs",
"=",
"[",
"attrs",
"]",
"coll",
"=",
"map",
"(",
"data",
".",
"get",
",",
"attrs",
")",
"else",
":",
"coll",
"=",
"map",
"(",
"lambda",
"x",
":",
"getattr",
"(",
"data",
",",
"x",
")",
",",
"attrs",
")",
"return",
"coll"
] |
Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singer'))
['Metallica', None, 'James Hetfield']
With a non dict data structure::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gender'))
>>> alice = Person('Alice', 30, 'F')
>>> use(alice, ('name', 'gender'))
['Alice', 'F']
|
[
"Return",
"the",
"values",
"of",
"the",
"attributes",
"for",
"the",
"given",
"data"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L501-L529
|
246,023
|
TaurusOlson/fntools
|
fntools/fntools.py
|
get_in
|
def get_in(record, *keys, **kwargs):
"""Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> get_in(d, 'id', 'name')
'Lancelot'
>>> get_in(d, 'id', 'age', default='?')
'?'
"""
default = kwargs.get('default', None)
return reduce(lambda a, x: a.get(x, default), keys, record)
|
python
|
def get_in(record, *keys, **kwargs):
"""Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> get_in(d, 'id', 'name')
'Lancelot'
>>> get_in(d, 'id', 'age', default='?')
'?'
"""
default = kwargs.get('default', None)
return reduce(lambda a, x: a.get(x, default), keys, record)
|
[
"def",
"get_in",
"(",
"record",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"x",
":",
"a",
".",
"get",
"(",
"x",
",",
"default",
")",
",",
"keys",
",",
"record",
")"
] |
Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> get_in(d, 'id', 'name')
'Lancelot'
>>> get_in(d, 'id', 'age', default='?')
'?'
|
[
"Return",
"the",
"value",
"corresponding",
"to",
"the",
"keys",
"in",
"a",
"nested",
"record"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L532-L549
|
246,024
|
TaurusOlson/fntools
|
fntools/fntools.py
|
valueof
|
def valueof(records, key):
"""Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singer')
['Robert Plant', 'James Hetfield']
"""
if isinstance(records, dict):
records = [records]
return map(operator.itemgetter(key), records)
|
python
|
def valueof(records, key):
"""Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singer')
['Robert Plant', 'James Hetfield']
"""
if isinstance(records, dict):
records = [records]
return map(operator.itemgetter(key), records)
|
[
"def",
"valueof",
"(",
"records",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"records",
",",
"dict",
")",
":",
"records",
"=",
"[",
"records",
"]",
"return",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"key",
")",
",",
"records",
")"
] |
Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singer')
['Robert Plant', 'James Hetfield']
|
[
"Extract",
"the",
"value",
"corresponding",
"to",
"the",
"given",
"key",
"in",
"all",
"the",
"dictionaries"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L553-L564
|
246,025
|
TaurusOlson/fntools
|
fntools/fntools.py
|
find
|
def find(fn, record):
"""Apply a function on the record and return the corresponding new record
:param fn: a function
:param record: a dictionary
:returns: a dictionary
>>> find(max, {'Terry': 30, 'Graham': 35, 'John': 27})
{'Graham': 35}
"""
values_result = fn(record.values())
keys_result = [k for k, v in record.items() if v == values_result]
return {keys_result[0]: values_result}
|
python
|
def find(fn, record):
"""Apply a function on the record and return the corresponding new record
:param fn: a function
:param record: a dictionary
:returns: a dictionary
>>> find(max, {'Terry': 30, 'Graham': 35, 'John': 27})
{'Graham': 35}
"""
values_result = fn(record.values())
keys_result = [k for k, v in record.items() if v == values_result]
return {keys_result[0]: values_result}
|
[
"def",
"find",
"(",
"fn",
",",
"record",
")",
":",
"values_result",
"=",
"fn",
"(",
"record",
".",
"values",
"(",
")",
")",
"keys_result",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"record",
".",
"items",
"(",
")",
"if",
"v",
"==",
"values_result",
"]",
"return",
"{",
"keys_result",
"[",
"0",
"]",
":",
"values_result",
"}"
] |
Apply a function on the record and return the corresponding new record
:param fn: a function
:param record: a dictionary
:returns: a dictionary
>>> find(max, {'Terry': 30, 'Graham': 35, 'John': 27})
{'Graham': 35}
|
[
"Apply",
"a",
"function",
"on",
"the",
"record",
"and",
"return",
"the",
"corresponding",
"new",
"record"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L595-L608
|
246,026
|
TaurusOlson/fntools
|
fntools/fntools.py
|
remove
|
def remove(coll, value):
"""Remove all the occurrences of a given value
:param coll: a collection
:param value: the value to remove
:returns: a list
>>> data = ('NA', 0, 1, 'NA', 1, 2, 3, 'NA', 5)
>>> remove(data, 'NA')
(0, 1, 1, 2, 3, 5)
"""
coll_class = coll.__class__
return coll_class(x for x in coll if x != value)
|
python
|
def remove(coll, value):
"""Remove all the occurrences of a given value
:param coll: a collection
:param value: the value to remove
:returns: a list
>>> data = ('NA', 0, 1, 'NA', 1, 2, 3, 'NA', 5)
>>> remove(data, 'NA')
(0, 1, 1, 2, 3, 5)
"""
coll_class = coll.__class__
return coll_class(x for x in coll if x != value)
|
[
"def",
"remove",
"(",
"coll",
",",
"value",
")",
":",
"coll_class",
"=",
"coll",
".",
"__class__",
"return",
"coll_class",
"(",
"x",
"for",
"x",
"in",
"coll",
"if",
"x",
"!=",
"value",
")"
] |
Remove all the occurrences of a given value
:param coll: a collection
:param value: the value to remove
:returns: a list
>>> data = ('NA', 0, 1, 'NA', 1, 2, 3, 'NA', 5)
>>> remove(data, 'NA')
(0, 1, 1, 2, 3, 5)
|
[
"Remove",
"all",
"the",
"occurrences",
"of",
"a",
"given",
"value"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L611-L624
|
246,027
|
TaurusOlson/fntools
|
fntools/fntools.py
|
are_in
|
def are_in(items, collection):
"""Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
"""
if not isinstance(items, (list, tuple)):
items = (items, )
return map(lambda x: x in collection, items)
|
python
|
def are_in(items, collection):
"""Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
"""
if not isinstance(items, (list, tuple)):
items = (items, )
return map(lambda x: x in collection, items)
|
[
"def",
"are_in",
"(",
"items",
",",
"collection",
")",
":",
"if",
"not",
"isinstance",
"(",
"items",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"items",
"=",
"(",
"items",
",",
")",
"return",
"map",
"(",
"lambda",
"x",
":",
"x",
"in",
"collection",
",",
"items",
")"
] |
Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
|
[
"Return",
"True",
"for",
"each",
"item",
"in",
"the",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L646-L659
|
246,028
|
TaurusOlson/fntools
|
fntools/fntools.py
|
monotony
|
def monotony(seq):
"""Determine the monotony of a sequence
:param seq: a sequence
:returns: 1 if the sequence is sorted (increasing)
:returns: 0 if it is not sorted
:returns: -1 if it is sorted in reverse order (decreasing)
>>> monotony([1, 2, 3])
1
>>> monotony([1, 3, 2])
0
>>> monotony([3, 2, 1])
-1
"""
if seq == sorted(seq):
return 1
elif seq == list(reversed(sorted(seq))):
return -1
else:
return 0
|
python
|
def monotony(seq):
"""Determine the monotony of a sequence
:param seq: a sequence
:returns: 1 if the sequence is sorted (increasing)
:returns: 0 if it is not sorted
:returns: -1 if it is sorted in reverse order (decreasing)
>>> monotony([1, 2, 3])
1
>>> monotony([1, 3, 2])
0
>>> monotony([3, 2, 1])
-1
"""
if seq == sorted(seq):
return 1
elif seq == list(reversed(sorted(seq))):
return -1
else:
return 0
|
[
"def",
"monotony",
"(",
"seq",
")",
":",
"if",
"seq",
"==",
"sorted",
"(",
"seq",
")",
":",
"return",
"1",
"elif",
"seq",
"==",
"list",
"(",
"reversed",
"(",
"sorted",
"(",
"seq",
")",
")",
")",
":",
"return",
"-",
"1",
"else",
":",
"return",
"0"
] |
Determine the monotony of a sequence
:param seq: a sequence
:returns: 1 if the sequence is sorted (increasing)
:returns: 0 if it is not sorted
:returns: -1 if it is sorted in reverse order (decreasing)
>>> monotony([1, 2, 3])
1
>>> monotony([1, 3, 2])
0
>>> monotony([3, 2, 1])
-1
|
[
"Determine",
"the",
"monotony",
"of",
"a",
"sequence"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L698-L720
|
246,029
|
TaurusOlson/fntools
|
fntools/fntools.py
|
attributes
|
def attributes(data):
"""Return all the non callable and non special attributes of the input data
:param data: an object
:returns: a list
>>> class table:
... def __init__(self, name, rows, cols):
... self.name = name
... self.rows = rows
... self.cols = cols
>>> t = table('people', 100, 3)
>>> attributes(t)
['cols', 'name', 'rows']
"""
return [x for x in dir(data) if not callable(x) and not x.startswith('__')]
|
python
|
def attributes(data):
"""Return all the non callable and non special attributes of the input data
:param data: an object
:returns: a list
>>> class table:
... def __init__(self, name, rows, cols):
... self.name = name
... self.rows = rows
... self.cols = cols
>>> t = table('people', 100, 3)
>>> attributes(t)
['cols', 'name', 'rows']
"""
return [x for x in dir(data) if not callable(x) and not x.startswith('__')]
|
[
"def",
"attributes",
"(",
"data",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"data",
")",
"if",
"not",
"callable",
"(",
"x",
")",
"and",
"not",
"x",
".",
"startswith",
"(",
"'__'",
")",
"]"
] |
Return all the non callable and non special attributes of the input data
:param data: an object
:returns: a list
>>> class table:
... def __init__(self, name, rows, cols):
... self.name = name
... self.rows = rows
... self.cols = cols
>>> t = table('people', 100, 3)
>>> attributes(t)
['cols', 'name', 'rows']
|
[
"Return",
"all",
"the",
"non",
"callable",
"and",
"non",
"special",
"attributes",
"of",
"the",
"input",
"data"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L723-L740
|
246,030
|
TaurusOlson/fntools
|
fntools/fntools.py
|
dfilter
|
def dfilter(fn, record):
"""filter for a directory
:param fn: A predicate function
:param record: a dict
:returns: a dict
>>> odd = lambda x: x % 2 != 0
>>> dfilter(odd, {'Terry': 30, 'Graham': 35, 'John': 27})
{'John': 27, 'Graham': 35}
"""
return dict([(k, v) for k, v in record.items() if fn(v)])
|
python
|
def dfilter(fn, record):
"""filter for a directory
:param fn: A predicate function
:param record: a dict
:returns: a dict
>>> odd = lambda x: x % 2 != 0
>>> dfilter(odd, {'Terry': 30, 'Graham': 35, 'John': 27})
{'John': 27, 'Graham': 35}
"""
return dict([(k, v) for k, v in record.items() if fn(v)])
|
[
"def",
"dfilter",
"(",
"fn",
",",
"record",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"record",
".",
"items",
"(",
")",
"if",
"fn",
"(",
"v",
")",
"]",
")"
] |
filter for a directory
:param fn: A predicate function
:param record: a dict
:returns: a dict
>>> odd = lambda x: x % 2 != 0
>>> dfilter(odd, {'Terry': 30, 'Graham': 35, 'John': 27})
{'John': 27, 'Graham': 35}
|
[
"filter",
"for",
"a",
"directory"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L760-L772
|
246,031
|
TaurusOlson/fntools
|
fntools/fntools.py
|
_filter_occurrences
|
def _filter_occurrences(count, relat_op):
"""Filter the occurrences with respect to the selected relational operators"""
# Filter the occurrences equal (or not equal) to a given value
if "eq" in relat_op:
count = dfilter(lambda x: x == relat_op["eq"], count)
elif "ne" in relat_op:
count = dfilter(lambda x: x != relat_op["ne"], count)
# Filter the occurrences lower (or equal) than a given value
if "lt" in relat_op:
count = dfilter(lambda x: x < relat_op["lt"], count)
elif "le" in relat_op:
count = dfilter(lambda x: x <= relat_op["le"], count)
# Filter the occurrences greater (or equal) than a given value
if "gt" in relat_op:
count = dfilter(lambda x: x > relat_op["gt"], count)
elif "ge" in relat_op:
count = dfilter(lambda x: x >= relat_op["ge"], count)
return count
|
python
|
def _filter_occurrences(count, relat_op):
"""Filter the occurrences with respect to the selected relational operators"""
# Filter the occurrences equal (or not equal) to a given value
if "eq" in relat_op:
count = dfilter(lambda x: x == relat_op["eq"], count)
elif "ne" in relat_op:
count = dfilter(lambda x: x != relat_op["ne"], count)
# Filter the occurrences lower (or equal) than a given value
if "lt" in relat_op:
count = dfilter(lambda x: x < relat_op["lt"], count)
elif "le" in relat_op:
count = dfilter(lambda x: x <= relat_op["le"], count)
# Filter the occurrences greater (or equal) than a given value
if "gt" in relat_op:
count = dfilter(lambda x: x > relat_op["gt"], count)
elif "ge" in relat_op:
count = dfilter(lambda x: x >= relat_op["ge"], count)
return count
|
[
"def",
"_filter_occurrences",
"(",
"count",
",",
"relat_op",
")",
":",
"# Filter the occurrences equal (or not equal) to a given value",
"if",
"\"eq\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
"==",
"relat_op",
"[",
"\"eq\"",
"]",
",",
"count",
")",
"elif",
"\"ne\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
"!=",
"relat_op",
"[",
"\"ne\"",
"]",
",",
"count",
")",
"# Filter the occurrences lower (or equal) than a given value",
"if",
"\"lt\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
"<",
"relat_op",
"[",
"\"lt\"",
"]",
",",
"count",
")",
"elif",
"\"le\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
"<=",
"relat_op",
"[",
"\"le\"",
"]",
",",
"count",
")",
"# Filter the occurrences greater (or equal) than a given value",
"if",
"\"gt\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
">",
"relat_op",
"[",
"\"gt\"",
"]",
",",
"count",
")",
"elif",
"\"ge\"",
"in",
"relat_op",
":",
"count",
"=",
"dfilter",
"(",
"lambda",
"x",
":",
"x",
">=",
"relat_op",
"[",
"\"ge\"",
"]",
",",
"count",
")",
"return",
"count"
] |
Filter the occurrences with respect to the selected relational operators
|
[
"Filter",
"the",
"occurrences",
"with",
"respect",
"to",
"the",
"selected",
"relational",
"operators"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L776-L795
|
246,032
|
TaurusOlson/fntools
|
fntools/fntools.py
|
occurrences
|
def occurrences(coll, value=None, **options):
"""Return the occurrences of the elements in the collection
:param coll: a collection
:param value: a value in the collection
:param options:
an optional keyword used as a criterion to filter the
values in the collection
:returns: the frequency of the values in the collection as a dictionary
>>> occurrences((1, 1, 2, 3))
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), 1)
2
Filter the values of the occurrences that are
<, <=, >, >=, == or != than a given number::
>>> occurrences((1, 1, 2, 3), lt=3)
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), gt=1)
{1: 2}
>>> occurrences((1, 1, 2, 3), ne=1)
{1: 2}
"""
count = {}
for element in coll:
count[element] = count.get(element, 0) + 1
if options:
count = _filter_occurrences(count, options)
if value:
count = count.get(value, 0)
return count
|
python
|
def occurrences(coll, value=None, **options):
"""Return the occurrences of the elements in the collection
:param coll: a collection
:param value: a value in the collection
:param options:
an optional keyword used as a criterion to filter the
values in the collection
:returns: the frequency of the values in the collection as a dictionary
>>> occurrences((1, 1, 2, 3))
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), 1)
2
Filter the values of the occurrences that are
<, <=, >, >=, == or != than a given number::
>>> occurrences((1, 1, 2, 3), lt=3)
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), gt=1)
{1: 2}
>>> occurrences((1, 1, 2, 3), ne=1)
{1: 2}
"""
count = {}
for element in coll:
count[element] = count.get(element, 0) + 1
if options:
count = _filter_occurrences(count, options)
if value:
count = count.get(value, 0)
return count
|
[
"def",
"occurrences",
"(",
"coll",
",",
"value",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"count",
"=",
"{",
"}",
"for",
"element",
"in",
"coll",
":",
"count",
"[",
"element",
"]",
"=",
"count",
".",
"get",
"(",
"element",
",",
"0",
")",
"+",
"1",
"if",
"options",
":",
"count",
"=",
"_filter_occurrences",
"(",
"count",
",",
"options",
")",
"if",
"value",
":",
"count",
"=",
"count",
".",
"get",
"(",
"value",
",",
"0",
")",
"return",
"count"
] |
Return the occurrences of the elements in the collection
:param coll: a collection
:param value: a value in the collection
:param options:
an optional keyword used as a criterion to filter the
values in the collection
:returns: the frequency of the values in the collection as a dictionary
>>> occurrences((1, 1, 2, 3))
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), 1)
2
Filter the values of the occurrences that are
<, <=, >, >=, == or != than a given number::
>>> occurrences((1, 1, 2, 3), lt=3)
{1: 2, 2: 1, 3: 1}
>>> occurrences((1, 1, 2, 3), gt=1)
{1: 2}
>>> occurrences((1, 1, 2, 3), ne=1)
{1: 2}
|
[
"Return",
"the",
"occurrences",
"of",
"the",
"elements",
"in",
"the",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L798-L833
|
246,033
|
TaurusOlson/fntools
|
fntools/fntools.py
|
indexof
|
def indexof(coll, item, start=0, default=None):
"""Return the index of the item in the collection
:param coll: iterable
:param item: scalar
:param start: (optional) The start index
:default: The default value of the index if the item is not in the collection
:returns: idx -- The index of the item in the collection
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexof(monties, 'Terry')
2
>>> indexof(monties, 'Terry', start=3)
3
>>> indexof(monties, 'Terry', start=4) is None
True
"""
if item in coll[start:]:
return list(coll).index(item, start)
else:
return default
|
python
|
def indexof(coll, item, start=0, default=None):
"""Return the index of the item in the collection
:param coll: iterable
:param item: scalar
:param start: (optional) The start index
:default: The default value of the index if the item is not in the collection
:returns: idx -- The index of the item in the collection
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexof(monties, 'Terry')
2
>>> indexof(monties, 'Terry', start=3)
3
>>> indexof(monties, 'Terry', start=4) is None
True
"""
if item in coll[start:]:
return list(coll).index(item, start)
else:
return default
|
[
"def",
"indexof",
"(",
"coll",
",",
"item",
",",
"start",
"=",
"0",
",",
"default",
"=",
"None",
")",
":",
"if",
"item",
"in",
"coll",
"[",
"start",
":",
"]",
":",
"return",
"list",
"(",
"coll",
")",
".",
"index",
"(",
"item",
",",
"start",
")",
"else",
":",
"return",
"default"
] |
Return the index of the item in the collection
:param coll: iterable
:param item: scalar
:param start: (optional) The start index
:default: The default value of the index if the item is not in the collection
:returns: idx -- The index of the item in the collection
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexof(monties, 'Terry')
2
>>> indexof(monties, 'Terry', start=3)
3
>>> indexof(monties, 'Terry', start=4) is None
True
|
[
"Return",
"the",
"index",
"of",
"the",
"item",
"in",
"the",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L836-L860
|
246,034
|
TaurusOlson/fntools
|
fntools/fntools.py
|
indexesof
|
def indexesof(coll, item):
"""Return all the indexes of the item in the collection
:param coll: the collection
:param item: a value
:returns: a list of indexes
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexesof(monties, 'Terry')
[2, 3]
"""
return [indexof(coll, item, i) for i in xrange(len(coll)) if coll[i] == item]
|
python
|
def indexesof(coll, item):
"""Return all the indexes of the item in the collection
:param coll: the collection
:param item: a value
:returns: a list of indexes
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexesof(monties, 'Terry')
[2, 3]
"""
return [indexof(coll, item, i) for i in xrange(len(coll)) if coll[i] == item]
|
[
"def",
"indexesof",
"(",
"coll",
",",
"item",
")",
":",
"return",
"[",
"indexof",
"(",
"coll",
",",
"item",
",",
"i",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"coll",
")",
")",
"if",
"coll",
"[",
"i",
"]",
"==",
"item",
"]"
] |
Return all the indexes of the item in the collection
:param coll: the collection
:param item: a value
:returns: a list of indexes
>>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael']
>>> indexesof(monties, 'Terry')
[2, 3]
|
[
"Return",
"all",
"the",
"indexes",
"of",
"the",
"item",
"in",
"the",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L863-L875
|
246,035
|
TaurusOlson/fntools
|
fntools/fntools.py
|
count
|
def count(fn, coll):
"""Return the count of True values returned by the predicate function applied to the
collection
:param fn: a predicate function
:param coll: a collection
:returns: an integer
>>> count(lambda x: x % 2 == 0, [11, 22, 31, 24, 15])
2
"""
return len([x for x in coll if fn(x) is True])
|
python
|
def count(fn, coll):
"""Return the count of True values returned by the predicate function applied to the
collection
:param fn: a predicate function
:param coll: a collection
:returns: an integer
>>> count(lambda x: x % 2 == 0, [11, 22, 31, 24, 15])
2
"""
return len([x for x in coll if fn(x) is True])
|
[
"def",
"count",
"(",
"fn",
",",
"coll",
")",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"coll",
"if",
"fn",
"(",
"x",
")",
"is",
"True",
"]",
")"
] |
Return the count of True values returned by the predicate function applied to the
collection
:param fn: a predicate function
:param coll: a collection
:returns: an integer
>>> count(lambda x: x % 2 == 0, [11, 22, 31, 24, 15])
2
|
[
"Return",
"the",
"count",
"of",
"True",
"values",
"returned",
"by",
"the",
"predicate",
"function",
"applied",
"to",
"the",
"collection"
] |
316080c7b5bfdd88c9f3fac4a67deb5be3c319e5
|
https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L878-L890
|
246,036
|
shaunduncan/helga-icanhazascii
|
helga_icanhazascii.py
|
icanhazascii
|
def icanhazascii(client, channel, nick, message, found):
"""
A plugin for generating showing ascii artz
"""
global FLOOD_RATE, LAST_USED
now = time.time()
if channel in LAST_USED and (now - LAST_USED[channel]) < FLOOD_RATE:
return
LAST_USED[channel] = now
return found
|
python
|
def icanhazascii(client, channel, nick, message, found):
"""
A plugin for generating showing ascii artz
"""
global FLOOD_RATE, LAST_USED
now = time.time()
if channel in LAST_USED and (now - LAST_USED[channel]) < FLOOD_RATE:
return
LAST_USED[channel] = now
return found
|
[
"def",
"icanhazascii",
"(",
"client",
",",
"channel",
",",
"nick",
",",
"message",
",",
"found",
")",
":",
"global",
"FLOOD_RATE",
",",
"LAST_USED",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"channel",
"in",
"LAST_USED",
"and",
"(",
"now",
"-",
"LAST_USED",
"[",
"channel",
"]",
")",
"<",
"FLOOD_RATE",
":",
"return",
"LAST_USED",
"[",
"channel",
"]",
"=",
"now",
"return",
"found"
] |
A plugin for generating showing ascii artz
|
[
"A",
"plugin",
"for",
"generating",
"showing",
"ascii",
"artz"
] |
a69d63232186d6b0e6c6ac72935cee906eb359b1
|
https://github.com/shaunduncan/helga-icanhazascii/blob/a69d63232186d6b0e6c6ac72935cee906eb359b1/helga_icanhazascii.py#L113-L124
|
246,037
|
xsleonard/wsgisubdomain
|
wsgisubdomain.py
|
SubdomainDispatcher.get_application
|
def get_application(self, environ):
""" Retrieve an application for a wsgi environ
:param environ: The environ object sent by wsgi to an application
"""
host = self._get_host(environ)
subdomain = self._extract_subdomain(host)
return self._get_application(subdomain)
|
python
|
def get_application(self, environ):
""" Retrieve an application for a wsgi environ
:param environ: The environ object sent by wsgi to an application
"""
host = self._get_host(environ)
subdomain = self._extract_subdomain(host)
return self._get_application(subdomain)
|
[
"def",
"get_application",
"(",
"self",
",",
"environ",
")",
":",
"host",
"=",
"self",
".",
"_get_host",
"(",
"environ",
")",
"subdomain",
"=",
"self",
".",
"_extract_subdomain",
"(",
"host",
")",
"return",
"self",
".",
"_get_application",
"(",
"subdomain",
")"
] |
Retrieve an application for a wsgi environ
:param environ: The environ object sent by wsgi to an application
|
[
"Retrieve",
"an",
"application",
"for",
"a",
"wsgi",
"environ"
] |
394c705a9e39cf4e4e1af2551ed0ed79d2c070f3
|
https://github.com/xsleonard/wsgisubdomain/blob/394c705a9e39cf4e4e1af2551ed0ed79d2c070f3/wsgisubdomain.py#L37-L44
|
246,038
|
xsleonard/wsgisubdomain
|
wsgisubdomain.py
|
SubdomainDispatcher._get_application
|
def _get_application(self, subdomain):
""" Return a WSGI application for subdomain. The subdomain is
passed to the create_application constructor as a keyword argument.
:param subdomain: Subdomain to get or create an application with
"""
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_application(subdomain=subdomain)
self.instances[subdomain] = app
return app
|
python
|
def _get_application(self, subdomain):
""" Return a WSGI application for subdomain. The subdomain is
passed to the create_application constructor as a keyword argument.
:param subdomain: Subdomain to get or create an application with
"""
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_application(subdomain=subdomain)
self.instances[subdomain] = app
return app
|
[
"def",
"_get_application",
"(",
"self",
",",
"subdomain",
")",
":",
"with",
"self",
".",
"lock",
":",
"app",
"=",
"self",
".",
"instances",
".",
"get",
"(",
"subdomain",
")",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"self",
".",
"create_application",
"(",
"subdomain",
"=",
"subdomain",
")",
"self",
".",
"instances",
"[",
"subdomain",
"]",
"=",
"app",
"return",
"app"
] |
Return a WSGI application for subdomain. The subdomain is
passed to the create_application constructor as a keyword argument.
:param subdomain: Subdomain to get or create an application with
|
[
"Return",
"a",
"WSGI",
"application",
"for",
"subdomain",
".",
"The",
"subdomain",
"is",
"passed",
"to",
"the",
"create_application",
"constructor",
"as",
"a",
"keyword",
"argument",
"."
] |
394c705a9e39cf4e4e1af2551ed0ed79d2c070f3
|
https://github.com/xsleonard/wsgisubdomain/blob/394c705a9e39cf4e4e1af2551ed0ed79d2c070f3/wsgisubdomain.py#L46-L57
|
246,039
|
xsleonard/wsgisubdomain
|
wsgisubdomain.py
|
SubdomainDispatcher._extract_subdomain
|
def _extract_subdomain(host):
""" Returns a subdomain from a host. This host is typically the
HTTP_HOST request envvar. If the host is an IP address, `None` is
returned
:param host: Request's target host
"""
host = host.split(':')[0]
# If the host is an IP address, there is no subdomain to extract
try:
# Check if the host is an ip address
socket.inet_aton(host)
except socket.error:
# It isn't an IP address, return the subdomain
return '.'.join(host.split('.')[:-2])
|
python
|
def _extract_subdomain(host):
""" Returns a subdomain from a host. This host is typically the
HTTP_HOST request envvar. If the host is an IP address, `None` is
returned
:param host: Request's target host
"""
host = host.split(':')[0]
# If the host is an IP address, there is no subdomain to extract
try:
# Check if the host is an ip address
socket.inet_aton(host)
except socket.error:
# It isn't an IP address, return the subdomain
return '.'.join(host.split('.')[:-2])
|
[
"def",
"_extract_subdomain",
"(",
"host",
")",
":",
"host",
"=",
"host",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"# If the host is an IP address, there is no subdomain to extract",
"try",
":",
"# Check if the host is an ip address",
"socket",
".",
"inet_aton",
"(",
"host",
")",
"except",
"socket",
".",
"error",
":",
"# It isn't an IP address, return the subdomain",
"return",
"'.'",
".",
"join",
"(",
"host",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"2",
"]",
")"
] |
Returns a subdomain from a host. This host is typically the
HTTP_HOST request envvar. If the host is an IP address, `None` is
returned
:param host: Request's target host
|
[
"Returns",
"a",
"subdomain",
"from",
"a",
"host",
".",
"This",
"host",
"is",
"typically",
"the",
"HTTP_HOST",
"request",
"envvar",
".",
"If",
"the",
"host",
"is",
"an",
"IP",
"address",
"None",
"is",
"returned"
] |
394c705a9e39cf4e4e1af2551ed0ed79d2c070f3
|
https://github.com/xsleonard/wsgisubdomain/blob/394c705a9e39cf4e4e1af2551ed0ed79d2c070f3/wsgisubdomain.py#L60-L74
|
246,040
|
nicktgr15/sac
|
sac/cli/wav_editor.py
|
WavEditor.are_labels_overlapping
|
def are_labels_overlapping(label1, label2):
"""
non-overlap cases
|---------| lbl1
|--------| lbl2
|---------| lbl1
|---------| lbl2
:param label1:
:param label2:
:return:
"""
if (
label2.start_seconds > label1.end_seconds and
label2.start_seconds > label1.start_seconds and
label2.end_seconds > label1.start_seconds and
label2.end_seconds > label1.start_seconds) or (
label2.start_seconds < label1.start_seconds and
label2.end_seconds < label1.start_seconds and
label2.start_seconds < label1.end_seconds and
label2.end_seconds < label1.end_seconds):
return False
else:
return True
|
python
|
def are_labels_overlapping(label1, label2):
"""
non-overlap cases
|---------| lbl1
|--------| lbl2
|---------| lbl1
|---------| lbl2
:param label1:
:param label2:
:return:
"""
if (
label2.start_seconds > label1.end_seconds and
label2.start_seconds > label1.start_seconds and
label2.end_seconds > label1.start_seconds and
label2.end_seconds > label1.start_seconds) or (
label2.start_seconds < label1.start_seconds and
label2.end_seconds < label1.start_seconds and
label2.start_seconds < label1.end_seconds and
label2.end_seconds < label1.end_seconds):
return False
else:
return True
|
[
"def",
"are_labels_overlapping",
"(",
"label1",
",",
"label2",
")",
":",
"if",
"(",
"label2",
".",
"start_seconds",
">",
"label1",
".",
"end_seconds",
"and",
"label2",
".",
"start_seconds",
">",
"label1",
".",
"start_seconds",
"and",
"label2",
".",
"end_seconds",
">",
"label1",
".",
"start_seconds",
"and",
"label2",
".",
"end_seconds",
">",
"label1",
".",
"start_seconds",
")",
"or",
"(",
"label2",
".",
"start_seconds",
"<",
"label1",
".",
"start_seconds",
"and",
"label2",
".",
"end_seconds",
"<",
"label1",
".",
"start_seconds",
"and",
"label2",
".",
"start_seconds",
"<",
"label1",
".",
"end_seconds",
"and",
"label2",
".",
"end_seconds",
"<",
"label1",
".",
"end_seconds",
")",
":",
"return",
"False",
"else",
":",
"return",
"True"
] |
non-overlap cases
|---------| lbl1
|--------| lbl2
|---------| lbl1
|---------| lbl2
:param label1:
:param label2:
:return:
|
[
"non",
"-",
"overlap",
"cases"
] |
4b1d5d8e6ca2c437972db34ddc72990860865159
|
https://github.com/nicktgr15/sac/blob/4b1d5d8e6ca2c437972db34ddc72990860865159/sac/cli/wav_editor.py#L72-L99
|
246,041
|
jkenlooper/chill
|
src/chill/app.py
|
multiple_directory_files_loader
|
def multiple_directory_files_loader(*args):
"""
Loads all the files in each directory as values in a dict with the key
being the relative file path of the directory. Updates the value if
subsequent file paths are the same.
"""
d = dict()
def load_files(folder):
for (dirpath, dirnames, filenames) in os.walk(folder):
for f in filenames:
filepath = os.path.join(dirpath, f)
with open( filepath, 'r' ) as f:
key = filepath[len(os.path.commonprefix([root, filepath]))+1:]
d[ key ] = f.read()
for foldername in dirnames:
load_files(os.path.join(dirpath, foldername))
for root in args:
load_files(root)
return d
|
python
|
def multiple_directory_files_loader(*args):
"""
Loads all the files in each directory as values in a dict with the key
being the relative file path of the directory. Updates the value if
subsequent file paths are the same.
"""
d = dict()
def load_files(folder):
for (dirpath, dirnames, filenames) in os.walk(folder):
for f in filenames:
filepath = os.path.join(dirpath, f)
with open( filepath, 'r' ) as f:
key = filepath[len(os.path.commonprefix([root, filepath]))+1:]
d[ key ] = f.read()
for foldername in dirnames:
load_files(os.path.join(dirpath, foldername))
for root in args:
load_files(root)
return d
|
[
"def",
"multiple_directory_files_loader",
"(",
"*",
"args",
")",
":",
"d",
"=",
"dict",
"(",
")",
"def",
"load_files",
"(",
"folder",
")",
":",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"folder",
")",
":",
"for",
"f",
"in",
"filenames",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"f",
")",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"key",
"=",
"filepath",
"[",
"len",
"(",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"root",
",",
"filepath",
"]",
")",
")",
"+",
"1",
":",
"]",
"d",
"[",
"key",
"]",
"=",
"f",
".",
"read",
"(",
")",
"for",
"foldername",
"in",
"dirnames",
":",
"load_files",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"foldername",
")",
")",
"for",
"root",
"in",
"args",
":",
"load_files",
"(",
"root",
")",
"return",
"d"
] |
Loads all the files in each directory as values in a dict with the key
being the relative file path of the directory. Updates the value if
subsequent file paths are the same.
|
[
"Loads",
"all",
"the",
"files",
"in",
"each",
"directory",
"as",
"values",
"in",
"a",
"dict",
"with",
"the",
"key",
"being",
"the",
"relative",
"file",
"path",
"of",
"the",
"directory",
".",
"Updates",
"the",
"value",
"if",
"subsequent",
"file",
"paths",
"are",
"the",
"same",
"."
] |
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
|
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/app.py#L67-L87
|
246,042
|
jkenlooper/chill
|
src/chill/app.py
|
ChillFlask.send_root_file
|
def send_root_file(self, filename):
"""
Function used to send static files from the root of the domain.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['ROOT_FOLDER'], filename,
cache_timeout=cache_timeout)
|
python
|
def send_root_file(self, filename):
"""
Function used to send static files from the root of the domain.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['ROOT_FOLDER'], filename,
cache_timeout=cache_timeout)
|
[
"def",
"send_root_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'ROOT_FOLDER'",
"]",
",",
"filename",
",",
"cache_timeout",
"=",
"cache_timeout",
")"
] |
Function used to send static files from the root of the domain.
|
[
"Function",
"used",
"to",
"send",
"static",
"files",
"from",
"the",
"root",
"of",
"the",
"domain",
"."
] |
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
|
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/app.py#L20-L26
|
246,043
|
jkenlooper/chill
|
src/chill/app.py
|
ChillFlask.send_media_file
|
def send_media_file(self, filename):
"""
Function used to send media files from the media folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['MEDIA_FOLDER'], filename,
cache_timeout=cache_timeout)
|
python
|
def send_media_file(self, filename):
"""
Function used to send media files from the media folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['MEDIA_FOLDER'], filename,
cache_timeout=cache_timeout)
|
[
"def",
"send_media_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'MEDIA_FOLDER'",
"]",
",",
"filename",
",",
"cache_timeout",
"=",
"cache_timeout",
")"
] |
Function used to send media files from the media folder to the browser.
|
[
"Function",
"used",
"to",
"send",
"media",
"files",
"from",
"the",
"media",
"folder",
"to",
"the",
"browser",
"."
] |
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
|
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/app.py#L28-L34
|
246,044
|
jkenlooper/chill
|
src/chill/app.py
|
ChillFlask.send_theme_file
|
def send_theme_file(self, filename):
"""
Function used to send static theme files from the theme folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename,
cache_timeout=cache_timeout)
|
python
|
def send_theme_file(self, filename):
"""
Function used to send static theme files from the theme folder to the browser.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename,
cache_timeout=cache_timeout)
|
[
"def",
"send_theme_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'THEME_STATIC_FOLDER'",
"]",
",",
"filename",
",",
"cache_timeout",
"=",
"cache_timeout",
")"
] |
Function used to send static theme files from the theme folder to the browser.
|
[
"Function",
"used",
"to",
"send",
"static",
"theme",
"files",
"from",
"the",
"theme",
"folder",
"to",
"the",
"browser",
"."
] |
35360c17c2a3b769ecb5406c6dabcf4cc70bd76f
|
https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/app.py#L36-L42
|
246,045
|
jut-io/jut-python-tools
|
jut/common.py
|
info
|
def info(message, *args, **kwargs):
"""
write a message to stdout
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if len(args) == 0:
sys.stdout.write(message)
else:
sys.stdout.write(message % args)
sys.stdout.write(end)
sys.stdout.flush()
|
python
|
def info(message, *args, **kwargs):
"""
write a message to stdout
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if len(args) == 0:
sys.stdout.write(message)
else:
sys.stdout.write(message % args)
sys.stdout.write(end)
sys.stdout.flush()
|
[
"def",
"info",
"(",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'end'",
"in",
"kwargs",
":",
"end",
"=",
"kwargs",
"[",
"'end'",
"]",
"else",
":",
"end",
"=",
"'\\n'",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"message",
")",
"else",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"message",
"%",
"args",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"end",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] |
write a message to stdout
|
[
"write",
"a",
"message",
"to",
"stdout"
] |
65574d23f51a7bbced9bb25010d02da5ca5d906f
|
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/common.py#L9-L24
|
246,046
|
jut-io/jut-python-tools
|
jut/common.py
|
error
|
def error(message, *args, **kwargs):
"""
write a message to stderr
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush()
|
python
|
def error(message, *args, **kwargs):
"""
write a message to stderr
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush()
|
[
"def",
"error",
"(",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'end'",
"in",
"kwargs",
":",
"end",
"=",
"kwargs",
"[",
"'end'",
"]",
"else",
":",
"end",
"=",
"'\\n'",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
"%",
"args",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"end",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] |
write a message to stderr
|
[
"write",
"a",
"message",
"to",
"stderr"
] |
65574d23f51a7bbced9bb25010d02da5ca5d906f
|
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/common.py#L27-L42
|
246,047
|
jut-io/jut-python-tools
|
jut/common.py
|
debug
|
def debug(message, *args, **kwargs):
"""
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if DEBUG:
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush()
|
python
|
def debug(message, *args, **kwargs):
"""
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if DEBUG:
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush()
|
[
"def",
"debug",
"(",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'end'",
"in",
"kwargs",
":",
"end",
"=",
"kwargs",
"[",
"'end'",
"]",
"else",
":",
"end",
"=",
"'\\n'",
"if",
"DEBUG",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
"%",
"args",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"end",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] |
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
|
[
"debug",
"output",
"goes",
"to",
"stderr",
"so",
"you",
"can",
"still",
"redirect",
"the",
"stdout",
"to",
"a",
"file",
"or",
"another",
"program",
".",
"Controlled",
"by",
"the",
"JUT_DEBUG",
"environment",
"variable",
"being",
"present"
] |
65574d23f51a7bbced9bb25010d02da5ca5d906f
|
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/common.py#L45-L64
|
246,048
|
klmitch/workq
|
workq.py
|
WorkQueue.add
|
def add(self, item):
"""
Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``, or a ``key``
callable must have been provided.
"""
# Are we to uniquify work items?
if self._unique:
key = self._key(item) if self._key else item
# If it already has been added to the queue, do nothing
if key in self._seen:
return
self._seen.add(key)
# Add the item to the queue
self._work.append(item)
# We'll keep a count of the number of items that have been
# through the queue
self._count += 1
|
python
|
def add(self, item):
"""
Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``, or a ``key``
callable must have been provided.
"""
# Are we to uniquify work items?
if self._unique:
key = self._key(item) if self._key else item
# If it already has been added to the queue, do nothing
if key in self._seen:
return
self._seen.add(key)
# Add the item to the queue
self._work.append(item)
# We'll keep a count of the number of items that have been
# through the queue
self._count += 1
|
[
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"# Are we to uniquify work items?",
"if",
"self",
".",
"_unique",
":",
"key",
"=",
"self",
".",
"_key",
"(",
"item",
")",
"if",
"self",
".",
"_key",
"else",
"item",
"# If it already has been added to the queue, do nothing",
"if",
"key",
"in",
"self",
".",
"_seen",
":",
"return",
"self",
".",
"_seen",
".",
"add",
"(",
"key",
")",
"# Add the item to the queue",
"self",
".",
"_work",
".",
"append",
"(",
"item",
")",
"# We'll keep a count of the number of items that have been",
"# through the queue",
"self",
".",
"_count",
"+=",
"1"
] |
Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``, or a ``key``
callable must have been provided.
|
[
"Add",
"an",
"item",
"to",
"the",
"work",
"queue",
"."
] |
6b26c7546947bd0b0c98d78cf4653411a1d09c55
|
https://github.com/klmitch/workq/blob/6b26c7546947bd0b0c98d78cf4653411a1d09c55/workq.py#L96-L122
|
246,049
|
rorr73/LifeSOSpy
|
lifesospy/enums.py
|
IntEnumEx.has_value
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
python
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
[
"def",
"has_value",
"(",
"cls",
",",
"value",
":",
"int",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"value",
"==",
"item",
".",
"value",
"for",
"item",
"in",
"cls",
")"
] |
True if specified value exists in int enum; otherwise, False.
|
[
"True",
"if",
"specified",
"value",
"exists",
"in",
"int",
"enum",
";",
"otherwise",
"False",
"."
] |
62360fbab2e90bf04d52b547093bdab2d4e389b4
|
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/enums.py#L20-L22
|
246,050
|
rorr73/LifeSOSpy
|
lifesospy/enums.py
|
IntEnumEx.parse_name
|
def parse_name(cls, name: str, default: T = None) -> T:
"""Parse specified name for IntEnum; return default if not found."""
if not name:
return default
name = name.lower()
return next((item for item in cls if name == item.name.lower()), default)
|
python
|
def parse_name(cls, name: str, default: T = None) -> T:
"""Parse specified name for IntEnum; return default if not found."""
if not name:
return default
name = name.lower()
return next((item for item in cls if name == item.name.lower()), default)
|
[
"def",
"parse_name",
"(",
"cls",
",",
"name",
":",
"str",
",",
"default",
":",
"T",
"=",
"None",
")",
"->",
"T",
":",
"if",
"not",
"name",
":",
"return",
"default",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"cls",
"if",
"name",
"==",
"item",
".",
"name",
".",
"lower",
"(",
")",
")",
",",
"default",
")"
] |
Parse specified name for IntEnum; return default if not found.
|
[
"Parse",
"specified",
"name",
"for",
"IntEnum",
";",
"return",
"default",
"if",
"not",
"found",
"."
] |
62360fbab2e90bf04d52b547093bdab2d4e389b4
|
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/enums.py#L25-L30
|
246,051
|
rorr73/LifeSOSpy
|
lifesospy/enums.py
|
IntEnumEx.parse_value
|
def parse_value(cls, value: int, default: T = None) -> T:
"""Parse specified value for IntEnum; return default if not found."""
return next((item for item in cls if value == item.value), default)
|
python
|
def parse_value(cls, value: int, default: T = None) -> T:
"""Parse specified value for IntEnum; return default if not found."""
return next((item for item in cls if value == item.value), default)
|
[
"def",
"parse_value",
"(",
"cls",
",",
"value",
":",
"int",
",",
"default",
":",
"T",
"=",
"None",
")",
"->",
"T",
":",
"return",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"cls",
"if",
"value",
"==",
"item",
".",
"value",
")",
",",
"default",
")"
] |
Parse specified value for IntEnum; return default if not found.
|
[
"Parse",
"specified",
"value",
"for",
"IntEnum",
";",
"return",
"default",
"if",
"not",
"found",
"."
] |
62360fbab2e90bf04d52b547093bdab2d4e389b4
|
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/enums.py#L33-L35
|
246,052
|
rorr73/LifeSOSpy
|
lifesospy/enums.py
|
IntFlagEx.parse_names
|
def parse_names(cls, names: List[str]) -> T:
"""Parse specified names for IntEnum; return default if not found."""
value = 0
iterable = cls # type: Iterable
for name in names:
name = name.lower()
flag = next((item for item in iterable if name == item.name.lower()), None)
if not flag:
raise ValueError("{} is not a member of {}".format(
name, cls.__name__))
value = value | int(flag)
return cls(value)
|
python
|
def parse_names(cls, names: List[str]) -> T:
"""Parse specified names for IntEnum; return default if not found."""
value = 0
iterable = cls # type: Iterable
for name in names:
name = name.lower()
flag = next((item for item in iterable if name == item.name.lower()), None)
if not flag:
raise ValueError("{} is not a member of {}".format(
name, cls.__name__))
value = value | int(flag)
return cls(value)
|
[
"def",
"parse_names",
"(",
"cls",
",",
"names",
":",
"List",
"[",
"str",
"]",
")",
"->",
"T",
":",
"value",
"=",
"0",
"iterable",
"=",
"cls",
"# type: Iterable",
"for",
"name",
"in",
"names",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"flag",
"=",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"iterable",
"if",
"name",
"==",
"item",
".",
"name",
".",
"lower",
"(",
")",
")",
",",
"None",
")",
"if",
"not",
"flag",
":",
"raise",
"ValueError",
"(",
"\"{} is not a member of {}\"",
".",
"format",
"(",
"name",
",",
"cls",
".",
"__name__",
")",
")",
"value",
"=",
"value",
"|",
"int",
"(",
"flag",
")",
"return",
"cls",
"(",
"value",
")"
] |
Parse specified names for IntEnum; return default if not found.
|
[
"Parse",
"specified",
"names",
"for",
"IntEnum",
";",
"return",
"default",
"if",
"not",
"found",
"."
] |
62360fbab2e90bf04d52b547093bdab2d4e389b4
|
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/enums.py#L46-L57
|
246,053
|
mbr/sshkeys
|
sshkeys/__init__.py
|
Key._extract_options
|
def _extract_options(line):
r'''Given a line as it would appear in the authorized_keys file,
return an OrderedDict of options, and the remainder of a line as a
string.
>>> Key._extract_options(r'no-pty,command="sh" ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
(OrderedDict([('no-pty', True), ('command', 'sh')]), 'ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
>>> Key._extract_options(r'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
(OrderedDict(), 'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
'''
options = OrderedDict({})
quoted = False
escaped = False
option_name = ''
option_val = None
key_without_options = ''
in_options = True
in_option_name = True
for letter in line.strip():
if in_options:
if quoted:
if letter == "\\":
escaped = True
elif letter == '"':
if escaped:
option_val += letter
escaped = False
else:
quoted = False
else:
if escaped:
option_val += "\\"
escaped = False
option_val += letter
else: # not quoted
if letter == ' ':
# end of options
in_options = False
if (option_name in ['ssh-rsa', 'ssh-dss'] or
option_name.startswith('ecdsa-')):
# what we thought was an option name was really the
# key type, and there are no options
key_without_options = option_name + " "
option_name = ''
else:
if option_val is None:
options[option_name] = True
else:
options[option_name] = option_val
elif letter == '"':
quoted = True
elif letter == '=':
# '=' separated option name from value
in_option_name = False
if option_val is None:
option_val = ''
elif letter == ',':
# next option_name
if option_val is None:
options[option_name] = True
else:
options[option_name] = option_val
in_option_name = True
option_name = ''
option_val = None
else: # general unquoted letter
if in_option_name:
option_name += letter
else:
option_val += letter
else:
key_without_options += letter
if key_without_options == '':
# certain mal-formed keys (e.g. a line not containing any spaces)
# will be completely swallowed up by the above parser. It's
# better to follow the principle of least surprize and return the
# original line, allowing the error to be handled later.
return OrderedDict({}), line.strip()
else:
return options, key_without_options
|
python
|
def _extract_options(line):
r'''Given a line as it would appear in the authorized_keys file,
return an OrderedDict of options, and the remainder of a line as a
string.
>>> Key._extract_options(r'no-pty,command="sh" ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
(OrderedDict([('no-pty', True), ('command', 'sh')]), 'ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
>>> Key._extract_options(r'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
(OrderedDict(), 'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
'''
options = OrderedDict({})
quoted = False
escaped = False
option_name = ''
option_val = None
key_without_options = ''
in_options = True
in_option_name = True
for letter in line.strip():
if in_options:
if quoted:
if letter == "\\":
escaped = True
elif letter == '"':
if escaped:
option_val += letter
escaped = False
else:
quoted = False
else:
if escaped:
option_val += "\\"
escaped = False
option_val += letter
else: # not quoted
if letter == ' ':
# end of options
in_options = False
if (option_name in ['ssh-rsa', 'ssh-dss'] or
option_name.startswith('ecdsa-')):
# what we thought was an option name was really the
# key type, and there are no options
key_without_options = option_name + " "
option_name = ''
else:
if option_val is None:
options[option_name] = True
else:
options[option_name] = option_val
elif letter == '"':
quoted = True
elif letter == '=':
# '=' separated option name from value
in_option_name = False
if option_val is None:
option_val = ''
elif letter == ',':
# next option_name
if option_val is None:
options[option_name] = True
else:
options[option_name] = option_val
in_option_name = True
option_name = ''
option_val = None
else: # general unquoted letter
if in_option_name:
option_name += letter
else:
option_val += letter
else:
key_without_options += letter
if key_without_options == '':
# certain mal-formed keys (e.g. a line not containing any spaces)
# will be completely swallowed up by the above parser. It's
# better to follow the principle of least surprize and return the
# original line, allowing the error to be handled later.
return OrderedDict({}), line.strip()
else:
return options, key_without_options
|
[
"def",
"_extract_options",
"(",
"line",
")",
":",
"options",
"=",
"OrderedDict",
"(",
"{",
"}",
")",
"quoted",
"=",
"False",
"escaped",
"=",
"False",
"option_name",
"=",
"''",
"option_val",
"=",
"None",
"key_without_options",
"=",
"''",
"in_options",
"=",
"True",
"in_option_name",
"=",
"True",
"for",
"letter",
"in",
"line",
".",
"strip",
"(",
")",
":",
"if",
"in_options",
":",
"if",
"quoted",
":",
"if",
"letter",
"==",
"\"\\\\\"",
":",
"escaped",
"=",
"True",
"elif",
"letter",
"==",
"'\"'",
":",
"if",
"escaped",
":",
"option_val",
"+=",
"letter",
"escaped",
"=",
"False",
"else",
":",
"quoted",
"=",
"False",
"else",
":",
"if",
"escaped",
":",
"option_val",
"+=",
"\"\\\\\"",
"escaped",
"=",
"False",
"option_val",
"+=",
"letter",
"else",
":",
"# not quoted",
"if",
"letter",
"==",
"' '",
":",
"# end of options",
"in_options",
"=",
"False",
"if",
"(",
"option_name",
"in",
"[",
"'ssh-rsa'",
",",
"'ssh-dss'",
"]",
"or",
"option_name",
".",
"startswith",
"(",
"'ecdsa-'",
")",
")",
":",
"# what we thought was an option name was really the",
"# key type, and there are no options",
"key_without_options",
"=",
"option_name",
"+",
"\" \"",
"option_name",
"=",
"''",
"else",
":",
"if",
"option_val",
"is",
"None",
":",
"options",
"[",
"option_name",
"]",
"=",
"True",
"else",
":",
"options",
"[",
"option_name",
"]",
"=",
"option_val",
"elif",
"letter",
"==",
"'\"'",
":",
"quoted",
"=",
"True",
"elif",
"letter",
"==",
"'='",
":",
"# '=' separated option name from value",
"in_option_name",
"=",
"False",
"if",
"option_val",
"is",
"None",
":",
"option_val",
"=",
"''",
"elif",
"letter",
"==",
"','",
":",
"# next option_name",
"if",
"option_val",
"is",
"None",
":",
"options",
"[",
"option_name",
"]",
"=",
"True",
"else",
":",
"options",
"[",
"option_name",
"]",
"=",
"option_val",
"in_option_name",
"=",
"True",
"option_name",
"=",
"''",
"option_val",
"=",
"None",
"else",
":",
"# general unquoted letter",
"if",
"in_option_name",
":",
"option_name",
"+=",
"letter",
"else",
":",
"option_val",
"+=",
"letter",
"else",
":",
"key_without_options",
"+=",
"letter",
"if",
"key_without_options",
"==",
"''",
":",
"# certain mal-formed keys (e.g. a line not containing any spaces)",
"# will be completely swallowed up by the above parser. It's",
"# better to follow the principle of least surprize and return the",
"# original line, allowing the error to be handled later.",
"return",
"OrderedDict",
"(",
"{",
"}",
")",
",",
"line",
".",
"strip",
"(",
")",
"else",
":",
"return",
"options",
",",
"key_without_options"
] |
r'''Given a line as it would appear in the authorized_keys file,
return an OrderedDict of options, and the remainder of a line as a
string.
>>> Key._extract_options(r'no-pty,command="sh" ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
(OrderedDict([('no-pty', True), ('command', 'sh')]), 'ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk=')
>>> Key._extract_options(r'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
(OrderedDict(), 'ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU=')
|
[
"r",
"Given",
"a",
"line",
"as",
"it",
"would",
"appear",
"in",
"the",
"authorized_keys",
"file",
"return",
"an",
"OrderedDict",
"of",
"options",
"and",
"the",
"remainder",
"of",
"a",
"line",
"as",
"a",
"string",
"."
] |
d62e46fcc5e677827ad7f0663ab3b2f99fe564a0
|
https://github.com/mbr/sshkeys/blob/d62e46fcc5e677827ad7f0663ab3b2f99fe564a0/sshkeys/__init__.py#L59-L138
|
246,054
|
mbr/sshkeys
|
sshkeys/__init__.py
|
Key.from_pubkey_line
|
def from_pubkey_line(cls, line):
"""Generate Key instance from a a string. Raise ValueError if string is
malformed"""
options, key_without_options = cls._extract_options(line)
if key_without_options == '':
raise ValueError("Empty key")
# the key (with options stripped out) should consist of the fields
# "type", "data", and optionally "comment", separated by a space.
# The comment field may contain additional spaces
fields = key_without_options.strip().split(None, 2) # maxsplit=2
if len(fields) == 3:
type_str, data64, comment = fields
elif len(fields) == 2:
type_str, data64 = fields
comment = None
else: # len(fields) <= 1
raise ValueError("Key has insufficient number of fields")
try:
data = b64decode(data64)
except (binascii.Error, TypeError):
raise ValueError("Key contains invalid data")
key_type = next(iter_prefixed(data))
if key_type == b'ssh-rsa':
key_class = RSAKey
elif key_type == b'ssh-dss':
key_class = DSAKey
elif key_type.startswith(b'ecdsa-'):
key_class = ECDSAKey
else:
raise ValueError('Unknown key type {}'.format(key_type))
return key_class(b64decode(data64), comment, options=options)
|
python
|
def from_pubkey_line(cls, line):
"""Generate Key instance from a a string. Raise ValueError if string is
malformed"""
options, key_without_options = cls._extract_options(line)
if key_without_options == '':
raise ValueError("Empty key")
# the key (with options stripped out) should consist of the fields
# "type", "data", and optionally "comment", separated by a space.
# The comment field may contain additional spaces
fields = key_without_options.strip().split(None, 2) # maxsplit=2
if len(fields) == 3:
type_str, data64, comment = fields
elif len(fields) == 2:
type_str, data64 = fields
comment = None
else: # len(fields) <= 1
raise ValueError("Key has insufficient number of fields")
try:
data = b64decode(data64)
except (binascii.Error, TypeError):
raise ValueError("Key contains invalid data")
key_type = next(iter_prefixed(data))
if key_type == b'ssh-rsa':
key_class = RSAKey
elif key_type == b'ssh-dss':
key_class = DSAKey
elif key_type.startswith(b'ecdsa-'):
key_class = ECDSAKey
else:
raise ValueError('Unknown key type {}'.format(key_type))
return key_class(b64decode(data64), comment, options=options)
|
[
"def",
"from_pubkey_line",
"(",
"cls",
",",
"line",
")",
":",
"options",
",",
"key_without_options",
"=",
"cls",
".",
"_extract_options",
"(",
"line",
")",
"if",
"key_without_options",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"\"Empty key\"",
")",
"# the key (with options stripped out) should consist of the fields",
"# \"type\", \"data\", and optionally \"comment\", separated by a space.",
"# The comment field may contain additional spaces",
"fields",
"=",
"key_without_options",
".",
"strip",
"(",
")",
".",
"split",
"(",
"None",
",",
"2",
")",
"# maxsplit=2",
"if",
"len",
"(",
"fields",
")",
"==",
"3",
":",
"type_str",
",",
"data64",
",",
"comment",
"=",
"fields",
"elif",
"len",
"(",
"fields",
")",
"==",
"2",
":",
"type_str",
",",
"data64",
"=",
"fields",
"comment",
"=",
"None",
"else",
":",
"# len(fields) <= 1",
"raise",
"ValueError",
"(",
"\"Key has insufficient number of fields\"",
")",
"try",
":",
"data",
"=",
"b64decode",
"(",
"data64",
")",
"except",
"(",
"binascii",
".",
"Error",
",",
"TypeError",
")",
":",
"raise",
"ValueError",
"(",
"\"Key contains invalid data\"",
")",
"key_type",
"=",
"next",
"(",
"iter_prefixed",
"(",
"data",
")",
")",
"if",
"key_type",
"==",
"b'ssh-rsa'",
":",
"key_class",
"=",
"RSAKey",
"elif",
"key_type",
"==",
"b'ssh-dss'",
":",
"key_class",
"=",
"DSAKey",
"elif",
"key_type",
".",
"startswith",
"(",
"b'ecdsa-'",
")",
":",
"key_class",
"=",
"ECDSAKey",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown key type {}'",
".",
"format",
"(",
"key_type",
")",
")",
"return",
"key_class",
"(",
"b64decode",
"(",
"data64",
")",
",",
"comment",
",",
"options",
"=",
"options",
")"
] |
Generate Key instance from a a string. Raise ValueError if string is
malformed
|
[
"Generate",
"Key",
"instance",
"from",
"a",
"a",
"string",
".",
"Raise",
"ValueError",
"if",
"string",
"is",
"malformed"
] |
d62e46fcc5e677827ad7f0663ab3b2f99fe564a0
|
https://github.com/mbr/sshkeys/blob/d62e46fcc5e677827ad7f0663ab3b2f99fe564a0/sshkeys/__init__.py#L141-L175
|
246,055
|
mbr/sshkeys
|
sshkeys/__init__.py
|
Key.from_pubkey_file
|
def from_pubkey_file(cls, file):
"""Generate a Key instance from a file. Raise ValueError is key is
malformed"""
if hasattr(file, 'read'):
return cls.from_pubkey_line(file.read())
return cls.from_pubkey_line(open(file).read())
|
python
|
def from_pubkey_file(cls, file):
"""Generate a Key instance from a file. Raise ValueError is key is
malformed"""
if hasattr(file, 'read'):
return cls.from_pubkey_line(file.read())
return cls.from_pubkey_line(open(file).read())
|
[
"def",
"from_pubkey_file",
"(",
"cls",
",",
"file",
")",
":",
"if",
"hasattr",
"(",
"file",
",",
"'read'",
")",
":",
"return",
"cls",
".",
"from_pubkey_line",
"(",
"file",
".",
"read",
"(",
")",
")",
"return",
"cls",
".",
"from_pubkey_line",
"(",
"open",
"(",
"file",
")",
".",
"read",
"(",
")",
")"
] |
Generate a Key instance from a file. Raise ValueError is key is
malformed
|
[
"Generate",
"a",
"Key",
"instance",
"from",
"a",
"file",
".",
"Raise",
"ValueError",
"is",
"key",
"is",
"malformed"
] |
d62e46fcc5e677827ad7f0663ab3b2f99fe564a0
|
https://github.com/mbr/sshkeys/blob/d62e46fcc5e677827ad7f0663ab3b2f99fe564a0/sshkeys/__init__.py#L178-L184
|
246,056
|
blubberdiblub/eztemplate
|
eztemplate/engines/__init__.py
|
_init
|
def _init():
"""Dynamically import engines that initialize successfully."""
import importlib
import os
import re
filenames = os.listdir(os.path.dirname(__file__))
module_names = set()
for filename in filenames:
match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
if match:
module_names.add(match.group('name'))
for module_name in module_names:
try:
module = importlib.import_module('.' + module_name, __name__)
except ImportError:
continue
for name, member in module.__dict__.items():
if not isinstance(member, type):
# skip non-new-style classes
continue
if not issubclass(member, Engine):
# skip non-subclasses of Engine
continue
if member is Engine:
# skip "abstract" class Engine
continue
try:
handle = member.handle
except AttributeError:
continue
engines[handle] = member
|
python
|
def _init():
"""Dynamically import engines that initialize successfully."""
import importlib
import os
import re
filenames = os.listdir(os.path.dirname(__file__))
module_names = set()
for filename in filenames:
match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
if match:
module_names.add(match.group('name'))
for module_name in module_names:
try:
module = importlib.import_module('.' + module_name, __name__)
except ImportError:
continue
for name, member in module.__dict__.items():
if not isinstance(member, type):
# skip non-new-style classes
continue
if not issubclass(member, Engine):
# skip non-subclasses of Engine
continue
if member is Engine:
# skip "abstract" class Engine
continue
try:
handle = member.handle
except AttributeError:
continue
engines[handle] = member
|
[
"def",
"_init",
"(",
")",
":",
"import",
"importlib",
"import",
"os",
"import",
"re",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"module_names",
"=",
"set",
"(",
")",
"for",
"filename",
"in",
"filenames",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(?P<name>[A-Z_a-z]\\w*)\\.py[co]?$'",
",",
"filename",
")",
"if",
"match",
":",
"module_names",
".",
"add",
"(",
"match",
".",
"group",
"(",
"'name'",
")",
")",
"for",
"module_name",
"in",
"module_names",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"'.'",
"+",
"module_name",
",",
"__name__",
")",
"except",
"ImportError",
":",
"continue",
"for",
"name",
",",
"member",
"in",
"module",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"member",
",",
"type",
")",
":",
"# skip non-new-style classes",
"continue",
"if",
"not",
"issubclass",
"(",
"member",
",",
"Engine",
")",
":",
"# skip non-subclasses of Engine",
"continue",
"if",
"member",
"is",
"Engine",
":",
"# skip \"abstract\" class Engine",
"continue",
"try",
":",
"handle",
"=",
"member",
".",
"handle",
"except",
"AttributeError",
":",
"continue",
"engines",
"[",
"handle",
"]",
"=",
"member"
] |
Dynamically import engines that initialize successfully.
|
[
"Dynamically",
"import",
"engines",
"that",
"initialize",
"successfully",
"."
] |
ab5b2b4987c045116d130fd83e216704b8edfb5d
|
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/__init__.py#L113-L149
|
246,057
|
blubberdiblub/eztemplate
|
eztemplate/engines/__init__.py
|
Engine.str
|
def str(self, value, tolerant=False, limit=1000, seen=frozenset()):
"""Transform value into a representation suitable for substitution."""
if value is None:
if tolerant:
return ""
raise ValueError("value is None")
if isinstance(value, (bool, numbers.Number, basestring)):
return str(value)
if not isinstance(value, collections.Iterable):
if not tolerant:
raise ValueError("unknown value type")
try:
name = value.name
except AttributeError:
try:
name = value.__name__
except AttributeError:
try:
name = value.__class__.__name__
except AttributeError:
return "<?>"
return "<%s>" % (name,)
is_mapping = isinstance(value, collections.Mapping)
if not seen:
wrap = "%s"
elif is_mapping:
wrap = "{%s}"
else:
wrap = "[%s]"
id_ = id(value)
if id_ in seen:
if tolerant:
return wrap % ("...",)
raise ValueError("recursive representation")
seen = seen.union((id_,))
if is_mapping:
items = [(self.str(n, tolerant=tolerant, limit=limit, seen=seen),
self.str(v, tolerant=tolerant, limit=limit, seen=seen))
for n, v in value.items()]
items.sort()
items = ("%s=%s" for n, v in items)
else:
it = iter(value)
items = [self.str(item, tolerant=tolerant, limit=limit, seen=seen)
for item in itertools.islice(
it,
len(value)
if isinstance(value, collections.Sized)
else limit)]
items.sort()
try:
next(it)
except StopIteration:
pass
else:
if not tolerant:
raise ValueError("iterable too long")
items.append("...")
return wrap % (", ".join(items),)
|
python
|
def str(self, value, tolerant=False, limit=1000, seen=frozenset()):
"""Transform value into a representation suitable for substitution."""
if value is None:
if tolerant:
return ""
raise ValueError("value is None")
if isinstance(value, (bool, numbers.Number, basestring)):
return str(value)
if not isinstance(value, collections.Iterable):
if not tolerant:
raise ValueError("unknown value type")
try:
name = value.name
except AttributeError:
try:
name = value.__name__
except AttributeError:
try:
name = value.__class__.__name__
except AttributeError:
return "<?>"
return "<%s>" % (name,)
is_mapping = isinstance(value, collections.Mapping)
if not seen:
wrap = "%s"
elif is_mapping:
wrap = "{%s}"
else:
wrap = "[%s]"
id_ = id(value)
if id_ in seen:
if tolerant:
return wrap % ("...",)
raise ValueError("recursive representation")
seen = seen.union((id_,))
if is_mapping:
items = [(self.str(n, tolerant=tolerant, limit=limit, seen=seen),
self.str(v, tolerant=tolerant, limit=limit, seen=seen))
for n, v in value.items()]
items.sort()
items = ("%s=%s" for n, v in items)
else:
it = iter(value)
items = [self.str(item, tolerant=tolerant, limit=limit, seen=seen)
for item in itertools.islice(
it,
len(value)
if isinstance(value, collections.Sized)
else limit)]
items.sort()
try:
next(it)
except StopIteration:
pass
else:
if not tolerant:
raise ValueError("iterable too long")
items.append("...")
return wrap % (", ".join(items),)
|
[
"def",
"str",
"(",
"self",
",",
"value",
",",
"tolerant",
"=",
"False",
",",
"limit",
"=",
"1000",
",",
"seen",
"=",
"frozenset",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"tolerant",
":",
"return",
"\"\"",
"raise",
"ValueError",
"(",
"\"value is None\"",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"bool",
",",
"numbers",
".",
"Number",
",",
"basestring",
")",
")",
":",
"return",
"str",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Iterable",
")",
":",
"if",
"not",
"tolerant",
":",
"raise",
"ValueError",
"(",
"\"unknown value type\"",
")",
"try",
":",
"name",
"=",
"value",
".",
"name",
"except",
"AttributeError",
":",
"try",
":",
"name",
"=",
"value",
".",
"__name__",
"except",
"AttributeError",
":",
"try",
":",
"name",
"=",
"value",
".",
"__class__",
".",
"__name__",
"except",
"AttributeError",
":",
"return",
"\"<?>\"",
"return",
"\"<%s>\"",
"%",
"(",
"name",
",",
")",
"is_mapping",
"=",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
"if",
"not",
"seen",
":",
"wrap",
"=",
"\"%s\"",
"elif",
"is_mapping",
":",
"wrap",
"=",
"\"{%s}\"",
"else",
":",
"wrap",
"=",
"\"[%s]\"",
"id_",
"=",
"id",
"(",
"value",
")",
"if",
"id_",
"in",
"seen",
":",
"if",
"tolerant",
":",
"return",
"wrap",
"%",
"(",
"\"...\"",
",",
")",
"raise",
"ValueError",
"(",
"\"recursive representation\"",
")",
"seen",
"=",
"seen",
".",
"union",
"(",
"(",
"id_",
",",
")",
")",
"if",
"is_mapping",
":",
"items",
"=",
"[",
"(",
"self",
".",
"str",
"(",
"n",
",",
"tolerant",
"=",
"tolerant",
",",
"limit",
"=",
"limit",
",",
"seen",
"=",
"seen",
")",
",",
"self",
".",
"str",
"(",
"v",
",",
"tolerant",
"=",
"tolerant",
",",
"limit",
"=",
"limit",
",",
"seen",
"=",
"seen",
")",
")",
"for",
"n",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
"]",
"items",
".",
"sort",
"(",
")",
"items",
"=",
"(",
"\"%s=%s\"",
"for",
"n",
",",
"v",
"in",
"items",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"value",
")",
"items",
"=",
"[",
"self",
".",
"str",
"(",
"item",
",",
"tolerant",
"=",
"tolerant",
",",
"limit",
"=",
"limit",
",",
"seen",
"=",
"seen",
")",
"for",
"item",
"in",
"itertools",
".",
"islice",
"(",
"it",
",",
"len",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Sized",
")",
"else",
"limit",
")",
"]",
"items",
".",
"sort",
"(",
")",
"try",
":",
"next",
"(",
"it",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"if",
"not",
"tolerant",
":",
"raise",
"ValueError",
"(",
"\"iterable too long\"",
")",
"items",
".",
"append",
"(",
"\"...\"",
")",
"return",
"wrap",
"%",
"(",
"\", \"",
".",
"join",
"(",
"items",
")",
",",
")"
] |
Transform value into a representation suitable for substitution.
|
[
"Transform",
"value",
"into",
"a",
"representation",
"suitable",
"for",
"substitution",
"."
] |
ab5b2b4987c045116d130fd83e216704b8edfb5d
|
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/__init__.py#L35-L103
|
246,058
|
databuild/databuild
|
databuild/adapters/locmem/models.py
|
LocMemSheet._match
|
def _match(self, doc, where):
"""Return True if 'doc' matches the 'where' condition."""
assert isinstance(where, dict), "where is not a dictionary"
assert isinstance(doc, dict), "doc is not a dictionary"
try:
return all([doc[k] == v for k, v in where.items()])
except KeyError:
return False
|
python
|
def _match(self, doc, where):
"""Return True if 'doc' matches the 'where' condition."""
assert isinstance(where, dict), "where is not a dictionary"
assert isinstance(doc, dict), "doc is not a dictionary"
try:
return all([doc[k] == v for k, v in where.items()])
except KeyError:
return False
|
[
"def",
"_match",
"(",
"self",
",",
"doc",
",",
"where",
")",
":",
"assert",
"isinstance",
"(",
"where",
",",
"dict",
")",
",",
"\"where is not a dictionary\"",
"assert",
"isinstance",
"(",
"doc",
",",
"dict",
")",
",",
"\"doc is not a dictionary\"",
"try",
":",
"return",
"all",
"(",
"[",
"doc",
"[",
"k",
"]",
"==",
"v",
"for",
"k",
",",
"v",
"in",
"where",
".",
"items",
"(",
")",
"]",
")",
"except",
"KeyError",
":",
"return",
"False"
] |
Return True if 'doc' matches the 'where' condition.
|
[
"Return",
"True",
"if",
"doc",
"matches",
"the",
"where",
"condition",
"."
] |
4c8ee04fad1748f5b966753057ac05efbc289b10
|
https://github.com/databuild/databuild/blob/4c8ee04fad1748f5b966753057ac05efbc289b10/databuild/adapters/locmem/models.py#L24-L31
|
246,059
|
zeaphoo/budoc
|
budoc/pydoc.py
|
import_module
|
def import_module(module_name):
"""
Imports a module. A single point of truth for importing modules to
be documented by `pydoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pydoc.import_path`.
If a module has already been imported, then its corresponding entry
in `sys.modules` is returned. This means that modules that have
changed on disk cannot be re-imported in the same process and have
its documentation updated.
"""
if import_path != sys.path:
# Such a kludge. Only restrict imports if the `import_path` has
# been changed. We don't want to always restrict imports, since
# providing a path to `imp.find_module` stops it from searching
# in special locations for built ins or frozen modules.
#
# The problem here is that this relies on the `sys.path` not being
# independently changed since the initialization of this module.
# If it is changed, then some packages may fail.
#
# Any other options available?
# Raises an exception if the parent module cannot be imported.
# This hopefully ensures that we only explicitly import modules
# contained in `pydoc.import_path`.
imp.find_module(module_name.split('.')[0], import_path)
if module_name in sys.modules:
return sys.modules[module_name]
else:
__import__(module_name)
return sys.modules[module_name]
|
python
|
def import_module(module_name):
"""
Imports a module. A single point of truth for importing modules to
be documented by `pydoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pydoc.import_path`.
If a module has already been imported, then its corresponding entry
in `sys.modules` is returned. This means that modules that have
changed on disk cannot be re-imported in the same process and have
its documentation updated.
"""
if import_path != sys.path:
# Such a kludge. Only restrict imports if the `import_path` has
# been changed. We don't want to always restrict imports, since
# providing a path to `imp.find_module` stops it from searching
# in special locations for built ins or frozen modules.
#
# The problem here is that this relies on the `sys.path` not being
# independently changed since the initialization of this module.
# If it is changed, then some packages may fail.
#
# Any other options available?
# Raises an exception if the parent module cannot be imported.
# This hopefully ensures that we only explicitly import modules
# contained in `pydoc.import_path`.
imp.find_module(module_name.split('.')[0], import_path)
if module_name in sys.modules:
return sys.modules[module_name]
else:
__import__(module_name)
return sys.modules[module_name]
|
[
"def",
"import_module",
"(",
"module_name",
")",
":",
"if",
"import_path",
"!=",
"sys",
".",
"path",
":",
"# Such a kludge. Only restrict imports if the `import_path` has",
"# been changed. We don't want to always restrict imports, since",
"# providing a path to `imp.find_module` stops it from searching",
"# in special locations for built ins or frozen modules.",
"#",
"# The problem here is that this relies on the `sys.path` not being",
"# independently changed since the initialization of this module.",
"# If it is changed, then some packages may fail.",
"#",
"# Any other options available?",
"# Raises an exception if the parent module cannot be imported.",
"# This hopefully ensures that we only explicitly import modules",
"# contained in `pydoc.import_path`.",
"imp",
".",
"find_module",
"(",
"module_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
",",
"import_path",
")",
"if",
"module_name",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"else",
":",
"__import__",
"(",
"module_name",
")",
"return",
"sys",
".",
"modules",
"[",
"module_name",
"]"
] |
Imports a module. A single point of truth for importing modules to
be documented by `pydoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pydoc.import_path`.
If a module has already been imported, then its corresponding entry
in `sys.modules` is returned. This means that modules that have
changed on disk cannot be re-imported in the same process and have
its documentation updated.
|
[
"Imports",
"a",
"module",
".",
"A",
"single",
"point",
"of",
"truth",
"for",
"importing",
"modules",
"to",
"be",
"documented",
"by",
"pydoc",
".",
"In",
"particular",
"it",
"makes",
"sure",
"that",
"the",
"top",
"module",
"in",
"module_name",
"can",
"be",
"imported",
"by",
"using",
"only",
"the",
"paths",
"in",
"pydoc",
".",
"import_path",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L26-L59
|
246,060
|
zeaphoo/budoc
|
budoc/pydoc.py
|
_safe_import
|
def _safe_import(module_name):
"""
A function for safely importing `module_name`, where errors are
suppressed and `stdout` and `stderr` are redirected to a null
device. The obligation is on the caller to close `stdin` in order
to avoid impolite modules from blocking on `stdin` when imported.
"""
class _Null (object):
def write(self, *_):
pass
sout, serr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = _Null(), _Null()
try:
m = import_module(module_name)
except:
m = None
sys.stdout, sys.stderr = sout, serr
return m
|
python
|
def _safe_import(module_name):
"""
A function for safely importing `module_name`, where errors are
suppressed and `stdout` and `stderr` are redirected to a null
device. The obligation is on the caller to close `stdin` in order
to avoid impolite modules from blocking on `stdin` when imported.
"""
class _Null (object):
def write(self, *_):
pass
sout, serr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = _Null(), _Null()
try:
m = import_module(module_name)
except:
m = None
sys.stdout, sys.stderr = sout, serr
return m
|
[
"def",
"_safe_import",
"(",
"module_name",
")",
":",
"class",
"_Null",
"(",
"object",
")",
":",
"def",
"write",
"(",
"self",
",",
"*",
"_",
")",
":",
"pass",
"sout",
",",
"serr",
"=",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"=",
"_Null",
"(",
")",
",",
"_Null",
"(",
")",
"try",
":",
"m",
"=",
"import_module",
"(",
"module_name",
")",
"except",
":",
"m",
"=",
"None",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"=",
"sout",
",",
"serr",
"return",
"m"
] |
A function for safely importing `module_name`, where errors are
suppressed and `stdout` and `stderr` are redirected to a null
device. The obligation is on the caller to close `stdin` in order
to avoid impolite modules from blocking on `stdin` when imported.
|
[
"A",
"function",
"for",
"safely",
"importing",
"module_name",
"where",
"errors",
"are",
"suppressed",
"and",
"stdout",
"and",
"stderr",
"are",
"redirected",
"to",
"a",
"null",
"device",
".",
"The",
"obligation",
"is",
"on",
"the",
"caller",
"to",
"close",
"stdin",
"in",
"order",
"to",
"avoid",
"impolite",
"modules",
"from",
"blocking",
"on",
"stdin",
"when",
"imported",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L80-L98
|
246,061
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.mro
|
def mro(self, cls):
"""
Returns a method resolution list of documentation objects
for `cls`, which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
ups = inspect.getmro(cls.cls)
return list(map(lambda c: self.find_class(c), ups))
|
python
|
def mro(self, cls):
"""
Returns a method resolution list of documentation objects
for `cls`, which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
ups = inspect.getmro(cls.cls)
return list(map(lambda c: self.find_class(c), ups))
|
[
"def",
"mro",
"(",
"self",
",",
"cls",
")",
":",
"ups",
"=",
"inspect",
".",
"getmro",
"(",
"cls",
".",
"cls",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"c",
":",
"self",
".",
"find_class",
"(",
"c",
")",
",",
"ups",
")",
")"
] |
Returns a method resolution list of documentation objects
for `cls`, which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
|
[
"Returns",
"a",
"method",
"resolution",
"list",
"of",
"documentation",
"objects",
"for",
"cls",
"which",
"must",
"be",
"a",
"documentation",
"object",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L400-L410
|
246,062
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.descendents
|
def descendents(self, cls):
"""
Returns a descendent list of documentation objects for `cls`,
which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
if cls.cls == type or not hasattr(cls.cls, '__subclasses__'):
# Is this right?
return []
downs = cls.cls.__subclasses__()
return list(map(lambda c: self.find_class(c), downs))
|
python
|
def descendents(self, cls):
"""
Returns a descendent list of documentation objects for `cls`,
which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
"""
if cls.cls == type or not hasattr(cls.cls, '__subclasses__'):
# Is this right?
return []
downs = cls.cls.__subclasses__()
return list(map(lambda c: self.find_class(c), downs))
|
[
"def",
"descendents",
"(",
"self",
",",
"cls",
")",
":",
"if",
"cls",
".",
"cls",
"==",
"type",
"or",
"not",
"hasattr",
"(",
"cls",
".",
"cls",
",",
"'__subclasses__'",
")",
":",
"# Is this right?",
"return",
"[",
"]",
"downs",
"=",
"cls",
".",
"cls",
".",
"__subclasses__",
"(",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"c",
":",
"self",
".",
"find_class",
"(",
"c",
")",
",",
"downs",
")",
")"
] |
Returns a descendent list of documentation objects for `cls`,
which must be a documentation object.
The list will contain objects belonging to `pydoc.Class` or
`pydoc.External`. Objects belonging to the former are exported
classes either in this module or in one of its sub-modules.
|
[
"Returns",
"a",
"descendent",
"list",
"of",
"documentation",
"objects",
"for",
"cls",
"which",
"must",
"be",
"a",
"documentation",
"object",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L412-L426
|
246,063
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.find_class
|
def find_class(self, cls):
"""
Given a Python `cls` object, try to find it in this module
or in any of the exported identifiers of the submodules.
"""
for doc_cls in self.classes():
if cls is doc_cls.cls:
return doc_cls
for module in self.submodules():
doc_cls = module.find_class(cls)
if not isinstance(doc_cls, External):
return doc_cls
return External('%s.%s' % (cls.__module__, cls.__name__))
|
python
|
def find_class(self, cls):
"""
Given a Python `cls` object, try to find it in this module
or in any of the exported identifiers of the submodules.
"""
for doc_cls in self.classes():
if cls is doc_cls.cls:
return doc_cls
for module in self.submodules():
doc_cls = module.find_class(cls)
if not isinstance(doc_cls, External):
return doc_cls
return External('%s.%s' % (cls.__module__, cls.__name__))
|
[
"def",
"find_class",
"(",
"self",
",",
"cls",
")",
":",
"for",
"doc_cls",
"in",
"self",
".",
"classes",
"(",
")",
":",
"if",
"cls",
"is",
"doc_cls",
".",
"cls",
":",
"return",
"doc_cls",
"for",
"module",
"in",
"self",
".",
"submodules",
"(",
")",
":",
"doc_cls",
"=",
"module",
".",
"find_class",
"(",
"cls",
")",
"if",
"not",
"isinstance",
"(",
"doc_cls",
",",
"External",
")",
":",
"return",
"doc_cls",
"return",
"External",
"(",
"'%s.%s'",
"%",
"(",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
")",
")"
] |
Given a Python `cls` object, try to find it in this module
or in any of the exported identifiers of the submodules.
|
[
"Given",
"a",
"Python",
"cls",
"object",
"try",
"to",
"find",
"it",
"in",
"this",
"module",
"or",
"in",
"any",
"of",
"the",
"exported",
"identifiers",
"of",
"the",
"submodules",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L440-L452
|
246,064
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.variables
|
def variables(self):
"""
Returns all documented module level variables in the module
sorted alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
python
|
def variables(self):
"""
Returns all documented module level variables in the module
sorted alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
[
"def",
"variables",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"isinstance",
"(",
"o",
",",
"Variable",
")",
"and",
"self",
".",
"_docfilter",
"(",
"o",
")",
"return",
"sorted",
"(",
"filter",
"(",
"p",
",",
"self",
".",
"doc",
".",
"values",
"(",
")",
")",
")"
] |
Returns all documented module level variables in the module
sorted alphabetically as a list of `pydoc.Variable`.
|
[
"Returns",
"all",
"documented",
"module",
"level",
"variables",
"in",
"the",
"module",
"sorted",
"alphabetically",
"as",
"a",
"list",
"of",
"pydoc",
".",
"Variable",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L476-L482
|
246,065
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.classes
|
def classes(self):
"""
Returns all documented module level classes in the module
sorted alphabetically as a list of `pydoc.Class`.
"""
p = lambda o: isinstance(o, Class) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
python
|
def classes(self):
"""
Returns all documented module level classes in the module
sorted alphabetically as a list of `pydoc.Class`.
"""
p = lambda o: isinstance(o, Class) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
[
"def",
"classes",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"isinstance",
"(",
"o",
",",
"Class",
")",
"and",
"self",
".",
"_docfilter",
"(",
"o",
")",
"return",
"sorted",
"(",
"filter",
"(",
"p",
",",
"self",
".",
"doc",
".",
"values",
"(",
")",
")",
")"
] |
Returns all documented module level classes in the module
sorted alphabetically as a list of `pydoc.Class`.
|
[
"Returns",
"all",
"documented",
"module",
"level",
"classes",
"in",
"the",
"module",
"sorted",
"alphabetically",
"as",
"a",
"list",
"of",
"pydoc",
".",
"Class",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L484-L490
|
246,066
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.functions
|
def functions(self):
"""
Returns all documented module level functions in the module
sorted alphabetically as a list of `pydoc.Function`.
"""
p = lambda o: isinstance(o, Function) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
python
|
def functions(self):
"""
Returns all documented module level functions in the module
sorted alphabetically as a list of `pydoc.Function`.
"""
p = lambda o: isinstance(o, Function) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
[
"def",
"functions",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"isinstance",
"(",
"o",
",",
"Function",
")",
"and",
"self",
".",
"_docfilter",
"(",
"o",
")",
"return",
"sorted",
"(",
"filter",
"(",
"p",
",",
"self",
".",
"doc",
".",
"values",
"(",
")",
")",
")"
] |
Returns all documented module level functions in the module
sorted alphabetically as a list of `pydoc.Function`.
|
[
"Returns",
"all",
"documented",
"module",
"level",
"functions",
"in",
"the",
"module",
"sorted",
"alphabetically",
"as",
"a",
"list",
"of",
"pydoc",
".",
"Function",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L492-L498
|
246,067
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.submodules
|
def submodules(self):
"""
Returns all documented sub-modules in the module sorted
alphabetically as a list of `pydoc.Module`.
"""
p = lambda o: isinstance(o, Module) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
python
|
def submodules(self):
"""
Returns all documented sub-modules in the module sorted
alphabetically as a list of `pydoc.Module`.
"""
p = lambda o: isinstance(o, Module) and self._docfilter(o)
return sorted(filter(p, self.doc.values()))
|
[
"def",
"submodules",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"isinstance",
"(",
"o",
",",
"Module",
")",
"and",
"self",
".",
"_docfilter",
"(",
"o",
")",
"return",
"sorted",
"(",
"filter",
"(",
"p",
",",
"self",
".",
"doc",
".",
"values",
"(",
")",
")",
")"
] |
Returns all documented sub-modules in the module sorted
alphabetically as a list of `pydoc.Module`.
|
[
"Returns",
"all",
"documented",
"sub",
"-",
"modules",
"in",
"the",
"module",
"sorted",
"alphabetically",
"as",
"a",
"list",
"of",
"pydoc",
".",
"Module",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L500-L506
|
246,068
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.__is_exported
|
def __is_exported(self, name, module):
"""
Returns `True` if and only if `pydoc` considers `name` to be
a public identifier for this module where `name` was defined
in the Python module `module`.
If this module has an `__all__` attribute, then `name` is
considered to be exported if and only if it is a member of
this module's `__all__` list.
If `__all__` is not set, then whether `name` is exported or
not is heuristically determined. Firstly, if `name` starts
with an underscore, it will not be considered exported.
Secondly, if `name` was defined in a module other than this
one, it will not be considered exported. In all other cases,
`name` will be considered exported.
"""
if hasattr(self.module, '__all__'):
return name in self.module.__all__
if not _is_exported(name):
return False
if module is None:
return False
if module is not None and self.module.__name__ != module.__name__:
return name in self._declared_variables
return True
|
python
|
def __is_exported(self, name, module):
"""
Returns `True` if and only if `pydoc` considers `name` to be
a public identifier for this module where `name` was defined
in the Python module `module`.
If this module has an `__all__` attribute, then `name` is
considered to be exported if and only if it is a member of
this module's `__all__` list.
If `__all__` is not set, then whether `name` is exported or
not is heuristically determined. Firstly, if `name` starts
with an underscore, it will not be considered exported.
Secondly, if `name` was defined in a module other than this
one, it will not be considered exported. In all other cases,
`name` will be considered exported.
"""
if hasattr(self.module, '__all__'):
return name in self.module.__all__
if not _is_exported(name):
return False
if module is None:
return False
if module is not None and self.module.__name__ != module.__name__:
return name in self._declared_variables
return True
|
[
"def",
"__is_exported",
"(",
"self",
",",
"name",
",",
"module",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"'__all__'",
")",
":",
"return",
"name",
"in",
"self",
".",
"module",
".",
"__all__",
"if",
"not",
"_is_exported",
"(",
"name",
")",
":",
"return",
"False",
"if",
"module",
"is",
"None",
":",
"return",
"False",
"if",
"module",
"is",
"not",
"None",
"and",
"self",
".",
"module",
".",
"__name__",
"!=",
"module",
".",
"__name__",
":",
"return",
"name",
"in",
"self",
".",
"_declared_variables",
"return",
"True"
] |
Returns `True` if and only if `pydoc` considers `name` to be
a public identifier for this module where `name` was defined
in the Python module `module`.
If this module has an `__all__` attribute, then `name` is
considered to be exported if and only if it is a member of
this module's `__all__` list.
If `__all__` is not set, then whether `name` is exported or
not is heuristically determined. Firstly, if `name` starts
with an underscore, it will not be considered exported.
Secondly, if `name` was defined in a module other than this
one, it will not be considered exported. In all other cases,
`name` will be considered exported.
|
[
"Returns",
"True",
"if",
"and",
"only",
"if",
"pydoc",
"considers",
"name",
"to",
"be",
"a",
"public",
"identifier",
"for",
"this",
"module",
"where",
"name",
"was",
"defined",
"in",
"the",
"Python",
"module",
"module",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L516-L541
|
246,069
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.__public_objs
|
def __public_objs(self):
"""
Returns a dictionary mapping a public identifier name to a
Python object.
"""
members = dict(inspect.getmembers(self.module))
return dict([(name, obj)
for name, obj in members.items()
if self.__is_exported(name, inspect.getmodule(obj))])
|
python
|
def __public_objs(self):
"""
Returns a dictionary mapping a public identifier name to a
Python object.
"""
members = dict(inspect.getmembers(self.module))
return dict([(name, obj)
for name, obj in members.items()
if self.__is_exported(name, inspect.getmodule(obj))])
|
[
"def",
"__public_objs",
"(",
"self",
")",
":",
"members",
"=",
"dict",
"(",
"inspect",
".",
"getmembers",
"(",
"self",
".",
"module",
")",
")",
"return",
"dict",
"(",
"[",
"(",
"name",
",",
"obj",
")",
"for",
"name",
",",
"obj",
"in",
"members",
".",
"items",
"(",
")",
"if",
"self",
".",
"__is_exported",
"(",
"name",
",",
"inspect",
".",
"getmodule",
"(",
"obj",
")",
")",
"]",
")"
] |
Returns a dictionary mapping a public identifier name to a
Python object.
|
[
"Returns",
"a",
"dictionary",
"mapping",
"a",
"public",
"identifier",
"name",
"to",
"a",
"Python",
"object",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L543-L551
|
246,070
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Module.__new_submodule
|
def __new_submodule(self, name, obj):
"""
Create a new submodule documentation object for this `obj`,
which must by a Python module object and pass along any
settings in this module.
"""
# Forcefully set the module name so that it is always the absolute
# import path. We can't rely on `obj.__name__`, since it doesn't
# necessarily correspond to the public exported name of the module.
obj.__dict__['__budoc_module_name'] = '%s.%s' % (self.refname, name)
return Module(obj,
docfilter=self._docfilter,
allsubmodules=self._allsubmodules)
|
python
|
def __new_submodule(self, name, obj):
"""
Create a new submodule documentation object for this `obj`,
which must by a Python module object and pass along any
settings in this module.
"""
# Forcefully set the module name so that it is always the absolute
# import path. We can't rely on `obj.__name__`, since it doesn't
# necessarily correspond to the public exported name of the module.
obj.__dict__['__budoc_module_name'] = '%s.%s' % (self.refname, name)
return Module(obj,
docfilter=self._docfilter,
allsubmodules=self._allsubmodules)
|
[
"def",
"__new_submodule",
"(",
"self",
",",
"name",
",",
"obj",
")",
":",
"# Forcefully set the module name so that it is always the absolute",
"# import path. We can't rely on `obj.__name__`, since it doesn't",
"# necessarily correspond to the public exported name of the module.",
"obj",
".",
"__dict__",
"[",
"'__budoc_module_name'",
"]",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"refname",
",",
"name",
")",
"return",
"Module",
"(",
"obj",
",",
"docfilter",
"=",
"self",
".",
"_docfilter",
",",
"allsubmodules",
"=",
"self",
".",
"_allsubmodules",
")"
] |
Create a new submodule documentation object for this `obj`,
which must by a Python module object and pass along any
settings in this module.
|
[
"Create",
"a",
"new",
"submodule",
"documentation",
"object",
"for",
"this",
"obj",
"which",
"must",
"by",
"a",
"Python",
"module",
"object",
"and",
"pass",
"along",
"any",
"settings",
"in",
"this",
"module",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L553-L565
|
246,071
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Class.class_variables
|
def class_variables(self):
"""
Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o)
return filter(p, self.doc.values())
|
python
|
def class_variables(self):
"""
Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o)
return filter(p, self.doc.values())
|
[
"def",
"class_variables",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"isinstance",
"(",
"o",
",",
"Variable",
")",
"and",
"self",
".",
"module",
".",
"_docfilter",
"(",
"o",
")",
"return",
"filter",
"(",
"p",
",",
"self",
".",
"doc",
".",
"values",
"(",
")",
")"
] |
Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`.
|
[
"Returns",
"all",
"documented",
"class",
"variables",
"in",
"the",
"class",
"sorted",
"alphabetically",
"as",
"a",
"list",
"of",
"pydoc",
".",
"Variable",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L645-L651
|
246,072
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Class._fill_inheritance
|
def _fill_inheritance(self):
"""
Traverses this class's ancestor list and attempts to fill in
missing documentation from its ancestor's documentation.
The first pass connects variables, methods and functions with
their inherited couterparts. (The templates will decide how to
display docstrings.) The second pass attempts to add instance
variables to this class that were only explicitly declared in
a parent class. This second pass is necessary since instance
variables are only discoverable by traversing the abstract
syntax tree.
"""
mro = filter(lambda c: c != self and isinstance(c, Class),
self.module.mro(self))
def search(d, fdoc):
for c in mro:
doc = fdoc(c)
if d.name in doc and isinstance(d, type(doc[d.name])):
return doc[d.name]
return None
for fdoc in (lambda c: c.doc_init, lambda c: c.doc):
for d in fdoc(self).values():
dinherit = search(d, fdoc)
if dinherit is not None:
d.inherits = dinherit
# Since instance variables aren't part of a class's members,
# we need to manually deduce inheritance. Oh lawdy.
for c in mro:
for name in filter(lambda n: n not in self.doc_init, c.doc_init):
d = c.doc_init[name]
self.doc_init[name] = Variable(d.name, d.module, '', cls=self)
self.doc_init[name].inherits = d
|
python
|
def _fill_inheritance(self):
"""
Traverses this class's ancestor list and attempts to fill in
missing documentation from its ancestor's documentation.
The first pass connects variables, methods and functions with
their inherited couterparts. (The templates will decide how to
display docstrings.) The second pass attempts to add instance
variables to this class that were only explicitly declared in
a parent class. This second pass is necessary since instance
variables are only discoverable by traversing the abstract
syntax tree.
"""
mro = filter(lambda c: c != self and isinstance(c, Class),
self.module.mro(self))
def search(d, fdoc):
for c in mro:
doc = fdoc(c)
if d.name in doc and isinstance(d, type(doc[d.name])):
return doc[d.name]
return None
for fdoc in (lambda c: c.doc_init, lambda c: c.doc):
for d in fdoc(self).values():
dinherit = search(d, fdoc)
if dinherit is not None:
d.inherits = dinherit
# Since instance variables aren't part of a class's members,
# we need to manually deduce inheritance. Oh lawdy.
for c in mro:
for name in filter(lambda n: n not in self.doc_init, c.doc_init):
d = c.doc_init[name]
self.doc_init[name] = Variable(d.name, d.module, '', cls=self)
self.doc_init[name].inherits = d
|
[
"def",
"_fill_inheritance",
"(",
"self",
")",
":",
"mro",
"=",
"filter",
"(",
"lambda",
"c",
":",
"c",
"!=",
"self",
"and",
"isinstance",
"(",
"c",
",",
"Class",
")",
",",
"self",
".",
"module",
".",
"mro",
"(",
"self",
")",
")",
"def",
"search",
"(",
"d",
",",
"fdoc",
")",
":",
"for",
"c",
"in",
"mro",
":",
"doc",
"=",
"fdoc",
"(",
"c",
")",
"if",
"d",
".",
"name",
"in",
"doc",
"and",
"isinstance",
"(",
"d",
",",
"type",
"(",
"doc",
"[",
"d",
".",
"name",
"]",
")",
")",
":",
"return",
"doc",
"[",
"d",
".",
"name",
"]",
"return",
"None",
"for",
"fdoc",
"in",
"(",
"lambda",
"c",
":",
"c",
".",
"doc_init",
",",
"lambda",
"c",
":",
"c",
".",
"doc",
")",
":",
"for",
"d",
"in",
"fdoc",
"(",
"self",
")",
".",
"values",
"(",
")",
":",
"dinherit",
"=",
"search",
"(",
"d",
",",
"fdoc",
")",
"if",
"dinherit",
"is",
"not",
"None",
":",
"d",
".",
"inherits",
"=",
"dinherit",
"# Since instance variables aren't part of a class's members,",
"# we need to manually deduce inheritance. Oh lawdy.",
"for",
"c",
"in",
"mro",
":",
"for",
"name",
"in",
"filter",
"(",
"lambda",
"n",
":",
"n",
"not",
"in",
"self",
".",
"doc_init",
",",
"c",
".",
"doc_init",
")",
":",
"d",
"=",
"c",
".",
"doc_init",
"[",
"name",
"]",
"self",
".",
"doc_init",
"[",
"name",
"]",
"=",
"Variable",
"(",
"d",
".",
"name",
",",
"d",
".",
"module",
",",
"''",
",",
"cls",
"=",
"self",
")",
"self",
".",
"doc_init",
"[",
"name",
"]",
".",
"inherits",
"=",
"d"
] |
Traverses this class's ancestor list and attempts to fill in
missing documentation from its ancestor's documentation.
The first pass connects variables, methods and functions with
their inherited couterparts. (The templates will decide how to
display docstrings.) The second pass attempts to add instance
variables to this class that were only explicitly declared in
a parent class. This second pass is necessary since instance
variables are only discoverable by traversing the abstract
syntax tree.
|
[
"Traverses",
"this",
"class",
"s",
"ancestor",
"list",
"and",
"attempts",
"to",
"fill",
"in",
"missing",
"documentation",
"from",
"its",
"ancestor",
"s",
"documentation",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L694-L728
|
246,073
|
zeaphoo/budoc
|
budoc/pydoc.py
|
Function.params
|
def params(self):
"""
Returns a list where each element is a nicely formatted
parameter of this function. This includes argument lists,
keyword arguments and default values.
"""
def fmt_param(el):
if isinstance(el, str) or isinstance(el, unicode):
return el
else:
return '(%s)' % (', '.join(map(fmt_param, el)))
try:
getspec = getattr(inspect, 'getfullargspec', inspect.getargspec)
s = getspec(self.func)
except TypeError:
# I guess this is for C builtin functions?
return ['...']
params = []
for i, param in enumerate(s.args):
if param.lower() == 'self':
continue
if s.defaults is not None and len(s.args) - i <= len(s.defaults):
defind = len(s.defaults) - (len(s.args) - i)
default_value = s.defaults[defind]
value = repr(default_value).strip()
if value[0] == '<' and value[-1] == '>':
if type(default_value) == types.TypeType:
value = default_value.__name__
elif type(default_value) == types.ObjectType:
value = '%s()'%(default_value.__class__.__name__)
params.append('%s=%s' % (param, value))
else:
params.append(fmt_param(param))
if s.varargs is not None:
params.append('*%s' % s.varargs)
# TODO: This needs to be adjusted in Python 3. There's more stuff
# returned from getfullargspec than what we're looking at here.
keywords = getattr(s, 'varkw', getattr(s, 'keywords', None))
if keywords is not None:
params.append('**%s' % keywords)
return params
|
python
|
def params(self):
"""
Returns a list where each element is a nicely formatted
parameter of this function. This includes argument lists,
keyword arguments and default values.
"""
def fmt_param(el):
if isinstance(el, str) or isinstance(el, unicode):
return el
else:
return '(%s)' % (', '.join(map(fmt_param, el)))
try:
getspec = getattr(inspect, 'getfullargspec', inspect.getargspec)
s = getspec(self.func)
except TypeError:
# I guess this is for C builtin functions?
return ['...']
params = []
for i, param in enumerate(s.args):
if param.lower() == 'self':
continue
if s.defaults is not None and len(s.args) - i <= len(s.defaults):
defind = len(s.defaults) - (len(s.args) - i)
default_value = s.defaults[defind]
value = repr(default_value).strip()
if value[0] == '<' and value[-1] == '>':
if type(default_value) == types.TypeType:
value = default_value.__name__
elif type(default_value) == types.ObjectType:
value = '%s()'%(default_value.__class__.__name__)
params.append('%s=%s' % (param, value))
else:
params.append(fmt_param(param))
if s.varargs is not None:
params.append('*%s' % s.varargs)
# TODO: This needs to be adjusted in Python 3. There's more stuff
# returned from getfullargspec than what we're looking at here.
keywords = getattr(s, 'varkw', getattr(s, 'keywords', None))
if keywords is not None:
params.append('**%s' % keywords)
return params
|
[
"def",
"params",
"(",
"self",
")",
":",
"def",
"fmt_param",
"(",
"el",
")",
":",
"if",
"isinstance",
"(",
"el",
",",
"str",
")",
"or",
"isinstance",
"(",
"el",
",",
"unicode",
")",
":",
"return",
"el",
"else",
":",
"return",
"'(%s)'",
"%",
"(",
"', '",
".",
"join",
"(",
"map",
"(",
"fmt_param",
",",
"el",
")",
")",
")",
"try",
":",
"getspec",
"=",
"getattr",
"(",
"inspect",
",",
"'getfullargspec'",
",",
"inspect",
".",
"getargspec",
")",
"s",
"=",
"getspec",
"(",
"self",
".",
"func",
")",
"except",
"TypeError",
":",
"# I guess this is for C builtin functions?",
"return",
"[",
"'...'",
"]",
"params",
"=",
"[",
"]",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"s",
".",
"args",
")",
":",
"if",
"param",
".",
"lower",
"(",
")",
"==",
"'self'",
":",
"continue",
"if",
"s",
".",
"defaults",
"is",
"not",
"None",
"and",
"len",
"(",
"s",
".",
"args",
")",
"-",
"i",
"<=",
"len",
"(",
"s",
".",
"defaults",
")",
":",
"defind",
"=",
"len",
"(",
"s",
".",
"defaults",
")",
"-",
"(",
"len",
"(",
"s",
".",
"args",
")",
"-",
"i",
")",
"default_value",
"=",
"s",
".",
"defaults",
"[",
"defind",
"]",
"value",
"=",
"repr",
"(",
"default_value",
")",
".",
"strip",
"(",
")",
"if",
"value",
"[",
"0",
"]",
"==",
"'<'",
"and",
"value",
"[",
"-",
"1",
"]",
"==",
"'>'",
":",
"if",
"type",
"(",
"default_value",
")",
"==",
"types",
".",
"TypeType",
":",
"value",
"=",
"default_value",
".",
"__name__",
"elif",
"type",
"(",
"default_value",
")",
"==",
"types",
".",
"ObjectType",
":",
"value",
"=",
"'%s()'",
"%",
"(",
"default_value",
".",
"__class__",
".",
"__name__",
")",
"params",
".",
"append",
"(",
"'%s=%s'",
"%",
"(",
"param",
",",
"value",
")",
")",
"else",
":",
"params",
".",
"append",
"(",
"fmt_param",
"(",
"param",
")",
")",
"if",
"s",
".",
"varargs",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"'*%s'",
"%",
"s",
".",
"varargs",
")",
"# TODO: This needs to be adjusted in Python 3. There's more stuff",
"# returned from getfullargspec than what we're looking at here.",
"keywords",
"=",
"getattr",
"(",
"s",
",",
"'varkw'",
",",
"getattr",
"(",
"s",
",",
"'keywords'",
",",
"None",
")",
")",
"if",
"keywords",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"'**%s'",
"%",
"keywords",
")",
"return",
"params"
] |
Returns a list where each element is a nicely formatted
parameter of this function. This includes argument lists,
keyword arguments and default values.
|
[
"Returns",
"a",
"list",
"where",
"each",
"element",
"is",
"a",
"nicely",
"formatted",
"parameter",
"of",
"this",
"function",
".",
"This",
"includes",
"argument",
"lists",
"keyword",
"arguments",
"and",
"default",
"values",
"."
] |
28f3aea4ad72ac90605ced012ed20e61af90c23a
|
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/pydoc.py#L802-L844
|
246,074
|
thomasvandoren/bugzscout-py
|
bugzscout/ext/cli.py
|
_defaults
|
def _defaults():
"""Returns a dict of default args from the environment, which can be
overridden by command line args.
"""
d = {}
d['url'] = os.environ.get('BUGZSCOUT_URL')
d['user'] = os.environ.get('BUGZSCOUT_USER')
d['project'] = os.environ.get('BUGZSCOUT_PROJECT')
d['area'] = os.environ.get('BUGZSCOUT_AREA')
return d
|
python
|
def _defaults():
"""Returns a dict of default args from the environment, which can be
overridden by command line args.
"""
d = {}
d['url'] = os.environ.get('BUGZSCOUT_URL')
d['user'] = os.environ.get('BUGZSCOUT_USER')
d['project'] = os.environ.get('BUGZSCOUT_PROJECT')
d['area'] = os.environ.get('BUGZSCOUT_AREA')
return d
|
[
"def",
"_defaults",
"(",
")",
":",
"d",
"=",
"{",
"}",
"d",
"[",
"'url'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BUGZSCOUT_URL'",
")",
"d",
"[",
"'user'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BUGZSCOUT_USER'",
")",
"d",
"[",
"'project'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BUGZSCOUT_PROJECT'",
")",
"d",
"[",
"'area'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BUGZSCOUT_AREA'",
")",
"return",
"d"
] |
Returns a dict of default args from the environment, which can be
overridden by command line args.
|
[
"Returns",
"a",
"dict",
"of",
"default",
"args",
"from",
"the",
"environment",
"which",
"can",
"be",
"overridden",
"by",
"command",
"line",
"args",
"."
] |
514528e958a97e0e7b36870037c5c69661511824
|
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L30-L39
|
246,075
|
thomasvandoren/bugzscout-py
|
bugzscout/ext/cli.py
|
_from_args
|
def _from_args(args):
"""Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace`
"""
return bugzscout.BugzScout(args.url, args.user, args.project, args.area)
|
python
|
def _from_args(args):
"""Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace`
"""
return bugzscout.BugzScout(args.url, args.user, args.project, args.area)
|
[
"def",
"_from_args",
"(",
"args",
")",
":",
"return",
"bugzscout",
".",
"BugzScout",
"(",
"args",
".",
"url",
",",
"args",
".",
"user",
",",
"args",
".",
"project",
",",
"args",
".",
"area",
")"
] |
Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace`
|
[
"Factory",
"method",
"to",
"create",
"a",
"new",
"instance",
"from",
"command",
"line",
"args",
"."
] |
514528e958a97e0e7b36870037c5c69661511824
|
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L42-L47
|
246,076
|
thomasvandoren/bugzscout-py
|
bugzscout/ext/cli.py
|
_init_logging
|
def _init_logging(verbose):
"""Enable logging o stream."""
hdlr = logging.StreamHandler()
hdlr.setFormatter(logging.Formatter(
'%(asctime)s [%(levelname)s] [%(module)s] %(message)s'))
LOG.addHandler(hdlr)
if verbose:
LOG.setLevel(logging.DEBUG)
LOG.debug('Verbose output enabled.')
else:
LOG.setLevel(logging.INFO)
|
python
|
def _init_logging(verbose):
"""Enable logging o stream."""
hdlr = logging.StreamHandler()
hdlr.setFormatter(logging.Formatter(
'%(asctime)s [%(levelname)s] [%(module)s] %(message)s'))
LOG.addHandler(hdlr)
if verbose:
LOG.setLevel(logging.DEBUG)
LOG.debug('Verbose output enabled.')
else:
LOG.setLevel(logging.INFO)
|
[
"def",
"_init_logging",
"(",
"verbose",
")",
":",
"hdlr",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"hdlr",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s [%(levelname)s] [%(module)s] %(message)s'",
")",
")",
"LOG",
".",
"addHandler",
"(",
"hdlr",
")",
"if",
"verbose",
":",
"LOG",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"LOG",
".",
"debug",
"(",
"'Verbose output enabled.'",
")",
"else",
":",
"LOG",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")"
] |
Enable logging o stream.
|
[
"Enable",
"logging",
"o",
"stream",
"."
] |
514528e958a97e0e7b36870037c5c69661511824
|
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L50-L60
|
246,077
|
thomasvandoren/bugzscout-py
|
bugzscout/ext/cli.py
|
_parse_args
|
def _parse_args():
"""Parse and return command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=_CliFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output.')
fb_group = parser.add_argument_group('FogBugz arguments')
fb_group.add_argument(
'-u', '--url', help=(
'URL for bugzscout requests to be sent. Should be something '
'like .../scoutSubmit.asp.'))
fb_group.add_argument(
'--user', help='User to designate when submitting via bugzscout.')
fb_group.add_argument(
'--project', help='Fogbugz project to file cases under.')
fb_group.add_argument(
'--area', help='Fogbugz area to file cases under.')
error_group = parser.add_argument_group('error arguments')
error_group.add_argument('-e', '--extra',
help='Extra data to send with error.')
error_group.add_argument('--default-message',
help='Set default message if case is new.')
error_group.add_argument('description',
help=('Description of error. Will be matched '
'against existing cases.'))
parser.set_defaults(**_defaults())
return parser.parse_args()
|
python
|
def _parse_args():
"""Parse and return command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=_CliFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output.')
fb_group = parser.add_argument_group('FogBugz arguments')
fb_group.add_argument(
'-u', '--url', help=(
'URL for bugzscout requests to be sent. Should be something '
'like .../scoutSubmit.asp.'))
fb_group.add_argument(
'--user', help='User to designate when submitting via bugzscout.')
fb_group.add_argument(
'--project', help='Fogbugz project to file cases under.')
fb_group.add_argument(
'--area', help='Fogbugz area to file cases under.')
error_group = parser.add_argument_group('error arguments')
error_group.add_argument('-e', '--extra',
help='Extra data to send with error.')
error_group.add_argument('--default-message',
help='Set default message if case is new.')
error_group.add_argument('description',
help=('Description of error. Will be matched '
'against existing cases.'))
parser.set_defaults(**_defaults())
return parser.parse_args()
|
[
"def",
"_parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"_CliFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Enable verbose output.'",
")",
"fb_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'FogBugz arguments'",
")",
"fb_group",
".",
"add_argument",
"(",
"'-u'",
",",
"'--url'",
",",
"help",
"=",
"(",
"'URL for bugzscout requests to be sent. Should be something '",
"'like .../scoutSubmit.asp.'",
")",
")",
"fb_group",
".",
"add_argument",
"(",
"'--user'",
",",
"help",
"=",
"'User to designate when submitting via bugzscout.'",
")",
"fb_group",
".",
"add_argument",
"(",
"'--project'",
",",
"help",
"=",
"'Fogbugz project to file cases under.'",
")",
"fb_group",
".",
"add_argument",
"(",
"'--area'",
",",
"help",
"=",
"'Fogbugz area to file cases under.'",
")",
"error_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'error arguments'",
")",
"error_group",
".",
"add_argument",
"(",
"'-e'",
",",
"'--extra'",
",",
"help",
"=",
"'Extra data to send with error.'",
")",
"error_group",
".",
"add_argument",
"(",
"'--default-message'",
",",
"help",
"=",
"'Set default message if case is new.'",
")",
"error_group",
".",
"add_argument",
"(",
"'description'",
",",
"help",
"=",
"(",
"'Description of error. Will be matched '",
"'against existing cases.'",
")",
")",
"parser",
".",
"set_defaults",
"(",
"*",
"*",
"_defaults",
"(",
")",
")",
"return",
"parser",
".",
"parse_args",
"(",
")"
] |
Parse and return command line arguments.
|
[
"Parse",
"and",
"return",
"command",
"line",
"arguments",
"."
] |
514528e958a97e0e7b36870037c5c69661511824
|
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L63-L94
|
246,078
|
thomasvandoren/bugzscout-py
|
bugzscout/ext/cli.py
|
main
|
def main():
"""Create a new instance and publish an error from command line args.
There is a console script for invoking this function from the command
line directly.
"""
args = _parse_args()
_init_logging(args.verbose)
client = _from_args(args)
client.submit_error(args.description, args.extra,
default_message=args.default_message)
|
python
|
def main():
"""Create a new instance and publish an error from command line args.
There is a console script for invoking this function from the command
line directly.
"""
args = _parse_args()
_init_logging(args.verbose)
client = _from_args(args)
client.submit_error(args.description, args.extra,
default_message=args.default_message)
|
[
"def",
"main",
"(",
")",
":",
"args",
"=",
"_parse_args",
"(",
")",
"_init_logging",
"(",
"args",
".",
"verbose",
")",
"client",
"=",
"_from_args",
"(",
"args",
")",
"client",
".",
"submit_error",
"(",
"args",
".",
"description",
",",
"args",
".",
"extra",
",",
"default_message",
"=",
"args",
".",
"default_message",
")"
] |
Create a new instance and publish an error from command line args.
There is a console script for invoking this function from the command
line directly.
|
[
"Create",
"a",
"new",
"instance",
"and",
"publish",
"an",
"error",
"from",
"command",
"line",
"args",
"."
] |
514528e958a97e0e7b36870037c5c69661511824
|
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L97-L107
|
246,079
|
ryanjdillon/pyotelem
|
pyotelem/plots/plotdsp.py
|
plot_lf_hf
|
def plot_lf_hf(x, xlf, xhf, title=''):
'''Plot original signal, low-pass filtered, and high-pass filtered signals
Args
----
x: ndarray
Signal data array
xlf: ndarray
Low-pass filtered signal
xhf: ndarray
High-pass filtered signal
title: str
Main title of plot
'''
from . import plotutils
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, sharey=True)
plt.title(title)
#ax1.title.set_text('All freqencies')
ax1.plot(range(len(x)), x, color=_colors[0], linewidth=_linewidth,
label='original')
ax1.legend(loc='upper right')
#ax2.title.set_text('Low-pass filtered')
ax2.plot(range(len(xlf)), xlf, color=_colors[1], linewidth=_linewidth,
label='low-pass')
ax2.legend(loc='upper right')
ax2.set_ylabel('Frequency (Hz)')
#ax3.title.set_text('High-pass filtered')
ax3.plot(range(len(xhf)), xhf, color=_colors[2], linewidth=_linewidth,
label='high-pass')
ax3.legend(loc='upper right')
ax1, ax2, ax3 = plotutils.add_alpha_labels([ax1, ax2, ax3], color='black',
facecolor='none',
edgecolor='none')
# TODO break into util function
# Convert sample # ticks to times
total_seconds = ax3.get_xticks()/16
# with timedelta: (stop - start).total_seconds()
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
strtime = lambda minutes, seconds: '{:.0f}:{:02.0f}'.format(minutes, seconds)
labels = list(map(strtime, minutes, seconds))
ax3.set_xticklabels(labels)
plt.xlabel('Sample time (minute:second)')
plt.show()
return None
|
python
|
def plot_lf_hf(x, xlf, xhf, title=''):
'''Plot original signal, low-pass filtered, and high-pass filtered signals
Args
----
x: ndarray
Signal data array
xlf: ndarray
Low-pass filtered signal
xhf: ndarray
High-pass filtered signal
title: str
Main title of plot
'''
from . import plotutils
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, sharey=True)
plt.title(title)
#ax1.title.set_text('All freqencies')
ax1.plot(range(len(x)), x, color=_colors[0], linewidth=_linewidth,
label='original')
ax1.legend(loc='upper right')
#ax2.title.set_text('Low-pass filtered')
ax2.plot(range(len(xlf)), xlf, color=_colors[1], linewidth=_linewidth,
label='low-pass')
ax2.legend(loc='upper right')
ax2.set_ylabel('Frequency (Hz)')
#ax3.title.set_text('High-pass filtered')
ax3.plot(range(len(xhf)), xhf, color=_colors[2], linewidth=_linewidth,
label='high-pass')
ax3.legend(loc='upper right')
ax1, ax2, ax3 = plotutils.add_alpha_labels([ax1, ax2, ax3], color='black',
facecolor='none',
edgecolor='none')
# TODO break into util function
# Convert sample # ticks to times
total_seconds = ax3.get_xticks()/16
# with timedelta: (stop - start).total_seconds()
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
strtime = lambda minutes, seconds: '{:.0f}:{:02.0f}'.format(minutes, seconds)
labels = list(map(strtime, minutes, seconds))
ax3.set_xticklabels(labels)
plt.xlabel('Sample time (minute:second)')
plt.show()
return None
|
[
"def",
"plot_lf_hf",
"(",
"x",
",",
"xlf",
",",
"xhf",
",",
"title",
"=",
"''",
")",
":",
"from",
".",
"import",
"plotutils",
"fig",
",",
"(",
"ax1",
",",
"ax2",
",",
"ax3",
")",
"=",
"plt",
".",
"subplots",
"(",
"3",
",",
"1",
",",
"sharex",
"=",
"True",
",",
"sharey",
"=",
"True",
")",
"plt",
".",
"title",
"(",
"title",
")",
"#ax1.title.set_text('All freqencies')",
"ax1",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"x",
")",
")",
",",
"x",
",",
"color",
"=",
"_colors",
"[",
"0",
"]",
",",
"linewidth",
"=",
"_linewidth",
",",
"label",
"=",
"'original'",
")",
"ax1",
".",
"legend",
"(",
"loc",
"=",
"'upper right'",
")",
"#ax2.title.set_text('Low-pass filtered')",
"ax2",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"xlf",
")",
")",
",",
"xlf",
",",
"color",
"=",
"_colors",
"[",
"1",
"]",
",",
"linewidth",
"=",
"_linewidth",
",",
"label",
"=",
"'low-pass'",
")",
"ax2",
".",
"legend",
"(",
"loc",
"=",
"'upper right'",
")",
"ax2",
".",
"set_ylabel",
"(",
"'Frequency (Hz)'",
")",
"#ax3.title.set_text('High-pass filtered')",
"ax3",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"xhf",
")",
")",
",",
"xhf",
",",
"color",
"=",
"_colors",
"[",
"2",
"]",
",",
"linewidth",
"=",
"_linewidth",
",",
"label",
"=",
"'high-pass'",
")",
"ax3",
".",
"legend",
"(",
"loc",
"=",
"'upper right'",
")",
"ax1",
",",
"ax2",
",",
"ax3",
"=",
"plotutils",
".",
"add_alpha_labels",
"(",
"[",
"ax1",
",",
"ax2",
",",
"ax3",
"]",
",",
"color",
"=",
"'black'",
",",
"facecolor",
"=",
"'none'",
",",
"edgecolor",
"=",
"'none'",
")",
"# TODO break into util function",
"# Convert sample # ticks to times",
"total_seconds",
"=",
"ax3",
".",
"get_xticks",
"(",
")",
"/",
"16",
"# with timedelta: (stop - start).total_seconds()",
"hours",
",",
"remainder",
"=",
"divmod",
"(",
"total_seconds",
",",
"3600",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"remainder",
",",
"60",
")",
"strtime",
"=",
"lambda",
"minutes",
",",
"seconds",
":",
"'{:.0f}:{:02.0f}'",
".",
"format",
"(",
"minutes",
",",
"seconds",
")",
"labels",
"=",
"list",
"(",
"map",
"(",
"strtime",
",",
"minutes",
",",
"seconds",
")",
")",
"ax3",
".",
"set_xticklabels",
"(",
"labels",
")",
"plt",
".",
"xlabel",
"(",
"'Sample time (minute:second)'",
")",
"plt",
".",
"show",
"(",
")",
"return",
"None"
] |
Plot original signal, low-pass filtered, and high-pass filtered signals
Args
----
x: ndarray
Signal data array
xlf: ndarray
Low-pass filtered signal
xhf: ndarray
High-pass filtered signal
title: str
Main title of plot
|
[
"Plot",
"original",
"signal",
"low",
"-",
"pass",
"filtered",
"and",
"high",
"-",
"pass",
"filtered",
"signals"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdsp.py#L10-L66
|
246,080
|
ryanjdillon/pyotelem
|
pyotelem/plots/plotdsp.py
|
plot_acc_pry_depth
|
def plot_acc_pry_depth(A_g_lf, A_g_hf, pry_deg, depths, glide_mask=None):
'''Plot the acceleration with the pitch, roll, and heading
Args
----
A_g_lf: ndarray
Low-pass filtered calibration accelerometer signal
A_g_hf: ndarray
High-pass filtered calibration accelerometer signal
pry_deg: ndarray
Pitch roll and heading in degrees
depths: ndarray
Depth data for all samples
glide_mask: ndarray
Boolean array for slicing glides from tag data
'''
import numpy
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True)
ax1.title.set_text('acceleromter')
ax1.plot(range(len(A_g_lf)), A_g_lf, color=_colors[0])
ax1.title.set_text('PRH')
ax2.plot(range(len(pry_deg)), pry_deg, color=_colors[1])
ax3.title.set_text('depth')
ax3.plot(range(len(depths)), depths, color=_colors[2])
ax3.invert_yaxis()
if glide_mask is not None:
ind = range(len(glide_mask))
ax1 = plot_shade_mask(ax1, ind, glide_mask)
ax2 = plot_shade_mask(ax2, ind, glide_mask)
ax3 = plot_shade_mask(ax3, ind, glide_mask)
plt.show()
return None
|
python
|
def plot_acc_pry_depth(A_g_lf, A_g_hf, pry_deg, depths, glide_mask=None):
'''Plot the acceleration with the pitch, roll, and heading
Args
----
A_g_lf: ndarray
Low-pass filtered calibration accelerometer signal
A_g_hf: ndarray
High-pass filtered calibration accelerometer signal
pry_deg: ndarray
Pitch roll and heading in degrees
depths: ndarray
Depth data for all samples
glide_mask: ndarray
Boolean array for slicing glides from tag data
'''
import numpy
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True)
ax1.title.set_text('acceleromter')
ax1.plot(range(len(A_g_lf)), A_g_lf, color=_colors[0])
ax1.title.set_text('PRH')
ax2.plot(range(len(pry_deg)), pry_deg, color=_colors[1])
ax3.title.set_text('depth')
ax3.plot(range(len(depths)), depths, color=_colors[2])
ax3.invert_yaxis()
if glide_mask is not None:
ind = range(len(glide_mask))
ax1 = plot_shade_mask(ax1, ind, glide_mask)
ax2 = plot_shade_mask(ax2, ind, glide_mask)
ax3 = plot_shade_mask(ax3, ind, glide_mask)
plt.show()
return None
|
[
"def",
"plot_acc_pry_depth",
"(",
"A_g_lf",
",",
"A_g_hf",
",",
"pry_deg",
",",
"depths",
",",
"glide_mask",
"=",
"None",
")",
":",
"import",
"numpy",
"fig",
",",
"(",
"ax1",
",",
"ax2",
",",
"ax3",
")",
"=",
"plt",
".",
"subplots",
"(",
"3",
",",
"1",
",",
"sharex",
"=",
"True",
")",
"ax1",
".",
"title",
".",
"set_text",
"(",
"'acceleromter'",
")",
"ax1",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"A_g_lf",
")",
")",
",",
"A_g_lf",
",",
"color",
"=",
"_colors",
"[",
"0",
"]",
")",
"ax1",
".",
"title",
".",
"set_text",
"(",
"'PRH'",
")",
"ax2",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"pry_deg",
")",
")",
",",
"pry_deg",
",",
"color",
"=",
"_colors",
"[",
"1",
"]",
")",
"ax3",
".",
"title",
".",
"set_text",
"(",
"'depth'",
")",
"ax3",
".",
"plot",
"(",
"range",
"(",
"len",
"(",
"depths",
")",
")",
",",
"depths",
",",
"color",
"=",
"_colors",
"[",
"2",
"]",
")",
"ax3",
".",
"invert_yaxis",
"(",
")",
"if",
"glide_mask",
"is",
"not",
"None",
":",
"ind",
"=",
"range",
"(",
"len",
"(",
"glide_mask",
")",
")",
"ax1",
"=",
"plot_shade_mask",
"(",
"ax1",
",",
"ind",
",",
"glide_mask",
")",
"ax2",
"=",
"plot_shade_mask",
"(",
"ax2",
",",
"ind",
",",
"glide_mask",
")",
"ax3",
"=",
"plot_shade_mask",
"(",
"ax3",
",",
"ind",
",",
"glide_mask",
")",
"plt",
".",
"show",
"(",
")",
"return",
"None"
] |
Plot the acceleration with the pitch, roll, and heading
Args
----
A_g_lf: ndarray
Low-pass filtered calibration accelerometer signal
A_g_hf: ndarray
High-pass filtered calibration accelerometer signal
pry_deg: ndarray
Pitch roll and heading in degrees
depths: ndarray
Depth data for all samples
glide_mask: ndarray
Boolean array for slicing glides from tag data
|
[
"Plot",
"the",
"acceleration",
"with",
"the",
"pitch",
"roll",
"and",
"heading"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdsp.py#L69-L108
|
246,081
|
ryanjdillon/pyotelem
|
pyotelem/plots/plotdsp.py
|
plot_welch_perdiogram
|
def plot_welch_perdiogram(x, fs, nperseg):
'''Plot Welch perdiogram
Args
----
x: ndarray
Signal array
fs: float
Sampling frequency
nperseg: float
Length of each data segment in PSD
'''
import scipy.signal
import numpy
# Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
# 0.001V**2/Hz of white noise sampled at 10 kHz.
N = len(x)
time = numpy.arange(N) / fs
# Compute and plot the power spectral density.
f, Pxx_den = scipy.signal.welch(x, fs, nperseg=nperseg)
plt.semilogy(f, Pxx_den)
plt.ylim([0.5e-3, 1])
plt.xlabel('frequency [Hz]')
plt.ylabel('PSD [V**2/Hz]')
plt.show()
# If we average the last half of the spectral density, to exclude the peak,
# we can recover the noise power on the signal.
numpy.mean(Pxx_den[256:]) # 0.0009924865443739191
# compute power spectrum
f, Pxx_spec = scipy.signal.welch(x, fs, 'flattop', 1024,
scaling='spectrum')
plt.figure()
plt.semilogy(f, numpy.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.show()
return None
|
python
|
def plot_welch_perdiogram(x, fs, nperseg):
'''Plot Welch perdiogram
Args
----
x: ndarray
Signal array
fs: float
Sampling frequency
nperseg: float
Length of each data segment in PSD
'''
import scipy.signal
import numpy
# Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
# 0.001V**2/Hz of white noise sampled at 10 kHz.
N = len(x)
time = numpy.arange(N) / fs
# Compute and plot the power spectral density.
f, Pxx_den = scipy.signal.welch(x, fs, nperseg=nperseg)
plt.semilogy(f, Pxx_den)
plt.ylim([0.5e-3, 1])
plt.xlabel('frequency [Hz]')
plt.ylabel('PSD [V**2/Hz]')
plt.show()
# If we average the last half of the spectral density, to exclude the peak,
# we can recover the noise power on the signal.
numpy.mean(Pxx_den[256:]) # 0.0009924865443739191
# compute power spectrum
f, Pxx_spec = scipy.signal.welch(x, fs, 'flattop', 1024,
scaling='spectrum')
plt.figure()
plt.semilogy(f, numpy.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.show()
return None
|
[
"def",
"plot_welch_perdiogram",
"(",
"x",
",",
"fs",
",",
"nperseg",
")",
":",
"import",
"scipy",
".",
"signal",
"import",
"numpy",
"# Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by",
"# 0.001V**2/Hz of white noise sampled at 10 kHz.",
"N",
"=",
"len",
"(",
"x",
")",
"time",
"=",
"numpy",
".",
"arange",
"(",
"N",
")",
"/",
"fs",
"# Compute and plot the power spectral density.",
"f",
",",
"Pxx_den",
"=",
"scipy",
".",
"signal",
".",
"welch",
"(",
"x",
",",
"fs",
",",
"nperseg",
"=",
"nperseg",
")",
"plt",
".",
"semilogy",
"(",
"f",
",",
"Pxx_den",
")",
"plt",
".",
"ylim",
"(",
"[",
"0.5e-3",
",",
"1",
"]",
")",
"plt",
".",
"xlabel",
"(",
"'frequency [Hz]'",
")",
"plt",
".",
"ylabel",
"(",
"'PSD [V**2/Hz]'",
")",
"plt",
".",
"show",
"(",
")",
"# If we average the last half of the spectral density, to exclude the peak,",
"# we can recover the noise power on the signal.",
"numpy",
".",
"mean",
"(",
"Pxx_den",
"[",
"256",
":",
"]",
")",
"# 0.0009924865443739191",
"# compute power spectrum",
"f",
",",
"Pxx_spec",
"=",
"scipy",
".",
"signal",
".",
"welch",
"(",
"x",
",",
"fs",
",",
"'flattop'",
",",
"1024",
",",
"scaling",
"=",
"'spectrum'",
")",
"plt",
".",
"figure",
"(",
")",
"plt",
".",
"semilogy",
"(",
"f",
",",
"numpy",
".",
"sqrt",
"(",
"Pxx_spec",
")",
")",
"plt",
".",
"xlabel",
"(",
"'frequency [Hz]'",
")",
"plt",
".",
"ylabel",
"(",
"'Linear spectrum [V RMS]'",
")",
"plt",
".",
"show",
"(",
")",
"return",
"None"
] |
Plot Welch perdiogram
Args
----
x: ndarray
Signal array
fs: float
Sampling frequency
nperseg: float
Length of each data segment in PSD
|
[
"Plot",
"Welch",
"perdiogram"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdsp.py#L160-L203
|
246,082
|
ryanjdillon/pyotelem
|
pyotelem/plots/plotdsp.py
|
plot_data_filter
|
def plot_data_filter(data, data_f, b, a, cutoff, fs):
'''Plot frequency response and filter overlay for butter filtered data
Args
----
data: ndarray
Signal array
data_f: float
Signal sampling rate
b: array_like
Numerator of a linear filter
a: array_like
Denominator of a linear filter
cutoff: float
Cutoff frequency for the filter
fs: float
Sampling rate of the signal
Notes
-----
http://stackoverflow.com/a/25192640/943773
'''
import matplotlib.pyplot as plt
import numpy
import scipy.signal
n = len(data)
T = n/fs
t = numpy.linspace(0, T, n, endpoint=False)
# Calculate frequency response
w, h = scipy.signal.freqz(b, a, worN=8000)
# Plot the frequency response.
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.title.set_text('Lowpass Filter Frequency Response')
ax1.plot(0.5*fs * w/numpy.pi, numpy.abs(h), 'b')
ax1.plot(cutoff, 0.5*numpy.sqrt(2), 'ko')
ax1.axvline(cutoff, color='k')
ax1.set_xlim(0, 0.5*fs)
ax1.set_xlabel('Frequency [Hz]')
ax2.legend()
# Demonstrate the use of the filter.
ax2.plot(t, data, linewidth=_linewidth, label='data')
ax2.plot(t, data_f, linewidth=_linewidth, label='filtered data')
ax2.set_xlabel('Time [sec]')
ax2.legend()
plt.show()
return None
|
python
|
def plot_data_filter(data, data_f, b, a, cutoff, fs):
'''Plot frequency response and filter overlay for butter filtered data
Args
----
data: ndarray
Signal array
data_f: float
Signal sampling rate
b: array_like
Numerator of a linear filter
a: array_like
Denominator of a linear filter
cutoff: float
Cutoff frequency for the filter
fs: float
Sampling rate of the signal
Notes
-----
http://stackoverflow.com/a/25192640/943773
'''
import matplotlib.pyplot as plt
import numpy
import scipy.signal
n = len(data)
T = n/fs
t = numpy.linspace(0, T, n, endpoint=False)
# Calculate frequency response
w, h = scipy.signal.freqz(b, a, worN=8000)
# Plot the frequency response.
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.title.set_text('Lowpass Filter Frequency Response')
ax1.plot(0.5*fs * w/numpy.pi, numpy.abs(h), 'b')
ax1.plot(cutoff, 0.5*numpy.sqrt(2), 'ko')
ax1.axvline(cutoff, color='k')
ax1.set_xlim(0, 0.5*fs)
ax1.set_xlabel('Frequency [Hz]')
ax2.legend()
# Demonstrate the use of the filter.
ax2.plot(t, data, linewidth=_linewidth, label='data')
ax2.plot(t, data_f, linewidth=_linewidth, label='filtered data')
ax2.set_xlabel('Time [sec]')
ax2.legend()
plt.show()
return None
|
[
"def",
"plot_data_filter",
"(",
"data",
",",
"data_f",
",",
"b",
",",
"a",
",",
"cutoff",
",",
"fs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"numpy",
"import",
"scipy",
".",
"signal",
"n",
"=",
"len",
"(",
"data",
")",
"T",
"=",
"n",
"/",
"fs",
"t",
"=",
"numpy",
".",
"linspace",
"(",
"0",
",",
"T",
",",
"n",
",",
"endpoint",
"=",
"False",
")",
"# Calculate frequency response",
"w",
",",
"h",
"=",
"scipy",
".",
"signal",
".",
"freqz",
"(",
"b",
",",
"a",
",",
"worN",
"=",
"8000",
")",
"# Plot the frequency response.",
"fig",
",",
"(",
"ax1",
",",
"ax2",
")",
"=",
"plt",
".",
"subplots",
"(",
"2",
",",
"1",
")",
"ax1",
".",
"title",
".",
"set_text",
"(",
"'Lowpass Filter Frequency Response'",
")",
"ax1",
".",
"plot",
"(",
"0.5",
"*",
"fs",
"*",
"w",
"/",
"numpy",
".",
"pi",
",",
"numpy",
".",
"abs",
"(",
"h",
")",
",",
"'b'",
")",
"ax1",
".",
"plot",
"(",
"cutoff",
",",
"0.5",
"*",
"numpy",
".",
"sqrt",
"(",
"2",
")",
",",
"'ko'",
")",
"ax1",
".",
"axvline",
"(",
"cutoff",
",",
"color",
"=",
"'k'",
")",
"ax1",
".",
"set_xlim",
"(",
"0",
",",
"0.5",
"*",
"fs",
")",
"ax1",
".",
"set_xlabel",
"(",
"'Frequency [Hz]'",
")",
"ax2",
".",
"legend",
"(",
")",
"# Demonstrate the use of the filter.",
"ax2",
".",
"plot",
"(",
"t",
",",
"data",
",",
"linewidth",
"=",
"_linewidth",
",",
"label",
"=",
"'data'",
")",
"ax2",
".",
"plot",
"(",
"t",
",",
"data_f",
",",
"linewidth",
"=",
"_linewidth",
",",
"label",
"=",
"'filtered data'",
")",
"ax2",
".",
"set_xlabel",
"(",
"'Time [sec]'",
")",
"ax2",
".",
"legend",
"(",
")",
"plt",
".",
"show",
"(",
")",
"return",
"None"
] |
Plot frequency response and filter overlay for butter filtered data
Args
----
data: ndarray
Signal array
data_f: float
Signal sampling rate
b: array_like
Numerator of a linear filter
a: array_like
Denominator of a linear filter
cutoff: float
Cutoff frequency for the filter
fs: float
Sampling rate of the signal
Notes
-----
http://stackoverflow.com/a/25192640/943773
|
[
"Plot",
"frequency",
"response",
"and",
"filter",
"overlay",
"for",
"butter",
"filtered",
"data"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdsp.py#L206-L258
|
246,083
|
Krokop/python-xmlstats
|
xmlstats/__init__.py
|
XMLStats._build_url
|
def _build_url(self, host, sport, method, id, format, parameters):
"""
build url from args
"""
path = "/".join(filter(None, (sport, method, id)))
url = "https://" + host + "/" + path + "." + format
if parameters:
paramstring = urllib.parse.urlencode(parameters)
url = url + "?" + paramstring
return url
|
python
|
def _build_url(self, host, sport, method, id, format, parameters):
"""
build url from args
"""
path = "/".join(filter(None, (sport, method, id)))
url = "https://" + host + "/" + path + "." + format
if parameters:
paramstring = urllib.parse.urlencode(parameters)
url = url + "?" + paramstring
return url
|
[
"def",
"_build_url",
"(",
"self",
",",
"host",
",",
"sport",
",",
"method",
",",
"id",
",",
"format",
",",
"parameters",
")",
":",
"path",
"=",
"\"/\"",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"(",
"sport",
",",
"method",
",",
"id",
")",
")",
")",
"url",
"=",
"\"https://\"",
"+",
"host",
"+",
"\"/\"",
"+",
"path",
"+",
"\".\"",
"+",
"format",
"if",
"parameters",
":",
"paramstring",
"=",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"parameters",
")",
"url",
"=",
"url",
"+",
"\"?\"",
"+",
"paramstring",
"return",
"url"
] |
build url from args
|
[
"build",
"url",
"from",
"args"
] |
d3ec60f09bdee71bbeaac8992ff792b5ebbdd704
|
https://github.com/Krokop/python-xmlstats/blob/d3ec60f09bdee71bbeaac8992ff792b5ebbdd704/xmlstats/__init__.py#L78-L87
|
246,084
|
Krokop/python-xmlstats
|
xmlstats/__init__.py
|
XMLStats.get_teams
|
def get_teams(self):
""" Return json current roster of team """
return self.make_request(host="erikberg.com", sport='nba',
method="teams", id=None,
format="json",
parameters={})
|
python
|
def get_teams(self):
""" Return json current roster of team """
return self.make_request(host="erikberg.com", sport='nba',
method="teams", id=None,
format="json",
parameters={})
|
[
"def",
"get_teams",
"(",
"self",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"host",
"=",
"\"erikberg.com\"",
",",
"sport",
"=",
"'nba'",
",",
"method",
"=",
"\"teams\"",
",",
"id",
"=",
"None",
",",
"format",
"=",
"\"json\"",
",",
"parameters",
"=",
"{",
"}",
")"
] |
Return json current roster of team
|
[
"Return",
"json",
"current",
"roster",
"of",
"team"
] |
d3ec60f09bdee71bbeaac8992ff792b5ebbdd704
|
https://github.com/Krokop/python-xmlstats/blob/d3ec60f09bdee71bbeaac8992ff792b5ebbdd704/xmlstats/__init__.py#L89-L94
|
246,085
|
ryanjdillon/pyotelem
|
pyotelem/dynamics.py
|
prh
|
def prh(ax, ay, az):
'''Calculate the pitch, roll and heading for triaxial movement signalsi
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
roll: ndarray
Pitch angle in radians
yaw: ndarray
Pitch angle in radians
'''
p = pitch(ax, ay, az)
r = roll(ax, ay, az)
y = yaw(ax, ay, az)
#from dtag_toolbox_python.dtag2 import a2pr
#pitch, roll, A_norm = a2pr.a2pr(A_g)
return p, r, y
|
python
|
def prh(ax, ay, az):
'''Calculate the pitch, roll and heading for triaxial movement signalsi
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
roll: ndarray
Pitch angle in radians
yaw: ndarray
Pitch angle in radians
'''
p = pitch(ax, ay, az)
r = roll(ax, ay, az)
y = yaw(ax, ay, az)
#from dtag_toolbox_python.dtag2 import a2pr
#pitch, roll, A_norm = a2pr.a2pr(A_g)
return p, r, y
|
[
"def",
"prh",
"(",
"ax",
",",
"ay",
",",
"az",
")",
":",
"p",
"=",
"pitch",
"(",
"ax",
",",
"ay",
",",
"az",
")",
"r",
"=",
"roll",
"(",
"ax",
",",
"ay",
",",
"az",
")",
"y",
"=",
"yaw",
"(",
"ax",
",",
"ay",
",",
"az",
")",
"#from dtag_toolbox_python.dtag2 import a2pr",
"#pitch, roll, A_norm = a2pr.a2pr(A_g)",
"return",
"p",
",",
"r",
",",
"y"
] |
Calculate the pitch, roll and heading for triaxial movement signalsi
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
roll: ndarray
Pitch angle in radians
yaw: ndarray
Pitch angle in radians
|
[
"Calculate",
"the",
"pitch",
"roll",
"and",
"heading",
"for",
"triaxial",
"movement",
"signalsi"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dynamics.py#L2-L31
|
246,086
|
ryanjdillon/pyotelem
|
pyotelem/dynamics.py
|
absdeg
|
def absdeg(deg):
'''Change from signed degrees to 0-180 or 0-360 ranges
deg: ndarray
Movement data in pitch, roll, yaw (degrees)
Returns
-------
deg_abs: ndarray
Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees
Example
-------
deg = numpy.array([-170, -120, 0, 90])
absdeg(deg) # returns array([190, 240, 0, 90])
'''
import numpy
d = numpy.copy(deg)
if numpy.max(numpy.abs(deg)) > 90.0:
d[deg < 0] = 360 + deg[deg < 0]
else:
d[deg < 0] = 180 + deg[deg < 0]
return d
|
python
|
def absdeg(deg):
'''Change from signed degrees to 0-180 or 0-360 ranges
deg: ndarray
Movement data in pitch, roll, yaw (degrees)
Returns
-------
deg_abs: ndarray
Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees
Example
-------
deg = numpy.array([-170, -120, 0, 90])
absdeg(deg) # returns array([190, 240, 0, 90])
'''
import numpy
d = numpy.copy(deg)
if numpy.max(numpy.abs(deg)) > 90.0:
d[deg < 0] = 360 + deg[deg < 0]
else:
d[deg < 0] = 180 + deg[deg < 0]
return d
|
[
"def",
"absdeg",
"(",
"deg",
")",
":",
"import",
"numpy",
"d",
"=",
"numpy",
".",
"copy",
"(",
"deg",
")",
"if",
"numpy",
".",
"max",
"(",
"numpy",
".",
"abs",
"(",
"deg",
")",
")",
">",
"90.0",
":",
"d",
"[",
"deg",
"<",
"0",
"]",
"=",
"360",
"+",
"deg",
"[",
"deg",
"<",
"0",
"]",
"else",
":",
"d",
"[",
"deg",
"<",
"0",
"]",
"=",
"180",
"+",
"deg",
"[",
"deg",
"<",
"0",
"]",
"return",
"d"
] |
Change from signed degrees to 0-180 or 0-360 ranges
deg: ndarray
Movement data in pitch, roll, yaw (degrees)
Returns
-------
deg_abs: ndarray
Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees
Example
-------
deg = numpy.array([-170, -120, 0, 90])
absdeg(deg) # returns array([190, 240, 0, 90])
|
[
"Change",
"from",
"signed",
"degrees",
"to",
"0",
"-",
"180",
"or",
"0",
"-",
"360",
"ranges"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dynamics.py#L100-L125
|
246,087
|
ryanjdillon/pyotelem
|
pyotelem/dynamics.py
|
acceleration_magnitude
|
def acceleration_magnitude(ax, ay, az):
'''Cacluate the magnitude of 3D acceleration
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
acc_mag: ndarray
Magnitude of acceleration from combined acceleration axes
http://physics.stackexchange.com/a/41655/126878
'''
import numpy
return numpy.sqrt(ax**2 + ay**2 + az**2)
|
python
|
def acceleration_magnitude(ax, ay, az):
'''Cacluate the magnitude of 3D acceleration
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
acc_mag: ndarray
Magnitude of acceleration from combined acceleration axes
http://physics.stackexchange.com/a/41655/126878
'''
import numpy
return numpy.sqrt(ax**2 + ay**2 + az**2)
|
[
"def",
"acceleration_magnitude",
"(",
"ax",
",",
"ay",
",",
"az",
")",
":",
"import",
"numpy",
"return",
"numpy",
".",
"sqrt",
"(",
"ax",
"**",
"2",
"+",
"ay",
"**",
"2",
"+",
"az",
"**",
"2",
")"
] |
Cacluate the magnitude of 3D acceleration
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
acc_mag: ndarray
Magnitude of acceleration from combined acceleration axes
http://physics.stackexchange.com/a/41655/126878
|
[
"Cacluate",
"the",
"magnitude",
"of",
"3D",
"acceleration"
] |
816563a9c3feb3fa416f1c2921c6b75db34111ad
|
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dynamics.py#L128-L148
|
246,088
|
Othernet-Project/conz
|
conz/console.py
|
Console.pstd
|
def pstd(self, *args, **kwargs):
""" Console to STDOUT """
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush()
|
python
|
def pstd(self, *args, **kwargs):
""" Console to STDOUT """
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush()
|
[
"def",
"pstd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"self",
".",
"out",
"self",
".",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] |
Console to STDOUT
|
[
"Console",
"to",
"STDOUT"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L67-L71
|
246,089
|
Othernet-Project/conz
|
conz/console.py
|
Console.perr
|
def perr(self, *args, **kwargs):
""" Console to STERR """
kwargs['file'] = self.err
self.print(*args, **kwargs)
sys.stderr.flush()
|
python
|
def perr(self, *args, **kwargs):
""" Console to STERR """
kwargs['file'] = self.err
self.print(*args, **kwargs)
sys.stderr.flush()
|
[
"def",
"perr",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"self",
".",
"err",
"self",
".",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] |
Console to STERR
|
[
"Console",
"to",
"STERR"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L73-L77
|
246,090
|
Othernet-Project/conz
|
conz/console.py
|
Console.pverb
|
def pverb(self, *args, **kwargs):
""" Console verbose message to STDOUT """
if not self.verbose:
return
self.pstd(*args, **kwargs)
|
python
|
def pverb(self, *args, **kwargs):
""" Console verbose message to STDOUT """
if not self.verbose:
return
self.pstd(*args, **kwargs)
|
[
"def",
"pverb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"verbose",
":",
"return",
"self",
".",
"pstd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Console verbose message to STDOUT
|
[
"Console",
"verbose",
"message",
"to",
"STDOUT"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L95-L99
|
246,091
|
Othernet-Project/conz
|
conz/console.py
|
Console.read
|
def read(self, prompt='', clean=lambda x: x):
""" Display a prompt and ask user for input
A function to clean the user input can be passed as ``clean`` argument.
This function takes a single value, which is the string user entered,
and returns a cleaned value. Default is a pass-through function, which
is an equivalent of::
def clean(val):
return val
"""
ans = read(prompt + ' ')
return clean(ans)
|
python
|
def read(self, prompt='', clean=lambda x: x):
""" Display a prompt and ask user for input
A function to clean the user input can be passed as ``clean`` argument.
This function takes a single value, which is the string user entered,
and returns a cleaned value. Default is a pass-through function, which
is an equivalent of::
def clean(val):
return val
"""
ans = read(prompt + ' ')
return clean(ans)
|
[
"def",
"read",
"(",
"self",
",",
"prompt",
"=",
"''",
",",
"clean",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"ans",
"=",
"read",
"(",
"prompt",
"+",
"' '",
")",
"return",
"clean",
"(",
"ans",
")"
] |
Display a prompt and ask user for input
A function to clean the user input can be passed as ``clean`` argument.
This function takes a single value, which is the string user entered,
and returns a cleaned value. Default is a pass-through function, which
is an equivalent of::
def clean(val):
return val
|
[
"Display",
"a",
"prompt",
"and",
"ask",
"user",
"for",
"input"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L104-L116
|
246,092
|
Othernet-Project/conz
|
conz/console.py
|
Console.rvpl
|
def rvpl(self, prompt, error='Entered value is invalid', intro=None,
validator=lambda x: x != '', clean=lambda x: x.strip(),
strict=True, default=None):
""" Start a read-validate-print loop
The RVPL will read the user input, validate it, and loop until the
entered value passes the validation, then return it.
Error message can be customized using the ``error`` argument. If the
value is a callable, it will be called with the value and it will be
expected to return a printable message. Exceptions raised by the
``error`` function are not trapped.
When ``intro`` is passed, it is printed above the prompt.
The ``validator`` argument is is a function that validates the user
input. Default validator simply validates if user entered any value.
The ``clean`` argument specifies a function for the ``read()`` method
with the same semantics.
"""
if intro:
self.pstd(utils.rewrap_long(intro))
val = self.read(prompt, clean)
while not validator(val):
if not strict:
return default
if hasattr(error, '__call__'):
self.perr(error(val))
else:
self.perr(error)
val = self.read(prompt, clean)
return val
|
python
|
def rvpl(self, prompt, error='Entered value is invalid', intro=None,
validator=lambda x: x != '', clean=lambda x: x.strip(),
strict=True, default=None):
""" Start a read-validate-print loop
The RVPL will read the user input, validate it, and loop until the
entered value passes the validation, then return it.
Error message can be customized using the ``error`` argument. If the
value is a callable, it will be called with the value and it will be
expected to return a printable message. Exceptions raised by the
``error`` function are not trapped.
When ``intro`` is passed, it is printed above the prompt.
The ``validator`` argument is is a function that validates the user
input. Default validator simply validates if user entered any value.
The ``clean`` argument specifies a function for the ``read()`` method
with the same semantics.
"""
if intro:
self.pstd(utils.rewrap_long(intro))
val = self.read(prompt, clean)
while not validator(val):
if not strict:
return default
if hasattr(error, '__call__'):
self.perr(error(val))
else:
self.perr(error)
val = self.read(prompt, clean)
return val
|
[
"def",
"rvpl",
"(",
"self",
",",
"prompt",
",",
"error",
"=",
"'Entered value is invalid'",
",",
"intro",
"=",
"None",
",",
"validator",
"=",
"lambda",
"x",
":",
"x",
"!=",
"''",
",",
"clean",
"=",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"strict",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"intro",
":",
"self",
".",
"pstd",
"(",
"utils",
".",
"rewrap_long",
"(",
"intro",
")",
")",
"val",
"=",
"self",
".",
"read",
"(",
"prompt",
",",
"clean",
")",
"while",
"not",
"validator",
"(",
"val",
")",
":",
"if",
"not",
"strict",
":",
"return",
"default",
"if",
"hasattr",
"(",
"error",
",",
"'__call__'",
")",
":",
"self",
".",
"perr",
"(",
"error",
"(",
"val",
")",
")",
"else",
":",
"self",
".",
"perr",
"(",
"error",
")",
"val",
"=",
"self",
".",
"read",
"(",
"prompt",
",",
"clean",
")",
"return",
"val"
] |
Start a read-validate-print loop
The RVPL will read the user input, validate it, and loop until the
entered value passes the validation, then return it.
Error message can be customized using the ``error`` argument. If the
value is a callable, it will be called with the value and it will be
expected to return a printable message. Exceptions raised by the
``error`` function are not trapped.
When ``intro`` is passed, it is printed above the prompt.
The ``validator`` argument is is a function that validates the user
input. Default validator simply validates if user entered any value.
The ``clean`` argument specifies a function for the ``read()`` method
with the same semantics.
|
[
"Start",
"a",
"read",
"-",
"validate",
"-",
"print",
"loop"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L118-L150
|
246,093
|
Othernet-Project/conz
|
conz/console.py
|
Console.yesno
|
def yesno(self, prompt, error='Please type either y or n', intro=None,
default=None):
""" Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argument can be ``True`` or ``False``, with meaning of
'yes' and 'no' respectively. Default is ``None`` which means no
default. When default value is specified, malformed or empty response
will cause the ``default`` value to be returned.
Optional ``intro`` text can be specified which will be shown above the
prompt.
"""
if default is None:
prompt += ' (y/n):'
else:
if default is True:
prompt += ' (Y/n):'
default = 'y'
if default is False:
prompt += ' (y/N):'
default = 'n'
validator = lambda x: x in ['y', 'yes', 'n', 'no']
val = self.rvpl(prompt, error=error, intro=intro, validator=validator,
clean=lambda x: x.strip().lower(),
strict=default is None, default=default)
return val in ['y', 'yes']
|
python
|
def yesno(self, prompt, error='Please type either y or n', intro=None,
default=None):
""" Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argument can be ``True`` or ``False``, with meaning of
'yes' and 'no' respectively. Default is ``None`` which means no
default. When default value is specified, malformed or empty response
will cause the ``default`` value to be returned.
Optional ``intro`` text can be specified which will be shown above the
prompt.
"""
if default is None:
prompt += ' (y/n):'
else:
if default is True:
prompt += ' (Y/n):'
default = 'y'
if default is False:
prompt += ' (y/N):'
default = 'n'
validator = lambda x: x in ['y', 'yes', 'n', 'no']
val = self.rvpl(prompt, error=error, intro=intro, validator=validator,
clean=lambda x: x.strip().lower(),
strict=default is None, default=default)
return val in ['y', 'yes']
|
[
"def",
"yesno",
"(",
"self",
",",
"prompt",
",",
"error",
"=",
"'Please type either y or n'",
",",
"intro",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"prompt",
"+=",
"' (y/n):'",
"else",
":",
"if",
"default",
"is",
"True",
":",
"prompt",
"+=",
"' (Y/n):'",
"default",
"=",
"'y'",
"if",
"default",
"is",
"False",
":",
"prompt",
"+=",
"' (y/N):'",
"default",
"=",
"'n'",
"validator",
"=",
"lambda",
"x",
":",
"x",
"in",
"[",
"'y'",
",",
"'yes'",
",",
"'n'",
",",
"'no'",
"]",
"val",
"=",
"self",
".",
"rvpl",
"(",
"prompt",
",",
"error",
"=",
"error",
",",
"intro",
"=",
"intro",
",",
"validator",
"=",
"validator",
",",
"clean",
"=",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
",",
"strict",
"=",
"default",
"is",
"None",
",",
"default",
"=",
"default",
")",
"return",
"val",
"in",
"[",
"'y'",
",",
"'yes'",
"]"
] |
Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argument can be ``True`` or ``False``, with meaning of
'yes' and 'no' respectively. Default is ``None`` which means no
default. When default value is specified, malformed or empty response
will cause the ``default`` value to be returned.
Optional ``intro`` text can be specified which will be shown above the
prompt.
|
[
"Ask",
"user",
"for",
"yes",
"or",
"no",
"answer"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L152-L181
|
246,094
|
Othernet-Project/conz
|
conz/console.py
|
Console.menu
|
def menu(self, choices, prompt='Please choose from the provided options:',
error='Invalid choice', intro=None, strict=True, default=None,
numerator=lambda x: [i + 1 for i in range(x)],
formatter=lambda x, y: '{0:>3}) {1}'.format(x, y),
clean=utils.safeint):
""" Print a menu
The choices must be an iterable of two-tuples where the first value is
the value of the menu item, and the second is the label for that
matches the value.
The menu will be printed with numeric choices. For example::
1) foo
2) bar
Formatting of the number is controlled by the formatter function which
can be overridden by passing the ``formatter`` argument.
The numbers used for the menu are generated using the numerator
function which can be specified using the ``numerator`` function. This
function must take the number of choices and return the same number of
items that will be used as choice characters as a list.
The cleaner function is passed to ``pvpl()`` method can be customized
using ``clean`` argument. This function should generally be customized
whenever ``numerator`` is customized, as default cleaner converts
input to integers to match the default numerator.
Optional ``intro`` argument can be passed to print a message above the
menu.
The return value of this method is the value user has chosen. The
prompt will keep asking the user for input until a valid choice is
selected. Each time an invalid selection is made, error message is
printed. This message can be customized using ``error`` argument.
If ``strict`` argument is set, then only values in choices are allowed,
otherwise any value will be allowed. The ``default`` argument can be
used to define what value is returned in case user select an invalid
value when strict checking is off.
"""
numbers = list(numerator(len(choices)))
labels = (label for _, label in choices)
values = [value for value, _ in choices]
# Print intro and menu itself
if intro:
self.pstd('\n' + utils.rewrap_long(intro))
for n, label in zip(numbers, labels):
self.pstd(formatter(n, label))
# Define the validator
validator = lambda x: x in numbers
val = self.rvpl(prompt, error=error, validator=validator, clean=clean,
strict=strict, default=default)
if not strict and val == default:
return val
return values[numbers.index(val)]
|
python
|
def menu(self, choices, prompt='Please choose from the provided options:',
error='Invalid choice', intro=None, strict=True, default=None,
numerator=lambda x: [i + 1 for i in range(x)],
formatter=lambda x, y: '{0:>3}) {1}'.format(x, y),
clean=utils.safeint):
""" Print a menu
The choices must be an iterable of two-tuples where the first value is
the value of the menu item, and the second is the label for that
matches the value.
The menu will be printed with numeric choices. For example::
1) foo
2) bar
Formatting of the number is controlled by the formatter function which
can be overridden by passing the ``formatter`` argument.
The numbers used for the menu are generated using the numerator
function which can be specified using the ``numerator`` function. This
function must take the number of choices and return the same number of
items that will be used as choice characters as a list.
The cleaner function is passed to ``pvpl()`` method can be customized
using ``clean`` argument. This function should generally be customized
whenever ``numerator`` is customized, as default cleaner converts
input to integers to match the default numerator.
Optional ``intro`` argument can be passed to print a message above the
menu.
The return value of this method is the value user has chosen. The
prompt will keep asking the user for input until a valid choice is
selected. Each time an invalid selection is made, error message is
printed. This message can be customized using ``error`` argument.
If ``strict`` argument is set, then only values in choices are allowed,
otherwise any value will be allowed. The ``default`` argument can be
used to define what value is returned in case user select an invalid
value when strict checking is off.
"""
numbers = list(numerator(len(choices)))
labels = (label for _, label in choices)
values = [value for value, _ in choices]
# Print intro and menu itself
if intro:
self.pstd('\n' + utils.rewrap_long(intro))
for n, label in zip(numbers, labels):
self.pstd(formatter(n, label))
# Define the validator
validator = lambda x: x in numbers
val = self.rvpl(prompt, error=error, validator=validator, clean=clean,
strict=strict, default=default)
if not strict and val == default:
return val
return values[numbers.index(val)]
|
[
"def",
"menu",
"(",
"self",
",",
"choices",
",",
"prompt",
"=",
"'Please choose from the provided options:'",
",",
"error",
"=",
"'Invalid choice'",
",",
"intro",
"=",
"None",
",",
"strict",
"=",
"True",
",",
"default",
"=",
"None",
",",
"numerator",
"=",
"lambda",
"x",
":",
"[",
"i",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"x",
")",
"]",
",",
"formatter",
"=",
"lambda",
"x",
",",
"y",
":",
"'{0:>3}) {1}'",
".",
"format",
"(",
"x",
",",
"y",
")",
",",
"clean",
"=",
"utils",
".",
"safeint",
")",
":",
"numbers",
"=",
"list",
"(",
"numerator",
"(",
"len",
"(",
"choices",
")",
")",
")",
"labels",
"=",
"(",
"label",
"for",
"_",
",",
"label",
"in",
"choices",
")",
"values",
"=",
"[",
"value",
"for",
"value",
",",
"_",
"in",
"choices",
"]",
"# Print intro and menu itself",
"if",
"intro",
":",
"self",
".",
"pstd",
"(",
"'\\n'",
"+",
"utils",
".",
"rewrap_long",
"(",
"intro",
")",
")",
"for",
"n",
",",
"label",
"in",
"zip",
"(",
"numbers",
",",
"labels",
")",
":",
"self",
".",
"pstd",
"(",
"formatter",
"(",
"n",
",",
"label",
")",
")",
"# Define the validator",
"validator",
"=",
"lambda",
"x",
":",
"x",
"in",
"numbers",
"val",
"=",
"self",
".",
"rvpl",
"(",
"prompt",
",",
"error",
"=",
"error",
",",
"validator",
"=",
"validator",
",",
"clean",
"=",
"clean",
",",
"strict",
"=",
"strict",
",",
"default",
"=",
"default",
")",
"if",
"not",
"strict",
"and",
"val",
"==",
"default",
":",
"return",
"val",
"return",
"values",
"[",
"numbers",
".",
"index",
"(",
"val",
")",
"]"
] |
Print a menu
The choices must be an iterable of two-tuples where the first value is
the value of the menu item, and the second is the label for that
matches the value.
The menu will be printed with numeric choices. For example::
1) foo
2) bar
Formatting of the number is controlled by the formatter function which
can be overridden by passing the ``formatter`` argument.
The numbers used for the menu are generated using the numerator
function which can be specified using the ``numerator`` function. This
function must take the number of choices and return the same number of
items that will be used as choice characters as a list.
The cleaner function is passed to ``pvpl()`` method can be customized
using ``clean`` argument. This function should generally be customized
whenever ``numerator`` is customized, as default cleaner converts
input to integers to match the default numerator.
Optional ``intro`` argument can be passed to print a message above the
menu.
The return value of this method is the value user has chosen. The
prompt will keep asking the user for input until a valid choice is
selected. Each time an invalid selection is made, error message is
printed. This message can be customized using ``error`` argument.
If ``strict`` argument is set, then only values in choices are allowed,
otherwise any value will be allowed. The ``default`` argument can be
used to define what value is returned in case user select an invalid
value when strict checking is off.
|
[
"Print",
"a",
"menu"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L183-L239
|
246,095
|
Othernet-Project/conz
|
conz/console.py
|
Console.readpipe
|
def readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one.
"""
read = []
while True:
l = sys.stdin.readline()
if not l:
if read:
yield read
return
return
if not chunk:
yield l
else:
read.append(l)
if len(read) == chunk:
yield read
|
python
|
def readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one.
"""
read = []
while True:
l = sys.stdin.readline()
if not l:
if read:
yield read
return
return
if not chunk:
yield l
else:
read.append(l)
if len(read) == chunk:
yield read
|
[
"def",
"readpipe",
"(",
"self",
",",
"chunk",
"=",
"None",
")",
":",
"read",
"=",
"[",
"]",
"while",
"True",
":",
"l",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"l",
":",
"if",
"read",
":",
"yield",
"read",
"return",
"return",
"if",
"not",
"chunk",
":",
"yield",
"l",
"else",
":",
"read",
".",
"append",
"(",
"l",
")",
"if",
"len",
"(",
"read",
")",
"==",
"chunk",
":",
"yield",
"read"
] |
Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one.
|
[
"Return",
"iterator",
"that",
"iterates",
"over",
"STDIN",
"line",
"by",
"line"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L241-L261
|
246,096
|
Othernet-Project/conz
|
conz/console.py
|
Console.error
|
def error(self, msg='Program error: {err}', exit=None):
""" Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string), then nothing is output to STDERR.
The ``exit`` argument can be set to a non-zero value, in which case the
program quits after printing the message using its value as return
value of the program.
The returned function can be used with the ``progress()`` context
manager as error handler.
"""
def handler(exc):
if msg:
self.perr(msg.format(err=exc))
if exit is not None:
self.quit(exit)
return handler
|
python
|
def error(self, msg='Program error: {err}', exit=None):
""" Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string), then nothing is output to STDERR.
The ``exit`` argument can be set to a non-zero value, in which case the
program quits after printing the message using its value as return
value of the program.
The returned function can be used with the ``progress()`` context
manager as error handler.
"""
def handler(exc):
if msg:
self.perr(msg.format(err=exc))
if exit is not None:
self.quit(exit)
return handler
|
[
"def",
"error",
"(",
"self",
",",
"msg",
"=",
"'Program error: {err}'",
",",
"exit",
"=",
"None",
")",
":",
"def",
"handler",
"(",
"exc",
")",
":",
"if",
"msg",
":",
"self",
".",
"perr",
"(",
"msg",
".",
"format",
"(",
"err",
"=",
"exc",
")",
")",
"if",
"exit",
"is",
"not",
"None",
":",
"self",
".",
"quit",
"(",
"exit",
")",
"return",
"handler"
] |
Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string), then nothing is output to STDERR.
The ``exit`` argument can be set to a non-zero value, in which case the
program quits after printing the message using its value as return
value of the program.
The returned function can be used with the ``progress()`` context
manager as error handler.
|
[
"Error",
"handler",
"factory"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L282-L304
|
246,097
|
Othernet-Project/conz
|
conz/console.py
|
Console.progress
|
def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',
prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a start
message. For example::
printer = Console(verbose=True)
with printer.progress('Checking files') as prog:
# Do some checks
if errors:
prog.abrt()
prog.end()
The context manager returns a ``Progress`` instance, which provides
methods like ``abrt()`` (abort), ``end()`` (end), and ``prog()`` (print
prog indicator).
The prog methods like ``abrt()`` and ``end()`` will raise an
exception that interrupts the prog. These exceptions are
``ProgressEnd`` exception subclasses and are ``ProgressAbrt`` and
``ProgressOK`` respectively. They are silenced and not handled in any
way as they only serve the purpose of flow control.
Other exceptions are trapped and ``abrt()`` is called. The exceptions
that should be trapped can be customized using the ``excs`` argument,
which should be a tuple of exception classes.
If a handler function is passed using ``onerror`` argument, then this
function takes the raised exception and handles it. By default, the
``error()`` factory is called with no arguments to generate the default
error handler. If string is passed, then ``error()`` factory is called
with that string.
Finally, when prog is aborted either naturally or when exception is
raised, it is possible to reraise the ``ProgressAbrt`` exception. This
is done using the ``reraise`` flag. Default is to reraise.
"""
if not onerror:
onerror = self.error()
if type(onerror) is str:
onerror = self.error(msg=onerror)
self.pverb(msg, end=sep)
prog = progress.Progress(self.pverb, end=end, abrt=abrt, prog=prog)
try:
yield prog
prog.end()
except self.ProgressOK:
pass
except self.ProgressAbrt as err:
if reraise:
raise err
except KeyboardInterrupt:
raise
except excs as err:
prog.abrt(noraise=True)
if onerror:
onerror(err)
if self.debug:
traceback.print_exc()
if reraise:
raise self.ProgressAbrt()
|
python
|
def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',
prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a start
message. For example::
printer = Console(verbose=True)
with printer.progress('Checking files') as prog:
# Do some checks
if errors:
prog.abrt()
prog.end()
The context manager returns a ``Progress`` instance, which provides
methods like ``abrt()`` (abort), ``end()`` (end), and ``prog()`` (print
prog indicator).
The prog methods like ``abrt()`` and ``end()`` will raise an
exception that interrupts the prog. These exceptions are
``ProgressEnd`` exception subclasses and are ``ProgressAbrt`` and
``ProgressOK`` respectively. They are silenced and not handled in any
way as they only serve the purpose of flow control.
Other exceptions are trapped and ``abrt()`` is called. The exceptions
that should be trapped can be customized using the ``excs`` argument,
which should be a tuple of exception classes.
If a handler function is passed using ``onerror`` argument, then this
function takes the raised exception and handles it. By default, the
``error()`` factory is called with no arguments to generate the default
error handler. If string is passed, then ``error()`` factory is called
with that string.
Finally, when prog is aborted either naturally or when exception is
raised, it is possible to reraise the ``ProgressAbrt`` exception. This
is done using the ``reraise`` flag. Default is to reraise.
"""
if not onerror:
onerror = self.error()
if type(onerror) is str:
onerror = self.error(msg=onerror)
self.pverb(msg, end=sep)
prog = progress.Progress(self.pverb, end=end, abrt=abrt, prog=prog)
try:
yield prog
prog.end()
except self.ProgressOK:
pass
except self.ProgressAbrt as err:
if reraise:
raise err
except KeyboardInterrupt:
raise
except excs as err:
prog.abrt(noraise=True)
if onerror:
onerror(err)
if self.debug:
traceback.print_exc()
if reraise:
raise self.ProgressAbrt()
|
[
"def",
"progress",
"(",
"self",
",",
"msg",
",",
"onerror",
"=",
"None",
",",
"sep",
"=",
"'...'",
",",
"end",
"=",
"'DONE'",
",",
"abrt",
"=",
"'FAIL'",
",",
"prog",
"=",
"'.'",
",",
"excs",
"=",
"(",
"Exception",
",",
")",
",",
"reraise",
"=",
"True",
")",
":",
"if",
"not",
"onerror",
":",
"onerror",
"=",
"self",
".",
"error",
"(",
")",
"if",
"type",
"(",
"onerror",
")",
"is",
"str",
":",
"onerror",
"=",
"self",
".",
"error",
"(",
"msg",
"=",
"onerror",
")",
"self",
".",
"pverb",
"(",
"msg",
",",
"end",
"=",
"sep",
")",
"prog",
"=",
"progress",
".",
"Progress",
"(",
"self",
".",
"pverb",
",",
"end",
"=",
"end",
",",
"abrt",
"=",
"abrt",
",",
"prog",
"=",
"prog",
")",
"try",
":",
"yield",
"prog",
"prog",
".",
"end",
"(",
")",
"except",
"self",
".",
"ProgressOK",
":",
"pass",
"except",
"self",
".",
"ProgressAbrt",
"as",
"err",
":",
"if",
"reraise",
":",
"raise",
"err",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
"excs",
"as",
"err",
":",
"prog",
".",
"abrt",
"(",
"noraise",
"=",
"True",
")",
"if",
"onerror",
":",
"onerror",
"(",
"err",
")",
"if",
"self",
".",
"debug",
":",
"traceback",
".",
"print_exc",
"(",
")",
"if",
"reraise",
":",
"raise",
"self",
".",
"ProgressAbrt",
"(",
")"
] |
Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a start
message. For example::
printer = Console(verbose=True)
with printer.progress('Checking files') as prog:
# Do some checks
if errors:
prog.abrt()
prog.end()
The context manager returns a ``Progress`` instance, which provides
methods like ``abrt()`` (abort), ``end()`` (end), and ``prog()`` (print
prog indicator).
The prog methods like ``abrt()`` and ``end()`` will raise an
exception that interrupts the prog. These exceptions are
``ProgressEnd`` exception subclasses and are ``ProgressAbrt`` and
``ProgressOK`` respectively. They are silenced and not handled in any
way as they only serve the purpose of flow control.
Other exceptions are trapped and ``abrt()`` is called. The exceptions
that should be trapped can be customized using the ``excs`` argument,
which should be a tuple of exception classes.
If a handler function is passed using ``onerror`` argument, then this
function takes the raised exception and handles it. By default, the
``error()`` factory is called with no arguments to generate the default
error handler. If string is passed, then ``error()`` factory is called
with that string.
Finally, when prog is aborted either naturally or when exception is
raised, it is possible to reraise the ``ProgressAbrt`` exception. This
is done using the ``reraise`` flag. Default is to reraise.
|
[
"Context",
"manager",
"for",
"handling",
"interactive",
"prog",
"indication"
] |
051214fa95a837c21595b03426a2c54c522d07a0
|
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L307-L369
|
246,098
|
daknuett/py_register_machine2
|
core/processor.py
|
RegisterInterface.write
|
def write(self, name_or_index, word):
"""
Write a word in the Register with the name ``name_or_index`` or with the index ``name_or_index``.
``name_or_index`` hat to be either ``str`` or ``int``. If the type of ``name_or_index``
is wrong an AttributeError will be raised.
If there is no Register with the specified name or index, a NameError will be raised.
"""
if(isinstance(name_or_index, str)):
if(name_or_index in self.registers_by_name):
self.registers_by_name[name_or_index].write(word)
else:
raise NameError("No Register with name '{}'".format(name_or_index))
elif( isinstance(name_or_index, int)):
if(name_or_index < len(self.registers_by_index)):
self.registers_by_index[name_or_index].write(word)
else:
raise NameError("No Register with index '{}'".format(name_or_index))
else:
raise AttributeError("name_or_index has to be `str` or `int`, but is {}".format(type(name_or_index)))
|
python
|
def write(self, name_or_index, word):
"""
Write a word in the Register with the name ``name_or_index`` or with the index ``name_or_index``.
``name_or_index`` hat to be either ``str`` or ``int``. If the type of ``name_or_index``
is wrong an AttributeError will be raised.
If there is no Register with the specified name or index, a NameError will be raised.
"""
if(isinstance(name_or_index, str)):
if(name_or_index in self.registers_by_name):
self.registers_by_name[name_or_index].write(word)
else:
raise NameError("No Register with name '{}'".format(name_or_index))
elif( isinstance(name_or_index, int)):
if(name_or_index < len(self.registers_by_index)):
self.registers_by_index[name_or_index].write(word)
else:
raise NameError("No Register with index '{}'".format(name_or_index))
else:
raise AttributeError("name_or_index has to be `str` or `int`, but is {}".format(type(name_or_index)))
|
[
"def",
"write",
"(",
"self",
",",
"name_or_index",
",",
"word",
")",
":",
"if",
"(",
"isinstance",
"(",
"name_or_index",
",",
"str",
")",
")",
":",
"if",
"(",
"name_or_index",
"in",
"self",
".",
"registers_by_name",
")",
":",
"self",
".",
"registers_by_name",
"[",
"name_or_index",
"]",
".",
"write",
"(",
"word",
")",
"else",
":",
"raise",
"NameError",
"(",
"\"No Register with name '{}'\"",
".",
"format",
"(",
"name_or_index",
")",
")",
"elif",
"(",
"isinstance",
"(",
"name_or_index",
",",
"int",
")",
")",
":",
"if",
"(",
"name_or_index",
"<",
"len",
"(",
"self",
".",
"registers_by_index",
")",
")",
":",
"self",
".",
"registers_by_index",
"[",
"name_or_index",
"]",
".",
"write",
"(",
"word",
")",
"else",
":",
"raise",
"NameError",
"(",
"\"No Register with index '{}'\"",
".",
"format",
"(",
"name_or_index",
")",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"\"name_or_index has to be `str` or `int`, but is {}\"",
".",
"format",
"(",
"type",
"(",
"name_or_index",
")",
")",
")"
] |
Write a word in the Register with the name ``name_or_index`` or with the index ``name_or_index``.
``name_or_index`` hat to be either ``str`` or ``int``. If the type of ``name_or_index``
is wrong an AttributeError will be raised.
If there is no Register with the specified name or index, a NameError will be raised.
|
[
"Write",
"a",
"word",
"in",
"the",
"Register",
"with",
"the",
"name",
"name_or_index",
"or",
"with",
"the",
"index",
"name_or_index",
".",
"name_or_index",
"hat",
"to",
"be",
"either",
"str",
"or",
"int",
".",
"If",
"the",
"type",
"of",
"name_or_index",
"is",
"wrong",
"an",
"AttributeError",
"will",
"be",
"raised",
"."
] |
599c53cd7576297d0d7a53344ed5d9aa98acc751
|
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/processor.py#L60-L79
|
246,099
|
daknuett/py_register_machine2
|
core/processor.py
|
Processor.add_interrupt
|
def add_interrupt(self, interrupt):
"""
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants.
"""
self.interrupts.append(interrupt)
self.constants[interrupt.name] = interrupt.address
|
python
|
def add_interrupt(self, interrupt):
"""
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants.
"""
self.interrupts.append(interrupt)
self.constants[interrupt.name] = interrupt.address
|
[
"def",
"add_interrupt",
"(",
"self",
",",
"interrupt",
")",
":",
"self",
".",
"interrupts",
".",
"append",
"(",
"interrupt",
")",
"self",
".",
"constants",
"[",
"interrupt",
".",
"name",
"]",
"=",
"interrupt",
".",
"address"
] |
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants.
|
[
"Adds",
"the",
"interrupt",
"to",
"the",
"internal",
"interrupt",
"storage",
"self",
".",
"interrupts",
"and",
"registers",
"the",
"interrupt",
"address",
"in",
"the",
"internal",
"constants",
"."
] |
599c53cd7576297d0d7a53344ed5d9aa98acc751
|
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/processor.py#L211-L217
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.