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
sequencelengths 20
707
| docstring
stringlengths 3
17.3k
| docstring_tokens
sequencelengths 3
222
| sha
stringlengths 40
40
| url
stringlengths 87
242
| docstring_summary
stringclasses 1
value | parameters
stringclasses 1
value | return_statement
stringclasses 1
value | argument_list
stringclasses 1
value | identifier
stringclasses 1
value | nwo
stringclasses 1
value | score
float32 -1
-1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
251,300 | pylast/pylast | src/pylast/__init__.py | Artist.get_listener_count | def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "listeners")
)
return self.listener_count | python | def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "listeners")
)
return self.listener_count | [
"def",
"get_listener_count",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"listener_count\"",
")",
":",
"return",
"self",
".",
"listener_count",
"else",
":",
"self",
".",
"listener_count",
"=",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
",",
"\"listeners\"",
")",
")",
"return",
"self",
".",
"listener_count"
] | Returns the number of listeners on the network. | [
"Returns",
"the",
"number",
"of",
"listeners",
"on",
"the",
"network",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1779-L1788 | -1 |
||||||
251,301 | pylast/pylast | src/pylast/__init__.py | Artist.is_streamable | def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(
_number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "streamable")
)
) | python | def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(
_number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "streamable")
)
) | [
"def",
"is_streamable",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
",",
"\"streamable\"",
")",
")",
")"
] | Returns True if the artist is streamable. | [
"Returns",
"True",
"if",
"the",
"artist",
"is",
"streamable",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1790-L1797 | -1 |
||||||
251,302 | pylast/pylast | src/pylast/__init__.py | Artist.get_similar | def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(
SimilarItem(Artist(names[i], self.network), _number(matches[i]))
)
return artists | python | def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(
SimilarItem(Artist(names[i], self.network), _number(matches[i]))
)
return artists | [
"def",
"get_similar",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getSimilar\"",
",",
"True",
",",
"params",
")",
"names",
"=",
"_extract_all",
"(",
"doc",
",",
"\"name\"",
")",
"matches",
"=",
"_extract_all",
"(",
"doc",
",",
"\"match\"",
")",
"artists",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"names",
")",
")",
":",
"artists",
".",
"append",
"(",
"SimilarItem",
"(",
"Artist",
"(",
"names",
"[",
"i",
"]",
",",
"self",
".",
"network",
")",
",",
"_number",
"(",
"matches",
"[",
"i",
"]",
")",
")",
")",
"return",
"artists"
] | Returns the similar artists on the network. | [
"Returns",
"the",
"similar",
"artists",
"on",
"the",
"network",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1827-L1845 | -1 |
||||||
251,303 | pylast/pylast | src/pylast/__init__.py | Artist.get_top_albums | def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopAlbums", "album", Album, params, cacheable) | python | def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopAlbums", "album", Album, params, cacheable) | [
"def",
"get_top_albums",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"return",
"self",
".",
"_get_things",
"(",
"\"getTopAlbums\"",
",",
"\"album\"",
",",
"Album",
",",
"params",
",",
"cacheable",
")"
] | Returns a list of the top albums. | [
"Returns",
"a",
"list",
"of",
"the",
"top",
"albums",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1847-L1853 | -1 |
||||||
251,304 | pylast/pylast | src/pylast/__init__.py | Artist.get_top_tracks | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopTracks", "track", Track, params, cacheable) | python | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopTracks", "track", Track, params, cacheable) | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"return",
"self",
".",
"_get_things",
"(",
"\"getTopTracks\"",
",",
"\"track\"",
",",
"Track",
",",
"params",
",",
"cacheable",
")"
] | Returns a list of the most played Tracks by this artist. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"played",
"Tracks",
"by",
"this",
"artist",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1855-L1861 | -1 |
||||||
251,305 | pylast/pylast | src/pylast/__init__.py | Country.get_top_artists | def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request("geo.getTopArtists", cacheable, params)
return _extract_top_artists(doc, self) | python | def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request("geo.getTopArtists", cacheable, params)
return _extract_top_artists(doc, self) | [
"def",
"get_top_artists",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"\"geo.getTopArtists\"",
",",
"cacheable",
",",
"params",
")",
"return",
"_extract_top_artists",
"(",
"doc",
",",
"self",
")"
] | Returns a sequence of the most played artists. | [
"Returns",
"a",
"sequence",
"of",
"the",
"most",
"played",
"artists",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1919-L1927 | -1 |
||||||
251,306 | pylast/pylast | src/pylast/__init__.py | Track.get_duration | def get_duration(self):
"""Returns the track duration."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "duration")) | python | def get_duration(self):
"""Returns the track duration."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "duration")) | [
"def",
"get_duration",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"duration\"",
")",
")"
] | Returns the track duration. | [
"Returns",
"the",
"track",
"duration",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2113-L2118 | -1 |
||||||
251,307 | pylast/pylast | src/pylast/__init__.py | Track.get_userloved | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userloved"))
return bool(loved) | python | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userloved"))
return bool(loved) | [
"def",
"get_userloved",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
":",
"return",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"username\"",
"]",
"=",
"self",
".",
"username",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
",",
"params",
")",
"loved",
"=",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"userloved\"",
")",
")",
"return",
"bool",
"(",
"loved",
")"
] | Whether the user loved this track | [
"Whether",
"the",
"user",
"loved",
"this",
"track"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2120-L2131 | -1 |
||||||
251,308 | pylast/pylast | src/pylast/__init__.py | Track.is_streamable | def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "streamable") == "1" | python | def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "streamable") == "1" | [
"def",
"is_streamable",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"streamable\"",
")",
"==",
"\"1\""
] | Returns True if the track is available at Last.fm. | [
"Returns",
"True",
"if",
"the",
"track",
"is",
"available",
"at",
"Last",
".",
"fm",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2133-L2137 | -1 |
||||||
251,309 | pylast/pylast | src/pylast/__init__.py | Track.is_fulltrack_available | def is_fulltrack_available(self):
"""Returns True if the full track is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return (
doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
) | python | def is_fulltrack_available(self):
"""Returns True if the full track is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return (
doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
) | [
"def",
"is_fulltrack_available",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"(",
"doc",
".",
"getElementsByTagName",
"(",
"\"streamable\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"fulltrack\"",
")",
"==",
"\"1\"",
")"
] | Returns True if the full track is available for streaming. | [
"Returns",
"True",
"if",
"the",
"full",
"track",
"is",
"available",
"for",
"streaming",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2139-L2145 | -1 |
||||||
251,310 | pylast/pylast | src/pylast/__init__.py | Track.get_album | def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(_extract(node, "artist"), _extract(node, "title"), self.network) | python | def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(_extract(node, "artist"), _extract(node, "title"), self.network) | [
"def",
"get_album",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"albums",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
"if",
"len",
"(",
"albums",
")",
"==",
"0",
":",
"return",
"node",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
"[",
"0",
"]",
"return",
"Album",
"(",
"_extract",
"(",
"node",
",",
"\"artist\"",
")",
",",
"_extract",
"(",
"node",
",",
"\"title\"",
")",
",",
"self",
".",
"network",
")"
] | Returns the album object of this track. | [
"Returns",
"the",
"album",
"object",
"of",
"this",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2147-L2158 | -1 |
||||||
251,311 | pylast/pylast | src/pylast/__init__.py | Track.get_similar | def get_similar(self, limit=None):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
seq = []
for node in doc.getElementsByTagName(self.ws_prefix):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq | python | def get_similar(self, limit=None):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
seq = []
for node in doc.getElementsByTagName(self.ws_prefix):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq | [
"def",
"get_similar",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getSimilar\"",
",",
"True",
",",
"params",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"doc",
".",
"getElementsByTagName",
"(",
"self",
".",
"ws_prefix",
")",
":",
"title",
"=",
"_extract",
"(",
"node",
",",
"\"name\"",
")",
"artist",
"=",
"_extract",
"(",
"node",
",",
"\"name\"",
",",
"1",
")",
"match",
"=",
"_number",
"(",
"_extract",
"(",
"node",
",",
"\"match\"",
")",
")",
"seq",
".",
"append",
"(",
"SimilarItem",
"(",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
")",
",",
"match",
")",
")",
"return",
"seq"
] | Returns similar tracks for this track on the network,
based on listening data. | [
"Returns",
"similar",
"tracks",
"for",
"this",
"track",
"on",
"the",
"network",
"based",
"on",
"listening",
"data",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2170-L2190 | -1 |
||||||
251,312 | pylast/pylast | src/pylast/__init__.py | User.get_artist_tracks | def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
warnings.warn(
"User.get_artist_tracks is deprecated and will be removed in a future "
"version. User.get_track_scrobbles is a partial replacement. "
"See https://github.com/pylast/pylast/issues/298",
DeprecationWarning,
stacklevel=2,
)
params = self._get_params()
params["artist"] = artist
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getArtistTracks", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
warnings.warn(
"User.get_artist_tracks is deprecated and will be removed in a future "
"version. User.get_track_scrobbles is a partial replacement. "
"See https://github.com/pylast/pylast/issues/298",
DeprecationWarning,
stacklevel=2,
)
params = self._get_params()
params["artist"] = artist
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getArtistTracks", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_artist_tracks",
"(",
"self",
",",
"artist",
",",
"cacheable",
"=",
"False",
")",
":",
"# Not implemented:",
"# \"Can be limited to specific timeranges, defaults to all time.\"",
"warnings",
".",
"warn",
"(",
"\"User.get_artist_tracks is deprecated and will be removed in a future \"",
"\"version. User.get_track_scrobbles is a partial replacement. \"",
"\"See https://github.com/pylast/pylast/issues/298\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"artist\"",
"]",
"=",
"artist",
"seq",
"=",
"[",
"]",
"for",
"track",
"in",
"_collect_nodes",
"(",
"None",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getArtistTracks\"",
",",
"cacheable",
",",
"params",
")",
":",
"title",
"=",
"_extract",
"(",
"track",
",",
"\"name\"",
")",
"artist",
"=",
"_extract",
"(",
"track",
",",
"\"artist\"",
")",
"date",
"=",
"_extract",
"(",
"track",
",",
"\"date\"",
")",
"album",
"=",
"_extract",
"(",
"track",
",",
"\"album\"",
")",
"timestamp",
"=",
"track",
".",
"getElementsByTagName",
"(",
"\"date\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"uts\"",
")",
"seq",
".",
"append",
"(",
"PlayedTrack",
"(",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
")",
",",
"album",
",",
"date",
",",
"timestamp",
")",
")",
"return",
"seq"
] | Get a list of tracks by a given artist scrobbled by this user,
including scrobble time. | [
"Get",
"a",
"list",
"of",
"tracks",
"by",
"a",
"given",
"artist",
"scrobbled",
"by",
"this",
"user",
"including",
"scrobble",
"time",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2261-L2294 | -1 |
||||||
251,313 | pylast/pylast | src/pylast/__init__.py | User.get_friends | def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getFriends", cacheable
):
seq.append(User(_extract(node, "name"), self.network))
return seq | python | def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getFriends", cacheable
):
seq.append(User(_extract(node, "name"), self.network))
return seq | [
"def",
"get_friends",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"cacheable",
"=",
"False",
")",
":",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"_collect_nodes",
"(",
"limit",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getFriends\"",
",",
"cacheable",
")",
":",
"seq",
".",
"append",
"(",
"User",
"(",
"_extract",
"(",
"node",
",",
"\"name\"",
")",
",",
"self",
".",
"network",
")",
")",
"return",
"seq"
] | Returns a list of the user's friends. | [
"Returns",
"a",
"list",
"of",
"the",
"user",
"s",
"friends",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2296-L2305 | -1 |
||||||
251,314 | pylast/pylast | src/pylast/__init__.py | User.get_loved_tracks | def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getLovedTracks", cacheable, params
):
try:
artist = _extract(track, "name", 1)
except IndexError: # pragma: no cover
continue
title = _extract(track, "name")
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp))
return seq | python | def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getLovedTracks", cacheable, params
):
try:
artist = _extract(track, "name", 1)
except IndexError: # pragma: no cover
continue
title = _extract(track, "name")
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp))
return seq | [
"def",
"get_loved_tracks",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"seq",
"=",
"[",
"]",
"for",
"track",
"in",
"_collect_nodes",
"(",
"limit",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getLovedTracks\"",
",",
"cacheable",
",",
"params",
")",
":",
"try",
":",
"artist",
"=",
"_extract",
"(",
"track",
",",
"\"name\"",
",",
"1",
")",
"except",
"IndexError",
":",
"# pragma: no cover",
"continue",
"title",
"=",
"_extract",
"(",
"track",
",",
"\"name\"",
")",
"date",
"=",
"_extract",
"(",
"track",
",",
"\"date\"",
")",
"timestamp",
"=",
"track",
".",
"getElementsByTagName",
"(",
"\"date\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"uts\"",
")",
"seq",
".",
"append",
"(",
"LovedTrack",
"(",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
")",
",",
"date",
",",
"timestamp",
")",
")",
"return",
"seq"
] | Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data. | [
"Returns",
"this",
"user",
"s",
"loved",
"track",
"as",
"a",
"sequence",
"of",
"LovedTrack",
"objects",
"in",
"reverse",
"order",
"of",
"their",
"timestamp",
"all",
"the",
"way",
"back",
"to",
"the",
"first",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2307-L2336 | -1 |
||||||
251,315 | pylast/pylast | src/pylast/__init__.py | User.get_now_playing | def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params["limit"] = "1"
doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)
tracks = doc.getElementsByTagName("track")
if len(tracks) == 0:
return None
e = tracks[0]
if not e.hasAttribute("nowplaying"):
return None
artist = _extract(e, "artist")
title = _extract(e, "name")
return Track(artist, title, self.network, self.name) | python | def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params["limit"] = "1"
doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)
tracks = doc.getElementsByTagName("track")
if len(tracks) == 0:
return None
e = tracks[0]
if not e.hasAttribute("nowplaying"):
return None
artist = _extract(e, "artist")
title = _extract(e, "name")
return Track(artist, title, self.network, self.name) | [
"def",
"get_now_playing",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"limit\"",
"]",
"=",
"\"1\"",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getRecentTracks\"",
",",
"False",
",",
"params",
")",
"tracks",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"track\"",
")",
"if",
"len",
"(",
"tracks",
")",
"==",
"0",
":",
"return",
"None",
"e",
"=",
"tracks",
"[",
"0",
"]",
"if",
"not",
"e",
".",
"hasAttribute",
"(",
"\"nowplaying\"",
")",
":",
"return",
"None",
"artist",
"=",
"_extract",
"(",
"e",
",",
"\"artist\"",
")",
"title",
"=",
"_extract",
"(",
"e",
",",
"\"name\"",
")",
"return",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
",",
"self",
".",
"name",
")"
] | Returns the currently playing track, or None if nothing is playing. | [
"Returns",
"the",
"currently",
"playing",
"track",
"or",
"None",
"if",
"nothing",
"is",
"playing",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2338-L2361 | -1 |
||||||
251,316 | pylast/pylast | src/pylast/__init__.py | User.get_recent_tracks | def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
if time_from:
params["from"] = time_from
if time_to:
params["to"] = time_to
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getRecentTracks", cacheable, params
):
if track.hasAttribute("nowplaying"):
continue # to prevent the now playing track from sneaking in
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
if time_from:
params["from"] = time_from
if time_to:
params["to"] = time_to
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getRecentTracks", cacheable, params
):
if track.hasAttribute("nowplaying"):
continue # to prevent the now playing track from sneaking in
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_recent_tracks",
"(",
"self",
",",
"limit",
"=",
"10",
",",
"cacheable",
"=",
"True",
",",
"time_from",
"=",
"None",
",",
"time_to",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"if",
"time_from",
":",
"params",
"[",
"\"from\"",
"]",
"=",
"time_from",
"if",
"time_to",
":",
"params",
"[",
"\"to\"",
"]",
"=",
"time_to",
"seq",
"=",
"[",
"]",
"for",
"track",
"in",
"_collect_nodes",
"(",
"limit",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getRecentTracks\"",
",",
"cacheable",
",",
"params",
")",
":",
"if",
"track",
".",
"hasAttribute",
"(",
"\"nowplaying\"",
")",
":",
"continue",
"# to prevent the now playing track from sneaking in",
"title",
"=",
"_extract",
"(",
"track",
",",
"\"name\"",
")",
"artist",
"=",
"_extract",
"(",
"track",
",",
"\"artist\"",
")",
"date",
"=",
"_extract",
"(",
"track",
",",
"\"date\"",
")",
"album",
"=",
"_extract",
"(",
"track",
",",
"\"album\"",
")",
"timestamp",
"=",
"track",
".",
"getElementsByTagName",
"(",
"\"date\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"uts\"",
")",
"seq",
".",
"append",
"(",
"PlayedTrack",
"(",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
")",
",",
"album",
",",
"date",
",",
"timestamp",
")",
")",
"return",
"seq"
] | Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data. | [
"Returns",
"this",
"user",
"s",
"played",
"track",
"as",
"a",
"sequence",
"of",
"PlayedTrack",
"objects",
"in",
"reverse",
"order",
"of",
"playtime",
"all",
"the",
"way",
"back",
"to",
"the",
"first",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2363-L2409 | -1 |
||||||
251,317 | pylast/pylast | src/pylast/__init__.py | User.get_country | def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
if country is None or country == "None":
return None
else:
return Country(country, self.network) | python | def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
if country is None or country == "None":
return None
else:
return Country(country, self.network) | [
"def",
"get_country",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"country",
"=",
"_extract",
"(",
"doc",
",",
"\"country\"",
")",
"if",
"country",
"is",
"None",
"or",
"country",
"==",
"\"None\"",
":",
"return",
"None",
"else",
":",
"return",
"Country",
"(",
"country",
",",
"self",
".",
"network",
")"
] | Returns the name of the country of the user. | [
"Returns",
"the",
"name",
"of",
"the",
"country",
"of",
"the",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2411-L2421 | -1 |
||||||
251,318 | pylast/pylast | src/pylast/__init__.py | User.is_subscriber | def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "subscriber") == "1" | python | def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "subscriber") == "1" | [
"def",
"is_subscriber",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"subscriber\"",
")",
"==",
"\"1\""
] | Returns whether the user is a subscriber or not. True or False. | [
"Returns",
"whether",
"the",
"user",
"is",
"a",
"subscriber",
"or",
"not",
".",
"True",
"or",
"False",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2423-L2428 | -1 |
||||||
251,319 | pylast/pylast | src/pylast/__init__.py | User.get_playcount | def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | python | def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | [
"def",
"get_playcount",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"playcount\"",
")",
")"
] | Returns the user's playcount so far. | [
"Returns",
"the",
"user",
"s",
"playcount",
"so",
"far",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2430-L2435 | -1 |
||||||
251,320 | pylast/pylast | src/pylast/__init__.py | User.get_registered | def get_registered(self):
"""Returns the user's registration date."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "registered") | python | def get_registered(self):
"""Returns the user's registration date."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "registered") | [
"def",
"get_registered",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"registered\"",
")"
] | Returns the user's registration date. | [
"Returns",
"the",
"user",
"s",
"registration",
"date",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2437-L2442 | -1 |
||||||
251,321 | pylast/pylast | src/pylast/__init__.py | User.get_unixtime_registered | def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return int(doc.getElementsByTagName("registered")[0].getAttribute("unixtime")) | python | def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return int(doc.getElementsByTagName("registered")[0].getAttribute("unixtime")) | [
"def",
"get_unixtime_registered",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"int",
"(",
"doc",
".",
"getElementsByTagName",
"(",
"\"registered\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"unixtime\"",
")",
")"
] | Returns the user's registration date as a UNIX timestamp. | [
"Returns",
"the",
"user",
"s",
"registration",
"date",
"as",
"a",
"UNIX",
"timestamp",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2444-L2449 | -1 |
||||||
251,322 | pylast/pylast | src/pylast/__init__.py | User.get_tagged_albums | def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "album"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_albums(doc, self.network) | python | def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "album"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_albums(doc, self.network) | [
"def",
"get_tagged_albums",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"]",
"=",
"\"album\"",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getpersonaltags\"",
",",
"cacheable",
",",
"params",
")",
"return",
"_extract_albums",
"(",
"doc",
",",
"self",
".",
"network",
")"
] | Returns the albums tagged by a user. | [
"Returns",
"the",
"albums",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2451-L2460 | -1 |
||||||
251,323 | pylast/pylast | src/pylast/__init__.py | User.get_tagged_artists | def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "artist"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", True, params)
return _extract_artists(doc, self.network) | python | def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "artist"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", True, params)
return _extract_artists(doc, self.network) | [
"def",
"get_tagged_artists",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"]",
"=",
"\"artist\"",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getpersonaltags\"",
",",
"True",
",",
"params",
")",
"return",
"_extract_artists",
"(",
"doc",
",",
"self",
".",
"network",
")"
] | Returns the artists tagged by a user. | [
"Returns",
"the",
"artists",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2462-L2471 | -1 |
||||||
251,324 | pylast/pylast | src/pylast/__init__.py | User.get_tagged_tracks | def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_tracks(doc, self.network) | python | def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_tracks(doc, self.network) | [
"def",
"get_tagged_tracks",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"]",
"=",
"\"track\"",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getpersonaltags\"",
",",
"cacheable",
",",
"params",
")",
"return",
"_extract_tracks",
"(",
"doc",
",",
"self",
".",
"network",
")"
] | Returns the tracks tagged by a user. | [
"Returns",
"the",
"tracks",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2473-L2482 | -1 |
||||||
251,325 | pylast/pylast | src/pylast/__init__.py | User.get_track_scrobbles | def get_track_scrobbles(self, artist, track, cacheable=False):
"""
Get a list of this user's scrobbles of this artist's track,
including scrobble time.
"""
params = self._get_params()
params["artist"] = artist
params["track"] = track
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getTrackScrobbles", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_track_scrobbles(self, artist, track, cacheable=False):
"""
Get a list of this user's scrobbles of this artist's track,
including scrobble time.
"""
params = self._get_params()
params["artist"] = artist
params["track"] = track
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getTrackScrobbles", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_track_scrobbles",
"(",
"self",
",",
"artist",
",",
"track",
",",
"cacheable",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"artist\"",
"]",
"=",
"artist",
"params",
"[",
"\"track\"",
"]",
"=",
"track",
"seq",
"=",
"[",
"]",
"for",
"track",
"in",
"_collect_nodes",
"(",
"None",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getTrackScrobbles\"",
",",
"cacheable",
",",
"params",
")",
":",
"title",
"=",
"_extract",
"(",
"track",
",",
"\"name\"",
")",
"artist",
"=",
"_extract",
"(",
"track",
",",
"\"artist\"",
")",
"date",
"=",
"_extract",
"(",
"track",
",",
"\"date\"",
")",
"album",
"=",
"_extract",
"(",
"track",
",",
"\"album\"",
")",
"timestamp",
"=",
"track",
".",
"getElementsByTagName",
"(",
"\"date\"",
")",
"[",
"0",
"]",
".",
"getAttribute",
"(",
"\"uts\"",
")",
"seq",
".",
"append",
"(",
"PlayedTrack",
"(",
"Track",
"(",
"artist",
",",
"title",
",",
"self",
".",
"network",
")",
",",
"album",
",",
"date",
",",
"timestamp",
")",
")",
"return",
"seq"
] | Get a list of this user's scrobbles of this artist's track,
including scrobble time. | [
"Get",
"a",
"list",
"of",
"this",
"user",
"s",
"scrobbles",
"of",
"this",
"artist",
"s",
"track",
"including",
"scrobble",
"time",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2566-L2590 | -1 |
||||||
251,326 | pylast/pylast | src/pylast/__init__.py | _Search.get_total_result_count | def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "totalResults") | python | def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "totalResults") | [
"def",
"get_total_result_count",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"_ws_prefix",
"+",
"\".search\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"totalResults\"",
")"
] | Returns the total count of all the results. | [
"Returns",
"the",
"total",
"count",
"of",
"all",
"the",
"results",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2664-L2669 | -1 |
||||||
251,327 | pylast/pylast | src/pylast/__init__.py | _Search._retrieve_page | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0] | python | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0] | [
"def",
"_retrieve_page",
"(",
"self",
",",
"page_index",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"page\"",
"]",
"=",
"str",
"(",
"page_index",
")",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"_ws_prefix",
"+",
"\".search\"",
",",
"True",
",",
"params",
")",
"return",
"doc",
".",
"getElementsByTagName",
"(",
"self",
".",
"_ws_prefix",
"+",
"\"matches\"",
")",
"[",
"0",
"]"
] | Returns the node of matches to be processed | [
"Returns",
"the",
"node",
"of",
"matches",
"to",
"be",
"processed"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2671-L2678 | -1 |
||||||
251,328 | pylast/pylast | src/pylast/__init__.py | AlbumSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
":",
"seq",
".",
"append",
"(",
"Album",
"(",
"_extract",
"(",
"node",
",",
"\"artist\"",
")",
",",
"_extract",
"(",
"node",
",",
"\"name\"",
")",
",",
"self",
".",
"network",
",",
"info",
"=",
"{",
"\"image\"",
":",
"_extract_all",
"(",
"node",
",",
"\"image\"",
")",
"}",
",",
")",
")",
"return",
"seq"
] | Returns the next page of results as a sequence of Album objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Album",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2692-L2708 | -1 |
||||||
251,329 | pylast/pylast | src/pylast/__init__.py | ArtistSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"artist\"",
")",
":",
"artist",
"=",
"Artist",
"(",
"_extract",
"(",
"node",
",",
"\"name\"",
")",
",",
"self",
".",
"network",
",",
"info",
"=",
"{",
"\"image\"",
":",
"_extract_all",
"(",
"node",
",",
"\"image\"",
")",
"}",
",",
")",
"artist",
".",
"listener_count",
"=",
"_number",
"(",
"_extract",
"(",
"node",
",",
"\"listeners\"",
")",
")",
"seq",
".",
"append",
"(",
"artist",
")",
"return",
"seq"
] | Returns the next page of results as a sequence of Artist objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Artist",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2717-L2732 | -1 |
||||||
251,330 | pylast/pylast | src/pylast/__init__.py | TrackSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"track\"",
")",
":",
"track",
"=",
"Track",
"(",
"_extract",
"(",
"node",
",",
"\"artist\"",
")",
",",
"_extract",
"(",
"node",
",",
"\"name\"",
")",
",",
"self",
".",
"network",
",",
"info",
"=",
"{",
"\"image\"",
":",
"_extract_all",
"(",
"node",
",",
"\"image\"",
")",
"}",
",",
")",
"track",
".",
"listener_count",
"=",
"_number",
"(",
"_extract",
"(",
"node",
",",
"\"listeners\"",
")",
")",
"seq",
".",
"append",
"(",
"track",
")",
"return",
"seq"
] | Returns the next page of results as a sequence of Track objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Track",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2747-L2763 | -1 |
||||||
251,331 | lovesegfault/beautysh | beautysh/beautysh.py | Beautify.write_file | def write_file(self, fp, data):
"""Write output to a file."""
with open(fp, 'w') as f:
f.write(data) | python | def write_file(self, fp, data):
"""Write output to a file."""
with open(fp, 'w') as f:
f.write(data) | [
"def",
"write_file",
"(",
"self",
",",
"fp",
",",
"data",
")",
":",
"with",
"open",
"(",
"fp",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"data",
")"
] | Write output to a file. | [
"Write",
"output",
"to",
"a",
"file",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L47-L50 | -1 |
||||||
251,332 | lovesegfault/beautysh | beautysh/beautysh.py | Beautify.detect_function_style | def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUNCTION_STYLE_REGEX:
if re.search(regex, test_record):
return index
index+=1
return None | python | def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUNCTION_STYLE_REGEX:
if re.search(regex, test_record):
return index
index+=1
return None | [
"def",
"detect_function_style",
"(",
"self",
",",
"test_record",
")",
":",
"index",
"=",
"0",
"# IMPORTANT: apply regex sequentially and stop on the first match:",
"for",
"regex",
"in",
"FUNCTION_STYLE_REGEX",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"test_record",
")",
":",
"return",
"index",
"index",
"+=",
"1",
"return",
"None"
] | Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected. | [
"Returns",
"the",
"index",
"for",
"the",
"function",
"declaration",
"style",
"detected",
"in",
"the",
"given",
"string",
"or",
"None",
"if",
"no",
"function",
"declarations",
"are",
"detected",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L52-L61 | -1 |
||||||
251,333 | lovesegfault/beautysh | beautysh/beautysh.py | Beautify.change_function_style | def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return stripped_record
if self.apply_function_style is None:
# user does not want to enforce any specific function style
return stripped_record
regex = FUNCTION_STYLE_REGEX[func_decl_style]
replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style]
changed_record = re.sub(regex, replacement, stripped_record)
return changed_record.strip() | python | def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return stripped_record
if self.apply_function_style is None:
# user does not want to enforce any specific function style
return stripped_record
regex = FUNCTION_STYLE_REGEX[func_decl_style]
replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style]
changed_record = re.sub(regex, replacement, stripped_record)
return changed_record.strip() | [
"def",
"change_function_style",
"(",
"self",
",",
"stripped_record",
",",
"func_decl_style",
")",
":",
"if",
"func_decl_style",
"is",
"None",
":",
"return",
"stripped_record",
"if",
"self",
".",
"apply_function_style",
"is",
"None",
":",
"# user does not want to enforce any specific function style",
"return",
"stripped_record",
"regex",
"=",
"FUNCTION_STYLE_REGEX",
"[",
"func_decl_style",
"]",
"replacement",
"=",
"FUNCTION_STYLE_REPLACEMENT",
"[",
"self",
".",
"apply_function_style",
"]",
"changed_record",
"=",
"re",
".",
"sub",
"(",
"regex",
",",
"replacement",
",",
"stripped_record",
")",
"return",
"changed_record",
".",
"strip",
"(",
")"
] | Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax. | [
"Converts",
"a",
"function",
"definition",
"syntax",
"from",
"the",
"func_decl_style",
"to",
"the",
"one",
"that",
"has",
"been",
"set",
"in",
"self",
".",
"apply_function_style",
"and",
"returns",
"the",
"string",
"with",
"the",
"converted",
"syntax",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L63-L74 | -1 |
||||||
251,334 | lovesegfault/beautysh | beautysh/beautysh.py | Beautify.beautify_file | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(path)
result, error = self.beautify_string(data, path)
if(data != result):
if(self.check_only):
if not error:
# we want to return 0 (success) only if the given file is already
# well formatted:
error = (result != data)
else:
if(self.backup):
self.write_file(path+'.bak', data)
self.write_file(path, result)
return error | python | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(path)
result, error = self.beautify_string(data, path)
if(data != result):
if(self.check_only):
if not error:
# we want to return 0 (success) only if the given file is already
# well formatted:
error = (result != data)
else:
if(self.backup):
self.write_file(path+'.bak', data)
self.write_file(path, result)
return error | [
"def",
"beautify_file",
"(",
"self",
",",
"path",
")",
":",
"error",
"=",
"False",
"if",
"(",
"path",
"==",
"'-'",
")",
":",
"data",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"result",
",",
"error",
"=",
"self",
".",
"beautify_string",
"(",
"data",
",",
"'(stdin)'",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"result",
")",
"else",
":",
"# named file",
"data",
"=",
"self",
".",
"read_file",
"(",
"path",
")",
"result",
",",
"error",
"=",
"self",
".",
"beautify_string",
"(",
"data",
",",
"path",
")",
"if",
"(",
"data",
"!=",
"result",
")",
":",
"if",
"(",
"self",
".",
"check_only",
")",
":",
"if",
"not",
"error",
":",
"# we want to return 0 (success) only if the given file is already",
"# well formatted:",
"error",
"=",
"(",
"result",
"!=",
"data",
")",
"else",
":",
"if",
"(",
"self",
".",
"backup",
")",
":",
"self",
".",
"write_file",
"(",
"path",
"+",
"'.bak'",
",",
"data",
")",
"self",
".",
"write_file",
"(",
"path",
",",
"result",
")",
"return",
"error"
] | Beautify bash script file. | [
"Beautify",
"bash",
"script",
"file",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L264-L284 | -1 |
||||||
251,335 | lovesegfault/beautysh | beautysh/beautysh.py | Beautify.main | def main(self):
"""Main beautifying function."""
error = False
parser = argparse.ArgumentParser(
description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False)
parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4,
help="Sets the number of spaces to be used in "
"indentation.")
parser.add_argument('--files', '-f', nargs='*',
help="Files to be beautified. This is mandatory. "
"If - is provided as filename, then beautysh reads "
"from stdin and writes on stdout.")
parser.add_argument('--backup', '-b', action='store_true',
help="Beautysh will create a backup file in the "
"same path as the original.")
parser.add_argument('--check', '-c', action='store_true',
help="Beautysh will just check the files without doing "
"any in-place beautify.")
parser.add_argument('--tab', '-t', action='store_true',
help="Sets indentation to tabs instead of spaces.")
parser.add_argument('--force-function-style', '-s', nargs=1,
help="Force a specific Bash function formatting. See below for more info.")
parser.add_argument('--version', '-v', action='store_true',
help="Prints the version and exits.")
parser.add_argument('--help', '-h', action='store_true',
help="Print this help message.")
args = parser.parse_args()
if (len(sys.argv) < 2) or args.help:
self.print_help(parser)
exit()
if args.version:
sys.stdout.write("%s\n" % self.get_version())
exit()
if(type(args.indent_size) is list):
args.indent_size = args.indent_size[0]
if not args.files:
sys.stdout.write("Please provide at least one input file\n")
exit()
self.tab_size = args.indent_size
self.backup = args.backup
self.check_only = args.check
if (args.tab):
self.tab_size = 1
self.tab_str = '\t'
if (type(args.force_function_style) is list):
provided_style = self.parse_function_style(args.force_function_style[0])
if provided_style is None:
sys.stdout.write("Invalid value for the function style. See --help for details.\n")
exit()
self.apply_function_style = provided_style
for path in args.files:
error |= self.beautify_file(path)
sys.exit((0, 1)[error]) | python | def main(self):
"""Main beautifying function."""
error = False
parser = argparse.ArgumentParser(
description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False)
parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4,
help="Sets the number of spaces to be used in "
"indentation.")
parser.add_argument('--files', '-f', nargs='*',
help="Files to be beautified. This is mandatory. "
"If - is provided as filename, then beautysh reads "
"from stdin and writes on stdout.")
parser.add_argument('--backup', '-b', action='store_true',
help="Beautysh will create a backup file in the "
"same path as the original.")
parser.add_argument('--check', '-c', action='store_true',
help="Beautysh will just check the files without doing "
"any in-place beautify.")
parser.add_argument('--tab', '-t', action='store_true',
help="Sets indentation to tabs instead of spaces.")
parser.add_argument('--force-function-style', '-s', nargs=1,
help="Force a specific Bash function formatting. See below for more info.")
parser.add_argument('--version', '-v', action='store_true',
help="Prints the version and exits.")
parser.add_argument('--help', '-h', action='store_true',
help="Print this help message.")
args = parser.parse_args()
if (len(sys.argv) < 2) or args.help:
self.print_help(parser)
exit()
if args.version:
sys.stdout.write("%s\n" % self.get_version())
exit()
if(type(args.indent_size) is list):
args.indent_size = args.indent_size[0]
if not args.files:
sys.stdout.write("Please provide at least one input file\n")
exit()
self.tab_size = args.indent_size
self.backup = args.backup
self.check_only = args.check
if (args.tab):
self.tab_size = 1
self.tab_str = '\t'
if (type(args.force_function_style) is list):
provided_style = self.parse_function_style(args.force_function_style[0])
if provided_style is None:
sys.stdout.write("Invalid value for the function style. See --help for details.\n")
exit()
self.apply_function_style = provided_style
for path in args.files:
error |= self.beautify_file(path)
sys.exit((0, 1)[error]) | [
"def",
"main",
"(",
"self",
")",
":",
"error",
"=",
"False",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"A Bash beautifier for the masses, version {}\"",
".",
"format",
"(",
"self",
".",
"get_version",
"(",
")",
")",
",",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--indent-size'",
",",
"'-i'",
",",
"nargs",
"=",
"1",
",",
"type",
"=",
"int",
",",
"default",
"=",
"4",
",",
"help",
"=",
"\"Sets the number of spaces to be used in \"",
"\"indentation.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--files'",
",",
"'-f'",
",",
"nargs",
"=",
"'*'",
",",
"help",
"=",
"\"Files to be beautified. This is mandatory. \"",
"\"If - is provided as filename, then beautysh reads \"",
"\"from stdin and writes on stdout.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--backup'",
",",
"'-b'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Beautysh will create a backup file in the \"",
"\"same path as the original.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--check'",
",",
"'-c'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Beautysh will just check the files without doing \"",
"\"any in-place beautify.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--tab'",
",",
"'-t'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Sets indentation to tabs instead of spaces.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--force-function-style'",
",",
"'-s'",
",",
"nargs",
"=",
"1",
",",
"help",
"=",
"\"Force a specific Bash function formatting. See below for more info.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"'-v'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Prints the version and exits.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--help'",
",",
"'-h'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Print this help message.\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"(",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"2",
")",
"or",
"args",
".",
"help",
":",
"self",
".",
"print_help",
"(",
"parser",
")",
"exit",
"(",
")",
"if",
"args",
".",
"version",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"self",
".",
"get_version",
"(",
")",
")",
"exit",
"(",
")",
"if",
"(",
"type",
"(",
"args",
".",
"indent_size",
")",
"is",
"list",
")",
":",
"args",
".",
"indent_size",
"=",
"args",
".",
"indent_size",
"[",
"0",
"]",
"if",
"not",
"args",
".",
"files",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Please provide at least one input file\\n\"",
")",
"exit",
"(",
")",
"self",
".",
"tab_size",
"=",
"args",
".",
"indent_size",
"self",
".",
"backup",
"=",
"args",
".",
"backup",
"self",
".",
"check_only",
"=",
"args",
".",
"check",
"if",
"(",
"args",
".",
"tab",
")",
":",
"self",
".",
"tab_size",
"=",
"1",
"self",
".",
"tab_str",
"=",
"'\\t'",
"if",
"(",
"type",
"(",
"args",
".",
"force_function_style",
")",
"is",
"list",
")",
":",
"provided_style",
"=",
"self",
".",
"parse_function_style",
"(",
"args",
".",
"force_function_style",
"[",
"0",
"]",
")",
"if",
"provided_style",
"is",
"None",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Invalid value for the function style. See --help for details.\\n\"",
")",
"exit",
"(",
")",
"self",
".",
"apply_function_style",
"=",
"provided_style",
"for",
"path",
"in",
"args",
".",
"files",
":",
"error",
"|=",
"self",
".",
"beautify_file",
"(",
"path",
")",
"sys",
".",
"exit",
"(",
"(",
"0",
",",
"1",
")",
"[",
"error",
"]",
")"
] | Main beautifying function. | [
"Main",
"beautifying",
"function",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L310-L362 | -1 |
||||||
251,336 | genomoncology/related | src/related/_init_fields.py | init_default | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs
"""
if not required and default == NOTHING:
default = optional_default
return default | python | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs
"""
if not required and default == NOTHING:
default = optional_default
return default | [
"def",
"init_default",
"(",
"required",
",",
"default",
",",
"optional_default",
")",
":",
"if",
"not",
"required",
"and",
"default",
"==",
"NOTHING",
":",
"default",
"=",
"optional_default",
"return",
"default"
] | Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs | [
"Returns",
"optional",
"default",
"if",
"field",
"is",
"not",
"required",
"and",
"default",
"was",
"not",
"provided",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/_init_fields.py#L5-L18 | -1 |
||||||
251,337 | genomoncology/related | src/related/converters.py | to_child_field | def to_child_field(cls):
"""
Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter.
"""
class ChildConverter(object):
def __init__(self, cls):
self._cls = cls
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, value):
try:
# Issue #33: if value is the class and callable, then invoke
if value == self._cls and callable(value):
value = value()
return to_model(self.cls, value)
except ValueError as e:
error_msg = CHILD_ERROR_MSG.format(value, self.cls, str(e))
raise ValueError(error_msg)
return ChildConverter(cls) | python | def to_child_field(cls):
"""
Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter.
"""
class ChildConverter(object):
def __init__(self, cls):
self._cls = cls
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, value):
try:
# Issue #33: if value is the class and callable, then invoke
if value == self._cls and callable(value):
value = value()
return to_model(self.cls, value)
except ValueError as e:
error_msg = CHILD_ERROR_MSG.format(value, self.cls, str(e))
raise ValueError(error_msg)
return ChildConverter(cls) | [
"def",
"to_child_field",
"(",
"cls",
")",
":",
"class",
"ChildConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"cls",
")",
":",
"self",
".",
"_cls",
"=",
"cls",
"@",
"property",
"def",
"cls",
"(",
"self",
")",
":",
"return",
"resolve_class",
"(",
"self",
".",
"_cls",
")",
"def",
"__call__",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"# Issue #33: if value is the class and callable, then invoke",
"if",
"value",
"==",
"self",
".",
"_cls",
"and",
"callable",
"(",
"value",
")",
":",
"value",
"=",
"value",
"(",
")",
"return",
"to_model",
"(",
"self",
".",
"cls",
",",
"value",
")",
"except",
"ValueError",
"as",
"e",
":",
"error_msg",
"=",
"CHILD_ERROR_MSG",
".",
"format",
"(",
"value",
",",
"self",
".",
"cls",
",",
"str",
"(",
"e",
")",
")",
"raise",
"ValueError",
"(",
"error_msg",
")",
"return",
"ChildConverter",
"(",
"cls",
")"
] | Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter. | [
"Returns",
"an",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"value",
"to",
"a",
"Child",
"object",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L17-L45 | -1 |
||||||
251,338 | genomoncology/related | src/related/converters.py | to_mapping_field | def to_mapping_field(cls, key): # pragma: no mccabe
"""
Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter.
"""
class MappingConverter(object):
def __init__(self, cls, key):
self._cls = cls
self.key = key
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, values):
kwargs = OrderedDict()
if isinstance(values, TypedMapping):
return values
if not isinstance(values, (type({}), type(None))):
raise TypeError("Invalid type : {}".format(type(values)))
if values:
for key_value, item in values.items():
if isinstance(item, dict):
item[self.key] = key_value
item = to_model(self.cls, item)
kwargs[key_value] = item
return TypedMapping(cls=self.cls, kwargs=kwargs, key=self.key)
return MappingConverter(cls, key) | python | def to_mapping_field(cls, key): # pragma: no mccabe
"""
Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter.
"""
class MappingConverter(object):
def __init__(self, cls, key):
self._cls = cls
self.key = key
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, values):
kwargs = OrderedDict()
if isinstance(values, TypedMapping):
return values
if not isinstance(values, (type({}), type(None))):
raise TypeError("Invalid type : {}".format(type(values)))
if values:
for key_value, item in values.items():
if isinstance(item, dict):
item[self.key] = key_value
item = to_model(self.cls, item)
kwargs[key_value] = item
return TypedMapping(cls=self.cls, kwargs=kwargs, key=self.key)
return MappingConverter(cls, key) | [
"def",
"to_mapping_field",
"(",
"cls",
",",
"key",
")",
":",
"# pragma: no mccabe",
"class",
"MappingConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"cls",
",",
"key",
")",
":",
"self",
".",
"_cls",
"=",
"cls",
"self",
".",
"key",
"=",
"key",
"@",
"property",
"def",
"cls",
"(",
"self",
")",
":",
"return",
"resolve_class",
"(",
"self",
".",
"_cls",
")",
"def",
"__call__",
"(",
"self",
",",
"values",
")",
":",
"kwargs",
"=",
"OrderedDict",
"(",
")",
"if",
"isinstance",
"(",
"values",
",",
"TypedMapping",
")",
":",
"return",
"values",
"if",
"not",
"isinstance",
"(",
"values",
",",
"(",
"type",
"(",
"{",
"}",
")",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid type : {}\"",
".",
"format",
"(",
"type",
"(",
"values",
")",
")",
")",
"if",
"values",
":",
"for",
"key_value",
",",
"item",
"in",
"values",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"item",
"[",
"self",
".",
"key",
"]",
"=",
"key_value",
"item",
"=",
"to_model",
"(",
"self",
".",
"cls",
",",
"item",
")",
"kwargs",
"[",
"key_value",
"]",
"=",
"item",
"return",
"TypedMapping",
"(",
"cls",
"=",
"self",
".",
"cls",
",",
"kwargs",
"=",
"kwargs",
",",
"key",
"=",
"self",
".",
"key",
")",
"return",
"MappingConverter",
"(",
"cls",
",",
"key",
")"
] | Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"value",
"to",
"a",
"Mapping",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L96-L132 | -1 |
||||||
251,339 | genomoncology/related | src/related/converters.py | to_date_field | def to_date_field(formatter):
"""
Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter.
"""
class DateConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).date()
if isinstance(value, datetime):
value = value.date()
return value
return DateConverter(formatter) | python | def to_date_field(formatter):
"""
Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter.
"""
class DateConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).date()
if isinstance(value, datetime):
value = value.date()
return value
return DateConverter(formatter) | [
"def",
"to_date_field",
"(",
"formatter",
")",
":",
"class",
"DateConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"datetime",
".",
"strptime",
"(",
"value",
",",
"self",
".",
"formatter",
")",
".",
"date",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"value",
"=",
"value",
".",
"date",
"(",
")",
"return",
"value",
"return",
"DateConverter",
"(",
"formatter",
")"
] | Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"Date",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L191-L212 | -1 |
||||||
251,340 | genomoncology/related | src/related/converters.py | to_datetime_field | def to_datetime_field(formatter):
"""
Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter.
"""
class DateTimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = parser.parse(value)
return value
return DateTimeConverter(formatter) | python | def to_datetime_field(formatter):
"""
Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter.
"""
class DateTimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = parser.parse(value)
return value
return DateTimeConverter(formatter) | [
"def",
"to_datetime_field",
"(",
"formatter",
")",
":",
"class",
"DateTimeConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"parser",
".",
"parse",
"(",
"value",
")",
"return",
"value",
"return",
"DateTimeConverter",
"(",
"formatter",
")"
] | Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"DateTime",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L215-L233 | -1 |
||||||
251,341 | genomoncology/related | src/related/converters.py | to_time_field | def to_time_field(formatter):
"""
Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter.
"""
class TimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).time()
return value
return TimeConverter(formatter) | python | def to_time_field(formatter):
"""
Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter.
"""
class TimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).time()
return value
return TimeConverter(formatter) | [
"def",
"to_time_field",
"(",
"formatter",
")",
":",
"class",
"TimeConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"datetime",
".",
"strptime",
"(",
"value",
",",
"self",
".",
"formatter",
")",
".",
"time",
"(",
")",
"return",
"value",
"return",
"TimeConverter",
"(",
"formatter",
")"
] | Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"Time",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L236-L254 | -1 |
||||||
251,342 | genomoncology/related | src/related/functions.py | to_dict | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary.
"""
# if is_related, then iterate attrs.
if is_model(obj.__class__):
return related_obj_to_dict(obj, **kwargs)
# else, return obj directly. register a custom to_dict if you need to!
# reference: https://pypi.python.org/pypi/singledispatch
else:
return obj | python | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary.
"""
# if is_related, then iterate attrs.
if is_model(obj.__class__):
return related_obj_to_dict(obj, **kwargs)
# else, return obj directly. register a custom to_dict if you need to!
# reference: https://pypi.python.org/pypi/singledispatch
else:
return obj | [
"def",
"to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"# if is_related, then iterate attrs.",
"if",
"is_model",
"(",
"obj",
".",
"__class__",
")",
":",
"return",
"related_obj_to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"# else, return obj directly. register a custom to_dict if you need to!",
"# reference: https://pypi.python.org/pypi/singledispatch",
"else",
":",
"return",
"obj"
] | Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary. | [
"Convert",
"an",
"object",
"into",
"dictionary",
".",
"Uses",
"singledispatch",
"to",
"allow",
"for",
"clean",
"extensions",
"for",
"custom",
"class",
"types",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L18-L38 | -1 |
||||||
251,343 | genomoncology/related | src/related/functions.py | related_obj_to_dict | def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("suppress_private_attr", False)
# if True, don't store fields with None values into dictionary.
suppress_empty_values = kwargs.get("suppress_empty_values", False)
# get list of attrs fields
attrs = fields(obj.__class__)
# instantiate return dict, use OrderedDict type by default
return_dict = kwargs.get("dict_factory", OrderedDict)()
for a in attrs:
# skip if private attr and flag tells you to skip
if suppress_private_attr and a.name.startswith("_"):
continue
metadata = a.metadata or {}
# formatter is a related-specific `attrs` meta field
# see fields.DateField
formatter = metadata.get('formatter')
# get value and call to_dict on it, passing the kwargs/formatter
value = getattr(obj, a.name)
value = to_dict(value, formatter=formatter, **kwargs)
# check flag, skip None values
if suppress_empty_values and value is None:
continue
# field name can be overridden by the metadata field
key_name = a.metadata.get('key') or a.name
# store converted / formatted value into return dictionary
return_dict[key_name] = value
return return_dict | python | def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("suppress_private_attr", False)
# if True, don't store fields with None values into dictionary.
suppress_empty_values = kwargs.get("suppress_empty_values", False)
# get list of attrs fields
attrs = fields(obj.__class__)
# instantiate return dict, use OrderedDict type by default
return_dict = kwargs.get("dict_factory", OrderedDict)()
for a in attrs:
# skip if private attr and flag tells you to skip
if suppress_private_attr and a.name.startswith("_"):
continue
metadata = a.metadata or {}
# formatter is a related-specific `attrs` meta field
# see fields.DateField
formatter = metadata.get('formatter')
# get value and call to_dict on it, passing the kwargs/formatter
value = getattr(obj, a.name)
value = to_dict(value, formatter=formatter, **kwargs)
# check flag, skip None values
if suppress_empty_values and value is None:
continue
# field name can be overridden by the metadata field
key_name = a.metadata.get('key') or a.name
# store converted / formatted value into return dictionary
return_dict[key_name] = value
return return_dict | [
"def",
"related_obj_to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"# Explicitly discard formatter kwarg, should not be cascaded down.",
"kwargs",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"# If True, remove fields that start with an underscore (e.g. _secret)",
"suppress_private_attr",
"=",
"kwargs",
".",
"get",
"(",
"\"suppress_private_attr\"",
",",
"False",
")",
"# if True, don't store fields with None values into dictionary.",
"suppress_empty_values",
"=",
"kwargs",
".",
"get",
"(",
"\"suppress_empty_values\"",
",",
"False",
")",
"# get list of attrs fields",
"attrs",
"=",
"fields",
"(",
"obj",
".",
"__class__",
")",
"# instantiate return dict, use OrderedDict type by default",
"return_dict",
"=",
"kwargs",
".",
"get",
"(",
"\"dict_factory\"",
",",
"OrderedDict",
")",
"(",
")",
"for",
"a",
"in",
"attrs",
":",
"# skip if private attr and flag tells you to skip",
"if",
"suppress_private_attr",
"and",
"a",
".",
"name",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"continue",
"metadata",
"=",
"a",
".",
"metadata",
"or",
"{",
"}",
"# formatter is a related-specific `attrs` meta field",
"# see fields.DateField",
"formatter",
"=",
"metadata",
".",
"get",
"(",
"'formatter'",
")",
"# get value and call to_dict on it, passing the kwargs/formatter",
"value",
"=",
"getattr",
"(",
"obj",
",",
"a",
".",
"name",
")",
"value",
"=",
"to_dict",
"(",
"value",
",",
"formatter",
"=",
"formatter",
",",
"*",
"*",
"kwargs",
")",
"# check flag, skip None values",
"if",
"suppress_empty_values",
"and",
"value",
"is",
"None",
":",
"continue",
"# field name can be overridden by the metadata field",
"key_name",
"=",
"a",
".",
"metadata",
".",
"get",
"(",
"'key'",
")",
"or",
"a",
".",
"name",
"# store converted / formatted value into return dictionary",
"return_dict",
"[",
"key_name",
"]",
"=",
"value",
"return",
"return_dict"
] | Covert a known related object to a dictionary. | [
"Covert",
"a",
"known",
"related",
"object",
"to",
"a",
"dictionary",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L41-L85 | -1 |
||||||
251,344 | genomoncology/related | src/related/functions.py | convert_key_to_attr_names | def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = original.get(key_name)
keys_pulled.add(key_name)
if getattr(cls, '__related_strict__', False):
extra = set(original.keys()) - keys_pulled
if len(extra):
raise ValueError("Extra keys (strict mode): {}".format(extra))
return updated | python | def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = original.get(key_name)
keys_pulled.add(key_name)
if getattr(cls, '__related_strict__', False):
extra = set(original.keys()) - keys_pulled
if len(extra):
raise ValueError("Extra keys (strict mode): {}".format(extra))
return updated | [
"def",
"convert_key_to_attr_names",
"(",
"cls",
",",
"original",
")",
":",
"attrs",
"=",
"fields",
"(",
"cls",
")",
"updated",
"=",
"{",
"}",
"keys_pulled",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"attrs",
":",
"key_name",
"=",
"a",
".",
"metadata",
".",
"get",
"(",
"'key'",
")",
"or",
"a",
".",
"name",
"if",
"key_name",
"in",
"original",
":",
"updated",
"[",
"a",
".",
"name",
"]",
"=",
"original",
".",
"get",
"(",
"key_name",
")",
"keys_pulled",
".",
"add",
"(",
"key_name",
")",
"if",
"getattr",
"(",
"cls",
",",
"'__related_strict__'",
",",
"False",
")",
":",
"extra",
"=",
"set",
"(",
"original",
".",
"keys",
"(",
")",
")",
"-",
"keys_pulled",
"if",
"len",
"(",
"extra",
")",
":",
"raise",
"ValueError",
"(",
"\"Extra keys (strict mode): {}\"",
".",
"format",
"(",
"extra",
")",
")",
"return",
"updated"
] | convert key names to their corresponding attribute names | [
"convert",
"key",
"names",
"to",
"their",
"corresponding",
"attribute",
"names"
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L112-L129 | -1 |
||||||
251,345 | genomoncology/related | src/related/functions.py | to_yaml | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None
"""
class OrderedDumper(dumper_cls):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
obj_dict = to_dict(obj, **kwargs)
return yaml.dump(obj_dict, stream, OrderedDumper,
default_flow_style=default_flow_style) | python | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None
"""
class OrderedDumper(dumper_cls):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
obj_dict = to_dict(obj, **kwargs)
return yaml.dump(obj_dict, stream, OrderedDumper,
default_flow_style=default_flow_style) | [
"def",
"to_yaml",
"(",
"obj",
",",
"stream",
"=",
"None",
",",
"dumper_cls",
"=",
"yaml",
".",
"Dumper",
",",
"default_flow_style",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"OrderedDumper",
"(",
"dumper_cls",
")",
":",
"pass",
"def",
"dict_representer",
"(",
"dumper",
",",
"data",
")",
":",
"return",
"dumper",
".",
"represent_mapping",
"(",
"yaml",
".",
"resolver",
".",
"BaseResolver",
".",
"DEFAULT_MAPPING_TAG",
",",
"data",
".",
"items",
"(",
")",
")",
"OrderedDumper",
".",
"add_representer",
"(",
"OrderedDict",
",",
"dict_representer",
")",
"obj_dict",
"=",
"to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"return",
"yaml",
".",
"dump",
"(",
"obj_dict",
",",
"stream",
",",
"OrderedDumper",
",",
"default_flow_style",
"=",
"default_flow_style",
")"
] | Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None | [
"Serialize",
"a",
"Python",
"object",
"into",
"a",
"YAML",
"stream",
"with",
"OrderedDict",
"and",
"default_flow_style",
"defaulted",
"to",
"False",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L144-L175 | -1 |
||||||
251,346 | genomoncology/related | src/related/functions.py | from_yaml | def from_yaml(stream, cls=None, loader_cls=yaml.Loader,
object_pairs_hook=OrderedDict, **extras):
"""
Convert a YAML stream into a class via the OrderedLoader class.
"""
class OrderedLoader(loader_cls):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
yaml_dict = yaml.load(stream, OrderedLoader) or {}
yaml_dict.update(extras)
return cls(**yaml_dict) if cls else yaml_dict | python | def from_yaml(stream, cls=None, loader_cls=yaml.Loader,
object_pairs_hook=OrderedDict, **extras):
"""
Convert a YAML stream into a class via the OrderedLoader class.
"""
class OrderedLoader(loader_cls):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
yaml_dict = yaml.load(stream, OrderedLoader) or {}
yaml_dict.update(extras)
return cls(**yaml_dict) if cls else yaml_dict | [
"def",
"from_yaml",
"(",
"stream",
",",
"cls",
"=",
"None",
",",
"loader_cls",
"=",
"yaml",
".",
"Loader",
",",
"object_pairs_hook",
"=",
"OrderedDict",
",",
"*",
"*",
"extras",
")",
":",
"class",
"OrderedLoader",
"(",
"loader_cls",
")",
":",
"pass",
"def",
"construct_mapping",
"(",
"loader",
",",
"node",
")",
":",
"loader",
".",
"flatten_mapping",
"(",
"node",
")",
"return",
"object_pairs_hook",
"(",
"loader",
".",
"construct_pairs",
"(",
"node",
")",
")",
"OrderedLoader",
".",
"add_constructor",
"(",
"yaml",
".",
"resolver",
".",
"BaseResolver",
".",
"DEFAULT_MAPPING_TAG",
",",
"construct_mapping",
")",
"yaml_dict",
"=",
"yaml",
".",
"load",
"(",
"stream",
",",
"OrderedLoader",
")",
"or",
"{",
"}",
"yaml_dict",
".",
"update",
"(",
"extras",
")",
"return",
"cls",
"(",
"*",
"*",
"yaml_dict",
")",
"if",
"cls",
"else",
"yaml_dict"
] | Convert a YAML stream into a class via the OrderedLoader class. | [
"Convert",
"a",
"YAML",
"stream",
"into",
"a",
"class",
"via",
"the",
"OrderedLoader",
"class",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L178-L197 | -1 |
||||||
251,347 | genomoncology/related | src/related/functions.py | from_json | def from_json(stream, cls=None, object_pairs_hook=OrderedDict, **extras):
"""
Convert a JSON string or stream into specified class.
"""
stream = stream.read() if hasattr(stream, 'read') else stream
json_dict = json.loads(stream, object_pairs_hook=object_pairs_hook)
if extras:
json_dict.update(extras) # pragma: no cover
return to_model(cls, json_dict) if cls else json_dict | python | def from_json(stream, cls=None, object_pairs_hook=OrderedDict, **extras):
"""
Convert a JSON string or stream into specified class.
"""
stream = stream.read() if hasattr(stream, 'read') else stream
json_dict = json.loads(stream, object_pairs_hook=object_pairs_hook)
if extras:
json_dict.update(extras) # pragma: no cover
return to_model(cls, json_dict) if cls else json_dict | [
"def",
"from_json",
"(",
"stream",
",",
"cls",
"=",
"None",
",",
"object_pairs_hook",
"=",
"OrderedDict",
",",
"*",
"*",
"extras",
")",
":",
"stream",
"=",
"stream",
".",
"read",
"(",
")",
"if",
"hasattr",
"(",
"stream",
",",
"'read'",
")",
"else",
"stream",
"json_dict",
"=",
"json",
".",
"loads",
"(",
"stream",
",",
"object_pairs_hook",
"=",
"object_pairs_hook",
")",
"if",
"extras",
":",
"json_dict",
".",
"update",
"(",
"extras",
")",
"# pragma: no cover",
"return",
"to_model",
"(",
"cls",
",",
"json_dict",
")",
"if",
"cls",
"else",
"json_dict"
] | Convert a JSON string or stream into specified class. | [
"Convert",
"a",
"JSON",
"string",
"or",
"stream",
"into",
"specified",
"class",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L212-L220 | -1 |
||||||
251,348 | genomoncology/related | src/related/fields.py | BooleanField | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, bool)
return attrib(default=default, validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, bool)
return attrib(default=default, validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"BooleanField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"bool",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"bool",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L13-L27 | -1 |
||||||
251,349 | genomoncology/related | src/related/fields.py | ChildField | def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
converter = converters.to_child_field(cls)
validator = _init_fields.init_validator(
required, object if isinstance(cls, str) else cls
)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp, metadata=dict(key=key)) | python | def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
converter = converters.to_child_field(cls)
validator = _init_fields.init_validator(
required, object if isinstance(cls, str) else cls
)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp, metadata=dict(key=key)) | [
"def",
"ChildField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"converter",
"=",
"converters",
".",
"to_child_field",
"(",
"cls",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"object",
"if",
"isinstance",
"(",
"cls",
",",
"str",
")",
"else",
"cls",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"child",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L30-L48 | -1 |
||||||
251,350 | genomoncology/related | src/related/fields.py | DateField | def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, date)
converter = converters.to_date_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, date)
converter = converters.to_date_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"DateField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_DATE_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"date",
")",
"converter",
"=",
"converters",
".",
"to_date_field",
"(",
"formatter",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"formatter",
"=",
"formatter",
",",
"key",
"=",
"key",
")",
")"
] | Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"date",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L51-L68 | -1 |
||||||
251,351 | genomoncology/related | src/related/fields.py | DateTimeField | def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, datetime)
converter = converters.to_datetime_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, datetime)
converter = converters.to_datetime_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"DateTimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_DATETIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"datetime",
")",
"converter",
"=",
"converters",
".",
"to_datetime_field",
"(",
"formatter",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"formatter",
"=",
"formatter",
",",
"key",
"=",
"key",
")",
")"
] | Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"datetime",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L71-L88 | -1 |
||||||
251,352 | genomoncology/related | src/related/fields.py | TimeField | def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, time)
converter = converters.to_time_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, time)
converter = converters.to_time_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"TimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_TIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"time",
")",
"converter",
"=",
"converters",
".",
"to_time_field",
"(",
"formatter",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"formatter",
"=",
"formatter",
",",
"key",
"=",
"key",
")",
")"
] | Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"time",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L91-L108 | -1 |
||||||
251,353 | genomoncology/related | src/related/fields.py | FloatField | def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, float)
return attrib(default=default, converter=converters.float_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, float)
return attrib(default=default, converter=converters.float_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"FloatField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"float",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converters",
".",
"float_if_not_none",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"float",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L111-L126 | -1 |
||||||
251,354 | genomoncology/related | src/related/fields.py | IntegerField | def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, int)
return attrib(default=default, converter=converters.int_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, int)
return attrib(default=default, converter=converters.int_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"IntegerField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"int",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converters",
".",
"int_if_not_none",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"int",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L129-L144 | -1 |
||||||
251,355 | genomoncology/related | src/related/fields.py | MappingField | def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, OrderedDict())
converter = converters.to_mapping_field(cls, child_key)
validator = _init_fields.init_validator(required, types.TypedMapping)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, OrderedDict())
converter = converters.to_mapping_field(cls, child_key)
validator = _init_fields.init_validator(required, types.TypedMapping)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"MappingField",
"(",
"cls",
",",
"child_key",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"OrderedDict",
"(",
")",
")",
"converter",
"=",
"converters",
".",
"to_mapping_field",
"(",
"cls",
",",
"child_key",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"types",
".",
"TypedMapping",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"mapping",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L147-L164 | -1 |
||||||
251,356 | genomoncology/related | src/related/fields.py | RegexField | def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, string_types,
validators.regex(regex))
return attrib(default=default, converter=converters.str_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, string_types,
validators.regex(regex))
return attrib(default=default, converter=converters.str_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"RegexField",
"(",
"regex",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"string_types",
",",
"validators",
".",
"regex",
"(",
"regex",
")",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converters",
".",
"str_if_not_none",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"str",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L167-L184 | -1 |
||||||
251,357 | genomoncology/related | src/related/fields.py | SequenceField | def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, [])
converter = converters.to_sequence_field(cls)
validator = _init_fields.init_validator(required, types.TypedSequence)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, [])
converter = converters.to_sequence_field(cls)
validator = _init_fields.init_validator(required, types.TypedSequence)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"SequenceField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"[",
"]",
")",
"converter",
"=",
"converters",
".",
"to_sequence_field",
"(",
"cls",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"types",
".",
"TypedSequence",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"sequence",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L187-L202 | -1 |
||||||
251,358 | genomoncology/related | src/related/fields.py | SetField | def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, set())
converter = converters.to_set_field(cls)
validator = _init_fields.init_validator(required, types.TypedSet)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, set())
converter = converters.to_set_field(cls)
validator = _init_fields.init_validator(required, types.TypedSet)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"SetField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"set",
"(",
")",
")",
"converter",
"=",
"converters",
".",
"to_set_field",
"(",
"cls",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"types",
".",
"TypedSet",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"converter",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"set",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L205-L220 | -1 |
||||||
251,359 | genomoncology/related | src/related/fields.py | DecimalField | def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, Decimal)
return attrib(default=default, converter=lambda x: Decimal(x),
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, Decimal)
return attrib(default=default, converter=lambda x: Decimal(x),
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"DecimalField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"None",
")",
"validator",
"=",
"_init_fields",
".",
"init_validator",
"(",
"required",
",",
"Decimal",
")",
"return",
"attrib",
"(",
"default",
"=",
"default",
",",
"converter",
"=",
"lambda",
"x",
":",
"Decimal",
"(",
"x",
")",
",",
"validator",
"=",
"validator",
",",
"repr",
"=",
"repr",
",",
"cmp",
"=",
"cmp",
",",
"metadata",
"=",
"dict",
"(",
"key",
"=",
"key",
")",
")"
] | Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"decimal",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L277-L292 | -1 |
||||||
251,360 | uwdata/draco | draco/run.py | run_clingo | def run_clingo(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
) -> Tuple[str, str]:
"""
Run draco and return stderr and stdout
"""
# default args
files = files or DRACO_LP
if relax_hard and "hard-integrity.lp" in files:
files.remove("hard-integrity.lp")
constants = constants or {}
options = ["--outf=2", "--quiet=1,2,2"]
if silence_warnings:
options.append("--warn=no-atom-undefined")
for name, value in constants.items():
options.append(f"-c {name}={value}")
cmd = ["clingo"] + options
logger.debug("Command: %s", " ".join(cmd))
proc = subprocess.Popen(
args=cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
program = "\n".join(draco_query)
file_names = [os.path.join(DRACO_LP_DIR, f) for f in files]
asp_program = b"\n".join(map(load_file, file_names)) + program.encode("utf8")
if debug:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as fd:
fd.write(program)
logger.info('Debug ASP with "clingo %s %s"', " ".join(file_names), fd.name)
stdout, stderr = proc.communicate(asp_program)
return (stderr, stdout) | python | def run_clingo(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
) -> Tuple[str, str]:
"""
Run draco and return stderr and stdout
"""
# default args
files = files or DRACO_LP
if relax_hard and "hard-integrity.lp" in files:
files.remove("hard-integrity.lp")
constants = constants or {}
options = ["--outf=2", "--quiet=1,2,2"]
if silence_warnings:
options.append("--warn=no-atom-undefined")
for name, value in constants.items():
options.append(f"-c {name}={value}")
cmd = ["clingo"] + options
logger.debug("Command: %s", " ".join(cmd))
proc = subprocess.Popen(
args=cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
program = "\n".join(draco_query)
file_names = [os.path.join(DRACO_LP_DIR, f) for f in files]
asp_program = b"\n".join(map(load_file, file_names)) + program.encode("utf8")
if debug:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as fd:
fd.write(program)
logger.info('Debug ASP with "clingo %s %s"', " ".join(file_names), fd.name)
stdout, stderr = proc.communicate(asp_program)
return (stderr, stdout) | [
"def",
"run_clingo",
"(",
"draco_query",
":",
"List",
"[",
"str",
"]",
",",
"constants",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"relax_hard",
"=",
"False",
",",
"silence_warnings",
"=",
"False",
",",
"debug",
"=",
"False",
",",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"# default args",
"files",
"=",
"files",
"or",
"DRACO_LP",
"if",
"relax_hard",
"and",
"\"hard-integrity.lp\"",
"in",
"files",
":",
"files",
".",
"remove",
"(",
"\"hard-integrity.lp\"",
")",
"constants",
"=",
"constants",
"or",
"{",
"}",
"options",
"=",
"[",
"\"--outf=2\"",
",",
"\"--quiet=1,2,2\"",
"]",
"if",
"silence_warnings",
":",
"options",
".",
"append",
"(",
"\"--warn=no-atom-undefined\"",
")",
"for",
"name",
",",
"value",
"in",
"constants",
".",
"items",
"(",
")",
":",
"options",
".",
"append",
"(",
"f\"-c {name}={value}\"",
")",
"cmd",
"=",
"[",
"\"clingo\"",
"]",
"+",
"options",
"logger",
".",
"debug",
"(",
"\"Command: %s\"",
",",
"\" \"",
".",
"join",
"(",
"cmd",
")",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
"=",
"cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"program",
"=",
"\"\\n\"",
".",
"join",
"(",
"draco_query",
")",
"file_names",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"DRACO_LP_DIR",
",",
"f",
")",
"for",
"f",
"in",
"files",
"]",
"asp_program",
"=",
"b\"\\n\"",
".",
"join",
"(",
"map",
"(",
"load_file",
",",
"file_names",
")",
")",
"+",
"program",
".",
"encode",
"(",
"\"utf8\"",
")",
"if",
"debug",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w\"",
",",
"delete",
"=",
"False",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"program",
")",
"logger",
".",
"info",
"(",
"'Debug ASP with \"clingo %s %s\"'",
",",
"\" \"",
".",
"join",
"(",
"file_names",
")",
",",
"fd",
".",
"name",
")",
"stdout",
",",
"stderr",
"=",
"proc",
".",
"communicate",
"(",
"asp_program",
")",
"return",
"(",
"stderr",
",",
"stdout",
")"
] | Run draco and return stderr and stdout | [
"Run",
"draco",
"and",
"return",
"stderr",
"and",
"stdout"
] | b130b5ebdb369e18e046706c73dc9c29b8159f7f | https://github.com/uwdata/draco/blob/b130b5ebdb369e18e046706c73dc9c29b8159f7f/draco/run.py#L74-L118 | -1 |
||||||
251,361 | uwdata/draco | draco/run.py | run | def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache. useful during development in notebooks.
if clear_cache and file_cache:
logger.warning("Cleared file cache")
file_cache.clear()
stderr, stdout = run_clingo(
draco_query, constants, files, relax_hard, silence_warnings, debug
)
try:
json_result = json.loads(stdout)
except json.JSONDecodeError:
logger.error("stdout: %s", stdout)
logger.error("stderr: %s", stderr)
raise
if stderr:
logger.error(stderr)
result = json_result["Result"]
if result == "UNSATISFIABLE":
logger.info("Constraints are unsatisfiable.")
return None
elif result == "OPTIMUM FOUND":
# get the last witness, which is the best result
answers = json_result["Call"][0]["Witnesses"][-1]
logger.debug(answers["Value"])
return Result(
clyngor.Answers(answers["Value"]).sorted,
cost=json_result["Models"]["Costs"][0],
)
elif result == "SATISFIABLE":
answers = json_result["Call"][0]["Witnesses"][-1]
assert (
json_result["Models"]["Number"] == 1
), "Should not have more than one model if we don't optimize"
logger.debug(answers["Value"])
return Result(clyngor.Answers(answers["Value"]).sorted)
else:
logger.error("Unsupported result: %s", result)
return None | python | def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache. useful during development in notebooks.
if clear_cache and file_cache:
logger.warning("Cleared file cache")
file_cache.clear()
stderr, stdout = run_clingo(
draco_query, constants, files, relax_hard, silence_warnings, debug
)
try:
json_result = json.loads(stdout)
except json.JSONDecodeError:
logger.error("stdout: %s", stdout)
logger.error("stderr: %s", stderr)
raise
if stderr:
logger.error(stderr)
result = json_result["Result"]
if result == "UNSATISFIABLE":
logger.info("Constraints are unsatisfiable.")
return None
elif result == "OPTIMUM FOUND":
# get the last witness, which is the best result
answers = json_result["Call"][0]["Witnesses"][-1]
logger.debug(answers["Value"])
return Result(
clyngor.Answers(answers["Value"]).sorted,
cost=json_result["Models"]["Costs"][0],
)
elif result == "SATISFIABLE":
answers = json_result["Call"][0]["Witnesses"][-1]
assert (
json_result["Models"]["Number"] == 1
), "Should not have more than one model if we don't optimize"
logger.debug(answers["Value"])
return Result(clyngor.Answers(answers["Value"]).sorted)
else:
logger.error("Unsupported result: %s", result)
return None | [
"def",
"run",
"(",
"draco_query",
":",
"List",
"[",
"str",
"]",
",",
"constants",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"relax_hard",
"=",
"False",
",",
"silence_warnings",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"clear_cache",
"=",
"False",
",",
")",
"->",
"Optional",
"[",
"Result",
"]",
":",
"# Clear file cache. useful during development in notebooks.",
"if",
"clear_cache",
"and",
"file_cache",
":",
"logger",
".",
"warning",
"(",
"\"Cleared file cache\"",
")",
"file_cache",
".",
"clear",
"(",
")",
"stderr",
",",
"stdout",
"=",
"run_clingo",
"(",
"draco_query",
",",
"constants",
",",
"files",
",",
"relax_hard",
",",
"silence_warnings",
",",
"debug",
")",
"try",
":",
"json_result",
"=",
"json",
".",
"loads",
"(",
"stdout",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"logger",
".",
"error",
"(",
"\"stdout: %s\"",
",",
"stdout",
")",
"logger",
".",
"error",
"(",
"\"stderr: %s\"",
",",
"stderr",
")",
"raise",
"if",
"stderr",
":",
"logger",
".",
"error",
"(",
"stderr",
")",
"result",
"=",
"json_result",
"[",
"\"Result\"",
"]",
"if",
"result",
"==",
"\"UNSATISFIABLE\"",
":",
"logger",
".",
"info",
"(",
"\"Constraints are unsatisfiable.\"",
")",
"return",
"None",
"elif",
"result",
"==",
"\"OPTIMUM FOUND\"",
":",
"# get the last witness, which is the best result",
"answers",
"=",
"json_result",
"[",
"\"Call\"",
"]",
"[",
"0",
"]",
"[",
"\"Witnesses\"",
"]",
"[",
"-",
"1",
"]",
"logger",
".",
"debug",
"(",
"answers",
"[",
"\"Value\"",
"]",
")",
"return",
"Result",
"(",
"clyngor",
".",
"Answers",
"(",
"answers",
"[",
"\"Value\"",
"]",
")",
".",
"sorted",
",",
"cost",
"=",
"json_result",
"[",
"\"Models\"",
"]",
"[",
"\"Costs\"",
"]",
"[",
"0",
"]",
",",
")",
"elif",
"result",
"==",
"\"SATISFIABLE\"",
":",
"answers",
"=",
"json_result",
"[",
"\"Call\"",
"]",
"[",
"0",
"]",
"[",
"\"Witnesses\"",
"]",
"[",
"-",
"1",
"]",
"assert",
"(",
"json_result",
"[",
"\"Models\"",
"]",
"[",
"\"Number\"",
"]",
"==",
"1",
")",
",",
"\"Should not have more than one model if we don't optimize\"",
"logger",
".",
"debug",
"(",
"answers",
"[",
"\"Value\"",
"]",
")",
"return",
"Result",
"(",
"clyngor",
".",
"Answers",
"(",
"answers",
"[",
"\"Value\"",
"]",
")",
".",
"sorted",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Unsupported result: %s\"",
",",
"result",
")",
"return",
"None"
] | Run clingo to compute a completion of a partial spec or violations. | [
"Run",
"clingo",
"to",
"compute",
"a",
"completion",
"of",
"a",
"partial",
"spec",
"or",
"violations",
"."
] | b130b5ebdb369e18e046706c73dc9c29b8159f7f | https://github.com/uwdata/draco/blob/b130b5ebdb369e18e046706c73dc9c29b8159f7f/draco/run.py#L121-L178 | -1 |
||||||
251,362 | thiderman/doge | doge/wow.py | DogeDeque.get | def get(self):
"""
Get one item. This will rotate the deque one step. Repeated gets will
return different items.
"""
self.index += 1
# If we've gone through the entire deque once, shuffle it again to
# simulate ever-flowing random. self.shuffle() will run __init__(),
# which will reset the index to 0.
if self.index == len(self):
self.shuffle()
self.rotate(1)
try:
return self[0]
except:
return "wow" | python | def get(self):
"""
Get one item. This will rotate the deque one step. Repeated gets will
return different items.
"""
self.index += 1
# If we've gone through the entire deque once, shuffle it again to
# simulate ever-flowing random. self.shuffle() will run __init__(),
# which will reset the index to 0.
if self.index == len(self):
self.shuffle()
self.rotate(1)
try:
return self[0]
except:
return "wow" | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"index",
"+=",
"1",
"# If we've gone through the entire deque once, shuffle it again to",
"# simulate ever-flowing random. self.shuffle() will run __init__(),",
"# which will reset the index to 0.",
"if",
"self",
".",
"index",
"==",
"len",
"(",
"self",
")",
":",
"self",
".",
"shuffle",
"(",
")",
"self",
".",
"rotate",
"(",
"1",
")",
"try",
":",
"return",
"self",
"[",
"0",
"]",
"except",
":",
"return",
"\"wow\""
] | Get one item. This will rotate the deque one step. Repeated gets will
return different items. | [
"Get",
"one",
"item",
".",
"This",
"will",
"rotate",
"the",
"deque",
"one",
"step",
".",
"Repeated",
"gets",
"will",
"return",
"different",
"items",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L29-L48 | -1 |
||||||
251,363 | thiderman/doge | doge/wow.py | DogeDeque.shuffle | def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
args = list(self)
random.shuffle(args)
self.clear()
super(DogeDeque, self).__init__(args) | python | def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
args = list(self)
random.shuffle(args)
self.clear()
super(DogeDeque, self).__init__(args) | [
"def",
"shuffle",
"(",
"self",
")",
":",
"args",
"=",
"list",
"(",
"self",
")",
"random",
".",
"shuffle",
"(",
"args",
")",
"self",
".",
"clear",
"(",
")",
"super",
"(",
"DogeDeque",
",",
"self",
")",
".",
"__init__",
"(",
"args",
")"
] | Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque. | [
"Shuffle",
"the",
"deque"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L55-L68 | -1 |
||||||
251,364 | thiderman/doge | doge/wow.py | FrequencyBasedDogeDeque.get | def get(self):
"""
Get one item and prepare to get an item with lower
rank on the next call.
"""
if len(self) < 1:
return "wow"
if self.index >= len(self):
self.index = 0
step = random.randint(1, min(self.step, len(self)))
res = self[0]
self.index += step
self.rotate(step)
return res | python | def get(self):
"""
Get one item and prepare to get an item with lower
rank on the next call.
"""
if len(self) < 1:
return "wow"
if self.index >= len(self):
self.index = 0
step = random.randint(1, min(self.step, len(self)))
res = self[0]
self.index += step
self.rotate(step)
return res | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"1",
":",
"return",
"\"wow\"",
"if",
"self",
".",
"index",
">=",
"len",
"(",
"self",
")",
":",
"self",
".",
"index",
"=",
"0",
"step",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"min",
"(",
"self",
".",
"step",
",",
"len",
"(",
"self",
")",
")",
")",
"res",
"=",
"self",
"[",
"0",
"]",
"self",
".",
"index",
"+=",
"step",
"self",
".",
"rotate",
"(",
"step",
")",
"return",
"res"
] | Get one item and prepare to get an item with lower
rank on the next call. | [
"Get",
"one",
"item",
"and",
"prepare",
"to",
"get",
"an",
"item",
"with",
"lower",
"rank",
"on",
"the",
"next",
"call",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L86-L103 | -1 |
||||||
251,365 | thiderman/doge | doge/core.py | onscreen_len | def onscreen_len(s):
"""
Calculate the length of a unicode string on screen,
accounting for double-width characters
"""
if sys.version_info < (3, 0) and isinstance(s, str):
return len(s)
length = 0
for ch in s:
length += 2 if unicodedata.east_asian_width(ch) == 'W' else 1
return length | python | def onscreen_len(s):
"""
Calculate the length of a unicode string on screen,
accounting for double-width characters
"""
if sys.version_info < (3, 0) and isinstance(s, str):
return len(s)
length = 0
for ch in s:
length += 2 if unicodedata.east_asian_width(ch) == 'W' else 1
return length | [
"def",
"onscreen_len",
"(",
"s",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"and",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"len",
"(",
"s",
")",
"length",
"=",
"0",
"for",
"ch",
"in",
"s",
":",
"length",
"+=",
"2",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"ch",
")",
"==",
"'W'",
"else",
"1",
"return",
"length"
] | Calculate the length of a unicode string on screen,
accounting for double-width characters | [
"Calculate",
"the",
"length",
"of",
"a",
"unicode",
"string",
"on",
"screen",
"accounting",
"for",
"double",
"-",
"width",
"characters"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L400-L414 | -1 |
||||||
251,366 | thiderman/doge | doge/core.py | Doge.setup_seasonal | def setup_seasonal(self):
"""
Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence.
"""
# If we've specified a season, just run that one
if self.ns.season:
return self.load_season(self.ns.season)
# If we've specified another doge or no doge at all, it does not make
# sense to use seasons.
if self.ns.doge_path is not None and not self.ns.no_shibe:
return
now = datetime.datetime.now()
for season, data in wow.SEASONS.items():
start, end = data['dates']
start_dt = datetime.datetime(now.year, start[0], start[1])
# Be sane if the holiday season spans over New Year's day.
end_dt = datetime.datetime(
now.year + (start[0] > end[0] and 1 or 0), end[0], end[1])
if start_dt <= now <= end_dt:
# Wow, much holiday!
return self.load_season(season) | python | def setup_seasonal(self):
"""
Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence.
"""
# If we've specified a season, just run that one
if self.ns.season:
return self.load_season(self.ns.season)
# If we've specified another doge or no doge at all, it does not make
# sense to use seasons.
if self.ns.doge_path is not None and not self.ns.no_shibe:
return
now = datetime.datetime.now()
for season, data in wow.SEASONS.items():
start, end = data['dates']
start_dt = datetime.datetime(now.year, start[0], start[1])
# Be sane if the holiday season spans over New Year's day.
end_dt = datetime.datetime(
now.year + (start[0] > end[0] and 1 or 0), end[0], end[1])
if start_dt <= now <= end_dt:
# Wow, much holiday!
return self.load_season(season) | [
"def",
"setup_seasonal",
"(",
"self",
")",
":",
"# If we've specified a season, just run that one",
"if",
"self",
".",
"ns",
".",
"season",
":",
"return",
"self",
".",
"load_season",
"(",
"self",
".",
"ns",
".",
"season",
")",
"# If we've specified another doge or no doge at all, it does not make",
"# sense to use seasons.",
"if",
"self",
".",
"ns",
".",
"doge_path",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"ns",
".",
"no_shibe",
":",
"return",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"for",
"season",
",",
"data",
"in",
"wow",
".",
"SEASONS",
".",
"items",
"(",
")",
":",
"start",
",",
"end",
"=",
"data",
"[",
"'dates'",
"]",
"start_dt",
"=",
"datetime",
".",
"datetime",
"(",
"now",
".",
"year",
",",
"start",
"[",
"0",
"]",
",",
"start",
"[",
"1",
"]",
")",
"# Be sane if the holiday season spans over New Year's day.",
"end_dt",
"=",
"datetime",
".",
"datetime",
"(",
"now",
".",
"year",
"+",
"(",
"start",
"[",
"0",
"]",
">",
"end",
"[",
"0",
"]",
"and",
"1",
"or",
"0",
")",
",",
"end",
"[",
"0",
"]",
",",
"end",
"[",
"1",
"]",
")",
"if",
"start_dt",
"<=",
"now",
"<=",
"end_dt",
":",
"# Wow, much holiday!",
"return",
"self",
".",
"load_season",
"(",
"season",
")"
] | Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence. | [
"Check",
"if",
"there",
"s",
"some",
"seasonal",
"holiday",
"going",
"on",
"setup",
"appropriate",
"Shibe",
"picture",
"and",
"load",
"holiday",
"words",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L75-L106 | -1 |
||||||
251,367 | thiderman/doge | doge/core.py | Doge.apply_text | def apply_text(self):
"""
Apply text around doge
"""
# Calculate a random sampling of lines that are to have text applied
# onto them. Return value is a sorted list of line index integers.
linelen = len(self.lines)
affected = sorted(random.sample(range(linelen), int(linelen / 3.5)))
for i, target in enumerate(affected, start=1):
line = self.lines[target]
line = re.sub('\n', ' ', line)
word = self.words.get()
# If first or last line, or a random selection, use standalone wow.
if i == 1 or i == len(affected) or random.choice(range(20)) == 0:
word = 'wow'
# Generate a new DogeMessage, possibly based on a word.
self.lines[target] = DogeMessage(self, line, word).generate() | python | def apply_text(self):
"""
Apply text around doge
"""
# Calculate a random sampling of lines that are to have text applied
# onto them. Return value is a sorted list of line index integers.
linelen = len(self.lines)
affected = sorted(random.sample(range(linelen), int(linelen / 3.5)))
for i, target in enumerate(affected, start=1):
line = self.lines[target]
line = re.sub('\n', ' ', line)
word = self.words.get()
# If first or last line, or a random selection, use standalone wow.
if i == 1 or i == len(affected) or random.choice(range(20)) == 0:
word = 'wow'
# Generate a new DogeMessage, possibly based on a word.
self.lines[target] = DogeMessage(self, line, word).generate() | [
"def",
"apply_text",
"(",
"self",
")",
":",
"# Calculate a random sampling of lines that are to have text applied",
"# onto them. Return value is a sorted list of line index integers.",
"linelen",
"=",
"len",
"(",
"self",
".",
"lines",
")",
"affected",
"=",
"sorted",
"(",
"random",
".",
"sample",
"(",
"range",
"(",
"linelen",
")",
",",
"int",
"(",
"linelen",
"/",
"3.5",
")",
")",
")",
"for",
"i",
",",
"target",
"in",
"enumerate",
"(",
"affected",
",",
"start",
"=",
"1",
")",
":",
"line",
"=",
"self",
".",
"lines",
"[",
"target",
"]",
"line",
"=",
"re",
".",
"sub",
"(",
"'\\n'",
",",
"' '",
",",
"line",
")",
"word",
"=",
"self",
".",
"words",
".",
"get",
"(",
")",
"# If first or last line, or a random selection, use standalone wow.",
"if",
"i",
"==",
"1",
"or",
"i",
"==",
"len",
"(",
"affected",
")",
"or",
"random",
".",
"choice",
"(",
"range",
"(",
"20",
")",
")",
"==",
"0",
":",
"word",
"=",
"'wow'",
"# Generate a new DogeMessage, possibly based on a word.",
"self",
".",
"lines",
"[",
"target",
"]",
"=",
"DogeMessage",
"(",
"self",
",",
"line",
",",
"word",
")",
".",
"generate",
"(",
")"
] | Apply text around doge | [
"Apply",
"text",
"around",
"doge"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L116-L138 | -1 |
||||||
251,368 | thiderman/doge | doge/core.py | Doge.load_doge | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lines = [l.decode('utf-8') for l in f.xreadlines()]
else:
# encode to printable characters, leaving a space in place
# of untranslatable characters, resulting in a slightly
# blockier doge on non-UTF8 terminals
doge_lines = [
l.decode('utf-8')
.encode(locale.getpreferredencoding(), 'replace')
.replace('?', ' ')
for l in f.xreadlines()
]
else:
doge_lines = [l for l in f.readlines()]
return doge_lines | python | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lines = [l.decode('utf-8') for l in f.xreadlines()]
else:
# encode to printable characters, leaving a space in place
# of untranslatable characters, resulting in a slightly
# blockier doge on non-UTF8 terminals
doge_lines = [
l.decode('utf-8')
.encode(locale.getpreferredencoding(), 'replace')
.replace('?', ' ')
for l in f.xreadlines()
]
else:
doge_lines = [l for l in f.readlines()]
return doge_lines | [
"def",
"load_doge",
"(",
"self",
")",
":",
"if",
"self",
".",
"ns",
".",
"no_shibe",
":",
"return",
"[",
"''",
"]",
"with",
"open",
"(",
"self",
".",
"doge_path",
")",
"as",
"f",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"if",
"locale",
".",
"getpreferredencoding",
"(",
")",
"==",
"'UTF-8'",
":",
"doge_lines",
"=",
"[",
"l",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"l",
"in",
"f",
".",
"xreadlines",
"(",
")",
"]",
"else",
":",
"# encode to printable characters, leaving a space in place",
"# of untranslatable characters, resulting in a slightly",
"# blockier doge on non-UTF8 terminals",
"doge_lines",
"=",
"[",
"l",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"encode",
"(",
"locale",
".",
"getpreferredencoding",
"(",
")",
",",
"'replace'",
")",
".",
"replace",
"(",
"'?'",
",",
"' '",
")",
"for",
"l",
"in",
"f",
".",
"xreadlines",
"(",
")",
"]",
"else",
":",
"doge_lines",
"=",
"[",
"l",
"for",
"l",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
"return",
"doge_lines"
] | Return pretty ASCII Shibe.
wow | [
"Return",
"pretty",
"ASCII",
"Shibe",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L140-L167 | -1 |
||||||
251,369 | thiderman/doge | doge/core.py | Doge.get_real_data | def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
ret.append(editor)
# OS, hostname and... architechture (because lel)
if hasattr(os, 'uname'):
uname = os.uname()
ret.append(uname[0])
ret.append(uname[1])
ret.append(uname[4])
# Grab actual files from $HOME.
files = os.listdir(os.environ.get('HOME'))
if files:
ret.append(random.choice(files))
# Grab some processes
ret += self.get_processes()[:2]
# Prepare the returned data. First, lowercase it.
# If there is unicode data being returned from any of the above
# Python 2 needs to decode the UTF bytes to not crash. See issue #45.
func = str.lower
if sys.version_info < (3,):
func = lambda x: str.lower(x).decode('utf-8')
self.words.extend(map(func, ret)) | python | def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
ret.append(editor)
# OS, hostname and... architechture (because lel)
if hasattr(os, 'uname'):
uname = os.uname()
ret.append(uname[0])
ret.append(uname[1])
ret.append(uname[4])
# Grab actual files from $HOME.
files = os.listdir(os.environ.get('HOME'))
if files:
ret.append(random.choice(files))
# Grab some processes
ret += self.get_processes()[:2]
# Prepare the returned data. First, lowercase it.
# If there is unicode data being returned from any of the above
# Python 2 needs to decode the UTF bytes to not crash. See issue #45.
func = str.lower
if sys.version_info < (3,):
func = lambda x: str.lower(x).decode('utf-8')
self.words.extend(map(func, ret)) | [
"def",
"get_real_data",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'USER'",
")",
"if",
"username",
":",
"ret",
".",
"append",
"(",
"username",
")",
"editor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'EDITOR'",
")",
"if",
"editor",
":",
"editor",
"=",
"editor",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"ret",
".",
"append",
"(",
"editor",
")",
"# OS, hostname and... architechture (because lel)",
"if",
"hasattr",
"(",
"os",
",",
"'uname'",
")",
":",
"uname",
"=",
"os",
".",
"uname",
"(",
")",
"ret",
".",
"append",
"(",
"uname",
"[",
"0",
"]",
")",
"ret",
".",
"append",
"(",
"uname",
"[",
"1",
"]",
")",
"ret",
".",
"append",
"(",
"uname",
"[",
"4",
"]",
")",
"# Grab actual files from $HOME.",
"files",
"=",
"os",
".",
"listdir",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
")",
")",
"if",
"files",
":",
"ret",
".",
"append",
"(",
"random",
".",
"choice",
"(",
"files",
")",
")",
"# Grab some processes",
"ret",
"+=",
"self",
".",
"get_processes",
"(",
")",
"[",
":",
"2",
"]",
"# Prepare the returned data. First, lowercase it.",
"# If there is unicode data being returned from any of the above",
"# Python 2 needs to decode the UTF bytes to not crash. See issue #45.",
"func",
"=",
"str",
".",
"lower",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
")",
":",
"func",
"=",
"lambda",
"x",
":",
"str",
".",
"lower",
"(",
"x",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"words",
".",
"extend",
"(",
"map",
"(",
"func",
",",
"ret",
")",
")"
] | Grab actual data from the system | [
"Grab",
"actual",
"data",
"from",
"the",
"system"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L169-L207 | -1 |
||||||
251,370 | thiderman/doge | doge/core.py | Doge.get_stdin_data | def get_stdin_data(self):
"""
Get words from stdin.
"""
if self.tty.in_is_tty:
# No pipez found
return False
if sys.version_info < (3, 0):
stdin_lines = (l.decode('utf-8') for l in sys.stdin.xreadlines())
else:
stdin_lines = (l for l in sys.stdin.readlines())
rx_word = re.compile("\w+", re.UNICODE)
# If we have stdin data, we should remove everything else!
self.words.clear()
word_list = [match.group(0)
for line in stdin_lines
for match in rx_word.finditer(line.lower())]
if self.ns.filter_stopwords:
word_list = self.filter_words(
word_list, stopwords=wow.STOPWORDS,
min_length=self.ns.min_length)
self.words.extend(word_list)
return True | python | def get_stdin_data(self):
"""
Get words from stdin.
"""
if self.tty.in_is_tty:
# No pipez found
return False
if sys.version_info < (3, 0):
stdin_lines = (l.decode('utf-8') for l in sys.stdin.xreadlines())
else:
stdin_lines = (l for l in sys.stdin.readlines())
rx_word = re.compile("\w+", re.UNICODE)
# If we have stdin data, we should remove everything else!
self.words.clear()
word_list = [match.group(0)
for line in stdin_lines
for match in rx_word.finditer(line.lower())]
if self.ns.filter_stopwords:
word_list = self.filter_words(
word_list, stopwords=wow.STOPWORDS,
min_length=self.ns.min_length)
self.words.extend(word_list)
return True | [
"def",
"get_stdin_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"tty",
".",
"in_is_tty",
":",
"# No pipez found",
"return",
"False",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"stdin_lines",
"=",
"(",
"l",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"l",
"in",
"sys",
".",
"stdin",
".",
"xreadlines",
"(",
")",
")",
"else",
":",
"stdin_lines",
"=",
"(",
"l",
"for",
"l",
"in",
"sys",
".",
"stdin",
".",
"readlines",
"(",
")",
")",
"rx_word",
"=",
"re",
".",
"compile",
"(",
"\"\\w+\"",
",",
"re",
".",
"UNICODE",
")",
"# If we have stdin data, we should remove everything else!",
"self",
".",
"words",
".",
"clear",
"(",
")",
"word_list",
"=",
"[",
"match",
".",
"group",
"(",
"0",
")",
"for",
"line",
"in",
"stdin_lines",
"for",
"match",
"in",
"rx_word",
".",
"finditer",
"(",
"line",
".",
"lower",
"(",
")",
")",
"]",
"if",
"self",
".",
"ns",
".",
"filter_stopwords",
":",
"word_list",
"=",
"self",
".",
"filter_words",
"(",
"word_list",
",",
"stopwords",
"=",
"wow",
".",
"STOPWORDS",
",",
"min_length",
"=",
"self",
".",
"ns",
".",
"min_length",
")",
"self",
".",
"words",
".",
"extend",
"(",
"word_list",
")",
"return",
"True"
] | Get words from stdin. | [
"Get",
"words",
"from",
"stdin",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L213-L242 | -1 |
||||||
251,371 | thiderman/doge | doge/core.py | Doge.get_processes | def get_processes(self):
"""
Grab a shuffled list of all currently running process names
"""
procs = set()
try:
# POSIX ps, so it should work in most environments where doge would
p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE)
output, error = p.communicate()
if sys.version_info > (3, 0):
output = output.decode('utf-8')
for comm in output.split('\n'):
name = comm.split('/')[-1]
# Filter short and weird ones
if name and len(name) >= 2 and ':' not in name:
procs.add(name)
finally:
# Either it executed properly or no ps was found.
proc_list = list(procs)
random.shuffle(proc_list)
return proc_list | python | def get_processes(self):
"""
Grab a shuffled list of all currently running process names
"""
procs = set()
try:
# POSIX ps, so it should work in most environments where doge would
p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE)
output, error = p.communicate()
if sys.version_info > (3, 0):
output = output.decode('utf-8')
for comm in output.split('\n'):
name = comm.split('/')[-1]
# Filter short and weird ones
if name and len(name) >= 2 and ':' not in name:
procs.add(name)
finally:
# Either it executed properly or no ps was found.
proc_list = list(procs)
random.shuffle(proc_list)
return proc_list | [
"def",
"get_processes",
"(",
"self",
")",
":",
"procs",
"=",
"set",
"(",
")",
"try",
":",
"# POSIX ps, so it should work in most environments where doge would",
"p",
"=",
"sp",
".",
"Popen",
"(",
"[",
"'ps'",
",",
"'-A'",
",",
"'-o'",
",",
"'comm='",
"]",
",",
"stdout",
"=",
"sp",
".",
"PIPE",
")",
"output",
",",
"error",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"comm",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"name",
"=",
"comm",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"# Filter short and weird ones",
"if",
"name",
"and",
"len",
"(",
"name",
")",
">=",
"2",
"and",
"':'",
"not",
"in",
"name",
":",
"procs",
".",
"add",
"(",
"name",
")",
"finally",
":",
"# Either it executed properly or no ps was found.",
"proc_list",
"=",
"list",
"(",
"procs",
")",
"random",
".",
"shuffle",
"(",
"proc_list",
")",
"return",
"proc_list"
] | Grab a shuffled list of all currently running process names | [
"Grab",
"a",
"shuffled",
"list",
"of",
"all",
"currently",
"running",
"process",
"names"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L244-L270 | -1 |
||||||
251,372 | thiderman/doge | doge/core.py | TTYHandler.get_tty_size | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
"""
if sys.platform == 'win32':
# stdin, stdout, stderr = -10, -11, -12
ret = self._tty_size_windows(-10)
ret = ret or self._tty_size_windows(-11)
ret = ret or self._tty_size_windows(-12)
else:
# stdin, stdout, stderr = 0, 1, 2
ret = self._tty_size_linux(0)
ret = ret or self._tty_size_linux(1)
ret = ret or self._tty_size_linux(2)
return ret or (25, 80) | python | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
"""
if sys.platform == 'win32':
# stdin, stdout, stderr = -10, -11, -12
ret = self._tty_size_windows(-10)
ret = ret or self._tty_size_windows(-11)
ret = ret or self._tty_size_windows(-12)
else:
# stdin, stdout, stderr = 0, 1, 2
ret = self._tty_size_linux(0)
ret = ret or self._tty_size_linux(1)
ret = ret or self._tty_size_linux(2)
return ret or (25, 80) | [
"def",
"get_tty_size",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"# stdin, stdout, stderr = -10, -11, -12",
"ret",
"=",
"self",
".",
"_tty_size_windows",
"(",
"-",
"10",
")",
"ret",
"=",
"ret",
"or",
"self",
".",
"_tty_size_windows",
"(",
"-",
"11",
")",
"ret",
"=",
"ret",
"or",
"self",
".",
"_tty_size_windows",
"(",
"-",
"12",
")",
"else",
":",
"# stdin, stdout, stderr = 0, 1, 2",
"ret",
"=",
"self",
".",
"_tty_size_linux",
"(",
"0",
")",
"ret",
"=",
"ret",
"or",
"self",
".",
"_tty_size_linux",
"(",
"1",
")",
"ret",
"=",
"ret",
"or",
"self",
".",
"_tty_size_linux",
"(",
"2",
")",
"return",
"ret",
"or",
"(",
"25",
",",
"80",
")"
] | Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does. | [
"Get",
"the",
"current",
"terminal",
"size",
"without",
"using",
"a",
"subprocess"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L365-L386 | -1 |
||||||
251,373 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _coords | def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates.
"""
assert shape.geom_type == 'Polygon'
coords = [list(shape.exterior.coords)]
for interior in shape.interiors:
coords.append(list(interior.coords))
return coords | python | def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates.
"""
assert shape.geom_type == 'Polygon'
coords = [list(shape.exterior.coords)]
for interior in shape.interiors:
coords.append(list(interior.coords))
return coords | [
"def",
"_coords",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
"coords",
"=",
"[",
"list",
"(",
"shape",
".",
"exterior",
".",
"coords",
")",
"]",
"for",
"interior",
"in",
"shape",
".",
"interiors",
":",
"coords",
".",
"append",
"(",
"list",
"(",
"interior",
".",
"coords",
")",
")",
"return",
"coords"
] | Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates. | [
"Return",
"a",
"list",
"of",
"lists",
"of",
"coordinates",
"of",
"the",
"polygon",
".",
"The",
"list",
"consists",
"firstly",
"of",
"the",
"list",
"of",
"exterior",
"coordinates",
"followed",
"by",
"zero",
"or",
"more",
"lists",
"of",
"any",
"interior",
"coordinates",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L8-L19 | -1 |
||||||
251,374 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _union_in_blocks | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
j = min(i + block_size, n_contours)
inners = []
for c in contours[i:j]:
p = _contour_to_poly(c)
if p.type == 'Polygon':
inners.append(p)
elif p.type == 'MultiPolygon':
inners.extend(p.geoms)
holes = unary_union(inners)
assert holes.is_valid
yield holes | python | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
j = min(i + block_size, n_contours)
inners = []
for c in contours[i:j]:
p = _contour_to_poly(c)
if p.type == 'Polygon':
inners.append(p)
elif p.type == 'MultiPolygon':
inners.extend(p.geoms)
holes = unary_union(inners)
assert holes.is_valid
yield holes | [
"def",
"_union_in_blocks",
"(",
"contours",
",",
"block_size",
")",
":",
"n_contours",
"=",
"len",
"(",
"contours",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"n_contours",
",",
"block_size",
")",
":",
"j",
"=",
"min",
"(",
"i",
"+",
"block_size",
",",
"n_contours",
")",
"inners",
"=",
"[",
"]",
"for",
"c",
"in",
"contours",
"[",
"i",
":",
"j",
"]",
":",
"p",
"=",
"_contour_to_poly",
"(",
"c",
")",
"if",
"p",
".",
"type",
"==",
"'Polygon'",
":",
"inners",
".",
"append",
"(",
"p",
")",
"elif",
"p",
".",
"type",
"==",
"'MultiPolygon'",
":",
"inners",
".",
"extend",
"(",
"p",
".",
"geoms",
")",
"holes",
"=",
"unary_union",
"(",
"inners",
")",
"assert",
"holes",
".",
"is_valid",
"yield",
"holes"
] | Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them. | [
"Generator",
"which",
"yields",
"a",
"valid",
"shape",
"for",
"each",
"block_size",
"multiple",
"of",
"input",
"contours",
".",
"This",
"merges",
"together",
"the",
"contours",
"for",
"each",
"block",
"before",
"yielding",
"them",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L53-L74 | -1 |
||||||
251,375 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _polytree_node_to_shapely | def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
polygons.extend(p)
children.extend(c)
if node.IsHole:
# check expectations: a node should be a hole, _or_ return children.
# this is because children of holes must be outers, and should be on
# the polygons list.
assert len(children) == 0
if node.Contour:
children = [node.Contour]
else:
children = []
elif node.Contour:
poly = _contour_to_poly(node.Contour)
# we add each inner one-by-one so that we can reject them individually
# if they cause the polygon to become invalid. if the shape has lots
# of inners, then this can mean a proportional amount of work, and may
# take 1,000s of seconds. instead, we can group inners together, which
# reduces the number of times we call the expensive 'difference'
# method.
block_size = 200
if len(children) > block_size:
inners = _union_in_blocks(children, block_size)
else:
inners = _generate_polys(children)
for inner in inners:
# the difference of two valid polygons may fail, and in this
# situation we'd like to be able to display the polygon anyway.
# so we discard the bad inner and continue.
#
# see test_polygon_inners_crossing_outer for a test case.
try:
diff = poly.difference(inner)
except:
continue
if not diff.is_valid:
diff = diff.buffer(0)
# keep this for when https://trac.osgeo.org/geos/ticket/789 is
# resolved.
#
# assert diff.is_valid, \
# "Difference of %s and %s did not make valid polygon %s " \
# " because %s" \
# % (poly.wkt, inner.wkt, diff.wkt, explain_validity(diff))
#
# NOTE: this throws away the inner ring if we can't produce a
# valid difference. not ideal, but we'd rather produce something
# that's valid than nothing.
if diff.is_valid:
poly = diff
assert poly.is_valid
if poly.type == 'MultiPolygon':
polygons.extend(poly.geoms)
else:
polygons.append(poly)
children = []
else:
# check expectations: this branch gets executed if this node is not a
# hole, and has no contour. in that situation we'd expect that it has
# no children, as it would not be possible to subtract children from
# an empty outer contour.
assert len(children) == 0
return (polygons, children) | python | def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
polygons.extend(p)
children.extend(c)
if node.IsHole:
# check expectations: a node should be a hole, _or_ return children.
# this is because children of holes must be outers, and should be on
# the polygons list.
assert len(children) == 0
if node.Contour:
children = [node.Contour]
else:
children = []
elif node.Contour:
poly = _contour_to_poly(node.Contour)
# we add each inner one-by-one so that we can reject them individually
# if they cause the polygon to become invalid. if the shape has lots
# of inners, then this can mean a proportional amount of work, and may
# take 1,000s of seconds. instead, we can group inners together, which
# reduces the number of times we call the expensive 'difference'
# method.
block_size = 200
if len(children) > block_size:
inners = _union_in_blocks(children, block_size)
else:
inners = _generate_polys(children)
for inner in inners:
# the difference of two valid polygons may fail, and in this
# situation we'd like to be able to display the polygon anyway.
# so we discard the bad inner and continue.
#
# see test_polygon_inners_crossing_outer for a test case.
try:
diff = poly.difference(inner)
except:
continue
if not diff.is_valid:
diff = diff.buffer(0)
# keep this for when https://trac.osgeo.org/geos/ticket/789 is
# resolved.
#
# assert diff.is_valid, \
# "Difference of %s and %s did not make valid polygon %s " \
# " because %s" \
# % (poly.wkt, inner.wkt, diff.wkt, explain_validity(diff))
#
# NOTE: this throws away the inner ring if we can't produce a
# valid difference. not ideal, but we'd rather produce something
# that's valid than nothing.
if diff.is_valid:
poly = diff
assert poly.is_valid
if poly.type == 'MultiPolygon':
polygons.extend(poly.geoms)
else:
polygons.append(poly)
children = []
else:
# check expectations: this branch gets executed if this node is not a
# hole, and has no contour. in that situation we'd expect that it has
# no children, as it would not be possible to subtract children from
# an empty outer contour.
assert len(children) == 0
return (polygons, children) | [
"def",
"_polytree_node_to_shapely",
"(",
"node",
")",
":",
"polygons",
"=",
"[",
"]",
"children",
"=",
"[",
"]",
"for",
"ch",
"in",
"node",
".",
"Childs",
":",
"p",
",",
"c",
"=",
"_polytree_node_to_shapely",
"(",
"ch",
")",
"polygons",
".",
"extend",
"(",
"p",
")",
"children",
".",
"extend",
"(",
"c",
")",
"if",
"node",
".",
"IsHole",
":",
"# check expectations: a node should be a hole, _or_ return children.",
"# this is because children of holes must be outers, and should be on",
"# the polygons list.",
"assert",
"len",
"(",
"children",
")",
"==",
"0",
"if",
"node",
".",
"Contour",
":",
"children",
"=",
"[",
"node",
".",
"Contour",
"]",
"else",
":",
"children",
"=",
"[",
"]",
"elif",
"node",
".",
"Contour",
":",
"poly",
"=",
"_contour_to_poly",
"(",
"node",
".",
"Contour",
")",
"# we add each inner one-by-one so that we can reject them individually",
"# if they cause the polygon to become invalid. if the shape has lots",
"# of inners, then this can mean a proportional amount of work, and may",
"# take 1,000s of seconds. instead, we can group inners together, which",
"# reduces the number of times we call the expensive 'difference'",
"# method.",
"block_size",
"=",
"200",
"if",
"len",
"(",
"children",
")",
">",
"block_size",
":",
"inners",
"=",
"_union_in_blocks",
"(",
"children",
",",
"block_size",
")",
"else",
":",
"inners",
"=",
"_generate_polys",
"(",
"children",
")",
"for",
"inner",
"in",
"inners",
":",
"# the difference of two valid polygons may fail, and in this",
"# situation we'd like to be able to display the polygon anyway.",
"# so we discard the bad inner and continue.",
"#",
"# see test_polygon_inners_crossing_outer for a test case.",
"try",
":",
"diff",
"=",
"poly",
".",
"difference",
"(",
"inner",
")",
"except",
":",
"continue",
"if",
"not",
"diff",
".",
"is_valid",
":",
"diff",
"=",
"diff",
".",
"buffer",
"(",
"0",
")",
"# keep this for when https://trac.osgeo.org/geos/ticket/789 is",
"# resolved.",
"#",
"# assert diff.is_valid, \\",
"# \"Difference of %s and %s did not make valid polygon %s \" \\",
"# \" because %s\" \\",
"# % (poly.wkt, inner.wkt, diff.wkt, explain_validity(diff))",
"#",
"# NOTE: this throws away the inner ring if we can't produce a",
"# valid difference. not ideal, but we'd rather produce something",
"# that's valid than nothing.",
"if",
"diff",
".",
"is_valid",
":",
"poly",
"=",
"diff",
"assert",
"poly",
".",
"is_valid",
"if",
"poly",
".",
"type",
"==",
"'MultiPolygon'",
":",
"polygons",
".",
"extend",
"(",
"poly",
".",
"geoms",
")",
"else",
":",
"polygons",
".",
"append",
"(",
"poly",
")",
"children",
"=",
"[",
"]",
"else",
":",
"# check expectations: this branch gets executed if this node is not a",
"# hole, and has no contour. in that situation we'd expect that it has",
"# no children, as it would not be possible to subtract children from",
"# an empty outer contour.",
"assert",
"len",
"(",
"children",
")",
"==",
"0",
"return",
"(",
"polygons",
",",
"children",
")"
] | Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children) | [
"Recurses",
"down",
"a",
"Clipper",
"PolyTree",
"extracting",
"the",
"results",
"as",
"Shapely",
"objects",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L87-L169 | -1 |
||||||
251,376 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_valid_pyclipper | def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process.
"""
# drop all degenerate inners
clean_shape = _drop_degenerate_inners(shape)
pc = pyclipper.Pyclipper()
try:
pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)
# note: Execute2 returns the polygon tree, not the list of paths
result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)
except pyclipper.ClipperException:
return MultiPolygon([])
return _polytree_to_shapely(result) | python | def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process.
"""
# drop all degenerate inners
clean_shape = _drop_degenerate_inners(shape)
pc = pyclipper.Pyclipper()
try:
pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)
# note: Execute2 returns the polygon tree, not the list of paths
result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)
except pyclipper.ClipperException:
return MultiPolygon([])
return _polytree_to_shapely(result) | [
"def",
"make_valid_pyclipper",
"(",
"shape",
")",
":",
"# drop all degenerate inners",
"clean_shape",
"=",
"_drop_degenerate_inners",
"(",
"shape",
")",
"pc",
"=",
"pyclipper",
".",
"Pyclipper",
"(",
")",
"try",
":",
"pc",
".",
"AddPaths",
"(",
"_coords",
"(",
"clean_shape",
")",
",",
"pyclipper",
".",
"PT_SUBJECT",
",",
"True",
")",
"# note: Execute2 returns the polygon tree, not the list of paths",
"result",
"=",
"pc",
".",
"Execute2",
"(",
"pyclipper",
".",
"CT_UNION",
",",
"pyclipper",
".",
"PFT_EVENODD",
")",
"except",
"pyclipper",
".",
"ClipperException",
":",
"return",
"MultiPolygon",
"(",
"[",
"]",
")",
"return",
"_polytree_to_shapely",
"(",
"result",
")"
] | Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process. | [
"Use",
"the",
"pyclipper",
"library",
"to",
"union",
"a",
"polygon",
"on",
"its",
"own",
".",
"This",
"operation",
"uses",
"the",
"even",
"-",
"odd",
"rule",
"to",
"determine",
"which",
"points",
"are",
"in",
"the",
"interior",
"of",
"the",
"polygon",
"and",
"can",
"reconstruct",
"the",
"orientation",
"of",
"the",
"polygon",
"from",
"that",
".",
"The",
"pyclipper",
"library",
"is",
"robust",
"and",
"uses",
"integer",
"coordinates",
"so",
"should",
"not",
"produce",
"any",
"additional",
"degeneracies",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L184-L211 | -1 |
||||||
251,377 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_valid_polygon | def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies.
"""
assert shape.geom_type == 'Polygon'
shape = make_valid_pyclipper(shape)
assert shape.is_valid
return shape | python | def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies.
"""
assert shape.geom_type == 'Polygon'
shape = make_valid_pyclipper(shape)
assert shape.is_valid
return shape | [
"def",
"make_valid_polygon",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
"shape",
"=",
"make_valid_pyclipper",
"(",
"shape",
")",
"assert",
"shape",
".",
"is_valid",
"return",
"shape"
] | Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies. | [
"Make",
"a",
"polygon",
"valid",
".",
"Polygons",
"can",
"be",
"invalid",
"in",
"many",
"ways",
"such",
"as",
"self",
"-",
"intersection",
"self",
"-",
"touching",
"and",
"degeneracy",
".",
"This",
"process",
"attempts",
"to",
"make",
"a",
"polygon",
"valid",
"while",
"retaining",
"as",
"much",
"of",
"its",
"extent",
"or",
"area",
"as",
"possible",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L214-L234 | -1 |
||||||
251,378 | tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_it_valid | def make_it_valid(shape):
"""
Attempt to make any polygon or multipolygon valid.
"""
if shape.is_empty:
return shape
elif shape.type == 'MultiPolygon':
shape = make_valid_multipolygon(shape)
elif shape.type == 'Polygon':
shape = make_valid_polygon(shape)
return shape | python | def make_it_valid(shape):
"""
Attempt to make any polygon or multipolygon valid.
"""
if shape.is_empty:
return shape
elif shape.type == 'MultiPolygon':
shape = make_valid_multipolygon(shape)
elif shape.type == 'Polygon':
shape = make_valid_polygon(shape)
return shape | [
"def",
"make_it_valid",
"(",
"shape",
")",
":",
"if",
"shape",
".",
"is_empty",
":",
"return",
"shape",
"elif",
"shape",
".",
"type",
"==",
"'MultiPolygon'",
":",
"shape",
"=",
"make_valid_multipolygon",
"(",
"shape",
")",
"elif",
"shape",
".",
"type",
"==",
"'Polygon'",
":",
"shape",
"=",
"make_valid_polygon",
"(",
"shape",
")",
"return",
"shape"
] | Attempt to make any polygon or multipolygon valid. | [
"Attempt",
"to",
"make",
"any",
"polygon",
"or",
"multipolygon",
"valid",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L254-L268 | -1 |
||||||
251,379 | tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _decode_lines | def _decode_lines(geom):
"""
Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines.
"""
lines = []
current_line = []
current_moveto = None
# to keep track of the position. we'll adapt the move-to commands to all
# be relative to 0,0 at the beginning of each linestring.
x = 0
y = 0
end = len(geom)
i = 0
while i < end:
header = geom[i]
cmd = header & 7
run_length = header // 8
if cmd == 1: # move to
# flush previous line.
if current_moveto:
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
current_line = []
assert run_length == 1
x += unzigzag(geom[i+1])
y += unzigzag(geom[i+2])
i += 3
current_moveto = MoveTo(x, y)
elif cmd == 2: # line to
assert current_moveto
# we just copy this run, since it's encoding isn't going to change
next_i = i + 1 + run_length * 2
current_line.extend(geom[i:next_i])
# but we still need to decode it to figure out where each move-to
# command is in absolute space.
for j in xrange(0, run_length):
dx = unzigzag(geom[i + 1 + 2 * j])
dy = unzigzag(geom[i + 2 + 2 * j])
x += dx
y += dy
i = next_i
else:
raise ValueError('Unhandled command: %d' % cmd)
if current_line:
assert current_moveto
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
return lines | python | def _decode_lines(geom):
"""
Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines.
"""
lines = []
current_line = []
current_moveto = None
# to keep track of the position. we'll adapt the move-to commands to all
# be relative to 0,0 at the beginning of each linestring.
x = 0
y = 0
end = len(geom)
i = 0
while i < end:
header = geom[i]
cmd = header & 7
run_length = header // 8
if cmd == 1: # move to
# flush previous line.
if current_moveto:
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
current_line = []
assert run_length == 1
x += unzigzag(geom[i+1])
y += unzigzag(geom[i+2])
i += 3
current_moveto = MoveTo(x, y)
elif cmd == 2: # line to
assert current_moveto
# we just copy this run, since it's encoding isn't going to change
next_i = i + 1 + run_length * 2
current_line.extend(geom[i:next_i])
# but we still need to decode it to figure out where each move-to
# command is in absolute space.
for j in xrange(0, run_length):
dx = unzigzag(geom[i + 1 + 2 * j])
dy = unzigzag(geom[i + 2 + 2 * j])
x += dx
y += dy
i = next_i
else:
raise ValueError('Unhandled command: %d' % cmd)
if current_line:
assert current_moveto
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
return lines | [
"def",
"_decode_lines",
"(",
"geom",
")",
":",
"lines",
"=",
"[",
"]",
"current_line",
"=",
"[",
"]",
"current_moveto",
"=",
"None",
"# to keep track of the position. we'll adapt the move-to commands to all",
"# be relative to 0,0 at the beginning of each linestring.",
"x",
"=",
"0",
"y",
"=",
"0",
"end",
"=",
"len",
"(",
"geom",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"end",
":",
"header",
"=",
"geom",
"[",
"i",
"]",
"cmd",
"=",
"header",
"&",
"7",
"run_length",
"=",
"header",
"//",
"8",
"if",
"cmd",
"==",
"1",
":",
"# move to",
"# flush previous line.",
"if",
"current_moveto",
":",
"lines",
".",
"append",
"(",
"Line",
"(",
"current_moveto",
",",
"EndsAt",
"(",
"x",
",",
"y",
")",
",",
"current_line",
")",
")",
"current_line",
"=",
"[",
"]",
"assert",
"run_length",
"==",
"1",
"x",
"+=",
"unzigzag",
"(",
"geom",
"[",
"i",
"+",
"1",
"]",
")",
"y",
"+=",
"unzigzag",
"(",
"geom",
"[",
"i",
"+",
"2",
"]",
")",
"i",
"+=",
"3",
"current_moveto",
"=",
"MoveTo",
"(",
"x",
",",
"y",
")",
"elif",
"cmd",
"==",
"2",
":",
"# line to",
"assert",
"current_moveto",
"# we just copy this run, since it's encoding isn't going to change",
"next_i",
"=",
"i",
"+",
"1",
"+",
"run_length",
"*",
"2",
"current_line",
".",
"extend",
"(",
"geom",
"[",
"i",
":",
"next_i",
"]",
")",
"# but we still need to decode it to figure out where each move-to",
"# command is in absolute space.",
"for",
"j",
"in",
"xrange",
"(",
"0",
",",
"run_length",
")",
":",
"dx",
"=",
"unzigzag",
"(",
"geom",
"[",
"i",
"+",
"1",
"+",
"2",
"*",
"j",
"]",
")",
"dy",
"=",
"unzigzag",
"(",
"geom",
"[",
"i",
"+",
"2",
"+",
"2",
"*",
"j",
"]",
")",
"x",
"+=",
"dx",
"y",
"+=",
"dy",
"i",
"=",
"next_i",
"else",
":",
"raise",
"ValueError",
"(",
"'Unhandled command: %d'",
"%",
"cmd",
")",
"if",
"current_line",
":",
"assert",
"current_moveto",
"lines",
".",
"append",
"(",
"Line",
"(",
"current_moveto",
",",
"EndsAt",
"(",
"x",
",",
"y",
")",
",",
"current_line",
")",
")",
"return",
"lines"
] | Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines. | [
"Decode",
"a",
"linear",
"MVT",
"geometry",
"into",
"a",
"list",
"of",
"Lines",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L85-L146 | -1 |
||||||
251,380 | tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _reorder_lines | def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# looping over all the lines like this isn't terribly efficient, but
# in local tests seems to handle a few thousand lines without a
# problem.
min_dist = None
min_i = None
for i, line in enumerate(lines):
moveto, _, _ = line
dist = abs(moveto.x - x) + abs(moveto.y - y)
if min_dist is None or dist < min_dist:
min_dist = dist
min_i = i
assert min_i is not None
line = lines.pop(min_i)
_, endsat, _ = line
x = endsat.x
y = endsat.y
new_lines.append(line)
return new_lines | python | def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# looping over all the lines like this isn't terribly efficient, but
# in local tests seems to handle a few thousand lines without a
# problem.
min_dist = None
min_i = None
for i, line in enumerate(lines):
moveto, _, _ = line
dist = abs(moveto.x - x) + abs(moveto.y - y)
if min_dist is None or dist < min_dist:
min_dist = dist
min_i = i
assert min_i is not None
line = lines.pop(min_i)
_, endsat, _ = line
x = endsat.x
y = endsat.y
new_lines.append(line)
return new_lines | [
"def",
"_reorder_lines",
"(",
"lines",
")",
":",
"x",
"=",
"0",
"y",
"=",
"0",
"new_lines",
"=",
"[",
"]",
"# treat the list of lines as a stack, off which we keep popping the best",
"# one to add next.",
"while",
"lines",
":",
"# looping over all the lines like this isn't terribly efficient, but",
"# in local tests seems to handle a few thousand lines without a",
"# problem.",
"min_dist",
"=",
"None",
"min_i",
"=",
"None",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"moveto",
",",
"_",
",",
"_",
"=",
"line",
"dist",
"=",
"abs",
"(",
"moveto",
".",
"x",
"-",
"x",
")",
"+",
"abs",
"(",
"moveto",
".",
"y",
"-",
"y",
")",
"if",
"min_dist",
"is",
"None",
"or",
"dist",
"<",
"min_dist",
":",
"min_dist",
"=",
"dist",
"min_i",
"=",
"i",
"assert",
"min_i",
"is",
"not",
"None",
"line",
"=",
"lines",
".",
"pop",
"(",
"min_i",
")",
"_",
",",
"endsat",
",",
"_",
"=",
"line",
"x",
"=",
"endsat",
".",
"x",
"y",
"=",
"endsat",
".",
"y",
"new_lines",
".",
"append",
"(",
"line",
")",
"return",
"new_lines"
] | Reorder lines so that the distance from the end of one to the beginning of
the next is minimised. | [
"Reorder",
"lines",
"so",
"that",
"the",
"distance",
"from",
"the",
"end",
"of",
"one",
"to",
"the",
"beginning",
"of",
"the",
"next",
"is",
"minimised",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L149-L182 | -1 |
||||||
251,381 | tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _rewrite_geometry | def _rewrite_geometry(geom, new_lines):
"""
Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream.
"""
new_geom = []
x = 0
y = 0
for line in new_lines:
moveto, endsat, lineto_cmds = line
dx = moveto.x - x
dy = moveto.y - y
x = endsat.x
y = endsat.y
new_geom.append(9) # move to, run_length = 1
new_geom.append(zigzag(dx))
new_geom.append(zigzag(dy))
new_geom.extend(lineto_cmds)
# write the lines back out to geom
del geom[:]
geom.extend(new_geom) | python | def _rewrite_geometry(geom, new_lines):
"""
Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream.
"""
new_geom = []
x = 0
y = 0
for line in new_lines:
moveto, endsat, lineto_cmds = line
dx = moveto.x - x
dy = moveto.y - y
x = endsat.x
y = endsat.y
new_geom.append(9) # move to, run_length = 1
new_geom.append(zigzag(dx))
new_geom.append(zigzag(dy))
new_geom.extend(lineto_cmds)
# write the lines back out to geom
del geom[:]
geom.extend(new_geom) | [
"def",
"_rewrite_geometry",
"(",
"geom",
",",
"new_lines",
")",
":",
"new_geom",
"=",
"[",
"]",
"x",
"=",
"0",
"y",
"=",
"0",
"for",
"line",
"in",
"new_lines",
":",
"moveto",
",",
"endsat",
",",
"lineto_cmds",
"=",
"line",
"dx",
"=",
"moveto",
".",
"x",
"-",
"x",
"dy",
"=",
"moveto",
".",
"y",
"-",
"y",
"x",
"=",
"endsat",
".",
"x",
"y",
"=",
"endsat",
".",
"y",
"new_geom",
".",
"append",
"(",
"9",
")",
"# move to, run_length = 1",
"new_geom",
".",
"append",
"(",
"zigzag",
"(",
"dx",
")",
")",
"new_geom",
".",
"append",
"(",
"zigzag",
"(",
"dy",
")",
")",
"new_geom",
".",
"extend",
"(",
"lineto_cmds",
")",
"# write the lines back out to geom",
"del",
"geom",
"[",
":",
"]",
"geom",
".",
"extend",
"(",
"new_geom",
")"
] | Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream. | [
"Re",
"-",
"encode",
"a",
"list",
"of",
"Lines",
"with",
"absolute",
"MoveTos",
"as",
"a",
"continuous",
"stream",
"of",
"MVT",
"geometry",
"commands",
"each",
"relative",
"to",
"the",
"last",
".",
"Replace",
"geom",
"with",
"that",
"stream",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L185-L210 | -1 |
||||||
251,382 | tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | optimise_tile | def optimise_tile(tile_bytes):
"""
Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes.
"""
t = tile()
t.ParseFromString(tile_bytes)
for layer in t.layers:
sto = StringTableOptimiser()
for feature in layer.features:
# (multi)linestrings only
if feature.type == 2:
optimise_multilinestring(feature.geometry)
sto.add_tags(feature.tags)
sto.update_string_table(layer)
return t.SerializeToString() | python | def optimise_tile(tile_bytes):
"""
Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes.
"""
t = tile()
t.ParseFromString(tile_bytes)
for layer in t.layers:
sto = StringTableOptimiser()
for feature in layer.features:
# (multi)linestrings only
if feature.type == 2:
optimise_multilinestring(feature.geometry)
sto.add_tags(feature.tags)
sto.update_string_table(layer)
return t.SerializeToString() | [
"def",
"optimise_tile",
"(",
"tile_bytes",
")",
":",
"t",
"=",
"tile",
"(",
")",
"t",
".",
"ParseFromString",
"(",
"tile_bytes",
")",
"for",
"layer",
"in",
"t",
".",
"layers",
":",
"sto",
"=",
"StringTableOptimiser",
"(",
")",
"for",
"feature",
"in",
"layer",
".",
"features",
":",
"# (multi)linestrings only",
"if",
"feature",
".",
"type",
"==",
"2",
":",
"optimise_multilinestring",
"(",
"feature",
".",
"geometry",
")",
"sto",
".",
"add_tags",
"(",
"feature",
".",
"tags",
")",
"sto",
".",
"update_string_table",
"(",
"layer",
")",
"return",
"t",
".",
"SerializeToString",
"(",
")"
] | Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes. | [
"Decode",
"a",
"sequence",
"of",
"bytes",
"as",
"an",
"MVT",
"tile",
"and",
"reorder",
"the",
"string",
"table",
"of",
"its",
"layers",
"and",
"the",
"order",
"of",
"its",
"multilinestrings",
"to",
"save",
"a",
"few",
"bytes",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L226-L247 | -1 |
||||||
251,383 | tilezen/mapbox-vector-tile | mapbox_vector_tile/geom_encoder.py | GeometryEncoder.coords_on_grid | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
return x, y | python | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
return x, y | [
"def",
"coords_on_grid",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"x",
"=",
"int",
"(",
"self",
".",
"_round",
"(",
"x",
")",
")",
"if",
"isinstance",
"(",
"y",
",",
"float",
")",
":",
"y",
"=",
"int",
"(",
"self",
".",
"_round",
"(",
"y",
")",
")",
"if",
"not",
"self",
".",
"_y_coord_down",
":",
"y",
"=",
"self",
".",
"_extents",
"-",
"y",
"return",
"x",
",",
"y"
] | Snap coordinates on the grid with integer coordinates | [
"Snap",
"coordinates",
"on",
"the",
"grid",
"with",
"integer",
"coordinates"
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/geom_encoder.py#L39-L48 | -1 |
||||||
251,384 | tilezen/mapbox-vector-tile | mapbox_vector_tile/geom_encoder.py | GeometryEncoder.encode_arc | def encode_arc(self, coords):
""" Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added
"""
last_x, last_y = self._last_x, self._last_y
float_x, float_y = next(coords)
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
cmd_encoded = encode_cmd_length(CMD_MOVE_TO, 1)
commands = [cmd_encoded,
zigzag(dx),
zigzag(dy),
CMD_FAKE
]
pairs_added = 0
last_x, last_y = x, y
for float_x, float_y in coords:
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
if dx == 0 and dy == 0:
continue
commands.append(zigzag(dx))
commands.append(zigzag(dy))
last_x, last_y = x, y
pairs_added += 1
if pairs_added == 0:
return False
cmd_encoded = encode_cmd_length(CMD_LINE_TO, pairs_added)
commands[3] = cmd_encoded
self._geometry.extend(commands)
self._last_x, self._last_y = last_x, last_y
return True | python | def encode_arc(self, coords):
""" Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added
"""
last_x, last_y = self._last_x, self._last_y
float_x, float_y = next(coords)
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
cmd_encoded = encode_cmd_length(CMD_MOVE_TO, 1)
commands = [cmd_encoded,
zigzag(dx),
zigzag(dy),
CMD_FAKE
]
pairs_added = 0
last_x, last_y = x, y
for float_x, float_y in coords:
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
if dx == 0 and dy == 0:
continue
commands.append(zigzag(dx))
commands.append(zigzag(dy))
last_x, last_y = x, y
pairs_added += 1
if pairs_added == 0:
return False
cmd_encoded = encode_cmd_length(CMD_LINE_TO, pairs_added)
commands[3] = cmd_encoded
self._geometry.extend(commands)
self._last_x, self._last_y = last_x, last_y
return True | [
"def",
"encode_arc",
"(",
"self",
",",
"coords",
")",
":",
"last_x",
",",
"last_y",
"=",
"self",
".",
"_last_x",
",",
"self",
".",
"_last_y",
"float_x",
",",
"float_y",
"=",
"next",
"(",
"coords",
")",
"x",
",",
"y",
"=",
"self",
".",
"coords_on_grid",
"(",
"float_x",
",",
"float_y",
")",
"dx",
",",
"dy",
"=",
"x",
"-",
"last_x",
",",
"y",
"-",
"last_y",
"cmd_encoded",
"=",
"encode_cmd_length",
"(",
"CMD_MOVE_TO",
",",
"1",
")",
"commands",
"=",
"[",
"cmd_encoded",
",",
"zigzag",
"(",
"dx",
")",
",",
"zigzag",
"(",
"dy",
")",
",",
"CMD_FAKE",
"]",
"pairs_added",
"=",
"0",
"last_x",
",",
"last_y",
"=",
"x",
",",
"y",
"for",
"float_x",
",",
"float_y",
"in",
"coords",
":",
"x",
",",
"y",
"=",
"self",
".",
"coords_on_grid",
"(",
"float_x",
",",
"float_y",
")",
"dx",
",",
"dy",
"=",
"x",
"-",
"last_x",
",",
"y",
"-",
"last_y",
"if",
"dx",
"==",
"0",
"and",
"dy",
"==",
"0",
":",
"continue",
"commands",
".",
"append",
"(",
"zigzag",
"(",
"dx",
")",
")",
"commands",
".",
"append",
"(",
"zigzag",
"(",
"dy",
")",
")",
"last_x",
",",
"last_y",
"=",
"x",
",",
"y",
"pairs_added",
"+=",
"1",
"if",
"pairs_added",
"==",
"0",
":",
"return",
"False",
"cmd_encoded",
"=",
"encode_cmd_length",
"(",
"CMD_LINE_TO",
",",
"pairs_added",
")",
"commands",
"[",
"3",
"]",
"=",
"cmd_encoded",
"self",
".",
"_geometry",
".",
"extend",
"(",
"commands",
")",
"self",
".",
"_last_x",
",",
"self",
".",
"_last_y",
"=",
"last_x",
",",
"last_y",
"return",
"True"
] | Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added | [
"Appends",
"commands",
"to",
"_geometry",
"to",
"create",
"an",
"arc",
".",
"-",
"Returns",
"False",
"if",
"nothing",
"was",
"added",
"-",
"Returns",
"True",
"and",
"moves",
"_last_x",
"_last_y",
"if",
"some",
"points",
"where",
"added"
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/geom_encoder.py#L63-L96 | -1 |
||||||
251,385 | thesharp/daemonize | daemonize.py | Daemonize.sigterm | def sigterm(self, signum, frame):
"""
These actions will be done after SIGTERM.
"""
self.logger.warning("Caught signal %s. Stopping daemon." % signum)
sys.exit(0) | python | def sigterm(self, signum, frame):
"""
These actions will be done after SIGTERM.
"""
self.logger.warning("Caught signal %s. Stopping daemon." % signum)
sys.exit(0) | [
"def",
"sigterm",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Caught signal %s. Stopping daemon.\"",
"%",
"signum",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | These actions will be done after SIGTERM. | [
"These",
"actions",
"will",
"be",
"done",
"after",
"SIGTERM",
"."
] | 39a880f74c1d8ea09fa44fe2b99dec1c961201a9 | https://github.com/thesharp/daemonize/blob/39a880f74c1d8ea09fa44fe2b99dec1c961201a9/daemonize.py#L59-L64 | -1 |
||||||
251,386 | thesharp/daemonize | daemonize.py | Daemonize.exit | def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning("Stopping daemon.")
os.remove(self.pid)
sys.exit(0) | python | def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning("Stopping daemon.")
os.remove(self.pid)
sys.exit(0) | [
"def",
"exit",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Stopping daemon.\"",
")",
"os",
".",
"remove",
"(",
"self",
".",
"pid",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Cleanup pid file at exit. | [
"Cleanup",
"pid",
"file",
"at",
"exit",
"."
] | 39a880f74c1d8ea09fa44fe2b99dec1c961201a9 | https://github.com/thesharp/daemonize/blob/39a880f74c1d8ea09fa44fe2b99dec1c961201a9/daemonize.py#L66-L72 | -1 |
||||||
251,387 | ierror/django-js-reverse | django_js_reverse/templatetags/js_reverse.py | js_reverse_inline | def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_resolver(None)
return mark_safe(generate_js(default_urlresolver)) | python | def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_resolver(None)
return mark_safe(generate_js(default_urlresolver)) | [
"def",
"js_reverse_inline",
"(",
"context",
")",
":",
"if",
"'request'",
"in",
"context",
":",
"default_urlresolver",
"=",
"get_resolver",
"(",
"getattr",
"(",
"context",
"[",
"'request'",
"]",
",",
"'urlconf'",
",",
"None",
")",
")",
"else",
":",
"default_urlresolver",
"=",
"get_resolver",
"(",
"None",
")",
"return",
"mark_safe",
"(",
"generate_js",
"(",
"default_urlresolver",
")",
")"
] | Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs. | [
"Outputs",
"a",
"string",
"of",
"javascript",
"that",
"can",
"generate",
"URLs",
"via",
"the",
"use",
"of",
"the",
"names",
"given",
"to",
"those",
"URLs",
"."
] | 58320a8acec040636e8ad718754c2d472d0d504d | https://github.com/ierror/django-js-reverse/blob/58320a8acec040636e8ad718754c2d472d0d504d/django_js_reverse/templatetags/js_reverse.py#L16-L25 | -1 |
||||||
251,388 | webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._iterate_records | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invalid_gzip_err()
yield self.record
except EOFError:
empty_record = True
self.read_to_end()
if self.reader.decompressor:
# if another gzip member, continue
if self.reader.read_next_member():
continue
# if empty record, then we're done
elif empty_record:
break
# otherwise, probably a gzip
# containing multiple non-chunked records
# raise this as an error
else:
raise_invalid_gzip = True
# non-gzip, so we're done
elif empty_record:
break
self.close() | python | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invalid_gzip_err()
yield self.record
except EOFError:
empty_record = True
self.read_to_end()
if self.reader.decompressor:
# if another gzip member, continue
if self.reader.read_next_member():
continue
# if empty record, then we're done
elif empty_record:
break
# otherwise, probably a gzip
# containing multiple non-chunked records
# raise this as an error
else:
raise_invalid_gzip = True
# non-gzip, so we're done
elif empty_record:
break
self.close() | [
"def",
"_iterate_records",
"(",
"self",
")",
":",
"raise_invalid_gzip",
"=",
"False",
"empty_record",
"=",
"False",
"while",
"True",
":",
"try",
":",
"self",
".",
"record",
"=",
"self",
".",
"_next_record",
"(",
"self",
".",
"next_line",
")",
"if",
"raise_invalid_gzip",
":",
"self",
".",
"_raise_invalid_gzip_err",
"(",
")",
"yield",
"self",
".",
"record",
"except",
"EOFError",
":",
"empty_record",
"=",
"True",
"self",
".",
"read_to_end",
"(",
")",
"if",
"self",
".",
"reader",
".",
"decompressor",
":",
"# if another gzip member, continue",
"if",
"self",
".",
"reader",
".",
"read_next_member",
"(",
")",
":",
"continue",
"# if empty record, then we're done",
"elif",
"empty_record",
":",
"break",
"# otherwise, probably a gzip",
"# containing multiple non-chunked records",
"# raise this as an error",
"else",
":",
"raise_invalid_gzip",
"=",
"True",
"# non-gzip, so we're done",
"elif",
"empty_record",
":",
"break",
"self",
".",
"close",
"(",
")"
] | iterate over each record | [
"iterate",
"over",
"each",
"record"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L80-L118 | -1 |
||||||
251,389 | webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._consume_blanklines | def _consume_blanklines(self):
""" Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning
"""
empty_size = 0
first_line = True
while True:
line = self.reader.readline()
if len(line) == 0:
return None, empty_size
stripped = line.rstrip()
if len(stripped) == 0 or first_line:
empty_size += len(line)
if len(stripped) != 0:
# if first line is not blank,
# likely content-length was invalid, display warning
err_offset = self.fh.tell() - self.reader.rem_length() - empty_size
sys.stderr.write(self.INC_RECORD.format(err_offset, line))
self.err_count += 1
first_line = False
continue
return line, empty_size | python | def _consume_blanklines(self):
""" Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning
"""
empty_size = 0
first_line = True
while True:
line = self.reader.readline()
if len(line) == 0:
return None, empty_size
stripped = line.rstrip()
if len(stripped) == 0 or first_line:
empty_size += len(line)
if len(stripped) != 0:
# if first line is not blank,
# likely content-length was invalid, display warning
err_offset = self.fh.tell() - self.reader.rem_length() - empty_size
sys.stderr.write(self.INC_RECORD.format(err_offset, line))
self.err_count += 1
first_line = False
continue
return line, empty_size | [
"def",
"_consume_blanklines",
"(",
"self",
")",
":",
"empty_size",
"=",
"0",
"first_line",
"=",
"True",
"while",
"True",
":",
"line",
"=",
"self",
".",
"reader",
".",
"readline",
"(",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"return",
"None",
",",
"empty_size",
"stripped",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"len",
"(",
"stripped",
")",
"==",
"0",
"or",
"first_line",
":",
"empty_size",
"+=",
"len",
"(",
"line",
")",
"if",
"len",
"(",
"stripped",
")",
"!=",
"0",
":",
"# if first line is not blank,",
"# likely content-length was invalid, display warning",
"err_offset",
"=",
"self",
".",
"fh",
".",
"tell",
"(",
")",
"-",
"self",
".",
"reader",
".",
"rem_length",
"(",
")",
"-",
"empty_size",
"sys",
".",
"stderr",
".",
"write",
"(",
"self",
".",
"INC_RECORD",
".",
"format",
"(",
"err_offset",
",",
"line",
")",
")",
"self",
".",
"err_count",
"+=",
"1",
"first_line",
"=",
"False",
"continue",
"return",
"line",
",",
"empty_size"
] | Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning | [
"Consume",
"blank",
"lines",
"that",
"are",
"between",
"records",
"-",
"For",
"warcs",
"there",
"are",
"usually",
"2",
"-",
"For",
"arcs",
"may",
"be",
"1",
"or",
"0",
"-",
"For",
"block",
"gzipped",
"files",
"these",
"are",
"at",
"end",
"of",
"each",
"gzip",
"envelope",
"and",
"are",
"included",
"in",
"record",
"length",
"which",
"is",
"the",
"full",
"gzip",
"envelope",
"-",
"For",
"uncompressed",
"they",
"are",
"between",
"records",
"and",
"so",
"are",
"NOT",
"part",
"of",
"the",
"record",
"length"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L133-L171 | -1 |
||||||
251,390 | webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator.read_to_end | def read_to_end(self, record=None):
""" Read remainder of the stream
If a digester is included, update it
with the data read
"""
# no current record to read
if not self.record:
return None
# already at end of this record, don't read until it is consumed
if self.member_info:
return None
curr_offset = self.offset
while True:
b = self.record.raw_stream.read(BUFF_SIZE)
if not b:
break
"""
- For compressed files, blank lines are consumed
since they are part of record length
- For uncompressed files, blank lines are read later,
and not included in the record length
"""
#if self.reader.decompressor:
self.next_line, empty_size = self._consume_blanklines()
self.offset = self.fh.tell() - self.reader.rem_length()
#if self.offset < 0:
# raise Exception('Not Gzipped Properly')
if self.next_line:
self.offset -= len(self.next_line)
length = self.offset - curr_offset
if not self.reader.decompressor:
length -= empty_size
self.member_info = (curr_offset, length) | python | def read_to_end(self, record=None):
""" Read remainder of the stream
If a digester is included, update it
with the data read
"""
# no current record to read
if not self.record:
return None
# already at end of this record, don't read until it is consumed
if self.member_info:
return None
curr_offset = self.offset
while True:
b = self.record.raw_stream.read(BUFF_SIZE)
if not b:
break
"""
- For compressed files, blank lines are consumed
since they are part of record length
- For uncompressed files, blank lines are read later,
and not included in the record length
"""
#if self.reader.decompressor:
self.next_line, empty_size = self._consume_blanklines()
self.offset = self.fh.tell() - self.reader.rem_length()
#if self.offset < 0:
# raise Exception('Not Gzipped Properly')
if self.next_line:
self.offset -= len(self.next_line)
length = self.offset - curr_offset
if not self.reader.decompressor:
length -= empty_size
self.member_info = (curr_offset, length) | [
"def",
"read_to_end",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"# no current record to read",
"if",
"not",
"self",
".",
"record",
":",
"return",
"None",
"# already at end of this record, don't read until it is consumed",
"if",
"self",
".",
"member_info",
":",
"return",
"None",
"curr_offset",
"=",
"self",
".",
"offset",
"while",
"True",
":",
"b",
"=",
"self",
".",
"record",
".",
"raw_stream",
".",
"read",
"(",
"BUFF_SIZE",
")",
"if",
"not",
"b",
":",
"break",
"\"\"\"\n - For compressed files, blank lines are consumed\n since they are part of record length\n - For uncompressed files, blank lines are read later,\n and not included in the record length\n \"\"\"",
"#if self.reader.decompressor:",
"self",
".",
"next_line",
",",
"empty_size",
"=",
"self",
".",
"_consume_blanklines",
"(",
")",
"self",
".",
"offset",
"=",
"self",
".",
"fh",
".",
"tell",
"(",
")",
"-",
"self",
".",
"reader",
".",
"rem_length",
"(",
")",
"#if self.offset < 0:",
"# raise Exception('Not Gzipped Properly')",
"if",
"self",
".",
"next_line",
":",
"self",
".",
"offset",
"-=",
"len",
"(",
"self",
".",
"next_line",
")",
"length",
"=",
"self",
".",
"offset",
"-",
"curr_offset",
"if",
"not",
"self",
".",
"reader",
".",
"decompressor",
":",
"length",
"-=",
"empty_size",
"self",
".",
"member_info",
"=",
"(",
"curr_offset",
",",
"length",
")"
] | Read remainder of the stream
If a digester is included, update it
with the data read | [
"Read",
"remainder",
"of",
"the",
"stream",
"If",
"a",
"digester",
"is",
"included",
"update",
"it",
"with",
"the",
"data",
"read"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L173-L215 | -1 |
||||||
251,391 | webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._next_record | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
self.known_format,
self.no_record_parse,
self.ensure_http_headers)
self.member_info = None
# Track known format for faster parsing of other records
if not self.mixed_arc_warc:
self.known_format = record.format
return record | python | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
self.known_format,
self.no_record_parse,
self.ensure_http_headers)
self.member_info = None
# Track known format for faster parsing of other records
if not self.mixed_arc_warc:
self.known_format = record.format
return record | [
"def",
"_next_record",
"(",
"self",
",",
"next_line",
")",
":",
"record",
"=",
"self",
".",
"loader",
".",
"parse_record_stream",
"(",
"self",
".",
"reader",
",",
"next_line",
",",
"self",
".",
"known_format",
",",
"self",
".",
"no_record_parse",
",",
"self",
".",
"ensure_http_headers",
")",
"self",
".",
"member_info",
"=",
"None",
"# Track known format for faster parsing of other records",
"if",
"not",
"self",
".",
"mixed_arc_warc",
":",
"self",
".",
"known_format",
"=",
"record",
".",
"format",
"return",
"record"
] | Use loader to parse the record from the reader stream
Supporting warc and arc records | [
"Use",
"loader",
"to",
"parse",
"the",
"record",
"from",
"the",
"reader",
"stream",
"Supporting",
"warc",
"and",
"arc",
"records"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L231-L247 | -1 |
||||||
251,392 | webrecorder/warcio | warcio/limitreader.py | LimitReader.wrap_stream | def wrap_stream(stream, content_length):
"""
If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered
"""
try:
content_length = int(content_length)
if content_length >= 0:
# optimize: if already a LimitStream, set limit to
# the smaller of the two limits
if isinstance(stream, LimitReader):
stream.limit = min(stream.limit, content_length)
else:
stream = LimitReader(stream, content_length)
except (ValueError, TypeError):
pass
return stream | python | def wrap_stream(stream, content_length):
"""
If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered
"""
try:
content_length = int(content_length)
if content_length >= 0:
# optimize: if already a LimitStream, set limit to
# the smaller of the two limits
if isinstance(stream, LimitReader):
stream.limit = min(stream.limit, content_length)
else:
stream = LimitReader(stream, content_length)
except (ValueError, TypeError):
pass
return stream | [
"def",
"wrap_stream",
"(",
"stream",
",",
"content_length",
")",
":",
"try",
":",
"content_length",
"=",
"int",
"(",
"content_length",
")",
"if",
"content_length",
">=",
"0",
":",
"# optimize: if already a LimitStream, set limit to",
"# the smaller of the two limits",
"if",
"isinstance",
"(",
"stream",
",",
"LimitReader",
")",
":",
"stream",
".",
"limit",
"=",
"min",
"(",
"stream",
".",
"limit",
",",
"content_length",
")",
"else",
":",
"stream",
"=",
"LimitReader",
"(",
"stream",
",",
"content_length",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"return",
"stream"
] | If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered | [
"If",
"given",
"content_length",
"is",
"an",
"int",
">",
"0",
"wrap",
"the",
"stream",
"in",
"a",
"LimitReader",
".",
"Otherwise",
"return",
"the",
"stream",
"unaltered"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/limitreader.py#L50-L68 | -1 |
||||||
251,393 | webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.replace_header | def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
if curr_name.lower() == name_lower:
self.headers[index] = (curr_name, value)
return curr_value
self.headers.append((name, value))
return None | python | def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
if curr_name.lower() == name_lower:
self.headers[index] = (curr_name, value)
return curr_value
self.headers.append((name, value))
return None | [
"def",
"replace_header",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name_lower",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"headers",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"curr_name",
",",
"curr_value",
"=",
"self",
".",
"headers",
"[",
"index",
"]",
"if",
"curr_name",
".",
"lower",
"(",
")",
"==",
"name_lower",
":",
"self",
".",
"headers",
"[",
"index",
"]",
"=",
"(",
"curr_name",
",",
"value",
")",
"return",
"curr_value",
"self",
".",
"headers",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")",
"return",
"None"
] | replace header with new value or add new header
return old header value, if any | [
"replace",
"header",
"with",
"new",
"value",
"or",
"add",
"new",
"header",
"return",
"old",
"header",
"value",
"if",
"any"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L49-L62 | -1 |
||||||
251,394 | webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.validate_statusline | def validate_statusline(self, valid_statusline):
"""
Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline
"""
code = self.get_statuscode()
try:
code = int(code)
assert(code > 0)
return True
except(ValueError, AssertionError):
self.statusline = valid_statusline
return False | python | def validate_statusline(self, valid_statusline):
"""
Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline
"""
code = self.get_statuscode()
try:
code = int(code)
assert(code > 0)
return True
except(ValueError, AssertionError):
self.statusline = valid_statusline
return False | [
"def",
"validate_statusline",
"(",
"self",
",",
"valid_statusline",
")",
":",
"code",
"=",
"self",
".",
"get_statuscode",
"(",
")",
"try",
":",
"code",
"=",
"int",
"(",
"code",
")",
"assert",
"(",
"code",
">",
"0",
")",
"return",
"True",
"except",
"(",
"ValueError",
",",
"AssertionError",
")",
":",
"self",
".",
"statusline",
"=",
"valid_statusline",
"return",
"False"
] | Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline | [
"Check",
"that",
"the",
"statusline",
"is",
"valid",
"eg",
".",
"starts",
"with",
"a",
"numeric",
"code",
".",
"If",
"not",
"replace",
"with",
"passed",
"in",
"valid_statusline"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L85-L97 | -1 |
||||||
251,395 | webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.add_range | def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
total_len)
self.statusline = '206 Partial Content'
self.replace_header('Content-Range', content_range)
self.replace_header('Content-Length', str(part_len))
self.replace_header('Accept-Ranges', 'bytes')
return self | python | def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
total_len)
self.statusline = '206 Partial Content'
self.replace_header('Content-Range', content_range)
self.replace_header('Content-Length', str(part_len))
self.replace_header('Accept-Ranges', 'bytes')
return self | [
"def",
"add_range",
"(",
"self",
",",
"start",
",",
"part_len",
",",
"total_len",
")",
":",
"content_range",
"=",
"'bytes {0}-{1}/{2}'",
".",
"format",
"(",
"start",
",",
"start",
"+",
"part_len",
"-",
"1",
",",
"total_len",
")",
"self",
".",
"statusline",
"=",
"'206 Partial Content'",
"self",
".",
"replace_header",
"(",
"'Content-Range'",
",",
"content_range",
")",
"self",
".",
"replace_header",
"(",
"'Content-Length'",
",",
"str",
"(",
"part_len",
")",
")",
"self",
".",
"replace_header",
"(",
"'Accept-Ranges'",
",",
"'bytes'",
")",
"return",
"self"
] | Add range headers indicating that this a partial response | [
"Add",
"range",
"headers",
"indicating",
"that",
"this",
"a",
"partial",
"response"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L99-L111 | -1 |
||||||
251,396 | webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeadersParser.parse | def parse(self, stream, full_statusline=None):
"""
parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab
"""
# status line w newlines intact
if full_statusline is None:
full_statusline = stream.readline()
full_statusline = self.decode_header(full_statusline)
statusline, total_read = _strip_count(full_statusline, 0)
headers = []
# at end of stream
if total_read == 0:
raise EOFError()
elif not statusline:
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol='',
total_len=total_read)
# validate only if verify is set
if self.verify:
protocol_status = self.split_prefix(statusline, self.statuslist)
if not protocol_status:
msg = 'Expected Status Line starting with {0} - Found: {1}'
msg = msg.format(self.statuslist, statusline)
raise StatusAndHeadersParserException(msg, full_statusline)
else:
protocol_status = statusline.split(' ', 1)
line, total_read = _strip_count(self.decode_header(stream.readline()), total_read)
while line:
result = line.split(':', 1)
if len(result) == 2:
name = result[0].rstrip(' \t')
value = result[1].lstrip()
else:
name = result[0]
value = None
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
# append continuation lines, if any
while next_line and next_line.startswith((' ', '\t')):
if value is not None:
value += next_line
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
if value is not None:
header = (name, value)
headers.append(header)
line = next_line
if len(protocol_status) > 1:
statusline = protocol_status[1].strip()
else:
statusline = ''
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol=protocol_status[0],
total_len=total_read) | python | def parse(self, stream, full_statusline=None):
"""
parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab
"""
# status line w newlines intact
if full_statusline is None:
full_statusline = stream.readline()
full_statusline = self.decode_header(full_statusline)
statusline, total_read = _strip_count(full_statusline, 0)
headers = []
# at end of stream
if total_read == 0:
raise EOFError()
elif not statusline:
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol='',
total_len=total_read)
# validate only if verify is set
if self.verify:
protocol_status = self.split_prefix(statusline, self.statuslist)
if not protocol_status:
msg = 'Expected Status Line starting with {0} - Found: {1}'
msg = msg.format(self.statuslist, statusline)
raise StatusAndHeadersParserException(msg, full_statusline)
else:
protocol_status = statusline.split(' ', 1)
line, total_read = _strip_count(self.decode_header(stream.readline()), total_read)
while line:
result = line.split(':', 1)
if len(result) == 2:
name = result[0].rstrip(' \t')
value = result[1].lstrip()
else:
name = result[0]
value = None
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
# append continuation lines, if any
while next_line and next_line.startswith((' ', '\t')):
if value is not None:
value += next_line
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
if value is not None:
header = (name, value)
headers.append(header)
line = next_line
if len(protocol_status) > 1:
statusline = protocol_status[1].strip()
else:
statusline = ''
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol=protocol_status[0],
total_len=total_read) | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"full_statusline",
"=",
"None",
")",
":",
"# status line w newlines intact",
"if",
"full_statusline",
"is",
"None",
":",
"full_statusline",
"=",
"stream",
".",
"readline",
"(",
")",
"full_statusline",
"=",
"self",
".",
"decode_header",
"(",
"full_statusline",
")",
"statusline",
",",
"total_read",
"=",
"_strip_count",
"(",
"full_statusline",
",",
"0",
")",
"headers",
"=",
"[",
"]",
"# at end of stream",
"if",
"total_read",
"==",
"0",
":",
"raise",
"EOFError",
"(",
")",
"elif",
"not",
"statusline",
":",
"return",
"StatusAndHeaders",
"(",
"statusline",
"=",
"statusline",
",",
"headers",
"=",
"headers",
",",
"protocol",
"=",
"''",
",",
"total_len",
"=",
"total_read",
")",
"# validate only if verify is set",
"if",
"self",
".",
"verify",
":",
"protocol_status",
"=",
"self",
".",
"split_prefix",
"(",
"statusline",
",",
"self",
".",
"statuslist",
")",
"if",
"not",
"protocol_status",
":",
"msg",
"=",
"'Expected Status Line starting with {0} - Found: {1}'",
"msg",
"=",
"msg",
".",
"format",
"(",
"self",
".",
"statuslist",
",",
"statusline",
")",
"raise",
"StatusAndHeadersParserException",
"(",
"msg",
",",
"full_statusline",
")",
"else",
":",
"protocol_status",
"=",
"statusline",
".",
"split",
"(",
"' '",
",",
"1",
")",
"line",
",",
"total_read",
"=",
"_strip_count",
"(",
"self",
".",
"decode_header",
"(",
"stream",
".",
"readline",
"(",
")",
")",
",",
"total_read",
")",
"while",
"line",
":",
"result",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"result",
")",
"==",
"2",
":",
"name",
"=",
"result",
"[",
"0",
"]",
".",
"rstrip",
"(",
"' \\t'",
")",
"value",
"=",
"result",
"[",
"1",
"]",
".",
"lstrip",
"(",
")",
"else",
":",
"name",
"=",
"result",
"[",
"0",
"]",
"value",
"=",
"None",
"next_line",
",",
"total_read",
"=",
"_strip_count",
"(",
"self",
".",
"decode_header",
"(",
"stream",
".",
"readline",
"(",
")",
")",
",",
"total_read",
")",
"# append continuation lines, if any",
"while",
"next_line",
"and",
"next_line",
".",
"startswith",
"(",
"(",
"' '",
",",
"'\\t'",
")",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"+=",
"next_line",
"next_line",
",",
"total_read",
"=",
"_strip_count",
"(",
"self",
".",
"decode_header",
"(",
"stream",
".",
"readline",
"(",
")",
")",
",",
"total_read",
")",
"if",
"value",
"is",
"not",
"None",
":",
"header",
"=",
"(",
"name",
",",
"value",
")",
"headers",
".",
"append",
"(",
"header",
")",
"line",
"=",
"next_line",
"if",
"len",
"(",
"protocol_status",
")",
">",
"1",
":",
"statusline",
"=",
"protocol_status",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"statusline",
"=",
"''",
"return",
"StatusAndHeaders",
"(",
"statusline",
"=",
"statusline",
",",
"headers",
"=",
"headers",
",",
"protocol",
"=",
"protocol_status",
"[",
"0",
"]",
",",
"total_len",
"=",
"total_read",
")"
] | parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab | [
"parse",
"stream",
"for",
"status",
"line",
"and",
"headers",
"return",
"a",
"StatusAndHeaders",
"object"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L223-L295 | -1 |
||||||
251,397 | webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeadersParser.split_prefix | def split_prefix(key, prefixs):
"""
split key string into prefix and remainder
for first matching prefix from a list
"""
key_upper = key.upper()
for prefix in prefixs:
if key_upper.startswith(prefix):
plen = len(prefix)
return (key_upper[:plen], key[plen:]) | python | def split_prefix(key, prefixs):
"""
split key string into prefix and remainder
for first matching prefix from a list
"""
key_upper = key.upper()
for prefix in prefixs:
if key_upper.startswith(prefix):
plen = len(prefix)
return (key_upper[:plen], key[plen:]) | [
"def",
"split_prefix",
"(",
"key",
",",
"prefixs",
")",
":",
"key_upper",
"=",
"key",
".",
"upper",
"(",
")",
"for",
"prefix",
"in",
"prefixs",
":",
"if",
"key_upper",
".",
"startswith",
"(",
"prefix",
")",
":",
"plen",
"=",
"len",
"(",
"prefix",
")",
"return",
"(",
"key_upper",
"[",
":",
"plen",
"]",
",",
"key",
"[",
"plen",
":",
"]",
")"
] | split key string into prefix and remainder
for first matching prefix from a list | [
"split",
"key",
"string",
"into",
"prefix",
"and",
"remainder",
"for",
"first",
"matching",
"prefix",
"from",
"a",
"list"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L298-L307 | -1 |
||||||
251,398 | nickjj/ansigenome | ansigenome/config.py | Config.ask_questions | def ask_questions(self):
"""
Obtain config settings from the user.
"""
out_config = {}
for key in c.CONFIG_QUESTIONS:
section = key[1]
print
for question in section:
answer = utils.ask(question[1], question[2])
out_config["{0}_{1}".format(key[0], question[0])] = answer
for key in c.CONFIG_MULTIPLE_CHOICE_QUESTIONS:
section = key[1]
print
# keep going until we get what we want
while True:
input = utils.ask(section[1], "")
if (input.isdigit() and
int(input) > 0 and
int(input) <= section[0]):
answer = input
break
print
# store the answer as 1 less than it is, we're dealing with
# a list to select the number which is 0 indexed
answer = int(input) - 1
if key[0] == "license":
out_config["license_type"] = c.LICENSE_TYPES[answer][0]
out_config["license_url"] = c.LICENSE_TYPES[answer][1]
# merge in defaults without asking questions
merged_config = dict(c.CONFIG_DEFAULTS.items() + out_config.items())
return merged_config | python | def ask_questions(self):
"""
Obtain config settings from the user.
"""
out_config = {}
for key in c.CONFIG_QUESTIONS:
section = key[1]
print
for question in section:
answer = utils.ask(question[1], question[2])
out_config["{0}_{1}".format(key[0], question[0])] = answer
for key in c.CONFIG_MULTIPLE_CHOICE_QUESTIONS:
section = key[1]
print
# keep going until we get what we want
while True:
input = utils.ask(section[1], "")
if (input.isdigit() and
int(input) > 0 and
int(input) <= section[0]):
answer = input
break
print
# store the answer as 1 less than it is, we're dealing with
# a list to select the number which is 0 indexed
answer = int(input) - 1
if key[0] == "license":
out_config["license_type"] = c.LICENSE_TYPES[answer][0]
out_config["license_url"] = c.LICENSE_TYPES[answer][1]
# merge in defaults without asking questions
merged_config = dict(c.CONFIG_DEFAULTS.items() + out_config.items())
return merged_config | [
"def",
"ask_questions",
"(",
"self",
")",
":",
"out_config",
"=",
"{",
"}",
"for",
"key",
"in",
"c",
".",
"CONFIG_QUESTIONS",
":",
"section",
"=",
"key",
"[",
"1",
"]",
"print",
"for",
"question",
"in",
"section",
":",
"answer",
"=",
"utils",
".",
"ask",
"(",
"question",
"[",
"1",
"]",
",",
"question",
"[",
"2",
"]",
")",
"out_config",
"[",
"\"{0}_{1}\"",
".",
"format",
"(",
"key",
"[",
"0",
"]",
",",
"question",
"[",
"0",
"]",
")",
"]",
"=",
"answer",
"for",
"key",
"in",
"c",
".",
"CONFIG_MULTIPLE_CHOICE_QUESTIONS",
":",
"section",
"=",
"key",
"[",
"1",
"]",
"print",
"# keep going until we get what we want",
"while",
"True",
":",
"input",
"=",
"utils",
".",
"ask",
"(",
"section",
"[",
"1",
"]",
",",
"\"\"",
")",
"if",
"(",
"input",
".",
"isdigit",
"(",
")",
"and",
"int",
"(",
"input",
")",
">",
"0",
"and",
"int",
"(",
"input",
")",
"<=",
"section",
"[",
"0",
"]",
")",
":",
"answer",
"=",
"input",
"break",
"print",
"# store the answer as 1 less than it is, we're dealing with",
"# a list to select the number which is 0 indexed",
"answer",
"=",
"int",
"(",
"input",
")",
"-",
"1",
"if",
"key",
"[",
"0",
"]",
"==",
"\"license\"",
":",
"out_config",
"[",
"\"license_type\"",
"]",
"=",
"c",
".",
"LICENSE_TYPES",
"[",
"answer",
"]",
"[",
"0",
"]",
"out_config",
"[",
"\"license_url\"",
"]",
"=",
"c",
".",
"LICENSE_TYPES",
"[",
"answer",
"]",
"[",
"1",
"]",
"# merge in defaults without asking questions",
"merged_config",
"=",
"dict",
"(",
"c",
".",
"CONFIG_DEFAULTS",
".",
"items",
"(",
")",
"+",
"out_config",
".",
"items",
"(",
")",
")",
"return",
"merged_config"
] | Obtain config settings from the user. | [
"Obtain",
"config",
"settings",
"from",
"the",
"user",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/config.py#L45-L83 | -1 |
||||||
251,399 | nickjj/ansigenome | ansigenome/ui.py | log | def log(color, *args):
"""
Print a message with a specific color.
"""
if color in c.LOG_COLOR.keys():
out_color = c.LOG_COLOR[color]
else:
out_color = color
for arg in args:
print clr.stringc(arg, out_color) | python | def log(color, *args):
"""
Print a message with a specific color.
"""
if color in c.LOG_COLOR.keys():
out_color = c.LOG_COLOR[color]
else:
out_color = color
for arg in args:
print clr.stringc(arg, out_color) | [
"def",
"log",
"(",
"color",
",",
"*",
"args",
")",
":",
"if",
"color",
"in",
"c",
".",
"LOG_COLOR",
".",
"keys",
"(",
")",
":",
"out_color",
"=",
"c",
".",
"LOG_COLOR",
"[",
"color",
"]",
"else",
":",
"out_color",
"=",
"color",
"for",
"arg",
"in",
"args",
":",
"print",
"clr",
".",
"stringc",
"(",
"arg",
",",
"out_color",
")"
] | Print a message with a specific color. | [
"Print",
"a",
"message",
"with",
"a",
"specific",
"color",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L5-L15 | -1 |