_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q251200
Boxscore.home_wins
train
def home_wins(self): """ Returns an ``int`` of the number of games the home team won after the conclusion of the game. """ try: wins, losses =
python
{ "resource": "" }
q251201
Boxscore.home_two_point_field_goal_percentage
train
def home_two_point_field_goal_percentage(self): """ Returns a ``float`` of the number of two point field goals made divided by the number of two point field goal attempts by the home team. Percentage ranges from 0-1. """
python
{ "resource": "" }
q251202
Team.dataframe
train
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string abbreviation of the team, such as 'KAN'. """ fields_to_include = { 'abbreviation': self.abbreviation, 'd...
python
{ "resource": "" }
q251203
Player._parse_team_name
train
def _parse_team_name(self, team): """ Parse the team name in the contract table. The team names in the contract table contain special encoded characters that are not supported by Python 2.7. These characters should be filtered out to get the proper team name. Parameters...
python
{ "resource": "" }
q251204
Player._parse_value
train
def _parse_value(self, html_data, field): """ Parse the HTML table to find the requested field's value. All of the values are passed in an HTML table row instead of as individual items. The values need to be parsed by matching the requested attribute with a parsing scheme that s...
python
{ "resource": "" }
q251205
Roster._get_id
train
def _get_id(self, player): """ Parse the player ID. Given a PyQuery object representing a single player on the team roster, parse the player ID and return it as a string. Parameters ---------- player : PyQuery object A PyQuery object representing the...
python
{ "resource": "" }
q251206
BoxscorePlayer.dataframe
train
def dataframe(self): """ Returns a ``pandas DataFrame`` containing all other relevant properties and values for the specified game. """ fields_to_include = { 'assists': self.assists, 'blocks_at_even_strength': self.blocks_at_even_strength, 'cor...
python
{ "resource": "" }
q251207
Boxscore._find_player_id
train
def _find_player_id(self, row): """ Find the player's ID. Find the player's ID as embedded in the 'data-append-csv' attribute, such as 'zettehe01' for Henrik Zetterberg. Parameters ---------- row : PyQuery object A PyQuery object representing a singl...
python
{ "resource": "" }
q251208
Boxscore.dataframe
train
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string URI that is used to instantiate the class, such as '201806070VEG'. """ if self._away_goals is None and self._home_goals is None:...
python
{ "resource": "" }
q251209
Boxscore.away_save_percentage
train
def away_save_percentage(self): """ Returns a ``float`` of the percentage of shots the away team saved. Percentage ranges from 0-1. """ try: save_pct = float(self.away_saves) /
python
{ "resource": "" }
q251210
Boxscore.home_save_percentage
train
def home_save_percentage(self): """ Returns a ``float`` of the percentage of shots the home team saved. Percentage ranges from 0-1. """ try: save_pct = float(self.home_saves) /
python
{ "resource": "" }
q251211
Game.location
train
def location(self): """ Returns a ``string`` constant to indicate whether the game was played at home, away, or in a neutral location. """ if self._location.lower() == 'n':
python
{ "resource": "" }
q251212
Game.rank
train
def rank(self): """ Returns an ``int`` of the team's rank at the time the game was played. """
python
{ "resource": "" }
q251213
Game.datetime
train
def datetime(self): """ Returns a datetime object of the month, day, year, and time the game was played.
python
{ "resource": "" }
q251214
Game.game_number_for_day
train
def game_number_for_day(self): """ Returns an ``int`` denoting which game is played for the team during the given day. Default value is 1 where a team plays only one game during the day, but can be higher for double headers, etc. For example, if a team has a double header one day...
python
{ "resource": "" }
q251215
Game.games_behind
train
def games_behind(self): """ Returns a ``float`` of the number of games behind the leader the team is. 0.0 indicates the team is tied for first. Negative numbers indicate the number of games a team is ahead of the second place team. """ if 'up'
python
{ "resource": "" }
q251216
Team._parse_name
train
def _parse_name(self, team_data): """ Parses the team's name. On the pages being parsed, the team's name doesn't follow the standard parsing algorithm that we use for the fields, and requires a special one-off algorithm. The name is attached in the 'title' attribute from ...
python
{ "resource": "" }
q251217
Game._parse_opponent_abbr
train
def _parse_opponent_abbr(self, game_data): """ Parses the opponent's abbreviation for the game. The opponent's 3-letter abbreviation is embedded within the HTML tag and needs a special parsing scheme in order to be extracted.
python
{ "resource": "" }
q251218
Schedule._add_games_to_schedule
train
def _add_games_to_schedule(self, schedule): """ Add game information to list of games. Create a Game instance for the given game in the schedule and add it to the list of games the team has or will play during the season. Parameters ---------- schedule : PyQuery...
python
{ "resource": "" }
q251219
BoxscorePlayer.dataframe
train
def dataframe(self): """ Returns a ``pandas DataFrame`` containing all other relevant class properties and value for the specified game. """ fields_to_include = { 'completed_passes': self.completed_passes, 'attempted_passes': self.attempted_passes, ...
python
{ "resource": "" }
q251220
Boxscore.dataframe
train
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string URI that is used to instantiate the class, such as '2018-01-08-georgia'. """ if self._away_points is None and self._home_points ...
python
{ "resource": "" }
q251221
Boxscore.winning_abbr
train
def winning_abbr(self): """ Returns a ``string`` of the winning team's abbreviation, such as 'ALABAMA' for the Alabama Crimson Tide. """ if self.winner == HOME: if 'cfb/schools' not in str(self._home_name): return self._home_name.text()
python
{ "resource": "" }
q251222
Player._combine_all_stats
train
def _combine_all_stats(self, player_info): """ Pull stats from all tables into a single data structure. Pull the stats from all of the requested tables into a dictionary that is separated by season to allow easy queries of the player's stats for each season. Parameters ...
python
{ "resource": "" }
q251223
Player._pull_player_data
train
def _pull_player_data(self): """ Pull and aggregate all player information. Pull the player's HTML stats page and parse unique properties, such as the player's height, weight, and name. Next, combine all stats for all seasons plus the player's career stats into a single object w...
python
{ "resource": "" }
q251224
Player.team_abbreviation
train
def team_abbreviation(self): """ Returns a ``string`` of the team's abbreviation, such as 'DET' for the Detroit Red Wings.
python
{ "resource": "" }
q251225
Notebook.add_cell_footer
train
def add_cell_footer(self): """ Add footer cell """ # check if there's already a cell footer... if true, do not add a second cell footer. # this situation happens when exporting to ipynb and then importing from ipynb. logging.info('Adding footer cell') for cell ...
python
{ "resource": "" }
q251226
Notebook.get_kernelspec
train
def get_kernelspec(self, name): """Get a kernel specification dictionary given a kernel name """ ksm = KernelSpecManager() kernelspec = ksm.get_kernel_spec(name).to_dict()
python
{ "resource": "" }
q251227
docker_start
train
def docker_start(develop=True): """ Start docker container """ curr_dir = os.path.dirname(os.path.realpath(__file__)) local('docker run --rm --name pynb -d -ti -p 127.0.0.1:8889:8888 -v {}:/code -t pynb'.format(curr_dir)) if develop:
python
{ "resource": "" }
q251228
TextBasedParser.read
train
def read(self, file): """Reads the captions file.""" content = self._read_content(file)
python
{ "resource": "" }
q251229
TextBasedParser._parse_timeframe_line
train
def _parse_timeframe_line(self, line): """Parse timeframe line and return start and end timestamps."""
python
{ "resource": "" }
q251230
main
train
def main(): """Main entry point for CLI commands.""" options = docopt(__doc__, version=__version__) if options['segment']:
python
{ "resource": "" }
q251231
segment
train
def segment(f, output, target_duration, mpegts): """Segment command.""" try: target_duration = int(target_duration) except ValueError:
python
{ "resource": "" }
q251232
WebVTT.from_srt
train
def from_srt(cls, file): """Reads captions from a file in SubRip format."""
python
{ "resource": "" }
q251233
WebVTT.from_sbv
train
def from_sbv(cls, file): """Reads captions from a file in YouTube SBV format."""
python
{ "resource": "" }
q251234
WebVTT.read
train
def read(cls, file): """Reads a WebVTT captions file.""" parser = WebVTTParser().read(file)
python
{ "resource": "" }
q251235
WebVTT.save
train
def save(self, output=''): """Save the document. If no output is provided the file will be saved in the same location. Otherwise output
python
{ "resource": "" }
q251236
WebVTT.total_length
train
def total_length(self): """Returns the total length of the captions.""" if not self._captions: return 0
python
{ "resource": "" }
q251237
WebVTTSegmenter.segment
train
def segment(self, webvtt, output='', seconds=SECONDS, mpegts=MPEGTS): """Segments the captions based on a number of seconds.""" if isinstance(webvtt, str): # if a string is supplied we parse the file captions = WebVTT().read(webvtt).captions elif not self._validate_webvtt...
python
{ "resource": "" }
q251238
best_fts_version
train
def best_fts_version(): "Discovers the most advanced supported SQLite FTS version" conn = sqlite3.connect(":memory:") for fts in ("FTS5", "FTS4", "FTS3"): try:
python
{ "resource": "" }
q251239
add_click_commands
train
def add_click_commands(module, cli, command_dict, namespaced): """Loads all click commands""" module_commands = [ item for item in getmembers(module) if isinstance(item[1], BaseCommand) ] options = command_dict.get('config', {}) namespace = command_dict.get('namespace') for name,...
python
{ "resource": "" }
q251240
load_commands
train
def load_commands(cli, manage_dict): """Loads the commands defined in manage file""" namespaced = manage_dict.get('namespaced') # get click commands commands = manage_dict.get('click_commands', []) for command_dict in commands: root_module = import_string(command_dict['module']) gro...
python
{ "resource": "" }
q251241
debug
train
def debug(version=False): """Shows the parsed manage file -V shows version""" if version: print(__version__)
python
{ "resource": "" }
q251242
create_shell
train
def create_shell(console, manage_dict=None, extra_vars=None, exit_hooks=None): """Creates the shell""" manage_dict = manage_dict or MANAGE_DICT _vars = globals() _vars.update(locals()) auto_imported = import_objects(manage_dict) if extra_vars: auto_imported.update(extra_vars) _vars.u...
python
{ "resource": "" }
q251243
find_invalid_filenames
train
def find_invalid_filenames(filenames, repository_root): """Find files that does not exist, are not in the repo or are directories. Args: filenames: list of filenames to check repository_root: the absolute path of the repository's root. Returns: A list of errors. """ errors = [] for...
python
{ "resource": "" }
q251244
get_config
train
def get_config(repo_root): """Gets the configuration file either from the repository or the default.""" config = os.path.join(os.path.dirname(__file__), 'configs', 'config.yaml') if repo_root: repo_config = os.path.join(repo_root, '.gitlint.yaml') if os.path.exists(repo_config): ...
python
{ "resource": "" }
q251245
format_comment
train
def format_comment(comment_data): """Formats the data returned by the linters. Given a dictionary with the fields: line, column, severity, message_id, message, will generate a message like: 'line {line}, col {column}: {severity}: [{message_id}]: {message}' Any of the fields may nbe absent. A...
python
{ "resource": "" }
q251246
get_vcs_root
train
def get_vcs_root(): """Returns the vcs module and the root of the repo. Returns: A tuple containing the vcs module to use (git, hg) and the root of the
python
{ "resource": "" }
q251247
process_file
train
def process_file(vcs, commit, force, gitlint_config, file_data): """Lint the file Returns: The results from the linter. """ filename, extra_data = file_data if force: modified_lines = None else: modified_lines = vcs.modified_lines(
python
{ "resource": "" }
q251248
last_commit
train
def last_commit(): """Returns the SHA1 of the last commit.""" try: root = subprocess.check_output( ['hg', 'parent', '--template={node}'], stderr=subprocess.STDOUT).strip()
python
{ "resource": "" }
q251249
modified_files
train
def modified_files(root, tracked_only=False, commit=None): """Returns a list of files that has been modified since the last commit. Args: root: the root of the repository, it has to be an absolute path. tracked_only: exclude untracked files when True. commit: SHA1 of the commit. If None, it w...
python
{ "resource": "" }
q251250
lint
train
def lint(filename): """Lints an INI file, returning 0 in case of success.""" config = ConfigParser.ConfigParser() try:
python
{ "resource": "" }
q251251
missing_requirements_command
train
def missing_requirements_command(missing_programs, installation_string, filename, unused_lines): """Pseudo-command to be used when requirements are missing.""" verb = 'is'
python
{ "resource": "" }
q251252
lint_command
train
def lint_command(name, program, arguments, filter_regex, filename, lines): """Executes a lint program and filter the output. Executes the lint tool 'program' with arguments 'arguments' over the file 'filename' returning only those lines matching the regular expression 'filter_regex'. Args: n...
python
{ "resource": "" }
q251253
_replace_variables
train
def _replace_variables(data, variables): """Replace the format variables in all items of data.""" formatter =
python
{ "resource": "" }
q251254
lint
train
def lint(filename, lines, config): """Lints a file. Args: filename: string: filename to lint. lines: list[int]|None: list of lines that we want to capture. If None, then all lines will be captured. config: dict[string: linter]: mapping from extension to a linter func...
python
{ "resource": "" }
q251255
filter_lines
train
def filter_lines(lines, filter_regex, groups=None): """Filters out the lines not matching the pattern. Args: lines: list[string]: lines to filter. pattern: string: regular expression to filter out lines. Returns: list[string]: the list of filtered lines. """ pattern = re.compile(filter...
python
{ "resource": "" }
q251256
which
train
def which(program): """Returns a list of paths where the program is found.""" if (os.path.isabs(program) and os.path.isfile(program) and os.access(program, os.X_OK)): return [program]
python
{ "resource": "" }
q251257
_open_for_write
train
def _open_for_write(filename): """Opens filename for writing, creating the directories if needed.""" dirname = os.path.dirname(filename)
python
{ "resource": "" }
q251258
_get_cache_filename
train
def _get_cache_filename(name, filename): """Returns the cache location for filename and linter name.""" filename = os.path.abspath(filename)[1:] home_folder = os.path.expanduser('~')
python
{ "resource": "" }
q251259
get_output_from_cache
train
def get_output_from_cache(name, filename): """Returns the output from the cache if still valid. It checks that the cache file is defined and that its modification time is after the modification time of the original file. Args: name: string: name of the linter. filename: string: path of the...
python
{ "resource": "" }
q251260
save_output_in_cache
train
def save_output_in_cache(name, filename, output): """Saves output in the cache location. Args: name: string: name of the linter. filename: string: path of the filename for which we are saving the output. output: string: full
python
{ "resource": "" }
q251261
md5
train
def md5(text): """Returns the md5 hash of a string.""" h = hashlib.md5()
python
{ "resource": "" }
q251262
cleanup_nodes
train
def cleanup_nodes(doc): """ Remove text nodes containing only whitespace """ for node in doc.documentElement.childNodes: if
python
{ "resource": "" }
q251263
_collect_nodes
train
def _collect_nodes(limit, sender, method_name, cacheable, params=None): """ Returns a sequence of dom.Node objects about as close to limit as possible """ if not params: params = sender._get_params() nodes = [] page = 1 end_of_pages = False while not end_of_pages and (not limi...
python
{ "resource": "" }
q251264
_extract
train
def _extract(node, name, index=0): """Extracts a value from the xml string""" nodes = node.getElementsByTagName(name) if len(nodes): if nodes[index].firstChild:
python
{ "resource": "" }
q251265
_extract_all
train
def _extract_all(node, name, limit_count=None): """Extracts all the values from the xml string. returning a list.""" seq = [] for i in range(0, len(node.getElementsByTagName(name))):
python
{ "resource": "" }
q251266
_Network._delay_call
train
def _delay_call(self): """ Makes sure that web service calls are at least 0.2 seconds apart. """ now = time.time() time_since_last = now - self.last_call_time
python
{ "resource": "" }
q251267
_Network.get_top_artists
train
def get_top_artists(self, limit=None, cacheable=True): """Returns the most played artists as a sequence of TopItem objects.""" params = {} if limit: params["limit"] =
python
{ "resource": "" }
q251268
_Network.get_top_tracks
train
def get_top_tracks(self, limit=None, cacheable=True): """Returns the most played tracks as a sequence of TopItem objects.""" params = {} if limit: params["limit"] = limit doc = _Request(self, "chart.getTopTracks", params).execute(cacheable) seq = [] for nod...
python
{ "resource": "" }
q251269
_Network.get_top_tags
train
def get_top_tags(self, limit=None, cacheable=True): """Returns the most used tags as a sequence of TopItem objects.""" # Last.fm has no "limit" parameter for tag.getTopTags # so we need to get all (250) and then limit locally doc = _Request(self, "tag.getTopTags").execute(cacheable) ...
python
{ "resource": "" }
q251270
_Network.enable_proxy
train
def enable_proxy(self, host, port): """Enable a default web proxy"""
python
{ "resource": "" }
q251271
_Network.enable_caching
train
def enable_caching(self, file_path=None): """Enables caching request-wide for all cacheable calls. * file_path: A file path for the backend storage file. If None set, a temp file would probably be created, according the backend. """
python
{ "resource": "" }
q251272
_Network.get_track_by_mbid
train
def get_track_by_mbid(self, mbid): """Looks up a track by its MusicBrainz ID""" params = {"mbid": mbid}
python
{ "resource": "" }
q251273
_Network.get_artist_by_mbid
train
def get_artist_by_mbid(self, mbid): """Looks up an artist by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "artist.getInfo",
python
{ "resource": "" }
q251274
_Network.get_album_by_mbid
train
def get_album_by_mbid(self, mbid): """Looks up an album by its MusicBrainz ID""" params = {"mbid":
python
{ "resource": "" }
q251275
_Network.update_now_playing
train
def update_now_playing( self, artist, title, album=None, album_artist=None, duration=None, track_number=None, mbid=None, context=None, ): """ Used to notify Last.fm that a user has started listening to a track. Para...
python
{ "resource": "" }
q251276
_Network.scrobble
train
def scrobble( self, artist, title, timestamp, album=None, album_artist=None, track_number=None, duration=None, stream_id=None, context=None, mbid=None, ): """Used to add a track-play to a user's profile. Parame...
python
{ "resource": "" }
q251277
_Request._get_signature
train
def _get_signature(self): """ Returns a 32-character hexadecimal md5 hash of the signature string. """ keys = list(self.params.keys()) keys.sort() string = "" for name in keys:
python
{ "resource": "" }
q251278
_Request._get_cache_key
train
def _get_cache_key(self): """ The cache key is a string of concatenated sorted names and values. """ keys = list(self.params.keys()) keys.sort() cache_key = str() for key in keys:
python
{ "resource": "" }
q251279
_Request._get_cached_response
train
def _get_cached_response(self): """Returns a file object of the cached response.""" if not self._is_cached(): response = self._download_response()
python
{ "resource": "" }
q251280
_Request._download_response
train
def _download_response(self): """Returns a response body string from the server.""" if self.network.limit_rate: self.network._delay_call() data = [] for name in self.params.keys(): data.append("=".join((name, url_quote_plus(_string(self.params[name]))))) ...
python
{ "resource": "" }
q251281
_Request.execute
train
def execute(self, cacheable=False): """Returns the XML DOM response of the POST Request from the server""" if self.network.is_caching_enabled() and cacheable: response = self._get_cached_response() else:
python
{ "resource": "" }
q251282
_Request._check_response_for_errors
train
def _check_response_for_errors(self, response): """Checks the response for errors and raises one if any exists.""" try: doc = minidom.parseString(_string(response).replace("opensearch:", "")) except Exception as e: raise MalformedResponseError(self.network, e) e...
python
{ "resource": "" }
q251283
SessionKeyGenerator._get_web_auth_token
train
def _get_web_auth_token(self): """ Retrieves a token from the network for web authentication. The token then has to be authorized from getAuthURL before creating session. """ request = _Request(self.network, "auth.getToken") # default action is that a request is...
python
{ "resource": "" }
q251284
SessionKeyGenerator.get_web_auth_session_key
train
def get_web_auth_session_key(self, url, token=""): """ Retrieves the session key of a web authorization process by its URL. """
python
{ "resource": "" }
q251285
SessionKeyGenerator.get_session_key
train
def get_session_key(self, username, password_hash): """ Retrieve a session key with a username and a md5 hash of the user's password. """ params = {"username": username, "authToken": md5(username
python
{ "resource": "" }
q251286
_BaseObject._get_things
train
def _get_things(self, method, thing, thing_type, params=None, cacheable=True): """Returns a list of the most played thing_types by this thing.""" limit = params.get("limit", 1) seq = [] for node in _collect_nodes( limit, self, self.ws_prefix + "." + method, cacheable, params...
python
{ "resource": "" }
q251287
_Chartable.get_weekly_chart_dates
train
def get_weekly_chart_dates(self): """Returns a list of From and To tuples for the available charts.""" doc = self._request(self.ws_prefix + ".getWeeklyChartList", True) seq = []
python
{ "resource": "" }
q251288
_Chartable.get_weekly_charts
train
def get_weekly_charts(self, chart_kind, from_date=None, to_date=None): """ Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track" """ method = ".getWeekly" + chart_kind.title(...
python
{ "resource": "" }
q251289
_Taggable.remove_tag
train
def remove_tag(self, tag): """Remove a user's tag from this object.""" if isinstance(tag, Tag):
python
{ "resource": "" }
q251290
_Taggable.get_tags
train
def get_tags(self): """Returns a list of the tags set by the user to this object.""" # Uncacheable because it can be dynamically changed by the user. params = self._get_params() doc = self._request(self.ws_prefix + ".getTags", False, params)
python
{ "resource": "" }
q251291
_Taggable.get_top_tags
train
def get_top_tags(self, limit=None): """Returns a list of the most frequently used Tags on this object.""" doc = self._request(self.ws_prefix + ".getTopTags", True) elements = doc.getElementsByTagName("tag") seq = [] for element in elements:
python
{ "resource": "" }
q251292
_Opus.get_title
train
def get_title(self, properly_capitalized=False): """Returns the artist or track title.""" if properly_capitalized:
python
{ "resource": "" }
q251293
_Opus.get_playcount
train
def get_playcount(self): """Returns the number of plays on the network""" return _number( _extract(
python
{ "resource": "" }
q251294
_Opus.get_userplaycount
train
def get_userplaycount(self): """Returns the number of plays by a given username""" if not self.username: return
python
{ "resource": "" }
q251295
_Opus.get_listener_count
train
def get_listener_count(self): """Returns the number of listeners on the network""" return _number(
python
{ "resource": "" }
q251296
_Opus.get_mbid
train
def get_mbid(self): """Returns the MusicBrainz ID of the album or track.""" doc = self._request(self.ws_prefix + ".getInfo", cacheable=True) try: lfm = doc.getElementsByTagName("lfm")[0]
python
{ "resource": "" }
q251297
Album.get_tracks
train
def get_tracks(self): """Returns the list of Tracks on this album.""" return _extract_tracks(
python
{ "resource": "" }
q251298
Artist.get_name
train
def get_name(self, properly_capitalized=False): """Returns the name of the artist. If properly_capitalized was asserted then the name would be downloaded overwriting the given one.""" if properly_capitalized:
python
{ "resource": "" }
q251299
Artist.get_mbid
train
def get_mbid(self): """Returns the MusicBrainz ID of this artist."""
python
{ "resource": "" }