uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45980c732eceef3fdd923443 | train | function | @app.route('/season_sos', methods=['GET', 'POST'])
def season_sos():
season_values = get_season_sos()
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_sos.html', league_id=... | @app.route('/season_sos', methods=['GET', 'POST'])
def season_sos():
| season_values = get_season_sos()
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_sos.html', league_id=league_id, current_week=season_values[1],
... | private_league=True)
return render_template('season_analysis.html', league_id=league_id, current_week=season_values[1],
weeks=season_values[2], analysis=season_values[3][1])
@app.route('/season_sos', methods=['GET', 'POST'])
def season_sos():
| 64 | 64 | 100 | 19 | 45 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | season_sos | season_sos | 118 | 125 | 118 | 119 | 6e1edef57a8a93873634f218dac6929f1675bafc | bigcode/the-stack | train |
080a1454ea4dbff9478c991f | train | function | @app.route('/season_rankings')
def season_rankings():
season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_rankings.html', league_id=leagu... | @app.route('/season_rankings')
def season_rankings():
| season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_rankings.html', league_id=league_id, rankings=season_values[3][0])
| ', league_id=league_id, private_league=True)
return render_template('weekly_analysis.html', league_id=league_id, current_week=weekly_values[1],
weeks=weekly_values[2], analysis=weekly_values[3][1])
@app.route('/season_rankings')
def season_rankings():
| 64 | 64 | 84 | 12 | 52 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | season_rankings | season_rankings | 89 | 95 | 89 | 90 | 16213c857dd2e3acf7722acc59ed22bef768b9e5 | bigcode/the-stack | train |
74f065c1fdc0952a935b7bc8 | train | function | def create_teams_matrix(is_season_data, categories, table_rows, league_id):
app.logger.info('%s - Creating teams matrix', league_id)
# Creates a 2-D matrix which resembles the Weekly Scoreboard or Season Stats table.
teams = []
for row in range(len(table_rows)):
# Get rid of extra <td>
i... | def create_teams_matrix(is_season_data, categories, table_rows, league_id):
| app.logger.info('%s - Creating teams matrix', league_id)
# Creates a 2-D matrix which resembles the Weekly Scoreboard or Season Stats table.
teams = []
for row in range(len(table_rows)):
# Get rid of extra <td>
if is_season_data:
columns = table_rows[row].findAll('td')
... | find_all('th')
categories = [c.string for c in categories if c.string is not None]
table_rows = table_body.findAll('tr', {'class': rows_class})
return table_rows, categories
def create_teams_matrix(is_season_data, categories, table_rows, league_id):
| 64 | 64 | 140 | 18 | 45 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | create_teams_matrix | create_teams_matrix | 275 | 287 | 275 | 275 | 609f68299dc3d9614b225933577ab6886264fb5f | bigcode/the-stack | train |
2e302631069c47073ccae286 | train | function | def calculate_score(team1, team2, categories, league_id):
wins = 0
losses = 0
ties = 0
won_margin = []
lost_margin = []
tied_margin = []
bad_categories = ['FGMI', 'FTMI', '3PMI', 'TO', 'EJ', 'FF', 'PF', 'TF', 'DQ']
bad_categories_idx = []
for bad_category in bad_categories:
... | def calculate_score(team1, team2, categories, league_id):
| wins = 0
losses = 0
ties = 0
won_margin = []
lost_margin = []
tied_margin = []
bad_categories = ['FGMI', 'FTMI', '3PMI', 'TO', 'EJ', 'FF', 'PF', 'TF', 'DQ']
bad_categories_idx = []
for bad_category in bad_categories:
try:
bad_categories_idx.append(categories.ind... | = {}
for val in team_dict:
if team_dict[val] in result:
result[team_dict[val]].append(val)
else:
result[team_dict[val]] = [val]
# Sort the dictionary by greatest standings score.
rankings = sorted(result.items(), key=itemgetter(0), reverse=True)
if not quiet:
... | 117 | 117 | 391 | 14 | 103 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | calculate_score | calculate_score | 351 | 397 | 351 | 351 | d5679ff221cd016a3e99bf0283275d604b2cac03 | bigcode/the-stack | train |
a540397875a6a64d773e6a87 | train | function | def get_week_matchups(teams):
matchup_dict = {}
for i in range(round(len(teams) / 2)):
team1 = teams[2*i][0]
team2 = teams[2*i+1][0]
matchup_dict[team1] = team2
matchup_dict[team2] = team1
return matchup_dict
| def get_week_matchups(teams):
| matchup_dict = {}
for i in range(round(len(teams) / 2)):
team1 = teams[2*i][0]
team2 = teams[2*i+1][0]
matchup_dict[team1] = team2
matchup_dict[team2] = team1
return matchup_dict
| _rank_sums[player] += ranks[player]
# if player doesn't have opponent rank values, store to dict
else:
player_rank_sums[player] = ranks[player]
return
# since scoreboard info is written in pairs, weekly matchups should be adjacent
def get_week_matchups(teams):
| 64 | 64 | 78 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_week_matchups | get_week_matchups | 543 | 550 | 543 | 543 | 476f9fd4965d5ceb71676b84edcedacc9e1428ca | bigcode/the-stack | train |
9b6f8ba88d509e879e559d2d | train | function | def get_scoreboards(league_id):
params = (('view', ['mScoreboard', 'mMatchupScore']),)
data = call_api(f'http://fantasy.espn.com/apis/v3/games/fba/seasons/{app.config.get("SEASON")}/segments/0/leagues/{league_id}',
params=params)
data = data['schedule']
return data
| def get_scoreboards(league_id):
| params = (('view', ['mScoreboard', 'mMatchupScore']),)
data = call_api(f'http://fantasy.espn.com/apis/v3/games/fba/seasons/{app.config.get("SEASON")}/segments/0/leagues/{league_id}',
params=params)
data = data['schedule']
return data
| )
team2 = format_team(matchup['home'], team_dict)
scoreboard.append(team1)
scoreboard.append(team2)
return scoreboard
# ESPN scoreboard api call, mMatchupScore param is necessary to get the important 'matchupPeriodId' key
def get_scoreboards(league_id):
| 64 | 64 | 84 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_scoreboards | get_scoreboards | 628 | 633 | 628 | 628 | 637a8b6c56de1cf231383fc582dac305dfe6cba3 | bigcode/the-stack | train |
db94358f02ef11f7ca8469e2 | train | function | def call_api(url, params=None):
try:
if params is None:
r = requests.get(url)
else:
r = requests.get(url, params=params)
except requests.exceptions.RequestException as ex:
app.logger.error('Could not make ESPN API call.', ex)
abort(500)
sys.exit('C... | def call_api(url, params=None):
| try:
if params is None:
r = requests.get(url)
else:
r = requests.get(url, params=params)
except requests.exceptions.RequestException as ex:
app.logger.error('Could not make ESPN API call.', ex)
abort(500)
sys.exit('Could not make ESPN API call.')
... | team_dict[team['location'] + ' ' + team['nickname']] = team['id']
team_dict[team['id']] = team['location'] + ' ' + team['nickname']
return team_dict
# call espn api allowing for params
def call_api(url, params=None):
| 64 | 64 | 86 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | call_api | call_api | 565 | 576 | 565 | 565 | d4708a3ae1ba701b0b5333f73f00a77ecbd67748 | bigcode/the-stack | train |
950e282688c4fc55ab67ebba | train | function | def reg_season_check(matchup):
reg_season = True
try:
if matchup['playoffTierType'] != 'NONE':
reg_season = False
except KeyError:
pass
return reg_season
| def reg_season_check(matchup):
| reg_season = True
try:
if matchup['playoffTierType'] != 'NONE':
reg_season = False
except KeyError:
pass
return reg_season
| ] = avg_rank
# update current rank
current_rank += num_teams
return ranks
# check if a week is a regular season week using playoffTierType key
# I don't think that key exists earlier in the season so key error returns true
def reg_season_check(matchup):
| 64 | 64 | 52 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | reg_season_check | reg_season_check | 424 | 431 | 424 | 424 | 568a2b4b21f677f3cf6bf7fee173e5a08f154e9e | bigcode/the-stack | train |
0692ce41e6987ca613fdb895 | train | function | def endpoints_setup(is_season_data):
league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
week = get_current_week(league_id)
if is_season_data:
url = 'https://fantasy.espn.com/basketball/league/standings?leagueId={}'.format(league_id)
else:
url = ... | def endpoints_setup(is_season_data):
| league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
week = get_current_week(league_id)
if is_season_data:
url = 'https://fantasy.espn.com/basketball/league/standings?leagueId={}'.format(league_id)
else:
url = 'https://fantasy.espn.com/basketball/... | _values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('overall_perf.html', league_id=league_id, current_week=season_values[1],
rankings=season_values[2])
def endpoints_setup(is_season_data):
| 66 | 66 | 222 | 8 | 58 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | endpoints_setup | endpoints_setup | 138 | 155 | 138 | 138 | 584de5e45ba1ba45b1d2a3c51c5007c6c3e86957 | bigcode/the-stack | train |
736117ed92377ecc3ac6ec8c | train | function | def get_overall_perf():
league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
current_week = get_current_week(league_id)
categories = ['FG%', 'FT%', '3PM', 'REB', 'AST', 'STL', 'BLK', 'TO', 'PTS']
data = get_scoreboards(league_id)
# get max regular season wee... | def get_overall_perf():
| league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
current_week = get_current_week(league_id)
categories = ['FG%', 'FT%', '3PM', 'REB', 'AST', 'STL', 'BLK', 'TO', 'PTS']
data = get_scoreboards(league_id)
# get max regular season week
max_reg_season = 0... | ums(player_opp_rank_sums, team_names, matchups, ranks)
# get weekly average
avg_opp_rank = {player: (round(sum_ranks / float(max_reg_season), 2)) for (player, sum_ranks) in player_opp_rank_sums.items()}
# convert into rankings to output in html
sos_rankings = build_rankings(avg_opp_rank)
return [lea... | 117 | 117 | 391 | 6 | 110 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_overall_perf | get_overall_perf | 474 | 506 | 474 | 474 | 434aca93390e04e09252c50e3713072b5194a84a | bigcode/the-stack | train |
245c8fae3a2dccf3ec7c31fd | train | function | def compute_stats(teams, categories, league_id, quiet):
if not quiet:
app.logger.info('%s - Starting to compute stats', league_id)
# Initialize the dictionary which will hold information about each team along with their "standings score".
team_dict = {}
for team in teams:
team_dict[team[... | def compute_stats(teams, categories, league_id, quiet):
| if not quiet:
app.logger.info('%s - Starting to compute stats', league_id)
# Initialize the dictionary which will hold information about each team along with their "standings score".
team_dict = {}
for team in teams:
team_dict[team[0]] = 0
matchups = []
for team1 in teams:
... | .find_all('table', class_=table_body_class)[0]
team_names = table_body.find_all('span', class_='teamName truncate')
else:
team_names = soup.find_all('div',
{'class': 'ScoreCell__TeamName ScoreCell__TeamName--shortDisplayName truncate db'})
team_names = [t.stri... | 130 | 130 | 434 | 13 | 117 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | compute_stats | compute_stats | 307 | 347 | 307 | 307 | b57bf8935e96e2bb9898dfd9d997ebe73be680f2 | bigcode/the-stack | train |
9f5cc425aaabb07f3b9333ee | train | function | def get_current_week(league_id):
# First get it from the dropdown
week = request.form.get('week_selection')
if week is None:
data = call_espn_api(league_id)
if 'status' not in data:
app.logger.error('League %s is a private league.', str(league_id))
week = 'private'
... | def get_current_week(league_id):
# First get it from the dropdown
| week = request.form.get('week_selection')
if week is None:
data = call_espn_api(league_id)
if 'status' not in data:
app.logger.error('League %s is a private league.', str(league_id))
week = 'private'
else:
week = data['status']['currentMatchupPeriod']
... | , or stats list empty.', str(league_id))
abort(500)
sys.exit('Teams, categories, or stats list empty.')
endpoints_params = league_id, week, weeks, stats
return endpoints_params
def get_current_week(league_id):
# First get it from the dropdown
| 64 | 64 | 115 | 17 | 46 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_current_week | get_current_week | 158 | 169 | 158 | 159 | f0d3e500db356d767be2c87f1c5cd8e0a4661bf4 | bigcode/the-stack | train |
c1c3e90449696eafbae75ceb | train | function | def key_check(stats, key):
try:
return stats[key]['score']
except KeyError:
pass
return 0
| def key_check(stats, key):
| try:
return stats[key]['score']
except KeyError:
pass
return 0
| .exceptions.RequestException as ex:
app.logger.error('Could not make ESPN API call.', ex)
abort(500)
sys.exit('Could not make ESPN API call.')
data = r.json()
return data
# check if val exists, otherwise return 0
def key_check(stats, key):
| 64 | 64 | 30 | 7 | 56 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | key_check | key_check | 580 | 585 | 580 | 580 | da1577eafb684d42281381ad6bbceebddfe81826 | bigcode/the-stack | train |
acf11495530f8c18e103a890 | train | function | def call_espn_api(league_id):
app.logger.info('%s - Calling ESPN API', league_id)
url = ("https://fantasy.espn.com/apis/v3/games/fba/seasons/{}/segments/0/leagues/{}?view=mMatchupScore&view"
"mScoreboard&view=mSettings&view=mTeam&view=modular&view=mNav").format(app.config.get("SEASON"), league_id)
... | def call_espn_api(league_id):
| app.logger.info('%s - Calling ESPN API', league_id)
url = ("https://fantasy.espn.com/apis/v3/games/fba/seasons/{}/segments/0/leagues/{}?view=mMatchupScore&view"
"mScoreboard&view=mSettings&view=mTeam&view=modular&view=mNav").format(app.config.get("SEASON"), league_id)
try:
r = requests.ge... | s is a private league.', str(league_id))
week = 'private'
else:
week = data['status']['currentMatchupPeriod']
app.logger.info('%s - Week requested: %s', league_id, week)
return week
def call_espn_api(league_id):
| 64 | 64 | 161 | 10 | 53 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | call_espn_api | call_espn_api | 172 | 183 | 172 | 172 | 332f1d4fd1a5908a1ef4c837c1c360be211bdf20 | bigcode/the-stack | train |
1c19eeeb6bfd89ca3a235d8a | train | function | def run_selenium(url, is_season_data, league_id):
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('no-sandbox')
options.add_argument('disable-dev-shm-usage')
capa = DesiredCapabilities.CHROME
capa["pageLoadStrategy"] = "none"
# chromedriver_loc = 'ch... | def run_selenium(url, is_season_data, league_id):
| options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('no-sandbox')
options.add_argument('disable-dev-shm-usage')
capa = DesiredCapabilities.CHROME
capa["pageLoadStrategy"] = "none"
# chromedriver_loc = 'chromedriver.exe'
# driver = webdriver.Chrome(ch... | Could not create teams matrix')
try:
append_team_names(soup, is_season_data, teams, league_id)
app.logger.info('%s - Successfully appended team names', league_id)
except Exception as ex:
app.logger.error('%s - Could not append team names', league_id, ex)
abort(500)
sys.ex... | 102 | 102 | 341 | 14 | 87 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | run_selenium | run_selenium | 225 | 255 | 225 | 225 | 8c6bf15c367230daf1b1a85a46d3a2eee5d17fff | bigcode/the-stack | train |
3049b0ce4954043f641cdebd | train | function | @app.route('/weekly_rankings', methods=['GET', 'POST'])
def weekly_rankings():
weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_ranki... | @app.route('/weekly_rankings', methods=['GET', 'POST'])
def weekly_rankings():
| weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_rankings.html', league_id=league_id, current_week=weekly_values[1],
... | %s is a private league.', str(league_id))
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('tools.html', league_id=league_id)
@app.route('/weekly_rankings', methods=['GET', 'POST'])
def weekly_rankings():
| 64 | 64 | 107 | 19 | 45 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | weekly_rankings | weekly_rankings | 59 | 66 | 59 | 60 | 80c7c3940c05ac12807efb6fbdcc9464f935b371 | bigcode/the-stack | train |
b48992c57520418774ebf810 | train | function | @app.route('/weekly_analysis', methods=['GET', 'POST'])
def weekly_analysis():
weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_analy... | @app.route('/weekly_analysis', methods=['GET', 'POST'])
def weekly_analysis():
| weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_analysis.html', league_id=league_id, current_week=weekly_values[1],
... | private_league=True)
return render_template('weekly_matchups.html', league_id=league_id, current_week=weekly_values[1],
weeks=weekly_values[2], matchups=weekly_values[3][1])
@app.route('/weekly_analysis', methods=['GET', 'POST'])
def weekly_analysis():
| 64 | 64 | 104 | 17 | 47 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | weekly_analysis | weekly_analysis | 79 | 86 | 79 | 80 | 58143edb0530fec3bc1936eddb1245a4469fa74a | bigcode/the-stack | train |
fb6aee53ac780cd1a47edc3c | train | function | @app.route('/season_matchups', methods=['GET', 'POST'])
def season_matchups():
season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_matchu... | @app.route('/season_matchups', methods=['GET', 'POST'])
def season_matchups():
| season_values = endpoints_setup(True)
league_id = season_values[0]
if season_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_matchups.html', league_id=league_id, current_week=season_values[1],
... | ':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('season_rankings.html', league_id=league_id, rankings=season_values[3][0])
@app.route('/season_matchups', methods=['GET', 'POST'])
def season_matchups():
| 64 | 64 | 108 | 19 | 45 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | season_matchups | season_matchups | 98 | 105 | 98 | 99 | 4b52334eedb6eedb2248b85386118371ffa1cd40 | bigcode/the-stack | train |
f127b4eb0abb2fa14567d064 | train | function | def get_week_scoreboard(league_id, week, data):
team_dict = get_team_dict(league_id)
matchups = [matchup for matchup in data if matchup['matchupPeriodId'] == week or matchup['matchupPeriodId'] == int(week)]
scoreboard = []
for matchup in matchups:
team1 = format_team(matchup['away'], team_dict)
... | def get_week_scoreboard(league_id, week, data):
| team_dict = get_team_dict(league_id)
matchups = [matchup for matchup in data if matchup['matchupPeriodId'] == week or matchup['matchupPeriodId'] == int(week)]
scoreboard = []
for matchup in matchups:
team1 = format_team(matchup['away'], team_dict)
team2 = format_team(matchup['home'], tea... | _check(scores, '1'))
# TO
team.append(key_check(scores, '11'))
# PTS
team.append(key_check(scores, '0'))
return team
# filter all scoreboards for current week scoreboard and format
def get_week_scoreboard(league_id, week, data):
| 64 | 64 | 113 | 13 | 50 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_week_scoreboard | get_week_scoreboard | 615 | 624 | 615 | 615 | 82dfde4270337c74c3fd6b1a4376618f365157f6 | bigcode/the-stack | train |
caad2e958e7f4000377cfa9e | train | function | def get_season_sos():
league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
current_week = get_current_week(league_id)
categories = ['FG%', 'FT%', '3PM', 'REB', 'AST', 'STL', 'BLK', 'TO', 'PTS']
# get all scoreboard data from ESPN api
data = get_scoreboards(le... | def get_season_sos():
| league_id = request.args.get('leagueId')
app.logger.info('League ID: %s', str(league_id))
current_week = get_current_week(league_id)
categories = ['FG%', 'FT%', '3PM', 'REB', 'AST', 'STL', 'BLK', 'TO', 'PTS']
# get all scoreboard data from ESPN api
data = get_scoreboards(league_id)
# get ma... | in row[1]:
ranks[player] = avg_rank
# update current rank
current_rank += num_teams
return ranks
# check if a week is a regular season week using playoffTierType key
# I don't think that key exists earlier in the season so key error returns true
def reg_season_check(matchup):
... | 133 | 133 | 445 | 7 | 125 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_season_sos | get_season_sos | 435 | 470 | 435 | 435 | 8cb100a8fffd0e7f4145b1b8871e6f70ec034663 | bigcode/the-stack | train |
ed058006d9e35d23e85fcfa1 | train | function | def get_team_dict(league_id):
url = f'https://fantasy.espn.com/apis/v3/games/fba/seasons/{app.config.get("SEASON")}/segments/0/leagues/{league_id}'
data = call_api(url)
team_dict = {}
for team in data['teams']:
team_dict[team['location'] + ' ' + team['nickname']] = team['id']
team_dict[t... | def get_team_dict(league_id):
| url = f'https://fantasy.espn.com/apis/v3/games/fba/seasons/{app.config.get("SEASON")}/segments/0/leagues/{league_id}'
data = call_api(url)
team_dict = {}
for team in data['teams']:
team_dict[team['location'] + ' ' + team['nickname']] = team['id']
team_dict[team['id']] = team['location'] ... | *i][0]
team2 = teams[2*i+1][0]
matchup_dict[team1] = team2
matchup_dict[team2] = team1
return matchup_dict
# create two way dictionary of team id and team name
def get_team_dict(league_id):
| 64 | 64 | 114 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_team_dict | get_team_dict | 554 | 561 | 554 | 554 | 1c0bbeba2a09f0a29932a61df35cb24dae9ad4e4 | bigcode/the-stack | train |
d6f8ec3475b2d5c87fba1d59 | train | function | def build_rankings(avg_ranks):
sorted_avg_rank = sorted(avg_ranks.items(), key=lambda kv:[kv[1], kv[0]], reverse=False)
rankings = []
rank = 1
for team in sorted_avg_rank:
rankings.append([rank, team[0], team[1]])
rank += 1
return rankings
| def build_rankings(avg_ranks):
| sorted_avg_rank = sorted(avg_ranks.items(), key=lambda kv:[kv[1], kv[0]], reverse=False)
rankings = []
rank = 1
for team in sorted_avg_rank:
rankings.append([rank, team[0], team[1]])
rank += 1
return rankings
| .items()}
# convert into rankings to output in html
perf_rankings = build_rankings(avg_player_rank)
return [league_id, current_week, perf_rankings]
# convert dictionary with average player ranks to table with general rank, team, and avg rank
def build_rankings(avg_ranks):
| 64 | 64 | 76 | 8 | 55 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | build_rankings | build_rankings | 510 | 517 | 510 | 510 | be521092320011085db12804e50c0bc1325a945f | bigcode/the-stack | train |
575b7c97fb5ce3fc9f109ce4 | train | function | def get_ranks(raw_rank):
ranks = {}
current_rank = 1
for row in raw_rank:
num_teams = len(row[1])
# if no ties, rank will be current_rank
if num_teams == 1:
ranks[row[1][0]] = current_rank
# if ties need to find average rank
else:
# list of ran... | def get_ranks(raw_rank):
| ranks = {}
current_rank = 1
for row in raw_rank:
num_teams = len(row[1])
# if no ties, rank will be current_rank
if num_teams == 1:
ranks[row[1][0]] = current_rank
# if ties need to find average rank
else:
# list of ranks that the tied players ... | lost_margin.append((categories[idx], round((a - b), 4)))
score = (wins, losses, ties), won_margin, lost_margin, tied_margin
return score
# calculate player ranks for a week and return as dictionary
# uses average rank
def get_ranks(raw_rank):
| 64 | 64 | 156 | 7 | 56 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | get_ranks | get_ranks | 402 | 419 | 402 | 402 | 30df1bcf853faf701f0891d11927b003ef39b3bd | bigcode/the-stack | train |
4d977d19686d8b1bd6afa180 | train | function | @app.route('/weekly_matchups', methods=['GET', 'POST'])
def weekly_matchups():
weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_match... | @app.route('/weekly_matchups', methods=['GET', 'POST'])
def weekly_matchups():
| weekly_values = endpoints_setup(False)
league_id = weekly_values[0]
if weekly_values[1] == 'private':
return render_template('index.html', league_id=league_id, private_league=True)
return render_template('weekly_matchups.html', league_id=league_id, current_week=weekly_values[1],
... | _league=True)
return render_template('weekly_rankings.html', league_id=league_id, current_week=weekly_values[1],
weeks=weekly_values[2], rankings=weekly_values[3][0])
@app.route('/weekly_matchups', methods=['GET', 'POST'])
def weekly_matchups():
| 64 | 64 | 108 | 19 | 45 | wcrasta/ESPN-Fantasy-Basketball | app.py | Python | weekly_matchups | weekly_matchups | 69 | 76 | 69 | 70 | cd9a73006a79887373adc803dc3c7de7231fc193 | bigcode/the-stack | train |
faef061e190260ce7f84f1ad | train | function | @check_args_type
def set_margins(
left: float = 0.13, bottom: float = 0.13, right: float = 0.96, top: float = 0.96
) -> None:
"""
adjust margins - Setting margins for graphs
Args:
left (float, optional): Description
bottom (float, optional): Description
right (float, optional): ... | @check_args_type
def set_margins(
left: float = 0.13, bottom: float = 0.13, right: float = 0.96, top: float = 0.96
) -> None:
| """
adjust margins - Setting margins for graphs
Args:
left (float, optional): Description
bottom (float, optional): Description
right (float, optional): Description
top (float, optional): Description
"""
fig = plt.gcf()
fig.subplots_adjust(bottom=bottom, top=top,... | return func(*args, **kwargs)
return wrapper
@check_args_type
def set_margins(
left: float = 0.13, bottom: float = 0.13, right: float = 0.96, top: float = 0.96
) -> None:
| 64 | 64 | 131 | 52 | 11 | jataware/flee | flee/postprocessing/FormatPyplotFigures.py | Python | set_margins | set_margins | 19 | 33 | 19 | 22 | 61b5d16118eab3c5d74fa5ebd3c27ef3c45e162a | bigcode/the-stack | train |
867b2ff7dcc9a2849cb6e2c1 | train | function | @check_args_type
def prepare_figure(
xlabel: str = "Days elapsed", ylabel: str = "Number of refugees"
) -> "matplotlib.figure.Figure":
"""
prepares and formats a basic flee visualization figure.
Args:
xlabel (str, optional): Description
ylabel (str, optional): Description
Returns:
... | @check_args_type
def prepare_figure(
xlabel: str = "Days elapsed", ylabel: str = "Number of refugees"
) -> "matplotlib.figure.Figure":
| """
prepares and formats a basic flee visualization figure.
Args:
xlabel (str, optional): Description
ylabel (str, optional): Description
Returns:
matplotlib.figure.Figure: Description
"""
plt.clf()
plt.xlabel(xlabel)
plt.ylabel(ylabel)
matplotlib.rcParams.... | fig = plt.gcf()
fig.subplots_adjust(bottom=bottom, top=top, left=left, right=right)
@check_args_type
def prepare_figure(
xlabel: str = "Days elapsed", ylabel: str = "Number of refugees"
) -> "matplotlib.figure.Figure":
| 64 | 64 | 141 | 37 | 27 | jataware/flee | flee/postprocessing/FormatPyplotFigures.py | Python | prepare_figure | prepare_figure | 36 | 58 | 36 | 39 | 9f7f9ce4e1dd9c1e85375df7824643ed689d9cce | bigcode/the-stack | train |
e9138a2c49c09f13e5b105ba | train | function | def lambda_handler(event, context):
stack_name = os.environ["stackname"]
# Logic to handle Stack delete
if event["RequestType"] == 'Delete':
try:
# List All connectors with the stackName as the prefix and get the ARN of the connector
response = connect.list_... | def lambda_handler(event, context):
| stack_name = os.environ["stackname"]
# Logic to handle Stack delete
if event["RequestType"] == 'Delete':
try:
# List All connectors with the stackName as the prefix and get the ARN of the connector
response = connect.list_connectors(connectorNamePrefix=stack_name)
... | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import boto3
import datetime
import json
import os
import random
from time import sleep
from datetime import datetime
import cfnresponse
import logging
msk = boto3.client("kafka")
kda = boto3.client('kinesisanalytic... | 101 | 256 | 1,917 | 8 | 93 | aws-samples/realtime-fraud-prevention | lambda-functions/LambdaConfig.py | Python | lambda_handler | lambda_handler | 19 | 281 | 19 | 21 | 28e83b94d762cbd5d6f76b852d32c0d7662a4cdd | bigcode/the-stack | train |
d1553cff964ddfea7be85f88 | train | class | class Filter(object):
def __init__(self):
pass
def search_key(self,input_string,word):
index=input_string.find(word)
if(index!=-1):
if(index!=0):
low=ord(input_string[index-1])
else:
low=95
if(index+len(word)!=len(input_string)):
high=ord(input_string[index+len(word)])
else:
... | class Filter(object):
| def __init__(self):
pass
def search_key(self,input_string,word):
index=input_string.find(word)
if(index!=-1):
if(index!=0):
low=ord(input_string[index-1])
else:
low=95
if(index+len(word)!=len(input_string)):
high=ord(input_string[index+len(word)])
else:
high=95
if( (low... | import requests
import os
from bs4 import BeautifulSoup
from scrape_with_bs4 import sc_reuters,sc_econt,sc_thehindu,moneyControl,ndtv,hindu_bl
from nltk.tokenize import sent_tokenize
# checks for the presence of a word in a string by checking character before
#the start of the word and after the end of the word
NEWS={... | 172 | 196 | 654 | 4 | 168 | ayush237/Business-news-scrapper | code/filter.py | Python | Filter | Filter | 18 | 96 | 18 | 18 | 15b4015089c201698357f37646e77fd43f548e1b | bigcode/the-stack | train |
4baad0e0d60b107956b5c76d | train | function | def get_policy(project_id):
"""Gets IAM policy for a project."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
... | def get_policy(project_id):
| """Gets IAM policy for a project."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcemanage... | Cloud IAM.
For more information, see the documentation at
https://cloud.google.com/iam/docs/granting-changing-revoking-access.
"""
import argparse
import os
from google.oauth2 import service_account
import googleapiclient.discovery
# [START iam_get_policy]
def get_policy(project_id):
| 64 | 64 | 105 | 6 | 58 | nilold/python-docs-samples | iam/api-client/access.py | Python | get_policy | get_policy | 29 | 40 | 29 | 29 | c824d48e04e8da612979e1a9bea7a4f482e866e2 | bigcode/the-stack | train |
20810501595c8e7319ec32c3 | train | function | def set_policy(project_id, policy):
"""Sets IAM policy for a project."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery... | def set_policy(project_id, policy):
| """Sets IAM policy for a project."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcemanage... | bindings'] if b['role'] == role)
if 'members' in binding and member in binding['members']:
binding['members'].remove(member)
print(binding)
return policy
# [END iam_modify_policy_remove_member]
# [START iam_set_policy]
def set_policy(project_id, policy):
| 64 | 64 | 114 | 8 | 56 | nilold/python-docs-samples | iam/api-client/access.py | Python | set_policy | set_policy | 81 | 95 | 81 | 81 | bf66daff4abf58fedccf49a9d82c184b59dcda1c | bigcode/the-stack | train |
f08a37b17aa65b44aebdb20d | train | function | def modify_policy_add_role(policy, role, member):
"""Adds a new role binding to a policy."""
binding = {
'role': role,
'members': [member]
}
policy['bindings'].append(binding)
print(policy)
return policy
| def modify_policy_add_role(policy, role, member):
| """Adds a new role binding to a policy."""
binding = {
'role': role,
'members': [member]
}
policy['bindings'].append(binding)
print(policy)
return policy
| binding = next(b for b in policy['bindings'] if b['role'] == role)
binding['members'].append(member)
print(binding)
return policy
# [END iam_modify_policy_add_member]
# [START iam_modify_policy_add_role]
def modify_policy_add_role(policy, role, member):
| 64 | 64 | 57 | 11 | 53 | nilold/python-docs-samples | iam/api-client/access.py | Python | modify_policy_add_role | modify_policy_add_role | 56 | 65 | 56 | 56 | ee49ee8ad593382b48275b357f381e011ef2315c | bigcode/the-stack | train |
0df034ebe0aabd0be161c7a6 | train | function | def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
subparsers = parser.add_subparsers(dest='command')
# Get
get_parser = subparsers.add_parser(
'get', help=get_policy.__doc__)
get_parser.add_argument('pro... | def main():
| parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
subparsers = parser.add_subparsers(dest='command')
# Get
get_parser = subparsers.add_parser(
'get', help=get_policy.__doc__)
get_parser.add_argument('project_id')
... | credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
permi... | 137 | 137 | 458 | 3 | 134 | nilold/python-docs-samples | iam/api-client/access.py | Python | main | main | 124 | 182 | 124 | 124 | ea37dec3dcd6d5ccb21f881d8bc0428c133b3d0c | bigcode/the-stack | train |
0bb4afa631afe706e604cc4c | train | function | def modify_policy_remove_member(policy, role, member):
"""Removes a member from a role binding."""
binding = next(b for b in policy['bindings'] if b['role'] == role)
if 'members' in binding and member in binding['members']:
binding['members'].remove(member)
print(binding)
return policy
| def modify_policy_remove_member(policy, role, member):
| """Removes a member from a role binding."""
binding = next(b for b in policy['bindings'] if b['role'] == role)
if 'members' in binding and member in binding['members']:
binding['members'].remove(member)
print(binding)
return policy
| binding = {
'role': role,
'members': [member]
}
policy['bindings'].append(binding)
print(policy)
return policy
# [END iam_modify_policy_add_role]
# [START iam_modify_policy_remove_member]
def modify_policy_remove_member(policy, role, member):
| 64 | 64 | 73 | 11 | 53 | nilold/python-docs-samples | iam/api-client/access.py | Python | modify_policy_remove_member | modify_policy_remove_member | 70 | 76 | 70 | 70 | 1e00cf1ba967d5082f7fd991ff658162c41e0405 | bigcode/the-stack | train |
10a8b9e960a2a628881e5a99 | train | function | def test_permissions(project_id):
"""Tests IAM permissions of the caller"""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discov... | def test_permissions(project_id):
| """Tests IAM permissions of the caller"""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
'cloudresourcem... | 'v1', credentials=credentials)
policy = service.projects().setIamPolicy(
resource=project_id, body={
'policy': policy
}).execute()
print(policy)
return policy
# [END iam_set_policy]
# [START iam_test_permissions]
def test_permissions(project_id):
| 64 | 64 | 143 | 6 | 58 | nilold/python-docs-samples | iam/api-client/access.py | Python | test_permissions | test_permissions | 100 | 120 | 100 | 100 | 16fdb299e418d3367e20c04c35b7eda266e92d5b | bigcode/the-stack | train |
557ba7371ae51dc3211523ac | train | function | def modify_policy_add_member(policy, role, member):
"""Adds a new member to a role binding."""
binding = next(b for b in policy['bindings'] if b['role'] == role)
binding['members'].append(member)
print(binding)
return policy
| def modify_policy_add_member(policy, role, member):
| """Adds a new member to a role binding."""
binding = next(b for b in policy['bindings'] if b['role'] == role)
binding['members'].append(member)
print(binding)
return policy
| 'v1', credentials=credentials)
policy = service.projects().getIamPolicy(
resource=project_id, body={}).execute()
print(policy)
return policy
# [END iam_get_policy]
# [START iam_modify_policy_add_member]
def modify_policy_add_member(policy, role, member):
| 64 | 64 | 58 | 11 | 53 | nilold/python-docs-samples | iam/api-client/access.py | Python | modify_policy_add_member | modify_policy_add_member | 45 | 51 | 45 | 45 | a637279655c0cac62fb2ebd4a201a851a98ce7a4 | bigcode/the-stack | train |
c26e7d388c13942f2556e070 | train | function | def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'pop_projection_flask.sqlite'),
)
if test_config is None:
# load the inst... | def create_app(test_config=None):
# create and configure the app
| app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'pop_projection_flask.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_p... | import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
| 23 | 71 | 237 | 15 | 7 | ateffal/pop-projection-flask | pop_projection_flask/__init__.py | Python | create_app | create_app | 6 | 48 | 6 | 7 | 231b4fe96559fbfeda332a7627b5bb4c92757375 | bigcode/the-stack | train |
c91661de7ed3c9a19f243a73 | train | function | def LA(args):
def fetch_flanking_seq(chrom, start, end, flanking_len, reference_genome, samtools):
pre_flanking_coor = "%s:%s-%s" % (chrom, int(start) - flanking_len, int(start)-1)
suf_flanking_coor = "%s:%s-%s" % (chrom, int(end) + 1, int(end) + flanking_len)
# print("## USE samtools ... | def LA(args):
| def fetch_flanking_seq(chrom, start, end, flanking_len, reference_genome, samtools):
pre_flanking_coor = "%s:%s-%s" % (chrom, int(start) - flanking_len, int(start)-1)
suf_flanking_coor = "%s:%s-%s" % (chrom, int(end) + 1, int(end) + flanking_len)
# print("## USE samtools to extract the flan... | _name][3]
count_lst = myBasicCount.func_extract_reads_in_bam(bam_file_path, chrom, start, end, pattern)
genotype, valid_alleles_num, total_cov, infos = myBasicCount.func_str_genotyper(count_lst)
## plot hist
# fig = myplot.func_save_plot(count_lst, str_nam... | 252 | 252 | 843 | 5 | 246 | Ming-Ni-Lab/NanoForenSTR | nanoforenstr.py | Python | LA | LA | 88 | 161 | 88 | 89 | 8108da45d6497c7dd150c3ffd6ee6de2881084f0 | bigcode/the-stack | train |
53232b7e980b442aa0da46de | train | function | def quick(args):
bam_file_path = args.BAM
pattern_file_path = args.PAT
sample = args.ID
## create dir
path1 = 'nanoforenstr_output/%s' % sample
path2 = 'nanoforenstr_output/%s/figs' % sample
pathlib.Path(path2).mkdir(parents=True, exist_ok=True)
## pattern file
... | def quick(args):
| bam_file_path = args.BAM
pattern_file_path = args.PAT
sample = args.ID
## create dir
path1 = 'nanoforenstr_output/%s' % sample
path2 = 'nanoforenstr_output/%s/figs' % sample
pathlib.Path(path2).mkdir(parents=True, exist_ok=True)
## pattern file
pattern_dict = myPatte... | ## parameters
# parser = argparse.ArgumentParser(description='Repeat quantification for reads from forenseq kit. Still working on')
# parser.add_argument('--BAM', help='input1: *.bam file', default = None)
# parser.add_argument('--PAT', help='input2: repeat pattern file', default = None)
# parser.add_argument('--ID', h... | 120 | 120 | 403 | 5 | 114 | Ming-Ni-Lab/NanoForenSTR | nanoforenstr.py | Python | quick | quick | 41 | 84 | 41 | 42 | ad1e5a4a57c03589b60b25cdfa01e1320834693b | bigcode/the-stack | train |
1508dd37e1a132e11232a45f | train | class | class TargetPicker:
WOBID_INV = 1
WOBID_ROOM = 2
UVZ_FLOORED = 4
UVZ = 8
| class TargetPicker:
| WOBID_INV = 1
WOBID_ROOM = 2
UVZ_FLOORED = 4
UVZ = 8
| .media.background import LevelBackground
BrowserInfo = {
'browser': 'Chrome',
'version': 82,
'OS': 'Windows'
}
Capabilities = {
'os': 'Windows 10',
'version': 'WIN 32,0,0,344'
}
class TargetPicker:
| 64 | 64 | 38 | 4 | 60 | Jan000/Python-Freggers-Bot | freggersbot/freggers.py | Python | TargetPicker | TargetPicker | 54 | 59 | 54 | 55 | 8ebf2fbb2d7d5c5ef285f876fc7519c049326841 | bigcode/the-stack | train |
6b57b36543e488d89372f301 | train | class | class Freggers:
VERSION = '20190130-160700phi'
BROWSER = BrowserInfo['browser'] + ' ' + str(BrowserInfo['version'])
GENDER_MALE = 'male'
GENDER_FEMALE = 'female'
SEND_LIVE_STATS = False
LIVE_STATS = False
STAT_UPDATE_INTERVAL = 60
TOUCH_INTERVAL = 300
AUTO_RECONNECT_TIME = 10
LOOP_INTERVAL = 0.02
PI... | class Freggers:
| VERSION = '20190130-160700phi'
BROWSER = BrowserInfo['browser'] + ' ' + str(BrowserInfo['version'])
GENDER_MALE = 'male'
GENDER_FEMALE = 'female'
SEND_LIVE_STATS = False
LIVE_STATS = False
STAT_UPDATE_INTERVAL = 60
TOUCH_INTERVAL = 300
AUTO_RECONNECT_TIME = 10
LOOP_INTERVAL = 0.02
PING = 256
COM_LOGO... | = 29
NOTIFY_COINS_OR_BILLS = 30
NOTIFY_STREAM = 31
NOTIFY_MAIL = 32
NOTIFY_ITEMUPDATE = 33
NOTIFY_STICKIES = 34
NOTIFY_BADGE = 35
NOTIFY_LEVEL = 36
NOTIFY_ITEM_INBOX = 37
NOTIFY_MODEL_UPDATE = 38
DATA_GENERAL = 39
COMMAND_REFRESH_IGNORES = 40
SET_HAND_HELD = 41
CLEAR_HAND_HELD = 42
OPEN_BUY_ITEM_VIEW = 4... | 256 | 256 | 13,567 | 6 | 249 | Jan000/Python-Freggers-Bot | freggersbot/freggers.py | Python | Freggers | Freggers | 120 | 1,646 | 120 | 121 | 98569b59c634d6f16b1a11db759d26c713b93800 | bigcode/the-stack | train |
d8a80aa490810d7f642ef8ea | train | class | class Event:
PING = 0
LOGOUT = 1
LOGIN = 2
CTXT_SERVER = 3
CTXT_ROOM = 4
ENV_USER = 5
ENV_EXIT = 6
ENV_ITEM = 7
ENV_STAT = 8
ENV_MISC = 9
ENV_BRIGHTNESS = 10
ENV_REMOVE_ITEMS = 11
ENV_ROOM_TOPIC = 12
ENV_WOB_PROPERTIES = 13
TR_ROOM_JOIN = 14
TR_ROOM_LEAVE = 15
TR_ROOM_REJECT = 16
CHAT_USR = 17
CHAT... | class Event:
| PING = 0
LOGOUT = 1
LOGIN = 2
CTXT_SERVER = 3
CTXT_ROOM = 4
ENV_USER = 5
ENV_EXIT = 6
ENV_ITEM = 7
ENV_STAT = 8
ENV_MISC = 9
ENV_BRIGHTNESS = 10
ENV_REMOVE_ITEMS = 11
ENV_ROOM_TOPIC = 12
ENV_WOB_PROPERTIES = 13
TR_ROOM_JOIN = 14
TR_ROOM_LEAVE = 15
TR_ROOM_REJECT = 16
CHAT_USR = 17
CHAT_SRV = 18
ACTI... | from freggersbot.iso.item import IsoItem
from freggersbot.iso.wob_registry import WOBRegistry
from freggersbot.media.resource_manager import RESOURCE_MANAGER
from freggersbot.media.level import Level
from freggersbot.media.background import LevelBackground
BrowserInfo = {
'browser': 'Chrome',
'version': 82,
'OS': '... | 149 | 149 | 497 | 4 | 144 | Jan000/Python-Freggers-Bot | freggersbot/freggers.py | Python | Event | Event | 61 | 118 | 61 | 62 | c95b3752b6d4dfe732504c01f19f69a39343c2dd | bigcode/the-stack | train |
14ec08cd891db96909d925b0 | train | class | class Migration(migrations.Migration):
dependencies = [
('events', '0009_eventsignup_transaction_token'),
]
operations = [
migrations.AddField(
model_name='eventsignup',
name='is_unsigned_up',
field=models.BooleanField(default=False),
),
... | class Migration(migrations.Migration):
| dependencies = [
('events', '0009_eventsignup_transaction_token'),
]
operations = [
migrations.AddField(
model_name='eventsignup',
name='is_unsigned_up',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_n... | # Generated by Django 2.0.2 on 2018-06-06 07:36
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 88 | 7 | 30 | RyanRMurray/warwick_gg | events/migrations/0010_auto_20180606_0836.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | f00761de0e97fe5e72a7e9cd19a89a56d7e97b59 | bigcode/the-stack | train |
f677d61a2074879dba64f61a | train | function | def main(_):
if not os.path.exists(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir)
if not os.path.exists(args.sample_dir):
os.makedirs(args.sample_dir)
if not os.path.exists(args.test_dir):
os.makedirs(args.test_dir)
tfconfig = tf.ConfigProto(allow_soft_placement=True)
... | def main(_):
| if not os.path.exists(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir)
if not os.path.exists(args.sample_dir):
os.makedirs(args.sample_dir)
if not os.path.exists(args.test_dir):
os.makedirs(args.test_dir)
tfconfig = tf.ConfigProto(allow_soft_placement=True)
tfconfig.gp... | =bool,
default=True, help='gan loss defined in lsgan')
parser.add_argument('--max_size', dest='max_size', type=int, default=50,
help='max size of image pool, 0 means do not use image pool')
args = parser.parse_args()
def main(_):
| 64 | 64 | 122 | 4 | 60 | NextTechLabAP/AI-Interior | main.py | Python | main | main | 64 | 77 | 64 | 64 | 7ea1321ca81d1f0c0ed172b41c15b377ce698211 | bigcode/the-stack | train |
126f12170c0dee9d3be79d08 | train | class | class _NullDisplay(object):
def __init__(self):
self.exec_result = None
def __call__(self, result):
logger.debug("NullDisplay %s", result)
self.exec_result = result
| class _NullDisplay(object):
| def __init__(self):
self.exec_result = None
def __call__(self, result):
logger.debug("NullDisplay %s", result)
self.exec_result = result
| 0.9.0'
logger = logging.getLogger('ansible_kernel.kernel')
version_pat = re.compile(r'version (\d+(\.\d+)+)')
DEBUG = False
def ensure_directory(d):
if not os.path.exists(d):
os.mkdir(d)
class _NullDisplay(object):
| 64 | 64 | 47 | 6 | 58 | jldowns/ansible-jupyter-kernel | ansible_kernel/kernel.py | Python | _NullDisplay | _NullDisplay | 66 | 73 | 66 | 67 | f93a80c9a482470bed81d218d5da65b5d5cc52fb | bigcode/the-stack | train |
97d9dffee24c01291b9a9653 | train | class | class AnsibleKernelHelpersThread(object):
def __init__(self, queue):
self.queue = queue
self.io_loop = IOLoop(make_current=False)
context = zmq.Context.instance()
self.pause_socket = context.socket(zmq.REP)
self.pause_socket_port = self.pause_socket.bind_to_random_port(
... | class AnsibleKernelHelpersThread(object):
| def __init__(self, queue):
self.queue = queue
self.io_loop = IOLoop(make_current=False)
context = zmq.Context.instance()
self.pause_socket = context.socket(zmq.REP)
self.pause_socket_port = self.pause_socket.bind_to_random_port(
"tcp://127.0.0.1")
self.sta... | Display()
NullDisplayTrap = DisplayTrap(hook=NullDisplay)
class Splitter(object):
def __init__(self, channels):
self.channels = channels
def send_multipart(self, msg, *args, **kwargs):
logger.debug('send_multipart %s %s %s', msg, args, kwargs)
for channel in self.channels:
... | 109 | 109 | 365 | 8 | 101 | jldowns/ansible-jupyter-kernel | ansible_kernel/kernel.py | Python | AnsibleKernelHelpersThread | AnsibleKernelHelpersThread | 92 | 138 | 92 | 93 | e6e170b64ab7f957a8078475b1c5c0a276dc0a62 | bigcode/the-stack | train |
cb0a435b44de87a0bef3db5d | train | class | class AnsibleKernel(Kernel):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
shell_class = Type(ZMQInteractiveShell)
implementation = 'ansible_kernel'
implementation_version = __version__
@property
def language_version(self):
m = version_pat.sear... | class AnsibleKernel(Kernel):
| shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
shell_class = Type(ZMQInteractiveShell)
implementation = 'ansible_kernel'
implementation_version = __version__
@property
def language_version(self):
m = version_pat.search(self.banner)
return... | .1")
self.pause_stream = ZMQStream(self.pause_socket, self.io_loop)
self.status_stream = ZMQStream(self.status_socket, self.io_loop)
self.pause_stream.on_recv(self.recv_pause)
self.status_stream.on_recv(self.recv_status)
self.thread = threading.Thread(target=self._thread_main)
... | 256 | 256 | 9,914 | 7 | 249 | jldowns/ansible-jupyter-kernel | ansible_kernel/kernel.py | Python | AnsibleKernel | AnsibleKernel | 141 | 1,282 | 141 | 142 | 1378e3fa5dd074a299bcd4964b021c81aa5a8400 | bigcode/the-stack | train |
5f4c56eff1980ca5faa1a687 | train | class | class Splitter(object):
def __init__(self, channels):
self.channels = channels
def send_multipart(self, msg, *args, **kwargs):
logger.debug('send_multipart %s %s %s', msg, args, kwargs)
for channel in self.channels:
result = channel.send_multipart(msg, *args, **kwargs)
... | class Splitter(object):
| def __init__(self, channels):
self.channels = channels
def send_multipart(self, msg, *args, **kwargs):
logger.debug('send_multipart %s %s %s', msg, args, kwargs)
for channel in self.channels:
result = channel.send_multipart(msg, *args, **kwargs)
logger.debug('res... | def __init__(self):
self.exec_result = None
def __call__(self, result):
logger.debug("NullDisplay %s", result)
self.exec_result = result
NullDisplay = _NullDisplay()
NullDisplayTrap = DisplayTrap(hook=NullDisplay)
class Splitter(object):
| 64 | 64 | 87 | 5 | 59 | jldowns/ansible-jupyter-kernel | ansible_kernel/kernel.py | Python | Splitter | Splitter | 80 | 89 | 80 | 81 | e41af49dfdaa0d73932707d534344fbe2077e6e2 | bigcode/the-stack | train |
a753ffd4ce528c51107ee494 | train | function | def ensure_directory(d):
if not os.path.exists(d):
os.mkdir(d)
| def ensure_directory(d):
| if not os.path.exists(d):
os.mkdir(d)
| task_num'])
TASK_ARGS_MODULES = modules + task_args
__version__ = '0.9.0'
logger = logging.getLogger('ansible_kernel.kernel')
version_pat = re.compile(r'version (\d+(\.\d+)+)')
DEBUG = False
def ensure_directory(d):
| 64 | 64 | 18 | 5 | 58 | jldowns/ansible-jupyter-kernel | ansible_kernel/kernel.py | Python | ensure_directory | ensure_directory | 61 | 63 | 61 | 61 | bb18dcf56b150d8ac5038377fa5735dd52bd17fc | bigcode/the-stack | train |
5834905eff7264abf9f5398f | train | function | def export_stl(_app, save_dir):
"""
export stl files into "sace_dir/"
Parameters
----------
_app: adsk.core.Application.get()
save_dir: str
directory path to save
"""
def traverse( occ):
# recursive method to get all bodies from components and sub-components
body =... | def export_stl(_app, save_dir):
| """
export stl files into "sace_dir/"
Parameters
----------
_app: adsk.core.Application.get()
save_dir: str
directory path to save
"""
def traverse( occ):
# recursive method to get all bodies from components and sub-components
body = adsk.fusion.BRepBody.cast(None)... | # -*- coding: utf-8 -*-
"""
Created on Sun May 12 19:15:34 2019
Modified on Sun Jan 17 2021
@author: syuntoku
@author: spacemaster85
"""
import adsk
import adsk.core
import adsk.fusion
import os.path
import re
from xml.etree import ElementTree
from xml.dom import minidom
from distutils.dir_util import copy_tree
impor... | 113 | 225 | 750 | 10 | 102 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | export_stl | export_stl | 22 | 110 | 22 | 22 | 62ac97d4bd99fd41f78ecbb9571deb4e7cafb0f9 | bigcode/the-stack | train |
cab04bab9e0f193545228935 | train | function | def prettify(elem):
"""
Return a pretty-printed XML string for the Element.
Parameters
----------
elem : xml.etree.ElementTree.Element
Returns
----------
pretified xml : str
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
... | def prettify(elem):
| """
Return a pretty-printed XML string for the Element.
Parameters
----------
elem : xml.etree.ElementTree.Element
Returns
----------
pretified xml : str
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.... | 2+z**2, x**2+z**2, x**2+y**2,
-x*y, -y*z, -x*z]
return [round(i - mass*t, 6) for i, t in zip(inertia, translation_matrix)]
def prettify(elem):
| 63 | 64 | 88 | 5 | 58 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | prettify | prettify | 151 | 165 | 151 | 151 | a5df4983f86a7480483ebfa09aeda5eebc2cbe00 | bigcode/the-stack | train |
0de5fbb49fdd023c4d91cd8f | train | function | def update_cmakelists(save_dir, package_name):
file_name = save_dir + '/CMakeLists.txt'
for line in fileinput.input(file_name, inplace=True):
if 'project(fusion2urdf)' in line:
sys.stdout.write("project(" + package_name + ")\n")
else:
sys.stdout.write(line)
| def update_cmakelists(save_dir, package_name):
| file_name = save_dir + '/CMakeLists.txt'
for line in fileinput.input(file_name, inplace=True):
if 'project(fusion2urdf)' in line:
sys.stdout.write("project(" + package_name + ")\n")
else:
sys.stdout.write(line)
| (save_dir, package_dir):
try:
os.mkdir(save_dir + '/launch')
except:
pass
try:
os.mkdir(save_dir + '/urdf')
except:
pass
copy_tree(package_dir, save_dir)
def update_cmakelists(save_dir, package_name):
| 64 | 64 | 75 | 12 | 52 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | update_cmakelists | update_cmakelists | 180 | 187 | 180 | 180 | 14a23032365bdae309c5f928a9669fcfa9d275eb | bigcode/the-stack | train |
e1d1e1ba03d91111664e2c88 | train | function | def origin2center_of_mass(inertia, center_of_mass, mass):
"""
convert the moment of the inertia about the world coordinate into
that about center of mass coordinate
Parameters
----------
moment of inertia about the world coordinate: [xx, yy, zz, xy, yz, xz]
center_of_mass: [x, y, z]
... | def origin2center_of_mass(inertia, center_of_mass, mass):
| """
convert the moment of the inertia about the world coordinate into
that about center of mass coordinate
Parameters
----------
moment of inertia about the world coordinate: [xx, yy, zz, xy, yz, xz]
center_of_mass: [x, y, z]
Returns
----------
moment of inertia about center... | ()
folderDlg.title = 'Fusion Folder Dialog'
# Show folder dialog
dlgResult = folderDlg.showDialog()
if dlgResult == adsk.core.DialogResults.DialogOK:
return folderDlg.folder
return False
def origin2center_of_mass(inertia, center_of_mass, mass):
| 64 | 64 | 201 | 15 | 48 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | origin2center_of_mass | origin2center_of_mass | 127 | 148 | 127 | 127 | d36c3c8eb7aea2cefb1285454c68df0c6c699fdd | bigcode/the-stack | train |
41efa9557cb1ddc12d6568ce | train | function | def copy_package(save_dir, package_dir):
try:
os.mkdir(save_dir + '/launch')
except:
pass
try:
os.mkdir(save_dir + '/urdf')
except:
pass
copy_tree(package_dir, save_dir)
| def copy_package(save_dir, package_dir):
| try:
os.mkdir(save_dir + '/launch')
except:
pass
try:
os.mkdir(save_dir + '/urdf')
except:
pass
copy_tree(package_dir, save_dir)
| Returns
----------
pretified xml : str
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def copy_package(save_dir, package_dir):
| 63 | 64 | 55 | 9 | 54 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | copy_package | copy_package | 168 | 177 | 168 | 168 | a8848adb6f0f60d9e44ad5f6252ae31fe7986a30 | bigcode/the-stack | train |
3ce173f5ba298d98b20f9632 | train | function | def file_dialog(ui):
"""
display the dialog to save the file
"""
# Set styles of folder dialog.
folderDlg = ui.createFolderDialog()
folderDlg.title = 'Fusion Folder Dialog'
# Show folder dialog
dlgResult = folderDlg.showDialog()
if dlgResult == adsk.core.DialogResults.DialogOK:
... | def file_dialog(ui):
| """
display the dialog to save the file
"""
# Set styles of folder dialog.
folderDlg = ui.createFolderDialog()
folderDlg.title = 'Fusion Folder Dialog'
# Show folder dialog
dlgResult = folderDlg.showDialog()
if dlgResult == adsk.core.DialogResults.DialogOK:
return folderDlg.... | .name)
expPath = os.path.join(exportFolder, '{}.stl'.format(expName))
stlOpts = exportMgr.createSTLExportOptions(occ, expPath)
exportMgr.execute(stlOpts)
# remove export Doc
expDoc.close(False)
def file_dialog(ui):
| 64 | 64 | 83 | 5 | 59 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | file_dialog | file_dialog | 112 | 124 | 112 | 112 | d6ec2f5e7377df9be45f25550c52bb2259636c51 | bigcode/the-stack | train |
d50a4238b13874f480bba3e0 | train | function | def update_ros2_launchfile(save_dir, package_name):
file_name = save_dir + '/launch/robot_description.launch.py'
for line in fileinput.input(file_name, inplace=True):
if 'fusion2urdf' in line:
sys.stdout.write(line.replace('fusion2urdf', package_name))
else:
sys.stdout.w... | def update_ros2_launchfile(save_dir, package_name):
| file_name = save_dir + '/launch/robot_description.launch.py'
for line in fileinput.input(file_name, inplace=True):
if 'fusion2urdf' in line:
sys.stdout.write(line.replace('fusion2urdf', package_name))
else:
sys.stdout.write(line)
| .txt'
for line in fileinput.input(file_name, inplace=True):
if 'project(fusion2urdf)' in line:
sys.stdout.write("project(" + package_name + ")\n")
else:
sys.stdout.write(line)
def update_ros2_launchfile(save_dir, package_name):
| 64 | 64 | 75 | 12 | 52 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | update_ros2_launchfile | update_ros2_launchfile | 189 | 196 | 189 | 189 | ca7127b91de4883efc778068028e367d463de14e | bigcode/the-stack | train |
a0ba3cc88c3a1c0751f9b53f | train | function | def update_package_xml(save_dir, package_name):
file_name = save_dir + '/package.xml'
for line in fileinput.input(file_name, inplace=True):
if '<name>' in line:
sys.stdout.write(" <name>" + package_name + "</name>\n")
elif '<description>' in line:
sys.stdout.write("<des... | def update_package_xml(save_dir, package_name):
| file_name = save_dir + '/package.xml'
for line in fileinput.input(file_name, inplace=True):
if '<name>' in line:
sys.stdout.write(" <name>" + package_name + "</name>\n")
elif '<description>' in line:
sys.stdout.write("<description>The " +
pa... | /robot_description.launch.py'
for line in fileinput.input(file_name, inplace=True):
if 'fusion2urdf' in line:
sys.stdout.write(line.replace('fusion2urdf', package_name))
else:
sys.stdout.write(line)
def update_package_xml(save_dir, package_name):
| 64 | 64 | 97 | 10 | 54 | xwavex/fusion2urdf | URDF_Exporter/utils/utils.py | Python | update_package_xml | update_package_xml | 198 | 208 | 198 | 198 | 1ca67d792126397d159a05d341a6d7942d64de95 | bigcode/the-stack | train |
20e12cdc83929c67af6f9dd6 | train | class | class GateConstructionTester(BaseCase):
def test_single_qubit_gate_matrix(self):
expected = np.array([[1.00000000e+00, 2.77555756e-16, -2.28983499e-16, 0.00000000e+00],
[-3.53885261e-16, -8.09667193e-01, 5.22395269e-01, -2.67473774e-01],
[-3.92523115... | class GateConstructionTester(BaseCase):
| def test_single_qubit_gate_matrix(self):
expected = np.array([[1.00000000e+00, 2.77555756e-16, -2.28983499e-16, 0.00000000e+00],
[-3.53885261e-16, -8.09667193e-01, 5.22395269e-01, -2.67473774e-01],
[-3.92523115e-17, 5.22395269e-01, 8.49200550e-01, 7.... | import numpy as np
import pygsti.tools.gatetools as gc
from ..util import BaseCase
class GateConstructionTester(BaseCase):
| 29 | 256 | 1,289 | 7 | 21 | colibri-coruscans/pyGSTi | test/unit/construction/test_gateconstruction.py | Python | GateConstructionTester | GateConstructionTester | 7 | 57 | 7 | 7 | dba250ca216acf46f98df90b82cf6bcb350b0672 | bigcode/the-stack | train |
38d5d6a23c917ef7e8d8a3b1 | train | function | def load_main_page(driver: webdriver) -> bool:
list_of_xpath = [
'//div[contains(@class, "btn-booking")]',
'//frame[@src="https://relay.kdca.go.kr/"]',
'//frame[@src="/cobk/index.jsp"]'
]
driver.get(URL)
isLocated = [expected_conditions.presence_of_element_loc... | def load_main_page(driver: webdriver) -> bool:
| list_of_xpath = [
'//div[contains(@class, "btn-booking")]',
'//frame[@src="https://relay.kdca.go.kr/"]',
'//frame[@src="/cobk/index.jsp"]'
]
driver.get(URL)
isLocated = [expected_conditions.presence_of_element_located((By.XPATH, xpath)) for xpath in list_of_xp... | 'https://ncvr.kdca.go.kr/'
FIRST_PAGE_TIMEOUT = 5 * 60 * 60 # 처음 로딩할때 기다리는 시간 (대기하는거 포함)
TIMEOUT = 30 # 로딩된 이후 기다리는 시간
def load_main_page(driver: webdriver) -> bool:
| 64 | 64 | 204 | 11 | 52 | onehowon/VaccineBot | run_vaccinate.py | Python | load_main_page | load_main_page | 21 | 41 | 21 | 21 | 7e6ab747e608e9b58416584b3e2a78ad1dbf187c | bigcode/the-stack | train |
dd4bb2a828f3f7066f7e062b | train | function | def click_if_loaded(driver: webdriver, by:By ,xpath: str) -> bool:
try:
WebDriverWait(driver, TIMEOUT).until(expected_conditions.presence_of_element_located((by, xpath)))
driver.find_element(by, xpath).click()
return True
except:
return False
| def click_if_loaded(driver: webdriver, by:By ,xpath: str) -> bool:
| try:
WebDriverWait(driver, TIMEOUT).until(expected_conditions.presence_of_element_located((by, xpath)))
driver.find_element(by, xpath).click()
return True
except:
return False
| click()
# driver.switch_to.window(driver.window_handles[0])
# driver.switch_to.frame(driver.find_element(By.XPATH, '//frame[@src="/cobk/index.jsp"]'))
except:
return False
def click_if_loaded(driver: webdriver, by:By ,xpath: str) -> bool:
| 64 | 64 | 66 | 19 | 44 | onehowon/VaccineBot | run_vaccinate.py | Python | click_if_loaded | click_if_loaded | 84 | 90 | 84 | 84 | 6a697bf5fc082e8d0630dadfea036f3cd3148473 | bigcode/the-stack | train |
5bb1e72d2aacd84252c5604d | train | function | def authenticate(driver: webdriver, config: dict) -> None:
# 사이트가 완전히 로딩되었는지 확인
element1_present = expected_conditions.presence_of_element_located((By.XPATH, '//a[@href="#kt"]'))
try:
WebDriverWait(driver, TIMEOUT).until(lambda driver: len(driver.window_handles) == 2)
driver.switch_to.window... | def authenticate(driver: webdriver, config: dict) -> None:
# 사이트가 완전히 로딩되었는지 확인
| element1_present = expected_conditions.presence_of_element_located((By.XPATH, '//a[@href="#kt"]'))
try:
WebDriverWait(driver, TIMEOUT).until(lambda driver: len(driver.window_handles) == 2)
driver.switch_to.window(driver.window_handles[1])
WebDriverWait(driver, TIMEOUT).until(element1_pre... | (config['대리인']['주민등록번호'].split('-')[0])
driver.find_element(By.ID, 'apnmRrn2').send_keys(config['대리인']['주민등록번호'].split('-')[1])
return True
except:
return False
def authenticate(driver: webdriver, config: dict) -> None:
# 사이트가 완전히 로딩되었는지 확인
| 86 | 86 | 288 | 27 | 58 | onehowon/VaccineBot | run_vaccinate.py | Python | authenticate | authenticate | 64 | 82 | 64 | 65 | 543f646d5b225e389ef6d6c16389b454c6bde0a4 | bigcode/the-stack | train |
330921fb716ebc4c531306e7 | train | function | def privacy(driver: webdriver, config: dict) -> bool:
# 사이트가 완전히 로딩되었는지 확인
element1_present = expected_conditions.presence_of_element_located((By.ID, 'ptntRrn2'))
try:
WebDriverWait(driver, TIMEOUT).until(element1_present)
# 카카오톡
driver.find_element(By.ID, 'smsRcptAgrmYn2').click()
... | def privacy(driver: webdriver, config: dict) -> bool:
# 사이트가 완전히 로딩되었는지 확인
| element1_present = expected_conditions.presence_of_element_located((By.ID, 'ptntRrn2'))
try:
WebDriverWait(driver, TIMEOUT).until(element1_present)
# 카카오톡
driver.find_element(By.ID, 'smsRcptAgrmYn2').click()
# 개인정보 채우기
driver.find_element(By.ID, 'patnam').send_keys(config... | list_of_xpath[0]).click()
WebDriverWait(driver, FIRST_PAGE_TIMEOUT).until(isLocated[1])
driver.switch_to.frame(driver.find_element(By.XPATH, list_of_xpath[1]))
WebDriverWait(driver, FIRST_PAGE_TIMEOUT).until(isLocated[2])
driver.switch_to.frame(driver.find_element(By.XPATH, list_of_xp... | 112 | 112 | 374 | 27 | 84 | onehowon/VaccineBot | run_vaccinate.py | Python | privacy | privacy | 43 | 62 | 43 | 44 | 82c4d874f4240f331d5911b53c2794a19c46c03c | bigcode/the-stack | train |
e2dc97bf5a27972f2e6df378 | train | function | def main(filename: str) -> None:
chromedriver_autoinstaller.install()
driver = webdriver.Chrome()
config = configparser.ConfigParser()
config.read(filename, encoding='utf-8')
# 화면 보일때 까지 계속 로딩하기
while not load_main_page(driver):
pass
# 백신 예약 버튼 클릭
click_if_loaded(driver, By.XPA... | def main(filename: str) -> None:
| chromedriver_autoinstaller.install()
driver = webdriver.Chrome()
config = configparser.ConfigParser()
config.read(filename, encoding='utf-8')
# 화면 보일때 까지 계속 로딩하기
while not load_main_page(driver):
pass
# 백신 예약 버튼 클릭
click_if_loaded(driver, By.XPATH, '//div[contains(@class, "bann... | ,xpath: str) -> bool:
try:
WebDriverWait(driver, TIMEOUT).until(expected_conditions.presence_of_element_located((by, xpath)))
driver.find_element(by, xpath).click()
return True
except:
return False
def main(filename: str) -> None:
| 64 | 64 | 212 | 9 | 54 | onehowon/VaccineBot | run_vaccinate.py | Python | main | main | 92 | 119 | 92 | 92 | 83d4a72419eb9e512e4c8792bb40dbb502bac8d7 | bigcode/the-stack | train |
f8c186bb3b983802130cb651 | train | function | def comp_parameters(
self, machine, OP, Tsta=None, Trot=None, Id_array=None, Iq_array=None
):
"""Compute the parameters dict for the equivalent electrical circuit:
resistance, inductance and back electromotive force
Parameters
----------
self : EEC_PMSM
an EEC_PMSM object
machine : ... | def comp_parameters(
self, machine, OP, Tsta=None, Trot=None, Id_array=None, Iq_array=None
):
| """Compute the parameters dict for the equivalent electrical circuit:
resistance, inductance and back electromotive force
Parameters
----------
self : EEC_PMSM
an EEC_PMSM object
machine : Machine
a Machine object
OP : OP
an OP object
Tsta : float
Average... | from numpy import isscalar
def comp_parameters(
self, machine, OP, Tsta=None, Trot=None, Id_array=None, Iq_array=None
):
| 35 | 256 | 927 | 29 | 5 | nnassar98/pyleecan | pyleecan/Methods/Simulation/EEC_PMSM/comp_parameters.py | Python | comp_parameters | comp_parameters | 4 | 111 | 4 | 6 | 2a848433d4c4eff4e39f224b3eb3fc69e5ba60ad | bigcode/the-stack | train |
c6cff000452a3ff535dc2239 | train | function | def get_points_for_equipment(equipment, building, pymortar_client):
"""Gets points for each equipment in the list of equipment"""
v = pymortar.View(
name=equipment,
definition="""
SELECT ?{eq_lower} ?point ?class FROM {building} WHERE {{
?{eq_lower} rdf:type brick:{eq_class}... | def get_points_for_equipment(equipment, building, pymortar_client):
| """Gets points for each equipment in the list of equipment"""
v = pymortar.View(
name=equipment,
definition="""
SELECT ?{eq_lower} ?point ?class FROM {building} WHERE {{
?{eq_lower} rdf:type brick:{eq_class} .
?{eq_lower} bf:hasPoint ?point .
?point r... | res.query("SELECT DISTINCT SUBSTR(equipclass, INSTR(equipclass, '#') + 1) AS eq FROM equipment WHERE equipname NOT LIKE '%Central%'")
return [row[0] for row in equip_query]
def get_points_for_equipment(equipment, building, pymortar_client):
| 64 | 64 | 156 | 15 | 49 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | get_points_for_equipment | get_points_for_equipment | 127 | 145 | 127 | 127 | 5f4a1208285a99d8f5b7b1dde4d07395587c13cf | bigcode/the-stack | train |
a1773b9dce93e983f4993f75 | train | function | def write_proto_message(file, points, equipment):
"""Writes a single message struct in the specified protobuf file"""
file.write("message %s {\r\n" % equipment)
file.write("\toption (brick_equip_class).namespace = 'https://brickschema.org/schema/1.0.3/Brick#';\r\n")
file.write("\toption (brick_equip_cl... | def write_proto_message(file, points, equipment):
| """Writes a single message struct in the specified protobuf file"""
file.write("message %s {\r\n" % equipment)
file.write("\toption (brick_equip_class).namespace = 'https://brickschema.org/schema/1.0.3/Brick#';\r\n")
file.write("\toption (brick_equip_class).value = '%s';\r\n\n" % equipment)
for p ... | (eq_lower=equipment.lower(), eq_class=equipment, building=building)
)
res = pymortar_client.fetch(pymortar.FetchRequest(
sites=[building],
views=[v]
))
return res.view(equipment)['class'].unique()
def write_proto_message(file, points, equipment):
| 64 | 64 | 198 | 10 | 54 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | write_proto_message | write_proto_message | 147 | 158 | 147 | 147 | 2328e5070e819fc33220977aa0be2f3e2d1a44ab | bigcode/the-stack | train |
38a73b3984899f8af6137620 | train | function | def match_proto_numbering_and_write(file, equipment, points, proto_json):
"""Matches the numbering of the existing points in hvac.proto and writes the points to the hvac.proto file"""
if equipment in proto_json:
# If the equipment already exists in hvac.proto
new_points = []
for p in po... | def match_proto_numbering_and_write(file, equipment, points, proto_json):
| """Matches the numbering of the existing points in hvac.proto and writes the points to the hvac.proto file"""
if equipment in proto_json:
# If the equipment already exists in hvac.proto
new_points = []
for p in points:
if p in proto_json[equipment]["Fields"]:
... | all clustered equipment to hvac.proto
for eq in clustered_equipment:
points = clustered_equipment[eq]
if points:
match_proto_numbering_and_write(f, eq, points, proto_json)
f.close()
def match_proto_numbering_and_write(file, equipment, points, proto_json):
| 66 | 66 | 223 | 16 | 50 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | match_proto_numbering_and_write | match_proto_numbering_and_write | 51 | 74 | 51 | 51 | a51da3dc583baf818f0f2d746972bf456c788616 | bigcode/the-stack | train |
fea43369a542cd000856036a | train | function | def main():
pymortar_client = pymortar.Client()
buildings = ['orinda-public-library']
proto_json = gen_proto_json() if os.path.exists('hvac.proto') and os.stat("hvac.proto").st_size != 0 else {}
f = open("hvac.proto","w+")
clustered_equipment = {"Damper": {}, "Fan": {}, "Thermostat": {}}
... | def main():
| pymortar_client = pymortar.Client()
buildings = ['orinda-public-library']
proto_json = gen_proto_json() if os.path.exists('hvac.proto') and os.stat("hvac.proto").st_size != 0 else {}
f = open("hvac.proto","w+")
clustered_equipment = {"Damper": {}, "Fan": {}, "Thermostat": {}}
f.write("synta... | # Quick script to autogenerate the hvac.proto file with definitions for unique equipment in the specified buildings
import pymortar
import subprocess
import os
import json
from collections import OrderedDict
def main():
| 45 | 120 | 400 | 4 | 40 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | main | main | 8 | 49 | 8 | 9 | 2f61a70e6c71d2adeb076ba10b06527d588e1b35 | bigcode/the-stack | train |
99ebe52114fbf39792bd9283 | train | function | def get_equipment_list(building, pymortar_client):
"""Gets unique list of equipment in the building"""
#Get unique list of equipment
v = pymortar.View(
name="equipment",
definition="""
SELECT ?equipname ?equipclass ?point ?pointclass FROM %s WHERE {
?equipclass rdfs:subC... | def get_equipment_list(building, pymortar_client):
| """Gets unique list of equipment in the building"""
#Get unique list of equipment
v = pymortar.View(
name="equipment",
definition="""
SELECT ?equipname ?equipclass ?point ?pointclass FROM %s WHERE {
?equipclass rdfs:subClassOf+ brick:Equipment .
?equipname rd... | k, v = [], []
for field in record["Fields"]:
k.append(field["Class"])
v.append(field)
record["Fields"] = dict(zip(k, v))
values.append(record)
return dict(zip(keys, values))
def get_equipment_list(building, pymortar_client):
| 64 | 64 | 205 | 12 | 52 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | get_equipment_list | get_equipment_list | 102 | 125 | 102 | 102 | 2a1f2e8bb485d300bfb8deabfba56048482c8845 | bigcode/the-stack | train |
876446ade71fc62c94b6a7cb | train | function | def gen_proto_json():
"""Generates json dictionary out of the hvac.proto file using protodef_to_json"""
# Run the protodef_to_json on hvac.proto to generate a json representation
cur_dir = os.getcwd()
os.chdir("../tools/protodef_to_json")
subprocess.call(["go", "build"])
proto_str = subprocess.... | def gen_proto_json():
| """Generates json dictionary out of the hvac.proto file using protodef_to_json"""
# Run the protodef_to_json on hvac.proto to generate a json representation
cur_dir = os.getcwd()
os.chdir("../tools/protodef_to_json")
subprocess.call(["go", "build"])
proto_str = subprocess.Popen(["./protodef_to_... | .items(), key=lambda kv: kv[1]))
write_proto_message(file, points, equipment)
else:
# If the equipment is new in hvac.proto
write_proto_message(file, dict(zip(points.keys(), list(range(1, len(points) + 1)))), equipment)
def gen_proto_json():
| 65 | 65 | 219 | 5 | 60 | sguduguntla/xboswave | proto/gen_hvac_proto.py | Python | gen_proto_json | gen_proto_json | 76 | 100 | 76 | 76 | d07641635b50a50f203b491d49fc19228406bc03 | bigcode/the-stack | train |
8a366ece9cead8ce2583f9de | train | function | def distance_matrix(x, y):
return torch.cdist(x, y, 2).sum()
| def distance_matrix(x, y):
| return torch.cdist(x, y, 2).sum()
| (
# root='data',
# train=False,
# transform=ToTensor()
# )
import matplotlib.pyplot as plt
import torch
plt.imshow(train_data.data[0], cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()
def distance_matrix(x, y):
| 64 | 64 | 21 | 7 | 57 | LCB0B/metric | load_mnist.py | Python | distance_matrix | distance_matrix | 29 | 30 | 29 | 29 | 57b9ee040b995ba4b692f236829a0e50f72b6c41 | bigcode/the-stack | train |
b64880e51534408570b90389 | train | function | def distance_matrix_2(x, y):
#return torch.sqrt(torch.square(x-y).sum())
return ((x - y)**2).sum()**0.5
| def distance_matrix_2(x, y):
#return torch.sqrt(torch.square(x-y).sum())
| return ((x - y)**2).sum()**0.5
| [0], cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()
def distance_matrix(x, y):
return torch.cdist(x, y, 2).sum()
def distance_matrix_2(x, y):
#return torch.sqrt(torch.square(x-y).sum())
| 64 | 64 | 37 | 21 | 43 | LCB0B/metric | load_mnist.py | Python | distance_matrix_2 | distance_matrix_2 | 32 | 34 | 32 | 33 | e1b254fa1a080055b8b18447815fedcc82fcf0f9 | bigcode/the-stack | train |
e34a65c6769ae3ee9cd8f2e6 | train | function | def bitonic_sort(array):
def swap(a, b):
array[a], array[b] = array[b], array[a]
def comparator(start, end, comp, div, swap_type):
index = start
while index + comp < end:
if swap_type == 1 and array[index] > array[index + comp]:
swap(index, index + comp)
if swap_type == -1 and array... | def bitonic_sort(array):
| def swap(a, b):
array[a], array[b] = array[b], array[a]
def comparator(start, end, comp, div, swap_type):
index = start
while index + comp < end:
if swap_type == 1 and array[index] > array[index + comp]:
swap(index, index + comp)
if swap_type == -1 and array[index] < array[index + c... | import math
numbers = [3, 7, 4, 8, 6, 2, 1, 5]
def bitonic_sort(array):
| 35 | 80 | 267 | 6 | 29 | Gern-Yataro/Daily-CS | May 2019/bitonic_sort.py | Python | bitonic_sort | bitonic_sort | 4 | 33 | 4 | 4 | 8d043654c001add00993e582a68261198722952e | bigcode/the-stack | train |
cbf9557abf2495bc9cfdec09 | train | class | class ZipRecords(strax.Plugin):
provides = 'zipped_records'
depends_on = ('even_recs', 'odd_recs')
data_type = 'zipped_records'
dtype = Records.dtype
parallel = True
def compute(self, even_recs, odd_recs):
return strax.sort_by_time(np.concatenate((even_recs, odd_recs)))
| class ZipRecords(strax.Plugin):
| provides = 'zipped_records'
depends_on = ('even_recs', 'odd_recs')
data_type = 'zipped_records'
dtype = Records.dtype
parallel = True
def compute(self, even_recs, odd_recs):
return strax.sort_by_time(np.concatenate((even_recs, odd_recs)))
| 0
return dict(even_recs=records[mask],
odd_recs=records[~mask],
rec_count=dict(n_records=[len(records)],
time=records[0]['time'],
endtime=strax.endtime(records[-1])))
class ZipRecords(strax.Plugin):
| 63 | 64 | 80 | 7 | 56 | ahiguera-mx/strax | tests/test_multi_output.py | Python | ZipRecords | ZipRecords | 40 | 48 | 40 | 40 | a3fc4a00236d2660fcb484c6bb46264e63ddeab7 | bigcode/the-stack | train |
6f1fc3104c9ed09861f79340 | train | class | class EvenOddSplit(strax.Plugin):
parallel = 'process'
depends_on = 'records'
provides = ('even_recs', 'odd_recs', 'rec_count')
data_kind = dict(
even_recs='even_recs',
odd_recs='odd_recs',
rec_count='chunk_bonus_data')
dtype = dict(
even_recs=Records.dtype,
... | class EvenOddSplit(strax.Plugin):
| parallel = 'process'
depends_on = 'records'
provides = ('even_recs', 'odd_recs', 'rec_count')
data_kind = dict(
even_recs='even_recs',
odd_recs='odd_recs',
rec_count='chunk_bonus_data')
dtype = dict(
even_recs=Records.dtype,
odd_recs=Records.dtype,
r... | import tempfile
import numpy as np
import strax
from strax.testutils import *
import unittest
import os
import shutil
class EvenOddSplit(strax.Plugin):
| 36 | 65 | 219 | 8 | 27 | ahiguera-mx/strax | tests/test_multi_output.py | Python | EvenOddSplit | EvenOddSplit | 12 | 37 | 12 | 12 | d22002a83e3ba312202e6a0883fc2cae5f383d47 | bigcode/the-stack | train |
24a354b25da8974ea6dcce6a | train | class | class FunnyPeaks(strax.Plugin):
parallel = True
provides = 'peaks'
depends_on = 'even_recs'
dtype = strax.peak_dtype()
def compute(self, even_recs):
p = np.zeros(len(even_recs), self.dtype)
p['time'] = even_recs['time']
return p
| class FunnyPeaks(strax.Plugin):
| parallel = True
provides = 'peaks'
depends_on = 'even_recs'
dtype = strax.peak_dtype()
def compute(self, even_recs):
p = np.zeros(len(even_recs), self.dtype)
p['time'] = even_recs['time']
return p
| ']
res['time'][n_even:] = odd_recs['time']
res['length'][n_even:] = odd_recs['length']
res['channel'][n_even:] = odd_recs['channel']
return strax.sort_by_time(res)
class FunnyPeaks(strax.Plugin):
| 64 | 64 | 77 | 8 | 56 | ahiguera-mx/strax | tests/test_multi_output.py | Python | FunnyPeaks | FunnyPeaks | 100 | 109 | 100 | 100 | 4ba49decd2fbf27f4f6aa631ee61207995b04be4 | bigcode/the-stack | train |
50f957bdadedbce932666182 | train | class | class TestMultiOutputs(unittest.TestCase):
def setUp(self):
# Temp directory for storing record data for the tests.
# Will be removed during TearDown.
self.temp_dir = tempfile.mkdtemp()
self.mystrax = strax.Context(
storage=strax.DataDirectory(self.temp_dir),
... | class TestMultiOutputs(unittest.TestCase):
| def setUp(self):
# Temp directory for storing record data for the tests.
# Will be removed during TearDown.
self.temp_dir = tempfile.mkdtemp()
self.mystrax = strax.Context(
storage=strax.DataDirectory(self.temp_dir),
register=[Records, EvenOddSplit, ZipRecords... | ):
n_even = len(even_recs)
n_odd = len(odd_recs)
res = np.zeros(n_even+n_odd, self.dtype)
res['dt'][:n_even] = even_recs['dt']
res['time'][:n_even] = even_recs['time']
res['length'][:n_even] = even_recs['length']
res['channel'][:n_even] = even_recs['channel']
... | 256 | 256 | 1,003 | 8 | 247 | ahiguera-mx/strax | tests/test_multi_output.py | Python | TestMultiOutputs | TestMultiOutputs | 112 | 211 | 112 | 113 | b53d19ed257229b9207399c422632ae60e891a10 | bigcode/the-stack | train |
a6f8df41c4d31f32ac3b850f | train | class | class ZipRecordsAdditionalDependency(strax.Plugin):
"""
Plugin required to test inline plugins for double dependency.
"""
provides = 'zipped_records_classified'
depends_on = ('even_recs', 'even_recs_classified', 'odd_recs')
data_type = 'zipped_records_classified'
dtype = Records.dtype
pa... | class ZipRecordsAdditionalDependency(strax.Plugin):
| """
Plugin required to test inline plugins for double dependency.
"""
provides = 'zipped_records_classified'
depends_on = ('even_recs', 'even_recs_classified', 'odd_recs')
data_type = 'zipped_records_classified'
dtype = Records.dtype
parallel = True
def compute(self, even_recs, odd_... | 8)]
return dtype
def compute(self, even_recs):
res = np.ones(len(even_recs), self.dtype)
res['time'] = even_recs['time']
res['dt'] = even_recs['dt']
res['length'] = even_recs['length']
return res
class ZipRecordsAdditionalDependency(strax.Plugin):
| 78 | 78 | 260 | 9 | 68 | ahiguera-mx/strax | tests/test_multi_output.py | Python | ZipRecordsAdditionalDependency | ZipRecordsAdditionalDependency | 73 | 97 | 73 | 73 | 285742a0ec1dba5cae45e99b62a2a60bb93b55b1 | bigcode/the-stack | train |
6a43a2bfa8ff68a3beb131bb | train | class | class EvenRecsClassified(strax.Plugin):
"""
Plugin required to test inline plugins for double dependency.
"""
provides = 'even_recs_classified'
depends_on = 'even_recs'
parallel = True
def infer_dtype(self):
dtype = []
dtype += strax.time_dt_fields
dtype += [(('... | class EvenRecsClassified(strax.Plugin):
| """
Plugin required to test inline plugins for double dependency.
"""
provides = 'even_recs_classified'
depends_on = 'even_recs'
parallel = True
def infer_dtype(self):
dtype = []
dtype += strax.time_dt_fields
dtype += [(('dummy classification', 'classifier'), np... | cs')
data_type = 'zipped_records'
dtype = Records.dtype
parallel = True
def compute(self, even_recs, odd_recs):
return strax.sort_by_time(np.concatenate((even_recs, odd_recs)))
class EvenRecsClassified(strax.Plugin):
| 63 | 64 | 151 | 10 | 53 | ahiguera-mx/strax | tests/test_multi_output.py | Python | EvenRecsClassified | EvenRecsClassified | 51 | 70 | 51 | 51 | 9f3ed9ee623e0f8955340ae5b27d2f3d10357c17 | bigcode/the-stack | train |
78640821347f789671707313 | train | class | class PythonFmtIntegrationTest(PantsRunIntegrationTest):
def test_black_one_python_source_should_leave_one_file_unchanged(self):
command = [
'fmt-v2',
'examples/src/python/example/hello/main:main'
]
pants_run = self.run_pants(command=command)
self.assert_success(pants_run)
self.asser... | class PythonFmtIntegrationTest(PantsRunIntegrationTest):
| def test_black_one_python_source_should_leave_one_file_unchanged(self):
command = [
'fmt-v2',
'examples/src/python/example/hello/main:main'
]
pants_run = self.run_pants(command=command)
self.assert_success(pants_run)
self.assertNotIn("reformatted", pants_run.stderr_data)
self.ass... | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from os.path import relpath
from pathlib import Path
from pants.util.contextutil import temporary_file, temporary_file_path
from pants_test.pants_run_integration_test import PantsRunInteg... | 84 | 193 | 646 | 11 | 72 | rusrushal13/pants | tests/python/pants_test/backend/python/rules/test_python_fmt_integration.py | Python | PythonFmtIntegrationTest | PythonFmtIntegrationTest | 11 | 78 | 11 | 11 | 36b492617724e492a95283e6cc97ffaec054e064 | bigcode/the-stack | train |
5ecfaf1f2cb328c4c9f0cd1e | train | function | def get_normalized_value(value, lhs):
from django.db.models import Model
if isinstance(value, Model):
value_list = []
sources = lhs.output_field.get_path_info()[-1].target_fields
for source in sources:
while not isinstance(value, source.model) and source.remote_field:
... | def get_normalized_value(value, lhs):
| from django.db.models import Model
if isinstance(value, Model):
value_list = []
sources = lhs.output_field.get_path_info()[-1].target_fields
for source in sources:
while not isinstance(value, source.model) and source.remote_field:
source = source.remote_field.... | "{}({}, {})".format(
self.__class__.__name__, self.alias, self.field)
def relabeled_clone(self, relabels):
return self.__class__(relabels.get(self.alias, self.alias),
self.targets, self.sources, self.field)
def get_normalized_value(value, lhs):
| 64 | 64 | 161 | 9 | 55 | geelweb/django | django/db/models/fields/related_lookups.py | Python | get_normalized_value | get_normalized_value | 23 | 40 | 23 | 23 | 89f3c4498f05719151d4fbeabd8e4f12dcf73afd | bigcode/the-stack | train |
af1a4cfb7018a32f65a4aca9 | train | class | class RelatedLessThan(RelatedLookupMixin, LessThan):
pass
| class RelatedLessThan(RelatedLookupMixin, LessThan):
| pass
| (self.lhs.alias, source), val), AND)
return root_constraint.as_sql(compiler, connection)
return super(RelatedLookupMixin, self).as_sql(compiler, connection)
class RelatedExact(RelatedLookupMixin, Exact):
pass
class RelatedLessThan(RelatedLookupMixin, LessThan):
| 64 | 64 | 15 | 12 | 51 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedLessThan | RelatedLessThan | 122 | 123 | 122 | 122 | 2baa3566e87ebda4c03b0e9b24a9b2899c2ef9fa | bigcode/the-stack | train |
c98e3429e0e63bde9d4bd3f3 | train | class | class RelatedGreaterThanOrEqual(RelatedLookupMixin, GreaterThanOrEqual):
pass
| class RelatedGreaterThanOrEqual(RelatedLookupMixin, GreaterThanOrEqual):
| pass
| (compiler, connection)
class RelatedExact(RelatedLookupMixin, Exact):
pass
class RelatedLessThan(RelatedLookupMixin, LessThan):
pass
class RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
pass
class RelatedGreaterThanOrEqual(RelatedLookupMixin, GreaterThanOrEqual):
| 64 | 64 | 19 | 16 | 47 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedGreaterThanOrEqual | RelatedGreaterThanOrEqual | 130 | 131 | 130 | 130 | 458cccd096ab5056b47b798dad796f0979ec2e6e | bigcode/the-stack | train |
25524c38890a8632fd0c8c83 | train | class | class RelatedIsNull(RelatedLookupMixin, IsNull):
pass
| class RelatedIsNull(RelatedLookupMixin, IsNull):
| pass
| RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
pass
class RelatedGreaterThanOrEqual(RelatedLookupMixin, GreaterThanOrEqual):
pass
class RelatedLessThanOrEqual(RelatedLookupMixin, LessThanOrEqual):
pass
class RelatedIsNull(RelatedLookupMixin, IsNull):
| 64 | 64 | 15 | 12 | 51 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedIsNull | RelatedIsNull | 138 | 139 | 138 | 138 | b0e94dab288af697c7e0d0c660aa555d63c558f6 | bigcode/the-stack | train |
f58e86dc6fcdb5eac23ac134 | train | class | class RelatedLookupMixin(object):
def get_prep_lookup(self):
if not isinstance(self.lhs, MultiColSource) and self.rhs_is_direct_value():
# If we get here, we are dealing with single-column relations.
self.rhs = get_normalized_value(self.rhs, self.lhs)[0]
# We need to run ... | class RelatedLookupMixin(object):
| def get_prep_lookup(self):
if not isinstance(self.lhs, MultiColSource) and self.rhs_is_direct_value():
# If we get here, we are dealing with single-column relations.
self.rhs = get_normalized_value(self.rhs, self.lhs)[0]
# We need to run the related field's get_prep_value... | (self.lhs.alias, source), val)
value_constraint.add(lookup, AND)
root_constraint.add(value_constraint, OR)
else:
root_constraint.add(
SubqueryConstraint(
self.lhs.alias, [target.column for target in self.... | 112 | 112 | 376 | 6 | 106 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedLookupMixin | RelatedLookupMixin | 87 | 115 | 87 | 87 | 4ee7a32946b1fc6f5359c156b1d5c34307c5e591 | bigcode/the-stack | train |
0541abb6f77bca4b82c2cb9a | train | class | class RelatedLessThanOrEqual(RelatedLookupMixin, LessThanOrEqual):
pass
| class RelatedLessThanOrEqual(RelatedLookupMixin, LessThanOrEqual):
| pass
| RelatedLessThan(RelatedLookupMixin, LessThan):
pass
class RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
pass
class RelatedGreaterThanOrEqual(RelatedLookupMixin, GreaterThanOrEqual):
pass
class RelatedLessThanOrEqual(RelatedLookupMixin, LessThanOrEqual):
| 64 | 64 | 19 | 16 | 47 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedLessThanOrEqual | RelatedLessThanOrEqual | 134 | 135 | 134 | 134 | d4a50acfad4e30b51182956a55b868e13e67a8e2 | bigcode/the-stack | train |
b486084ac48a57af1d44294b | train | class | class RelatedIn(In):
def get_prep_lookup(self):
if not isinstance(self.lhs, MultiColSource) and self.rhs_is_direct_value():
# If we get here, we are dealing with single-column relations.
self.rhs = [get_normalized_value(val, self.lhs)[0] for val in self.rhs]
# We need to ... | class RelatedIn(In):
| def get_prep_lookup(self):
if not isinstance(self.lhs, MultiColSource) and self.rhs_is_direct_value():
# If we get here, we are dealing with single-column relations.
self.rhs = [get_normalized_value(val, self.lhs)[0] for val in self.rhs]
# We need to run the related field... | _value(value, lhs):
from django.db.models import Model
if isinstance(value, Model):
value_list = []
sources = lhs.output_field.get_path_info()[-1].target_fields
for source in sources:
while not isinstance(value, source.model) and source.remote_field:
source = ... | 162 | 162 | 541 | 5 | 156 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedIn | RelatedIn | 43 | 84 | 43 | 43 | 90bc40ff3be10d83e8aeb6b58809f3e0e53b4cd4 | bigcode/the-stack | train |
133232c1cde3e8831f78844a | train | class | class RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
pass
| class RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
| pass
| .as_sql(compiler, connection)
return super(RelatedLookupMixin, self).as_sql(compiler, connection)
class RelatedExact(RelatedLookupMixin, Exact):
pass
class RelatedLessThan(RelatedLookupMixin, LessThan):
pass
class RelatedGreaterThan(RelatedLookupMixin, GreaterThan):
| 64 | 64 | 15 | 12 | 51 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedGreaterThan | RelatedGreaterThan | 126 | 127 | 126 | 126 | 36d224243f7668d59b41bc622134518b9b042279 | bigcode/the-stack | train |
8858fe72c2e5669ba40ebb00 | train | class | class RelatedExact(RelatedLookupMixin, Exact):
pass
| class RelatedExact(RelatedLookupMixin, Exact):
| pass
| (self.lookup_name)
root_constraint.add(
lookup_class(target.get_col(self.lhs.alias, source), val), AND)
return root_constraint.as_sql(compiler, connection)
return super(RelatedLookupMixin, self).as_sql(compiler, connection)
class RelatedExact(RelatedLookupMixin, E... | 64 | 64 | 13 | 10 | 54 | geelweb/django | django/db/models/fields/related_lookups.py | Python | RelatedExact | RelatedExact | 118 | 119 | 118 | 118 | e2bef5d3970cfd197138c414da4e3024a9f8b200 | bigcode/the-stack | train |
fc1451188db97435d85a5d2f | train | class | class MultiColSource(object):
contains_aggregate = False
def __init__(self, alias, targets, sources, field):
self.targets, self.sources, self.field, self.alias = targets, sources, field, alias
self.output_field = self.field
def __repr__(self):
return "{}({}, {})".format(
... | class MultiColSource(object):
| contains_aggregate = False
def __init__(self, alias, targets, sources, field):
self.targets, self.sources, self.field, self.alias = targets, sources, field, alias
self.output_field = self.field
def __repr__(self):
return "{}({}, {})".format(
self.__class__.__name__, sel... | from django.db.models.lookups import (
Exact, GreaterThan, GreaterThanOrEqual, In, IsNull, LessThan,
LessThanOrEqual,
)
class MultiColSource(object):
| 40 | 64 | 121 | 6 | 34 | geelweb/django | django/db/models/fields/related_lookups.py | Python | MultiColSource | MultiColSource | 7 | 20 | 7 | 7 | dc479eda3dd2b871c851b192f6ac708d15f0212d | bigcode/the-stack | train |
9f83504f98dbe79421e62ef6 | train | function | def create_concat_state(state, num_layers, RNN_type, BiRNN=None):
'''
GOAL : concatenate the tuple-type tensor (state) into a single tensor
state : input state is a tuple ofo MulticellRNN (i.e. output of MulticellRNN)
consist of only hidden states h for GRU and hid... | def create_concat_state(state, num_layers, RNN_type, BiRNN=None):
| '''
GOAL : concatenate the tuple-type tensor (state) into a single tensor
state : input state is a tuple ofo MulticellRNN (i.e. output of MulticellRNN)
consist of only hidden states h for GRU and hidden states c and h for LSTM
num_layers : number of layer... | STMCell(num_units, activation=activation_fn)
if not keep_prob is None:
cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=keep_prob, output_keep_prob=keep_prob) # state_keep_prob=keep_prob
cells.append(cell)
cell = tf.contrib.rnn.MultiRNNCell(cells)
return cell
### EXT... | 107 | 107 | 359 | 18 | 88 | loramf/mlforhealthlabpub | alg/Deep Temporal Predictive Clustering/utils_network.py | Python | create_concat_state | create_concat_state | 36 | 65 | 36 | 36 | d6dd4c3b65cb8aba10c15bbcb0e72e04a304f7e3 | bigcode/the-stack | train |
d49a3f5344af91ae8aa25afa | train | function | def create_rnn_cell(num_units, num_layers, keep_prob, RNN_type, activation_fn):
'''
GOAL : create multi-cell (including a single cell) to construct multi-layer RNN
num_units : number of units in each layer
num_layers : number of layers in MulticellRNN
keep_prob : kee... | def create_rnn_cell(num_units, num_layers, keep_prob, RNN_type, activation_fn):
| '''
GOAL : create multi-cell (including a single cell) to construct multi-layer RNN
num_units : number of units in each layer
num_layers : number of layers in MulticellRNN
keep_prob : keep probabilty [0, 1] (if None, dropout is not employed)
RNN_type : ei... |
import tensorflow as tf
import numpy as np
from tensorflow.contrib.layers import fully_connected as FC_Net
### CONSTRUCT MULTICELL FOR MULTI-LAYER RNNS
def create_rnn_cell(num_units, num_layers, keep_prob, RNN_type, activation_fn):
| 59 | 90 | 301 | 22 | 36 | loramf/mlforhealthlabpub | alg/Deep Temporal Predictive Clustering/utils_network.py | Python | create_rnn_cell | create_rnn_cell | 9 | 32 | 9 | 9 | 96aa475198fcedb95994d5fa461c50beca8a2e98 | bigcode/the-stack | train |
22f32d20bd0bb0c6ddfbd244 | train | function | def create_FCNet(inputs, num_layers, h_dim, h_fn, o_dim, o_fn, w_init, w_reg=None, keep_prob=1.0):
'''
GOAL : Create FC network with different specifications
inputs (tensor) : input tensor
num_layers : number of layers in FCNet
h_dim (int) : number of hidden ... | def create_FCNet(inputs, num_layers, h_dim, h_fn, o_dim, o_fn, w_init, w_reg=None, keep_prob=1.0):
| '''
GOAL : Create FC network with different specifications
inputs (tensor) : input tensor
num_layers : number of layers in FCNet
h_dim (int) : number of hidden units
h_fn : activation function for hidden layers (default: tf.nn.relu)
... | i-th layer, h state for LSTM
elif RNN_type == 'GRU':
tmp = state[i] ## i-th layer, h state for GRU
else:
print('ERROR: WRONG RNN CELL TYPE')
if i == 0:
rnn_state_out = tmp
else:
rnn_state_out = tf.concat([rnn_state_out, tm... | 141 | 141 | 473 | 36 | 104 | loramf/mlforhealthlabpub | alg/Deep Temporal Predictive Clustering/utils_network.py | Python | create_FCNet | create_FCNet | 69 | 108 | 69 | 69 | 4ae5f19e8e46cda2b31c2acff52eb4e68d2a0f5e | bigcode/the-stack | train |
446e1932a196673f2ebf096b | train | function | def py_or_json_opener(thing):
if thing.endswith('.json'):
with open(thing, 'r') as f:
try:
param_dict = json.load(f)
except Exception as e:
print(e)
raise e
meta_funcs = None
elif thing.endswith('.py'):
try:
... | def py_or_json_opener(thing):
| if thing.endswith('.json'):
with open(thing, 'r') as f:
try:
param_dict = json.load(f)
except Exception as e:
print(e)
raise e
meta_funcs = None
elif thing.endswith('.py'):
try:
loader = importlib.mac... | past_run = Run(term_dict.copy(), self.get_stats(term_dict))
self.past_runs.append(past_run)
elif args.dry_run:
print(f"DRY-RUN: Not running {term_dict} because it failed user-provided constraint function")
def py_or_json_opener(thing):
| 64 | 64 | 200 | 9 | 55 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | py_or_json_opener | py_or_json_opener | 336 | 357 | 336 | 336 | dc4cbc6e285eda38746ca56e1fda054c5f0d24be | bigcode/the-stack | train |
665ee5cb89104337959c34db | train | function | def finalize_log_dir(directory, cross_term, extra_info):
data = {
"config": cross_term,
"run_info": extra_info
}
with open(os.path.join(directory, METAFILE), 'w') as f:
json.dump(data, f, indent=2)
| def finalize_log_dir(directory, cross_term, extra_info):
| data = {
"config": cross_term,
"run_info": extra_info
}
with open(os.path.join(directory, METAFILE), 'w') as f:
json.dump(data, f, indent=2)
| if mean_temp <= temp:
print("GPU has finished cooling")
succ = True
break
print(mean_temp)
time.sleep(2)
if not succ:
print("GPU failed to fully cool")
return mean_temp
def finalize_log_dir(directory, cross_term, extra_... | 64 | 64 | 62 | 12 | 51 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | finalize_log_dir | finalize_log_dir | 424 | 430 | 424 | 424 | c00a41b897ed005dd6427726d0389bea0a070e61 | bigcode/the-stack | train |
bf107534fdf9814c752bcec8 | train | class | class PerfStats:
# List the loadgen keys we want
scenario_keys_set = {v for k, v in scenario_loadgen_log_keys.items()} | {"result_validity"}
_extra_key_set = {
"result_min_latency_ns",
"result_max_latency_ns",
"result_mean_latency_ns",
"result_50.00_percentile_latency_ns",
... | class PerfStats:
# List the loadgen keys we want
| scenario_keys_set = {v for k, v in scenario_loadgen_log_keys.items()} | {"result_validity"}
_extra_key_set = {
"result_min_latency_ns",
"result_max_latency_ns",
"result_mean_latency_ns",
"result_50.00_percentile_latency_ns",
"result_90.00_percentile_latency_ns",
"... | to what the harness already records)
METAFILE = "autotuneMETAFILE.json"
class ExecStats:
"""Named tuple that helps us understand how much work each autotuning session is doing."""
def __init__(self):
self.builds = 0
self.cached_builds = 0
self.runs = 0
self.cached_runs = 0
... | 136 | 137 | 457 | 14 | 122 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | PerfStats | PerfStats | 63 | 109 | 63 | 64 | d8df8e1970fe607162bbaff0ba33720fef41cc4d | bigcode/the-stack | train |
3041feaa070d98ca9d06613f | train | function | def execute(lam, description):
if args.dry_run:
print(f"DRY-RUN: {description}")
else:
return lam()
| def execute(lam, description):
| if args.dry_run:
print(f"DRY-RUN: {description}")
else:
return lam()
| , cross_term, extra_info):
data = {
"config": cross_term,
"run_info": extra_info
}
with open(os.path.join(directory, METAFILE), 'w') as f:
json.dump(data, f, indent=2)
def execute(lam, description):
| 64 | 64 | 33 | 7 | 57 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | execute | execute | 433 | 437 | 433 | 433 | 28860bc8b71425f0134dcd7be6286c95f8e451de | bigcode/the-stack | train |
1972cec74faa779a161c76a9 | train | function | def tee(cmd):
# Unused return, but we need to request output to get tee effect
run_command(cmd, get_output=True, tee=True)
| def tee(cmd):
# Unused return, but we need to request output to get tee effect
| run_command(cmd, get_output=True, tee=True)
| ("META")}
except Exception as e:
print(e)
raise e
else:
raise RuntimeError("Config doesn't end in .py or .json")
return param_dict, meta_funcs
def tee(cmd):
# Unused return, but we need to request output to get tee effect
| 64 | 64 | 33 | 21 | 42 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | tee | tee | 360 | 362 | 360 | 361 | c9deff7ea70685b618edd07c6748f8f97f0b4fdd | bigcode/the-stack | train |
c243caac5d16ee00bcbae6f5 | train | class | class ConfigGrid:
""" An iterable to enumerate through either
- A cartesian product of configurations (Default)
- User-provided configurations (as defined by META_search_callback)
Actual iterator is referred to as a "cross-term", which is a single
value in the cartesian product.
The cross-ter... | class ConfigGrid:
| """ An iterable to enumerate through either
- A cartesian product of configurations (Default)
- User-provided configurations (as defined by META_search_callback)
Actual iterator is referred to as a "cross-term", which is a single
value in the cartesian product.
The cross-term on its own isn't... | _log_summary.txt in a run/platform-specific subdirectory.
"""
verbose = args.verbose_stats
search_path = os.path.join(directory, "**/mlperf_log_detail.txt")
paths = [name for name in glob.glob(search_path, recursive=True)]
if not paths:
raise RuntimeError(f"Could not ... | 256 | 256 | 2,242 | 4 | 252 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | ConfigGrid | ConfigGrid | 112 | 333 | 112 | 112 | b021e68e05fdfbb604b5275bcaf35bdcfbfb8c88 | bigcode/the-stack | train |
e1231b9dc316ba990f3c48c3 | train | class | class Temperature:
"""A wrapper, non-instance class to do one-time initialization of get_system().
Initialization is done at the first call of logged_temp_wait akin to 'magic statics'
We need run-time initialization (rather than module-load-time) to support spoof_system_id"""
system = None
@classm... | class Temperature:
| """A wrapper, non-instance class to do one-time initialization of get_system().
Initialization is done at the first call of logged_temp_wait akin to 'magic statics'
We need run-time initialization (rather than module-load-time) to support spoof_system_id"""
system = None
@classmethod
def _get_... | :
loader = importlib.machinery.SourceFileLoader('mod', thing)
mod = loader.load_module()
attrs = [(k, v) for k, v in vars(mod).items() if not k.startswith('_')]
param_dict = {k: v for k, v in attrs if isinstance(v, list)}
meta_funcs = {k: v for k, v in attrs i... | 168 | 168 | 562 | 3 | 165 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | Temperature | Temperature | 365 | 421 | 365 | 365 | 47874f05baf98092751b560633bab49d1fb793d1 | bigcode/the-stack | train |
5d664432742f8389842a7d10 | train | class | class ExecStats:
"""Named tuple that helps us understand how much work each autotuning session is doing."""
def __init__(self):
self.builds = 0
self.cached_builds = 0
self.runs = 0
self.cached_runs = 0
def __str__(self):
return f"builds={self.builds}, cached_builds=... | class ExecStats:
| """Named tuple that helps us understand how much work each autotuning session is doing."""
def __init__(self):
self.builds = 0
self.cached_builds = 0
self.runs = 0
self.cached_runs = 0
def __str__(self):
return f"builds={self.builds}, cached_builds={self.cached_buil... | , Scenario, config_ver_to_workload_setting
from code.main import main, parse_main_args
from configs.configuration import ConfigRegistry
# For metadata and stats we record for each run (in addition to what the harness already records)
METAFILE = "autotuneMETAFILE.json"
class ExecStats:
| 64 | 64 | 102 | 4 | 60 | ctuning/inference_results_v1.1 | open/Dell/scripts/autotune/grid.py | Python | ExecStats | ExecStats | 50 | 60 | 50 | 50 | 80b25106e753a32cb5f66a9f88922c139af92f38 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.