sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key, data_list in reporters.items(): ...
Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date.
entailment
def check_rank(player, platform="steam"): """Gets the Rocket League stats and name and dp of a UserID Args: player (str): The UserID of the player we want to rank check platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox' Returns: success (bool): Whether the r...
Gets the Rocket League stats and name and dp of a UserID Args: player (str): The UserID of the player we want to rank check platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox' Returns: success (bool): Whether the rank check was successful package (tuple):...
entailment
def send_message(channel_id, message): """ Send a message to a channel Args: channel_id (str): The id of the channel to send the message to message (str): The message to send to the channel """ channel = client.get_channel(channel_id) if channel is None: logger.info("{...
Send a message to a channel Args: channel_id (str): The id of the channel to send the message to message (str): The message to send to the channel
entailment
def runcoro(async_function): """ Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run """ future = _asyncio.run_coroutine_threadsafe(async_function, client.loop) result = future.result() re...
Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
def update_keys(self): """Updates the Google API key with the text value""" from ...main import add_api_key add_api_key("reddit_api_user_agent", self.reddit_api_user_agent.get()) add_api_key("reddit_api_client_id", self.reddit_api_client_id.get()) add_api_key("reddit_api_client_s...
Updates the Google API key with the text value
entailment
async def activate_module(channel, module_name, activate): """ Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module...
Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module
entailment
async def warn_user(channel, user): """ Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id ...
Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to
entailment
async def ban_user(channel, user): """ Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id try: await client.ban(user) except dis...
Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to
entailment
def get_help_datapacks(module_name, server_prefix): """ Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module """ ...
Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module
entailment
def get_help_commands(server_prefix): """ Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules """ datapacks = [] _dir = os.path.realpath( os.p...
Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
def topic_update(channel, topic_channel): """ Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed """ if topic_channel is not None: ...
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed
entailment
def error_message(channel, err_title, err_message): """ Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to err_title: The title for the error err_message: The message for the error Returns: embed: The creat...
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to err_title: The title for the error err_message: The message for the error Returns: embed: The created embed
entailment
def clear_cache_root(): """Clears everything in the song cache""" logger.debug("Clearing root cache") if os.path.isdir(_root_songcache_dir): for filename in os.listdir(_root_songcache_dir): file_path = os.path.join(_root_songcache_dir, filename) try: if os.pat...
Clears everything in the song cache
entailment
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False): """ The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called q...
The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end ...
entailment
async def destroy(self): """Destroy the whole gui and music player""" self.logger.debug("destroy command") self.state = 'destroyed' await self.set_topic("") self.nowplayinglog.debug("---") self.nowplayingauthorlog.debug("---") self.nowplayingsourcelog.debug("---...
Destroy the whole gui and music player
entailment
async def toggle(self): """Toggles between pause and resume command""" self.logger.debug("toggle command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): await self....
Toggles between pause and resume command
entailment
async def pause(self): """Pauses playback if playing""" self.logger.debug("pause command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): self.streamer.pause() ...
Pauses playback if playing
entailment
async def resume(self): """Resumes playback if paused""" self.logger.debug("resume command") if not self.state == 'ready': return if self.streamer is None: return try: if not self.streamer.is_playing(): play_state = "Streami...
Resumes playback if paused
entailment
async def skip(self, query="1"): """The skip command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to skip from wrong state '{}'".format(self.state)) return if query == "": ...
The skip command Args: query (str): The number of items to skip
entailment
async def remove(self, index=""): """ The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##' """ if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.sta...
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
entailment
async def rewind(self, query="1"): """ The rewind command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to rewind from wrong state '{}'".format(self.state)) return if query == "...
The rewind command Args: query (str): The number of items to skip
entailment
async def shuffle(self): """The shuffle command""" self.logger.debug("shuffle command") if not self.state == 'ready': return self.statuslog.debug("Shuffling") random.shuffle(self.queue) self.update_queue() self.statuslog.debug("Shuffled")
The shuffle command
entailment
async def set_loop(self, loop_value): """Updates the loop value, can be 'off', 'on', or 'shuffle'""" if loop_value not in ['on', 'off', 'shuffle']: self.statuslog.error("Loop value must be `off`, `on`, or `shuffle`") return self.loop_type = loop_value if self.loo...
Updates the loop value, can be 'off', 'on', or 'shuffle
entailment
async def setvolume(self, value): """The volume command Args: value (str): The value to set the volume to """ self.logger.debug("volume command") if self.state != 'ready': return logger.debug("Volume command received") if value == '+':...
The volume command Args: value (str): The value to set the volume to
entailment
def write_volume(self): """Writes the current volume to the data.json""" # Update the volume data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume datatools.write_data(data)
Writes the current volume to the data.json
entailment
async def movehere(self, channel): """ Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to """ self.logger.debug("movehere command") # Delete the old message...
Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to
entailment
async def set_topic_channel(self, channel): """Set the topic channel for this server""" data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"] = channel.id datatools.write_data(data) self.topicchannel = channel await self.set...
Set the topic channel for this server
entailment
async def clear_topic_channel(self, channel): """Set the topic channel for this server""" try: if self.topicchannel: await client.edit_channel(self.topicchannel, topic="") except Exception as e: logger.exception(e) self.topicchannel = None ...
Set the topic channel for this server
entailment
async def vsetup(self, author): """Creates the voice client Args: author (discord.Member): The user that the voice ui will seek """ if self.vready: logger.warning("Attempt to init voice when already initialised") return if self.state != 'sta...
Creates the voice client Args: author (discord.Member): The user that the voice ui will seek
entailment
async def msetup(self, text_channel): """Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in """ if self.mready: logger.warning("Attempt to init music when already initialised") return if self.state !...
Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in
entailment
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))) ...
Create the embed UI object and save it to self
entailment
async def add_reactions(self): """Adds the reactions buttons to the current message""" self.statuslog.info("Loading buttons") for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"): try: if self.embed is not None: await client.add_reaction(self.embed.sent...
Adds the reactions buttons to the current message
entailment
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) ...
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 (boo...
entailment
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...
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 a...
entailment
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] +...
Updates the queue in the music player
entailment
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)
Sets the topic for the topic channel
entailment
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: ...
Removes all files from the songcache dir
entailment
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.re...
Moves files in the 'next' cache dir to the root
entailment
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["elapse...
Called when youtube-dl updates progress
entailment
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)
Play blank audio to let Discord know we're still here
entailment
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 ...
Downloads the next song and starts playing it
entailment
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: ...
Downloads the next song in the queue to the cache
entailment
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: ...
Creates a streamer that plays from a file
entailment
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_s...
Creates a streamer that plays from a URL
entailment
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 nex...
Sets up basic defaults for the streamer
entailment
def vafter_ts(self): """Function that is called after a song finishes playing""" logger.debug("Song finishing") future = asyncio.run_coroutine_threadsafe(self.vafter(), client.loop) try: future.result() except Exception as e: logger.exception(e)
Function that is called after a song finishes playing
entailment
async def vafter(self): """Function that is called after a song finishes playing""" self.logger.debug("Finished playing a song") if self.state != 'ready': self.logger.debug("Returning because player is in state {}".format(self.state)) return self.pause_time = Non...
Function that is called after a song finishes playing
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
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' " ...
Build the YouTube API for future use
entailment
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_...
Build the SoundCloud API for future use
entailment
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'...
Build the Spotify API for future use
entailment
def parse_query(query, ilogger): """ Gets either a list of videos from a query, parsing links and search queries and playlists Args: query (str): The YouTube search query ilogger (logging.logger): The logger to log API calls to Returns: queue (list): The items obtained from...
Gets either a list of videos from a query, parsing links and search queries and playlists 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
entailment
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 i...
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
entailment
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)
Converts a duration to a string Args: duration (int): The duration in seconds to convert Returns s (str): The duration as a string
entailment
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 = s...
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
entailment
def flipcheck(content): """Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text """ # Prevent tampering with flip punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─""" tamperdict =...
Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text
entailment
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' } ...
Gets a botcust2, used to identify a speaker with Mitsuku Returns: botcust2 (str): The botcust2 identifier
entailment
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") ...
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
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
def start(token, client_id, loop, on_ready_handler=None): """Start the Discord client and log Modis into Discord.""" import discord import asyncio # Create client logger.debug("Creating Discord client") asyncio.set_event_loop(loop) client = discord.Client() from . import _client _cl...
Start the Discord client and log Modis into Discord.
entailment
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": [], ...
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"
entailment
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 ...
Adds a key to the bot's data Args: key: The name of the key to add value: The value for the key
entailment
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...
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
entailment
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...
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
entailment
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 = _ge...
Tarbell configuration routine.
entailment
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: i...
Get or create a Tarbell configuration directory.
entailment
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...
Set up a Google spreadsheet.
entailment
def _setup_s3(settings, path, prompt=True): """ Prompt user to set up Amazon S3. """ ret = {'default_s3_buckets': {}, 's3_credentials': settings.get('s3_credentials', {})} if prompt: use = raw_input("\nWould you like to set up Amazon S3? [Y/n] ") if use.lower() != "y" and use != "":...
Prompt user to set up Amazon S3.
entailment
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 pro...
Prompt user to set up project path.
entailment
def _setup_default_templates(settings, path, prompt=True): """ Add some (hardcoded) default templates. """ project_templates = [{ "name": "Basic Bootstrap 3 template", "url": "https://github.com/tarbell-project/tarbell-template", }, { "name": "Searchable map template", ...
Add some (hardcoded) default templates.
entailment
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_filenam...
Backup a file.
entailment
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' >>> s...
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." ...
entailment
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, s...
Wrap puts to avoid getting called twice by Werkzeug reloader.
entailment
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
Get from a list with an optional default value.
entailment
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] sent...
Split sentences for formatting.
entailment
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)
Ensure directory exists for a given file path.
entailment
def show_error(msg): """ Displays error message. """ sys.stdout.flush() sys.stderr.write("\n{0!s}: {1}".format(colored.red("Error"), msg + '\n'))
Displays error message.
entailment
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))
Add a stream to the SRTP session, applying the given `policy` to the stream. :param policy: :class:`Policy`
entailment
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)))
Remove the stream with the given `ssrc` from the SRTP session. :param ssrc: :class:`int`
entailment
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.startsw...
Turn Excel file contents into Tarbell worksheet data
entailment
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 " ...
Copy values worksheet into global namespace.
entailment
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....
Make headers from worksheet
entailment
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 ...
Make data from worksheet
entailment
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
Ensure preview is never cached
entailment
def call_hook(self, hook, *args, **kwargs): """ Calls each registered hook """ for function in self.hooks[hook]: function.__call__(*args, **kwargs)
Calls each registered hook
entailment
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 project blueprint
entailment
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 =...
Load a Tarbell project
entailment
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...
Resolve static file paths
entailment
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 sit...
Serve site context as JSON. Useful for debugging.
entailment
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_p...
Serve up a project path
entailment
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: ...
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.
entailment
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: ...
Get context from an Excel file
entailment
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_li...
Open CONTEXT_SOURCE_FILE, parse and return a context
entailment
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...
Wrap getting context from Google sheets in a simple caching mechanism.
entailment
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 ...
Create a Jinja2 context from a Google spreadsheet.
entailment
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.shee...
Download xlsx version of spreadsheet.
entailment
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_r...
Bake out static site
entailment