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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
roclark/sportsreference | sportsreference/nhl/schedule.py | Game.overtime | def overtime(self):
"""
Returns an ``int`` of the number of overtimes that were played during
the game, or an int constant if the game went to a shootout.
"""
if self._overtime.lower() == 'ot':
return 1
if self._overtime.lower() == 'so':
return SHOOTOUT
if self._overtime == '':
return 0
num = re.findall(r'\d+', self._overtime)
if len(num) > 0:
return num[0]
return 0 | python | def overtime(self):
"""
Returns an ``int`` of the number of overtimes that were played during
the game, or an int constant if the game went to a shootout.
"""
if self._overtime.lower() == 'ot':
return 1
if self._overtime.lower() == 'so':
return SHOOTOUT
if self._overtime == '':
return 0
num = re.findall(r'\d+', self._overtime)
if len(num) > 0:
return num[0]
return 0 | [
"def",
"overtime",
"(",
"self",
")",
":",
"if",
"self",
".",
"_overtime",
".",
"lower",
"(",
")",
"==",
"'ot'",
":",
"return",
"1",
"if",
"self",
".",
"_overtime",
".",
"lower",
"(",
")",
"==",
"'so'",
":",
"return",
"SHOOTOUT",
"if",
"self",
".",
... | Returns an ``int`` of the number of overtimes that were played during
the game, or an int constant if the game went to a shootout. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"overtimes",
"that",
"were",
"played",
"during",
"the",
"game",
"or",
"an",
"int",
"constant",
"if",
"the",
"game",
"went",
"to",
"a",
"shootout",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/schedule.py#L284-L298 | train | 34,600 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.datetime | def datetime(self):
"""
Returns a datetime object to indicate the month, day, year, and time
the requested game took place.
"""
date_string = '%s %s' % (self._date, self._time.upper())
date_string = re.sub(r'/.*', '', date_string)
date_string = re.sub(r' ET', '', date_string)
date_string += 'M'
date_string = re.sub(r'PMM', 'PM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r'AMM', 'AM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r' PM', 'PM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r' AM', 'AM', date_string, flags=re.IGNORECASE)
return datetime.strptime(date_string, '%a, %b %d, %Y %I:%M%p') | python | def datetime(self):
"""
Returns a datetime object to indicate the month, day, year, and time
the requested game took place.
"""
date_string = '%s %s' % (self._date, self._time.upper())
date_string = re.sub(r'/.*', '', date_string)
date_string = re.sub(r' ET', '', date_string)
date_string += 'M'
date_string = re.sub(r'PMM', 'PM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r'AMM', 'AM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r' PM', 'PM', date_string, flags=re.IGNORECASE)
date_string = re.sub(r' AM', 'AM', date_string, flags=re.IGNORECASE)
return datetime.strptime(date_string, '%a, %b %d, %Y %I:%M%p') | [
"def",
"datetime",
"(",
"self",
")",
":",
"date_string",
"=",
"'%s %s'",
"%",
"(",
"self",
".",
"_date",
",",
"self",
".",
"_time",
".",
"upper",
"(",
")",
")",
"date_string",
"=",
"re",
".",
"sub",
"(",
"r'/.*'",
",",
"''",
",",
"date_string",
")"... | Returns a datetime object to indicate the month, day, year, and time
the requested game took place. | [
"Returns",
"a",
"datetime",
"object",
"to",
"indicate",
"the",
"month",
"day",
"year",
"and",
"time",
"the",
"requested",
"game",
"took",
"place",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L195-L208 | train | 34,601 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.type | def type(self):
"""
Returns a ``string`` constant to indicate whether the game was played
during the regular season or in the post season.
"""
if self._type.lower() == 'reg':
return REGULAR_SEASON
if self._type.lower() == 'ctourn':
return CONFERENCE_TOURNAMENT
if self._type.lower() == 'ncaa':
return NCAA_TOURNAMENT
if self._type.lower() == 'nit':
return NIT_TOURNAMENT
if self._type.lower() == 'cbi':
return CBI_TOURNAMENT
if self._type.lower() == 'cit':
return CIT_TOURNAMENT | python | def type(self):
"""
Returns a ``string`` constant to indicate whether the game was played
during the regular season or in the post season.
"""
if self._type.lower() == 'reg':
return REGULAR_SEASON
if self._type.lower() == 'ctourn':
return CONFERENCE_TOURNAMENT
if self._type.lower() == 'ncaa':
return NCAA_TOURNAMENT
if self._type.lower() == 'nit':
return NIT_TOURNAMENT
if self._type.lower() == 'cbi':
return CBI_TOURNAMENT
if self._type.lower() == 'cit':
return CIT_TOURNAMENT | [
"def",
"type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_type",
".",
"lower",
"(",
")",
"==",
"'reg'",
":",
"return",
"REGULAR_SEASON",
"if",
"self",
".",
"_type",
".",
"lower",
"(",
")",
"==",
"'ctourn'",
":",
"return",
"CONFERENCE_TOURNAMENT",
"if"... | Returns a ``string`` constant to indicate whether the game was played
during the regular season or in the post season. | [
"Returns",
"a",
"string",
"constant",
"to",
"indicate",
"whether",
"the",
"game",
"was",
"played",
"during",
"the",
"regular",
"season",
"or",
"in",
"the",
"post",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L235-L251 | train | 34,602 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.location | def location(self):
"""
Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site.
"""
if self._location == '':
return HOME
if self._location == 'N':
return NEUTRAL
if self._location == '@':
return AWAY | python | def location(self):
"""
Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site.
"""
if self._location == '':
return HOME
if self._location == 'N':
return NEUTRAL
if self._location == '@':
return AWAY | [
"def",
"location",
"(",
"self",
")",
":",
"if",
"self",
".",
"_location",
"==",
"''",
":",
"return",
"HOME",
"if",
"self",
".",
"_location",
"==",
"'N'",
":",
"return",
"NEUTRAL",
"if",
"self",
".",
"_location",
"==",
"'@'",
":",
"return",
"AWAY"
] | Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site. | [
"Returns",
"a",
"string",
"constant",
"to",
"indicate",
"whether",
"the",
"game",
"was",
"played",
"at",
"the",
"team",
"s",
"home",
"venue",
"the",
"opponent",
"s",
"venue",
"or",
"at",
"a",
"neutral",
"site",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L254-L264 | train | 34,603 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.opponent_name | def opponent_name(self):
"""
Returns a ``string`` of the opponent's name, such as the 'Purdue
Boilermakers'.
"""
name = re.sub(r'\(\d+\)', '', self._opponent_name)
name = name.replace(u'\xa0', '')
return name | python | def opponent_name(self):
"""
Returns a ``string`` of the opponent's name, such as the 'Purdue
Boilermakers'.
"""
name = re.sub(r'\(\d+\)', '', self._opponent_name)
name = name.replace(u'\xa0', '')
return name | [
"def",
"opponent_name",
"(",
"self",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"r'\\(\\d+\\)'",
",",
"''",
",",
"self",
".",
"_opponent_name",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"u'\\xa0'",
",",
"''",
")",
"return",
"name"
] | Returns a ``string`` of the opponent's name, such as the 'Purdue
Boilermakers'. | [
"Returns",
"a",
"string",
"of",
"the",
"opponent",
"s",
"name",
"such",
"as",
"the",
"Purdue",
"Boilermakers",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L275-L282 | train | 34,604 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.opponent_rank | def opponent_rank(self):
"""
Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked.
"""
rank = re.findall(r'\d+', self._opponent_name)
if len(rank) > 0:
return int(rank[0])
return None | python | def opponent_rank(self):
"""
Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked.
"""
rank = re.findall(r'\d+', self._opponent_name)
if len(rank) > 0:
return int(rank[0])
return None | [
"def",
"opponent_rank",
"(",
"self",
")",
":",
"rank",
"=",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"self",
".",
"_opponent_name",
")",
"if",
"len",
"(",
"rank",
")",
">",
"0",
":",
"return",
"int",
"(",
"rank",
"[",
"0",
"]",
")",
"return",
"... | Returns a ``string`` of the opponent's rank when the game was played
and None if the team was unranked. | [
"Returns",
"a",
"string",
"of",
"the",
"opponent",
"s",
"rank",
"when",
"the",
"game",
"was",
"played",
"and",
"None",
"if",
"the",
"team",
"was",
"unranked",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L285-L293 | train | 34,605 |
roclark/sportsreference | sportsreference/ncaab/schedule.py | Game.overtimes | def overtimes(self):
"""
Returns an ``int`` of the number of overtimes that were played during
the game and 0 if the game finished at the end of regulation time.
"""
if self._overtimes == '' or self._overtimes is None:
return 0
if self._overtimes.lower() == 'ot':
return 1
num_overtimes = re.findall(r'\d+', self._overtimes)
try:
return int(num_overtimes[0])
except (ValueError, IndexError):
return 0 | python | def overtimes(self):
"""
Returns an ``int`` of the number of overtimes that were played during
the game and 0 if the game finished at the end of regulation time.
"""
if self._overtimes == '' or self._overtimes is None:
return 0
if self._overtimes.lower() == 'ot':
return 1
num_overtimes = re.findall(r'\d+', self._overtimes)
try:
return int(num_overtimes[0])
except (ValueError, IndexError):
return 0 | [
"def",
"overtimes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_overtimes",
"==",
"''",
"or",
"self",
".",
"_overtimes",
"is",
"None",
":",
"return",
"0",
"if",
"self",
".",
"_overtimes",
".",
"lower",
"(",
")",
"==",
"'ot'",
":",
"return",
"1",
"n... | Returns an ``int`` of the number of overtimes that were played during
the game and 0 if the game finished at the end of regulation time. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"overtimes",
"that",
"were",
"played",
"during",
"the",
"game",
"and",
"0",
"if",
"the",
"game",
"finished",
"at",
"the",
"end",
"of",
"regulation",
"time",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/schedule.py#L333-L346 | train | 34,606 |
roclark/sportsreference | sportsreference/nba/roster.py | Player._parse_nationality | def _parse_nationality(self, player_info):
"""
Parse the player's nationality.
The player's nationality is denoted by a flag in the information
section with a country code for each nation. The country code needs to
pulled and then matched to find the player's home country. Once found,
the '_nationality' attribute is set for the player.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
"""
for span in player_info('span').items():
if 'class="f-i' in str(span):
nationality = span.text()
nationality = NATIONALITY[nationality]
setattr(self, '_nationality', nationality)
break | python | def _parse_nationality(self, player_info):
"""
Parse the player's nationality.
The player's nationality is denoted by a flag in the information
section with a country code for each nation. The country code needs to
pulled and then matched to find the player's home country. Once found,
the '_nationality' attribute is set for the player.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
"""
for span in player_info('span').items():
if 'class="f-i' in str(span):
nationality = span.text()
nationality = NATIONALITY[nationality]
setattr(self, '_nationality', nationality)
break | [
"def",
"_parse_nationality",
"(",
"self",
",",
"player_info",
")",
":",
"for",
"span",
"in",
"player_info",
"(",
"'span'",
")",
".",
"items",
"(",
")",
":",
"if",
"'class=\"f-i'",
"in",
"str",
"(",
"span",
")",
":",
"nationality",
"=",
"span",
".",
"te... | Parse the player's nationality.
The player's nationality is denoted by a flag in the information
section with a country code for each nation. The country code needs to
pulled and then matched to find the player's home country. Once found,
the '_nationality' attribute is set for the player.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page. | [
"Parse",
"the",
"player",
"s",
"nationality",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L312-L331 | train | 34,607 |
roclark/sportsreference | sportsreference/nba/roster.py | Player._parse_contract_headers | def _parse_contract_headers(self, table):
"""
Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list where each element is a string denoting the season,
such as '2017-18'.
"""
years = [i.text() for i in table('th').items()]
years.remove('Team')
return years | python | def _parse_contract_headers(self, table):
"""
Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list where each element is a string denoting the season,
such as '2017-18'.
"""
years = [i.text() for i in table('th').items()]
years.remove('Team')
return years | [
"def",
"_parse_contract_headers",
"(",
"self",
",",
"table",
")",
":",
"years",
"=",
"[",
"i",
".",
"text",
"(",
")",
"for",
"i",
"in",
"table",
"(",
"'th'",
")",
".",
"items",
"(",
")",
"]",
"years",
".",
"remove",
"(",
"'Team'",
")",
"return",
... | Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list where each element is a string denoting the season,
such as '2017-18'. | [
"Parse",
"the",
"years",
"on",
"the",
"contract",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L366-L387 | train | 34,608 |
roclark/sportsreference | sportsreference/nba/roster.py | Player._parse_contract_wages | def _parse_contract_wages(self, table):
"""
Parse the wages on the contract.
The wages are listed as the data points in the contract table. Any
values that don't have a value which starts with a '$' sign are likely
not valid and should be dropped.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list of all wages where each element is a string denoting
the dollar amount, such as '$40,000,000'.
"""
wages = [i.text() if i.text().startswith('$') else ''
for i in table('td').items()]
wages.remove('')
return wages | python | def _parse_contract_wages(self, table):
"""
Parse the wages on the contract.
The wages are listed as the data points in the contract table. Any
values that don't have a value which starts with a '$' sign are likely
not valid and should be dropped.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list of all wages where each element is a string denoting
the dollar amount, such as '$40,000,000'.
"""
wages = [i.text() if i.text().startswith('$') else ''
for i in table('td').items()]
wages.remove('')
return wages | [
"def",
"_parse_contract_wages",
"(",
"self",
",",
"table",
")",
":",
"wages",
"=",
"[",
"i",
".",
"text",
"(",
")",
"if",
"i",
".",
"text",
"(",
")",
".",
"startswith",
"(",
"'$'",
")",
"else",
"''",
"for",
"i",
"in",
"table",
"(",
"'td'",
")",
... | Parse the wages on the contract.
The wages are listed as the data points in the contract table. Any
values that don't have a value which starts with a '$' sign are likely
not valid and should be dropped.
Parameters
----------
table : PyQuery object
A PyQuery object containing the contract table.
Returns
-------
list
Returns a list of all wages where each element is a string denoting
the dollar amount, such as '$40,000,000'. | [
"Parse",
"the",
"wages",
"on",
"the",
"contract",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L389-L411 | train | 34,609 |
roclark/sportsreference | sportsreference/nba/roster.py | Player._combine_contract | def _combine_contract(self, years, wages):
"""
Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a string denoting the season, such as
'2017-18'.
wages : list
A list of all wages where each element is a string denoting the
dollar amount, such as '$40,000,000'.
Returns
-------
dictionary
Returns a dictionary representing the player's contract where each
key is a ``string`` of the season, such as '2017-18' and each value
is a ``string`` of the wages, such as '$40,000,000'.
"""
contract = {}
for i in range(len(years)):
contract[years[i]] = wages[i]
return contract | python | def _combine_contract(self, years, wages):
"""
Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a string denoting the season, such as
'2017-18'.
wages : list
A list of all wages where each element is a string denoting the
dollar amount, such as '$40,000,000'.
Returns
-------
dictionary
Returns a dictionary representing the player's contract where each
key is a ``string`` of the season, such as '2017-18' and each value
is a ``string`` of the wages, such as '$40,000,000'.
"""
contract = {}
for i in range(len(years)):
contract[years[i]] = wages[i]
return contract | [
"def",
"_combine_contract",
"(",
"self",
",",
"years",
",",
"wages",
")",
":",
"contract",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"years",
")",
")",
":",
"contract",
"[",
"years",
"[",
"i",
"]",
"]",
"=",
"wages",
"[",
"i",
... | Combine the contract wages and year.
Match the wages with the year and add to a dictionary representing the
player's contract.
Parameters
----------
years : list
A list where each element is a string denoting the season, such as
'2017-18'.
wages : list
A list of all wages where each element is a string denoting the
dollar amount, such as '$40,000,000'.
Returns
-------
dictionary
Returns a dictionary representing the player's contract where each
key is a ``string`` of the season, such as '2017-18' and each value
is a ``string`` of the wages, such as '$40,000,000'. | [
"Combine",
"the",
"contract",
"wages",
"and",
"year",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L413-L440 | train | 34,610 |
roclark/sportsreference | sportsreference/nba/roster.py | Player._find_initial_index | def _find_initial_index(self):
"""
Find the index of career stats.
When the Player class is instantiated, the default stats to pull are
the player's career stats. Upon being called, the index of the 'Career'
element should be the index value.
"""
index = 0
for season in self._season:
if season == 'Career':
self._index = index
break
index += 1 | python | def _find_initial_index(self):
"""
Find the index of career stats.
When the Player class is instantiated, the default stats to pull are
the player's career stats. Upon being called, the index of the 'Career'
element should be the index value.
"""
index = 0
for season in self._season:
if season == 'Career':
self._index = index
break
index += 1 | [
"def",
"_find_initial_index",
"(",
"self",
")",
":",
"index",
"=",
"0",
"for",
"season",
"in",
"self",
".",
"_season",
":",
"if",
"season",
"==",
"'Career'",
":",
"self",
".",
"_index",
"=",
"index",
"break",
"index",
"+=",
"1"
] | Find the index of career stats.
When the Player class is instantiated, the default stats to pull are
the player's career stats. Upon being called, the index of the 'Career'
element should be the index value. | [
"Find",
"the",
"index",
"of",
"career",
"stats",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L495-L508 | train | 34,611 |
roclark/sportsreference | sportsreference/ncaab/roster.py | Player._parse_player_position | def _parse_player_position(self, player_info):
"""
Parse the player's position.
The player's position isn't contained within a unique tag and the
player's meta information should be iterated through until 'Position'
is found as it contains the desired text.
Parameters
----------
player_info : PyQuery object
A PyQuery object of the player's information on the HTML stats
page.
"""
for section in player_info('div#meta p').items():
if 'Position' in str(section):
position = section.text().replace('Position: ', '')
setattr(self, '_position', position)
break | python | def _parse_player_position(self, player_info):
"""
Parse the player's position.
The player's position isn't contained within a unique tag and the
player's meta information should be iterated through until 'Position'
is found as it contains the desired text.
Parameters
----------
player_info : PyQuery object
A PyQuery object of the player's information on the HTML stats
page.
"""
for section in player_info('div#meta p').items():
if 'Position' in str(section):
position = section.text().replace('Position: ', '')
setattr(self, '_position', position)
break | [
"def",
"_parse_player_position",
"(",
"self",
",",
"player_info",
")",
":",
"for",
"section",
"in",
"player_info",
"(",
"'div#meta p'",
")",
".",
"items",
"(",
")",
":",
"if",
"'Position'",
"in",
"str",
"(",
"section",
")",
":",
"position",
"=",
"section",... | Parse the player's position.
The player's position isn't contained within a unique tag and the
player's meta information should be iterated through until 'Position'
is found as it contains the desired text.
Parameters
----------
player_info : PyQuery object
A PyQuery object of the player's information on the HTML stats
page. | [
"Parse",
"the",
"player",
"s",
"position",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/roster.py#L258-L276 | train | 34,612 |
roclark/sportsreference | sportsreference/ncaab/roster.py | Player._parse_conference | def _parse_conference(self, stats):
"""
Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'.
"""
conference_tag = stats(PLAYER_SCHEME['conference'])
conference = re.sub(r'.*/cbb/conferences/',
'',
str(conference_tag('a')))
conference = re.sub(r'/.*', '', conference)
return conference | python | def _parse_conference(self, stats):
"""
Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'.
"""
conference_tag = stats(PLAYER_SCHEME['conference'])
conference = re.sub(r'.*/cbb/conferences/',
'',
str(conference_tag('a')))
conference = re.sub(r'/.*', '', conference)
return conference | [
"def",
"_parse_conference",
"(",
"self",
",",
"stats",
")",
":",
"conference_tag",
"=",
"stats",
"(",
"PLAYER_SCHEME",
"[",
"'conference'",
"]",
")",
"conference",
"=",
"re",
".",
"sub",
"(",
"r'.*/cbb/conferences/'",
",",
"''",
",",
"str",
"(",
"conference_... | Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'. | [
"Parse",
"the",
"conference",
"abbreviation",
"for",
"the",
"player",
"s",
"team",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/roster.py#L278-L300 | train | 34,613 |
roclark/sportsreference | sportsreference/ncaab/roster.py | Player._parse_team_abbreviation | def _parse_team_abbreviation(self, stats):
"""
Parse the team abbreviation.
The team abbreviation is embedded within the team name tag and should
be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE' for
the Purdue Boilermakers.
"""
team_tag = stats(PLAYER_SCHEME['team_abbreviation'])
team = re.sub(r'.*/cbb/schools/', '', str(team_tag('a')))
team = re.sub(r'/.*', '', team)
return team | python | def _parse_team_abbreviation(self, stats):
"""
Parse the team abbreviation.
The team abbreviation is embedded within the team name tag and should
be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE' for
the Purdue Boilermakers.
"""
team_tag = stats(PLAYER_SCHEME['team_abbreviation'])
team = re.sub(r'.*/cbb/schools/', '', str(team_tag('a')))
team = re.sub(r'/.*', '', team)
return team | [
"def",
"_parse_team_abbreviation",
"(",
"self",
",",
"stats",
")",
":",
"team_tag",
"=",
"stats",
"(",
"PLAYER_SCHEME",
"[",
"'team_abbreviation'",
"]",
")",
"team",
"=",
"re",
".",
"sub",
"(",
"r'.*/cbb/schools/'",
",",
"''",
",",
"str",
"(",
"team_tag",
... | Parse the team abbreviation.
The team abbreviation is embedded within the team name tag and should
be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE' for
the Purdue Boilermakers. | [
"Parse",
"the",
"team",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/roster.py#L302-L323 | train | 34,614 |
roclark/sportsreference | sportsreference/nhl/player.py | AbstractPlayer._parse_player_data | def _parse_player_data(self, player_data):
"""
Parse all player information and set attributes.
Iterate through each class attribute to parse the data from the HTML
page and set the attribute value with the result.
Parameters
----------
player_data : dictionary or string
If this class is inherited from the ``Player`` class, player_data
will be a dictionary where each key is a string representing the
season and each value contains the HTML data as a string. If this
class is inherited from the ``BoxscorePlayer`` class, player_data
will be a string representing the player's game statistics in HTML
format.
"""
for field in self.__dict__:
short_field = str(field)[1:]
if short_field == 'player_id' or \
short_field == 'index' or \
short_field == 'most_recent_season' or \
short_field == 'name' or \
short_field == 'weight' or \
short_field == 'height' or \
short_field == 'season':
continue
field_stats = []
if type(player_data) == dict:
for year, data in player_data.items():
stats = pq(data['data'])
value = self._parse_value(stats, short_field)
field_stats.append(value)
else:
stats = pq(player_data)
value = self._parse_value(stats, short_field)
field_stats.append(value)
setattr(self, field, field_stats) | python | def _parse_player_data(self, player_data):
"""
Parse all player information and set attributes.
Iterate through each class attribute to parse the data from the HTML
page and set the attribute value with the result.
Parameters
----------
player_data : dictionary or string
If this class is inherited from the ``Player`` class, player_data
will be a dictionary where each key is a string representing the
season and each value contains the HTML data as a string. If this
class is inherited from the ``BoxscorePlayer`` class, player_data
will be a string representing the player's game statistics in HTML
format.
"""
for field in self.__dict__:
short_field = str(field)[1:]
if short_field == 'player_id' or \
short_field == 'index' or \
short_field == 'most_recent_season' or \
short_field == 'name' or \
short_field == 'weight' or \
short_field == 'height' or \
short_field == 'season':
continue
field_stats = []
if type(player_data) == dict:
for year, data in player_data.items():
stats = pq(data['data'])
value = self._parse_value(stats, short_field)
field_stats.append(value)
else:
stats = pq(player_data)
value = self._parse_value(stats, short_field)
field_stats.append(value)
setattr(self, field, field_stats) | [
"def",
"_parse_player_data",
"(",
"self",
",",
"player_data",
")",
":",
"for",
"field",
"in",
"self",
".",
"__dict__",
":",
"short_field",
"=",
"str",
"(",
"field",
")",
"[",
"1",
":",
"]",
"if",
"short_field",
"==",
"'player_id'",
"or",
"short_field",
"... | Parse all player information and set attributes.
Iterate through each class attribute to parse the data from the HTML
page and set the attribute value with the result.
Parameters
----------
player_data : dictionary or string
If this class is inherited from the ``Player`` class, player_data
will be a dictionary where each key is a string representing the
season and each value contains the HTML data as a string. If this
class is inherited from the ``BoxscorePlayer`` class, player_data
will be a string representing the player's game statistics in HTML
format. | [
"Parse",
"all",
"player",
"information",
"and",
"set",
"attributes",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/player.py#L127-L164 | train | 34,615 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore._parse_ranking | def _parse_ranking(self, field, boxscore):
"""
Parse each team's rank if applicable.
Retrieve the team's rank according to the rankings published each week.
The ranking for the week is only located in the scores section at
the top of the page and not in the actual boxscore information. The
rank is after the team name inside a parenthesis with a special
'pollrank' attribute. If this is not in the team's boxscore
information, the team is assumed to not have a rank and will return a
value of None.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery obejct containing all of the HTML data from the boxscore.
Returns
-------
int
An int representing the team's ranking or None if the team is not
ranked.
"""
ranking = None
index = BOXSCORE_ELEMENT_INDEX[field]
teams_boxscore = boxscore(BOXSCORE_SCHEME[field])
# Occasionally, the list of boxscores for the day won't be saved on the
# page. If that's the case, return the default ranking.
if str(teams_boxscore) == '':
return ranking
team = pq(teams_boxscore[index])
if 'pollrank' in str(team):
rank_str = re.findall(r'\(\d+\)', str(team))
if len(rank_str) == 1:
ranking = int(rank_str[0].replace('(', '').replace(')', ''))
return ranking | python | def _parse_ranking(self, field, boxscore):
"""
Parse each team's rank if applicable.
Retrieve the team's rank according to the rankings published each week.
The ranking for the week is only located in the scores section at
the top of the page and not in the actual boxscore information. The
rank is after the team name inside a parenthesis with a special
'pollrank' attribute. If this is not in the team's boxscore
information, the team is assumed to not have a rank and will return a
value of None.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery obejct containing all of the HTML data from the boxscore.
Returns
-------
int
An int representing the team's ranking or None if the team is not
ranked.
"""
ranking = None
index = BOXSCORE_ELEMENT_INDEX[field]
teams_boxscore = boxscore(BOXSCORE_SCHEME[field])
# Occasionally, the list of boxscores for the day won't be saved on the
# page. If that's the case, return the default ranking.
if str(teams_boxscore) == '':
return ranking
team = pq(teams_boxscore[index])
if 'pollrank' in str(team):
rank_str = re.findall(r'\(\d+\)', str(team))
if len(rank_str) == 1:
ranking = int(rank_str[0].replace('(', '').replace(')', ''))
return ranking | [
"def",
"_parse_ranking",
"(",
"self",
",",
"field",
",",
"boxscore",
")",
":",
"ranking",
"=",
"None",
"index",
"=",
"BOXSCORE_ELEMENT_INDEX",
"[",
"field",
"]",
"teams_boxscore",
"=",
"boxscore",
"(",
"BOXSCORE_SCHEME",
"[",
"field",
"]",
")",
"# Occasionally... | Parse each team's rank if applicable.
Retrieve the team's rank according to the rankings published each week.
The ranking for the week is only located in the scores section at
the top of the page and not in the actual boxscore information. The
rank is after the team name inside a parenthesis with a special
'pollrank' attribute. If this is not in the team's boxscore
information, the team is assumed to not have a rank and will return a
value of None.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery obejct containing all of the HTML data from the boxscore.
Returns
-------
int
An int representing the team's ranking or None if the team is not
ranked. | [
"Parse",
"each",
"team",
"s",
"rank",
"if",
"applicable",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L311-L348 | train | 34,616 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore._parse_record | def _parse_record(self, field, boxscore, index):
"""
Parse each team's record.
Find the record for both the home and away teams which are listed above
the basic boxscore stats tables. Depending on whether or not the
advanced stats table is included on the page (generally only for more
recent matchups), a blank header is added to the list which should be
removed. With all blank headers removed, the home and away team records
can be easily parsed by specifying which team is desired.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery object containing all of the HTML data from the boxscore.
index : int
An int of the index to pull the record from, as specified in the
BOXSCORE_ELEMENT_INDEX dictionary.
Returns
-------
string
A string of the team's record in the format 'Team Name (W-L)'.
"""
records = boxscore(BOXSCORE_SCHEME[field]).items()
records = [x.text() for x in records if x.text() != '']
return records[index] | python | def _parse_record(self, field, boxscore, index):
"""
Parse each team's record.
Find the record for both the home and away teams which are listed above
the basic boxscore stats tables. Depending on whether or not the
advanced stats table is included on the page (generally only for more
recent matchups), a blank header is added to the list which should be
removed. With all blank headers removed, the home and away team records
can be easily parsed by specifying which team is desired.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery object containing all of the HTML data from the boxscore.
index : int
An int of the index to pull the record from, as specified in the
BOXSCORE_ELEMENT_INDEX dictionary.
Returns
-------
string
A string of the team's record in the format 'Team Name (W-L)'.
"""
records = boxscore(BOXSCORE_SCHEME[field]).items()
records = [x.text() for x in records if x.text() != '']
return records[index] | [
"def",
"_parse_record",
"(",
"self",
",",
"field",
",",
"boxscore",
",",
"index",
")",
":",
"records",
"=",
"boxscore",
"(",
"BOXSCORE_SCHEME",
"[",
"field",
"]",
")",
".",
"items",
"(",
")",
"records",
"=",
"[",
"x",
".",
"text",
"(",
")",
"for",
... | Parse each team's record.
Find the record for both the home and away teams which are listed above
the basic boxscore stats tables. Depending on whether or not the
advanced stats table is included on the page (generally only for more
recent matchups), a blank header is added to the list which should be
removed. With all blank headers removed, the home and away team records
can be easily parsed by specifying which team is desired.
Parameters
----------
field : string
The name of the attribute to parse.
boxscore : PyQuery object
A PyQuery object containing all of the HTML data from the boxscore.
index : int
An int of the index to pull the record from, as specified in the
BOXSCORE_ELEMENT_INDEX dictionary.
Returns
-------
string
A string of the team's record in the format 'Team Name (W-L)'. | [
"Parse",
"each",
"team",
"s",
"record",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L350-L378 | train | 34,617 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore.winning_name | def winning_name(self):
"""
Returns a ``string`` of the winning team's name, such as 'Purdue
Boilermakers'.
"""
if self.winner == HOME:
if 'cbb/schools' not in str(self._home_name):
return str(self._home_name)
return self._home_name.text()
if 'cbb/schools' not in str(self._away_name):
return str(self._away_name)
return self._away_name.text() | python | def winning_name(self):
"""
Returns a ``string`` of the winning team's name, such as 'Purdue
Boilermakers'.
"""
if self.winner == HOME:
if 'cbb/schools' not in str(self._home_name):
return str(self._home_name)
return self._home_name.text()
if 'cbb/schools' not in str(self._away_name):
return str(self._away_name)
return self._away_name.text() | [
"def",
"winning_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"if",
"'cbb/schools'",
"not",
"in",
"str",
"(",
"self",
".",
"_home_name",
")",
":",
"return",
"str",
"(",
"self",
".",
"_home_name",
")",
"return",
"self",
... | Returns a ``string`` of the winning team's name, such as 'Purdue
Boilermakers'. | [
"Returns",
"a",
"string",
"of",
"the",
"winning",
"team",
"s",
"name",
"such",
"as",
"Purdue",
"Boilermakers",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L796-L807 | train | 34,618 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore.losing_name | def losing_name(self):
"""
Returns a ``string`` of the losing team's name, such as 'Indiana'
Hoosiers'.
"""
if self.winner == HOME:
if 'cbb/schools' not in str(self._away_name):
return str(self._away_name)
return self._away_name.text()
if 'cbb/schools' not in str(self._home_name):
return str(self._home_name)
return self._home_name.text() | python | def losing_name(self):
"""
Returns a ``string`` of the losing team's name, such as 'Indiana'
Hoosiers'.
"""
if self.winner == HOME:
if 'cbb/schools' not in str(self._away_name):
return str(self._away_name)
return self._away_name.text()
if 'cbb/schools' not in str(self._home_name):
return str(self._home_name)
return self._home_name.text() | [
"def",
"losing_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"if",
"'cbb/schools'",
"not",
"in",
"str",
"(",
"self",
".",
"_away_name",
")",
":",
"return",
"str",
"(",
"self",
".",
"_away_name",
")",
"return",
"self",
... | Returns a ``string`` of the losing team's name, such as 'Indiana'
Hoosiers'. | [
"Returns",
"a",
"string",
"of",
"the",
"losing",
"team",
"s",
"name",
"such",
"as",
"Indiana",
"Hoosiers",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L824-L835 | train | 34,619 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore.away_win_percentage | def away_win_percentage(self):
"""
Returns a ``float`` of the percentage of games the away team has won
after the conclusion of the game. Percentage ranges from 0-1.
"""
try:
result = float(self.away_wins) / \
float(self.away_wins + self.away_losses)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | python | def away_win_percentage(self):
"""
Returns a ``float`` of the percentage of games the away team has won
after the conclusion of the game. Percentage ranges from 0-1.
"""
try:
result = float(self.away_wins) / \
float(self.away_wins + self.away_losses)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"away_win_percentage",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"float",
"(",
"self",
".",
"away_wins",
")",
"/",
"float",
"(",
"self",
".",
"away_wins",
"+",
"self",
".",
"away_losses",
")",
"return",
"round",
"(",
"result",
",",
"3",
... | Returns a ``float`` of the percentage of games the away team has won
after the conclusion of the game. Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"percentage",
"of",
"games",
"the",
"away",
"team",
"has",
"won",
"after",
"the",
"conclusion",
"of",
"the",
"game",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L868-L878 | train | 34,620 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore.away_wins | def away_wins(self):
"""
Returns an ``int`` of the number of games the team has won after the
conclusion of the game.
"""
try:
wins, losses = re.findall(r'\d+', self._away_record)
return wins
except (ValueError, TypeError):
return 0 | python | def away_wins(self):
"""
Returns an ``int`` of the number of games the team has won after the
conclusion of the game.
"""
try:
wins, losses = re.findall(r'\d+', self._away_record)
return wins
except (ValueError, TypeError):
return 0 | [
"def",
"away_wins",
"(",
"self",
")",
":",
"try",
":",
"wins",
",",
"losses",
"=",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"self",
".",
"_away_record",
")",
"return",
"wins",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"0"
] | Returns an ``int`` of the number of games the team has won after the
conclusion of the game. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"games",
"the",
"team",
"has",
"won",
"after",
"the",
"conclusion",
"of",
"the",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L881-L890 | train | 34,621 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscore.home_win_percentage | def home_win_percentage(self):
"""
Returns a ``float`` of the percentage of games the home team has won
after the conclusion of the game. Percentage ranges from 0-1.
"""
try:
result = float(self.home_wins) / \
float(self.home_wins + self.home_losses)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | python | def home_win_percentage(self):
"""
Returns a ``float`` of the percentage of games the home team has won
after the conclusion of the game. Percentage ranges from 0-1.
"""
try:
result = float(self.home_wins) / \
float(self.home_wins + self.home_losses)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"home_win_percentage",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"float",
"(",
"self",
".",
"home_wins",
")",
"/",
"float",
"(",
"self",
".",
"home_wins",
"+",
"self",
".",
"home_losses",
")",
"return",
"round",
"(",
"result",
",",
"3",
... | Returns a ``float`` of the percentage of games the home team has won
after the conclusion of the game. Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"percentage",
"of",
"games",
"the",
"home",
"team",
"has",
"won",
"after",
"the",
"conclusion",
"of",
"the",
"game",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L1191-L1201 | train | 34,622 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscores._get_rank | def _get_rank(self, team):
"""
Find the team's rank when applicable.
If a team is ranked, it will showup in a separate <span> tag with the
actual rank embedded between parentheses. When a team is ranked, the
integer value representing their ranking should be returned. For teams
that are not ranked, None should be returned.
Parameters
----------
team : PyQuery object
A PyQuery object of a team's HTML tag in the boxscore.
Returns
-------
int
Returns an integer representing the team's ranking when applicable,
or None if the team is not ranked.
"""
rank = None
rank_field = team('span[class="pollrank"]')
if len(rank_field) > 0:
rank = re.findall(r'\(\d+\)', str(rank_field))[0]
rank = int(rank.replace('(', '').replace(')', ''))
return rank | python | def _get_rank(self, team):
"""
Find the team's rank when applicable.
If a team is ranked, it will showup in a separate <span> tag with the
actual rank embedded between parentheses. When a team is ranked, the
integer value representing their ranking should be returned. For teams
that are not ranked, None should be returned.
Parameters
----------
team : PyQuery object
A PyQuery object of a team's HTML tag in the boxscore.
Returns
-------
int
Returns an integer representing the team's ranking when applicable,
or None if the team is not ranked.
"""
rank = None
rank_field = team('span[class="pollrank"]')
if len(rank_field) > 0:
rank = re.findall(r'\(\d+\)', str(rank_field))[0]
rank = int(rank.replace('(', '').replace(')', ''))
return rank | [
"def",
"_get_rank",
"(",
"self",
",",
"team",
")",
":",
"rank",
"=",
"None",
"rank_field",
"=",
"team",
"(",
"'span[class=\"pollrank\"]'",
")",
"if",
"len",
"(",
"rank_field",
")",
">",
"0",
":",
"rank",
"=",
"re",
".",
"findall",
"(",
"r'\\(\\d+\\)'",
... | Find the team's rank when applicable.
If a team is ranked, it will showup in a separate <span> tag with the
actual rank embedded between parentheses. When a team is ranked, the
integer value representing their ranking should be returned. For teams
that are not ranked, None should be returned.
Parameters
----------
team : PyQuery object
A PyQuery object of a team's HTML tag in the boxscore.
Returns
-------
int
Returns an integer representing the team's ranking when applicable,
or None if the team is not ranked. | [
"Find",
"the",
"team",
"s",
"rank",
"when",
"applicable",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L1717-L1742 | train | 34,623 |
roclark/sportsreference | sportsreference/ncaab/boxscore.py | Boxscores._get_team_results | def _get_team_results(self, away_name, away_abbr, away_score, home_name,
home_abbr, home_score):
"""
Determine the winner and loser of the game.
If the game has been completed and sports-reference has been updated
with the score, determine the winner and loser and return their
respective names and abbreviations.
Parameters
----------
away_name : string
The name of the away team, such as 'Indiana'.
away_abbr : string
The abbreviation of the away team, such as 'indiana'.
away_score : int
The number of points the away team scored, or None if the game
hasn't completed yet.
home_score : string
The name of the home team, such as 'Purdue'.
home_abbr : string
The abbreviation of the home team, such as 'purdue'.
home_score : int
The number of points the home team scored, or None if the game
hasn't completed yet.
Returns
-------
tuple, tuple
Returns two tuples, each containing the name followed by the
abbreviation of the winning and losing team, respectively. If the
game doesn't have a score associated with it yet, both tuples will
be None.
"""
if not away_score or not home_score:
return None, None
if away_score > home_score:
return (away_name, away_abbr), (home_name, home_abbr)
else:
return (home_name, home_abbr), (away_name, away_abbr) | python | def _get_team_results(self, away_name, away_abbr, away_score, home_name,
home_abbr, home_score):
"""
Determine the winner and loser of the game.
If the game has been completed and sports-reference has been updated
with the score, determine the winner and loser and return their
respective names and abbreviations.
Parameters
----------
away_name : string
The name of the away team, such as 'Indiana'.
away_abbr : string
The abbreviation of the away team, such as 'indiana'.
away_score : int
The number of points the away team scored, or None if the game
hasn't completed yet.
home_score : string
The name of the home team, such as 'Purdue'.
home_abbr : string
The abbreviation of the home team, such as 'purdue'.
home_score : int
The number of points the home team scored, or None if the game
hasn't completed yet.
Returns
-------
tuple, tuple
Returns two tuples, each containing the name followed by the
abbreviation of the winning and losing team, respectively. If the
game doesn't have a score associated with it yet, both tuples will
be None.
"""
if not away_score or not home_score:
return None, None
if away_score > home_score:
return (away_name, away_abbr), (home_name, home_abbr)
else:
return (home_name, home_abbr), (away_name, away_abbr) | [
"def",
"_get_team_results",
"(",
"self",
",",
"away_name",
",",
"away_abbr",
",",
"away_score",
",",
"home_name",
",",
"home_abbr",
",",
"home_score",
")",
":",
"if",
"not",
"away_score",
"or",
"not",
"home_score",
":",
"return",
"None",
",",
"None",
"if",
... | Determine the winner and loser of the game.
If the game has been completed and sports-reference has been updated
with the score, determine the winner and loser and return their
respective names and abbreviations.
Parameters
----------
away_name : string
The name of the away team, such as 'Indiana'.
away_abbr : string
The abbreviation of the away team, such as 'indiana'.
away_score : int
The number of points the away team scored, or None if the game
hasn't completed yet.
home_score : string
The name of the home team, such as 'Purdue'.
home_abbr : string
The abbreviation of the home team, such as 'purdue'.
home_score : int
The number of points the home team scored, or None if the game
hasn't completed yet.
Returns
-------
tuple, tuple
Returns two tuples, each containing the name followed by the
abbreviation of the winning and losing team, respectively. If the
game doesn't have a score associated with it yet, both tuples will
be None. | [
"Determine",
"the",
"winner",
"and",
"loser",
"of",
"the",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L1793-L1832 | train | 34,624 |
roclark/sportsreference | sportsreference/ncaab/teams.py | Team.two_point_field_goal_percentage | def 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. Percentage ranges from
0-1.
"""
try:
result = float(self.two_point_field_goals) / \
float(self.two_point_field_goal_attempts)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | python | def 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. Percentage ranges from
0-1.
"""
try:
result = float(self.two_point_field_goals) / \
float(self.two_point_field_goal_attempts)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"two_point_field_goal_percentage",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"float",
"(",
"self",
".",
"two_point_field_goals",
")",
"/",
"float",
"(",
"self",
".",
"two_point_field_goal_attempts",
")",
"return",
"round",
"(",
"result",
",",
"3... | Returns a ``float`` of the number of two point field goals made divided
by the number of two point field goal attempts. Percentage ranges from
0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"number",
"of",
"two",
"point",
"field",
"goals",
"made",
"divided",
"by",
"the",
"number",
"of",
"two",
"point",
"field",
"goal",
"attempts",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/teams.py#L465-L476 | train | 34,625 |
roclark/sportsreference | sportsreference/ncaab/teams.py | Team.opp_two_point_field_goal_percentage | def opp_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 opponents. Percentage
ranges from 0-1.
"""
try:
result = float(self.opp_two_point_field_goals) / \
float(self.opp_two_point_field_goal_attempts)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | python | def opp_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 opponents. Percentage
ranges from 0-1.
"""
try:
result = float(self.opp_two_point_field_goals) / \
float(self.opp_two_point_field_goal_attempts)
return round(result, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"opp_two_point_field_goal_percentage",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"float",
"(",
"self",
".",
"opp_two_point_field_goals",
")",
"/",
"float",
"(",
"self",
".",
"opp_two_point_field_goal_attempts",
")",
"return",
"round",
"(",
"result",... | Returns a ``float`` of the number of two point field goals made divided
by the number of two point field goal attempts by opponents. Percentage
ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"number",
"of",
"two",
"point",
"field",
"goals",
"made",
"divided",
"by",
"the",
"number",
"of",
"two",
"point",
"field",
"goal",
"attempts",
"by",
"opponents",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
".... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/teams.py#L632-L643 | train | 34,626 |
roclark/sportsreference | sportsreference/ncaab/teams.py | Teams._add_stats_data | def _add_stats_data(self, teams_list, team_data_dict):
"""
Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
A generator of all row items in a given table.
team_data_dict : {str: {'data': str}} dictionary
A dictionary where every key is the team's abbreviation and every
value is another dictionary with a 'data' key which contains the
string version of the row data for the matched team.
Returns
-------
dictionary
An updated version of the team_data_dict with the passed table row
information included.
"""
for team_data in teams_list:
if 'class="over_header thead"' in str(team_data) or\
'class="thead"' in str(team_data):
continue
abbr = utils._parse_field(PARSING_SCHEME,
team_data,
'abbreviation')
try:
team_data_dict[abbr]['data'] += team_data
except KeyError:
team_data_dict[abbr] = {'data': team_data}
return team_data_dict | python | def _add_stats_data(self, teams_list, team_data_dict):
"""
Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
A generator of all row items in a given table.
team_data_dict : {str: {'data': str}} dictionary
A dictionary where every key is the team's abbreviation and every
value is another dictionary with a 'data' key which contains the
string version of the row data for the matched team.
Returns
-------
dictionary
An updated version of the team_data_dict with the passed table row
information included.
"""
for team_data in teams_list:
if 'class="over_header thead"' in str(team_data) or\
'class="thead"' in str(team_data):
continue
abbr = utils._parse_field(PARSING_SCHEME,
team_data,
'abbreviation')
try:
team_data_dict[abbr]['data'] += team_data
except KeyError:
team_data_dict[abbr] = {'data': team_data}
return team_data_dict | [
"def",
"_add_stats_data",
"(",
"self",
",",
"teams_list",
",",
"team_data_dict",
")",
":",
"for",
"team_data",
"in",
"teams_list",
":",
"if",
"'class=\"over_header thead\"'",
"in",
"str",
"(",
"team_data",
")",
"or",
"'class=\"thead\"'",
"in",
"str",
"(",
"team_... | Add a team's stats row to a dictionary.
Pass table contents and a stats dictionary of all teams to accumulate
all stats for each team in a single variable.
Parameters
----------
teams_list : generator
A generator of all row items in a given table.
team_data_dict : {str: {'data': str}} dictionary
A dictionary where every key is the team's abbreviation and every
value is another dictionary with a 'data' key which contains the
string version of the row data for the matched team.
Returns
-------
dictionary
An updated version of the team_data_dict with the passed table row
information included. | [
"Add",
"a",
"team",
"s",
"stats",
"row",
"to",
"a",
"dictionary",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/teams.py#L1061-L1094 | train | 34,627 |
roclark/sportsreference | sportsreference/ncaaf/conferences.py | Conference._get_team_abbreviation | def _get_team_abbreviation(self, team):
"""
Retrieve team's abbreviation.
The team's abbreviation is embedded within the 'school_name' tag and
requires special parsing as it is located in the middle of a URI. The
abbreviation is returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
conference page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE'.
"""
name_tag = team('th[data-stat="school_name"] a')
team_abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag))
team_abbreviation = re.sub(r'/.*', '', team_abbreviation)
return team_abbreviation | python | def _get_team_abbreviation(self, team):
"""
Retrieve team's abbreviation.
The team's abbreviation is embedded within the 'school_name' tag and
requires special parsing as it is located in the middle of a URI. The
abbreviation is returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
conference page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE'.
"""
name_tag = team('th[data-stat="school_name"] a')
team_abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag))
team_abbreviation = re.sub(r'/.*', '', team_abbreviation)
return team_abbreviation | [
"def",
"_get_team_abbreviation",
"(",
"self",
",",
"team",
")",
":",
"name_tag",
"=",
"team",
"(",
"'th[data-stat=\"school_name\"] a'",
")",
"team_abbreviation",
"=",
"re",
".",
"sub",
"(",
"r'.*/cfb/schools/'",
",",
"''",
",",
"str",
"(",
"name_tag",
")",
")"... | Retrieve team's abbreviation.
The team's abbreviation is embedded within the 'school_name' tag and
requires special parsing as it is located in the middle of a URI. The
abbreviation is returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
conference page.
Returns
-------
string
Returns a string of the team's abbreviation, such as 'PURDUE'. | [
"Retrieve",
"team",
"s",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/conferences.py#L49-L71 | train | 34,628 |
roclark/sportsreference | sportsreference/ncaaf/conferences.py | Conference._find_conference_teams | def _find_conference_teams(self, conference_abbreviation, year):
"""
Retrieve the teams in the conference for the requested season.
Find and retrieve all teams that participated in a conference for a
given season. The name and abbreviation for each team are parsed and
recorded to enable easy queries of conference schools..
Parameters
----------
conference_abbreviation : string
A string of the requested conference's abbreviation, such as
'big-12'.
year : string
A string of the requested year to pull conference information from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_conference_page(conference_abbreviation, year)
if not page:
url = CONFERENCE_URL % (conference_abbreviation, year)
output = ("Can't pull requested conference page. Ensure the "
"following URL exists: %s" % url)
raise ValueError(output)
conference = page('table#standings tbody tr').items()
for team in conference:
team_abbreviation = self._get_team_abbreviation(team)
if team_abbreviation == '':
continue
team_name = team('th[data-stat="school_name"]').text()
self._teams[team_abbreviation] = team_name | python | def _find_conference_teams(self, conference_abbreviation, year):
"""
Retrieve the teams in the conference for the requested season.
Find and retrieve all teams that participated in a conference for a
given season. The name and abbreviation for each team are parsed and
recorded to enable easy queries of conference schools..
Parameters
----------
conference_abbreviation : string
A string of the requested conference's abbreviation, such as
'big-12'.
year : string
A string of the requested year to pull conference information from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_conference_page(conference_abbreviation, year)
if not page:
url = CONFERENCE_URL % (conference_abbreviation, year)
output = ("Can't pull requested conference page. Ensure the "
"following URL exists: %s" % url)
raise ValueError(output)
conference = page('table#standings tbody tr').items()
for team in conference:
team_abbreviation = self._get_team_abbreviation(team)
if team_abbreviation == '':
continue
team_name = team('th[data-stat="school_name"]').text()
self._teams[team_abbreviation] = team_name | [
"def",
"_find_conference_teams",
"(",
"self",
",",
"conference_abbreviation",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'ncaaf'",
")",
"page",
"=",
"self",
".",
"_pull_conference_page",
"(",
"con... | Retrieve the teams in the conference for the requested season.
Find and retrieve all teams that participated in a conference for a
given season. The name and abbreviation for each team are parsed and
recorded to enable easy queries of conference schools..
Parameters
----------
conference_abbreviation : string
A string of the requested conference's abbreviation, such as
'big-12'.
year : string
A string of the requested year to pull conference information from. | [
"Retrieve",
"the",
"teams",
"in",
"the",
"conference",
"for",
"the",
"requested",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/conferences.py#L73-L103 | train | 34,629 |
roclark/sportsreference | sportsreference/ncaaf/conferences.py | Conferences._get_conference_id | def _get_conference_id(self, conference):
"""
Get the conference abbreviation, such as 'big-12'.
The conference abbreviation is embedded within the Conference Name
tag and requires special parsing to extract. The abbreviation is
returned as a string.
Parameters
----------
conference : PyQuery object
A PyQuery object representing a single row in the conference table
which can be used to find the conference abbreviation.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'.
"""
name_tag = conference('td[data-stat="conf_name"] a')
conference_id = re.sub(r'.*/cfb/conferences/', '', str(name_tag))
conference_id = re.sub(r'/.*', '', conference_id)
return conference_id | python | def _get_conference_id(self, conference):
"""
Get the conference abbreviation, such as 'big-12'.
The conference abbreviation is embedded within the Conference Name
tag and requires special parsing to extract. The abbreviation is
returned as a string.
Parameters
----------
conference : PyQuery object
A PyQuery object representing a single row in the conference table
which can be used to find the conference abbreviation.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'.
"""
name_tag = conference('td[data-stat="conf_name"] a')
conference_id = re.sub(r'.*/cfb/conferences/', '', str(name_tag))
conference_id = re.sub(r'/.*', '', conference_id)
return conference_id | [
"def",
"_get_conference_id",
"(",
"self",
",",
"conference",
")",
":",
"name_tag",
"=",
"conference",
"(",
"'td[data-stat=\"conf_name\"] a'",
")",
"conference_id",
"=",
"re",
".",
"sub",
"(",
"r'.*/cfb/conferences/'",
",",
"''",
",",
"str",
"(",
"name_tag",
")",... | Get the conference abbreviation, such as 'big-12'.
The conference abbreviation is embedded within the Conference Name
tag and requires special parsing to extract. The abbreviation is
returned as a string.
Parameters
----------
conference : PyQuery object
A PyQuery object representing a single row in the conference table
which can be used to find the conference abbreviation.
Returns
-------
string
Returns a string of the conference abbreviation, such as 'big-12'. | [
"Get",
"the",
"conference",
"abbreviation",
"such",
"as",
"big",
"-",
"12",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/conferences.py#L159-L181 | train | 34,630 |
roclark/sportsreference | sportsreference/ncaaf/conferences.py | Conferences._find_conferences | def _find_conferences(self, year):
"""
Retrieve the conferences and teams for the requested season.
Find and retrieve all conferences for a given season and parse all of
the teams that participated in the conference during that year.
Conference information includes abbreviation and full name for the
conference as well as the abbreviation and full name for each team in
the conference.
Parameters
----------
year : string
A string of the requested year to pull conferences from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_conference_page(year)
if not page:
output = ("Can't pull requested conference page. Ensure the "
"following URL exists: %s" % (CONFERENCES_URL % year))
raise ValueError(output)
conferences = page('table#conferences tbody tr').items()
for conference in conferences:
conference_abbreviation = self._get_conference_id(conference)
conference_name = conference('td[data-stat="conf_name"]').text()
teams_dict = Conference(conference_abbreviation, year).teams
conference_dict = {
'name': conference_name,
'teams': teams_dict
}
for team in teams_dict.keys():
self._team_conference[team] = conference_abbreviation
self._conferences[conference_abbreviation] = conference_dict | python | def _find_conferences(self, year):
"""
Retrieve the conferences and teams for the requested season.
Find and retrieve all conferences for a given season and parse all of
the teams that participated in the conference during that year.
Conference information includes abbreviation and full name for the
conference as well as the abbreviation and full name for each team in
the conference.
Parameters
----------
year : string
A string of the requested year to pull conferences from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_conference_page(year)
if not page:
output = ("Can't pull requested conference page. Ensure the "
"following URL exists: %s" % (CONFERENCES_URL % year))
raise ValueError(output)
conferences = page('table#conferences tbody tr').items()
for conference in conferences:
conference_abbreviation = self._get_conference_id(conference)
conference_name = conference('td[data-stat="conf_name"]').text()
teams_dict = Conference(conference_abbreviation, year).teams
conference_dict = {
'name': conference_name,
'teams': teams_dict
}
for team in teams_dict.keys():
self._team_conference[team] = conference_abbreviation
self._conferences[conference_abbreviation] = conference_dict | [
"def",
"_find_conferences",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'ncaaf'",
")",
"page",
"=",
"self",
".",
"_pull_conference_page",
"(",
"year",
")",
"if",
"not",
"page",
"... | Retrieve the conferences and teams for the requested season.
Find and retrieve all conferences for a given season and parse all of
the teams that participated in the conference during that year.
Conference information includes abbreviation and full name for the
conference as well as the abbreviation and full name for each team in
the conference.
Parameters
----------
year : string
A string of the requested year to pull conferences from. | [
"Retrieve",
"the",
"conferences",
"and",
"teams",
"for",
"the",
"requested",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/conferences.py#L183-L216 | train | 34,631 |
roclark/sportsreference | sportsreference/nfl/schedule.py | Game.week | def week(self):
"""
Returns an ``int`` of the week number in the season, such as 1 for the
first week of the regular season.
"""
if self._week.lower() == 'wild card':
return WILD_CARD
if self._week.lower() == 'division':
return DIVISION
if self._week.lower() == 'conf. champ.':
return CONF_CHAMPIONSHIP
if self._week.lower() == 'superbowl':
return SUPER_BOWL
return self._week | python | def week(self):
"""
Returns an ``int`` of the week number in the season, such as 1 for the
first week of the regular season.
"""
if self._week.lower() == 'wild card':
return WILD_CARD
if self._week.lower() == 'division':
return DIVISION
if self._week.lower() == 'conf. champ.':
return CONF_CHAMPIONSHIP
if self._week.lower() == 'superbowl':
return SUPER_BOWL
return self._week | [
"def",
"week",
"(",
"self",
")",
":",
"if",
"self",
".",
"_week",
".",
"lower",
"(",
")",
"==",
"'wild card'",
":",
"return",
"WILD_CARD",
"if",
"self",
".",
"_week",
".",
"lower",
"(",
")",
"==",
"'division'",
":",
"return",
"DIVISION",
"if",
"self"... | Returns an ``int`` of the week number in the season, such as 1 for the
first week of the regular season. | [
"Returns",
"an",
"int",
"of",
"the",
"week",
"number",
"in",
"the",
"season",
"such",
"as",
"1",
"for",
"the",
"first",
"week",
"of",
"the",
"regular",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/schedule.py#L216-L229 | train | 34,632 |
roclark/sportsreference | sportsreference/nfl/schedule.py | Game.datetime | def datetime(self):
"""
Returns a datetime object representing the date the game was played.
"""
date_string = '%s %s %s' % (self._day,
self._date,
self._year)
return datetime.strptime(date_string, '%a %B %d %Y') | python | def datetime(self):
"""
Returns a datetime object representing the date the game was played.
"""
date_string = '%s %s %s' % (self._day,
self._date,
self._year)
return datetime.strptime(date_string, '%a %B %d %Y') | [
"def",
"datetime",
"(",
"self",
")",
":",
"date_string",
"=",
"'%s %s %s'",
"%",
"(",
"self",
".",
"_day",
",",
"self",
".",
"_date",
",",
"self",
".",
"_year",
")",
"return",
"datetime",
".",
"strptime",
"(",
"date_string",
",",
"'%a %B %d %Y'",
")"
] | Returns a datetime object representing the date the game was played. | [
"Returns",
"a",
"datetime",
"object",
"representing",
"the",
"date",
"the",
"game",
"was",
"played",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/schedule.py#L272-L279 | train | 34,633 |
roclark/sportsreference | sportsreference/nfl/schedule.py | Schedule._add_games_to_schedule | def _add_games_to_schedule(self, schedule, game_type, year):
"""
Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
A PyQuery object pertaining to a team's schedule table.
game_type : string
A string constant denoting whether the game is being played as part
of the regular season or the playoffs.
year : string
The requested year to pull stats from.
"""
for item in schedule:
game = Game(item, game_type, year)
self._games.append(game) | python | def _add_games_to_schedule(self, schedule, game_type, year):
"""
Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
A PyQuery object pertaining to a team's schedule table.
game_type : string
A string constant denoting whether the game is being played as part
of the regular season or the playoffs.
year : string
The requested year to pull stats from.
"""
for item in schedule:
game = Game(item, game_type, year)
self._games.append(game) | [
"def",
"_add_games_to_schedule",
"(",
"self",
",",
"schedule",
",",
"game_type",
",",
"year",
")",
":",
"for",
"item",
"in",
"schedule",
":",
"game",
"=",
"Game",
"(",
"item",
",",
"game_type",
",",
"year",
")",
"self",
".",
"_games",
".",
"append",
"(... | Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
A PyQuery object pertaining to a team's schedule table.
game_type : string
A string constant denoting whether the game is being played as part
of the regular season or the playoffs.
year : string
The requested year to pull stats from. | [
"Add",
"games",
"instances",
"to",
"schedule",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/schedule.py#L623-L642 | train | 34,634 |
roclark/sportsreference | sportsreference/nba/boxscore.py | BoxscorePlayer.minutes_played | def minutes_played(self):
"""
Returns a ``float`` of the number of game minutes the player was on the
court for.
"""
if self._minutes_played[self._index]:
minutes, seconds = self._minutes_played[self._index].split(':')
minutes = float(minutes) + float(seconds) / 60
return float(minutes)
return None | python | def minutes_played(self):
"""
Returns a ``float`` of the number of game minutes the player was on the
court for.
"""
if self._minutes_played[self._index]:
minutes, seconds = self._minutes_played[self._index].split(':')
minutes = float(minutes) + float(seconds) / 60
return float(minutes)
return None | [
"def",
"minutes_played",
"(",
"self",
")",
":",
"if",
"self",
".",
"_minutes_played",
"[",
"self",
".",
"_index",
"]",
":",
"minutes",
",",
"seconds",
"=",
"self",
".",
"_minutes_played",
"[",
"self",
".",
"_index",
"]",
".",
"split",
"(",
"':'",
")",
... | Returns a ``float`` of the number of game minutes the player was on the
court for. | [
"Returns",
"a",
"float",
"of",
"the",
"number",
"of",
"game",
"minutes",
"the",
"player",
"was",
"on",
"the",
"court",
"for",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L110-L119 | train | 34,635 |
roclark/sportsreference | sportsreference/nba/boxscore.py | BoxscorePlayer.two_pointers | def two_pointers(self):
"""
Returns an ``int`` of the total number of two point field goals the
player made.
"""
if self.field_goals and self.three_pointers:
return int(self.field_goals - self.three_pointers)
# Occurs when the player didn't make any three pointers, so the number
# of two pointers the player made is equal to the total number of field
# goals the player made.
if self.field_goals:
return int(self.field_goals)
# If the player didn't make any shots, they didn't make any two point
# field goals.
return None | python | def two_pointers(self):
"""
Returns an ``int`` of the total number of two point field goals the
player made.
"""
if self.field_goals and self.three_pointers:
return int(self.field_goals - self.three_pointers)
# Occurs when the player didn't make any three pointers, so the number
# of two pointers the player made is equal to the total number of field
# goals the player made.
if self.field_goals:
return int(self.field_goals)
# If the player didn't make any shots, they didn't make any two point
# field goals.
return None | [
"def",
"two_pointers",
"(",
"self",
")",
":",
"if",
"self",
".",
"field_goals",
"and",
"self",
".",
"three_pointers",
":",
"return",
"int",
"(",
"self",
".",
"field_goals",
"-",
"self",
".",
"three_pointers",
")",
"# Occurs when the player didn't make any three po... | Returns an ``int`` of the total number of two point field goals the
player made. | [
"Returns",
"an",
"int",
"of",
"the",
"total",
"number",
"of",
"two",
"point",
"field",
"goals",
"the",
"player",
"made",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L122-L136 | train | 34,636 |
roclark/sportsreference | sportsreference/nba/boxscore.py | BoxscorePlayer.two_point_attempts | def two_point_attempts(self):
"""
Returns an ``int`` of the total number of two point field goals the
player attempted during the season.
"""
if self.field_goal_attempts and self.three_point_attempts:
return int(self.field_goal_attempts - self.three_point_attempts)
# Occurs when the player didn't take any three pointers, so the number
# of two pointers the player took is equal to the total number of field
# goals the player took.
if self.field_goal_attempts:
return int(self.field_goal_attempts)
# If the player didn't take any shots, they didn't take any two point
# field goals.
return None | python | def two_point_attempts(self):
"""
Returns an ``int`` of the total number of two point field goals the
player attempted during the season.
"""
if self.field_goal_attempts and self.three_point_attempts:
return int(self.field_goal_attempts - self.three_point_attempts)
# Occurs when the player didn't take any three pointers, so the number
# of two pointers the player took is equal to the total number of field
# goals the player took.
if self.field_goal_attempts:
return int(self.field_goal_attempts)
# If the player didn't take any shots, they didn't take any two point
# field goals.
return None | [
"def",
"two_point_attempts",
"(",
"self",
")",
":",
"if",
"self",
".",
"field_goal_attempts",
"and",
"self",
".",
"three_point_attempts",
":",
"return",
"int",
"(",
"self",
".",
"field_goal_attempts",
"-",
"self",
".",
"three_point_attempts",
")",
"# Occurs when t... | Returns an ``int`` of the total number of two point field goals the
player attempted during the season. | [
"Returns",
"an",
"int",
"of",
"the",
"total",
"number",
"of",
"two",
"point",
"field",
"goals",
"the",
"player",
"attempted",
"during",
"the",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L139-L153 | train | 34,637 |
roclark/sportsreference | sportsreference/nba/boxscore.py | BoxscorePlayer.two_point_percentage | def two_point_percentage(self):
"""
Returns a ``float`` of the player's two point field goal percentage
during the season. Percentage ranges from 0-1.
"""
if self.two_pointers and self.two_point_attempts:
perc = float(self.two_pointers) / float(self.two_point_attempts)
return round(perc, 3)
# Occurs when the player didn't make and two pointers.
if self.two_point_attempts:
return 0.0
return None | python | def two_point_percentage(self):
"""
Returns a ``float`` of the player's two point field goal percentage
during the season. Percentage ranges from 0-1.
"""
if self.two_pointers and self.two_point_attempts:
perc = float(self.two_pointers) / float(self.two_point_attempts)
return round(perc, 3)
# Occurs when the player didn't make and two pointers.
if self.two_point_attempts:
return 0.0
return None | [
"def",
"two_point_percentage",
"(",
"self",
")",
":",
"if",
"self",
".",
"two_pointers",
"and",
"self",
".",
"two_point_attempts",
":",
"perc",
"=",
"float",
"(",
"self",
".",
"two_pointers",
")",
"/",
"float",
"(",
"self",
".",
"two_point_attempts",
")",
... | Returns a ``float`` of the player's two point field goal percentage
during the season. Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"player",
"s",
"two",
"point",
"field",
"goal",
"percentage",
"during",
"the",
"season",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L156-L167 | train | 34,638 |
roclark/sportsreference | sportsreference/nba/boxscore.py | Boxscore.away_two_point_field_goal_percentage | def away_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 away team.
Percentage ranges from 0-1.
"""
result = float(self.away_two_point_field_goals) / \
float(self.away_two_point_field_goal_attempts)
return round(float(result), 3) | python | def away_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 away team.
Percentage ranges from 0-1.
"""
result = float(self.away_two_point_field_goals) / \
float(self.away_two_point_field_goal_attempts)
return round(float(result), 3) | [
"def",
"away_two_point_field_goal_percentage",
"(",
"self",
")",
":",
"result",
"=",
"float",
"(",
"self",
".",
"away_two_point_field_goals",
")",
"/",
"float",
"(",
"self",
".",
"away_two_point_field_goal_attempts",
")",
"return",
"round",
"(",
"float",
"(",
"res... | Returns a ``float`` of the number of two point field goals made divided
by the number of two point field goal attempts by the away team.
Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"number",
"of",
"two",
"point",
"field",
"goals",
"made",
"divided",
"by",
"the",
"number",
"of",
"two",
"point",
"field",
"goal",
"attempts",
"by",
"the",
"away",
"team",
".",
"Percentage",
"ranges",
"from",
"0",
"-... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L909-L917 | train | 34,639 |
roclark/sportsreference | sportsreference/nba/boxscore.py | Boxscore.home_wins | 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 = re.findall(r'\d+', self._home_record)
return wins
except ValueError:
return 0 | python | 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 = re.findall(r'\d+', self._home_record)
return wins
except ValueError:
return 0 | [
"def",
"home_wins",
"(",
"self",
")",
":",
"try",
":",
"wins",
",",
"losses",
"=",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"self",
".",
"_home_record",
")",
"return",
"wins",
"except",
"ValueError",
":",
"return",
"0"
] | Returns an ``int`` of the number of games the home team won after the
conclusion of the game. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"games",
"the",
"home",
"team",
"won",
"after",
"the",
"conclusion",
"of",
"the",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L1115-L1124 | train | 34,640 |
roclark/sportsreference | sportsreference/nba/boxscore.py | Boxscore.home_two_point_field_goal_percentage | 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.
"""
result = float(self.home_two_point_field_goals) / \
float(self.home_two_point_field_goal_attempts)
return round(float(result), 3) | python | 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.
"""
result = float(self.home_two_point_field_goals) / \
float(self.home_two_point_field_goal_attempts)
return round(float(result), 3) | [
"def",
"home_two_point_field_goal_percentage",
"(",
"self",
")",
":",
"result",
"=",
"float",
"(",
"self",
".",
"home_two_point_field_goals",
")",
"/",
"float",
"(",
"self",
".",
"home_two_point_field_goal_attempts",
")",
"return",
"round",
"(",
"float",
"(",
"res... | 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. | [
"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",
"-... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L1214-L1222 | train | 34,641 |
roclark/sportsreference | sportsreference/nfl/teams.py | Team.dataframe | 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,
'defensive_simple_rating_system':
self.defensive_simple_rating_system,
'first_downs': self.first_downs,
'first_downs_from_penalties': self.first_downs_from_penalties,
'fumbles': self.fumbles,
'games_played': self.games_played,
'interceptions': self.interceptions,
'losses': self.losses,
'margin_of_victory': self.margin_of_victory,
'name': self.name,
'offensive_simple_rating_system':
self.offensive_simple_rating_system,
'pass_attempts': self.pass_attempts,
'pass_completions': self.pass_completions,
'pass_first_downs': self.pass_first_downs,
'pass_net_yards_per_attempt': self.pass_net_yards_per_attempt,
'pass_touchdowns': self.pass_touchdowns,
'pass_yards': self.pass_yards,
'penalties': self.penalties,
'percent_drives_with_points': self.percent_drives_with_points,
'percent_drives_with_turnovers':
self.percent_drives_with_turnovers,
'plays': self.plays,
'points_against': self.points_against,
'points_contributed_by_offense':
self.points_contributed_by_offense,
'points_difference': self.points_difference,
'points_for': self.points_for,
'rank': self.rank,
'rush_attempts': self.rush_attempts,
'rush_first_downs': self.rush_first_downs,
'rush_touchdowns': self.rush_touchdowns,
'rush_yards': self.rush_yards,
'rush_yards_per_attempt': self.rush_yards_per_attempt,
'simple_rating_system': self.simple_rating_system,
'strength_of_schedule': self.strength_of_schedule,
'turnovers': self.turnovers,
'win_percentage': self.win_percentage,
'wins': self.wins,
'yards': self.yards,
'yards_from_penalties': self.yards_from_penalties,
'yards_per_play': self.yards_per_play
}
return pd.DataFrame([fields_to_include], index=[self._abbreviation]) | python | 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,
'defensive_simple_rating_system':
self.defensive_simple_rating_system,
'first_downs': self.first_downs,
'first_downs_from_penalties': self.first_downs_from_penalties,
'fumbles': self.fumbles,
'games_played': self.games_played,
'interceptions': self.interceptions,
'losses': self.losses,
'margin_of_victory': self.margin_of_victory,
'name': self.name,
'offensive_simple_rating_system':
self.offensive_simple_rating_system,
'pass_attempts': self.pass_attempts,
'pass_completions': self.pass_completions,
'pass_first_downs': self.pass_first_downs,
'pass_net_yards_per_attempt': self.pass_net_yards_per_attempt,
'pass_touchdowns': self.pass_touchdowns,
'pass_yards': self.pass_yards,
'penalties': self.penalties,
'percent_drives_with_points': self.percent_drives_with_points,
'percent_drives_with_turnovers':
self.percent_drives_with_turnovers,
'plays': self.plays,
'points_against': self.points_against,
'points_contributed_by_offense':
self.points_contributed_by_offense,
'points_difference': self.points_difference,
'points_for': self.points_for,
'rank': self.rank,
'rush_attempts': self.rush_attempts,
'rush_first_downs': self.rush_first_downs,
'rush_touchdowns': self.rush_touchdowns,
'rush_yards': self.rush_yards,
'rush_yards_per_attempt': self.rush_yards_per_attempt,
'simple_rating_system': self.simple_rating_system,
'strength_of_schedule': self.strength_of_schedule,
'turnovers': self.turnovers,
'win_percentage': self.win_percentage,
'wins': self.wins,
'yards': self.yards,
'yards_from_penalties': self.yards_from_penalties,
'yards_per_play': self.yards_per_play
}
return pd.DataFrame([fields_to_include], index=[self._abbreviation]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'abbreviation'",
":",
"self",
".",
"abbreviation",
",",
"'defensive_simple_rating_system'",
":",
"self",
".",
"defensive_simple_rating_system",
",",
"'first_downs'",
":",
"self",
".",
"first_... | 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'. | [
"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",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/teams.py#L106-L157 | train | 34,642 |
roclark/sportsreference | sportsreference/mlb/roster.py | Player._parse_team_name | 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
----------
team : string
A string representing the team_name tag in a row in the player's
contract table.
Returns
-------
string
A string of the team's name, such as 'Houston Astros'.
"""
team = team.replace(' ', ' ')
team = team.replace('\xa0', ' ')
team_html = pq(team)
return team_html.text() | python | 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
----------
team : string
A string representing the team_name tag in a row in the player's
contract table.
Returns
-------
string
A string of the team's name, such as 'Houston Astros'.
"""
team = team.replace(' ', ' ')
team = team.replace('\xa0', ' ')
team_html = pq(team)
return team_html.text() | [
"def",
"_parse_team_name",
"(",
"self",
",",
"team",
")",
":",
"team",
"=",
"team",
".",
"replace",
"(",
"' '",
",",
"' '",
")",
"team",
"=",
"team",
".",
"replace",
"(",
"'\\xa0'",
",",
"' '",
")",
"team_html",
"=",
"pq",
"(",
"team",
")",
"r... | 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
----------
team : string
A string representing the team_name tag in a row in the player's
contract table.
Returns
-------
string
A string of the team's name, such as 'Houston Astros'. | [
"Parse",
"the",
"team",
"name",
"in",
"the",
"contract",
"table",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/roster.py#L403-L425 | train | 34,643 |
roclark/sportsreference | sportsreference/mlb/roster.py | Player._parse_value | 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 sports-reference uses
to differentiate stats. This function returns a single value for the
given attribute.
Parameters
----------
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in the
PLAYER_SCHEME dictionary.
Returns
-------
list
A list of all values that match the requested field. If no value
could be found, returns None.
"""
scheme = PLAYER_SCHEME[field]
items = [i.text() for i in html_data(scheme).items()]
# Stats can be added and removed on a yearly basis. If no stats are
# found, return None and have that be the value.
if len(items) == 0:
return None
return items | python | 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 sports-reference uses
to differentiate stats. This function returns a single value for the
given attribute.
Parameters
----------
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in the
PLAYER_SCHEME dictionary.
Returns
-------
list
A list of all values that match the requested field. If no value
could be found, returns None.
"""
scheme = PLAYER_SCHEME[field]
items = [i.text() for i in html_data(scheme).items()]
# Stats can be added and removed on a yearly basis. If no stats are
# found, return None and have that be the value.
if len(items) == 0:
return None
return items | [
"def",
"_parse_value",
"(",
"self",
",",
"html_data",
",",
"field",
")",
":",
"scheme",
"=",
"PLAYER_SCHEME",
"[",
"field",
"]",
"items",
"=",
"[",
"i",
".",
"text",
"(",
")",
"for",
"i",
"in",
"html_data",
"(",
"scheme",
")",
".",
"items",
"(",
")... | 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 sports-reference uses
to differentiate stats. This function returns a single value for the
given attribute.
Parameters
----------
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in the
PLAYER_SCHEME dictionary.
Returns
-------
list
A list of all values that match the requested field. If no value
could be found, returns None. | [
"Parse",
"the",
"HTML",
"table",
"to",
"find",
"the",
"requested",
"field",
"s",
"value",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/roster.py#L459-L491 | train | 34,644 |
roclark/sportsreference | sportsreference/mlb/roster.py | Roster._get_id | 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 player information from the
roster table.
Returns
-------
string
Returns a string of the player ID.
"""
name_tag = player('td[data-stat="player"] a')
name = re.sub(r'.*/players/./', '', str(name_tag))
return re.sub(r'\.shtml.*', '', name) | python | 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 player information from the
roster table.
Returns
-------
string
Returns a string of the player ID.
"""
name_tag = player('td[data-stat="player"] a')
name = re.sub(r'.*/players/./', '', str(name_tag))
return re.sub(r'\.shtml.*', '', name) | [
"def",
"_get_id",
"(",
"self",
",",
"player",
")",
":",
"name_tag",
"=",
"player",
"(",
"'td[data-stat=\"player\"] a'",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'.*/players/./'",
",",
"''",
",",
"str",
"(",
"name_tag",
")",
")",
"return",
"re",
".",
... | 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 player information from the
roster table.
Returns
-------
string
Returns a string of the player ID. | [
"Parse",
"the",
"player",
"ID",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/roster.py#L1489-L1509 | train | 34,645 |
roclark/sportsreference | sportsreference/nhl/boxscore.py | BoxscorePlayer.dataframe | 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,
'corsi_for_percentage': self.corsi_for_percentage,
'decision': self.decision,
'defensive_zone_starts': self.defensive_zone_starts,
'defensive_zone_start_percentage':
self.defensive_zone_start_percentage,
'even_strength_assists': self.even_strength_assists,
'even_strength_goals': self.even_strength_goals,
'game_winning_goals': self.game_winning_goals,
'goals': self.goals,
'goals_against': self.goals_against,
'hits_at_even_strength': self.hits_at_even_strength,
'invidual_corsi_for_events': self.individual_corsi_for_events,
'name': self.name,
'offensive_zone_start_percentage':
self.offensive_zone_start_percentage,
'offensive_zone_starts': self.offensive_zone_starts,
'on_ice_shot_attempts_against': self.on_ice_shot_attempts_against,
'on_ice_shot_attempts_for': self.on_ice_shot_attempts_for,
'penalties_in_minutes': self.penalties_in_minutes,
'player_id': self.player_id,
'plus_minus': self.plus_minus,
'points': self.points,
'power_play_assists': self.power_play_assists,
'power_play_goals': self.power_play_goals,
'relative_corsi_for_percentage':
self.relative_corsi_for_percentage,
'save_percentage': self.save_percentage,
'saves': self.saves,
'shifts': self.shifts,
'shooting_percentage': self.shooting_percentage,
'short_handed_assists': self.short_handed_assists,
'short_handed_goals': self.short_handed_goals,
'shots_against': self.shots_against,
'shots_on_goal': self.shots_on_goal,
'shutouts': self.shutouts,
'time_on_ice': self.time_on_ice
}
return pd.DataFrame([fields_to_include], index=[self._player_id]) | python | 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,
'corsi_for_percentage': self.corsi_for_percentage,
'decision': self.decision,
'defensive_zone_starts': self.defensive_zone_starts,
'defensive_zone_start_percentage':
self.defensive_zone_start_percentage,
'even_strength_assists': self.even_strength_assists,
'even_strength_goals': self.even_strength_goals,
'game_winning_goals': self.game_winning_goals,
'goals': self.goals,
'goals_against': self.goals_against,
'hits_at_even_strength': self.hits_at_even_strength,
'invidual_corsi_for_events': self.individual_corsi_for_events,
'name': self.name,
'offensive_zone_start_percentage':
self.offensive_zone_start_percentage,
'offensive_zone_starts': self.offensive_zone_starts,
'on_ice_shot_attempts_against': self.on_ice_shot_attempts_against,
'on_ice_shot_attempts_for': self.on_ice_shot_attempts_for,
'penalties_in_minutes': self.penalties_in_minutes,
'player_id': self.player_id,
'plus_minus': self.plus_minus,
'points': self.points,
'power_play_assists': self.power_play_assists,
'power_play_goals': self.power_play_goals,
'relative_corsi_for_percentage':
self.relative_corsi_for_percentage,
'save_percentage': self.save_percentage,
'saves': self.saves,
'shifts': self.shifts,
'shooting_percentage': self.shooting_percentage,
'short_handed_assists': self.short_handed_assists,
'short_handed_goals': self.short_handed_goals,
'shots_against': self.shots_against,
'shots_on_goal': self.shots_on_goal,
'shutouts': self.shutouts,
'time_on_ice': self.time_on_ice
}
return pd.DataFrame([fields_to_include], index=[self._player_id]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'assists'",
":",
"self",
".",
"assists",
",",
"'blocks_at_even_strength'",
":",
"self",
".",
"blocks_at_even_strength",
",",
"'corsi_for_percentage'",
":",
"self",
".",
"corsi_for_percentage"... | Returns a ``pandas DataFrame`` containing all other relevant
properties and values for the specified game. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"relevant",
"properties",
"and",
"values",
"for",
"the",
"specified",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L96-L141 | train | 34,646 |
roclark/sportsreference | sportsreference/nhl/boxscore.py | Boxscore._find_player_id | 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 single row in a boxscore table for
a single player.
Returns
-------
str
Returns a ``string`` of the player's ID, such as 'zettehe01' for
Henrik Zetterberg.
"""
player_id = row('th').attr('data-append-csv')
if not player_id:
player_id = row('td').attr('data-append-csv')
return player_id | python | 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 single row in a boxscore table for
a single player.
Returns
-------
str
Returns a ``string`` of the player's ID, such as 'zettehe01' for
Henrik Zetterberg.
"""
player_id = row('th').attr('data-append-csv')
if not player_id:
player_id = row('td').attr('data-append-csv')
return player_id | [
"def",
"_find_player_id",
"(",
"self",
",",
"row",
")",
":",
"player_id",
"=",
"row",
"(",
"'th'",
")",
".",
"attr",
"(",
"'data-append-csv'",
")",
"if",
"not",
"player_id",
":",
"player_id",
"=",
"row",
"(",
"'td'",
")",
".",
"attr",
"(",
"'data-appen... | 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 single row in a boxscore table for
a single player.
Returns
-------
str
Returns a ``string`` of the player's ID, such as 'zettehe01' for
Henrik Zetterberg. | [
"Find",
"the",
"player",
"s",
"ID",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L413-L435 | train | 34,647 |
roclark/sportsreference | sportsreference/nhl/boxscore.py | Boxscore.dataframe | 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:
return None
fields_to_include = {
'arena': self.arena,
'attendance': self.attendance,
'away_assists': self.away_assists,
'away_even_strength_assists': self.away_even_strength_assists,
'away_even_strength_goals': self.away_even_strength_goals,
'away_game_winning_goals': self.away_game_winning_goals,
'away_goals': self.away_goals,
'away_penalties_in_minutes': self.away_penalties_in_minutes,
'away_points': self.away_points,
'away_power_play_assists': self.away_power_play_assists,
'away_power_play_goals': self.away_power_play_goals,
'away_save_percentage': self.away_save_percentage,
'away_saves': self.away_saves,
'away_shooting_percentage': self.away_shooting_percentage,
'away_short_handed_assists': self.away_short_handed_assists,
'away_short_handed_goals': self.away_short_handed_goals,
'away_shots_on_goal': self.away_shots_on_goal,
'away_shutout': self.away_shutout,
'date': self.date,
'duration': self.duration,
'home_assists': self.home_assists,
'home_even_strength_assists': self.home_even_strength_assists,
'home_even_strength_goals': self.home_even_strength_goals,
'home_game_winning_goals': self.home_game_winning_goals,
'home_goals': self.home_goals,
'home_penalties_in_minutes': self.home_penalties_in_minutes,
'home_points': self.home_points,
'home_power_play_assists': self.home_power_play_assists,
'home_power_play_goals': self.home_power_play_goals,
'home_save_percentage': self.home_save_percentage,
'home_saves': self.home_saves,
'home_shooting_percentage': self.home_shooting_percentage,
'home_short_handed_assists': self.home_short_handed_assists,
'home_short_handed_goals': self.home_short_handed_goals,
'home_shots_on_goal': self.home_shots_on_goal,
'home_shutout': self.home_shutout,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | python | 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:
return None
fields_to_include = {
'arena': self.arena,
'attendance': self.attendance,
'away_assists': self.away_assists,
'away_even_strength_assists': self.away_even_strength_assists,
'away_even_strength_goals': self.away_even_strength_goals,
'away_game_winning_goals': self.away_game_winning_goals,
'away_goals': self.away_goals,
'away_penalties_in_minutes': self.away_penalties_in_minutes,
'away_points': self.away_points,
'away_power_play_assists': self.away_power_play_assists,
'away_power_play_goals': self.away_power_play_goals,
'away_save_percentage': self.away_save_percentage,
'away_saves': self.away_saves,
'away_shooting_percentage': self.away_shooting_percentage,
'away_short_handed_assists': self.away_short_handed_assists,
'away_short_handed_goals': self.away_short_handed_goals,
'away_shots_on_goal': self.away_shots_on_goal,
'away_shutout': self.away_shutout,
'date': self.date,
'duration': self.duration,
'home_assists': self.home_assists,
'home_even_strength_assists': self.home_even_strength_assists,
'home_even_strength_goals': self.home_even_strength_goals,
'home_game_winning_goals': self.home_game_winning_goals,
'home_goals': self.home_goals,
'home_penalties_in_minutes': self.home_penalties_in_minutes,
'home_points': self.home_points,
'home_power_play_assists': self.home_power_play_assists,
'home_power_play_goals': self.home_power_play_goals,
'home_save_percentage': self.home_save_percentage,
'home_saves': self.home_saves,
'home_shooting_percentage': self.home_shooting_percentage,
'home_short_handed_assists': self.home_short_handed_assists,
'home_short_handed_goals': self.home_short_handed_goals,
'home_shots_on_goal': self.home_shots_on_goal,
'home_shutout': self.home_shutout,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_away_goals",
"is",
"None",
"and",
"self",
".",
"_home_goals",
"is",
"None",
":",
"return",
"None",
"fields_to_include",
"=",
"{",
"'arena'",
":",
"self",
".",
"arena",
",",
"'attendance'",
"... | 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'. | [
"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"... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L667-L719 | train | 34,648 |
roclark/sportsreference | sportsreference/nhl/boxscore.py | Boxscore.away_save_percentage | 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) / float(self.home_shots_on_goal)
return round(save_pct, 3)
except ZeroDivisionError:
return 0.0 | python | 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) / float(self.home_shots_on_goal)
return round(save_pct, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"away_save_percentage",
"(",
"self",
")",
":",
"try",
":",
"save_pct",
"=",
"float",
"(",
"self",
".",
"away_saves",
")",
"/",
"float",
"(",
"self",
".",
"home_shots_on_goal",
")",
"return",
"round",
"(",
"save_pct",
",",
"3",
")",
"except",
"Zero... | Returns a ``float`` of the percentage of shots the away team saved.
Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"percentage",
"of",
"shots",
"the",
"away",
"team",
"saved",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L941-L950 | train | 34,649 |
roclark/sportsreference | sportsreference/nhl/boxscore.py | Boxscore.home_save_percentage | 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) / float(self.away_shots_on_goal)
return round(save_pct, 3)
except ZeroDivisionError:
return 0.0 | python | 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) / float(self.away_shots_on_goal)
return round(save_pct, 3)
except ZeroDivisionError:
return 0.0 | [
"def",
"home_save_percentage",
"(",
"self",
")",
":",
"try",
":",
"save_pct",
"=",
"float",
"(",
"self",
".",
"home_saves",
")",
"/",
"float",
"(",
"self",
".",
"away_shots_on_goal",
")",
"return",
"round",
"(",
"save_pct",
",",
"3",
")",
"except",
"Zero... | Returns a ``float`` of the percentage of shots the home team saved.
Percentage ranges from 0-1. | [
"Returns",
"a",
"float",
"of",
"the",
"percentage",
"of",
"shots",
"the",
"home",
"team",
"saved",
".",
"Percentage",
"ranges",
"from",
"0",
"-",
"1",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/boxscore.py#L1069-L1078 | train | 34,650 |
roclark/sportsreference | sportsreference/ncaaf/schedule.py | Game.location | 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':
return NEUTRAL
if self._location.lower() == '@':
return AWAY
return HOME | python | 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':
return NEUTRAL
if self._location.lower() == '@':
return AWAY
return HOME | [
"def",
"location",
"(",
"self",
")",
":",
"if",
"self",
".",
"_location",
".",
"lower",
"(",
")",
"==",
"'n'",
":",
"return",
"NEUTRAL",
"if",
"self",
".",
"_location",
".",
"lower",
"(",
")",
"==",
"'@'",
":",
"return",
"AWAY",
"return",
"HOME"
] | Returns a ``string`` constant to indicate whether the game was played
at home, away, or in a neutral location. | [
"Returns",
"a",
"string",
"constant",
"to",
"indicate",
"whether",
"the",
"game",
"was",
"played",
"at",
"home",
"away",
"or",
"in",
"a",
"neutral",
"location",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/schedule.py#L223-L232 | train | 34,651 |
roclark/sportsreference | sportsreference/ncaaf/schedule.py | Game.rank | def rank(self):
"""
Returns an ``int`` of the team's rank at the time the game was played.
"""
rank = re.findall(r'\d+', self._rank)
if len(rank) == 0:
return None
return rank[0] | python | def rank(self):
"""
Returns an ``int`` of the team's rank at the time the game was played.
"""
rank = re.findall(r'\d+', self._rank)
if len(rank) == 0:
return None
return rank[0] | [
"def",
"rank",
"(",
"self",
")",
":",
"rank",
"=",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"self",
".",
"_rank",
")",
"if",
"len",
"(",
"rank",
")",
"==",
"0",
":",
"return",
"None",
"return",
"rank",
"[",
"0",
"]"
] | Returns an ``int`` of the team's rank at the time the game was played. | [
"Returns",
"an",
"int",
"of",
"the",
"team",
"s",
"rank",
"at",
"the",
"time",
"the",
"game",
"was",
"played",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/schedule.py#L235-L242 | train | 34,652 |
roclark/sportsreference | sportsreference/mlb/schedule.py | Game.datetime | def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
date_string = '%s %s' % (self._date, self._year)
date_string = re.sub(r' \(\d+\)', '', date_string)
return datetime.strptime(date_string, '%A, %b %d %Y') | python | def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
date_string = '%s %s' % (self._date, self._year)
date_string = re.sub(r' \(\d+\)', '', date_string)
return datetime.strptime(date_string, '%A, %b %d %Y') | [
"def",
"datetime",
"(",
"self",
")",
":",
"date_string",
"=",
"'%s %s'",
"%",
"(",
"self",
".",
"_date",
",",
"self",
".",
"_year",
")",
"date_string",
"=",
"re",
".",
"sub",
"(",
"r' \\(\\d+\\)'",
",",
"''",
",",
"date_string",
")",
"return",
"datetim... | Returns a datetime object of the month, day, year, and time the game
was played. | [
"Returns",
"a",
"datetime",
"object",
"of",
"the",
"month",
"day",
"year",
"and",
"time",
"the",
"game",
"was",
"played",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/schedule.py#L172-L179 | train | 34,653 |
roclark/sportsreference | sportsreference/mlb/schedule.py | Game.game_number_for_day | 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, the first game of the day will
return 1 while the second game will return 2.
"""
game_number = re.findall(r'\(\d+\)', self._date)
if len(game_number) == 0:
return 1
game_number = re.findall(r'\d+', game_number[0])
return int(game_number[0]) | python | 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, the first game of the day will
return 1 while the second game will return 2.
"""
game_number = re.findall(r'\(\d+\)', self._date)
if len(game_number) == 0:
return 1
game_number = re.findall(r'\d+', game_number[0])
return int(game_number[0]) | [
"def",
"game_number_for_day",
"(",
"self",
")",
":",
"game_number",
"=",
"re",
".",
"findall",
"(",
"r'\\(\\d+\\)'",
",",
"self",
".",
"_date",
")",
"if",
"len",
"(",
"game_number",
")",
"==",
"0",
":",
"return",
"1",
"game_number",
"=",
"re",
".",
"fi... | 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, the first game of the day will
return 1 while the second game will return 2. | [
"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",
... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/schedule.py#L182-L194 | train | 34,654 |
roclark/sportsreference | sportsreference/mlb/schedule.py | Game.games_behind | 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' in self._games_behind.lower():
games_behind = re.sub('up *', '', self._games_behind.lower())
try:
return float(games_behind) * -1.0
except ValueError:
return None
if 'tied' in self._games_behind.lower():
return 0.0
try:
return float(self._games_behind)
except ValueError:
return None | python | 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' in self._games_behind.lower():
games_behind = re.sub('up *', '', self._games_behind.lower())
try:
return float(games_behind) * -1.0
except ValueError:
return None
if 'tied' in self._games_behind.lower():
return 0.0
try:
return float(self._games_behind)
except ValueError:
return None | [
"def",
"games_behind",
"(",
"self",
")",
":",
"if",
"'up'",
"in",
"self",
".",
"_games_behind",
".",
"lower",
"(",
")",
":",
"games_behind",
"=",
"re",
".",
"sub",
"(",
"'up *'",
",",
"''",
",",
"self",
".",
"_games_behind",
".",
"lower",
"(",
")",
... | 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. | [
"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",
... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/schedule.py#L279-L296 | train | 34,655 |
roclark/sportsreference | sportsreference/mlb/teams.py | Team._parse_name | 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
within 'team_ID'. A few simple regex subs captures the team name. The
'_name' attribute is applied with the captured team name from this
function.
Parameters
----------
team_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
"""
name = team_data('td[data-stat="team_ID"]:first')
name = re.sub(r'.*title="', '', str(name))
name = re.sub(r'".*', '', name)
setattr(self, '_name', name) | python | 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
within 'team_ID'. A few simple regex subs captures the team name. The
'_name' attribute is applied with the captured team name from this
function.
Parameters
----------
team_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
"""
name = team_data('td[data-stat="team_ID"]:first')
name = re.sub(r'.*title="', '', str(name))
name = re.sub(r'".*', '', name)
setattr(self, '_name', name) | [
"def",
"_parse_name",
"(",
"self",
",",
"team_data",
")",
":",
"name",
"=",
"team_data",
"(",
"'td[data-stat=\"team_ID\"]:first'",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'.*title=\"'",
",",
"''",
",",
"str",
"(",
"name",
")",
")",
"name",
"=",
"re",
... | 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
within 'team_ID'. A few simple regex subs captures the team name. The
'_name' attribute is applied with the captured team name from this
function.
Parameters
----------
team_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string. | [
"Parses",
"the",
"team",
"s",
"name",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/teams.py#L140-L161 | train | 34,656 |
roclark/sportsreference | sportsreference/nba/schedule.py | Game._parse_opponent_abbr | 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.
Parameters
----------
game_data : PyQuery object
A PyQuery object containing the information specific to a game.
"""
opponent = game_data('td[data-stat="opp_name"]:first')
opponent = re.sub(r'.*/teams/', '', str(opponent))
opponent = re.sub(r'\/.*.html.*', '', opponent)
setattr(self, '_opponent_abbr', opponent) | python | 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.
Parameters
----------
game_data : PyQuery object
A PyQuery object containing the information specific to a game.
"""
opponent = game_data('td[data-stat="opp_name"]:first')
opponent = re.sub(r'.*/teams/', '', str(opponent))
opponent = re.sub(r'\/.*.html.*', '', opponent)
setattr(self, '_opponent_abbr', opponent) | [
"def",
"_parse_opponent_abbr",
"(",
"self",
",",
"game_data",
")",
":",
"opponent",
"=",
"game_data",
"(",
"'td[data-stat=\"opp_name\"]:first'",
")",
"opponent",
"=",
"re",
".",
"sub",
"(",
"r'.*/teams/'",
",",
"''",
",",
"str",
"(",
"opponent",
")",
")",
"o... | 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.
Parameters
----------
game_data : PyQuery object
A PyQuery object containing the information specific to a game. | [
"Parses",
"the",
"opponent",
"s",
"abbreviation",
"for",
"the",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/schedule.py#L66-L81 | train | 34,657 |
roclark/sportsreference | sportsreference/nba/schedule.py | Schedule._add_games_to_schedule | 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 object
A PyQuery object pertaining to a team's schedule table.
year : string
The requested year to pull stats from.
"""
for item in schedule:
if 'class="thead"' in str(item) or \
'class="over_header thead"' in str(item):
continue # pragma: no cover
game = Game(item)
self._games.append(game) | python | 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 object
A PyQuery object pertaining to a team's schedule table.
year : string
The requested year to pull stats from.
"""
for item in schedule:
if 'class="thead"' in str(item) or \
'class="over_header thead"' in str(item):
continue # pragma: no cover
game = Game(item)
self._games.append(game) | [
"def",
"_add_games_to_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"for",
"item",
"in",
"schedule",
":",
"if",
"'class=\"thead\"'",
"in",
"str",
"(",
"item",
")",
"or",
"'class=\"over_header thead\"'",
"in",
"str",
"(",
"item",
")",
":",
"continue",
"#... | 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 object
A PyQuery object pertaining to a team's schedule table.
year : string
The requested year to pull stats from. | [
"Add",
"game",
"information",
"to",
"list",
"of",
"games",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/schedule.py#L359-L378 | train | 34,658 |
roclark/sportsreference | sportsreference/ncaaf/boxscore.py | BoxscorePlayer.dataframe | 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,
'passing_completion': self.passing_completion,
'passing_yards': self.passing_yards,
'pass_yards_per_attempt': self.pass_yards_per_attempt,
'adjusted_yards_per_attempt': self.adjusted_yards_per_attempt,
'passing_touchdowns': self.passing_touchdowns,
'interceptions_thrown': self.interceptions_thrown,
'quarterback_rating': self.quarterback_rating,
'rush_attempts': self.rush_attempts,
'rush_yards': self.rush_yards,
'rush_yards_per_attempt': self.rush_yards_per_attempt,
'rush_touchdowns': self.rush_touchdowns,
'receptions': self.receptions,
'receiving_yards': self.receiving_yards,
'receiving_yards_per_reception':
self.receiving_yards_per_reception,
'receiving_touchdowns': self.receiving_touchdowns,
'plays_from_scrimmage': self.plays_from_scrimmage,
'yards_from_scrimmage': self.yards_from_scrimmage,
'yards_from_scrimmage_per_play':
self.yards_from_scrimmage_per_play,
'rushing_and_receiving_touchdowns':
self.rushing_and_receiving_touchdowns,
'solo_tackles': self.solo_tackles,
'assists_on_tackles': self.assists_on_tackles,
'total_tackles': self.total_tackles,
'tackles_for_loss': self.tackles_for_loss,
'sacks': self.sacks,
'interceptions': self.interceptions,
'yards_returned_from_interceptions':
self.yards_returned_from_interceptions,
'yards_returned_per_interception':
self.yards_returned_per_interception,
'interceptions_returned_for_touchdown':
self.interceptions_returned_for_touchdown,
'passes_defended': self.passes_defended,
'fumbles_recovered': self.fumbles_recovered,
'yards_recovered_from_fumble': self.yards_recovered_from_fumble,
'fumbles_recovered_for_touchdown':
self.fumbles_recovered_for_touchdown,
'fumbles_forced': self.fumbles_forced,
'kickoff_returns': self.kickoff_returns,
'kickoff_return_yards': self.kickoff_return_yards,
'average_kickoff_return_yards': self.average_kickoff_return_yards,
'kickoff_return_touchdowns': self.kickoff_return_touchdowns,
'punt_returns': self.punt_returns,
'punt_return_yards': self.punt_return_yards,
'average_punt_return_yards': self.average_punt_return_yards,
'punt_return_touchdowns': self.punt_return_touchdowns,
'extra_points_made': self.extra_points_made,
'extra_points_attempted': self.extra_points_attempted,
'extra_point_percentage': self.extra_point_percentage,
'field_goals_made': self.field_goals_made,
'field_goals_attempted': self.field_goals_attempted,
'field_goal_percentage': self.field_goal_percentage,
'points_kicking': self.points_kicking,
'punts': self.punts,
'punting_yards': self.punting_yards,
'punting_yards_per_punt': self.punting_yards_per_attempt
}
return pd.DataFrame([fields_to_include], index=[self._player_id]) | python | 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,
'passing_completion': self.passing_completion,
'passing_yards': self.passing_yards,
'pass_yards_per_attempt': self.pass_yards_per_attempt,
'adjusted_yards_per_attempt': self.adjusted_yards_per_attempt,
'passing_touchdowns': self.passing_touchdowns,
'interceptions_thrown': self.interceptions_thrown,
'quarterback_rating': self.quarterback_rating,
'rush_attempts': self.rush_attempts,
'rush_yards': self.rush_yards,
'rush_yards_per_attempt': self.rush_yards_per_attempt,
'rush_touchdowns': self.rush_touchdowns,
'receptions': self.receptions,
'receiving_yards': self.receiving_yards,
'receiving_yards_per_reception':
self.receiving_yards_per_reception,
'receiving_touchdowns': self.receiving_touchdowns,
'plays_from_scrimmage': self.plays_from_scrimmage,
'yards_from_scrimmage': self.yards_from_scrimmage,
'yards_from_scrimmage_per_play':
self.yards_from_scrimmage_per_play,
'rushing_and_receiving_touchdowns':
self.rushing_and_receiving_touchdowns,
'solo_tackles': self.solo_tackles,
'assists_on_tackles': self.assists_on_tackles,
'total_tackles': self.total_tackles,
'tackles_for_loss': self.tackles_for_loss,
'sacks': self.sacks,
'interceptions': self.interceptions,
'yards_returned_from_interceptions':
self.yards_returned_from_interceptions,
'yards_returned_per_interception':
self.yards_returned_per_interception,
'interceptions_returned_for_touchdown':
self.interceptions_returned_for_touchdown,
'passes_defended': self.passes_defended,
'fumbles_recovered': self.fumbles_recovered,
'yards_recovered_from_fumble': self.yards_recovered_from_fumble,
'fumbles_recovered_for_touchdown':
self.fumbles_recovered_for_touchdown,
'fumbles_forced': self.fumbles_forced,
'kickoff_returns': self.kickoff_returns,
'kickoff_return_yards': self.kickoff_return_yards,
'average_kickoff_return_yards': self.average_kickoff_return_yards,
'kickoff_return_touchdowns': self.kickoff_return_touchdowns,
'punt_returns': self.punt_returns,
'punt_return_yards': self.punt_return_yards,
'average_punt_return_yards': self.average_punt_return_yards,
'punt_return_touchdowns': self.punt_return_touchdowns,
'extra_points_made': self.extra_points_made,
'extra_points_attempted': self.extra_points_attempted,
'extra_point_percentage': self.extra_point_percentage,
'field_goals_made': self.field_goals_made,
'field_goals_attempted': self.field_goals_attempted,
'field_goal_percentage': self.field_goal_percentage,
'points_kicking': self.points_kicking,
'punts': self.punts,
'punting_yards': self.punting_yards,
'punting_yards_per_punt': self.punting_yards_per_attempt
}
return pd.DataFrame([fields_to_include], index=[self._player_id]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'completed_passes'",
":",
"self",
".",
"completed_passes",
",",
"'attempted_passes'",
":",
"self",
".",
"attempted_passes",
",",
"'passing_completion'",
":",
"self",
".",
"passing_completion"... | Returns a ``pandas DataFrame`` containing all other relevant class
properties and value for the specified game. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"relevant",
"class",
"properties",
"and",
"value",
"for",
"the",
"specified",
"game",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/boxscore.py#L101-L168 | train | 34,659 |
roclark/sportsreference | sportsreference/ncaaf/boxscore.py | Boxscore.dataframe | 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 is None:
return None
fields_to_include = {
'away_first_downs': self.away_first_downs,
'away_fumbles': self.away_fumbles,
'away_fumbles_lost': self.away_fumbles_lost,
'away_interceptions': self.away_interceptions,
'away_pass_attempts': self.away_pass_attempts,
'away_pass_completions': self.away_pass_completions,
'away_pass_touchdowns': self.away_pass_touchdowns,
'away_pass_yards': self.away_pass_yards,
'away_penalties': self.away_penalties,
'away_points': self.away_points,
'away_rush_attempts': self.away_rush_attempts,
'away_rush_touchdowns': self.away_rush_touchdowns,
'away_rush_yards': self.away_rush_yards,
'away_total_yards': self.away_total_yards,
'away_turnovers': self.away_turnovers,
'away_yards_from_penalties': self.away_yards_from_penalties,
'date': self.date,
'home_first_downs': self.home_first_downs,
'home_fumbles': self.home_fumbles,
'home_fumbles_lost': self.home_fumbles_lost,
'home_interceptions': self.home_interceptions,
'home_pass_attempts': self.home_pass_attempts,
'home_pass_completions': self.home_pass_completions,
'home_pass_touchdowns': self.home_pass_touchdowns,
'home_pass_yards': self.home_pass_yards,
'home_penalties': self.home_penalties,
'home_points': self.home_points,
'home_rush_attempts': self.home_rush_attempts,
'home_rush_touchdowns': self.home_rush_touchdowns,
'home_rush_yards': self.home_rush_yards,
'home_total_yards': self.home_total_yards,
'home_turnovers': self.home_turnovers,
'home_yards_from_penalties': self.home_yards_from_penalties,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'stadium': self.stadium,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | python | 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 is None:
return None
fields_to_include = {
'away_first_downs': self.away_first_downs,
'away_fumbles': self.away_fumbles,
'away_fumbles_lost': self.away_fumbles_lost,
'away_interceptions': self.away_interceptions,
'away_pass_attempts': self.away_pass_attempts,
'away_pass_completions': self.away_pass_completions,
'away_pass_touchdowns': self.away_pass_touchdowns,
'away_pass_yards': self.away_pass_yards,
'away_penalties': self.away_penalties,
'away_points': self.away_points,
'away_rush_attempts': self.away_rush_attempts,
'away_rush_touchdowns': self.away_rush_touchdowns,
'away_rush_yards': self.away_rush_yards,
'away_total_yards': self.away_total_yards,
'away_turnovers': self.away_turnovers,
'away_yards_from_penalties': self.away_yards_from_penalties,
'date': self.date,
'home_first_downs': self.home_first_downs,
'home_fumbles': self.home_fumbles,
'home_fumbles_lost': self.home_fumbles_lost,
'home_interceptions': self.home_interceptions,
'home_pass_attempts': self.home_pass_attempts,
'home_pass_completions': self.home_pass_completions,
'home_pass_touchdowns': self.home_pass_touchdowns,
'home_pass_yards': self.home_pass_yards,
'home_penalties': self.home_penalties,
'home_points': self.home_points,
'home_rush_attempts': self.home_rush_attempts,
'home_rush_touchdowns': self.home_rush_touchdowns,
'home_rush_yards': self.home_rush_yards,
'home_total_yards': self.home_total_yards,
'home_turnovers': self.home_turnovers,
'home_yards_from_penalties': self.home_yards_from_penalties,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'stadium': self.stadium,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_away_points",
"is",
"None",
"and",
"self",
".",
"_home_points",
"is",
"None",
":",
"return",
"None",
"fields_to_include",
"=",
"{",
"'away_first_downs'",
":",
"self",
".",
"away_first_downs",
",... | 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'. | [
"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"... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/boxscore.py#L708-L758 | train | 34,660 |
roclark/sportsreference | sportsreference/ncaaf/boxscore.py | Boxscore.winning_abbr | 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()
return utils._parse_abbreviation(self._home_name)
if 'cfb/schools' not in str(self._away_name):
return self._away_name.text()
return utils._parse_abbreviation(self._away_name) | python | 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()
return utils._parse_abbreviation(self._home_name)
if 'cfb/schools' not in str(self._away_name):
return self._away_name.text()
return utils._parse_abbreviation(self._away_name) | [
"def",
"winning_abbr",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"if",
"'cfb/schools'",
"not",
"in",
"str",
"(",
"self",
".",
"_home_name",
")",
":",
"return",
"self",
".",
"_home_name",
".",
"text",
"(",
")",
"return",
"... | Returns a ``string`` of the winning team's abbreviation, such as
'ALABAMA'
for the Alabama Crimson Tide. | [
"Returns",
"a",
"string",
"of",
"the",
"winning",
"team",
"s",
"abbreviation",
"such",
"as",
"ALABAMA",
"for",
"the",
"Alabama",
"Crimson",
"Tide",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/boxscore.py#L818-L830 | train | 34,661 |
roclark/sportsreference | sportsreference/ncaaf/roster.py | Player._combine_all_stats | 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
----------
player_info : PyQuery object
A PyQuery object containing all of the stats information for the
requested player.
Returns
-------
dictionary
Returns a dictionary where all stats from each table are combined
by season to allow easy queries by year.
"""
all_stats_dict = {}
for table_id in ['passing', 'rushing', 'defense', 'scoring']:
table_items = utils._get_stats_table(player_info,
'table#%s' % table_id)
career_items = utils._get_stats_table(player_info,
'table#%s' % table_id,
footer=True)
all_stats_dict = self._combine_season_stats(table_items,
career_items,
all_stats_dict)
return all_stats_dict | python | 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
----------
player_info : PyQuery object
A PyQuery object containing all of the stats information for the
requested player.
Returns
-------
dictionary
Returns a dictionary where all stats from each table are combined
by season to allow easy queries by year.
"""
all_stats_dict = {}
for table_id in ['passing', 'rushing', 'defense', 'scoring']:
table_items = utils._get_stats_table(player_info,
'table#%s' % table_id)
career_items = utils._get_stats_table(player_info,
'table#%s' % table_id,
footer=True)
all_stats_dict = self._combine_season_stats(table_items,
career_items,
all_stats_dict)
return all_stats_dict | [
"def",
"_combine_all_stats",
"(",
"self",
",",
"player_info",
")",
":",
"all_stats_dict",
"=",
"{",
"}",
"for",
"table_id",
"in",
"[",
"'passing'",
",",
"'rushing'",
",",
"'defense'",
",",
"'scoring'",
"]",
":",
"table_items",
"=",
"utils",
".",
"_get_stats_... | 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
----------
player_info : PyQuery object
A PyQuery object containing all of the stats information for the
requested player.
Returns
-------
dictionary
Returns a dictionary where all stats from each table are combined
by season to allow easy queries by year. | [
"Pull",
"stats",
"from",
"all",
"tables",
"into",
"a",
"single",
"data",
"structure",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/roster.py#L233-L264 | train | 34,662 |
roclark/sportsreference | sportsreference/ncaaf/roster.py | Player._pull_player_data | 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 which can
easily be iterated upon.
Returns
-------
dictionary
Returns a dictionary of the player's combined stats where each key
is a string of the season and the value is the season's associated
stats.
"""
player_info = self._retrieve_html_page()
if not player_info:
return
self._parse_player_information(player_info)
all_stats = self._combine_all_stats(player_info)
setattr(self, '_season', list(all_stats.keys()))
return all_stats | python | 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 which can
easily be iterated upon.
Returns
-------
dictionary
Returns a dictionary of the player's combined stats where each key
is a string of the season and the value is the season's associated
stats.
"""
player_info = self._retrieve_html_page()
if not player_info:
return
self._parse_player_information(player_info)
all_stats = self._combine_all_stats(player_info)
setattr(self, '_season', list(all_stats.keys()))
return all_stats | [
"def",
"_pull_player_data",
"(",
"self",
")",
":",
"player_info",
"=",
"self",
".",
"_retrieve_html_page",
"(",
")",
"if",
"not",
"player_info",
":",
"return",
"self",
".",
"_parse_player_information",
"(",
"player_info",
")",
"all_stats",
"=",
"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 which can
easily be iterated upon.
Returns
-------
dictionary
Returns a dictionary of the player's combined stats where each key
is a string of the season and the value is the season's associated
stats. | [
"Pull",
"and",
"aggregate",
"all",
"player",
"information",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/roster.py#L284-L306 | train | 34,663 |
roclark/sportsreference | sportsreference/nhl/roster.py | Player.team_abbreviation | def team_abbreviation(self):
"""
Returns a ``string`` of the team's abbreviation, such as 'DET' for the
Detroit Red Wings.
"""
# For career stats, skip the team abbreviation.
if self._season[self._index].lower() == 'career':
return None
return self._team_abbreviation[self._index] | python | def team_abbreviation(self):
"""
Returns a ``string`` of the team's abbreviation, such as 'DET' for the
Detroit Red Wings.
"""
# For career stats, skip the team abbreviation.
if self._season[self._index].lower() == 'career':
return None
return self._team_abbreviation[self._index] | [
"def",
"team_abbreviation",
"(",
"self",
")",
":",
"# For career stats, skip the team abbreviation.",
"if",
"self",
".",
"_season",
"[",
"self",
".",
"_index",
"]",
".",
"lower",
"(",
")",
"==",
"'career'",
":",
"return",
"None",
"return",
"self",
".",
"_team_... | Returns a ``string`` of the team's abbreviation, such as 'DET' for the
Detroit Red Wings. | [
"Returns",
"a",
"string",
"of",
"the",
"team",
"s",
"abbreviation",
"such",
"as",
"DET",
"for",
"the",
"Detroit",
"Red",
"Wings",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/roster.py#L548-L556 | train | 34,664 |
elehcimd/pynb | pynb/notebook.py | Notebook.add_cell_footer | 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 in self.nb['cells']:
if cell.cell_type == 'markdown':
if 'pynb_footer_tag' in cell.source:
logging.debug('Footer cell already present')
return
m = """
---
* **Notebook class name**: {class_name}
* **Notebook cells name**: {cells_name}
* **Execution time**: {exec_begin}
* **Execution duration**: {exec_time:.2f}s
* **Command line**: {argv}
[//]: # (pynb_footer_tag)
"""
self.add_cell_markdown(
m.format(exec_time=self.exec_time, exec_begin=self.exec_begin_dt, class_name=self.__class__.__name__,
argv=str(sys.argv), cells_name=self.cells_name)) | python | 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 in self.nb['cells']:
if cell.cell_type == 'markdown':
if 'pynb_footer_tag' in cell.source:
logging.debug('Footer cell already present')
return
m = """
---
* **Notebook class name**: {class_name}
* **Notebook cells name**: {cells_name}
* **Execution time**: {exec_begin}
* **Execution duration**: {exec_time:.2f}s
* **Command line**: {argv}
[//]: # (pynb_footer_tag)
"""
self.add_cell_markdown(
m.format(exec_time=self.exec_time, exec_begin=self.exec_begin_dt, class_name=self.__class__.__name__,
argv=str(sys.argv), cells_name=self.cells_name)) | [
"def",
"add_cell_footer",
"(",
"self",
")",
":",
"# 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",
... | Add footer cell | [
"Add",
"footer",
"cell"
] | a32af1f0e574f880eccda4a46aede6d65151f8c9 | https://github.com/elehcimd/pynb/blob/a32af1f0e574f880eccda4a46aede6d65151f8c9/pynb/notebook.py#L278-L306 | train | 34,665 |
elehcimd/pynb | pynb/notebook.py | Notebook.get_kernelspec | def get_kernelspec(self, name):
"""Get a kernel specification dictionary given a kernel name
"""
ksm = KernelSpecManager()
kernelspec = ksm.get_kernel_spec(name).to_dict()
kernelspec['name'] = name
kernelspec.pop('argv')
return kernelspec | python | def get_kernelspec(self, name):
"""Get a kernel specification dictionary given a kernel name
"""
ksm = KernelSpecManager()
kernelspec = ksm.get_kernel_spec(name).to_dict()
kernelspec['name'] = name
kernelspec.pop('argv')
return kernelspec | [
"def",
"get_kernelspec",
"(",
"self",
",",
"name",
")",
":",
"ksm",
"=",
"KernelSpecManager",
"(",
")",
"kernelspec",
"=",
"ksm",
".",
"get_kernel_spec",
"(",
"name",
")",
".",
"to_dict",
"(",
")",
"kernelspec",
"[",
"'name'",
"]",
"=",
"name",
"kernelsp... | Get a kernel specification dictionary given a kernel name | [
"Get",
"a",
"kernel",
"specification",
"dictionary",
"given",
"a",
"kernel",
"name"
] | a32af1f0e574f880eccda4a46aede6d65151f8c9 | https://github.com/elehcimd/pynb/blob/a32af1f0e574f880eccda4a46aede6d65151f8c9/pynb/notebook.py#L558-L565 | train | 34,666 |
elehcimd/pynb | fabfile.py | docker_start | 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:
# Install package in develop mode: the code in /code is mapped to the installed package.
docker_exec('python3 setup.py develop')
print('Jupyter available at http://127.0.0.1:8889') | python | 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:
# Install package in develop mode: the code in /code is mapped to the installed package.
docker_exec('python3 setup.py develop')
print('Jupyter available at http://127.0.0.1:8889') | [
"def",
"docker_start",
"(",
"develop",
"=",
"True",
")",
":",
"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 {}... | Start docker container | [
"Start",
"docker",
"container"
] | a32af1f0e574f880eccda4a46aede6d65151f8c9 | https://github.com/elehcimd/pynb/blob/a32af1f0e574f880eccda4a46aede6d65151f8c9/fabfile.py#L99-L110 | train | 34,667 |
glut23/webvtt-py | webvtt/parsers.py | TextBasedParser.read | def read(self, file):
"""Reads the captions file."""
content = self._read_content(file)
self._validate(content)
self._parse(content)
return self | python | def read(self, file):
"""Reads the captions file."""
content = self._read_content(file)
self._validate(content)
self._parse(content)
return self | [
"def",
"read",
"(",
"self",
",",
"file",
")",
":",
"content",
"=",
"self",
".",
"_read_content",
"(",
"file",
")",
"self",
".",
"_validate",
"(",
"content",
")",
"self",
".",
"_parse",
"(",
"content",
")",
"return",
"self"
] | Reads the captions file. | [
"Reads",
"the",
"captions",
"file",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/parsers.py#L22-L28 | train | 34,668 |
glut23/webvtt-py | webvtt/parsers.py | TextBasedParser._parse_timeframe_line | def _parse_timeframe_line(self, line):
"""Parse timeframe line and return start and end timestamps."""
tf = self._validate_timeframe_line(line)
if not tf:
raise MalformedCaptionError('Invalid time format')
return tf.group(1), tf.group(2) | python | def _parse_timeframe_line(self, line):
"""Parse timeframe line and return start and end timestamps."""
tf = self._validate_timeframe_line(line)
if not tf:
raise MalformedCaptionError('Invalid time format')
return tf.group(1), tf.group(2) | [
"def",
"_parse_timeframe_line",
"(",
"self",
",",
"line",
")",
":",
"tf",
"=",
"self",
".",
"_validate_timeframe_line",
"(",
"line",
")",
"if",
"not",
"tf",
":",
"raise",
"MalformedCaptionError",
"(",
"'Invalid time format'",
")",
"return",
"tf",
".",
"group",... | Parse timeframe line and return start and end timestamps. | [
"Parse",
"timeframe",
"line",
"and",
"return",
"start",
"and",
"end",
"timestamps",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/parsers.py#L49-L55 | train | 34,669 |
glut23/webvtt-py | webvtt/cli.py | main | def main():
"""Main entry point for CLI commands."""
options = docopt(__doc__, version=__version__)
if options['segment']:
segment(
options['<file>'],
options['--output'],
options['--target-duration'],
options['--mpegts'],
) | python | def main():
"""Main entry point for CLI commands."""
options = docopt(__doc__, version=__version__)
if options['segment']:
segment(
options['<file>'],
options['--output'],
options['--target-duration'],
options['--mpegts'],
) | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")",
"if",
"options",
"[",
"'segment'",
"]",
":",
"segment",
"(",
"options",
"[",
"'<file>'",
"]",
",",
"options",
"[",
"'--output'",
"]",
",",
... | Main entry point for CLI commands. | [
"Main",
"entry",
"point",
"for",
"CLI",
"commands",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/cli.py#L23-L32 | train | 34,670 |
glut23/webvtt-py | webvtt/cli.py | segment | def segment(f, output, target_duration, mpegts):
"""Segment command."""
try:
target_duration = int(target_duration)
except ValueError:
exit('Error: Invalid target duration.')
try:
mpegts = int(mpegts)
except ValueError:
exit('Error: Invalid MPEGTS value.')
WebVTTSegmenter().segment(f, output, target_duration, mpegts) | python | def segment(f, output, target_duration, mpegts):
"""Segment command."""
try:
target_duration = int(target_duration)
except ValueError:
exit('Error: Invalid target duration.')
try:
mpegts = int(mpegts)
except ValueError:
exit('Error: Invalid MPEGTS value.')
WebVTTSegmenter().segment(f, output, target_duration, mpegts) | [
"def",
"segment",
"(",
"f",
",",
"output",
",",
"target_duration",
",",
"mpegts",
")",
":",
"try",
":",
"target_duration",
"=",
"int",
"(",
"target_duration",
")",
"except",
"ValueError",
":",
"exit",
"(",
"'Error: Invalid target duration.'",
")",
"try",
":",
... | Segment command. | [
"Segment",
"command",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/cli.py#L35-L47 | train | 34,671 |
glut23/webvtt-py | webvtt/webvtt.py | WebVTT.from_srt | def from_srt(cls, file):
"""Reads captions from a file in SubRip format."""
parser = SRTParser().read(file)
return cls(file=file, captions=parser.captions) | python | def from_srt(cls, file):
"""Reads captions from a file in SubRip format."""
parser = SRTParser().read(file)
return cls(file=file, captions=parser.captions) | [
"def",
"from_srt",
"(",
"cls",
",",
"file",
")",
":",
"parser",
"=",
"SRTParser",
"(",
")",
".",
"read",
"(",
"file",
")",
"return",
"cls",
"(",
"file",
"=",
"file",
",",
"captions",
"=",
"parser",
".",
"captions",
")"
] | Reads captions from a file in SubRip format. | [
"Reads",
"captions",
"from",
"a",
"file",
"in",
"SubRip",
"format",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L46-L49 | train | 34,672 |
glut23/webvtt-py | webvtt/webvtt.py | WebVTT.from_sbv | def from_sbv(cls, file):
"""Reads captions from a file in YouTube SBV format."""
parser = SBVParser().read(file)
return cls(file=file, captions=parser.captions) | python | def from_sbv(cls, file):
"""Reads captions from a file in YouTube SBV format."""
parser = SBVParser().read(file)
return cls(file=file, captions=parser.captions) | [
"def",
"from_sbv",
"(",
"cls",
",",
"file",
")",
":",
"parser",
"=",
"SBVParser",
"(",
")",
".",
"read",
"(",
"file",
")",
"return",
"cls",
"(",
"file",
"=",
"file",
",",
"captions",
"=",
"parser",
".",
"captions",
")"
] | Reads captions from a file in YouTube SBV format. | [
"Reads",
"captions",
"from",
"a",
"file",
"in",
"YouTube",
"SBV",
"format",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L52-L55 | train | 34,673 |
glut23/webvtt-py | webvtt/webvtt.py | WebVTT.read | def read(cls, file):
"""Reads a WebVTT captions file."""
parser = WebVTTParser().read(file)
return cls(file=file, captions=parser.captions, styles=parser.styles) | python | def read(cls, file):
"""Reads a WebVTT captions file."""
parser = WebVTTParser().read(file)
return cls(file=file, captions=parser.captions, styles=parser.styles) | [
"def",
"read",
"(",
"cls",
",",
"file",
")",
":",
"parser",
"=",
"WebVTTParser",
"(",
")",
".",
"read",
"(",
"file",
")",
"return",
"cls",
"(",
"file",
"=",
"file",
",",
"captions",
"=",
"parser",
".",
"captions",
",",
"styles",
"=",
"parser",
".",... | Reads a WebVTT captions file. | [
"Reads",
"a",
"WebVTT",
"captions",
"file",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L58-L61 | train | 34,674 |
glut23/webvtt-py | webvtt/webvtt.py | WebVTT.save | def save(self, output=''):
"""Save the document.
If no output is provided the file will be saved in the same location. Otherwise output
can determine a target directory or file.
"""
self.file = self._get_output_file(output)
with open(self.file, 'w', encoding='utf-8') as f:
self.write(f) | python | def save(self, output=''):
"""Save the document.
If no output is provided the file will be saved in the same location. Otherwise output
can determine a target directory or file.
"""
self.file = self._get_output_file(output)
with open(self.file, 'w', encoding='utf-8') as f:
self.write(f) | [
"def",
"save",
"(",
"self",
",",
"output",
"=",
"''",
")",
":",
"self",
".",
"file",
"=",
"self",
".",
"_get_output_file",
"(",
"output",
")",
"with",
"open",
"(",
"self",
".",
"file",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
... | Save the document.
If no output is provided the file will be saved in the same location. Otherwise output
can determine a target directory or file. | [
"Save",
"the",
"document",
".",
"If",
"no",
"output",
"is",
"provided",
"the",
"file",
"will",
"be",
"saved",
"in",
"the",
"same",
"location",
".",
"Otherwise",
"output",
"can",
"determine",
"a",
"target",
"directory",
"or",
"file",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L84-L91 | train | 34,675 |
glut23/webvtt-py | webvtt/webvtt.py | WebVTT.total_length | def total_length(self):
"""Returns the total length of the captions."""
if not self._captions:
return 0
return int(self._captions[-1].end_in_seconds) - int(self._captions[0].start_in_seconds) | python | def total_length(self):
"""Returns the total length of the captions."""
if not self._captions:
return 0
return int(self._captions[-1].end_in_seconds) - int(self._captions[0].start_in_seconds) | [
"def",
"total_length",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_captions",
":",
"return",
"0",
"return",
"int",
"(",
"self",
".",
"_captions",
"[",
"-",
"1",
"]",
".",
"end_in_seconds",
")",
"-",
"int",
"(",
"self",
".",
"_captions",
"[",
... | Returns the total length of the captions. | [
"Returns",
"the",
"total",
"length",
"of",
"the",
"captions",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/webvtt.py#L117-L121 | train | 34,676 |
glut23/webvtt-py | webvtt/segmenter.py | WebVTTSegmenter.segment | 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(webvtt):
raise InvalidCaptionsError('The captions provided are invalid')
else:
# we expect to have a webvtt object
captions = webvtt.captions
self._total_segments = 0 if not captions else int(ceil(captions[-1].end_in_seconds / seconds))
self._output_folder = output
self._seconds = seconds
self._mpegts = mpegts
output_folder = os.path.join(os.getcwd(), output)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self._slice_segments(captions)
self._write_segments()
self._write_manifest() | python | 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(webvtt):
raise InvalidCaptionsError('The captions provided are invalid')
else:
# we expect to have a webvtt object
captions = webvtt.captions
self._total_segments = 0 if not captions else int(ceil(captions[-1].end_in_seconds / seconds))
self._output_folder = output
self._seconds = seconds
self._mpegts = mpegts
output_folder = os.path.join(os.getcwd(), output)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self._slice_segments(captions)
self._write_segments()
self._write_manifest() | [
"def",
"segment",
"(",
"self",
",",
"webvtt",
",",
"output",
"=",
"''",
",",
"seconds",
"=",
"SECONDS",
",",
"mpegts",
"=",
"MPEGTS",
")",
":",
"if",
"isinstance",
"(",
"webvtt",
",",
"str",
")",
":",
"# if a string is supplied we parse the file",
"captions"... | Segments the captions based on a number of seconds. | [
"Segments",
"the",
"captions",
"based",
"on",
"a",
"number",
"of",
"seconds",
"."
] | 7b4da0123c2e2afaf31402107528721eb1d3d481 | https://github.com/glut23/webvtt-py/blob/7b4da0123c2e2afaf31402107528721eb1d3d481/webvtt/segmenter.py#L73-L95 | train | 34,677 |
simonw/csvs-to-sqlite | csvs_to_sqlite/utils.py | best_fts_version | def best_fts_version():
"Discovers the most advanced supported SQLite FTS version"
conn = sqlite3.connect(":memory:")
for fts in ("FTS5", "FTS4", "FTS3"):
try:
conn.execute("CREATE VIRTUAL TABLE v USING {} (t TEXT);".format(fts))
return fts
except sqlite3.OperationalError:
continue
return None | python | def best_fts_version():
"Discovers the most advanced supported SQLite FTS version"
conn = sqlite3.connect(":memory:")
for fts in ("FTS5", "FTS4", "FTS3"):
try:
conn.execute("CREATE VIRTUAL TABLE v USING {} (t TEXT);".format(fts))
return fts
except sqlite3.OperationalError:
continue
return None | [
"def",
"best_fts_version",
"(",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"\":memory:\"",
")",
"for",
"fts",
"in",
"(",
"\"FTS5\"",
",",
"\"FTS4\"",
",",
"\"FTS3\"",
")",
":",
"try",
":",
"conn",
".",
"execute",
"(",
"\"CREATE VIRTUAL TABLE v ... | Discovers the most advanced supported SQLite FTS version | [
"Discovers",
"the",
"most",
"advanced",
"supported",
"SQLite",
"FTS",
"version"
] | 0a014284eac75c1b06cbdaca362f2a66648c11d2 | https://github.com/simonw/csvs-to-sqlite/blob/0a014284eac75c1b06cbdaca362f2a66648c11d2/csvs_to_sqlite/utils.py#L359-L368 | train | 34,678 |
rochacbruno/manage | manage/commands_collector.py | add_click_commands | 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, function in module_commands:
f_options = options.get(name, {})
command_name = f_options.get('name', getattr(function, 'name', name))
if namespace:
command_name = '{}_{}'.format(namespace, command_name)
elif namespaced:
module_namespace = module.__name__.split('.')[-1]
command_name = '{}_{}'.format(module_namespace, command_name)
function.short_help = f_options.get('help_text', function.short_help)
cli.add_command(function, name=command_name) | python | 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, function in module_commands:
f_options = options.get(name, {})
command_name = f_options.get('name', getattr(function, 'name', name))
if namespace:
command_name = '{}_{}'.format(namespace, command_name)
elif namespaced:
module_namespace = module.__name__.split('.')[-1]
command_name = '{}_{}'.format(module_namespace, command_name)
function.short_help = f_options.get('help_text', function.short_help)
cli.add_command(function, name=command_name) | [
"def",
"add_click_commands",
"(",
"module",
",",
"cli",
",",
"command_dict",
",",
"namespaced",
")",
":",
"module_commands",
"=",
"[",
"item",
"for",
"item",
"in",
"getmembers",
"(",
"module",
")",
"if",
"isinstance",
"(",
"item",
"[",
"1",
"]",
",",
"Ba... | Loads all click commands | [
"Loads",
"all",
"click",
"commands"
] | e904c451862f036f4be8723df5704a9844103c74 | https://github.com/rochacbruno/manage/blob/e904c451862f036f4be8723df5704a9844103c74/manage/commands_collector.py#L10-L27 | train | 34,679 |
rochacbruno/manage | manage/commands_collector.py | load_commands | 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'])
group = cli.manage_groups.get(command_dict.get('group'), cli)
if getattr(root_module, '__path__', None):
# This is a package
iter_modules = pkgutil.iter_modules(
root_module.__path__, prefix=root_module.__name__ + '.'
)
submodules_names = [item[1] for item in iter_modules]
submodules = [import_string(name) for name in submodules_names]
for module in submodules:
add_click_commands(module, group, command_dict, namespaced)
else:
# a single file module
add_click_commands(root_module, group, command_dict, namespaced)
# get inline commands
commands = manage_dict.get('inline_commands', [])
for command_dict in commands:
name = command_dict['name']
help_text = command_dict.get('help_text')
options = command_dict.get('options', {})
arguments = command_dict.get('arguments', {})
context = command_dict.get('context', [])
code = command_dict['code']
group = cli.manage_groups.get(command_dict.get('group'), cli)
group.add_command(
make_command_from_string(
code=code,
cmd_context=get_context(context),
options=options,
arguments=arguments,
help_text=help_text
),
name=name
)
# get function commands
commands = manage_dict.get('function_commands', [])
for command_dict in commands:
name = command_dict['name']
help_text = command_dict.get('help_text')
options = command_dict.get('options', {})
arguments = command_dict.get('arguments', {})
function = import_string(command_dict['function'])
group = cli.manage_groups.get(command_dict.get('group'), cli)
group.add_command(
make_command_from_function(
function=function,
options=options,
arguments=arguments,
help_text=help_text
),
name=name
) | python | 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'])
group = cli.manage_groups.get(command_dict.get('group'), cli)
if getattr(root_module, '__path__', None):
# This is a package
iter_modules = pkgutil.iter_modules(
root_module.__path__, prefix=root_module.__name__ + '.'
)
submodules_names = [item[1] for item in iter_modules]
submodules = [import_string(name) for name in submodules_names]
for module in submodules:
add_click_commands(module, group, command_dict, namespaced)
else:
# a single file module
add_click_commands(root_module, group, command_dict, namespaced)
# get inline commands
commands = manage_dict.get('inline_commands', [])
for command_dict in commands:
name = command_dict['name']
help_text = command_dict.get('help_text')
options = command_dict.get('options', {})
arguments = command_dict.get('arguments', {})
context = command_dict.get('context', [])
code = command_dict['code']
group = cli.manage_groups.get(command_dict.get('group'), cli)
group.add_command(
make_command_from_string(
code=code,
cmd_context=get_context(context),
options=options,
arguments=arguments,
help_text=help_text
),
name=name
)
# get function commands
commands = manage_dict.get('function_commands', [])
for command_dict in commands:
name = command_dict['name']
help_text = command_dict.get('help_text')
options = command_dict.get('options', {})
arguments = command_dict.get('arguments', {})
function = import_string(command_dict['function'])
group = cli.manage_groups.get(command_dict.get('group'), cli)
group.add_command(
make_command_from_function(
function=function,
options=options,
arguments=arguments,
help_text=help_text
),
name=name
) | [
"def",
"load_commands",
"(",
"cli",
",",
"manage_dict",
")",
":",
"namespaced",
"=",
"manage_dict",
".",
"get",
"(",
"'namespaced'",
")",
"# get click commands",
"commands",
"=",
"manage_dict",
".",
"get",
"(",
"'click_commands'",
",",
"[",
"]",
")",
"for",
... | Loads the commands defined in manage file | [
"Loads",
"the",
"commands",
"defined",
"in",
"manage",
"file"
] | e904c451862f036f4be8723df5704a9844103c74 | https://github.com/rochacbruno/manage/blob/e904c451862f036f4be8723df5704a9844103c74/manage/commands_collector.py#L83-L143 | train | 34,680 |
rochacbruno/manage | manage/cli.py | debug | def debug(version=False):
"""Shows the parsed manage file -V shows version"""
if version:
print(__version__)
return
print(json.dumps(MANAGE_DICT, indent=2)) | python | def debug(version=False):
"""Shows the parsed manage file -V shows version"""
if version:
print(__version__)
return
print(json.dumps(MANAGE_DICT, indent=2)) | [
"def",
"debug",
"(",
"version",
"=",
"False",
")",
":",
"if",
"version",
":",
"print",
"(",
"__version__",
")",
"return",
"print",
"(",
"json",
".",
"dumps",
"(",
"MANAGE_DICT",
",",
"indent",
"=",
"2",
")",
")"
] | Shows the parsed manage file -V shows version | [
"Shows",
"the",
"parsed",
"manage",
"file",
"-",
"V",
"shows",
"version"
] | e904c451862f036f4be8723df5704a9844103c74 | https://github.com/rochacbruno/manage/blob/e904c451862f036f4be8723df5704a9844103c74/manage/cli.py#L95-L100 | train | 34,681 |
rochacbruno/manage | manage/cli.py | create_shell | 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.update(auto_imported)
msgs = []
if manage_dict['shell']['banner']['enabled']:
msgs.append(
manage_dict['shell']['banner']['message'].format(**manage_dict)
)
if auto_imported and manage_dict['shell']['auto_import']['display']:
auto_imported_names = [
key for key in auto_imported.keys()
if key not in ['__builtins__', 'builtins']
]
msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names))
banner_msg = u'\n'.join(msgs)
exec_init(manage_dict, _vars)
exec_init_script(manage_dict, _vars)
atexit_functions = [
import_string(func_name) for func_name in
manage_dict['shell'].get('exit_hooks', [])
]
atexit_functions += exit_hooks or []
for atexit_function in atexit_functions:
atexit.register(atexit_function)
if console == 'ptpython':
try:
from ptpython.repl import embed
embed({}, _vars)
except ImportError:
click.echo("ptpython is not installed!")
return
if console == 'bpython':
try:
from bpython import embed
embed(locals_=_vars, banner=banner_msg)
except ImportError:
click.echo("bpython is not installed!")
return
try:
if console == 'ipython':
from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = banner_msg
c.InteractiveShellApp.extensions = [
extension for extension in
manage_dict['shell'].get('ipython_extensions', [])
]
c.InteractiveShellApp.exec_lines = [
exec_line for exec_line in
manage_dict['shell'].get('ipython_exec_lines', [])
]
if manage_dict['shell'].get('ipython_auto_reload', True) is True:
c.InteractiveShellApp.extensions.append('autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
start_ipython(argv=[], user_ns=_vars, config=c)
else:
raise ImportError
except ImportError:
if manage_dict['shell']['readline_enabled']:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(_vars).complete)
readline.parse_and_bind('tab: complete')
shell = code.InteractiveConsole(_vars)
shell.interact(banner=banner_msg) | python | 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.update(auto_imported)
msgs = []
if manage_dict['shell']['banner']['enabled']:
msgs.append(
manage_dict['shell']['banner']['message'].format(**manage_dict)
)
if auto_imported and manage_dict['shell']['auto_import']['display']:
auto_imported_names = [
key for key in auto_imported.keys()
if key not in ['__builtins__', 'builtins']
]
msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names))
banner_msg = u'\n'.join(msgs)
exec_init(manage_dict, _vars)
exec_init_script(manage_dict, _vars)
atexit_functions = [
import_string(func_name) for func_name in
manage_dict['shell'].get('exit_hooks', [])
]
atexit_functions += exit_hooks or []
for atexit_function in atexit_functions:
atexit.register(atexit_function)
if console == 'ptpython':
try:
from ptpython.repl import embed
embed({}, _vars)
except ImportError:
click.echo("ptpython is not installed!")
return
if console == 'bpython':
try:
from bpython import embed
embed(locals_=_vars, banner=banner_msg)
except ImportError:
click.echo("bpython is not installed!")
return
try:
if console == 'ipython':
from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = banner_msg
c.InteractiveShellApp.extensions = [
extension for extension in
manage_dict['shell'].get('ipython_extensions', [])
]
c.InteractiveShellApp.exec_lines = [
exec_line for exec_line in
manage_dict['shell'].get('ipython_exec_lines', [])
]
if manage_dict['shell'].get('ipython_auto_reload', True) is True:
c.InteractiveShellApp.extensions.append('autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
start_ipython(argv=[], user_ns=_vars, config=c)
else:
raise ImportError
except ImportError:
if manage_dict['shell']['readline_enabled']:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(_vars).complete)
readline.parse_and_bind('tab: complete')
shell = code.InteractiveConsole(_vars)
shell.interact(banner=banner_msg) | [
"def",
"create_shell",
"(",
"console",
",",
"manage_dict",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"exit_hooks",
"=",
"None",
")",
":",
"manage_dict",
"=",
"manage_dict",
"or",
"MANAGE_DICT",
"_vars",
"=",
"globals",
"(",
")",
"_vars",
".",
"upda... | Creates the shell | [
"Creates",
"the",
"shell"
] | e904c451862f036f4be8723df5704a9844103c74 | https://github.com/rochacbruno/manage/blob/e904c451862f036f4be8723df5704a9844103c74/manage/cli.py#L103-L180 | train | 34,682 |
sk-/git-lint | gitlint/__init__.py | find_invalid_filenames | 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 filename in filenames:
if not os.path.abspath(filename).startswith(repository_root):
errors.append((filename, 'Error: File %s does not belong to '
'repository %s' % (filename, repository_root)))
if not os.path.exists(filename):
errors.append((filename,
'Error: File %s does not exist' % (filename, )))
if os.path.isdir(filename):
errors.append((filename,
'Error: %s is a directory. Directories are'
' not yet supported' % (filename, )))
return errors | python | 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 filename in filenames:
if not os.path.abspath(filename).startswith(repository_root):
errors.append((filename, 'Error: File %s does not belong to '
'repository %s' % (filename, repository_root)))
if not os.path.exists(filename):
errors.append((filename,
'Error: File %s does not exist' % (filename, )))
if os.path.isdir(filename):
errors.append((filename,
'Error: %s is a directory. Directories are'
' not yet supported' % (filename, )))
return errors | [
"def",
"find_invalid_filenames",
"(",
"filenames",
",",
"repository_root",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"filename",
"in",
"filenames",
":",
"if",
"not",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
".",
"startswith",
"(",
"reposito... | 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. | [
"Find",
"files",
"that",
"does",
"not",
"exist",
"are",
"not",
"in",
"the",
"repo",
"or",
"are",
"directories",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/__init__.py#L65-L87 | train | 34,683 |
sk-/git-lint | gitlint/__init__.py | get_config | 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):
config = repo_config
with open(config) as f:
# We have to read the content first as yaml hangs up when reading from
# MockOpen
content = f.read()
# Yaml.load will return None when the input is empty.
if not content:
yaml_config = {}
else:
yaml_config = yaml.load(content)
return linters.parse_yaml_config(yaml_config, repo_root) | python | 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):
config = repo_config
with open(config) as f:
# We have to read the content first as yaml hangs up when reading from
# MockOpen
content = f.read()
# Yaml.load will return None when the input is empty.
if not content:
yaml_config = {}
else:
yaml_config = yaml.load(content)
return linters.parse_yaml_config(yaml_config, repo_root) | [
"def",
"get_config",
"(",
"repo_root",
")",
":",
"config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'configs'",
",",
"'config.yaml'",
")",
"if",
"repo_root",
":",
"repo_config",
"=",
"os",... | Gets the configuration file either from the repository or the default. | [
"Gets",
"the",
"configuration",
"file",
"either",
"from",
"the",
"repository",
"or",
"the",
"default",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/__init__.py#L90-L109 | train | 34,684 |
sk-/git-lint | gitlint/__init__.py | format_comment | 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.
Args:
comment_data: dictionary with the linter data.
Returns:
a string with the formatted message.
"""
format_pieces = []
# Line and column information
if 'line' in comment_data:
format_pieces.append('line {line}')
if 'column' in comment_data:
if format_pieces:
format_pieces.append(', ')
format_pieces.append('col {column}')
if format_pieces:
format_pieces.append(': ')
# Severity and Id information
if 'severity' in comment_data:
format_pieces.append('{severity}: ')
if 'message_id' in comment_data:
format_pieces.append('[{message_id}]: ')
# The message
if 'message' in comment_data:
format_pieces.append('{message}')
return ''.join(format_pieces).format(**comment_data) | python | 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.
Args:
comment_data: dictionary with the linter data.
Returns:
a string with the formatted message.
"""
format_pieces = []
# Line and column information
if 'line' in comment_data:
format_pieces.append('line {line}')
if 'column' in comment_data:
if format_pieces:
format_pieces.append(', ')
format_pieces.append('col {column}')
if format_pieces:
format_pieces.append(': ')
# Severity and Id information
if 'severity' in comment_data:
format_pieces.append('{severity}: ')
if 'message_id' in comment_data:
format_pieces.append('[{message_id}]: ')
# The message
if 'message' in comment_data:
format_pieces.append('{message}')
return ''.join(format_pieces).format(**comment_data) | [
"def",
"format_comment",
"(",
"comment_data",
")",
":",
"format_pieces",
"=",
"[",
"]",
"# Line and column information",
"if",
"'line'",
"in",
"comment_data",
":",
"format_pieces",
".",
"append",
"(",
"'line {line}'",
")",
"if",
"'column'",
"in",
"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.
Args:
comment_data: dictionary with the linter data.
Returns:
a string with the formatted message. | [
"Formats",
"the",
"data",
"returned",
"by",
"the",
"linters",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/__init__.py#L112-L150 | train | 34,685 |
sk-/git-lint | gitlint/__init__.py | get_vcs_root | 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
repository. If no repository exisits then (None, None) is returned.
"""
for vcs in (git, hg):
repo_root = vcs.repository_root()
if repo_root:
return vcs, repo_root
return (None, None) | python | 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
repository. If no repository exisits then (None, None) is returned.
"""
for vcs in (git, hg):
repo_root = vcs.repository_root()
if repo_root:
return vcs, repo_root
return (None, None) | [
"def",
"get_vcs_root",
"(",
")",
":",
"for",
"vcs",
"in",
"(",
"git",
",",
"hg",
")",
":",
"repo_root",
"=",
"vcs",
".",
"repository_root",
"(",
")",
"if",
"repo_root",
":",
"return",
"vcs",
",",
"repo_root",
"return",
"(",
"None",
",",
"None",
")"
] | 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
repository. If no repository exisits then (None, None) is returned. | [
"Returns",
"the",
"vcs",
"module",
"and",
"the",
"root",
"of",
"the",
"repo",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/__init__.py#L153-L165 | train | 34,686 |
sk-/git-lint | gitlint/__init__.py | process_file | 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(
filename, extra_data, commit=commit)
result = linters.lint(filename, modified_lines, gitlint_config)
result = result[filename]
return filename, result | python | 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(
filename, extra_data, commit=commit)
result = linters.lint(filename, modified_lines, gitlint_config)
result = result[filename]
return filename, result | [
"def",
"process_file",
"(",
"vcs",
",",
"commit",
",",
"force",
",",
"gitlint_config",
",",
"file_data",
")",
":",
"filename",
",",
"extra_data",
"=",
"file_data",
"if",
"force",
":",
"modified_lines",
"=",
"None",
"else",
":",
"modified_lines",
"=",
"vcs",
... | Lint the file
Returns:
The results from the linter. | [
"Lint",
"the",
"file"
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/__init__.py#L168-L184 | train | 34,687 |
sk-/git-lint | gitlint/hg.py | last_commit | def last_commit():
"""Returns the SHA1 of the last commit."""
try:
root = subprocess.check_output(
['hg', 'parent', '--template={node}'],
stderr=subprocess.STDOUT).strip()
# Convert to unicode first
return root.decode('utf-8')
except subprocess.CalledProcessError:
return None | python | def last_commit():
"""Returns the SHA1 of the last commit."""
try:
root = subprocess.check_output(
['hg', 'parent', '--template={node}'],
stderr=subprocess.STDOUT).strip()
# Convert to unicode first
return root.decode('utf-8')
except subprocess.CalledProcessError:
return None | [
"def",
"last_commit",
"(",
")",
":",
"try",
":",
"root",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'hg'",
",",
"'parent'",
",",
"'--template={node}'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"strip",
"(",
")",
"# Convert ... | Returns the SHA1 of the last commit. | [
"Returns",
"the",
"SHA1",
"of",
"the",
"last",
"commit",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/hg.py#L33-L42 | train | 34,688 |
sk-/git-lint | gitlint/hg.py | modified_files | 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 will get the modified files in the
working copy.
Returns: a dictionary with the modified files as keys, and additional
information as value. In this case it adds the status returned by
hg status.
"""
assert os.path.isabs(root), "Root has to be absolute, got: %s" % root
command = ['hg', 'status']
if commit:
command.append('--change=%s' % commit)
# Convert to unicode and split
status_lines = subprocess.check_output(command).decode('utf-8').split(
os.linesep)
modes = ['M', 'A']
if not tracked_only:
modes.append(r'\?')
modes_str = '|'.join(modes)
modified_file_status = utils.filter_lines(
status_lines,
r'(?P<mode>%s) (?P<filename>.+)' % modes_str,
groups=('filename', 'mode'))
return dict((os.path.join(root, filename), mode)
for filename, mode in modified_file_status) | python | 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 will get the modified files in the
working copy.
Returns: a dictionary with the modified files as keys, and additional
information as value. In this case it adds the status returned by
hg status.
"""
assert os.path.isabs(root), "Root has to be absolute, got: %s" % root
command = ['hg', 'status']
if commit:
command.append('--change=%s' % commit)
# Convert to unicode and split
status_lines = subprocess.check_output(command).decode('utf-8').split(
os.linesep)
modes = ['M', 'A']
if not tracked_only:
modes.append(r'\?')
modes_str = '|'.join(modes)
modified_file_status = utils.filter_lines(
status_lines,
r'(?P<mode>%s) (?P<filename>.+)' % modes_str,
groups=('filename', 'mode'))
return dict((os.path.join(root, filename), mode)
for filename, mode in modified_file_status) | [
"def",
"modified_files",
"(",
"root",
",",
"tracked_only",
"=",
"False",
",",
"commit",
"=",
"None",
")",
":",
"assert",
"os",
".",
"path",
".",
"isabs",
"(",
"root",
")",
",",
"\"Root has to be absolute, got: %s\"",
"%",
"root",
"command",
"=",
"[",
"'hg'... | 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 will get the modified files in the
working copy.
Returns: a dictionary with the modified files as keys, and additional
information as value. In this case it adds the status returned by
hg status. | [
"Returns",
"a",
"list",
"of",
"files",
"that",
"has",
"been",
"modified",
"since",
"the",
"last",
"commit",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/hg.py#L45-L79 | train | 34,689 |
sk-/git-lint | scripts/custom_linters/ini_linter.py | lint | def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0
except ConfigParser.Error as error:
print('Error: %s' % error)
return 1
except:
print('Unexpected Error')
return 2 | python | def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0
except ConfigParser.Error as error:
print('Error: %s' % error)
return 1
except:
print('Unexpected Error')
return 2 | [
"def",
"lint",
"(",
"filename",
")",
":",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"try",
":",
"config",
".",
"read",
"(",
"filename",
")",
"return",
"0",
"except",
"ConfigParser",
".",
"Error",
"as",
"error",
":",
"print",
"(",
"'... | Lints an INI file, returning 0 in case of success. | [
"Lints",
"an",
"INI",
"file",
"returning",
"0",
"in",
"case",
"of",
"success",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/scripts/custom_linters/ini_linter.py#L23-L34 | train | 34,690 |
sk-/git-lint | gitlint/linters.py | missing_requirements_command | def missing_requirements_command(missing_programs, installation_string,
filename, unused_lines):
"""Pseudo-command to be used when requirements are missing."""
verb = 'is'
if len(missing_programs) > 1:
verb = 'are'
return {
filename: {
'skipped': [
'%s %s not installed. %s' % (', '.join(missing_programs), verb,
installation_string)
]
}
} | python | def missing_requirements_command(missing_programs, installation_string,
filename, unused_lines):
"""Pseudo-command to be used when requirements are missing."""
verb = 'is'
if len(missing_programs) > 1:
verb = 'are'
return {
filename: {
'skipped': [
'%s %s not installed. %s' % (', '.join(missing_programs), verb,
installation_string)
]
}
} | [
"def",
"missing_requirements_command",
"(",
"missing_programs",
",",
"installation_string",
",",
"filename",
",",
"unused_lines",
")",
":",
"verb",
"=",
"'is'",
"if",
"len",
"(",
"missing_programs",
")",
">",
"1",
":",
"verb",
"=",
"'are'",
"return",
"{",
"fil... | Pseudo-command to be used when requirements are missing. | [
"Pseudo",
"-",
"command",
"to",
"be",
"used",
"when",
"requirements",
"are",
"missing",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/linters.py#L41-L54 | train | 34,691 |
sk-/git-lint | gitlint/linters.py | lint_command | 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:
name: string: the name of the linter.
program: string: lint program.
arguments: list[string]: extra arguments for the program.
filter_regex: string: regular expression to filter lines.
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.
Returns: dict: a dict with the extracted info from the message.
"""
output = utils.get_output_from_cache(name, filename)
if output is None:
call_arguments = [program] + arguments + [filename]
try:
output = subprocess.check_output(
call_arguments, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as error:
output = error.output
except OSError:
return {
filename: {
'error': [('Could not execute "%s".%sMake sure all ' +
'required programs are installed') %
(' '.join(call_arguments), os.linesep)]
}
}
output = output.decode('utf-8')
utils.save_output_in_cache(name, filename, output)
output_lines = output.split(os.linesep)
if lines is None:
lines_regex = r'\d+'
else:
lines_regex = '|'.join(map(str, lines))
lines_regex = '(%s)' % lines_regex
groups = ('line', 'column', 'message', 'severity', 'message_id')
filtered_lines = utils.filter_lines(
output_lines,
filter_regex.format(lines=lines_regex, filename=re.escape(filename)),
groups=groups)
result = []
for data in filtered_lines:
comment = dict(p for p in zip(groups, data) if p[1] is not None)
if 'line' in comment:
comment['line'] = int(comment['line'])
if 'column' in comment:
comment['column'] = int(comment['column'])
if 'severity' in comment:
comment['severity'] = comment['severity'].title()
result.append(comment)
return {filename: {'comments': result}} | python | 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:
name: string: the name of the linter.
program: string: lint program.
arguments: list[string]: extra arguments for the program.
filter_regex: string: regular expression to filter lines.
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.
Returns: dict: a dict with the extracted info from the message.
"""
output = utils.get_output_from_cache(name, filename)
if output is None:
call_arguments = [program] + arguments + [filename]
try:
output = subprocess.check_output(
call_arguments, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as error:
output = error.output
except OSError:
return {
filename: {
'error': [('Could not execute "%s".%sMake sure all ' +
'required programs are installed') %
(' '.join(call_arguments), os.linesep)]
}
}
output = output.decode('utf-8')
utils.save_output_in_cache(name, filename, output)
output_lines = output.split(os.linesep)
if lines is None:
lines_regex = r'\d+'
else:
lines_regex = '|'.join(map(str, lines))
lines_regex = '(%s)' % lines_regex
groups = ('line', 'column', 'message', 'severity', 'message_id')
filtered_lines = utils.filter_lines(
output_lines,
filter_regex.format(lines=lines_regex, filename=re.escape(filename)),
groups=groups)
result = []
for data in filtered_lines:
comment = dict(p for p in zip(groups, data) if p[1] is not None)
if 'line' in comment:
comment['line'] = int(comment['line'])
if 'column' in comment:
comment['column'] = int(comment['column'])
if 'severity' in comment:
comment['severity'] = comment['severity'].title()
result.append(comment)
return {filename: {'comments': result}} | [
"def",
"lint_command",
"(",
"name",
",",
"program",
",",
"arguments",
",",
"filter_regex",
",",
"filename",
",",
"lines",
")",
":",
"output",
"=",
"utils",
".",
"get_output_from_cache",
"(",
"name",
",",
"filename",
")",
"if",
"output",
"is",
"None",
":",
... | 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:
name: string: the name of the linter.
program: string: lint program.
arguments: list[string]: extra arguments for the program.
filter_regex: string: regular expression to filter lines.
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.
Returns: dict: a dict with the extracted info from the message. | [
"Executes",
"a",
"lint",
"program",
"and",
"filter",
"the",
"output",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/linters.py#L58-L121 | train | 34,692 |
sk-/git-lint | gitlint/linters.py | _replace_variables | def _replace_variables(data, variables):
"""Replace the format variables in all items of data."""
formatter = string.Formatter()
return [formatter.vformat(item, [], variables) for item in data] | python | def _replace_variables(data, variables):
"""Replace the format variables in all items of data."""
formatter = string.Formatter()
return [formatter.vformat(item, [], variables) for item in data] | [
"def",
"_replace_variables",
"(",
"data",
",",
"variables",
")",
":",
"formatter",
"=",
"string",
".",
"Formatter",
"(",
")",
"return",
"[",
"formatter",
".",
"vformat",
"(",
"item",
",",
"[",
"]",
",",
"variables",
")",
"for",
"item",
"in",
"data",
"]... | Replace the format variables in all items of data. | [
"Replace",
"the",
"format",
"variables",
"in",
"all",
"items",
"of",
"data",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/linters.py#L124-L127 | train | 34,693 |
sk-/git-lint | gitlint/linters.py | lint | 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
function.
Returns: dict: if there were errors running the command then the field
'error' will have the reasons in a list. if the lint process was skipped,
then a field 'skipped' will be set with the reasons. Otherwise, the field
'comments' will have the messages.
"""
_, ext = os.path.splitext(filename)
if ext in config:
output = collections.defaultdict(list)
for linter in config[ext]:
linter_output = linter(filename, lines)
for category, values in linter_output[filename].items():
output[category].extend(values)
if 'comments' in output:
output['comments'] = sorted(
output['comments'],
key=lambda x: (x.get('line', -1), x.get('column', -1)))
return {filename: dict(output)}
else:
return {
filename: {
'skipped': [
'no linter is defined or enabled for files'
' with extension "%s"' % ext
]
}
} | python | 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
function.
Returns: dict: if there were errors running the command then the field
'error' will have the reasons in a list. if the lint process was skipped,
then a field 'skipped' will be set with the reasons. Otherwise, the field
'comments' will have the messages.
"""
_, ext = os.path.splitext(filename)
if ext in config:
output = collections.defaultdict(list)
for linter in config[ext]:
linter_output = linter(filename, lines)
for category, values in linter_output[filename].items():
output[category].extend(values)
if 'comments' in output:
output['comments'] = sorted(
output['comments'],
key=lambda x: (x.get('line', -1), x.get('column', -1)))
return {filename: dict(output)}
else:
return {
filename: {
'skipped': [
'no linter is defined or enabled for files'
' with extension "%s"' % ext
]
}
} | [
"def",
"lint",
"(",
"filename",
",",
"lines",
",",
"config",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"in",
"config",
":",
"output",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
... | 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
function.
Returns: dict: if there were errors running the command then the field
'error' will have the reasons in a list. if the lint process was skipped,
then a field 'skipped' will be set with the reasons. Otherwise, the field
'comments' will have the messages. | [
"Lints",
"a",
"file",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/linters.py#L160-L197 | train | 34,694 |
sk-/git-lint | gitlint/utils.py | filter_lines | 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_regex)
for line in lines:
match = pattern.search(line)
if match:
if groups is None:
yield line
elif len(groups) == 1:
yield match.group(groups[0])
else:
matched_groups = match.groupdict()
yield tuple(matched_groups.get(group) for group in groups) | python | 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_regex)
for line in lines:
match = pattern.search(line)
if match:
if groups is None:
yield line
elif len(groups) == 1:
yield match.group(groups[0])
else:
matched_groups = match.groupdict()
yield tuple(matched_groups.get(group) for group in groups) | [
"def",
"filter_lines",
"(",
"lines",
",",
"filter_regex",
",",
"groups",
"=",
"None",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"filter_regex",
")",
"for",
"line",
"in",
"lines",
":",
"match",
"=",
"pattern",
".",
"search",
"(",
"line",
")",... | 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. | [
"Filters",
"out",
"the",
"lines",
"not",
"matching",
"the",
"pattern",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L24-L43 | train | 34,695 |
sk-/git-lint | gitlint/utils.py | which | 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]
candidates = []
locations = os.environ.get("PATH").split(os.pathsep)
for location in locations:
candidate = os.path.join(location, program)
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
candidates.append(candidate)
return candidates | python | 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]
candidates = []
locations = os.environ.get("PATH").split(os.pathsep)
for location in locations:
candidate = os.path.join(location, program)
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
candidates.append(candidate)
return candidates | [
"def",
"which",
"(",
"program",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"isabs",
"(",
"program",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"program",
")",
"and",
"os",
".",
"access",
"(",
"program",
",",
"os",
".",
"X_OK",
")",
")... | Returns a list of paths where the program is found. | [
"Returns",
"a",
"list",
"of",
"paths",
"where",
"the",
"program",
"is",
"found",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L47-L59 | train | 34,696 |
sk-/git-lint | gitlint/utils.py | _open_for_write | def _open_for_write(filename):
"""Opens filename for writing, creating the directories if needed."""
dirname = os.path.dirname(filename)
pathlib.Path(dirname).mkdir(parents=True, exist_ok=True)
return io.open(filename, 'w') | python | def _open_for_write(filename):
"""Opens filename for writing, creating the directories if needed."""
dirname = os.path.dirname(filename)
pathlib.Path(dirname).mkdir(parents=True, exist_ok=True)
return io.open(filename, 'w') | [
"def",
"_open_for_write",
"(",
"filename",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"pathlib",
".",
"Path",
"(",
"dirname",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"... | Opens filename for writing, creating the directories if needed. | [
"Opens",
"filename",
"for",
"writing",
"creating",
"the",
"directories",
"if",
"needed",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L67-L72 | train | 34,697 |
sk-/git-lint | gitlint/utils.py | _get_cache_filename | 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('~')
base_cache_dir = os.path.join(home_folder, '.git-lint', 'cache')
return os.path.join(base_cache_dir, name, filename) | python | 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('~')
base_cache_dir = os.path.join(home_folder, '.git-lint', 'cache')
return os.path.join(base_cache_dir, name, filename) | [
"def",
"_get_cache_filename",
"(",
"name",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"[",
"1",
":",
"]",
"home_folder",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"base_cache_d... | Returns the cache location for filename and linter name. | [
"Returns",
"the",
"cache",
"location",
"for",
"filename",
"and",
"linter",
"name",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L75-L81 | train | 34,698 |
sk-/git-lint | gitlint/utils.py | get_output_from_cache | 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 filename for which we are retrieving the
output.
Returns: a string with the output, if it is still valid, or None otherwise.
"""
cache_filename = _get_cache_filename(name, filename)
if (os.path.exists(cache_filename)
and os.path.getmtime(filename) < os.path.getmtime(cache_filename)):
with io.open(cache_filename) as f:
return f.read()
return None | python | 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 filename for which we are retrieving the
output.
Returns: a string with the output, if it is still valid, or None otherwise.
"""
cache_filename = _get_cache_filename(name, filename)
if (os.path.exists(cache_filename)
and os.path.getmtime(filename) < os.path.getmtime(cache_filename)):
with io.open(cache_filename) as f:
return f.read()
return None | [
"def",
"get_output_from_cache",
"(",
"name",
",",
"filename",
")",
":",
"cache_filename",
"=",
"_get_cache_filename",
"(",
"name",
",",
"filename",
")",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"cache_filename",
")",
"and",
"os",
".",
"path",
".",... | 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 filename for which we are retrieving the
output.
Returns: a string with the output, if it is still valid, or None otherwise. | [
"Returns",
"the",
"output",
"from",
"the",
"cache",
"if",
"still",
"valid",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L84-L103 | train | 34,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.