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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.new_embed_ui | def new_embed_ui(self):
"""Create the embed UI object and save it to self"""
self.logger.debug("Creating new embed ui object")
# Initial queue display
queue_display = []
for i in range(self.queue_display):
queue_display.append("{}. ---\n".format(str(i + 1)))
# Initial datapacks
datapacks = [
("Now playing", "---", False),
("Author", "---", True),
("Source", "---", True),
("Time", "```http\n" + _timebar.make_timebar() + "\n```", False),
("Queue", "```md\n{}\n```".format(''.join(queue_display)), False),
("Songs left in queue", "---", True),
("Volume", "{}%".format(self.volume), True),
("Status", "```---```", False)
]
# Create embed UI object
self.embed = ui_embed_tools.UI(
self.mchannel,
"",
"",
modulename=_data.modulename,
colour=_data.modulecolor,
datapacks=datapacks
)
# Add handlers to update gui
noformatter = logging.Formatter("{message}", style="{")
timeformatter = logging.Formatter("```http\n{message}\n```", style="{")
mdformatter = logging.Formatter("```md\n{message}\n```", style="{")
statusformatter = logging.Formatter("```__{levelname}__\n{message}\n```", style="{")
volumeformatter = logging.Formatter("{message}%", style="{")
nowplayinghandler = EmbedLogHandler(self, self.embed, 0)
nowplayinghandler.setFormatter(noformatter)
nowplayingauthorhandler = EmbedLogHandler(self, self.embed, 1)
nowplayingauthorhandler.setFormatter(noformatter)
nowplayingsourcehandler = EmbedLogHandler(self, self.embed, 2)
nowplayingsourcehandler.setFormatter(noformatter)
timehandler = EmbedLogHandler(self, self.embed, 3)
timehandler.setFormatter(timeformatter)
queuehandler = EmbedLogHandler(self, self.embed, 4)
queuehandler.setFormatter(mdformatter)
queuelenhandler = EmbedLogHandler(self, self.embed, 5)
queuelenhandler.setFormatter(noformatter)
volumehandler = EmbedLogHandler(self, self.embed, 6)
volumehandler.setFormatter(volumeformatter)
statushandler = EmbedLogHandler(self, self.embed, 7)
statushandler.setFormatter(statusformatter)
self.nowplayinglog.addHandler(nowplayinghandler)
self.nowplayingauthorlog.addHandler(nowplayingauthorhandler)
self.nowplayingsourcelog.addHandler(nowplayingsourcehandler)
self.timelog.addHandler(timehandler)
self.queuelog.addHandler(queuehandler)
self.queuelenlog.addHandler(queuelenhandler)
self.volumelog.addHandler(volumehandler)
self.statuslog.addHandler(statushandler) | python | def new_embed_ui(self):
"""Create the embed UI object and save it to self"""
self.logger.debug("Creating new embed ui object")
# Initial queue display
queue_display = []
for i in range(self.queue_display):
queue_display.append("{}. ---\n".format(str(i + 1)))
# Initial datapacks
datapacks = [
("Now playing", "---", False),
("Author", "---", True),
("Source", "---", True),
("Time", "```http\n" + _timebar.make_timebar() + "\n```", False),
("Queue", "```md\n{}\n```".format(''.join(queue_display)), False),
("Songs left in queue", "---", True),
("Volume", "{}%".format(self.volume), True),
("Status", "```---```", False)
]
# Create embed UI object
self.embed = ui_embed_tools.UI(
self.mchannel,
"",
"",
modulename=_data.modulename,
colour=_data.modulecolor,
datapacks=datapacks
)
# Add handlers to update gui
noformatter = logging.Formatter("{message}", style="{")
timeformatter = logging.Formatter("```http\n{message}\n```", style="{")
mdformatter = logging.Formatter("```md\n{message}\n```", style="{")
statusformatter = logging.Formatter("```__{levelname}__\n{message}\n```", style="{")
volumeformatter = logging.Formatter("{message}%", style="{")
nowplayinghandler = EmbedLogHandler(self, self.embed, 0)
nowplayinghandler.setFormatter(noformatter)
nowplayingauthorhandler = EmbedLogHandler(self, self.embed, 1)
nowplayingauthorhandler.setFormatter(noformatter)
nowplayingsourcehandler = EmbedLogHandler(self, self.embed, 2)
nowplayingsourcehandler.setFormatter(noformatter)
timehandler = EmbedLogHandler(self, self.embed, 3)
timehandler.setFormatter(timeformatter)
queuehandler = EmbedLogHandler(self, self.embed, 4)
queuehandler.setFormatter(mdformatter)
queuelenhandler = EmbedLogHandler(self, self.embed, 5)
queuelenhandler.setFormatter(noformatter)
volumehandler = EmbedLogHandler(self, self.embed, 6)
volumehandler.setFormatter(volumeformatter)
statushandler = EmbedLogHandler(self, self.embed, 7)
statushandler.setFormatter(statusformatter)
self.nowplayinglog.addHandler(nowplayinghandler)
self.nowplayingauthorlog.addHandler(nowplayingauthorhandler)
self.nowplayingsourcelog.addHandler(nowplayingsourcehandler)
self.timelog.addHandler(timehandler)
self.queuelog.addHandler(queuehandler)
self.queuelenlog.addHandler(queuelenhandler)
self.volumelog.addHandler(volumehandler)
self.statuslog.addHandler(statushandler) | [
"def",
"new_embed_ui",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Creating new embed ui object\"",
")",
"# Initial queue display",
"queue_display",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"queue_display",
")",
":",
... | Create the embed UI object and save it to self | [
"Create",
"the",
"embed",
"UI",
"object",
"and",
"save",
"it",
"to",
"self"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L732-L795 | train | 41,300 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.enqueue | async def enqueue(self, query, queue_index=None, stop_current=False, shuffle=False):
"""
Queues songs based on either a YouTube search or a link
Args:
query (str): Either a search term or a link
queue_index (str): The queue index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs
"""
if query is None or query == "":
return
self.statuslog.info("Parsing {}".format(query))
self.logger.debug("Enqueueing from query")
indexnum = None
if queue_index is not None:
try:
indexnum = int(queue_index) - 1
except TypeError:
self.statuslog.error("Play index argument must be a number")
return
except ValueError:
self.statuslog.error("Play index argument must be a number")
return
if not self.vready:
self.parse_query(query, indexnum, stop_current, shuffle)
else:
parse_thread = threading.Thread(
target=self.parse_query,
args=[query, indexnum, stop_current, shuffle])
# Run threads
parse_thread.start() | python | async def enqueue(self, query, queue_index=None, stop_current=False, shuffle=False):
"""
Queues songs based on either a YouTube search or a link
Args:
query (str): Either a search term or a link
queue_index (str): The queue index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs
"""
if query is None or query == "":
return
self.statuslog.info("Parsing {}".format(query))
self.logger.debug("Enqueueing from query")
indexnum = None
if queue_index is not None:
try:
indexnum = int(queue_index) - 1
except TypeError:
self.statuslog.error("Play index argument must be a number")
return
except ValueError:
self.statuslog.error("Play index argument must be a number")
return
if not self.vready:
self.parse_query(query, indexnum, stop_current, shuffle)
else:
parse_thread = threading.Thread(
target=self.parse_query,
args=[query, indexnum, stop_current, shuffle])
# Run threads
parse_thread.start() | [
"async",
"def",
"enqueue",
"(",
"self",
",",
"query",
",",
"queue_index",
"=",
"None",
",",
"stop_current",
"=",
"False",
",",
"shuffle",
"=",
"False",
")",
":",
"if",
"query",
"is",
"None",
"or",
"query",
"==",
"\"\"",
":",
"return",
"self",
".",
"s... | Queues songs based on either a YouTube search or a link
Args:
query (str): Either a search term or a link
queue_index (str): The queue index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs | [
"Queues",
"songs",
"based",
"on",
"either",
"a",
"YouTube",
"search",
"or",
"a",
"link"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L810-L845 | train | 41,301 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.parse_query | def parse_query(self, query, index, stop_current, shuffle):
"""
Parses a query and adds it to the queue
Args:
query (str): Either a search term or a link
index (int): The index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs
"""
if index is not None and len(self.queue) > 0:
if index < 0 or index >= len(self.queue):
if len(self.queue) == 1:
self.statuslog.error("Play index must be 1 (1 song in queue)")
return
else:
self.statuslog.error("Play index must be between 1 and {}".format(len(self.queue)))
return
try:
yt_videos = api_music.parse_query(query, self.statuslog)
if shuffle:
random.shuffle(yt_videos)
if len(yt_videos) == 0:
self.statuslog.error("No results for: {}".format(query))
return
if index is None:
self.queue = self.queue + yt_videos
else:
if len(self.queue) > 0:
self.queue = self.queue[:index] + yt_videos + self.queue[index:]
else:
self.queue = yt_videos
self.update_queue()
if stop_current:
if self.streamer:
self.streamer.stop()
except Exception as e:
logger.exception(e) | python | def parse_query(self, query, index, stop_current, shuffle):
"""
Parses a query and adds it to the queue
Args:
query (str): Either a search term or a link
index (int): The index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs
"""
if index is not None and len(self.queue) > 0:
if index < 0 or index >= len(self.queue):
if len(self.queue) == 1:
self.statuslog.error("Play index must be 1 (1 song in queue)")
return
else:
self.statuslog.error("Play index must be between 1 and {}".format(len(self.queue)))
return
try:
yt_videos = api_music.parse_query(query, self.statuslog)
if shuffle:
random.shuffle(yt_videos)
if len(yt_videos) == 0:
self.statuslog.error("No results for: {}".format(query))
return
if index is None:
self.queue = self.queue + yt_videos
else:
if len(self.queue) > 0:
self.queue = self.queue[:index] + yt_videos + self.queue[index:]
else:
self.queue = yt_videos
self.update_queue()
if stop_current:
if self.streamer:
self.streamer.stop()
except Exception as e:
logger.exception(e) | [
"def",
"parse_query",
"(",
"self",
",",
"query",
",",
"index",
",",
"stop_current",
",",
"shuffle",
")",
":",
"if",
"index",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"if",
"index",
"<",
"0",
"or",
"index",
... | Parses a query and adds it to the queue
Args:
query (str): Either a search term or a link
index (int): The index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs | [
"Parses",
"a",
"query",
"and",
"adds",
"it",
"to",
"the",
"queue"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L847-L890 | train | 41,302 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.update_queue | def update_queue(self):
"""Updates the queue in the music player """
self.logger.debug("Updating queue display")
queue_display = []
for i in range(self.queue_display):
try:
if len(self.queue[i][1]) > 40:
songname = self.queue[i][1][:37] + "..."
else:
songname = self.queue[i][1]
except IndexError:
songname = "---"
queue_display.append("{}. {}\n".format(str(i + 1), songname))
self.queuelog.debug(''.join(queue_display))
self.queuelenlog.debug(str(len(self.queue))) | python | def update_queue(self):
"""Updates the queue in the music player """
self.logger.debug("Updating queue display")
queue_display = []
for i in range(self.queue_display):
try:
if len(self.queue[i][1]) > 40:
songname = self.queue[i][1][:37] + "..."
else:
songname = self.queue[i][1]
except IndexError:
songname = "---"
queue_display.append("{}. {}\n".format(str(i + 1), songname))
self.queuelog.debug(''.join(queue_display))
self.queuelenlog.debug(str(len(self.queue))) | [
"def",
"update_queue",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Updating queue display\"",
")",
"queue_display",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"queue_display",
")",
":",
"try",
":",
"if",
"len",
... | Updates the queue in the music player | [
"Updates",
"the",
"queue",
"in",
"the",
"music",
"player"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L892-L909 | train | 41,303 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.set_topic | async def set_topic(self, topic):
"""Sets the topic for the topic channel"""
self.topic = topic
try:
if self.topicchannel:
await client.edit_channel(self.topicchannel, topic=topic)
except Exception as e:
logger.exception(e) | python | async def set_topic(self, topic):
"""Sets the topic for the topic channel"""
self.topic = topic
try:
if self.topicchannel:
await client.edit_channel(self.topicchannel, topic=topic)
except Exception as e:
logger.exception(e) | [
"async",
"def",
"set_topic",
"(",
"self",
",",
"topic",
")",
":",
"self",
".",
"topic",
"=",
"topic",
"try",
":",
"if",
"self",
".",
"topicchannel",
":",
"await",
"client",
".",
"edit_channel",
"(",
"self",
".",
"topicchannel",
",",
"topic",
"=",
"topi... | Sets the topic for the topic channel | [
"Sets",
"the",
"topic",
"for",
"the",
"topic",
"channel"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L911-L918 | train | 41,304 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.clear_cache | def clear_cache(self):
"""Removes all files from the songcache dir"""
self.logger.debug("Clearing cache")
if os.path.isdir(self.songcache_dir):
for filename in os.listdir(self.songcache_dir):
file_path = os.path.join(self.songcache_dir, filename)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except PermissionError:
pass
except Exception as e:
logger.exception(e)
self.logger.debug("Cache cleared") | python | def clear_cache(self):
"""Removes all files from the songcache dir"""
self.logger.debug("Clearing cache")
if os.path.isdir(self.songcache_dir):
for filename in os.listdir(self.songcache_dir):
file_path = os.path.join(self.songcache_dir, filename)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except PermissionError:
pass
except Exception as e:
logger.exception(e)
self.logger.debug("Cache cleared") | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Clearing cache\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"songcache_dir",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
... | Removes all files from the songcache dir | [
"Removes",
"all",
"files",
"from",
"the",
"songcache",
"dir"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L945-L958 | train | 41,305 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.move_next_cache | def move_next_cache(self):
"""Moves files in the 'next' cache dir to the root"""
if not os.path.isdir(self.songcache_next_dir):
return
logger.debug("Moving next cache")
files = os.listdir(self.songcache_next_dir)
for f in files:
try:
os.rename("{}/{}".format(self.songcache_next_dir, f), "{}/{}".format(self.songcache_dir, f))
except PermissionError:
pass
except Exception as e:
logger.exception(e)
logger.debug("Next cache moved") | python | def move_next_cache(self):
"""Moves files in the 'next' cache dir to the root"""
if not os.path.isdir(self.songcache_next_dir):
return
logger.debug("Moving next cache")
files = os.listdir(self.songcache_next_dir)
for f in files:
try:
os.rename("{}/{}".format(self.songcache_next_dir, f), "{}/{}".format(self.songcache_dir, f))
except PermissionError:
pass
except Exception as e:
logger.exception(e)
logger.debug("Next cache moved") | [
"def",
"move_next_cache",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"songcache_next_dir",
")",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Moving next cache\"",
")",
"files",
"=",
"os",
".",
"listdir",
"(",... | Moves files in the 'next' cache dir to the root | [
"Moves",
"files",
"in",
"the",
"next",
"cache",
"dir",
"to",
"the",
"root"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L960-L974 | train | 41,306 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.ytdl_progress_hook | def ytdl_progress_hook(self, d):
"""Called when youtube-dl updates progress"""
if d['status'] == 'downloading':
self.play_empty()
if "elapsed" in d:
if d["elapsed"] > self.current_download_elapsed + 4:
self.current_download_elapsed = d["elapsed"]
current_download = 0
current_download_total = 0
current_download_eta = 0
if "total_bytes" in d and d["total_bytes"] > 0:
current_download_total = d["total_bytes"]
elif "total_bytes_estimate" in d and d["total_bytes_estimate"] > 0:
current_download_total = d["total_bytes_estimate"]
if "downloaded_bytes" in d and d["downloaded_bytes"] > 0:
current_download = d["downloaded_bytes"]
if "eta" in d and d["eta"] > 0:
current_download_eta = d["eta"]
if current_download_total > 0:
percent = round(100 * (current_download / current_download_total))
if percent > 100:
percent = 100
elif percent < 0:
percent = 0
seconds = str(round(current_download_eta)) if current_download_eta > 0 else ""
eta = " ({} {} remaining)".format(seconds, "seconds" if seconds != 1 else "second")
downloading = "Downloading song: {}%{}".format(percent, eta)
if self.prev_time != downloading:
self.timelog.debug(downloading)
self.prev_time = downloading
if d['status'] == 'error':
self.statuslog.error("Error downloading song")
elif d['status'] == 'finished':
self.statuslog.info("Downloaded song")
downloading = "Downloading song: {}%".format(100)
if self.prev_time != downloading:
self.timelog.debug(downloading)
self.prev_time = downloading
if "elapsed" in d:
download_time = "{} {}".format(d["elapsed"] if d["elapsed"] > 0 else "<1",
"seconds" if d["elapsed"] != 1 else "second")
self.logger.debug("Downloaded song in {}".format(download_time))
# Create an FFmpeg player
future = asyncio.run_coroutine_threadsafe(self.create_ffmpeg_player(d['filename']), client.loop)
try:
future.result()
except Exception as e:
logger.exception(e)
return | python | def ytdl_progress_hook(self, d):
"""Called when youtube-dl updates progress"""
if d['status'] == 'downloading':
self.play_empty()
if "elapsed" in d:
if d["elapsed"] > self.current_download_elapsed + 4:
self.current_download_elapsed = d["elapsed"]
current_download = 0
current_download_total = 0
current_download_eta = 0
if "total_bytes" in d and d["total_bytes"] > 0:
current_download_total = d["total_bytes"]
elif "total_bytes_estimate" in d and d["total_bytes_estimate"] > 0:
current_download_total = d["total_bytes_estimate"]
if "downloaded_bytes" in d and d["downloaded_bytes"] > 0:
current_download = d["downloaded_bytes"]
if "eta" in d and d["eta"] > 0:
current_download_eta = d["eta"]
if current_download_total > 0:
percent = round(100 * (current_download / current_download_total))
if percent > 100:
percent = 100
elif percent < 0:
percent = 0
seconds = str(round(current_download_eta)) if current_download_eta > 0 else ""
eta = " ({} {} remaining)".format(seconds, "seconds" if seconds != 1 else "second")
downloading = "Downloading song: {}%{}".format(percent, eta)
if self.prev_time != downloading:
self.timelog.debug(downloading)
self.prev_time = downloading
if d['status'] == 'error':
self.statuslog.error("Error downloading song")
elif d['status'] == 'finished':
self.statuslog.info("Downloaded song")
downloading = "Downloading song: {}%".format(100)
if self.prev_time != downloading:
self.timelog.debug(downloading)
self.prev_time = downloading
if "elapsed" in d:
download_time = "{} {}".format(d["elapsed"] if d["elapsed"] > 0 else "<1",
"seconds" if d["elapsed"] != 1 else "second")
self.logger.debug("Downloaded song in {}".format(download_time))
# Create an FFmpeg player
future = asyncio.run_coroutine_threadsafe(self.create_ffmpeg_player(d['filename']), client.loop)
try:
future.result()
except Exception as e:
logger.exception(e)
return | [
"def",
"ytdl_progress_hook",
"(",
"self",
",",
"d",
")",
":",
"if",
"d",
"[",
"'status'",
"]",
"==",
"'downloading'",
":",
"self",
".",
"play_empty",
"(",
")",
"if",
"\"elapsed\"",
"in",
"d",
":",
"if",
"d",
"[",
"\"elapsed\"",
"]",
">",
"self",
".",... | Called when youtube-dl updates progress | [
"Called",
"when",
"youtube",
"-",
"dl",
"updates",
"progress"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L976-L1031 | train | 41,307 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.play_empty | def play_empty(self):
"""Play blank audio to let Discord know we're still here"""
if self.vclient:
if self.streamer:
self.streamer.volume = 0
self.vclient.play_audio("\n".encode(), encode=False) | python | def play_empty(self):
"""Play blank audio to let Discord know we're still here"""
if self.vclient:
if self.streamer:
self.streamer.volume = 0
self.vclient.play_audio("\n".encode(), encode=False) | [
"def",
"play_empty",
"(",
"self",
")",
":",
"if",
"self",
".",
"vclient",
":",
"if",
"self",
".",
"streamer",
":",
"self",
".",
"streamer",
".",
"volume",
"=",
"0",
"self",
".",
"vclient",
".",
"play_audio",
"(",
"\"\\n\"",
".",
"encode",
"(",
")",
... | Play blank audio to let Discord know we're still here | [
"Play",
"blank",
"audio",
"to",
"let",
"Discord",
"know",
"we",
"re",
"still",
"here"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1033-L1038 | train | 41,308 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.download_next_song | def download_next_song(self, song):
"""Downloads the next song and starts playing it"""
dl_ydl_opts = dict(ydl_opts)
dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook]
dl_ydl_opts["outtmpl"] = self.output_format
# Move the songs from the next cache to the current cache
self.move_next_cache()
self.state = 'ready'
self.play_empty()
# Download the file and create the stream
with youtube_dl.YoutubeDL(dl_ydl_opts) as ydl:
try:
ydl.download([song])
except DownloadStreamException:
# This is a livestream, use the appropriate player
future = asyncio.run_coroutine_threadsafe(self.create_stream_player(song, dl_ydl_opts), client.loop)
try:
future.result()
except Exception as e:
logger.exception(e)
self.vafter_ts()
return
except PermissionError:
# File is still in use, it'll get cleared next time
pass
except youtube_dl.utils.DownloadError as e:
self.logger.exception(e)
self.statuslog.error(e)
self.vafter_ts()
return
except Exception as e:
self.logger.exception(e)
self.vafter_ts()
return | python | def download_next_song(self, song):
"""Downloads the next song and starts playing it"""
dl_ydl_opts = dict(ydl_opts)
dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook]
dl_ydl_opts["outtmpl"] = self.output_format
# Move the songs from the next cache to the current cache
self.move_next_cache()
self.state = 'ready'
self.play_empty()
# Download the file and create the stream
with youtube_dl.YoutubeDL(dl_ydl_opts) as ydl:
try:
ydl.download([song])
except DownloadStreamException:
# This is a livestream, use the appropriate player
future = asyncio.run_coroutine_threadsafe(self.create_stream_player(song, dl_ydl_opts), client.loop)
try:
future.result()
except Exception as e:
logger.exception(e)
self.vafter_ts()
return
except PermissionError:
# File is still in use, it'll get cleared next time
pass
except youtube_dl.utils.DownloadError as e:
self.logger.exception(e)
self.statuslog.error(e)
self.vafter_ts()
return
except Exception as e:
self.logger.exception(e)
self.vafter_ts()
return | [
"def",
"download_next_song",
"(",
"self",
",",
"song",
")",
":",
"dl_ydl_opts",
"=",
"dict",
"(",
"ydl_opts",
")",
"dl_ydl_opts",
"[",
"\"progress_hooks\"",
"]",
"=",
"[",
"self",
".",
"ytdl_progress_hook",
"]",
"dl_ydl_opts",
"[",
"\"outtmpl\"",
"]",
"=",
"... | Downloads the next song and starts playing it | [
"Downloads",
"the",
"next",
"song",
"and",
"starts",
"playing",
"it"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1040-L1076 | train | 41,309 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.download_next_song_cache | def download_next_song_cache(self):
"""Downloads the next song in the queue to the cache"""
if len(self.queue) == 0:
return
cache_ydl_opts = dict(ydl_opts)
cache_ydl_opts["outtmpl"] = self.output_format_next
with youtube_dl.YoutubeDL(cache_ydl_opts) as ydl:
try:
url = self.queue[0][0]
ydl.download([url])
except:
pass | python | def download_next_song_cache(self):
"""Downloads the next song in the queue to the cache"""
if len(self.queue) == 0:
return
cache_ydl_opts = dict(ydl_opts)
cache_ydl_opts["outtmpl"] = self.output_format_next
with youtube_dl.YoutubeDL(cache_ydl_opts) as ydl:
try:
url = self.queue[0][0]
ydl.download([url])
except:
pass | [
"def",
"download_next_song_cache",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"queue",
")",
"==",
"0",
":",
"return",
"cache_ydl_opts",
"=",
"dict",
"(",
"ydl_opts",
")",
"cache_ydl_opts",
"[",
"\"outtmpl\"",
"]",
"=",
"self",
".",
"output_forma... | Downloads the next song in the queue to the cache | [
"Downloads",
"the",
"next",
"song",
"in",
"the",
"queue",
"to",
"the",
"cache"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1078-L1091 | train | 41,310 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.create_ffmpeg_player | async def create_ffmpeg_player(self, filepath):
"""Creates a streamer that plays from a file"""
self.current_download_elapsed = 0
self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts)
self.state = "ready"
await self.setup_streamer()
try:
# Read from the info json
info_filename = "{}.info.json".format(filepath)
with open(info_filename, 'r') as file:
info = json.load(file)
self.nowplayinglog.debug(info["title"])
self.is_live = False
if "duration" in info and info["duration"] is not None:
self.current_duration = info["duration"]
else:
self.current_duration = 0
if "uploader" in info:
self.nowplayingauthorlog.info(info["uploader"])
else:
self.nowplayingauthorlog.info("Unknown")
self.nowplayingsourcelog.info(api_music.parse_source(info))
play_state = "Streaming" if self.is_live else "Playing"
await self.set_topic("{} {}".format(play_state, info["title"]))
self.statuslog.debug(play_state)
except Exception as e:
logger.exception(e) | python | async def create_ffmpeg_player(self, filepath):
"""Creates a streamer that plays from a file"""
self.current_download_elapsed = 0
self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts)
self.state = "ready"
await self.setup_streamer()
try:
# Read from the info json
info_filename = "{}.info.json".format(filepath)
with open(info_filename, 'r') as file:
info = json.load(file)
self.nowplayinglog.debug(info["title"])
self.is_live = False
if "duration" in info and info["duration"] is not None:
self.current_duration = info["duration"]
else:
self.current_duration = 0
if "uploader" in info:
self.nowplayingauthorlog.info(info["uploader"])
else:
self.nowplayingauthorlog.info("Unknown")
self.nowplayingsourcelog.info(api_music.parse_source(info))
play_state = "Streaming" if self.is_live else "Playing"
await self.set_topic("{} {}".format(play_state, info["title"]))
self.statuslog.debug(play_state)
except Exception as e:
logger.exception(e) | [
"async",
"def",
"create_ffmpeg_player",
"(",
"self",
",",
"filepath",
")",
":",
"self",
".",
"current_download_elapsed",
"=",
"0",
"self",
".",
"streamer",
"=",
"self",
".",
"vclient",
".",
"create_ffmpeg_player",
"(",
"filepath",
",",
"after",
"=",
"self",
... | Creates a streamer that plays from a file | [
"Creates",
"a",
"streamer",
"that",
"plays",
"from",
"a",
"file"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1093-L1126 | train | 41,311 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.create_stream_player | async def create_stream_player(self, url, opts=ydl_opts):
"""Creates a streamer that plays from a URL"""
self.current_download_elapsed = 0
self.streamer = await self.vclient.create_ytdl_player(url, ytdl_options=opts, after=self.vafter_ts)
self.state = "ready"
await self.setup_streamer()
self.nowplayinglog.debug(self.streamer.title)
self.nowplayingauthorlog.debug(self.streamer.uploader if self.streamer.uploader is not None else "Unknown")
self.current_duration = 0
self.is_live = True
info = self.streamer.yt.extract_info(url, download=False)
self.nowplayingsourcelog.info(api_music.parse_source(info))
play_state = "Streaming" if self.is_live else "Playing"
await self.set_topic("{} {}".format(play_state, self.streamer.title))
self.statuslog.debug(play_state) | python | async def create_stream_player(self, url, opts=ydl_opts):
"""Creates a streamer that plays from a URL"""
self.current_download_elapsed = 0
self.streamer = await self.vclient.create_ytdl_player(url, ytdl_options=opts, after=self.vafter_ts)
self.state = "ready"
await self.setup_streamer()
self.nowplayinglog.debug(self.streamer.title)
self.nowplayingauthorlog.debug(self.streamer.uploader if self.streamer.uploader is not None else "Unknown")
self.current_duration = 0
self.is_live = True
info = self.streamer.yt.extract_info(url, download=False)
self.nowplayingsourcelog.info(api_music.parse_source(info))
play_state = "Streaming" if self.is_live else "Playing"
await self.set_topic("{} {}".format(play_state, self.streamer.title))
self.statuslog.debug(play_state) | [
"async",
"def",
"create_stream_player",
"(",
"self",
",",
"url",
",",
"opts",
"=",
"ydl_opts",
")",
":",
"self",
".",
"current_download_elapsed",
"=",
"0",
"self",
".",
"streamer",
"=",
"await",
"self",
".",
"vclient",
".",
"create_ytdl_player",
"(",
"url",
... | Creates a streamer that plays from a URL | [
"Creates",
"a",
"streamer",
"that",
"plays",
"from",
"a",
"URL"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1128-L1147 | train | 41,312 |
ModisWorks/modis | modis/discord_modis/modules/music/_musicplayer.py | MusicPlayer.setup_streamer | async def setup_streamer(self):
"""Sets up basic defaults for the streamer"""
self.streamer.volume = self.volume / 100
self.streamer.start()
self.pause_time = None
self.vclient_starttime = self.vclient.loop.time()
# Cache next song
self.logger.debug("Caching next song")
dl_thread = threading.Thread(target=self.download_next_song_cache)
dl_thread.start() | python | async def setup_streamer(self):
"""Sets up basic defaults for the streamer"""
self.streamer.volume = self.volume / 100
self.streamer.start()
self.pause_time = None
self.vclient_starttime = self.vclient.loop.time()
# Cache next song
self.logger.debug("Caching next song")
dl_thread = threading.Thread(target=self.download_next_song_cache)
dl_thread.start() | [
"async",
"def",
"setup_streamer",
"(",
"self",
")",
":",
"self",
".",
"streamer",
".",
"volume",
"=",
"self",
".",
"volume",
"/",
"100",
"self",
".",
"streamer",
".",
"start",
"(",
")",
"self",
".",
"pause_time",
"=",
"None",
"self",
".",
"vclient_star... | Sets up basic defaults for the streamer | [
"Sets",
"up",
"basic",
"defaults",
"for",
"the",
"streamer"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L1149-L1160 | train | 41,313 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | build_yt_api | def build_yt_api():
"""Build the YouTube API for future use"""
data = datatools.get_data()
if "google_api_key" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'google_api_key'")
logger.info("Please add your Google API key with name 'google_api_key' "
"in data.json to use YouTube features of the music module")
return False
logger.debug("Building YouTube discovery API")
ytdevkey = data["discord"]["keys"]["google_api_key"]
try:
global ytdiscoveryapi
ytdiscoveryapi = googleapiclient.discovery.build("youtube", "v3", developerKey=ytdevkey)
logger.debug("YouTube API build successful")
return True
except Exception as e:
logger.exception(e)
logger.warning("HTTP error connecting to YouTube API, YouTube won't be available")
return False | python | def build_yt_api():
"""Build the YouTube API for future use"""
data = datatools.get_data()
if "google_api_key" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'google_api_key'")
logger.info("Please add your Google API key with name 'google_api_key' "
"in data.json to use YouTube features of the music module")
return False
logger.debug("Building YouTube discovery API")
ytdevkey = data["discord"]["keys"]["google_api_key"]
try:
global ytdiscoveryapi
ytdiscoveryapi = googleapiclient.discovery.build("youtube", "v3", developerKey=ytdevkey)
logger.debug("YouTube API build successful")
return True
except Exception as e:
logger.exception(e)
logger.warning("HTTP error connecting to YouTube API, YouTube won't be available")
return False | [
"def",
"build_yt_api",
"(",
")",
":",
"data",
"=",
"datatools",
".",
"get_data",
"(",
")",
"if",
"\"google_api_key\"",
"not",
"in",
"data",
"[",
"\"discord\"",
"]",
"[",
"\"keys\"",
"]",
":",
"logger",
".",
"warning",
"(",
"\"No API key found with name 'google... | Build the YouTube API for future use | [
"Build",
"the",
"YouTube",
"API",
"for",
"future",
"use"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L25-L45 | train | 41,314 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | build_sc_api | def build_sc_api():
"""Build the SoundCloud API for future use"""
data = datatools.get_data()
if "soundcloud_client_id" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'soundcloud_client_id'")
logger.info("Please add your SoundCloud client id with name 'soundcloud_client_id' "
"in data.json to use Soundcloud features of the music module")
return False
try:
global scclient
scclient = soundcloud.Client(client_id=data["discord"]["keys"]["soundcloud_client_id"])
logger.debug("SoundCloud build successful")
return True
except Exception as e:
logger.exception(e)
return False | python | def build_sc_api():
"""Build the SoundCloud API for future use"""
data = datatools.get_data()
if "soundcloud_client_id" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'soundcloud_client_id'")
logger.info("Please add your SoundCloud client id with name 'soundcloud_client_id' "
"in data.json to use Soundcloud features of the music module")
return False
try:
global scclient
scclient = soundcloud.Client(client_id=data["discord"]["keys"]["soundcloud_client_id"])
logger.debug("SoundCloud build successful")
return True
except Exception as e:
logger.exception(e)
return False | [
"def",
"build_sc_api",
"(",
")",
":",
"data",
"=",
"datatools",
".",
"get_data",
"(",
")",
"if",
"\"soundcloud_client_id\"",
"not",
"in",
"data",
"[",
"\"discord\"",
"]",
"[",
"\"keys\"",
"]",
":",
"logger",
".",
"warning",
"(",
"\"No API key found with name '... | Build the SoundCloud API for future use | [
"Build",
"the",
"SoundCloud",
"API",
"for",
"future",
"use"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L48-L64 | train | 41,315 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | build_spotify_api | def build_spotify_api():
"""Build the Spotify API for future use"""
data = datatools.get_data()
if "spotify_client_id" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'spotify_client_id'")
logger.info("Please add your Spotify client id with name 'spotify_client_id' "
"in data.json to use Spotify features of the music module")
return False
if "spotify_client_secret" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'spotify_client_secret'")
logger.info("Please add your Spotify client secret with name 'spotify_client_secret' "
"in data.json to use Spotify features of the music module")
return False
try:
global spclient
client_credentials_manager = SpotifyClientCredentials(
data["discord"]["keys"]["spotify_client_id"],
data["discord"]["keys"]["spotify_client_secret"])
spclient = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
logger.debug("Spotify build successful")
return True
except Exception as e:
logger.exception(e)
return False | python | def build_spotify_api():
"""Build the Spotify API for future use"""
data = datatools.get_data()
if "spotify_client_id" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'spotify_client_id'")
logger.info("Please add your Spotify client id with name 'spotify_client_id' "
"in data.json to use Spotify features of the music module")
return False
if "spotify_client_secret" not in data["discord"]["keys"]:
logger.warning("No API key found with name 'spotify_client_secret'")
logger.info("Please add your Spotify client secret with name 'spotify_client_secret' "
"in data.json to use Spotify features of the music module")
return False
try:
global spclient
client_credentials_manager = SpotifyClientCredentials(
data["discord"]["keys"]["spotify_client_id"],
data["discord"]["keys"]["spotify_client_secret"])
spclient = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
logger.debug("Spotify build successful")
return True
except Exception as e:
logger.exception(e)
return False | [
"def",
"build_spotify_api",
"(",
")",
":",
"data",
"=",
"datatools",
".",
"get_data",
"(",
")",
"if",
"\"spotify_client_id\"",
"not",
"in",
"data",
"[",
"\"discord\"",
"]",
"[",
"\"keys\"",
"]",
":",
"logger",
".",
"warning",
"(",
"\"No API key found with name... | Build the Spotify API for future use | [
"Build",
"the",
"Spotify",
"API",
"for",
"future",
"use"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L67-L91 | train | 41,316 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | get_ytvideos | def get_ytvideos(query, ilogger):
"""
Gets either a list of videos from a playlist or a single video, using the
first result of a YouTube search
Args:
query (str): The YouTube search query
ilogger (logging.logger): The logger to log API calls to
Returns:
queue (list): The items obtained from the YouTube search
"""
queue = []
# Search YouTube
search_result = ytdiscoveryapi.search().list(
q=query,
part="id,snippet",
maxResults=1,
type="video,playlist"
).execute()
if not search_result["items"]:
return []
# Get video/playlist title
title = search_result["items"][0]["snippet"]["title"]
ilogger.info("Queueing {}".format(title))
# Queue video if video
if search_result["items"][0]["id"]["kind"] == "youtube#video":
# Get ID of video
videoid = search_result["items"][0]["id"]["videoId"]
# Append video to queue
queue.append(["https://www.youtube.com/watch?v={}".format(videoid), title])
# Queue playlist if playlist
elif search_result["items"][0]["id"]["kind"] == "youtube#playlist":
queue = get_queue_from_playlist(search_result["items"][0]["id"]["playlistId"])
return queue | python | def get_ytvideos(query, ilogger):
"""
Gets either a list of videos from a playlist or a single video, using the
first result of a YouTube search
Args:
query (str): The YouTube search query
ilogger (logging.logger): The logger to log API calls to
Returns:
queue (list): The items obtained from the YouTube search
"""
queue = []
# Search YouTube
search_result = ytdiscoveryapi.search().list(
q=query,
part="id,snippet",
maxResults=1,
type="video,playlist"
).execute()
if not search_result["items"]:
return []
# Get video/playlist title
title = search_result["items"][0]["snippet"]["title"]
ilogger.info("Queueing {}".format(title))
# Queue video if video
if search_result["items"][0]["id"]["kind"] == "youtube#video":
# Get ID of video
videoid = search_result["items"][0]["id"]["videoId"]
# Append video to queue
queue.append(["https://www.youtube.com/watch?v={}".format(videoid), title])
# Queue playlist if playlist
elif search_result["items"][0]["id"]["kind"] == "youtube#playlist":
queue = get_queue_from_playlist(search_result["items"][0]["id"]["playlistId"])
return queue | [
"def",
"get_ytvideos",
"(",
"query",
",",
"ilogger",
")",
":",
"queue",
"=",
"[",
"]",
"# Search YouTube",
"search_result",
"=",
"ytdiscoveryapi",
".",
"search",
"(",
")",
".",
"list",
"(",
"q",
"=",
"query",
",",
"part",
"=",
"\"id,snippet\"",
",",
"max... | Gets either a list of videos from a playlist or a single video, using the
first result of a YouTube search
Args:
query (str): The YouTube search query
ilogger (logging.logger): The logger to log API calls to
Returns:
queue (list): The items obtained from the YouTube search | [
"Gets",
"either",
"a",
"list",
"of",
"videos",
"from",
"a",
"playlist",
"or",
"a",
"single",
"video",
"using",
"the",
"first",
"result",
"of",
"a",
"YouTube",
"search"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L237-L279 | train | 41,317 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | duration_to_string | def duration_to_string(duration):
"""
Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string
"""
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | python | def duration_to_string(duration):
"""
Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string
"""
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | [
"def",
"duration_to_string",
"(",
"duration",
")",
":",
"m",
",",
"s",
"=",
"divmod",
"(",
"duration",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
"return",
"\"%d:%02d:%02d\"",
"%",
"(",
"h",
",",
"m",
",",
"s",
")"
] | Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string | [
"Converts",
"a",
"duration",
"to",
"a",
"string"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L458-L470 | train | 41,318 |
ModisWorks/modis | modis/discord_modis/modules/music/api_music.py | parse_source | def parse_source(info):
"""
Parses the source info from an info dict generated by youtube-dl
Args:
info (dict): The info dict to parse
Returns:
source (str): The source of this song
"""
if "extractor_key" in info:
source = info["extractor_key"]
lower_source = source.lower()
for key in SOURCE_TO_NAME:
lower_key = key.lower()
if lower_source == lower_key:
source = SOURCE_TO_NAME[lower_key]
if source != "Generic":
return source
if "url" in info and info["url"] is not None:
p = urlparse(info["url"])
if p and p.netloc:
return p.netloc
return "Unknown" | python | def parse_source(info):
"""
Parses the source info from an info dict generated by youtube-dl
Args:
info (dict): The info dict to parse
Returns:
source (str): The source of this song
"""
if "extractor_key" in info:
source = info["extractor_key"]
lower_source = source.lower()
for key in SOURCE_TO_NAME:
lower_key = key.lower()
if lower_source == lower_key:
source = SOURCE_TO_NAME[lower_key]
if source != "Generic":
return source
if "url" in info and info["url"] is not None:
p = urlparse(info["url"])
if p and p.netloc:
return p.netloc
return "Unknown" | [
"def",
"parse_source",
"(",
"info",
")",
":",
"if",
"\"extractor_key\"",
"in",
"info",
":",
"source",
"=",
"info",
"[",
"\"extractor_key\"",
"]",
"lower_source",
"=",
"source",
".",
"lower",
"(",
")",
"for",
"key",
"in",
"SOURCE_TO_NAME",
":",
"lower_key",
... | Parses the source info from an info dict generated by youtube-dl
Args:
info (dict): The info dict to parse
Returns:
source (str): The source of this song | [
"Parses",
"the",
"source",
"info",
"from",
"an",
"info",
"dict",
"generated",
"by",
"youtube",
"-",
"dl"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/api_music.py#L473-L501 | train | 41,319 |
ModisWorks/modis | modis/discord_modis/modules/_chatbot/api_mitsuku.py | get_botcust2 | def get_botcust2():
"""Gets a botcust2, used to identify a speaker with Mitsuku
Returns:
botcust2 (str): The botcust2 identifier
"""
logger.debug("Getting new botcust2")
# Set up http request packages
params = {
'botid': 'f6a012073e345a08',
'amp;skin': 'chat'
}
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch, br',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
'DNT': '1',
'Host': 'kakko.pandorabots.com',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/58.0.3029.110 Safari/537.36'
}
# Get response from http POST request to url
logger.debug("Sending POST request")
response = requests.post(
url,
params=params,
headers=headers
)
logger.debug("POST response {}".format(response))
# Try to extract Mitsuku response from POST response
try:
result = response.headers['set-cookie'][9:25]
logger.debug("Getting botcust2 successful")
except IndexError:
result = False
logger.critical("Getting botcust2 from html failed")
return result | python | def get_botcust2():
"""Gets a botcust2, used to identify a speaker with Mitsuku
Returns:
botcust2 (str): The botcust2 identifier
"""
logger.debug("Getting new botcust2")
# Set up http request packages
params = {
'botid': 'f6a012073e345a08',
'amp;skin': 'chat'
}
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch, br',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
'DNT': '1',
'Host': 'kakko.pandorabots.com',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/58.0.3029.110 Safari/537.36'
}
# Get response from http POST request to url
logger.debug("Sending POST request")
response = requests.post(
url,
params=params,
headers=headers
)
logger.debug("POST response {}".format(response))
# Try to extract Mitsuku response from POST response
try:
result = response.headers['set-cookie'][9:25]
logger.debug("Getting botcust2 successful")
except IndexError:
result = False
logger.critical("Getting botcust2 from html failed")
return result | [
"def",
"get_botcust2",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting new botcust2\"",
")",
"# Set up http request packages",
"params",
"=",
"{",
"'botid'",
":",
"'f6a012073e345a08'",
",",
"'amp;skin'",
":",
"'chat'",
"}",
"headers",
"=",
"{",
"'Accept'",
... | Gets a botcust2, used to identify a speaker with Mitsuku
Returns:
botcust2 (str): The botcust2 identifier | [
"Gets",
"a",
"botcust2",
"used",
"to",
"identify",
"a",
"speaker",
"with",
"Mitsuku"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/_chatbot/api_mitsuku.py#L12-L55 | train | 41,320 |
ModisWorks/modis | modis/discord_modis/modules/_chatbot/api_mitsuku.py | query | def query(botcust2, message):
"""Sends a message to Mitsuku and retrieves the reply
Args:
botcust2 (str): The botcust2 identifier
message (str): The message to send to Mitsuku
Returns:
reply (str): The message Mitsuku sent back
"""
logger.debug("Getting Mitsuku reply")
# Set up http request packages
params = {
'botid': 'f6a012073e345a08',
'amp;skin': 'chat'
}
headers = {
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Content-Length': str(len(message) + 34),
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'botcust2=' + botcust2,
'DNT': '1',
'Host': 'kakko.pandorabots.com',
'Origin': 'https://kakko.pandorabots.com',
'Referer': 'https://kakko.pandorabots.com/pandora/talk?botid=f6a012073e345a08&skin=chat',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/58.0.3029.110 Safari/537.36'
}
data = {
'botcust2': botcust2,
'message': message
}
# Get response from http POST request to url
logger.debug("Sending POST request")
response = requests.post(
url,
params=params,
headers=headers,
data=data
)
logger.debug("POST response {}".format(response))
# Parse response
parsed = lxml.html.parse(io.StringIO(response.text)).getroot()
try:
result = parsed[1][2][0][2].tail[1:]
logger.debug("Getting botcust2 successful")
except IndexError:
result = False
logger.critical("Getting botcust2 from html failed")
return result | python | def query(botcust2, message):
"""Sends a message to Mitsuku and retrieves the reply
Args:
botcust2 (str): The botcust2 identifier
message (str): The message to send to Mitsuku
Returns:
reply (str): The message Mitsuku sent back
"""
logger.debug("Getting Mitsuku reply")
# Set up http request packages
params = {
'botid': 'f6a012073e345a08',
'amp;skin': 'chat'
}
headers = {
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Content-Length': str(len(message) + 34),
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'botcust2=' + botcust2,
'DNT': '1',
'Host': 'kakko.pandorabots.com',
'Origin': 'https://kakko.pandorabots.com',
'Referer': 'https://kakko.pandorabots.com/pandora/talk?botid=f6a012073e345a08&skin=chat',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/58.0.3029.110 Safari/537.36'
}
data = {
'botcust2': botcust2,
'message': message
}
# Get response from http POST request to url
logger.debug("Sending POST request")
response = requests.post(
url,
params=params,
headers=headers,
data=data
)
logger.debug("POST response {}".format(response))
# Parse response
parsed = lxml.html.parse(io.StringIO(response.text)).getroot()
try:
result = parsed[1][2][0][2].tail[1:]
logger.debug("Getting botcust2 successful")
except IndexError:
result = False
logger.critical("Getting botcust2 from html failed")
return result | [
"def",
"query",
"(",
"botcust2",
",",
"message",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting Mitsuku reply\"",
")",
"# Set up http request packages",
"params",
"=",
"{",
"'botid'",
":",
"'f6a012073e345a08'",
",",
"'amp;skin'",
":",
"'chat'",
"}",
"headers",
... | Sends a message to Mitsuku and retrieves the reply
Args:
botcust2 (str): The botcust2 identifier
message (str): The message to send to Mitsuku
Returns:
reply (str): The message Mitsuku sent back | [
"Sends",
"a",
"message",
"to",
"Mitsuku",
"and",
"retrieves",
"the",
"reply"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/_chatbot/api_mitsuku.py#L58-L116 | train | 41,321 |
ModisWorks/modis | modis/discord_modis/main.py | _get_event_handlers | def _get_event_handlers():
"""
Gets dictionary of event handlers and the modules that define them
Returns:
event_handlers (dict): Contains "all", "on_ready", "on_message", "on_reaction_add", "on_error"
"""
import os
import importlib
event_handlers = {
"on_ready": [],
"on_resume": [],
"on_error": [],
"on_message": [],
"on_socket_raw_receive": [],
"on_socket_raw_send": [],
"on_message_delete": [],
"on_message_edit": [],
"on_reaction_add": [],
"on_reaction_remove": [],
"on_reaction_clear": [],
"on_channel_delete": [],
"on_channel_create": [],
"on_channel_update": [],
"on_member_join": [],
"on_member_remove": [],
"on_member_update": [],
"on_server_join": [],
"on_server_remove": [],
"on_server_update": [],
"on_server_role_create": [],
"on_server_role_delete": [],
"on_server_role_update": [],
"on_server_emojis_update": [],
"on_server_available": [],
"on_server_unavailable": [],
"on_voice_state_update": [],
"on_member_ban": [],
"on_member_unban": [],
"on_typing": [],
"on_group_join": [],
"on_group_remove": []
}
# Iterate through module folders
database_dir = "{}/modules".format(
os.path.dirname(os.path.realpath(__file__)))
for module_name in os.listdir(database_dir):
module_dir = "{}/{}".format(database_dir, module_name)
# Iterate through files in module
if os.path.isdir(module_dir) and not module_name.startswith("_"):
# Add all defined event handlers in module files
module_event_handlers = os.listdir(module_dir)
for event_handler in event_handlers.keys():
if "{}.py".format(event_handler) in module_event_handlers:
import_name = ".discord_modis.modules.{}.{}".format(
module_name, event_handler)
logger.debug("Found event handler {}".format(import_name[23:]))
try:
event_handlers[event_handler].append(
importlib.import_module(import_name, "modis"))
except Exception as e:
# Log errors in modules
logger.exception(e)
return event_handlers | python | def _get_event_handlers():
"""
Gets dictionary of event handlers and the modules that define them
Returns:
event_handlers (dict): Contains "all", "on_ready", "on_message", "on_reaction_add", "on_error"
"""
import os
import importlib
event_handlers = {
"on_ready": [],
"on_resume": [],
"on_error": [],
"on_message": [],
"on_socket_raw_receive": [],
"on_socket_raw_send": [],
"on_message_delete": [],
"on_message_edit": [],
"on_reaction_add": [],
"on_reaction_remove": [],
"on_reaction_clear": [],
"on_channel_delete": [],
"on_channel_create": [],
"on_channel_update": [],
"on_member_join": [],
"on_member_remove": [],
"on_member_update": [],
"on_server_join": [],
"on_server_remove": [],
"on_server_update": [],
"on_server_role_create": [],
"on_server_role_delete": [],
"on_server_role_update": [],
"on_server_emojis_update": [],
"on_server_available": [],
"on_server_unavailable": [],
"on_voice_state_update": [],
"on_member_ban": [],
"on_member_unban": [],
"on_typing": [],
"on_group_join": [],
"on_group_remove": []
}
# Iterate through module folders
database_dir = "{}/modules".format(
os.path.dirname(os.path.realpath(__file__)))
for module_name in os.listdir(database_dir):
module_dir = "{}/{}".format(database_dir, module_name)
# Iterate through files in module
if os.path.isdir(module_dir) and not module_name.startswith("_"):
# Add all defined event handlers in module files
module_event_handlers = os.listdir(module_dir)
for event_handler in event_handlers.keys():
if "{}.py".format(event_handler) in module_event_handlers:
import_name = ".discord_modis.modules.{}.{}".format(
module_name, event_handler)
logger.debug("Found event handler {}".format(import_name[23:]))
try:
event_handlers[event_handler].append(
importlib.import_module(import_name, "modis"))
except Exception as e:
# Log errors in modules
logger.exception(e)
return event_handlers | [
"def",
"_get_event_handlers",
"(",
")",
":",
"import",
"os",
"import",
"importlib",
"event_handlers",
"=",
"{",
"\"on_ready\"",
":",
"[",
"]",
",",
"\"on_resume\"",
":",
"[",
"]",
",",
"\"on_error\"",
":",
"[",
"]",
",",
"\"on_message\"",
":",
"[",
"]",
... | Gets dictionary of event handlers and the modules that define them
Returns:
event_handlers (dict): Contains "all", "on_ready", "on_message", "on_reaction_add", "on_error" | [
"Gets",
"dictionary",
"of",
"event",
"handlers",
"and",
"the",
"modules",
"that",
"define",
"them"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/main.py#L110-L180 | train | 41,322 |
ModisWorks/modis | modis/discord_modis/main.py | add_api_key | def add_api_key(key, value):
"""
Adds a key to the bot's data
Args:
key: The name of the key to add
value: The value for the key
"""
if key is None or key == "":
logger.error("Key cannot be empty")
if value is None or value == "":
logger.error("Value cannot be empty")
from .. import datatools
data = datatools.get_data()
if "keys" not in data["discord"]:
data["discord"]["keys"] = {}
is_key_new = False
if key not in data["discord"]["keys"]:
is_key_new = True
elif data["discord"]["keys"][key] == value:
logger.info("API key '{}' already has value '{}'".format(key, value))
return
data["discord"]["keys"][key] = value
datatools.write_data(data)
key_text = "added" if is_key_new else "updated"
logger.info("API key '{}' {} with value '{}'".format(key, key_text, value)) | python | def add_api_key(key, value):
"""
Adds a key to the bot's data
Args:
key: The name of the key to add
value: The value for the key
"""
if key is None or key == "":
logger.error("Key cannot be empty")
if value is None or value == "":
logger.error("Value cannot be empty")
from .. import datatools
data = datatools.get_data()
if "keys" not in data["discord"]:
data["discord"]["keys"] = {}
is_key_new = False
if key not in data["discord"]["keys"]:
is_key_new = True
elif data["discord"]["keys"][key] == value:
logger.info("API key '{}' already has value '{}'".format(key, value))
return
data["discord"]["keys"][key] = value
datatools.write_data(data)
key_text = "added" if is_key_new else "updated"
logger.info("API key '{}' {} with value '{}'".format(key, key_text, value)) | [
"def",
"add_api_key",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"is",
"None",
"or",
"key",
"==",
"\"\"",
":",
"logger",
".",
"error",
"(",
"\"Key cannot be empty\"",
")",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"\"\"",
":",
"logger",
... | Adds a key to the bot's data
Args:
key: The name of the key to add
value: The value for the key | [
"Adds",
"a",
"key",
"to",
"the",
"bot",
"s",
"data"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/main.py#L183-L215 | train | 41,323 |
ModisWorks/modis | modis/discord_modis/modules/help/ui_embed.py | success | def success(channel, title, datapacks):
"""
Creates an embed UI containing the help message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
datapacks (list): The hex value
Returns:
ui (ui_embed.UI): The embed UI object
"""
# Create embed UI object
gui = ui_embed.UI(
channel,
title,
"",
modulename=modulename,
datapacks=datapacks
)
return gui | python | def success(channel, title, datapacks):
"""
Creates an embed UI containing the help message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
datapacks (list): The hex value
Returns:
ui (ui_embed.UI): The embed UI object
"""
# Create embed UI object
gui = ui_embed.UI(
channel,
title,
"",
modulename=modulename,
datapacks=datapacks
)
return gui | [
"def",
"success",
"(",
"channel",
",",
"title",
",",
"datapacks",
")",
":",
"# Create embed UI object",
"gui",
"=",
"ui_embed",
".",
"UI",
"(",
"channel",
",",
"title",
",",
"\"\"",
",",
"modulename",
"=",
"modulename",
",",
"datapacks",
"=",
"datapacks",
... | Creates an embed UI containing the help message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
datapacks (list): The hex value
Returns:
ui (ui_embed.UI): The embed UI object | [
"Creates",
"an",
"embed",
"UI",
"containing",
"the",
"help",
"message"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/help/ui_embed.py#L5-L27 | train | 41,324 |
ModisWorks/modis | modis/discord_modis/modules/help/ui_embed.py | http_exception | def http_exception(channel, title):
"""
Creates an embed UI containing the 'too long' error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
Returns:
ui (ui_embed.UI): The embed UI object
"""
# Create embed UI object
gui = ui_embed.UI(
channel,
"Too much help",
"{} is too helpful! Try trimming some of the help messages.".format(title),
modulename=modulename
)
return gui | python | def http_exception(channel, title):
"""
Creates an embed UI containing the 'too long' error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
Returns:
ui (ui_embed.UI): The embed UI object
"""
# Create embed UI object
gui = ui_embed.UI(
channel,
"Too much help",
"{} is too helpful! Try trimming some of the help messages.".format(title),
modulename=modulename
)
return gui | [
"def",
"http_exception",
"(",
"channel",
",",
"title",
")",
":",
"# Create embed UI object",
"gui",
"=",
"ui_embed",
".",
"UI",
"(",
"channel",
",",
"\"Too much help\"",
",",
"\"{} is too helpful! Try trimming some of the help messages.\"",
".",
"format",
"(",
"title",
... | Creates an embed UI containing the 'too long' error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
Returns:
ui (ui_embed.UI): The embed UI object | [
"Creates",
"an",
"embed",
"UI",
"containing",
"the",
"too",
"long",
"error",
"message"
] | 1f1225c9841835ec1d1831fc196306527567db8b | https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/help/ui_embed.py#L30-L50 | train | 41,325 |
tarbell-project/tarbell | tarbell/configure.py | tarbell_configure | def tarbell_configure(command, args):
"""
Tarbell configuration routine.
"""
puts("Configuring Tarbell. Press ctrl-c to bail out!")
# Check if there's settings configured
settings = Settings()
path = settings.path
prompt = True
if len(args):
prompt = False
config = _get_or_create_config(path)
if prompt or "drive" in args:
config.update(_setup_google_spreadsheets(config, path, prompt))
if prompt or "s3" in args:
config.update(_setup_s3(config, path, prompt))
if prompt or "path" in args:
config.update(_setup_tarbell_project_path(config, path, prompt))
if prompt or "templates" in args:
if "project_templates" in config:
override_templates = raw_input("\nFound Base Template config. Would you like to override them? [Default: No, 'none' to skip]")
if override_templates and override_templates != "No" and override_templates != "no" and override_templates != "N" and override_templates != "n":
config.update(_setup_default_templates(config, path, prompt))
else:
puts("\nPreserving Base Template config...")
else:
config.update(_setup_default_templates(config, path, prompt))
settings.config = config
with open(path, 'w') as f:
puts("\nWriting {0}".format(colored.green(path)))
settings.save()
if all:
puts("\n- Done configuring Tarbell. Type `{0}` for help.\n"
.format(colored.green("tarbell")))
return settings | python | def tarbell_configure(command, args):
"""
Tarbell configuration routine.
"""
puts("Configuring Tarbell. Press ctrl-c to bail out!")
# Check if there's settings configured
settings = Settings()
path = settings.path
prompt = True
if len(args):
prompt = False
config = _get_or_create_config(path)
if prompt or "drive" in args:
config.update(_setup_google_spreadsheets(config, path, prompt))
if prompt or "s3" in args:
config.update(_setup_s3(config, path, prompt))
if prompt or "path" in args:
config.update(_setup_tarbell_project_path(config, path, prompt))
if prompt or "templates" in args:
if "project_templates" in config:
override_templates = raw_input("\nFound Base Template config. Would you like to override them? [Default: No, 'none' to skip]")
if override_templates and override_templates != "No" and override_templates != "no" and override_templates != "N" and override_templates != "n":
config.update(_setup_default_templates(config, path, prompt))
else:
puts("\nPreserving Base Template config...")
else:
config.update(_setup_default_templates(config, path, prompt))
settings.config = config
with open(path, 'w') as f:
puts("\nWriting {0}".format(colored.green(path)))
settings.save()
if all:
puts("\n- Done configuring Tarbell. Type `{0}` for help.\n"
.format(colored.green("tarbell")))
return settings | [
"def",
"tarbell_configure",
"(",
"command",
",",
"args",
")",
":",
"puts",
"(",
"\"Configuring Tarbell. Press ctrl-c to bail out!\"",
")",
"# Check if there's settings configured",
"settings",
"=",
"Settings",
"(",
")",
"path",
"=",
"settings",
".",
"path",
"prompt",
... | Tarbell configuration routine. | [
"Tarbell",
"configuration",
"routine",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/configure.py#L26-L68 | train | 41,326 |
tarbell-project/tarbell | tarbell/configure.py | _get_or_create_config | def _get_or_create_config(path, prompt=True):
"""
Get or create a Tarbell configuration directory.
"""
dirname = os.path.dirname(path)
filename = os.path.basename(path)
try:
os.makedirs(dirname)
except OSError:
pass
try:
with open(path, 'r+') as f:
if os.path.isfile(path):
puts("{0} already exists, backing up".format(colored.green(path)))
_backup(dirname, filename)
return yaml.load(f)
except IOError:
return {} | python | def _get_or_create_config(path, prompt=True):
"""
Get or create a Tarbell configuration directory.
"""
dirname = os.path.dirname(path)
filename = os.path.basename(path)
try:
os.makedirs(dirname)
except OSError:
pass
try:
with open(path, 'r+') as f:
if os.path.isfile(path):
puts("{0} already exists, backing up".format(colored.green(path)))
_backup(dirname, filename)
return yaml.load(f)
except IOError:
return {} | [
"def",
"_get_or_create_config",
"(",
"path",
",",
"prompt",
"=",
"True",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"try",
":",
"os",
".",
"m... | Get or create a Tarbell configuration directory. | [
"Get",
"or",
"create",
"a",
"Tarbell",
"configuration",
"directory",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/configure.py#L71-L90 | train | 41,327 |
tarbell-project/tarbell | tarbell/configure.py | _setup_google_spreadsheets | def _setup_google_spreadsheets(settings, path, prompt=True):
"""
Set up a Google spreadsheet.
"""
ret = {}
if prompt:
use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ")
if use.lower() != "y" and use != "":
return settings
dirname = os.path.dirname(path)
path = os.path.join(dirname, "client_secrets.json")
write_secrets = True
if os.path.isfile(path):
write_secrets_input = raw_input("client_secrets.json already exists. Would you like to overwrite it? [y/N] ")
if not write_secrets_input.lower().startswith('y'):
write_secrets = False
if write_secrets:
puts(("\nLogin in to Google and go to {0} to create an app and generate a "
"\nclient_secrets authentication file. You should create credentials for an `installed app`. See "
"\n{1} for more information."
.format(colored.red("https://console.developers.google.com/project"),
colored.red("http://tarbell.readthedocs.org/en/{0}/install.html#configure-google-spreadsheet-access-optional".format(LONG_VERSION))
)
))
secrets_path = raw_input(("\nWhere is your client secrets file? "
"[~/Downloads/client_secrets.json] "
))
if secrets_path == "":
secrets_path = os.path.join("~", "Downloads/client_secrets.json")
secrets_path = os.path.expanduser(secrets_path)
puts("\nCopying {0} to {1}\n"
.format(colored.green(secrets_path),
colored.green(dirname))
)
_backup(dirname, "client_secrets.json")
try:
shutil.copy(secrets_path, os.path.join(dirname, 'client_secrets.json'))
except shutil.Error as e:
show_error(str(e))
# Now, try and obtain the API for the first time
get_api = raw_input("Would you like to authenticate your client_secrets.json? [Y/n] ")
if get_api == '' or get_api.lower().startswith('y'):
get_drive_api_from_client_secrets(path, reset_creds=True)
default_account = settings.get("google_account", "")
account = raw_input(("What Google account(s) should have access to new spreadsheets? "
"(e.g. somebody@gmail.com, leave blank to specify for each new "
"project, separate multiple addresses with commas) [{0}] "
.format(default_account)
))
if default_account != "" and account == "":
account = default_account
if account != "":
ret = { "google_account" : account }
puts("\n- Done configuring Google spreadsheets.")
return ret | python | def _setup_google_spreadsheets(settings, path, prompt=True):
"""
Set up a Google spreadsheet.
"""
ret = {}
if prompt:
use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ")
if use.lower() != "y" and use != "":
return settings
dirname = os.path.dirname(path)
path = os.path.join(dirname, "client_secrets.json")
write_secrets = True
if os.path.isfile(path):
write_secrets_input = raw_input("client_secrets.json already exists. Would you like to overwrite it? [y/N] ")
if not write_secrets_input.lower().startswith('y'):
write_secrets = False
if write_secrets:
puts(("\nLogin in to Google and go to {0} to create an app and generate a "
"\nclient_secrets authentication file. You should create credentials for an `installed app`. See "
"\n{1} for more information."
.format(colored.red("https://console.developers.google.com/project"),
colored.red("http://tarbell.readthedocs.org/en/{0}/install.html#configure-google-spreadsheet-access-optional".format(LONG_VERSION))
)
))
secrets_path = raw_input(("\nWhere is your client secrets file? "
"[~/Downloads/client_secrets.json] "
))
if secrets_path == "":
secrets_path = os.path.join("~", "Downloads/client_secrets.json")
secrets_path = os.path.expanduser(secrets_path)
puts("\nCopying {0} to {1}\n"
.format(colored.green(secrets_path),
colored.green(dirname))
)
_backup(dirname, "client_secrets.json")
try:
shutil.copy(secrets_path, os.path.join(dirname, 'client_secrets.json'))
except shutil.Error as e:
show_error(str(e))
# Now, try and obtain the API for the first time
get_api = raw_input("Would you like to authenticate your client_secrets.json? [Y/n] ")
if get_api == '' or get_api.lower().startswith('y'):
get_drive_api_from_client_secrets(path, reset_creds=True)
default_account = settings.get("google_account", "")
account = raw_input(("What Google account(s) should have access to new spreadsheets? "
"(e.g. somebody@gmail.com, leave blank to specify for each new "
"project, separate multiple addresses with commas) [{0}] "
.format(default_account)
))
if default_account != "" and account == "":
account = default_account
if account != "":
ret = { "google_account" : account }
puts("\n- Done configuring Google spreadsheets.")
return ret | [
"def",
"_setup_google_spreadsheets",
"(",
"settings",
",",
"path",
",",
"prompt",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"prompt",
":",
"use",
"=",
"raw_input",
"(",
"\"\\nWould you like to use Google spreadsheets [Y/n]? \"",
")",
"if",
"use",
".",
... | Set up a Google spreadsheet. | [
"Set",
"up",
"a",
"Google",
"spreadsheet",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/configure.py#L93-L158 | train | 41,328 |
tarbell-project/tarbell | tarbell/configure.py | _setup_tarbell_project_path | def _setup_tarbell_project_path(settings, path, prompt=True):
"""
Prompt user to set up project path.
"""
default_path = os.path.expanduser(os.path.join("~", "tarbell"))
projects_path = raw_input("\nWhat is your Tarbell projects path? [Default: {0}, 'none' to skip] ".format(default_path))
if projects_path == "":
projects_path = default_path
if projects_path.lower() == 'none':
puts("\n- Not creating projects directory.")
return {}
if os.path.isdir(projects_path):
puts("\nDirectory exists!")
else:
puts("\nDirectory does not exist.")
make = raw_input("\nWould you like to create it? [Y/n] ")
if make.lower() == "y" or not make:
os.makedirs(projects_path)
puts("\nProjects path is {0}".format(projects_path))
puts("\n- Done setting up projects path.")
return {"projects_path": projects_path} | python | def _setup_tarbell_project_path(settings, path, prompt=True):
"""
Prompt user to set up project path.
"""
default_path = os.path.expanduser(os.path.join("~", "tarbell"))
projects_path = raw_input("\nWhat is your Tarbell projects path? [Default: {0}, 'none' to skip] ".format(default_path))
if projects_path == "":
projects_path = default_path
if projects_path.lower() == 'none':
puts("\n- Not creating projects directory.")
return {}
if os.path.isdir(projects_path):
puts("\nDirectory exists!")
else:
puts("\nDirectory does not exist.")
make = raw_input("\nWould you like to create it? [Y/n] ")
if make.lower() == "y" or not make:
os.makedirs(projects_path)
puts("\nProjects path is {0}".format(projects_path))
puts("\n- Done setting up projects path.")
return {"projects_path": projects_path} | [
"def",
"_setup_tarbell_project_path",
"(",
"settings",
",",
"path",
",",
"prompt",
"=",
"True",
")",
":",
"default_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"~\"",
",",
"\"tarbell\"",
")",
")",
"project... | Prompt user to set up project path. | [
"Prompt",
"user",
"to",
"set",
"up",
"project",
"path",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/configure.py#L292-L313 | train | 41,329 |
tarbell-project/tarbell | tarbell/configure.py | _backup | def _backup(path, filename):
"""
Backup a file.
"""
target = os.path.join(path, filename)
if os.path.isfile(target):
dt = datetime.now()
new_filename = ".{0}.{1}.{2}".format(
filename, dt.isoformat(), "backup"
)
destination = os.path.join(path, new_filename)
puts("- Backing up {0} to {1}".format(
colored.cyan(target),
colored.cyan(destination)
))
shutil.copy(target, destination) | python | def _backup(path, filename):
"""
Backup a file.
"""
target = os.path.join(path, filename)
if os.path.isfile(target):
dt = datetime.now()
new_filename = ".{0}.{1}.{2}".format(
filename, dt.isoformat(), "backup"
)
destination = os.path.join(path, new_filename)
puts("- Backing up {0} to {1}".format(
colored.cyan(target),
colored.cyan(destination)
))
shutil.copy(target, destination) | [
"def",
"_backup",
"(",
"path",
",",
"filename",
")",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"target",
")",
":",
"dt",
"=",
"datetime",
".",
"now",
"(",
... | Backup a file. | [
"Backup",
"a",
"file",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/configure.py#L337-L353 | train | 41,330 |
tarbell-project/tarbell | tarbell/slughifi.py | slughifi | def slughifi(value, overwrite_char_map={}):
"""
High Fidelity slugify - slughifi.py, v 0.1
Examples :
>>> text = 'C\'est déjà l\'été.'
>>> slughifi(text)
'cest-deja-lete'
>>> slughifi(text, overwrite_char_map={u'\': '-',})
'c-est-deja-l-ete'
>>> slughifi(text, do_slugify=False)
"C'est deja l'ete."
# Normal slugify removes accented characters
>>> slugify(text)
'cest-dj-lt'
"""
# unicodification
if type(value) != text_type:
value = value.decode('utf-8', 'ignore')
# overwrite chararcter mapping
char_map.update(overwrite_char_map)
# try to replace chars
value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value)
value = slugify(value)
return value.encode('ascii', 'ignore').decode('ascii') | python | def slughifi(value, overwrite_char_map={}):
"""
High Fidelity slugify - slughifi.py, v 0.1
Examples :
>>> text = 'C\'est déjà l\'été.'
>>> slughifi(text)
'cest-deja-lete'
>>> slughifi(text, overwrite_char_map={u'\': '-',})
'c-est-deja-l-ete'
>>> slughifi(text, do_slugify=False)
"C'est deja l'ete."
# Normal slugify removes accented characters
>>> slugify(text)
'cest-dj-lt'
"""
# unicodification
if type(value) != text_type:
value = value.decode('utf-8', 'ignore')
# overwrite chararcter mapping
char_map.update(overwrite_char_map)
# try to replace chars
value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value)
value = slugify(value)
return value.encode('ascii', 'ignore').decode('ascii') | [
"def",
"slughifi",
"(",
"value",
",",
"overwrite_char_map",
"=",
"{",
"}",
")",
":",
"# unicodification",
"if",
"type",
"(",
"value",
")",
"!=",
"text_type",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
"# overwrite char... | High Fidelity slugify - slughifi.py, v 0.1
Examples :
>>> text = 'C\'est déjà l\'été.'
>>> slughifi(text)
'cest-deja-lete'
>>> slughifi(text, overwrite_char_map={u'\': '-',})
'c-est-deja-l-ete'
>>> slughifi(text, do_slugify=False)
"C'est deja l'ete."
# Normal slugify removes accented characters
>>> slugify(text)
'cest-dj-lt' | [
"High",
"Fidelity",
"slugify",
"-",
"slughifi",
".",
"py",
"v",
"0",
".",
"1"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/slughifi.py#L29-L64 | train | 41,331 |
tarbell-project/tarbell | tarbell/utils.py | puts | def puts(s='', newline=True, stream=STDOUT):
"""
Wrap puts to avoid getting called twice by Werkzeug reloader.
"""
if not is_werkzeug_process():
try:
return _puts(s, newline, stream)
except UnicodeEncodeError:
return _puts(s.encode(sys.stdout.encoding), newline, stream) | python | def puts(s='', newline=True, stream=STDOUT):
"""
Wrap puts to avoid getting called twice by Werkzeug reloader.
"""
if not is_werkzeug_process():
try:
return _puts(s, newline, stream)
except UnicodeEncodeError:
return _puts(s.encode(sys.stdout.encoding), newline, stream) | [
"def",
"puts",
"(",
"s",
"=",
"''",
",",
"newline",
"=",
"True",
",",
"stream",
"=",
"STDOUT",
")",
":",
"if",
"not",
"is_werkzeug_process",
"(",
")",
":",
"try",
":",
"return",
"_puts",
"(",
"s",
",",
"newline",
",",
"stream",
")",
"except",
"Unic... | Wrap puts to avoid getting called twice by Werkzeug reloader. | [
"Wrap",
"puts",
"to",
"avoid",
"getting",
"called",
"twice",
"by",
"Werkzeug",
"reloader",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L23-L31 | train | 41,332 |
tarbell-project/tarbell | tarbell/utils.py | list_get | def list_get(l, idx, default=None):
"""
Get from a list with an optional default value.
"""
try:
if l[idx]:
return l[idx]
else:
return default
except IndexError:
return default | python | def list_get(l, idx, default=None):
"""
Get from a list with an optional default value.
"""
try:
if l[idx]:
return l[idx]
else:
return default
except IndexError:
return default | [
"def",
"list_get",
"(",
"l",
",",
"idx",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"if",
"l",
"[",
"idx",
"]",
":",
"return",
"l",
"[",
"idx",
"]",
"else",
":",
"return",
"default",
"except",
"IndexError",
":",
"return",
"default"
] | Get from a list with an optional default value. | [
"Get",
"from",
"a",
"list",
"with",
"an",
"optional",
"default",
"value",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L34-L44 | train | 41,333 |
tarbell-project/tarbell | tarbell/utils.py | split_sentences | def split_sentences(s, pad=0):
"""
Split sentences for formatting.
"""
sentences = []
for index, sentence in enumerate(s.split('. ')):
padding = ''
if index > 0:
padding = ' ' * (pad + 1)
if sentence.endswith('.'):
sentence = sentence[:-1]
sentences.append('%s %s.' % (padding, sentence.strip()))
return "\n".join(sentences) | python | def split_sentences(s, pad=0):
"""
Split sentences for formatting.
"""
sentences = []
for index, sentence in enumerate(s.split('. ')):
padding = ''
if index > 0:
padding = ' ' * (pad + 1)
if sentence.endswith('.'):
sentence = sentence[:-1]
sentences.append('%s %s.' % (padding, sentence.strip()))
return "\n".join(sentences) | [
"def",
"split_sentences",
"(",
"s",
",",
"pad",
"=",
"0",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"index",
",",
"sentence",
"in",
"enumerate",
"(",
"s",
".",
"split",
"(",
"'. '",
")",
")",
":",
"padding",
"=",
"''",
"if",
"index",
">",
"0",... | Split sentences for formatting. | [
"Split",
"sentences",
"for",
"formatting",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L47-L59 | train | 41,334 |
tarbell-project/tarbell | tarbell/utils.py | ensure_directory | def ensure_directory(path):
"""
Ensure directory exists for a given file path.
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname) | python | def ensure_directory(path):
"""
Ensure directory exists for a given file path.
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname) | [
"def",
"ensure_directory",
"(",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")"
] | Ensure directory exists for a given file path. | [
"Ensure",
"directory",
"exists",
"for",
"a",
"given",
"file",
"path",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L62-L68 | train | 41,335 |
tarbell-project/tarbell | tarbell/utils.py | show_error | def show_error(msg):
"""
Displays error message.
"""
sys.stdout.flush()
sys.stderr.write("\n{0!s}: {1}".format(colored.red("Error"), msg + '\n')) | python | def show_error(msg):
"""
Displays error message.
"""
sys.stdout.flush()
sys.stderr.write("\n{0!s}: {1}".format(colored.red("Error"), msg + '\n')) | [
"def",
"show_error",
"(",
"msg",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n{0!s}: {1}\"",
".",
"format",
"(",
"colored",
".",
"red",
"(",
"\"Error\"",
")",
",",
"msg",
"+",
"'\\n'",
")",
... | Displays error message. | [
"Displays",
"error",
"message",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/utils.py#L71-L76 | train | 41,336 |
aiortc/pylibsrtp | pylibsrtp/__init__.py | Session.add_stream | def add_stream(self, policy):
"""
Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy`
"""
_srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy)) | python | def add_stream(self, policy):
"""
Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy`
"""
_srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy)) | [
"def",
"add_stream",
"(",
"self",
",",
"policy",
")",
":",
"_srtp_assert",
"(",
"lib",
".",
"srtp_add_stream",
"(",
"self",
".",
"_srtp",
"[",
"0",
"]",
",",
"policy",
".",
"_policy",
")",
")"
] | Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy` | [
"Add",
"a",
"stream",
"to",
"the",
"SRTP",
"session",
"applying",
"the",
"given",
"policy",
"to",
"the",
"stream",
"."
] | 31824d1f8430ff6dc217cfc101093b6ba2a307b2 | https://github.com/aiortc/pylibsrtp/blob/31824d1f8430ff6dc217cfc101093b6ba2a307b2/pylibsrtp/__init__.py#L167-L174 | train | 41,337 |
aiortc/pylibsrtp | pylibsrtp/__init__.py | Session.remove_stream | def remove_stream(self, ssrc):
"""
Remove the stream with the given `ssrc` from the SRTP session.
:param ssrc: :class:`int`
"""
_srtp_assert(lib.srtp_remove_stream(self._srtp[0], htonl(ssrc))) | python | def remove_stream(self, ssrc):
"""
Remove the stream with the given `ssrc` from the SRTP session.
:param ssrc: :class:`int`
"""
_srtp_assert(lib.srtp_remove_stream(self._srtp[0], htonl(ssrc))) | [
"def",
"remove_stream",
"(",
"self",
",",
"ssrc",
")",
":",
"_srtp_assert",
"(",
"lib",
".",
"srtp_remove_stream",
"(",
"self",
".",
"_srtp",
"[",
"0",
"]",
",",
"htonl",
"(",
"ssrc",
")",
")",
")"
] | Remove the stream with the given `ssrc` from the SRTP session.
:param ssrc: :class:`int` | [
"Remove",
"the",
"stream",
"with",
"the",
"given",
"ssrc",
"from",
"the",
"SRTP",
"session",
"."
] | 31824d1f8430ff6dc217cfc101093b6ba2a307b2 | https://github.com/aiortc/pylibsrtp/blob/31824d1f8430ff6dc217cfc101093b6ba2a307b2/pylibsrtp/__init__.py#L176-L182 | train | 41,338 |
tarbell-project/tarbell | tarbell/app.py | process_xlsx | def process_xlsx(content):
"""
Turn Excel file contents into Tarbell worksheet data
"""
data = {}
workbook = xlrd.open_workbook(file_contents=content)
worksheets = [w for w in workbook.sheet_names() if not w.startswith('_')]
for worksheet_name in worksheets:
if worksheet_name.startswith('_'):
continue
worksheet = workbook.sheet_by_name(worksheet_name)
merged_cells = worksheet.merged_cells
if len(merged_cells):
raise MergedCellError(worksheet.name, merged_cells)
worksheet.name = slughifi(worksheet.name)
headers = make_headers(worksheet)
worksheet_data = make_worksheet_data(headers, worksheet)
data[worksheet.name] = worksheet_data
return data | python | def process_xlsx(content):
"""
Turn Excel file contents into Tarbell worksheet data
"""
data = {}
workbook = xlrd.open_workbook(file_contents=content)
worksheets = [w for w in workbook.sheet_names() if not w.startswith('_')]
for worksheet_name in worksheets:
if worksheet_name.startswith('_'):
continue
worksheet = workbook.sheet_by_name(worksheet_name)
merged_cells = worksheet.merged_cells
if len(merged_cells):
raise MergedCellError(worksheet.name, merged_cells)
worksheet.name = slughifi(worksheet.name)
headers = make_headers(worksheet)
worksheet_data = make_worksheet_data(headers, worksheet)
data[worksheet.name] = worksheet_data
return data | [
"def",
"process_xlsx",
"(",
"content",
")",
":",
"data",
"=",
"{",
"}",
"workbook",
"=",
"xlrd",
".",
"open_workbook",
"(",
"file_contents",
"=",
"content",
")",
"worksheets",
"=",
"[",
"w",
"for",
"w",
"in",
"workbook",
".",
"sheet_names",
"(",
")",
"... | Turn Excel file contents into Tarbell worksheet data | [
"Turn",
"Excel",
"file",
"contents",
"into",
"Tarbell",
"worksheet",
"data"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L43-L64 | train | 41,339 |
tarbell-project/tarbell | tarbell/app.py | copy_global_values | def copy_global_values(data):
"""
Copy values worksheet into global namespace.
"""
for k, v in data['values'].items():
if not data.get(k):
data[k] = v
else:
puts("There is both a worksheet and a "
"value named '{0}'. The worksheet data "
"will be preserved.".format(k))
data.pop("values", None)
return data | python | def copy_global_values(data):
"""
Copy values worksheet into global namespace.
"""
for k, v in data['values'].items():
if not data.get(k):
data[k] = v
else:
puts("There is both a worksheet and a "
"value named '{0}'. The worksheet data "
"will be preserved.".format(k))
data.pop("values", None)
return data | [
"def",
"copy_global_values",
"(",
"data",
")",
":",
"for",
"k",
",",
"v",
"in",
"data",
"[",
"'values'",
"]",
".",
"items",
"(",
")",
":",
"if",
"not",
"data",
".",
"get",
"(",
"k",
")",
":",
"data",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"put... | Copy values worksheet into global namespace. | [
"Copy",
"values",
"worksheet",
"into",
"global",
"namespace",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L67-L79 | train | 41,340 |
tarbell-project/tarbell | tarbell/app.py | make_headers | def make_headers(worksheet):
"""
Make headers from worksheet
"""
headers = {}
cell_idx = 0
while cell_idx < worksheet.ncols:
cell_type = worksheet.cell_type(0, cell_idx)
if cell_type == 1:
header = slughifi(worksheet.cell_value(0, cell_idx))
if not header.startswith("_"):
headers[cell_idx] = header
cell_idx += 1
return headers | python | def make_headers(worksheet):
"""
Make headers from worksheet
"""
headers = {}
cell_idx = 0
while cell_idx < worksheet.ncols:
cell_type = worksheet.cell_type(0, cell_idx)
if cell_type == 1:
header = slughifi(worksheet.cell_value(0, cell_idx))
if not header.startswith("_"):
headers[cell_idx] = header
cell_idx += 1
return headers | [
"def",
"make_headers",
"(",
"worksheet",
")",
":",
"headers",
"=",
"{",
"}",
"cell_idx",
"=",
"0",
"while",
"cell_idx",
"<",
"worksheet",
".",
"ncols",
":",
"cell_type",
"=",
"worksheet",
".",
"cell_type",
"(",
"0",
",",
"cell_idx",
")",
"if",
"cell_type... | Make headers from worksheet | [
"Make",
"headers",
"from",
"worksheet"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L82-L95 | train | 41,341 |
tarbell-project/tarbell | tarbell/app.py | make_worksheet_data | def make_worksheet_data(headers, worksheet):
"""
Make data from worksheet
"""
data = []
row_idx = 1
while row_idx < worksheet.nrows:
cell_idx = 0
row_dict = {}
while cell_idx < worksheet.ncols:
cell_type = worksheet.cell_type(row_idx, cell_idx)
if cell_type in VALID_CELL_TYPES:
cell_value = worksheet.cell_value(row_idx, cell_idx)
try:
if cell_type == 2 and cell_value.is_integer():
cell_value = int(cell_value)
row_dict[headers[cell_idx]] = cell_value
except KeyError:
try:
column = ascii_uppercase[cell_idx]
except IndexError:
column = cell_idx
puts("There is no header for cell with value '{0}' in column '{1}' of '{2}'" .format(
cell_value, column, worksheet.name
))
cell_idx += 1
data.append(row_dict)
row_idx += 1
# Magic key handling
if 'key' in headers.values():
keyed_data = {}
for row in data:
if 'key' in row.keys():
key = slughifi(row['key'])
if keyed_data.get(key):
puts("There is already a key named '{0}' with value "
"'{1}' in '{2}'. It is being overwritten with "
"value '{3}'.".format(key,
keyed_data.get(key),
worksheet.name,
row))
# Magic values worksheet
if worksheet.name == "values":
value = row.get('value')
if value not in ("", None):
keyed_data[key] = value
else:
keyed_data[key] = row
data = keyed_data
return data | python | def make_worksheet_data(headers, worksheet):
"""
Make data from worksheet
"""
data = []
row_idx = 1
while row_idx < worksheet.nrows:
cell_idx = 0
row_dict = {}
while cell_idx < worksheet.ncols:
cell_type = worksheet.cell_type(row_idx, cell_idx)
if cell_type in VALID_CELL_TYPES:
cell_value = worksheet.cell_value(row_idx, cell_idx)
try:
if cell_type == 2 and cell_value.is_integer():
cell_value = int(cell_value)
row_dict[headers[cell_idx]] = cell_value
except KeyError:
try:
column = ascii_uppercase[cell_idx]
except IndexError:
column = cell_idx
puts("There is no header for cell with value '{0}' in column '{1}' of '{2}'" .format(
cell_value, column, worksheet.name
))
cell_idx += 1
data.append(row_dict)
row_idx += 1
# Magic key handling
if 'key' in headers.values():
keyed_data = {}
for row in data:
if 'key' in row.keys():
key = slughifi(row['key'])
if keyed_data.get(key):
puts("There is already a key named '{0}' with value "
"'{1}' in '{2}'. It is being overwritten with "
"value '{3}'.".format(key,
keyed_data.get(key),
worksheet.name,
row))
# Magic values worksheet
if worksheet.name == "values":
value = row.get('value')
if value not in ("", None):
keyed_data[key] = value
else:
keyed_data[key] = row
data = keyed_data
return data | [
"def",
"make_worksheet_data",
"(",
"headers",
",",
"worksheet",
")",
":",
"data",
"=",
"[",
"]",
"row_idx",
"=",
"1",
"while",
"row_idx",
"<",
"worksheet",
".",
"nrows",
":",
"cell_idx",
"=",
"0",
"row_dict",
"=",
"{",
"}",
"while",
"cell_idx",
"<",
"w... | Make data from worksheet | [
"Make",
"data",
"from",
"worksheet"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L98-L151 | train | 41,342 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.never_cache_preview | def never_cache_preview(self, response):
"""
Ensure preview is never cached
"""
response.cache_control.max_age = 0
response.cache_control.no_cache = True
response.cache_control.must_revalidate = True
response.cache_control.no_store = True
return response | python | def never_cache_preview(self, response):
"""
Ensure preview is never cached
"""
response.cache_control.max_age = 0
response.cache_control.no_cache = True
response.cache_control.must_revalidate = True
response.cache_control.no_store = True
return response | [
"def",
"never_cache_preview",
"(",
"self",
",",
"response",
")",
":",
"response",
".",
"cache_control",
".",
"max_age",
"=",
"0",
"response",
".",
"cache_control",
".",
"no_cache",
"=",
"True",
"response",
".",
"cache_control",
".",
"must_revalidate",
"=",
"Tr... | Ensure preview is never cached | [
"Ensure",
"preview",
"is",
"never",
"cached"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L195-L203 | train | 41,343 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.call_hook | def call_hook(self, hook, *args, **kwargs):
"""
Calls each registered hook
"""
for function in self.hooks[hook]:
function.__call__(*args, **kwargs) | python | def call_hook(self, hook, *args, **kwargs):
"""
Calls each registered hook
"""
for function in self.hooks[hook]:
function.__call__(*args, **kwargs) | [
"def",
"call_hook",
"(",
"self",
",",
"hook",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"function",
"in",
"self",
".",
"hooks",
"[",
"hook",
"]",
":",
"function",
".",
"__call__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Calls each registered hook | [
"Calls",
"each",
"registered",
"hook"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L215-L220 | train | 41,344 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite._get_base | def _get_base(self, path):
"""
Get project blueprint
"""
base = None
# Slightly ugly DRY violation for backwards compatibility with old
# "_base" convention
if os.path.isdir(os.path.join(path, "_blueprint")):
base_dir = os.path.join(path, "_blueprint/")
# Get the blueprint template and register it as a blueprint
if os.path.exists(os.path.join(base_dir, "blueprint.py")):
filename, pathname, description = imp.find_module('blueprint', [base_dir])
base = imp.load_module('blueprint', filename, pathname, description)
self.blueprint_name = "_blueprint"
else:
puts("No _blueprint/blueprint.py file found")
elif os.path.isdir(os.path.join(path, "_base")):
puts("Using old '_base' convention")
base_dir = os.path.join(path, "_base/")
if os.path.exists(os.path.join(base_dir, "base.py")):
filename, pathname, description = imp.find_module('base', [base_dir])
base = imp.load_module('base', filename, pathname, description)
self.blueprint_name = "_base"
else:
puts("No _base/base.py file found")
if base:
base.base_dir = base_dir
if hasattr(base, 'blueprint') and isinstance(base.blueprint, Blueprint):
self.app.register_blueprint(base.blueprint, site=self)
return base | python | def _get_base(self, path):
"""
Get project blueprint
"""
base = None
# Slightly ugly DRY violation for backwards compatibility with old
# "_base" convention
if os.path.isdir(os.path.join(path, "_blueprint")):
base_dir = os.path.join(path, "_blueprint/")
# Get the blueprint template and register it as a blueprint
if os.path.exists(os.path.join(base_dir, "blueprint.py")):
filename, pathname, description = imp.find_module('blueprint', [base_dir])
base = imp.load_module('blueprint', filename, pathname, description)
self.blueprint_name = "_blueprint"
else:
puts("No _blueprint/blueprint.py file found")
elif os.path.isdir(os.path.join(path, "_base")):
puts("Using old '_base' convention")
base_dir = os.path.join(path, "_base/")
if os.path.exists(os.path.join(base_dir, "base.py")):
filename, pathname, description = imp.find_module('base', [base_dir])
base = imp.load_module('base', filename, pathname, description)
self.blueprint_name = "_base"
else:
puts("No _base/base.py file found")
if base:
base.base_dir = base_dir
if hasattr(base, 'blueprint') and isinstance(base.blueprint, Blueprint):
self.app.register_blueprint(base.blueprint, site=self)
return base | [
"def",
"_get_base",
"(",
"self",
",",
"path",
")",
":",
"base",
"=",
"None",
"# Slightly ugly DRY violation for backwards compatibility with old",
"# \"_base\" convention",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
... | Get project blueprint | [
"Get",
"project",
"blueprint"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L222-L255 | train | 41,345 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.load_project | def load_project(self, path):
"""
Load a Tarbell project
"""
base = self._get_base(path)
filename, pathname, description = imp.find_module('tarbell_config', [path])
project = imp.load_module('project', filename, pathname, description)
try:
self.key = project.SPREADSHEET_KEY
self.client = get_drive_api()
except AttributeError:
self.key = None
self.client = None
try:
project.CREATE_JSON
except AttributeError:
project.CREATE_JSON = False
try:
project.S3_BUCKETS
except AttributeError:
project.S3_BUCKETS = {}
project.EXCLUDES = list(set(EXCLUDES + getattr(project, 'EXCLUDES', []) + getattr(base, 'EXCLUDES', [])))
# merge project template types with defaults
project.TEMPLATE_TYPES = set(getattr(project, 'TEMPLATE_TYPES', [])) | set(TEMPLATE_TYPES)
try:
project.DEFAULT_CONTEXT
except AttributeError:
project.DEFAULT_CONTEXT = {}
project.DEFAULT_CONTEXT.update({
"PROJECT_PATH": self.path,
"ROOT_URL": "127.0.0.1:5000",
"SPREADSHEET_KEY": self.key,
"BUCKETS": project.S3_BUCKETS,
"SITE": self,
})
# Set up template loaders
template_dirs = [path]
if base:
template_dirs.append(base.base_dir)
error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates')
template_dirs.append(error_path)
self.app.jinja_loader = TarbellFileSystemLoader(template_dirs)
# load the project blueprint, if it exists
if hasattr(project, 'blueprint') and isinstance(project.blueprint, Blueprint):
self.app.register_blueprint(project.blueprint, site=self)
return project, base | python | def load_project(self, path):
"""
Load a Tarbell project
"""
base = self._get_base(path)
filename, pathname, description = imp.find_module('tarbell_config', [path])
project = imp.load_module('project', filename, pathname, description)
try:
self.key = project.SPREADSHEET_KEY
self.client = get_drive_api()
except AttributeError:
self.key = None
self.client = None
try:
project.CREATE_JSON
except AttributeError:
project.CREATE_JSON = False
try:
project.S3_BUCKETS
except AttributeError:
project.S3_BUCKETS = {}
project.EXCLUDES = list(set(EXCLUDES + getattr(project, 'EXCLUDES', []) + getattr(base, 'EXCLUDES', [])))
# merge project template types with defaults
project.TEMPLATE_TYPES = set(getattr(project, 'TEMPLATE_TYPES', [])) | set(TEMPLATE_TYPES)
try:
project.DEFAULT_CONTEXT
except AttributeError:
project.DEFAULT_CONTEXT = {}
project.DEFAULT_CONTEXT.update({
"PROJECT_PATH": self.path,
"ROOT_URL": "127.0.0.1:5000",
"SPREADSHEET_KEY": self.key,
"BUCKETS": project.S3_BUCKETS,
"SITE": self,
})
# Set up template loaders
template_dirs = [path]
if base:
template_dirs.append(base.base_dir)
error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates')
template_dirs.append(error_path)
self.app.jinja_loader = TarbellFileSystemLoader(template_dirs)
# load the project blueprint, if it exists
if hasattr(project, 'blueprint') and isinstance(project.blueprint, Blueprint):
self.app.register_blueprint(project.blueprint, site=self)
return project, base | [
"def",
"load_project",
"(",
"self",
",",
"path",
")",
":",
"base",
"=",
"self",
".",
"_get_base",
"(",
"path",
")",
"filename",
",",
"pathname",
",",
"description",
"=",
"imp",
".",
"find_module",
"(",
"'tarbell_config'",
",",
"[",
"path",
"]",
")",
"p... | Load a Tarbell project | [
"Load",
"a",
"Tarbell",
"project"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L257-L314 | train | 41,346 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite._resolve_path | def _resolve_path(self, path):
"""
Resolve static file paths
"""
filepath = None
mimetype = None
for root, dirs, files in self.filter_files(self.path):
# Does it exist in error path?
error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates', path)
try:
with open(error_path):
mimetype, encoding = mimetypes.guess_type(error_path)
filepath = error_path
except IOError:
pass
# Does it exist in Tarbell blueprint?
if self.base:
basepath = os.path.join(root, self.blueprint_name, path)
try:
with open(basepath):
mimetype, encoding = mimetypes.guess_type(basepath)
filepath = basepath
except IOError:
pass
# Does it exist under regular path?
fullpath = os.path.join(root, path)
try:
with open(fullpath):
mimetype, encoding = mimetypes.guess_type(fullpath)
filepath = fullpath
except IOError:
pass
return filepath, mimetype | python | def _resolve_path(self, path):
"""
Resolve static file paths
"""
filepath = None
mimetype = None
for root, dirs, files in self.filter_files(self.path):
# Does it exist in error path?
error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates', path)
try:
with open(error_path):
mimetype, encoding = mimetypes.guess_type(error_path)
filepath = error_path
except IOError:
pass
# Does it exist in Tarbell blueprint?
if self.base:
basepath = os.path.join(root, self.blueprint_name, path)
try:
with open(basepath):
mimetype, encoding = mimetypes.guess_type(basepath)
filepath = basepath
except IOError:
pass
# Does it exist under regular path?
fullpath = os.path.join(root, path)
try:
with open(fullpath):
mimetype, encoding = mimetypes.guess_type(fullpath)
filepath = fullpath
except IOError:
pass
return filepath, mimetype | [
"def",
"_resolve_path",
"(",
"self",
",",
"path",
")",
":",
"filepath",
"=",
"None",
"mimetype",
"=",
"None",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"self",
".",
"filter_files",
"(",
"self",
".",
"path",
")",
":",
"# Does it exist in error path?",... | Resolve static file paths | [
"Resolve",
"static",
"file",
"paths"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L316-L352 | train | 41,347 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.data_json | def data_json(self, extra_context=None, publish=False):
"""
Serve site context as JSON. Useful for debugging.
"""
if not self.project.CREATE_JSON:
# nothing to see here, but the right mimetype
return jsonify()
if not self.data:
# this sets site.data by spreadsheet or gdoc
self.get_context(publish)
return jsonify(self.data) | python | def data_json(self, extra_context=None, publish=False):
"""
Serve site context as JSON. Useful for debugging.
"""
if not self.project.CREATE_JSON:
# nothing to see here, but the right mimetype
return jsonify()
if not self.data:
# this sets site.data by spreadsheet or gdoc
self.get_context(publish)
return jsonify(self.data) | [
"def",
"data_json",
"(",
"self",
",",
"extra_context",
"=",
"None",
",",
"publish",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"project",
".",
"CREATE_JSON",
":",
"# nothing to see here, but the right mimetype",
"return",
"jsonify",
"(",
")",
"if",
"not... | Serve site context as JSON. Useful for debugging. | [
"Serve",
"site",
"context",
"as",
"JSON",
".",
"Useful",
"for",
"debugging",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L354-L366 | train | 41,348 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.preview | def preview(self, path=None, extra_context=None, publish=False):
"""
Serve up a project path
"""
try:
self.call_hook("preview", self)
if path is None:
path = 'index.html'
# Detect files
filepath, mimetype = self._resolve_path(path)
# Serve dynamic
if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
context = self.get_context(publish)
context.update({
"PATH": path,
"PREVIEW_SERVER": not publish,
"TIMESTAMP": int(time.time()),
})
if extra_context:
context.update(extra_context)
rendered = render_template(path, **context)
return Response(rendered, mimetype=mimetype)
# Serve static
if filepath:
dir, filename = os.path.split(filepath)
return send_from_directory(dir, filename)
except Exception as e:
ex_type, ex, tb = sys.exc_info()
try:
# Find template with name of error
cls = e.__class__
ex_type, ex, tb = sys.exc_info()
context = self.project.DEFAULT_CONTEXT
context.update({
'PATH': path,
'traceback': traceback.format_exception(ex_type, ex, tb),
'e': e,
})
if extra_context:
context.update(extra_context)
try:
error_path = '_{0}.{1}.html'.format(cls.__module__, cls.__name__)
rendered = render_template(error_path, **context)
except TemplateNotFound:
# Find template without underscore prefix, @TODO remove in v1.1
error_path = '{0}.{1}.html'.format(cls.__module__, cls.__name__)
rendered = render_template(error_path, **context)
return Response(rendered, mimetype="text/html")
except TemplateNotFound:
# Otherwise raise old error
reraise(ex_type, ex, tb)
# Last ditch effort -- see if path has "index.html" underneath it
if not path.endswith("index.html"):
if not path.endswith("/"):
path = "{0}/".format(path)
path = "{0}{1}".format(path, "index.html")
return self.preview(path)
# It's a 404
if path.endswith('/index.html'):
path = path[:-11]
rendered = render_template("404.html", PATH=path)
return Response(rendered, status=404) | python | def preview(self, path=None, extra_context=None, publish=False):
"""
Serve up a project path
"""
try:
self.call_hook("preview", self)
if path is None:
path = 'index.html'
# Detect files
filepath, mimetype = self._resolve_path(path)
# Serve dynamic
if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
context = self.get_context(publish)
context.update({
"PATH": path,
"PREVIEW_SERVER": not publish,
"TIMESTAMP": int(time.time()),
})
if extra_context:
context.update(extra_context)
rendered = render_template(path, **context)
return Response(rendered, mimetype=mimetype)
# Serve static
if filepath:
dir, filename = os.path.split(filepath)
return send_from_directory(dir, filename)
except Exception as e:
ex_type, ex, tb = sys.exc_info()
try:
# Find template with name of error
cls = e.__class__
ex_type, ex, tb = sys.exc_info()
context = self.project.DEFAULT_CONTEXT
context.update({
'PATH': path,
'traceback': traceback.format_exception(ex_type, ex, tb),
'e': e,
})
if extra_context:
context.update(extra_context)
try:
error_path = '_{0}.{1}.html'.format(cls.__module__, cls.__name__)
rendered = render_template(error_path, **context)
except TemplateNotFound:
# Find template without underscore prefix, @TODO remove in v1.1
error_path = '{0}.{1}.html'.format(cls.__module__, cls.__name__)
rendered = render_template(error_path, **context)
return Response(rendered, mimetype="text/html")
except TemplateNotFound:
# Otherwise raise old error
reraise(ex_type, ex, tb)
# Last ditch effort -- see if path has "index.html" underneath it
if not path.endswith("index.html"):
if not path.endswith("/"):
path = "{0}/".format(path)
path = "{0}{1}".format(path, "index.html")
return self.preview(path)
# It's a 404
if path.endswith('/index.html'):
path = path[:-11]
rendered = render_template("404.html", PATH=path)
return Response(rendered, status=404) | [
"def",
"preview",
"(",
"self",
",",
"path",
"=",
"None",
",",
"extra_context",
"=",
"None",
",",
"publish",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"call_hook",
"(",
"\"preview\"",
",",
"self",
")",
"if",
"path",
"is",
"None",
":",
"path",
... | Serve up a project path | [
"Serve",
"up",
"a",
"project",
"path"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L368-L440 | train | 41,349 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.get_context | def get_context(self, publish=False):
"""
Use optional CONTEXT_SOURCE_FILE setting to determine data source.
Return the parsed data.
Can be an http|https url or local file. Supports csv and excel files.
"""
context = self.project.DEFAULT_CONTEXT
try:
file = self.project.CONTEXT_SOURCE_FILE
# CSV
if re.search(r'(csv|CSV)$', file):
context.update(self.get_context_from_csv())
# Excel
if re.search(r'(xlsx|XLSX|xls|XLS)$', file):
context.update(self.get_context_from_xlsx())
except AttributeError:
context.update(self.get_context_from_gdoc())
return context | python | def get_context(self, publish=False):
"""
Use optional CONTEXT_SOURCE_FILE setting to determine data source.
Return the parsed data.
Can be an http|https url or local file. Supports csv and excel files.
"""
context = self.project.DEFAULT_CONTEXT
try:
file = self.project.CONTEXT_SOURCE_FILE
# CSV
if re.search(r'(csv|CSV)$', file):
context.update(self.get_context_from_csv())
# Excel
if re.search(r'(xlsx|XLSX|xls|XLS)$', file):
context.update(self.get_context_from_xlsx())
except AttributeError:
context.update(self.get_context_from_gdoc())
return context | [
"def",
"get_context",
"(",
"self",
",",
"publish",
"=",
"False",
")",
":",
"context",
"=",
"self",
".",
"project",
".",
"DEFAULT_CONTEXT",
"try",
":",
"file",
"=",
"self",
".",
"project",
".",
"CONTEXT_SOURCE_FILE",
"# CSV",
"if",
"re",
".",
"search",
"(... | Use optional CONTEXT_SOURCE_FILE setting to determine data source.
Return the parsed data.
Can be an http|https url or local file. Supports csv and excel files. | [
"Use",
"optional",
"CONTEXT_SOURCE_FILE",
"setting",
"to",
"determine",
"data",
"source",
".",
"Return",
"the",
"parsed",
"data",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L442-L461 | train | 41,350 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.get_context_from_xlsx | def get_context_from_xlsx(self):
"""
Get context from an Excel file
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
resp = requests.get(self.project.CONTEXT_SOURCE_FILE)
content = resp.content
else:
try:
with open(self.project.CONTEXT_SOURCE_FILE) as xlsxfile:
content = xlsxfile.read()
except IOError:
filepath = "%s/%s" % (
os.path.abspath(self.path),
self.project.CONTEXT_SOURCE_FILE)
with open(filepath) as xlsxfile:
content = xlsxfile.read()
data = process_xlsx(content)
if 'values' in data:
data = copy_global_values(data)
return data | python | def get_context_from_xlsx(self):
"""
Get context from an Excel file
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
resp = requests.get(self.project.CONTEXT_SOURCE_FILE)
content = resp.content
else:
try:
with open(self.project.CONTEXT_SOURCE_FILE) as xlsxfile:
content = xlsxfile.read()
except IOError:
filepath = "%s/%s" % (
os.path.abspath(self.path),
self.project.CONTEXT_SOURCE_FILE)
with open(filepath) as xlsxfile:
content = xlsxfile.read()
data = process_xlsx(content)
if 'values' in data:
data = copy_global_values(data)
return data | [
"def",
"get_context_from_xlsx",
"(",
"self",
")",
":",
"if",
"re",
".",
"search",
"(",
"'^(http|https)://'",
",",
"self",
".",
"project",
".",
"CONTEXT_SOURCE_FILE",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"project",
".",
"CONTEXT_... | Get context from an Excel file | [
"Get",
"context",
"from",
"an",
"Excel",
"file"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L463-L485 | train | 41,351 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.get_context_from_csv | def get_context_from_csv(self):
"""
Open CONTEXT_SOURCE_FILE, parse and return a context
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
data = requests.get(self.project.CONTEXT_SOURCE_FILE)
reader = csv.reader(
data.iter_lines(), delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
else:
try:
with open(self.project.CONTEXT_SOURCE_FILE) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
except IOError:
file = "%s/%s" % (
os.path.abspath(self.path),
self.project.CONTEXT_SOURCE_FILE)
with open(file) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
ret.update({
"CONTEXT_SOURCE_FILE": self.project.CONTEXT_SOURCE_FILE,
})
return ret | python | def get_context_from_csv(self):
"""
Open CONTEXT_SOURCE_FILE, parse and return a context
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
data = requests.get(self.project.CONTEXT_SOURCE_FILE)
reader = csv.reader(
data.iter_lines(), delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
else:
try:
with open(self.project.CONTEXT_SOURCE_FILE) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
except IOError:
file = "%s/%s" % (
os.path.abspath(self.path),
self.project.CONTEXT_SOURCE_FILE)
with open(file) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
ret = {rows[0]: rows[1] for rows in reader}
ret.update({
"CONTEXT_SOURCE_FILE": self.project.CONTEXT_SOURCE_FILE,
})
return ret | [
"def",
"get_context_from_csv",
"(",
"self",
")",
":",
"if",
"re",
".",
"search",
"(",
"'^(http|https)://'",
",",
"self",
".",
"project",
".",
"CONTEXT_SOURCE_FILE",
")",
":",
"data",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"project",
".",
"CONTEXT_S... | Open CONTEXT_SOURCE_FILE, parse and return a context | [
"Open",
"CONTEXT_SOURCE_FILE",
"parse",
"and",
"return",
"a",
"context"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L487-L511 | train | 41,352 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.get_context_from_gdoc | def get_context_from_gdoc(self):
"""
Wrap getting context from Google sheets in a simple caching mechanism.
"""
try:
start = int(time.time())
if not self.data or start > self.expires:
self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY)
end = int(time.time())
ttl = getattr(self.project, 'SPREADSHEET_CACHE_TTL',
SPREADSHEET_CACHE_TTL)
self.expires = end + ttl
return self.data
except AttributeError:
return {} | python | def get_context_from_gdoc(self):
"""
Wrap getting context from Google sheets in a simple caching mechanism.
"""
try:
start = int(time.time())
if not self.data or start > self.expires:
self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY)
end = int(time.time())
ttl = getattr(self.project, 'SPREADSHEET_CACHE_TTL',
SPREADSHEET_CACHE_TTL)
self.expires = end + ttl
return self.data
except AttributeError:
return {} | [
"def",
"get_context_from_gdoc",
"(",
"self",
")",
":",
"try",
":",
"start",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"if",
"not",
"self",
".",
"data",
"or",
"start",
">",
"self",
".",
"expires",
":",
"self",
".",
"data",
"=",
"self",
... | Wrap getting context from Google sheets in a simple caching mechanism. | [
"Wrap",
"getting",
"context",
"from",
"Google",
"sheets",
"in",
"a",
"simple",
"caching",
"mechanism",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L513-L527 | train | 41,353 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite._get_context_from_gdoc | def _get_context_from_gdoc(self, key):
"""
Create a Jinja2 context from a Google spreadsheet.
"""
try:
content = self.export_xlsx(key)
data = process_xlsx(content)
if 'values' in data:
data = copy_global_values(data)
return data
except BadStatusLine:
# Stale connection, reset API and data
puts("Connection reset, reloading drive API")
self.client = get_drive_api()
return self._get_context_from_gdoc(key) | python | def _get_context_from_gdoc(self, key):
"""
Create a Jinja2 context from a Google spreadsheet.
"""
try:
content = self.export_xlsx(key)
data = process_xlsx(content)
if 'values' in data:
data = copy_global_values(data)
return data
except BadStatusLine:
# Stale connection, reset API and data
puts("Connection reset, reloading drive API")
self.client = get_drive_api()
return self._get_context_from_gdoc(key) | [
"def",
"_get_context_from_gdoc",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"content",
"=",
"self",
".",
"export_xlsx",
"(",
"key",
")",
"data",
"=",
"process_xlsx",
"(",
"content",
")",
"if",
"'values'",
"in",
"data",
":",
"data",
"=",
"copy_global_... | Create a Jinja2 context from a Google spreadsheet. | [
"Create",
"a",
"Jinja2",
"context",
"from",
"a",
"Google",
"spreadsheet",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L529-L543 | train | 41,354 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.export_xlsx | def export_xlsx(self, key):
"""
Download xlsx version of spreadsheet.
"""
spreadsheet_file = self.client.files().get(fileId=key).execute()
links = spreadsheet_file.get('exportLinks')
downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
resp, content = self.client._http.request(downloadurl)
return content | python | def export_xlsx(self, key):
"""
Download xlsx version of spreadsheet.
"""
spreadsheet_file = self.client.files().get(fileId=key).execute()
links = spreadsheet_file.get('exportLinks')
downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
resp, content = self.client._http.request(downloadurl)
return content | [
"def",
"export_xlsx",
"(",
"self",
",",
"key",
")",
":",
"spreadsheet_file",
"=",
"self",
".",
"client",
".",
"files",
"(",
")",
".",
"get",
"(",
"fileId",
"=",
"key",
")",
".",
"execute",
"(",
")",
"links",
"=",
"spreadsheet_file",
".",
"get",
"(",
... | Download xlsx version of spreadsheet. | [
"Download",
"xlsx",
"version",
"of",
"spreadsheet",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L545-L553 | train | 41,355 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.generate_static_site | def generate_static_site(self, output_root=None, extra_context=None):
"""
Bake out static site
"""
self.app.config['BUILD_PATH'] = output_root
# use this hook for registering URLs to freeze
self.call_hook("generate", self, output_root, extra_context)
if output_root is not None:
# realpath or this gets generated relative to the tarbell package
self.app.config['FREEZER_DESTINATION'] = os.path.realpath(output_root)
self.freezer.freeze() | python | def generate_static_site(self, output_root=None, extra_context=None):
"""
Bake out static site
"""
self.app.config['BUILD_PATH'] = output_root
# use this hook for registering URLs to freeze
self.call_hook("generate", self, output_root, extra_context)
if output_root is not None:
# realpath or this gets generated relative to the tarbell package
self.app.config['FREEZER_DESTINATION'] = os.path.realpath(output_root)
self.freezer.freeze() | [
"def",
"generate_static_site",
"(",
"self",
",",
"output_root",
"=",
"None",
",",
"extra_context",
"=",
"None",
")",
":",
"self",
".",
"app",
".",
"config",
"[",
"'BUILD_PATH'",
"]",
"=",
"output_root",
"# use this hook for registering URLs to freeze",
"self",
"."... | Bake out static site | [
"Bake",
"out",
"static",
"site"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L555-L568 | train | 41,356 |
tarbell-project/tarbell | tarbell/app.py | TarbellSite.filter_files | def filter_files(self, path):
"""
Exclude files based on blueprint and project configuration as well as hidden files.
"""
excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.'
for root, dirs, files in os.walk(path, topdown=True):
dirs[:] = [d for d in dirs if not re.match(excludes, d)]
dirs[:] = [os.path.join(root, d) for d in dirs]
rel_path = os.path.relpath(root, path)
paths = []
for f in files:
if rel_path == '.':
file_path = f
else:
file_path = os.path.join(rel_path, f)
if not re.match(excludes, file_path):
paths.append(f)
files[:] = paths
yield root, dirs, files | python | def filter_files(self, path):
"""
Exclude files based on blueprint and project configuration as well as hidden files.
"""
excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.'
for root, dirs, files in os.walk(path, topdown=True):
dirs[:] = [d for d in dirs if not re.match(excludes, d)]
dirs[:] = [os.path.join(root, d) for d in dirs]
rel_path = os.path.relpath(root, path)
paths = []
for f in files:
if rel_path == '.':
file_path = f
else:
file_path = os.path.join(rel_path, f)
if not re.match(excludes, file_path):
paths.append(f)
files[:] = paths
yield root, dirs, files | [
"def",
"filter_files",
"(",
"self",
",",
"path",
")",
":",
"excludes",
"=",
"r'|'",
".",
"join",
"(",
"[",
"fnmatch",
".",
"translate",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"project",
".",
"EXCLUDES",
"]",
")",
"or",
"r'$.'",
"for",
"root"... | Exclude files based on blueprint and project configuration as well as hidden files. | [
"Exclude",
"files",
"based",
"on",
"blueprint",
"and",
"project",
"configuration",
"as",
"well",
"as",
"hidden",
"files",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L570-L590 | train | 41,357 |
tarbell-project/tarbell | tarbell/s3.py | S3Sync.deploy_to_s3 | def deploy_to_s3(self):
"""
Deploy a directory to an s3 bucket.
"""
self.tempdir = tempfile.mkdtemp('s3deploy')
for keyname, absolute_path in self.find_file_paths():
self.s3_upload(keyname, absolute_path)
shutil.rmtree(self.tempdir, True)
return True | python | def deploy_to_s3(self):
"""
Deploy a directory to an s3 bucket.
"""
self.tempdir = tempfile.mkdtemp('s3deploy')
for keyname, absolute_path in self.find_file_paths():
self.s3_upload(keyname, absolute_path)
shutil.rmtree(self.tempdir, True)
return True | [
"def",
"deploy_to_s3",
"(",
"self",
")",
":",
"self",
".",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'s3deploy'",
")",
"for",
"keyname",
",",
"absolute_path",
"in",
"self",
".",
"find_file_paths",
"(",
")",
":",
"self",
".",
"s3_upload",
"(",
"ke... | Deploy a directory to an s3 bucket. | [
"Deploy",
"a",
"directory",
"to",
"an",
"s3",
"bucket",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/s3.py#L54-L64 | train | 41,358 |
tarbell-project/tarbell | tarbell/s3.py | S3Sync.s3_upload | def s3_upload(self, keyname, absolute_path):
"""
Upload a file to s3
"""
mimetype = mimetypes.guess_type(absolute_path)
options = {'Content-Type': mimetype[0]}
if mimetype[0] is not None and mimetype[0].startswith('text/'):
upload = open(absolute_path, 'rb')
options['Content-Encoding'] = 'gzip'
key_parts = keyname.split('/')
filename = key_parts.pop()
temp_path = os.path.join(self.tempdir, filename)
gzfile = gzip.GzipFile(temp_path, 'wb', 9, None, GZIP_TIMESTAMP)
gzfile.write(upload.read())
gzfile.close()
absolute_path = temp_path
hash = '"{0}"'.format(hashlib.md5(open(absolute_path, 'rb').read()).hexdigest())
key = "{0}/{1}".format(self.bucket.path, keyname)
existing = self.connection.get_key(key)
if self.force or not existing or (existing.etag != hash):
k = Key(self.connection)
k.key = key
puts("+ Uploading {0}/{1}".format(self.bucket, keyname))
k.set_contents_from_filename(absolute_path, options, policy='public-read')
else:
puts("- Skipping {0}/{1}, files match".format(self.bucket, keyname)) | python | def s3_upload(self, keyname, absolute_path):
"""
Upload a file to s3
"""
mimetype = mimetypes.guess_type(absolute_path)
options = {'Content-Type': mimetype[0]}
if mimetype[0] is not None and mimetype[0].startswith('text/'):
upload = open(absolute_path, 'rb')
options['Content-Encoding'] = 'gzip'
key_parts = keyname.split('/')
filename = key_parts.pop()
temp_path = os.path.join(self.tempdir, filename)
gzfile = gzip.GzipFile(temp_path, 'wb', 9, None, GZIP_TIMESTAMP)
gzfile.write(upload.read())
gzfile.close()
absolute_path = temp_path
hash = '"{0}"'.format(hashlib.md5(open(absolute_path, 'rb').read()).hexdigest())
key = "{0}/{1}".format(self.bucket.path, keyname)
existing = self.connection.get_key(key)
if self.force or not existing or (existing.etag != hash):
k = Key(self.connection)
k.key = key
puts("+ Uploading {0}/{1}".format(self.bucket, keyname))
k.set_contents_from_filename(absolute_path, options, policy='public-read')
else:
puts("- Skipping {0}/{1}, files match".format(self.bucket, keyname)) | [
"def",
"s3_upload",
"(",
"self",
",",
"keyname",
",",
"absolute_path",
")",
":",
"mimetype",
"=",
"mimetypes",
".",
"guess_type",
"(",
"absolute_path",
")",
"options",
"=",
"{",
"'Content-Type'",
":",
"mimetype",
"[",
"0",
"]",
"}",
"if",
"mimetype",
"[",
... | Upload a file to s3 | [
"Upload",
"a",
"file",
"to",
"s3"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/s3.py#L66-L94 | train | 41,359 |
tarbell-project/tarbell | tarbell/s3.py | S3Sync.find_file_paths | def find_file_paths(self):
"""
A generator function that recursively finds all files in the upload directory.
"""
paths = []
for root, dirs, files in os.walk(self.directory, topdown=True):
rel_path = os.path.relpath(root, self.directory)
for f in files:
if rel_path == '.':
path = (f, os.path.join(root, f))
else:
path = (os.path.join(rel_path, f), os.path.join(root, f))
paths.append(path)
return paths | python | def find_file_paths(self):
"""
A generator function that recursively finds all files in the upload directory.
"""
paths = []
for root, dirs, files in os.walk(self.directory, topdown=True):
rel_path = os.path.relpath(root, self.directory)
for f in files:
if rel_path == '.':
path = (f, os.path.join(root, f))
else:
path = (os.path.join(rel_path, f), os.path.join(root, f))
paths.append(path)
return paths | [
"def",
"find_file_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"directory",
",",
"topdown",
"=",
"True",
")",
":",
"rel_path",
"=",
"os",
".",
"path",
... | A generator function that recursively finds all files in the upload directory. | [
"A",
"generator",
"function",
"that",
"recursively",
"finds",
"all",
"files",
"in",
"the",
"upload",
"directory",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/s3.py#L97-L110 | train | 41,360 |
tarbell-project/tarbell | tarbell/oauth.py | get_drive_api | def get_drive_api():
"""
Get drive API client based on settings.
"""
settings = Settings()
if settings.credentials:
return get_drive_api_from_file(settings.credentials_path)
if settings.client_secrets:
return get_drive_api_from_client_secrets(settings.client_secrets_path) | python | def get_drive_api():
"""
Get drive API client based on settings.
"""
settings = Settings()
if settings.credentials:
return get_drive_api_from_file(settings.credentials_path)
if settings.client_secrets:
return get_drive_api_from_client_secrets(settings.client_secrets_path) | [
"def",
"get_drive_api",
"(",
")",
":",
"settings",
"=",
"Settings",
"(",
")",
"if",
"settings",
".",
"credentials",
":",
"return",
"get_drive_api_from_file",
"(",
"settings",
".",
"credentials_path",
")",
"if",
"settings",
".",
"client_secrets",
":",
"return",
... | Get drive API client based on settings. | [
"Get",
"drive",
"API",
"client",
"based",
"on",
"settings",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/oauth.py#L24-L34 | train | 41,361 |
tarbell-project/tarbell | tarbell/oauth.py | get_drive_api_from_file | def get_drive_api_from_file(path):
"""
Open file with OAuth tokens.
"""
f = open(path)
credentials = client.OAuth2Credentials.from_json(f.read())
return _get_drive_api(credentials) | python | def get_drive_api_from_file(path):
"""
Open file with OAuth tokens.
"""
f = open(path)
credentials = client.OAuth2Credentials.from_json(f.read())
return _get_drive_api(credentials) | [
"def",
"get_drive_api_from_file",
"(",
"path",
")",
":",
"f",
"=",
"open",
"(",
"path",
")",
"credentials",
"=",
"client",
".",
"OAuth2Credentials",
".",
"from_json",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"_get_drive_api",
"(",
"credentials",
")"... | Open file with OAuth tokens. | [
"Open",
"file",
"with",
"OAuth",
"tokens",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/oauth.py#L56-L62 | train | 41,362 |
tarbell-project/tarbell | tarbell/oauth.py | _get_drive_api | def _get_drive_api(credentials):
"""
For a given set of credentials, return a drive API object.
"""
http = httplib2.Http()
http = credentials.authorize(http)
service = discovery.build('drive', 'v2', http=http)
service.credentials = credentials # duck punch service obj. with credentials
return service | python | def _get_drive_api(credentials):
"""
For a given set of credentials, return a drive API object.
"""
http = httplib2.Http()
http = credentials.authorize(http)
service = discovery.build('drive', 'v2', http=http)
service.credentials = credentials # duck punch service obj. with credentials
return service | [
"def",
"_get_drive_api",
"(",
"credentials",
")",
":",
"http",
"=",
"httplib2",
".",
"Http",
"(",
")",
"http",
"=",
"credentials",
".",
"authorize",
"(",
"http",
")",
"service",
"=",
"discovery",
".",
"build",
"(",
"'drive'",
",",
"'v2'",
",",
"http",
... | For a given set of credentials, return a drive API object. | [
"For",
"a",
"given",
"set",
"of",
"credentials",
"return",
"a",
"drive",
"API",
"object",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/oauth.py#L65-L73 | train | 41,363 |
tarbell-project/tarbell | tarbell/cli.py | main | def main():
"""
Primary Tarbell command dispatch.
"""
command = Command.lookup(args.get(0))
if len(args) == 0 or args.contains(('-h', '--help', 'help')):
display_info(args)
sys.exit(1)
elif args.contains(('-v', '--version')):
display_version()
sys.exit(1)
elif command:
arg = args.get(0)
args.remove(arg)
command.__call__(command, args)
sys.exit()
else:
show_error(colored.red('Error! Unknown command \'{0}\'.\n'
.format(args.get(0))))
display_info(args)
sys.exit(1) | python | def main():
"""
Primary Tarbell command dispatch.
"""
command = Command.lookup(args.get(0))
if len(args) == 0 or args.contains(('-h', '--help', 'help')):
display_info(args)
sys.exit(1)
elif args.contains(('-v', '--version')):
display_version()
sys.exit(1)
elif command:
arg = args.get(0)
args.remove(arg)
command.__call__(command, args)
sys.exit()
else:
show_error(colored.red('Error! Unknown command \'{0}\'.\n'
.format(args.get(0))))
display_info(args)
sys.exit(1) | [
"def",
"main",
"(",
")",
":",
"command",
"=",
"Command",
".",
"lookup",
"(",
"args",
".",
"get",
"(",
"0",
")",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"or",
"args",
".",
"contains",
"(",
"(",
"'-h'",
",",
"'--help'",
",",
"'help'",
")",... | Primary Tarbell command dispatch. | [
"Primary",
"Tarbell",
"command",
"dispatch",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L59-L83 | train | 41,364 |
tarbell-project/tarbell | tarbell/cli.py | display_info | def display_info(args):
"""
Displays Tarbell info.
"""
puts('\nTarbell: Simple web publishing\n')
puts('Usage: {0}\n'.format(colored.cyan('tarbell <command>')))
puts('Commands:\n')
for command in Command.all_commands():
usage = command.usage or command.name
help = command.help or ''
puts('{0} {1}'.format(
colored.yellow('{0: <37}'.format(usage)),
split_sentences(help, 37)
))
puts("")
settings = Settings()
if settings.file_missing:
puts('---\n{0}: {1}'.format(
colored.red("Warning"),
"No Tarbell configuration found. Run:"
))
puts('\n{0}'.format(
colored.green("tarbell configure")
))
puts('\n{0}\n---'.format(
"to configure Tarbell."
)) | python | def display_info(args):
"""
Displays Tarbell info.
"""
puts('\nTarbell: Simple web publishing\n')
puts('Usage: {0}\n'.format(colored.cyan('tarbell <command>')))
puts('Commands:\n')
for command in Command.all_commands():
usage = command.usage or command.name
help = command.help or ''
puts('{0} {1}'.format(
colored.yellow('{0: <37}'.format(usage)),
split_sentences(help, 37)
))
puts("")
settings = Settings()
if settings.file_missing:
puts('---\n{0}: {1}'.format(
colored.red("Warning"),
"No Tarbell configuration found. Run:"
))
puts('\n{0}'.format(
colored.green("tarbell configure")
))
puts('\n{0}\n---'.format(
"to configure Tarbell."
)) | [
"def",
"display_info",
"(",
"args",
")",
":",
"puts",
"(",
"'\\nTarbell: Simple web publishing\\n'",
")",
"puts",
"(",
"'Usage: {0}\\n'",
".",
"format",
"(",
"colored",
".",
"cyan",
"(",
"'tarbell <command>'",
")",
")",
")",
"puts",
"(",
"'Commands:\\n'",
")",
... | Displays Tarbell info. | [
"Displays",
"Tarbell",
"info",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L86-L114 | train | 41,365 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_generate | def tarbell_generate(command, args, skip_args=False, extra_context=None, quiet=False):
"""
Generate static files.
"""
output_root = None
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
if not skip_args:
output_root = list_get(args, 0, False)
if output_root:
is_folder = os.path.exists(output_root)
else:
puts("\nYou must specify an output directory (e.g. `{0}`)".format(
colored.cyan("tarbell generate _out")
))
sys.exit()
if quiet:
site.quiet = True
if not output_root:
output_root = tempfile.mkdtemp(prefix="{0}-".format(site.project.__name__))
is_folder = False
if args.contains('--context'):
site.project.CONTEXT_SOURCE_FILE = args.value_after('--context')
if args.contains('--overwrite'):
is_folder = False
#check to see if the folder we're trying to create already exists
if is_folder:
output_file = raw_input(("\nA folder named {0} already exists! Do you want to delete it? (selecting 'N' will quit) [y/N] ").format(
output_root
))
if output_file and output_file.lower() == "y":
puts(("\nDeleting {0}...\n").format(
colored.cyan(output_root)
))
_delete_dir(output_root)
else:
puts("\nNot overwriting. See ya!")
sys.exit()
site.generate_static_site(output_root, extra_context)
if not quiet:
puts("\nCreated site in {0}".format(colored.cyan(output_root)))
return output_root | python | def tarbell_generate(command, args, skip_args=False, extra_context=None, quiet=False):
"""
Generate static files.
"""
output_root = None
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
if not skip_args:
output_root = list_get(args, 0, False)
if output_root:
is_folder = os.path.exists(output_root)
else:
puts("\nYou must specify an output directory (e.g. `{0}`)".format(
colored.cyan("tarbell generate _out")
))
sys.exit()
if quiet:
site.quiet = True
if not output_root:
output_root = tempfile.mkdtemp(prefix="{0}-".format(site.project.__name__))
is_folder = False
if args.contains('--context'):
site.project.CONTEXT_SOURCE_FILE = args.value_after('--context')
if args.contains('--overwrite'):
is_folder = False
#check to see if the folder we're trying to create already exists
if is_folder:
output_file = raw_input(("\nA folder named {0} already exists! Do you want to delete it? (selecting 'N' will quit) [y/N] ").format(
output_root
))
if output_file and output_file.lower() == "y":
puts(("\nDeleting {0}...\n").format(
colored.cyan(output_root)
))
_delete_dir(output_root)
else:
puts("\nNot overwriting. See ya!")
sys.exit()
site.generate_static_site(output_root, extra_context)
if not quiet:
puts("\nCreated site in {0}".format(colored.cyan(output_root)))
return output_root | [
"def",
"tarbell_generate",
"(",
"command",
",",
"args",
",",
"skip_args",
"=",
"False",
",",
"extra_context",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"output_root",
"=",
"None",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
... | Generate static files. | [
"Generate",
"static",
"files",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L126-L176 | train | 41,366 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_install | def tarbell_install(command, args):
"""
Install a project.
"""
with ensure_settings(command, args) as settings:
project_url = args.get(0)
puts("\n- Getting project information for {0}".format(project_url))
project_name = project_url.split("/").pop()
error = None
# Create a tempdir and clone
tempdir = tempfile.mkdtemp()
try:
testgit = sh.git.bake(_cwd=tempdir, _tty_in=True, _tty_out=False) # _err_to_out=True)
testclone = testgit.clone(project_url, '.', '--depth=1', '--bare')
puts(testclone)
config = testgit.show("HEAD:tarbell_config.py")
puts("\n- Found tarbell_config.py")
path = _get_path(_clean_suffix(project_name, ".git"), settings)
_mkdir(path)
git = sh.git.bake(_cwd=path)
clone = git.clone(project_url, '.', _tty_in=True, _tty_out=False, _err_to_out=True)
puts(clone)
puts(git.submodule.update('--init', '--recursive', _tty_in=True, _tty_out=False, _err_to_out=True))
_install_requirements(path)
# Get site, run hook
with ensure_project(command, args, path) as site:
site.call_hook("install", site, git)
except sh.ErrorReturnCode_128 as e:
if e.message.endswith('Device not configured\n'):
error = 'Git tried to prompt for a username or password.\n\nTarbell doesn\'t support interactive sessions. Please configure ssh key access to your Git repository. (See https://help.github.com/articles/generating-ssh-keys/)'
else:
error = 'Not a valid repository or Tarbell project'
finally:
_delete_dir(tempdir)
if error:
show_error(error)
else:
puts("\n- Done installing project in {0}".format(colored.yellow(path))) | python | def tarbell_install(command, args):
"""
Install a project.
"""
with ensure_settings(command, args) as settings:
project_url = args.get(0)
puts("\n- Getting project information for {0}".format(project_url))
project_name = project_url.split("/").pop()
error = None
# Create a tempdir and clone
tempdir = tempfile.mkdtemp()
try:
testgit = sh.git.bake(_cwd=tempdir, _tty_in=True, _tty_out=False) # _err_to_out=True)
testclone = testgit.clone(project_url, '.', '--depth=1', '--bare')
puts(testclone)
config = testgit.show("HEAD:tarbell_config.py")
puts("\n- Found tarbell_config.py")
path = _get_path(_clean_suffix(project_name, ".git"), settings)
_mkdir(path)
git = sh.git.bake(_cwd=path)
clone = git.clone(project_url, '.', _tty_in=True, _tty_out=False, _err_to_out=True)
puts(clone)
puts(git.submodule.update('--init', '--recursive', _tty_in=True, _tty_out=False, _err_to_out=True))
_install_requirements(path)
# Get site, run hook
with ensure_project(command, args, path) as site:
site.call_hook("install", site, git)
except sh.ErrorReturnCode_128 as e:
if e.message.endswith('Device not configured\n'):
error = 'Git tried to prompt for a username or password.\n\nTarbell doesn\'t support interactive sessions. Please configure ssh key access to your Git repository. (See https://help.github.com/articles/generating-ssh-keys/)'
else:
error = 'Not a valid repository or Tarbell project'
finally:
_delete_dir(tempdir)
if error:
show_error(error)
else:
puts("\n- Done installing project in {0}".format(colored.yellow(path))) | [
"def",
"tarbell_install",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"project_url",
"=",
"args",
".",
"get",
"(",
"0",
")",
"puts",
"(",
"\"\\n- Getting project information for {0}... | Install a project. | [
"Install",
"a",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L179-L219 | train | 41,367 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_install_blueprint | def tarbell_install_blueprint(command, args):
"""
Install a project template.
"""
with ensure_settings(command, args) as settings:
name = None
error = None
template_url = args.get(0)
matches = [template for template in settings.config["project_templates"] if template.get("url") == template_url]
tempdir = tempfile.mkdtemp()
if matches:
puts("\n{0} already exists. Nothing more to do.\n".format(
colored.yellow(template_url)
))
sys.exit()
try:
puts("\nInstalling {0}".format(colored.cyan(template_url)))
puts("\n- Cloning repo")
git = sh.git.bake(_cwd=tempdir, _tty_in=True, _tty_out=False, _err_to_out=True)
puts(git.clone(template_url, '.'))
_install_requirements(tempdir)
filename, pathname, description = imp.find_module('blueprint', [tempdir])
blueprint = imp.load_module('blueprint', filename, pathname, description)
puts("\n- Found _blueprint/blueprint.py")
name = blueprint.NAME
puts("\n- Name specified in blueprint.py: {0}".format(colored.yellow(name)))
settings.config["project_templates"].append({"name": name, "url": template_url})
settings.save()
except AttributeError:
name = template_url.split("/")[-1]
error = "\n- No name specified in blueprint.py, using '{0}'".format(colored.yellow(name))
except ImportError:
error = 'No blueprint.py found'
except sh.ErrorReturnCode_128 as e:
if e.stdout.strip('\n').endswith('Device not configured'):
error = 'Git tried to prompt for a username or password.\n\nTarbell doesn\'t support interactive sessions. Please configure ssh key access to your Git repository. (See https://help.github.com/articles/generating-ssh-keys/)'
else:
error = 'Not a valid repository or Tarbell project'
finally:
_delete_dir(tempdir)
if error:
show_error(error)
else:
puts("\n+ Added new project template: {0}".format(colored.yellow(name))) | python | def tarbell_install_blueprint(command, args):
"""
Install a project template.
"""
with ensure_settings(command, args) as settings:
name = None
error = None
template_url = args.get(0)
matches = [template for template in settings.config["project_templates"] if template.get("url") == template_url]
tempdir = tempfile.mkdtemp()
if matches:
puts("\n{0} already exists. Nothing more to do.\n".format(
colored.yellow(template_url)
))
sys.exit()
try:
puts("\nInstalling {0}".format(colored.cyan(template_url)))
puts("\n- Cloning repo")
git = sh.git.bake(_cwd=tempdir, _tty_in=True, _tty_out=False, _err_to_out=True)
puts(git.clone(template_url, '.'))
_install_requirements(tempdir)
filename, pathname, description = imp.find_module('blueprint', [tempdir])
blueprint = imp.load_module('blueprint', filename, pathname, description)
puts("\n- Found _blueprint/blueprint.py")
name = blueprint.NAME
puts("\n- Name specified in blueprint.py: {0}".format(colored.yellow(name)))
settings.config["project_templates"].append({"name": name, "url": template_url})
settings.save()
except AttributeError:
name = template_url.split("/")[-1]
error = "\n- No name specified in blueprint.py, using '{0}'".format(colored.yellow(name))
except ImportError:
error = 'No blueprint.py found'
except sh.ErrorReturnCode_128 as e:
if e.stdout.strip('\n').endswith('Device not configured'):
error = 'Git tried to prompt for a username or password.\n\nTarbell doesn\'t support interactive sessions. Please configure ssh key access to your Git repository. (See https://help.github.com/articles/generating-ssh-keys/)'
else:
error = 'Not a valid repository or Tarbell project'
finally:
_delete_dir(tempdir)
if error:
show_error(error)
else:
puts("\n+ Added new project template: {0}".format(colored.yellow(name))) | [
"def",
"tarbell_install_blueprint",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"name",
"=",
"None",
"error",
"=",
"None",
"template_url",
"=",
"args",
".",
"get",
"(",
"0",
"... | Install a project template. | [
"Install",
"a",
"project",
"template",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L222-L272 | train | 41,368 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_list | def tarbell_list(command, args):
"""
List tarbell projects.
"""
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
puts("Listing projects in {0}\n".format(
colored.yellow(projects_path)
))
longest_title = 0
projects = []
for directory in os.listdir(projects_path):
project_path = os.path.join(projects_path, directory)
try:
filename, pathname, description = imp.find_module('tarbell_config', [project_path])
config = imp.load_module(directory, filename, pathname, description)
title = config.DEFAULT_CONTEXT.get("title", directory)
projects.append((directory, title))
if len(title) > longest_title:
longest_title = len(title)
except ImportError:
pass
if len(projects):
fmt = "{0: <"+str(longest_title+1)+"} {1}"
puts(fmt.format(
'title',
'project name'
))
for projectname, title in projects:
title = codecs.encode(title, 'utf8')
puts(colored.yellow(fmt.format(
title,
colored.cyan(projectname)
)))
puts("\nUse {0} to switch to a project".format(
colored.green("tarbell switch <project name>")
))
else:
puts("No projects found") | python | def tarbell_list(command, args):
"""
List tarbell projects.
"""
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
puts("Listing projects in {0}\n".format(
colored.yellow(projects_path)
))
longest_title = 0
projects = []
for directory in os.listdir(projects_path):
project_path = os.path.join(projects_path, directory)
try:
filename, pathname, description = imp.find_module('tarbell_config', [project_path])
config = imp.load_module(directory, filename, pathname, description)
title = config.DEFAULT_CONTEXT.get("title", directory)
projects.append((directory, title))
if len(title) > longest_title:
longest_title = len(title)
except ImportError:
pass
if len(projects):
fmt = "{0: <"+str(longest_title+1)+"} {1}"
puts(fmt.format(
'title',
'project name'
))
for projectname, title in projects:
title = codecs.encode(title, 'utf8')
puts(colored.yellow(fmt.format(
title,
colored.cyan(projectname)
)))
puts("\nUse {0} to switch to a project".format(
colored.green("tarbell switch <project name>")
))
else:
puts("No projects found") | [
"def",
"tarbell_list",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"projects_path",
"=",
"settings",
".",
"config",
".",
"get",
"(",
"\"projects_path\"",
")",
"if",
"not",
"proj... | List tarbell projects. | [
"List",
"tarbell",
"projects",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L275-L320 | train | 41,369 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_list_templates | def tarbell_list_templates(command, args):
"""
List available Tarbell blueprints.
"""
with ensure_settings(command, args) as settings:
puts("\nAvailable project templates\n")
_list_templates(settings)
puts("") | python | def tarbell_list_templates(command, args):
"""
List available Tarbell blueprints.
"""
with ensure_settings(command, args) as settings:
puts("\nAvailable project templates\n")
_list_templates(settings)
puts("") | [
"def",
"tarbell_list_templates",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"puts",
"(",
"\"\\nAvailable project templates\\n\"",
")",
"_list_templates",
"(",
"settings",
")",
"puts",
... | List available Tarbell blueprints. | [
"List",
"available",
"Tarbell",
"blueprints",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L322-L329 | train | 41,370 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_publish | def tarbell_publish(command, args):
"""
Publish to s3.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
bucket_name = list_get(args, 0, "staging")
try:
bucket_url = S3Url(site.project.S3_BUCKETS[bucket_name])
except KeyError:
show_error(
"\nThere's no bucket configuration called '{0}' in "
"tarbell_config.py.".format(colored.yellow(bucket_name)))
sys.exit(1)
extra_context = {
"ROOT_URL": bucket_url,
"S3_BUCKET": bucket_url.root,
"BUCKET_NAME": bucket_name,
}
tempdir = "{0}/".format(tarbell_generate(command,
args, extra_context=extra_context, skip_args=True, quiet=True))
try:
title = site.project.DEFAULT_CONTEXT.get("title", "")
puts("\nDeploying {0} to {1} ({2})\n".format(
colored.yellow(title),
colored.red(bucket_name),
colored.green(bucket_url)
))
# Get creds
if settings.config:
# If settings has a config section, use it
kwargs = settings.config['s3_credentials'].get(bucket_url.root)
if not kwargs:
kwargs = {
'access_key_id': settings.config.get('default_s3_access_key_id'),
'secret_access_key': settings.config.get('default_s3_secret_access_key'),
}
puts("Using default bucket credentials")
else:
puts("Using custom bucket configuration for {0}".format(bucket_url.root))
else:
# If no configuration exists, read from environment variables if possible
puts("Attemping to use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY")
kwargs = {
'access_key_id': os.environ["AWS_ACCESS_KEY_ID"],
'secret_access_key': os.environ["AWS_SECRET_ACCESS_KEY"],
}
if not kwargs.get('access_key_id') and not kwargs.get('secret_access_key'):
show_error('S3 access is not configured. Set up S3 with {0} to publish.'
.format(colored.green('tarbell configure')))
sys.exit()
s3 = S3Sync(tempdir, bucket_url, **kwargs)
s3.deploy_to_s3()
site.call_hook("publish", site, s3)
puts("\nIf you have website hosting enabled, you can see your project at:")
puts(colored.green("http://{0}\n".format(bucket_url)))
except KeyboardInterrupt:
show_error("ctrl-c pressed, bailing out!")
finally:
_delete_dir(tempdir) | python | def tarbell_publish(command, args):
"""
Publish to s3.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
bucket_name = list_get(args, 0, "staging")
try:
bucket_url = S3Url(site.project.S3_BUCKETS[bucket_name])
except KeyError:
show_error(
"\nThere's no bucket configuration called '{0}' in "
"tarbell_config.py.".format(colored.yellow(bucket_name)))
sys.exit(1)
extra_context = {
"ROOT_URL": bucket_url,
"S3_BUCKET": bucket_url.root,
"BUCKET_NAME": bucket_name,
}
tempdir = "{0}/".format(tarbell_generate(command,
args, extra_context=extra_context, skip_args=True, quiet=True))
try:
title = site.project.DEFAULT_CONTEXT.get("title", "")
puts("\nDeploying {0} to {1} ({2})\n".format(
colored.yellow(title),
colored.red(bucket_name),
colored.green(bucket_url)
))
# Get creds
if settings.config:
# If settings has a config section, use it
kwargs = settings.config['s3_credentials'].get(bucket_url.root)
if not kwargs:
kwargs = {
'access_key_id': settings.config.get('default_s3_access_key_id'),
'secret_access_key': settings.config.get('default_s3_secret_access_key'),
}
puts("Using default bucket credentials")
else:
puts("Using custom bucket configuration for {0}".format(bucket_url.root))
else:
# If no configuration exists, read from environment variables if possible
puts("Attemping to use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY")
kwargs = {
'access_key_id': os.environ["AWS_ACCESS_KEY_ID"],
'secret_access_key': os.environ["AWS_SECRET_ACCESS_KEY"],
}
if not kwargs.get('access_key_id') and not kwargs.get('secret_access_key'):
show_error('S3 access is not configured. Set up S3 with {0} to publish.'
.format(colored.green('tarbell configure')))
sys.exit()
s3 = S3Sync(tempdir, bucket_url, **kwargs)
s3.deploy_to_s3()
site.call_hook("publish", site, s3)
puts("\nIf you have website hosting enabled, you can see your project at:")
puts(colored.green("http://{0}\n".format(bucket_url)))
except KeyboardInterrupt:
show_error("ctrl-c pressed, bailing out!")
finally:
_delete_dir(tempdir) | [
"def",
"tarbell_publish",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
",",
"ensure_project",
"(",
"command",
",",
"args",
")",
"as",
"site",
":",
"bucket_name",
"=",
"list_get",
"(",... | Publish to s3. | [
"Publish",
"to",
"s3",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L332-L397 | train | 41,371 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_newproject | def tarbell_newproject(command, args):
"""
Create new Tarbell project.
"""
with ensure_settings(command, args) as settings:
# Set it up and make the directory
name = _get_project_name(args)
puts("Creating {0}".format(colored.cyan(name)))
path = _get_path(name, settings)
_mkdir(path)
try:
_newproject(command, path, name, settings)
except KeyboardInterrupt:
_delete_dir(path)
show_error("ctrl-c pressed, not creating new project.")
except:
_delete_dir(path)
show_error("Unexpected error: {0}".format(sys.exc_info()[0]))
raise | python | def tarbell_newproject(command, args):
"""
Create new Tarbell project.
"""
with ensure_settings(command, args) as settings:
# Set it up and make the directory
name = _get_project_name(args)
puts("Creating {0}".format(colored.cyan(name)))
path = _get_path(name, settings)
_mkdir(path)
try:
_newproject(command, path, name, settings)
except KeyboardInterrupt:
_delete_dir(path)
show_error("ctrl-c pressed, not creating new project.")
except:
_delete_dir(path)
show_error("Unexpected error: {0}".format(sys.exc_info()[0]))
raise | [
"def",
"tarbell_newproject",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"# Set it up and make the directory",
"name",
"=",
"_get_project_name",
"(",
"args",
")",
"puts",
"(",
"\"Crea... | Create new Tarbell project. | [
"Create",
"new",
"Tarbell",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L400-L419 | train | 41,372 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_serve | def tarbell_serve(command, args):
"""
Serve the current Tarbell project.
"""
with ensure_project(command, args) as site:
with ensure_settings(command, args) as settings:
address = list_get(args, 0, "").split(":")
ip = list_get(address, 0, settings.config['default_server_ip'])
port = int(list_get(address, 1, settings.config['default_server_port']))
puts("\n * Running local server. Press {0} to stop the server".format(colored.red("ctrl-c")))
puts(" * Edit this project's templates at {0}".format(colored.yellow(site.path)))
try:
if not is_werkzeug_process():
site.call_hook("server_start", site)
site.app.run(ip, port=port)
if not is_werkzeug_process():
site.call_hook("server_stop", site)
except socket.error:
show_error("Address {0} is already in use, please try another port or address."
.format(colored.yellow("{0}:{1}".format(ip, port)))) | python | def tarbell_serve(command, args):
"""
Serve the current Tarbell project.
"""
with ensure_project(command, args) as site:
with ensure_settings(command, args) as settings:
address = list_get(args, 0, "").split(":")
ip = list_get(address, 0, settings.config['default_server_ip'])
port = int(list_get(address, 1, settings.config['default_server_port']))
puts("\n * Running local server. Press {0} to stop the server".format(colored.red("ctrl-c")))
puts(" * Edit this project's templates at {0}".format(colored.yellow(site.path)))
try:
if not is_werkzeug_process():
site.call_hook("server_start", site)
site.app.run(ip, port=port)
if not is_werkzeug_process():
site.call_hook("server_stop", site)
except socket.error:
show_error("Address {0} is already in use, please try another port or address."
.format(colored.yellow("{0}:{1}".format(ip, port)))) | [
"def",
"tarbell_serve",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_project",
"(",
"command",
",",
"args",
")",
"as",
"site",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"address",
"=",
"list_get",
... | Serve the current Tarbell project. | [
"Serve",
"the",
"current",
"Tarbell",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L422-L445 | train | 41,373 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_switch | def tarbell_switch(command, args):
"""
Switch to a project.
"""
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
project = args.get(0)
args.remove(project)
project_path = os.path.join(projects_path, project)
if os.path.isdir(project_path):
os.chdir(project_path)
puts("\nSwitching to {0}".format(colored.red(project)))
tarbell_serve(command, args)
else:
show_error("{0} isn't a tarbell project".format(project_path)) | python | def tarbell_switch(command, args):
"""
Switch to a project.
"""
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
project = args.get(0)
args.remove(project)
project_path = os.path.join(projects_path, project)
if os.path.isdir(project_path):
os.chdir(project_path)
puts("\nSwitching to {0}".format(colored.red(project)))
tarbell_serve(command, args)
else:
show_error("{0} isn't a tarbell project".format(project_path)) | [
"def",
"tarbell_switch",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"projects_path",
"=",
"settings",
".",
"config",
".",
"get",
"(",
"\"projects_path\"",
")",
"if",
"not",
"pr... | Switch to a project. | [
"Switch",
"to",
"a",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L448-L465 | train | 41,374 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_update | def tarbell_update(command, args):
"""
Update the current tarbell project.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
puts("Updating to latest blueprint\n")
git = sh.git.bake(_cwd=site.base.base_dir)
# stash then pull
puts(colored.yellow("Stashing local changes"))
puts(git.stash())
puts(colored.yellow("Pull latest changes"))
puts(git.pull())
# need to pop any local changes back to get back on the original branch
# this may behave oddly if you have old changes stashed
if git.stash.list():
puts(git.stash.pop()) | python | def tarbell_update(command, args):
"""
Update the current tarbell project.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
puts("Updating to latest blueprint\n")
git = sh.git.bake(_cwd=site.base.base_dir)
# stash then pull
puts(colored.yellow("Stashing local changes"))
puts(git.stash())
puts(colored.yellow("Pull latest changes"))
puts(git.pull())
# need to pop any local changes back to get back on the original branch
# this may behave oddly if you have old changes stashed
if git.stash.list():
puts(git.stash.pop()) | [
"def",
"tarbell_update",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
",",
"ensure_project",
"(",
"command",
",",
"args",
")",
"as",
"site",
":",
"puts",
"(",
"\"Updating to latest blue... | Update the current tarbell project. | [
"Update",
"the",
"current",
"tarbell",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L476-L495 | train | 41,375 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_unpublish | def tarbell_unpublish(command, args):
"""
Delete a project.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
show_error("Not implemented!") | python | def tarbell_unpublish(command, args):
"""
Delete a project.
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
show_error("Not implemented!") | [
"def",
"tarbell_unpublish",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
",",
"ensure_project",
"(",
"command",
",",
"args",
")",
"as",
"site",
":",
"show_error",
"(",
"\"Not implemente... | Delete a project. | [
"Delete",
"a",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L498-L503 | train | 41,376 |
tarbell-project/tarbell | tarbell/cli.py | tarbell_spreadsheet | def tarbell_spreadsheet(command, args):
"""
Open context spreadsheet
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
try:
# First, try to get the Google Spreadsheet URL
spreadsheet_url = _google_spreadsheet_url(site.project.SPREADSHEET_KEY)
except AttributeError:
# The project doesn't seem to be using a Google Spreadsheet.
# Try the URL or path specified in the CONTEXT_SOURCE_FILE setting
try:
spreadsheet_url = _context_source_file_url(
site.project.CONTEXT_SOURCE_FILE)
print(spreadsheet_url)
except AttributeError:
puts(colored.red("No Google spreadsheet or context source file "
"has been configured.\n"))
return
# Use the webbrowser package to try to open the file whether it's a
# remote URL on the web, or a local file. On some platforms it will
# successfully open local files in the default application.
# This seems preferable to trying to do os detection and calling
# the system-specific command for opening files in default
# applications.
# See
# http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python
webbrowser.open(spreadsheet_url) | python | def tarbell_spreadsheet(command, args):
"""
Open context spreadsheet
"""
with ensure_settings(command, args) as settings, ensure_project(command, args) as site:
try:
# First, try to get the Google Spreadsheet URL
spreadsheet_url = _google_spreadsheet_url(site.project.SPREADSHEET_KEY)
except AttributeError:
# The project doesn't seem to be using a Google Spreadsheet.
# Try the URL or path specified in the CONTEXT_SOURCE_FILE setting
try:
spreadsheet_url = _context_source_file_url(
site.project.CONTEXT_SOURCE_FILE)
print(spreadsheet_url)
except AttributeError:
puts(colored.red("No Google spreadsheet or context source file "
"has been configured.\n"))
return
# Use the webbrowser package to try to open the file whether it's a
# remote URL on the web, or a local file. On some platforms it will
# successfully open local files in the default application.
# This seems preferable to trying to do os detection and calling
# the system-specific command for opening files in default
# applications.
# See
# http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python
webbrowser.open(spreadsheet_url) | [
"def",
"tarbell_spreadsheet",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
",",
"ensure_project",
"(",
"command",
",",
"args",
")",
"as",
"site",
":",
"try",
":",
"# First, try to get t... | Open context spreadsheet | [
"Open",
"context",
"spreadsheet"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L507-L535 | train | 41,377 |
tarbell-project/tarbell | tarbell/cli.py | _context_source_file_url | def _context_source_file_url(path_or_url):
"""
Returns a URL for a remote or local context CSV file
"""
if path_or_url.startswith('http'):
# Remote CSV. Just return the URL
return path_or_url
if path_or_url.startswith('/'):
# Absolute path
return "file://" + path_or_url
return "file://" + os.path.join(os.path.realpath(os.getcwd()), path_or_url) | python | def _context_source_file_url(path_or_url):
"""
Returns a URL for a remote or local context CSV file
"""
if path_or_url.startswith('http'):
# Remote CSV. Just return the URL
return path_or_url
if path_or_url.startswith('/'):
# Absolute path
return "file://" + path_or_url
return "file://" + os.path.join(os.path.realpath(os.getcwd()), path_or_url) | [
"def",
"_context_source_file_url",
"(",
"path_or_url",
")",
":",
"if",
"path_or_url",
".",
"startswith",
"(",
"'http'",
")",
":",
"# Remote CSV. Just return the URL",
"return",
"path_or_url",
"if",
"path_or_url",
".",
"startswith",
"(",
"'/'",
")",
":",
"# Absolute ... | Returns a URL for a remote or local context CSV file | [
"Returns",
"a",
"URL",
"for",
"a",
"remote",
"or",
"local",
"context",
"CSV",
"file"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L547-L559 | train | 41,378 |
tarbell-project/tarbell | tarbell/cli.py | _newproject | def _newproject(command, path, name, settings):
"""
Helper to create new project.
"""
key = None
title = _get_project_title()
template = _get_template(settings)
# Init repo
git = sh.git.bake(_cwd=path)
puts(git.init())
if template.get("url"):
# Create submodule
puts(git.submodule.add(template['url'], '_blueprint'))
puts(git.submodule.update(*['--init']))
# Create spreadsheet
key = _create_spreadsheet(name, title, path, settings)
# Copy html files
puts(colored.green("\nCopying html files..."))
files = glob.iglob(os.path.join(path, "_blueprint", "*.html"))
for file in files:
if os.path.isfile(file):
dir, filename = os.path.split(file)
if not filename.startswith("_") and not filename.startswith("."):
puts("Copying {0} to {1}".format(filename, path))
shutil.copy2(file, path)
ignore = os.path.join(path, "_blueprint", ".gitignore")
if os.path.isfile(ignore):
shutil.copy2(ignore, path)
else:
empty_index_path = os.path.join(path, "index.html")
open(empty_index_path, "w")
# Create config file
_copy_config_template(name, title, template, path, key, settings)
# Commit
puts(colored.green("\nInitial commit"))
puts(git.add('.'))
puts(git.commit(m='Created {0} from {1}'.format(name, template['name'])))
_install_requirements(path)
# Get site, run hook
with ensure_project(command, args, path) as site:
site.call_hook("newproject", site, git)
# Messages
puts("\nAll done! To preview your new project, type:\n")
puts("{0} {1}".format(colored.green("tarbell switch"), colored.green(name)))
puts("\nor\n")
puts("{0}".format(colored.green("cd %s" % path)))
puts("{0}".format(colored.green("tarbell serve\n")))
puts("\nYou got this!\n") | python | def _newproject(command, path, name, settings):
"""
Helper to create new project.
"""
key = None
title = _get_project_title()
template = _get_template(settings)
# Init repo
git = sh.git.bake(_cwd=path)
puts(git.init())
if template.get("url"):
# Create submodule
puts(git.submodule.add(template['url'], '_blueprint'))
puts(git.submodule.update(*['--init']))
# Create spreadsheet
key = _create_spreadsheet(name, title, path, settings)
# Copy html files
puts(colored.green("\nCopying html files..."))
files = glob.iglob(os.path.join(path, "_blueprint", "*.html"))
for file in files:
if os.path.isfile(file):
dir, filename = os.path.split(file)
if not filename.startswith("_") and not filename.startswith("."):
puts("Copying {0} to {1}".format(filename, path))
shutil.copy2(file, path)
ignore = os.path.join(path, "_blueprint", ".gitignore")
if os.path.isfile(ignore):
shutil.copy2(ignore, path)
else:
empty_index_path = os.path.join(path, "index.html")
open(empty_index_path, "w")
# Create config file
_copy_config_template(name, title, template, path, key, settings)
# Commit
puts(colored.green("\nInitial commit"))
puts(git.add('.'))
puts(git.commit(m='Created {0} from {1}'.format(name, template['name'])))
_install_requirements(path)
# Get site, run hook
with ensure_project(command, args, path) as site:
site.call_hook("newproject", site, git)
# Messages
puts("\nAll done! To preview your new project, type:\n")
puts("{0} {1}".format(colored.green("tarbell switch"), colored.green(name)))
puts("\nor\n")
puts("{0}".format(colored.green("cd %s" % path)))
puts("{0}".format(colored.green("tarbell serve\n")))
puts("\nYou got this!\n") | [
"def",
"_newproject",
"(",
"command",
",",
"path",
",",
"name",
",",
"settings",
")",
":",
"key",
"=",
"None",
"title",
"=",
"_get_project_title",
"(",
")",
"template",
"=",
"_get_template",
"(",
"settings",
")",
"# Init repo",
"git",
"=",
"sh",
".",
"gi... | Helper to create new project. | [
"Helper",
"to",
"create",
"new",
"project",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L563-L620 | train | 41,379 |
tarbell-project/tarbell | tarbell/cli.py | _install_requirements | def _install_requirements(path):
"""
Install a blueprint's requirements.txt
"""
locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path]
success = True
for location in locations:
try:
with open(os.path.join(location, "requirements.txt")):
puts("\nRequirements file found at {0}".format(os.path.join(location, "requirements.txt")))
install_reqs = raw_input("Install requirements now with pip install -r requirements.txt? [Y/n] ")
if not install_reqs or install_reqs.lower() == 'y':
pip = sh.pip.bake(_cwd=location)
puts("\nInstalling requirements...")
puts(pip("install", "-r", "requirements.txt"))
else:
success = False
puts("Not installing requirements. This may break everything! Vaya con dios.")
except IOError:
pass
return success | python | def _install_requirements(path):
"""
Install a blueprint's requirements.txt
"""
locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path]
success = True
for location in locations:
try:
with open(os.path.join(location, "requirements.txt")):
puts("\nRequirements file found at {0}".format(os.path.join(location, "requirements.txt")))
install_reqs = raw_input("Install requirements now with pip install -r requirements.txt? [Y/n] ")
if not install_reqs or install_reqs.lower() == 'y':
pip = sh.pip.bake(_cwd=location)
puts("\nInstalling requirements...")
puts(pip("install", "-r", "requirements.txt"))
else:
success = False
puts("Not installing requirements. This may break everything! Vaya con dios.")
except IOError:
pass
return success | [
"def",
"_install_requirements",
"(",
"path",
")",
":",
"locations",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"_blueprint\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"_base\"",
")",
",",
"path",
"]",
"success... | Install a blueprint's requirements.txt | [
"Install",
"a",
"blueprint",
"s",
"requirements",
".",
"txt"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L623-L645 | train | 41,380 |
tarbell-project/tarbell | tarbell/cli.py | _get_project_name | def _get_project_name(args):
"""
Get project name.
"""
name = args.get(0)
puts("")
while not name:
name = raw_input("What is the project's short directory name? (e.g. my_project) ")
return name | python | def _get_project_name(args):
"""
Get project name.
"""
name = args.get(0)
puts("")
while not name:
name = raw_input("What is the project's short directory name? (e.g. my_project) ")
return name | [
"def",
"_get_project_name",
"(",
"args",
")",
":",
"name",
"=",
"args",
".",
"get",
"(",
"0",
")",
"puts",
"(",
"\"\"",
")",
"while",
"not",
"name",
":",
"name",
"=",
"raw_input",
"(",
"\"What is the project's short directory name? (e.g. my_project) \"",
")",
... | Get project name. | [
"Get",
"project",
"name",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L648-L656 | train | 41,381 |
tarbell-project/tarbell | tarbell/cli.py | _clean_suffix | def _clean_suffix(string, suffix):
"""
If string endswith the suffix, remove it. Else leave it alone.
"""
suffix_len = len(suffix)
if len(string) < suffix_len:
# the string param was shorter than the suffix
raise ValueError("A suffix can not be bigger than string argument.")
if string.endswith(suffix):
# return from the beginning up to
# but not including the first letter
# in the suffix
return string[0:-suffix_len]
else:
# leave unharmed
return string | python | def _clean_suffix(string, suffix):
"""
If string endswith the suffix, remove it. Else leave it alone.
"""
suffix_len = len(suffix)
if len(string) < suffix_len:
# the string param was shorter than the suffix
raise ValueError("A suffix can not be bigger than string argument.")
if string.endswith(suffix):
# return from the beginning up to
# but not including the first letter
# in the suffix
return string[0:-suffix_len]
else:
# leave unharmed
return string | [
"def",
"_clean_suffix",
"(",
"string",
",",
"suffix",
")",
":",
"suffix_len",
"=",
"len",
"(",
"suffix",
")",
"if",
"len",
"(",
"string",
")",
"<",
"suffix_len",
":",
"# the string param was shorter than the suffix",
"raise",
"ValueError",
"(",
"\"A suffix can not... | If string endswith the suffix, remove it. Else leave it alone. | [
"If",
"string",
"endswith",
"the",
"suffix",
"remove",
"it",
".",
"Else",
"leave",
"it",
"alone",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L671-L687 | train | 41,382 |
tarbell-project/tarbell | tarbell/cli.py | _get_path | def _get_path(name, settings, mkdir=True):
"""
Generate a project path.
"""
default_projects_path = settings.config.get("projects_path")
path = None
if default_projects_path:
path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name))
if not path:
path = os.path.join(default_projects_path, name)
else:
while not path:
path = raw_input("\nWhere would you like to create this project? (e.g. ~/tarbell/) ")
return os.path.expanduser(path) | python | def _get_path(name, settings, mkdir=True):
"""
Generate a project path.
"""
default_projects_path = settings.config.get("projects_path")
path = None
if default_projects_path:
path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name))
if not path:
path = os.path.join(default_projects_path, name)
else:
while not path:
path = raw_input("\nWhere would you like to create this project? (e.g. ~/tarbell/) ")
return os.path.expanduser(path) | [
"def",
"_get_path",
"(",
"name",
",",
"settings",
",",
"mkdir",
"=",
"True",
")",
":",
"default_projects_path",
"=",
"settings",
".",
"config",
".",
"get",
"(",
"\"projects_path\"",
")",
"path",
"=",
"None",
"if",
"default_projects_path",
":",
"path",
"=",
... | Generate a project path. | [
"Generate",
"a",
"project",
"path",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L690-L705 | train | 41,383 |
tarbell-project/tarbell | tarbell/cli.py | _mkdir | def _mkdir(path):
"""
Make a directory or bail.
"""
try:
os.mkdir(path)
except OSError as e:
if e.errno == 17:
show_error("ABORTING: Directory {0} already exists.".format(path))
else:
show_error("ABORTING: OSError {0}".format(e))
sys.exit() | python | def _mkdir(path):
"""
Make a directory or bail.
"""
try:
os.mkdir(path)
except OSError as e:
if e.errno == 17:
show_error("ABORTING: Directory {0} already exists.".format(path))
else:
show_error("ABORTING: OSError {0}".format(e))
sys.exit() | [
"def",
"_mkdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"17",
":",
"show_error",
"(",
"\"ABORTING: Directory {0} already exists.\"",
".",
"format",
"(",... | Make a directory or bail. | [
"Make",
"a",
"directory",
"or",
"bail",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L708-L719 | train | 41,384 |
tarbell-project/tarbell | tarbell/cli.py | _get_template | def _get_template(settings):
"""
Prompt user to pick template from a list.
"""
puts("\nPick a template\n")
template = None
while not template:
_list_templates(settings)
index = raw_input("\nWhich template would you like to use? [1] ")
if not index:
index = "1"
try:
index = int(index) - 1
return settings.config["project_templates"][index]
except:
puts("\"{0}\" isn't a valid option!".format(colored.red("{0}".format(index))))
pass | python | def _get_template(settings):
"""
Prompt user to pick template from a list.
"""
puts("\nPick a template\n")
template = None
while not template:
_list_templates(settings)
index = raw_input("\nWhich template would you like to use? [1] ")
if not index:
index = "1"
try:
index = int(index) - 1
return settings.config["project_templates"][index]
except:
puts("\"{0}\" isn't a valid option!".format(colored.red("{0}".format(index))))
pass | [
"def",
"_get_template",
"(",
"settings",
")",
":",
"puts",
"(",
"\"\\nPick a template\\n\"",
")",
"template",
"=",
"None",
"while",
"not",
"template",
":",
"_list_templates",
"(",
"settings",
")",
"index",
"=",
"raw_input",
"(",
"\"\\nWhich template would you like t... | Prompt user to pick template from a list. | [
"Prompt",
"user",
"to",
"pick",
"template",
"from",
"a",
"list",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L722-L738 | train | 41,385 |
tarbell-project/tarbell | tarbell/cli.py | _list_templates | def _list_templates(settings):
"""
List templates from settings.
"""
for idx, option in enumerate(settings.config.get("project_templates"), start=1):
puts(" {0!s:5} {1!s:36}".format(
colored.yellow("[{0}]".format(idx)),
colored.cyan(option.get("name"))
))
if option.get("url"):
puts(" {0}\n".format(option.get("url"))) | python | def _list_templates(settings):
"""
List templates from settings.
"""
for idx, option in enumerate(settings.config.get("project_templates"), start=1):
puts(" {0!s:5} {1!s:36}".format(
colored.yellow("[{0}]".format(idx)),
colored.cyan(option.get("name"))
))
if option.get("url"):
puts(" {0}\n".format(option.get("url"))) | [
"def",
"_list_templates",
"(",
"settings",
")",
":",
"for",
"idx",
",",
"option",
"in",
"enumerate",
"(",
"settings",
".",
"config",
".",
"get",
"(",
"\"project_templates\"",
")",
",",
"start",
"=",
"1",
")",
":",
"puts",
"(",
"\" {0!s:5} {1!s:36}\"",
"."... | List templates from settings. | [
"List",
"templates",
"from",
"settings",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L741-L751 | train | 41,386 |
tarbell-project/tarbell | tarbell/cli.py | _create_spreadsheet | def _create_spreadsheet(name, title, path, settings):
"""
Create Google spreadsheet.
"""
if not settings.client_secrets:
return None
create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ")
if create and not create.lower() == "y":
return puts("Not creating spreadsheet.")
email_message = (
"What Google account(s) should have access to this "
"this spreadsheet? (Use a full email address, such as "
"your.name@gmail.com. Separate multiple addresses with commas.)")
if settings.config.get("google_account"):
emails = raw_input("\n{0}(Default: {1}) ".format(email_message,
settings.config.get("google_account")
))
if not emails:
emails = settings.config.get("google_account")
else:
emails = None
while not emails:
emails = raw_input(email_message)
try:
media_body = _MediaFileUpload(os.path.join(path, '_blueprint/_spreadsheet.xlsx'),
mimetype='application/vnd.ms-excel')
except IOError:
show_error("_blueprint/_spreadsheet.xlsx doesn't exist!")
return None
service = get_drive_api()
body = {
'title': '{0} (Tarbell)'.format(title),
'description': '{0} ({1})'.format(title, name),
'mimeType': 'application/vnd.ms-excel',
}
try:
newfile = service.files()\
.insert(body=body, media_body=media_body, convert=True).execute()
for email in emails.split(","):
_add_user_to_file(newfile['id'], service, user_email=email.strip())
puts("\n{0!s}! View the spreadsheet at {1!s}".format(
colored.green("Success"),
colored.yellow("https://docs.google.com/spreadsheet/ccc?key={0}"
.format(newfile['id']))
))
return newfile['id']
except errors.HttpError as error:
show_error('An error occurred creating spreadsheet: {0}'.format(error))
return None | python | def _create_spreadsheet(name, title, path, settings):
"""
Create Google spreadsheet.
"""
if not settings.client_secrets:
return None
create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ")
if create and not create.lower() == "y":
return puts("Not creating spreadsheet.")
email_message = (
"What Google account(s) should have access to this "
"this spreadsheet? (Use a full email address, such as "
"your.name@gmail.com. Separate multiple addresses with commas.)")
if settings.config.get("google_account"):
emails = raw_input("\n{0}(Default: {1}) ".format(email_message,
settings.config.get("google_account")
))
if not emails:
emails = settings.config.get("google_account")
else:
emails = None
while not emails:
emails = raw_input(email_message)
try:
media_body = _MediaFileUpload(os.path.join(path, '_blueprint/_spreadsheet.xlsx'),
mimetype='application/vnd.ms-excel')
except IOError:
show_error("_blueprint/_spreadsheet.xlsx doesn't exist!")
return None
service = get_drive_api()
body = {
'title': '{0} (Tarbell)'.format(title),
'description': '{0} ({1})'.format(title, name),
'mimeType': 'application/vnd.ms-excel',
}
try:
newfile = service.files()\
.insert(body=body, media_body=media_body, convert=True).execute()
for email in emails.split(","):
_add_user_to_file(newfile['id'], service, user_email=email.strip())
puts("\n{0!s}! View the spreadsheet at {1!s}".format(
colored.green("Success"),
colored.yellow("https://docs.google.com/spreadsheet/ccc?key={0}"
.format(newfile['id']))
))
return newfile['id']
except errors.HttpError as error:
show_error('An error occurred creating spreadsheet: {0}'.format(error))
return None | [
"def",
"_create_spreadsheet",
"(",
"name",
",",
"title",
",",
"path",
",",
"settings",
")",
":",
"if",
"not",
"settings",
".",
"client_secrets",
":",
"return",
"None",
"create",
"=",
"raw_input",
"(",
"\"Would you like to create a Google spreadsheet? [Y/n] \"",
")",... | Create Google spreadsheet. | [
"Create",
"Google",
"spreadsheet",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L754-L808 | train | 41,387 |
tarbell-project/tarbell | tarbell/cli.py | _add_user_to_file | def _add_user_to_file(file_id, service, user_email,
perm_type='user', role='writer'):
"""
Grants the given set of permissions for a given file_id. service is an
already-credentialed Google Drive service instance.
"""
new_permission = {
'value': user_email,
'type': perm_type,
'role': role
}
try:
service.permissions()\
.insert(fileId=file_id, body=new_permission)\
.execute()
except errors.HttpError as error:
show_error('An error adding users to spreadsheet: {0}'.format(error)) | python | def _add_user_to_file(file_id, service, user_email,
perm_type='user', role='writer'):
"""
Grants the given set of permissions for a given file_id. service is an
already-credentialed Google Drive service instance.
"""
new_permission = {
'value': user_email,
'type': perm_type,
'role': role
}
try:
service.permissions()\
.insert(fileId=file_id, body=new_permission)\
.execute()
except errors.HttpError as error:
show_error('An error adding users to spreadsheet: {0}'.format(error)) | [
"def",
"_add_user_to_file",
"(",
"file_id",
",",
"service",
",",
"user_email",
",",
"perm_type",
"=",
"'user'",
",",
"role",
"=",
"'writer'",
")",
":",
"new_permission",
"=",
"{",
"'value'",
":",
"user_email",
",",
"'type'",
":",
"perm_type",
",",
"'role'",
... | Grants the given set of permissions for a given file_id. service is an
already-credentialed Google Drive service instance. | [
"Grants",
"the",
"given",
"set",
"of",
"permissions",
"for",
"a",
"given",
"file_id",
".",
"service",
"is",
"an",
"already",
"-",
"credentialed",
"Google",
"Drive",
"service",
"instance",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L811-L827 | train | 41,388 |
tarbell-project/tarbell | tarbell/cli.py | _copy_config_template | def _copy_config_template(name, title, template, path, key, settings):
"""
Get and render tarbell_config.py.template from Tarbell default.
"""
puts("\nCopying configuration file")
context = settings.config
context.update({
"default_context": {
"name": name,
"title": title,
},
"name": name,
"title": title,
"template_repo_url": template.get('url'),
"key": key,
})
# @TODO refactor this a bit
if not key:
spreadsheet_path = os.path.join(path, '_blueprint/', '_spreadsheet.xlsx')
try:
with open(spreadsheet_path, "rb") as f:
puts("Copying _blueprint/_spreadsheet.xlsx to tarbell_config.py's DEFAULT_CONTEXT")
data = process_xlsx(f.read())
if 'values' in data:
data = copy_global_values(data)
context["default_context"].update(data)
except IOError:
pass
s3_buckets = settings.config.get("s3_buckets")
if s3_buckets:
puts("")
for bucket, bucket_conf in s3_buckets.items():
puts("Configuring {0!s} bucket at {1!s}\n".format(
colored.green(bucket),
colored.yellow("{0}/{1}".format(bucket_conf['uri'], name))
))
puts("\n- Creating {0!s} project configuration file".format(
colored.cyan("tarbell_config.py")
))
template_dir = os.path.dirname(pkg_resources.resource_filename("tarbell", "templates/tarbell_config.py.template"))
loader = jinja2.FileSystemLoader(template_dir)
env = jinja2.Environment(loader=loader)
env.filters["pprint_lines"] = pprint_lines # For dumping context
content = env.get_template('tarbell_config.py.template').render(context)
codecs.open(os.path.join(path, "tarbell_config.py"), "w", encoding="utf-8").write(content)
puts("\n- Done copying configuration file") | python | def _copy_config_template(name, title, template, path, key, settings):
"""
Get and render tarbell_config.py.template from Tarbell default.
"""
puts("\nCopying configuration file")
context = settings.config
context.update({
"default_context": {
"name": name,
"title": title,
},
"name": name,
"title": title,
"template_repo_url": template.get('url'),
"key": key,
})
# @TODO refactor this a bit
if not key:
spreadsheet_path = os.path.join(path, '_blueprint/', '_spreadsheet.xlsx')
try:
with open(spreadsheet_path, "rb") as f:
puts("Copying _blueprint/_spreadsheet.xlsx to tarbell_config.py's DEFAULT_CONTEXT")
data = process_xlsx(f.read())
if 'values' in data:
data = copy_global_values(data)
context["default_context"].update(data)
except IOError:
pass
s3_buckets = settings.config.get("s3_buckets")
if s3_buckets:
puts("")
for bucket, bucket_conf in s3_buckets.items():
puts("Configuring {0!s} bucket at {1!s}\n".format(
colored.green(bucket),
colored.yellow("{0}/{1}".format(bucket_conf['uri'], name))
))
puts("\n- Creating {0!s} project configuration file".format(
colored.cyan("tarbell_config.py")
))
template_dir = os.path.dirname(pkg_resources.resource_filename("tarbell", "templates/tarbell_config.py.template"))
loader = jinja2.FileSystemLoader(template_dir)
env = jinja2.Environment(loader=loader)
env.filters["pprint_lines"] = pprint_lines # For dumping context
content = env.get_template('tarbell_config.py.template').render(context)
codecs.open(os.path.join(path, "tarbell_config.py"), "w", encoding="utf-8").write(content)
puts("\n- Done copying configuration file") | [
"def",
"_copy_config_template",
"(",
"name",
",",
"title",
",",
"template",
",",
"path",
",",
"key",
",",
"settings",
")",
":",
"puts",
"(",
"\"\\nCopying configuration file\"",
")",
"context",
"=",
"settings",
".",
"config",
"context",
".",
"update",
"(",
"... | Get and render tarbell_config.py.template from Tarbell default. | [
"Get",
"and",
"render",
"tarbell_config",
".",
"py",
".",
"template",
"from",
"Tarbell",
"default",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L830-L878 | train | 41,389 |
tarbell-project/tarbell | tarbell/cli.py | _delete_dir | def _delete_dir(dir):
"""
Delete a directory.
"""
try:
shutil.rmtree(dir) # delete directory
except OSError as exc:
if exc.errno != 2: # code 2 - no such file or directory
raise # re-raise exception
except UnboundLocalError:
pass | python | def _delete_dir(dir):
"""
Delete a directory.
"""
try:
shutil.rmtree(dir) # delete directory
except OSError as exc:
if exc.errno != 2: # code 2 - no such file or directory
raise # re-raise exception
except UnboundLocalError:
pass | [
"def",
"_delete_dir",
"(",
"dir",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"dir",
")",
"# delete directory",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"2",
":",
"# code 2 - no such file or directory",
"raise",
"# re-r... | Delete a directory. | [
"Delete",
"a",
"directory",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L881-L891 | train | 41,390 |
tarbell-project/tarbell | tarbell/cli.py | def_cmd | def def_cmd(name=None, short=None, fn=None, usage=None, help=None):
"""
Define a command.
"""
command = Command(name=name, short=short, fn=fn, usage=usage, help=help)
Command.register(command) | python | def def_cmd(name=None, short=None, fn=None, usage=None, help=None):
"""
Define a command.
"""
command = Command(name=name, short=short, fn=fn, usage=usage, help=help)
Command.register(command) | [
"def",
"def_cmd",
"(",
"name",
"=",
"None",
",",
"short",
"=",
"None",
",",
"fn",
"=",
"None",
",",
"usage",
"=",
"None",
",",
"help",
"=",
"None",
")",
":",
"command",
"=",
"Command",
"(",
"name",
"=",
"name",
",",
"short",
"=",
"short",
",",
... | Define a command. | [
"Define",
"a",
"command",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L933-L938 | train | 41,391 |
tarbell-project/tarbell | tarbell/settings.py | Settings.save | def save(self):
"""
Save settings.
"""
with open(self.path, "w") as f:
self.config["project_templates"] = list(filter(lambda template: template.get("url"), self.config["project_templates"]))
yaml.dump(self.config, f, default_flow_style=False) | python | def save(self):
"""
Save settings.
"""
with open(self.path, "w") as f:
self.config["project_templates"] = list(filter(lambda template: template.get("url"), self.config["project_templates"]))
yaml.dump(self.config, f, default_flow_style=False) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"self",
".",
"config",
"[",
"\"project_templates\"",
"]",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"template",
":",
"template",
".",
... | Save settings. | [
"Save",
"settings",
"."
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/settings.py#L49-L55 | train | 41,392 |
tarbell-project/tarbell | tarbell/template.py | pprint_lines | def pprint_lines(value):
"""
Pretty print lines
"""
pformatted = pformat(value, width=1, indent=4)
formatted = "{0}\n {1}\n{2}".format(
pformatted[0],
pformatted[1:-1],
pformatted[-1]
)
return Markup(formatted) | python | def pprint_lines(value):
"""
Pretty print lines
"""
pformatted = pformat(value, width=1, indent=4)
formatted = "{0}\n {1}\n{2}".format(
pformatted[0],
pformatted[1:-1],
pformatted[-1]
)
return Markup(formatted) | [
"def",
"pprint_lines",
"(",
"value",
")",
":",
"pformatted",
"=",
"pformat",
"(",
"value",
",",
"width",
"=",
"1",
",",
"indent",
"=",
"4",
")",
"formatted",
"=",
"\"{0}\\n {1}\\n{2}\"",
".",
"format",
"(",
"pformatted",
"[",
"0",
"]",
",",
"pformatted",... | Pretty print lines | [
"Pretty",
"print",
"lines"
] | 818b3d3623dcda5a08a5bf45550219719b0f0365 | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/template.py#L176-L186 | train | 41,393 |
matthewgilbert/mapping | mapping/plot.py | plot_composition | def plot_composition(df, intervals, axes=None):
"""
Plot time series of generics and label underlying instruments which
these series are composed of.
Parameters:
-----------
df: pd.DataFrame
DataFrame of time series to be plotted. Each column is a generic time
series.
intervals: pd.DataFrame
A DataFrame including information for when each contract is used in the
generic series.
Columns are['contract', 'generic', 'start_date', 'end_date']
axes: list
List of matplotlib.axes.Axes
Example
-------
>>> import mapping.plot as mplot
>>> import pandas as pd
>>> from pandas import Timestamp as TS
>>> idx = pd.date_range("2017-01-01", "2017-01-15")
>>> rets_data = pd.np.random.randn(len(idx))
>>> rets = pd.DataFrame({"CL1": rets_data, "CL2": rets_data}, index=idx)
>>> intervals = pd.DataFrame(
... [(TS("2017-01-01"), TS("2017-01-05"), "2017_CL_F", "CL1"),
... (TS("2017-01-05"), TS("2017-01-15"), "2017_CL_G", "CL1"),
... (TS("2017-01-01"), TS("2017-01-12"), "2017_CL_G", "CL2"),
... (TS("2017-01-10"), TS("2017-01-15"), "2017_CL_H", "CL2")],
... columns=["start_date", "end_date", "contract", "generic"])
>>> mplot.plot_composition(rets, intervals)
"""
generics = df.columns
if (axes is not None) and (len(axes) != len(generics)):
raise ValueError("If 'axes' is not None then it must be the same "
"length as 'df.columns'")
if axes is None:
_, axes = plt.subplots(nrows=len(generics), ncols=1)
if len(generics) == 1:
axes = [axes]
for ax, generic in zip(axes, generics):
ax.plot(df.loc[:, generic], label=generic)
# no legend line to avoid clutter
ax.legend(loc='center right', handlelength=0)
dates = intervals.loc[intervals.loc[:, "generic"] == generic,
["start_date", "end_date", "contract"]]
date_ticks = set(
dates.loc[:, "start_date"].tolist() +
dates.loc[:, "end_date"].tolist()
)
xticks = [ts.toordinal() for ts in date_ticks]
xlabels = [ts.strftime("%Y-%m-%d") for ts in date_ticks]
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
y_top = ax.get_ylim()[1]
count = 0
# label and colour each underlying
for _, dt1, dt2, instr in dates.itertuples():
if count % 2:
fc = "b"
else:
fc = "r"
count += 1
ax.axvspan(dt1, dt2, facecolor=fc, alpha=0.2)
x_mid = dt1 + (dt2 - dt1) / 2
ax.text(x_mid, y_top, instr, rotation=45)
return axes | python | def plot_composition(df, intervals, axes=None):
"""
Plot time series of generics and label underlying instruments which
these series are composed of.
Parameters:
-----------
df: pd.DataFrame
DataFrame of time series to be plotted. Each column is a generic time
series.
intervals: pd.DataFrame
A DataFrame including information for when each contract is used in the
generic series.
Columns are['contract', 'generic', 'start_date', 'end_date']
axes: list
List of matplotlib.axes.Axes
Example
-------
>>> import mapping.plot as mplot
>>> import pandas as pd
>>> from pandas import Timestamp as TS
>>> idx = pd.date_range("2017-01-01", "2017-01-15")
>>> rets_data = pd.np.random.randn(len(idx))
>>> rets = pd.DataFrame({"CL1": rets_data, "CL2": rets_data}, index=idx)
>>> intervals = pd.DataFrame(
... [(TS("2017-01-01"), TS("2017-01-05"), "2017_CL_F", "CL1"),
... (TS("2017-01-05"), TS("2017-01-15"), "2017_CL_G", "CL1"),
... (TS("2017-01-01"), TS("2017-01-12"), "2017_CL_G", "CL2"),
... (TS("2017-01-10"), TS("2017-01-15"), "2017_CL_H", "CL2")],
... columns=["start_date", "end_date", "contract", "generic"])
>>> mplot.plot_composition(rets, intervals)
"""
generics = df.columns
if (axes is not None) and (len(axes) != len(generics)):
raise ValueError("If 'axes' is not None then it must be the same "
"length as 'df.columns'")
if axes is None:
_, axes = plt.subplots(nrows=len(generics), ncols=1)
if len(generics) == 1:
axes = [axes]
for ax, generic in zip(axes, generics):
ax.plot(df.loc[:, generic], label=generic)
# no legend line to avoid clutter
ax.legend(loc='center right', handlelength=0)
dates = intervals.loc[intervals.loc[:, "generic"] == generic,
["start_date", "end_date", "contract"]]
date_ticks = set(
dates.loc[:, "start_date"].tolist() +
dates.loc[:, "end_date"].tolist()
)
xticks = [ts.toordinal() for ts in date_ticks]
xlabels = [ts.strftime("%Y-%m-%d") for ts in date_ticks]
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
y_top = ax.get_ylim()[1]
count = 0
# label and colour each underlying
for _, dt1, dt2, instr in dates.itertuples():
if count % 2:
fc = "b"
else:
fc = "r"
count += 1
ax.axvspan(dt1, dt2, facecolor=fc, alpha=0.2)
x_mid = dt1 + (dt2 - dt1) / 2
ax.text(x_mid, y_top, instr, rotation=45)
return axes | [
"def",
"plot_composition",
"(",
"df",
",",
"intervals",
",",
"axes",
"=",
"None",
")",
":",
"generics",
"=",
"df",
".",
"columns",
"if",
"(",
"axes",
"is",
"not",
"None",
")",
"and",
"(",
"len",
"(",
"axes",
")",
"!=",
"len",
"(",
"generics",
")",
... | Plot time series of generics and label underlying instruments which
these series are composed of.
Parameters:
-----------
df: pd.DataFrame
DataFrame of time series to be plotted. Each column is a generic time
series.
intervals: pd.DataFrame
A DataFrame including information for when each contract is used in the
generic series.
Columns are['contract', 'generic', 'start_date', 'end_date']
axes: list
List of matplotlib.axes.Axes
Example
-------
>>> import mapping.plot as mplot
>>> import pandas as pd
>>> from pandas import Timestamp as TS
>>> idx = pd.date_range("2017-01-01", "2017-01-15")
>>> rets_data = pd.np.random.randn(len(idx))
>>> rets = pd.DataFrame({"CL1": rets_data, "CL2": rets_data}, index=idx)
>>> intervals = pd.DataFrame(
... [(TS("2017-01-01"), TS("2017-01-05"), "2017_CL_F", "CL1"),
... (TS("2017-01-05"), TS("2017-01-15"), "2017_CL_G", "CL1"),
... (TS("2017-01-01"), TS("2017-01-12"), "2017_CL_G", "CL2"),
... (TS("2017-01-10"), TS("2017-01-15"), "2017_CL_H", "CL2")],
... columns=["start_date", "end_date", "contract", "generic"])
>>> mplot.plot_composition(rets, intervals) | [
"Plot",
"time",
"series",
"of",
"generics",
"and",
"label",
"underlying",
"instruments",
"which",
"these",
"series",
"are",
"composed",
"of",
"."
] | 24ea21acfe37a0ee273f63a273b5d24ea405e70d | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/plot.py#L5-L76 | train | 41,394 |
matthewgilbert/mapping | mapping/plot.py | intervals | def intervals(weights):
"""
Extract intervals where generics are composed of different tradeable
instruments.
Parameters
----------
weights: DataFrame or dict
A DataFrame or dictionary of DataFrames with columns representing
generics and a MultiIndex of date and contract. Values represent
weights on tradeables for each generic.
Returns
-------
A DataFrame with [columns]
['contract', 'generic', 'start_date', 'end_date']
"""
intrvls = []
if isinstance(weights, dict):
for root in weights:
wts = weights[root]
intrvls.append(_intervals(wts))
intrvls = pd.concat(intrvls, axis=0)
else:
intrvls = _intervals(weights)
intrvls = intrvls.reset_index(drop=True)
return intrvls | python | def intervals(weights):
"""
Extract intervals where generics are composed of different tradeable
instruments.
Parameters
----------
weights: DataFrame or dict
A DataFrame or dictionary of DataFrames with columns representing
generics and a MultiIndex of date and contract. Values represent
weights on tradeables for each generic.
Returns
-------
A DataFrame with [columns]
['contract', 'generic', 'start_date', 'end_date']
"""
intrvls = []
if isinstance(weights, dict):
for root in weights:
wts = weights[root]
intrvls.append(_intervals(wts))
intrvls = pd.concat(intrvls, axis=0)
else:
intrvls = _intervals(weights)
intrvls = intrvls.reset_index(drop=True)
return intrvls | [
"def",
"intervals",
"(",
"weights",
")",
":",
"intrvls",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"weights",
",",
"dict",
")",
":",
"for",
"root",
"in",
"weights",
":",
"wts",
"=",
"weights",
"[",
"root",
"]",
"intrvls",
".",
"append",
"(",
"_interval... | Extract intervals where generics are composed of different tradeable
instruments.
Parameters
----------
weights: DataFrame or dict
A DataFrame or dictionary of DataFrames with columns representing
generics and a MultiIndex of date and contract. Values represent
weights on tradeables for each generic.
Returns
-------
A DataFrame with [columns]
['contract', 'generic', 'start_date', 'end_date'] | [
"Extract",
"intervals",
"where",
"generics",
"are",
"composed",
"of",
"different",
"tradeable",
"instruments",
"."
] | 24ea21acfe37a0ee273f63a273b5d24ea405e70d | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/plot.py#L79-L106 | train | 41,395 |
openstack/networking-arista | networking_arista/l3Plugin/l3_arista.py | AristaL3SyncWorker.synchronize | def synchronize(self):
"""Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
Uses idempotent properties of EOS configuration, which means
same commands can be repeated.
"""
LOG.info(_LI('Syncing Neutron Router DB <-> EOS'))
routers, router_interfaces = self.get_routers_and_interfaces()
expected_vrfs = set()
if self._use_vrf:
expected_vrfs.update(self.driver._arista_router_name(
r['id'], r['name']) for r in routers)
expected_vlans = set(r['seg_id'] for r in router_interfaces)
if self._enable_cleanup:
self.do_cleanup(expected_vrfs, expected_vlans)
self.create_routers(routers)
self.create_router_interfaces(router_interfaces) | python | def synchronize(self):
"""Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
Uses idempotent properties of EOS configuration, which means
same commands can be repeated.
"""
LOG.info(_LI('Syncing Neutron Router DB <-> EOS'))
routers, router_interfaces = self.get_routers_and_interfaces()
expected_vrfs = set()
if self._use_vrf:
expected_vrfs.update(self.driver._arista_router_name(
r['id'], r['name']) for r in routers)
expected_vlans = set(r['seg_id'] for r in router_interfaces)
if self._enable_cleanup:
self.do_cleanup(expected_vrfs, expected_vlans)
self.create_routers(routers)
self.create_router_interfaces(router_interfaces) | [
"def",
"synchronize",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"_LI",
"(",
"'Syncing Neutron Router DB <-> EOS'",
")",
")",
"routers",
",",
"router_interfaces",
"=",
"self",
".",
"get_routers_and_interfaces",
"(",
")",
"expected_vrfs",
"=",
"set",
"(",
... | Synchronizes Router DB from Neturon DB with EOS.
Walks through the Neturon Db and ensures that all the routers
created in Netuton DB match with EOS. After creating appropriate
routers, it ensures to add interfaces as well.
Uses idempotent properties of EOS configuration, which means
same commands can be repeated. | [
"Synchronizes",
"Router",
"DB",
"from",
"Neturon",
"DB",
"with",
"EOS",
"."
] | 07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/l3Plugin/l3_arista.py#L106-L125 | train | 41,396 |
openstack/networking-arista | networking_arista/l3Plugin/l3_arista.py | AristaL3ServicePlugin.create_router | def create_router(self, context, router):
"""Create a new router entry in DB, and create it Arista HW."""
# Add router to the DB
new_router = super(AristaL3ServicePlugin, self).create_router(
context,
router)
# create router on the Arista Hw
try:
self.driver.create_router(context, new_router)
return new_router
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error creating router on Arista HW router=%s "),
new_router)
super(AristaL3ServicePlugin, self).delete_router(
context,
new_router['id']
) | python | def create_router(self, context, router):
"""Create a new router entry in DB, and create it Arista HW."""
# Add router to the DB
new_router = super(AristaL3ServicePlugin, self).create_router(
context,
router)
# create router on the Arista Hw
try:
self.driver.create_router(context, new_router)
return new_router
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error creating router on Arista HW router=%s "),
new_router)
super(AristaL3ServicePlugin, self).delete_router(
context,
new_router['id']
) | [
"def",
"create_router",
"(",
"self",
",",
"context",
",",
"router",
")",
":",
"# Add router to the DB",
"new_router",
"=",
"super",
"(",
"AristaL3ServicePlugin",
",",
"self",
")",
".",
"create_router",
"(",
"context",
",",
"router",
")",
"# create router on the Ar... | Create a new router entry in DB, and create it Arista HW. | [
"Create",
"a",
"new",
"router",
"entry",
"in",
"DB",
"and",
"create",
"it",
"Arista",
"HW",
"."
] | 07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/l3Plugin/l3_arista.py#L231-L249 | train | 41,397 |
openstack/networking-arista | networking_arista/l3Plugin/l3_arista.py | AristaL3ServicePlugin.update_router | def update_router(self, context, router_id, router):
"""Update an existing router in DB, and update it in Arista HW."""
# Read existing router record from DB
original_router = self.get_router(context, router_id)
# Update router DB
new_router = super(AristaL3ServicePlugin, self).update_router(
context, router_id, router)
# Modify router on the Arista Hw
try:
self.driver.update_router(context, router_id,
original_router, new_router)
return new_router
except Exception:
LOG.error(_LE("Error updating router on Arista HW router=%s "),
new_router) | python | def update_router(self, context, router_id, router):
"""Update an existing router in DB, and update it in Arista HW."""
# Read existing router record from DB
original_router = self.get_router(context, router_id)
# Update router DB
new_router = super(AristaL3ServicePlugin, self).update_router(
context, router_id, router)
# Modify router on the Arista Hw
try:
self.driver.update_router(context, router_id,
original_router, new_router)
return new_router
except Exception:
LOG.error(_LE("Error updating router on Arista HW router=%s "),
new_router) | [
"def",
"update_router",
"(",
"self",
",",
"context",
",",
"router_id",
",",
"router",
")",
":",
"# Read existing router record from DB",
"original_router",
"=",
"self",
".",
"get_router",
"(",
"context",
",",
"router_id",
")",
"# Update router DB",
"new_router",
"="... | Update an existing router in DB, and update it in Arista HW. | [
"Update",
"an",
"existing",
"router",
"in",
"DB",
"and",
"update",
"it",
"in",
"Arista",
"HW",
"."
] | 07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/l3Plugin/l3_arista.py#L252-L268 | train | 41,398 |
openstack/networking-arista | networking_arista/l3Plugin/l3_arista.py | AristaL3ServicePlugin.delete_router | def delete_router(self, context, router_id):
"""Delete an existing router from Arista HW as well as from the DB."""
router = self.get_router(context, router_id)
# Delete router on the Arista Hw
try:
self.driver.delete_router(context, router_id, router)
except Exception as e:
LOG.error(_LE("Error deleting router on Arista HW "
"router %(r)s exception=%(e)s"),
{'r': router, 'e': e})
super(AristaL3ServicePlugin, self).delete_router(context, router_id) | python | def delete_router(self, context, router_id):
"""Delete an existing router from Arista HW as well as from the DB."""
router = self.get_router(context, router_id)
# Delete router on the Arista Hw
try:
self.driver.delete_router(context, router_id, router)
except Exception as e:
LOG.error(_LE("Error deleting router on Arista HW "
"router %(r)s exception=%(e)s"),
{'r': router, 'e': e})
super(AristaL3ServicePlugin, self).delete_router(context, router_id) | [
"def",
"delete_router",
"(",
"self",
",",
"context",
",",
"router_id",
")",
":",
"router",
"=",
"self",
".",
"get_router",
"(",
"context",
",",
"router_id",
")",
"# Delete router on the Arista Hw",
"try",
":",
"self",
".",
"driver",
".",
"delete_router",
"(",
... | Delete an existing router from Arista HW as well as from the DB. | [
"Delete",
"an",
"existing",
"router",
"from",
"Arista",
"HW",
"as",
"well",
"as",
"from",
"the",
"DB",
"."
] | 07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/l3Plugin/l3_arista.py#L271-L284 | train | 41,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.