import json
from datetime import datetime as dt
import datetime
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from rest_framework.decorators import api_view
from rest_framework.response import Response

from rest_framework.response import Response
from rest_framework.decorators import api_view

from .models import *
from .serializers import *

def index(request):
    return HttpResponse("Index page for website")

@api_view(['POST'])
def join_team(request):
	user_id = request.data['user_id']
	team_id = request.data['team_id']
	user_account = Account.objects.get(id=user_id)

	team_join = Team.objects.get(id=team_id)
	serial_team = TeamSerializer(team_join)
	league_id = serial_team.data['league']

	league = League.objects.get(id=league_id)
	league_serializer = LeagueSerializer(league)
	teams_obj = Team.objects.filter(league=league_id)
	serial_teams = TeamSerializer(teams_obj, context={'request': request}, many=True)

	if(len(serial_team.data['players']) == league_serializer.data['player_limit']):
		return JsonResponse({'status': 'FullTeam'})
	for team in serial_teams.data:
		if team['id'] != team_id:
			if user_id in team['players']:
				return JsonResponse({'status': 'PlayerExists'})
	team_join.players.add(user_account)
	team_join.save()
	return JsonResponse({'status': 'ok'})

@api_view(['POST'])
def leave_team(request):
    user_id = request.data['user_id']
    team_id = request.data['team_id']
    user_account = Account.objects.get(id=user_id)
    team = Team.objects.get(id=team_id)
    team.players.remove(user_account)
    team.save()
    return JsonResponse({'status': 'ok'})

@api_view(['POST'])
def create_sport(request):
	serializer = SportSerializer(data=request.data)
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['POST'])
def create_league(request):
	serializer = LeagueSerializer(data=request.data)
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['POST'])
def create_post(request):
	serializer = PostSerializer(data=request.data)
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['POST'])
def createAccount(request):
	body = json.loads(request.body.decode('utf-8'))
	email = body["email"]
	if not Account.objects.filter(email=email).exists():
		serializer = AccountSerializer(data=request.data)
		if serializer.is_valid():
			serializer.save()
		return Response(serializer.data)
	return JsonResponse({'status': 'ok'})

@api_view(['GET'])
def getSportsList(request):
    data = Sport.objects.all()

    sports = SportSerializer(data, context={'request': request}, many=True)

    return Response(sports.data)

@api_view(['GET'])
def getLeagueList(request):
    data = League.objects.all()

    leagues = LeagueSerializer(data, context={'request': request}, many=True)

    return Response(leagues.data)

@api_view(['GET'])
def getTeamList(request):
    data = Team.objects.all()

    teams = TeamSerializer(data, context={'request': request}, many=True)

    return Response(teams.data)

@api_view(['GET'])
def getPosts(request):
	data = Post.objects.all()

	posts_serializer = PostSerializer(data, context={'request': request}, many=True)

	for i in range(len(posts_serializer.data)):
		user = Account.objects.get(id=posts_serializer.data[i]['owner'])
		posts_serializer.data[i]['display_name'] = user.display_name

		date = dt.strptime(posts_serializer.data[i]['posted_date'], '%Y-%m-%dT%H:%M:%SZ')
		posts_serializer.data[i]['posted_date'] = date.strftime("%m-%d-%Y %I:%M %p")

	return Response(posts_serializer.data)

@api_view(['GET'])
def getPosts(request):
	data = Post.objects.all()

	posts_serializer = PostSerializer(data, context={'request': request}, many=True)

	for i in range(len(posts_serializer.data)):
		user = Account.objects.get(id=posts_serializer.data[i]['owner'])
		posts_serializer.data[i]['display_name'] = user.display_name

		date = dt.strptime(posts_serializer.data[i]['posted_date'], '%Y-%m-%dT%H:%M:%SZ')
		posts_serializer.data[i]['posted_date'] = date.strftime("%m-%d-%Y %I:%M %p")

	return Response(posts_serializer.data)

@api_view(['GET'])
def getAccountByEmail(request, email):
	if not Account.objects.filter(email=email):
		return JsonResponse({"status":"DoesNotExist"})
	account = Account.objects.get(email=email)
	serializer = AccountSerializer(instance=account)
	return Response(serializer.data)

@api_view(['POST'])
def generateGameSchedule(request):
	leagueId = request.data['leagueId']
	#number of total games to played throughout season
	gameNum = int(request.data['gameNum'])
	#int representing day of week, 0 Monday, 6 Sunday
	gameDay = int(request.data['gameDay'])
	#time that games will begin, in minutes
	startTime = request.data['startTime'].split(":")
	startTime = int(startTime[0])*60 + int(startTime[1])
	#length of each game, in minutes
	gameLength = int(request.data['gameLength'])
	#games to be played by each team per day
	teamGamesPerDay = int(request.data['teamGamesPerDay'])

	# TODO:'loactionNum': for case of multiple usable locations
	#	         i.e. 2 or more courts/fields can be used at a time
	#	   'location': string of location name
	#			 i.e. 'Otter Sports Center'

	teams = list(Team.objects.filter(league=leagueId))
	leagueStart = League.objects.get(id=leagueId).start_date
	if leagueStart.weekday() < gameDay:
		leagueStart += datetime.timedelta(days=gameDay)
	elif leagueStart.weekday() > gameDay:
		leagueStart += 7-leagueStart.weekday() + datetime.timedelta(days=gameDay)

	leagueStart = datetime.datetime(leagueStart.year, leagueStart.month, leagueStart.day) + datetime.timedelta(minutes=startTime)

	games = generateSchedule(teams, gameNum, leagueStart, gameLength, teamGamesPerDay)
	for game in games:
		game.save()
	serializer = GameSerializer(games, context={'request': request}, many=True)
	return Response(serializer.data)

def generateSchedule(teams, gameNum, leagueStart, gameLength, teamGamesPerDay):
	# TODO:
	# case of multiple usable locations
	# how to determine home/away
	# what location will the game be played

	if len(teams) % 2 != 0:
		teams.append(None)
	games = []

	currDateTime = leagueStart
	currGamesPerDay = 0
	currWeek = 0
	for i in range(gameNum):
		if currGamesPerDay == teamGamesPerDay:
			currGamesPerDay = 0
			currWeek += 1
			currDateTime = leagueStart + datetime.timedelta(weeks=currWeek)
		matrix = [teams[:len(teams)//2], teams[len(teams)//2:][::-1]]
		for j in range(len(matrix[0])):
			if matrix[0][j] != None and matrix[1][j] != None:
				game = Game(league=teams[0].league,
							start_time=str(currDateTime),
							home_team=matrix[0][j],
							away_team=matrix[1][j])
				games.append(game)
				currDateTime += datetime.timedelta(minutes=gameLength)

		currGamesPerDay += 1
		teams = [teams[0]] + [teams[-1]] + teams[1:-1]
	return games

@api_view(['POST'])
def generatePlayoffs(request):
	leagueId = request.data['leagueId']
	startDay = request.data['startDay']
	#int representing day of week, 0 Monday, 6 Sunday
	gameDay = int(request.data['gameDay'])
	#time that games will begin, in minutes
	startTime = request.data['startTime'].split(":")
	startTime = int(startTime[0])*60 + int(startTime[1])
	#length of each game, in minutes
	gameLength = int(request.data['gameLength'])
	#games to be played by each team per day
	teamGamesPerDay = int(request.data['teamGamesPerDay'])
	isBracket = request.data['isBracket']
	teamNum = request.data['teamNum']

	playoffTeams = getPlayoffTeams(leagueId, teamNum)

	if not isBracket:
		# round robin style tournament
		# should be able to use the normal game schedule function
		# games = generateSchedule(playoffTeams, len(playoffTeams)-1, startDay, gameLength, teamGamesPerDay)
		pass
	else:
		# bracket tournament
		pass

# def generateBracket():

def getPlayoffTeams(leagueId, numTeams):
	allTeams = Team.objects.filter(league=leagueId)
	ranked = sorted(allTeams)[::-1]
	cutoff = ranked[:numTeams]
	return cutoff

def updateRecords(game, first_entry, prev_home, prev_away):

	home_team = game.home_team
	away_team = game.away_team
	home_players = home_team.players.all()
	away_players = away_team.players.all()

	# if scores were previously entered, deduct wins/losses accordingly
	if not first_entry:
		if prev_home == prev_away:
			home_team.ties -= 1
			away_team.ties -= 1
			home_players = updatePlayerRecords(home_players, 0, -1)
			away_players = updatePlayerRecords(away_players, 0, -1)
		elif prev_home > prev_away:
			home_team.wins -= 1
			away_team.losses -= 1
			home_players = updatePlayerRecords(home_players, 1, -1)
			away_players = updatePlayerRecords(away_players, 2, -1)
		else:
			home_team.losses -= 1
			away_team.wins -= 1
			home_players = updatePlayerRecords(home_players, 2, -1)
			away_players = updatePlayerRecords(away_players, 1, -1)

	if game.home_score == game.away_score:
		home_team.ties += 1
		away_team.ties += 1
		home_players = updatePlayerRecords(home_players, 0, 1)
		away_players = updatePlayerRecords(away_players, 0, 1)

	elif game.home_score > game.away_score:
		home_team.wins += 1
		away_team.losses += 1
		home_players = updatePlayerRecords(home_players, 1, 1)
		away_players = updatePlayerRecords(away_players, 2, 1)

	else:
		home_team.losses += 1
		away_team.wins += 1
		home_players = updatePlayerRecords(home_players, 2, 1)
		away_players = updatePlayerRecords(away_players, 1, 1)

	home_team.save()
	away_team.save()
	for player in home_players:
		player.save()
	for player in away_players:
		player.save()

# field: 0 = ties, 1 = wins, 2 = losses
# delta: change in value
def updatePlayerRecords(players, field, delta):
	for player in players:
		if field == 0:
			player.ties += delta
		elif field == 1:
			player.wins += delta
		elif field == 2:
			player.losses += delta

	return players

@api_view(['PUT'])
def updateScores(request, leagueId):
	games = request.data
	for game in games:
		if game['away_score'] and game['home_score']:
			game_obj = Game.objects.get(id=game['id'])
			first_entry = not game_obj.home_score or not game_obj.away_score
			prev_home = game_obj.home_score
			prev_away = game_obj.away_score
			game_obj.home_score = game['home_score']
			game_obj.away_score = game['away_score']
			updateRecords(game_obj, first_entry, prev_home, prev_away)
			game_obj.save()
	return JsonResponse({'status': 'ok'})

@api_view(['GET'])
def getEventsByLeague(request, leagueId):
	games = Game.objects.filter(league=leagueId)
	game_serializer = GameSerializer(games, context={'request': request}, many=True)
	return Response(game_serializer.data)

@api_view(['GET'])
def getEventsByUser(request, userId):
	# grab teams based on userId
	team_data = Team.objects.filter(players=userId)
	team_serializer = TeamSerializer(team_data, context={'request': request}, many=True)

	# grab league ids and team ids from the list of teams
	team_ids = []
	league_ids = []
	for i in range(len(team_serializer.data)):
		if team_serializer.data[i]["league"] not in league_ids:
			league_ids.append(team_serializer.data[i]["league"])
		if team_serializer.data[i]["id"] not in team_ids:
			team_ids.append(team_serializer.data[i]["id"])

	# grab leagues from list of league ids
	league_data = League.objects.filter(id__in=league_ids)
	league_serializer = LeagueSerializer(league_data, context={'request': request}, many=True)

	# grab sport ids from list of leagues
	sport_ids = []
	for i in range(len(league_serializer.data)):
		if league_serializer.data[i]["sport"] not in sport_ids:
			sport_ids.append(league_serializer.data[i]["sport"])

	# grab sports from list of sport ids
	sport_data = Sport.objects.filter(id__in=sport_ids)
	sport_serializer = SportSerializer(sport_data, context={'request': request}, many=True)

	# grab games from team_ids
	game_data = Game.objects.filter(home_team__in=team_ids) | Game.objects.filter(away_team__in=team_ids)
	game_serializer = GameSerializer(game_data, context={'request': request}, many=True)

	#put together events to be able to return one list
	events = []
	for game in game_serializer.data:
		leagueTitle = ''
		sportId = 0
		sportTitle = ''
		teamName = ''
		home = False

		gameTime = dt.strptime(game['start_time'], '%Y-%m-%dT%H:%M:%SZ')

		if gameTime > dt.today():

			for i in range(len(team_serializer.data)):
				if team_serializer.data[i]['id'] == game['home_team']:
					home = True
					teamName = team_serializer.data[i]['team_name']
					break
				elif team_serializer.data[i]['id'] == game['away_team']:
					home = False
					teamName = team_serializer.data[i]['team_name']
					break

			for i in range(len(league_serializer.data)):
				if league_serializer.data[i]['id'] == game['league']:
					sportId = league_serializer.data[i]['sport']
					leagueTitle = league_serializer.data[i]['league_name']
					break

			for i in range(len(sport_serializer.data)):
				if sport_serializer.data[i]['id'] == sportId:
					sportTitle = sport_serializer.data[i]['sport_name']
					break

			event = sportTitle + ': ' + leagueTitle + ' - ' + teamName
			strGameTime = gameTime.strftime("%m-%d-%Y %I:%M %p")
			pair = {'gameTime': strGameTime, 'gameTitle':event, 'homeTeam': home}
			events.append(pair)

	events.sort(key = lambda x: dt.strptime(x['gameTime'], '%m-%d-%Y %I:%M %p'))

	return Response(events)

@api_view(['GET'])
def getProfileInfoByUser(request, userId):
	# grab teams based on userId
	team_data = Team.objects.filter(players=userId)
	team_serializer = TeamSerializer(team_data, context={'request': request}, many=True)

	# grab league ids and team ids from the list of teams
	team_ids = []
	league_ids = []
	for i in range(len(team_serializer.data)):
		if team_serializer.data[i]["league"] not in league_ids:
			league_ids.append(team_serializer.data[i]["league"])
		if team_serializer.data[i]["id"] not in team_ids:
			team_ids.append(team_serializer.data[i]["id"])

	# grab leagues from list of league ids
	league_data = League.objects.filter(id__in=league_ids)
	league_serializer = LeagueSerializer(league_data, context={'request': request}, many=True)

	# grab sport ids from list of leagues
	sport_ids = []
	for i in range(len(league_serializer.data)):
		if league_serializer.data[i]["sport"] not in sport_ids:
			sport_ids.append(league_serializer.data[i]["sport"])

	# grab sports from list of sport ids
	sport_data = Sport.objects.filter(id__in=sport_ids)
	sport_serializer = SportSerializer(sport_data, context={'request': request}, many=True)

	# grab games from team_ids
	game_data = Game.objects.filter(home_team__in=team_ids) | Game.objects.filter(away_team__in=team_ids)
	game_serializer = GameSerializer(game_data, context={'request': request}, many=True)

	#put together events to be able to return one list
	upcoming_games = []

	for team in team_serializer.data:
		team_name = team['team_name']
		league = League.objects.get(pk=team['league'])
		league_name = league.league_name
		vs = ''
		outcome = ''
		score = ''

		if league.end_date > dt.today().date():
			upcoming_game_data = []
			past_game_data = []
			for game in game_serializer.data:
				if game['home_team'] == team['id'] or game['away_team'] == team['id']:
					home_score = game['home_score']
					away_score = game['away_score']
					gameTime = dt.strptime(game['start_time'], '%Y-%m-%dT%H:%M:%SZ')
					if gameTime >= dt.today():
						if game['home_team'] == team['id']:
							other_team = Team.objects.get(pk=game['away_team'])
							vs = other_team.team_name
						elif game['away_team'] == team['id']:
							other_team = Team.objects.get(pk=game['home_team'])
							vs = other_team.team_name
						strGameTime = gameTime.strftime("%m-%d-%Y %I:%M %p")
						pair = {'gameTime': strGameTime, 'vs':vs}
						upcoming_game_data.append(pair)
					elif gameTime < dt.today():
						if game['home_team'] == team['id']:
							other_team = Team.objects.get(pk=game['away_team'])
							vs = other_team.team_name
							if game['home_score'] > game['away_score']:
								outcome = 'W'
							elif game['home_score'] < game['away_score']:
								outcome = 'L'
							else:
								outcome = 'T'
						elif game['away_team'] == team['id']:
							other_team = Team.objects.get(pk=game['home_team'])
							vs = other_team.team_name
							if game['home_score'] > game['away_score']:
								outcome = 'L'
							elif game['home_score'] < game['away_score']:
								outcome = 'W'
							else:
								outcome = 'T'
						strGameTime = gameTime.strftime("%m-%d-%Y %I:%M %p")
						pair = {'gameTime': strGameTime, 'vs':vs, 'outcome':outcome,
						'home_score': home_score, 'away_score': away_score}
						past_game_data.append(pair)
			pair = {'team_name': team_name,
					'league_name':league_name,
					'upcoming_game_data': upcoming_game_data,
					'past_game_data': past_game_data}
			upcoming_games.append(pair)

	return Response(upcoming_games)

@api_view(['GET'])
def getProfilePastInfoByUser(request, userId):
	# grab teams based on userId
	team_data = Team.objects.filter(players=userId)
	team_serializer = TeamSerializer(team_data, context={'request': request}, many=True)

	# grab league ids and team ids from the list of teams
	team_ids = []
	league_ids = []
	for i in range(len(team_serializer.data)):
		if team_serializer.data[i]["league"] not in league_ids:
			league_ids.append(team_serializer.data[i]["league"])
		if team_serializer.data[i]["id"] not in team_ids:
			team_ids.append(team_serializer.data[i]["id"])

	# grab leagues from list of league ids
	league_data = League.objects.filter(id__in=league_ids)
	league_serializer = LeagueSerializer(league_data, context={'request': request}, many=True)

	# grab sport ids from list of leagues
	sport_ids = []
	for i in range(len(league_serializer.data)):
		if league_serializer.data[i]["sport"] not in sport_ids:
			sport_ids.append(league_serializer.data[i]["sport"])

	# grab sports from list of sport ids
	sport_data = Sport.objects.filter(id__in=sport_ids)
	sport_serializer = SportSerializer(sport_data, context={'request': request}, many=True)

	# grab games from team_ids
	game_data = Game.objects.filter(home_team__in=team_ids) | Game.objects.filter(away_team__in=team_ids)
	game_serializer = GameSerializer(game_data, context={'request': request}, many=True)

	#put together events to be able to return one list
	upcoming_games = []

	for team in team_serializer.data:
		team_name = team['team_name']
		league = League.objects.get(pk=team['league'])
		league_name = league.league_name
		vs = ''
		outcome = ''
		leagueTime = league.end_date # dt.strptime(league.end_date, '%Y-%m-%dT%H:%M:%SZ')

		if leagueTime < dt.today().date():
			game_data = []
			for game in game_serializer.data:
				if game['home_team'] == team['id'] or game['away_team'] == team['id']:
					gameTime = dt.strptime(game['start_time'], '%Y-%m-%dT%H:%M:%SZ')
					home_score = game['home_score']
					away_score = game['away_score']
					#if user is on the home team
					if game['home_team'] == team['id']:
						other_team = Team.objects.get(pk=game['away_team'])
						vs = other_team.team_name
						if game['home_score'] > game['away_score']:
							outcome = 'W'
						elif game['home_score'] < game['away_score']:
							outcome = 'L'
						else:
							outcome = 'T'
					# if user is on the away team
					elif game['away_team'] == team['id']:
						other_team = Team.objects.get(pk=game['home_team'])
						vs = other_team.team_name
						if game['home_score'] > game['away_score']:
							outcome = 'L'
						elif game['home_score'] < game['away_score']:
							outcome = 'W'
						else:
							outcome = 'T'
					strGameTime = gameTime.strftime("%m-%d-%Y %I:%M %p")
					pair = {'gameTime': strGameTime, 'vs':vs, 'outcome':outcome,
						'home_score': home_score, 'away_score': away_score}
					game_data.append(pair)
			pair = {'team_name': team_name, 'league_name':league_name, 'game_data': game_data}
			upcoming_games.append(pair)

	return Response(upcoming_games)

@api_view(['GET'])
def getTeamsByLeague(request,leagueId):
	team_data = Team.objects.filter(league=leagueId)
	team_data = sorted(team_data)[::-1]
	team_serializer = TeamSerializer(team_data, context={'request': request}, many=True)

	for i in range(len(team_serializer.data)):
		totalGames = team_serializer.data[i]['wins'] + team_serializer.data[i]['losses'] + team_serializer.data[i]['ties']
		wpt = "0.000"
		if totalGames != 0:
			winper = team_serializer.data[i]['wins'] / totalGames
			wpt = "{:.3f}".format(winper)

		team_serializer.data[i]['wpt'] = wpt

	return Response(team_serializer.data)

@api_view(['GET'])
def getAccounts(request):
	account = Account.objects.all()
	account_data = AccountSerializer(account, context={'request': request}, many=True)
	return Response(account_data.data)

@api_view(['DELETE'])
def deletePost(request, postId):
	post = Post.objects.get(id=postId)
	post.delete()
	return HttpResponse('deleted')

@api_view(['PUT'])
def editPost(request, postId):
	post = Post.objects.get(id=postId)
	serializer = PostSerializer(post, data=request.data)
	if serializer.is_valid():
		serializer.save()

	return HttpResponse('updated')

@api_view(['POST'])
def createTeam(request):
	serializer = TeamSerializer(data=request.data)
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['GET'])
def getTeamById(request, teamId):
	team = Team.objects.get(id=teamId)
	team_serializer = TeamSerializer(team, context={'request': request})
	return Response(team_serializer.data)

@api_view(['GET'])
def getLeagueById(request, leagueId):
	league = League.objects.get(id=leagueId)
	league_serializer = LeagueSerializer(league, context={'request': request})
	return Response(league_serializer.data)

@api_view(['GET'])
def getSportById(request, sportId):
	sport = Sport.objects.get(id=sportId)
	sport_serializer = SportSerializer(sport, context={'request': request})
	return Response(sport_serializer.data)

@api_view(['GET'])
def getPlayersByTeamId(request, teamId):
	team = Team.objects.get(id=teamId)
	team_serializer = TeamSerializer(team, context={'request': request})

	players = Account.objects.filter(id__in=team_serializer.data['players'])
	player_serializer = AccountSerializer(players, context={'request': request}, many=True)
	return Response(player_serializer.data)

@api_view(['GET'])
def getGamesByTeam(request, teamId):
	game_data = Game.objects.filter(home_team=teamId) | Game.objects.filter(away_team=teamId)
	game_serializer = GameSerializer(game_data, context={'request': request}, many=True)

	team_data = Team.objects.all()
	team_serializer = TeamSerializer(team_data, context={'request': request}, many=True)

	for i in range(len(team_serializer.data)):
		for j in range(len(game_serializer.data)):
			if team_serializer.data[i]['id'] == game_serializer.data[j]['home_team']:
				game_serializer.data[j]['home_name'] = team_serializer.data[i]['team_name']
			if team_serializer.data[i]['id'] == game_serializer.data[j]['away_team']:
				game_serializer.data[j]['away_name'] = team_serializer.data[i]['team_name']
			gameTime = dt.strptime(game_serializer.data[j]['start_time'], '%Y-%m-%dT%H:%M:%SZ')
			strGameTime = gameTime.strftime("%m-%d-%Y %I:%M %p")

			game_serializer.data[j]['format_start_time'] = strGameTime

	return Response(game_serializer.data)

@api_view(['DELETE'])
def deletePost(request, postId):
	post = Post.objects.get(id=postId)
	post.delete()
	return HttpResponse('deleted')

@api_view(['PUT'])
def editPost(request, postId):
	post = Post.objects.get(id=postId)
	serializer = PostSerializer(post, data=request.data)
	if serializer.is_valid():
		serializer.save()

	return HttpResponse('updated')

@api_view(['DELETE'])
def deleteTeam(request, teamId):
	team = Team.objects.get(id=teamId)
	team.delete()
	return HttpResponse('deleted')

@api_view(['PUT'])
def editPlayers(request, teamId):
	team = Team.objects.get(id=teamId)
	serializer = TeamSerializer(team, data=request.data)
	if serializer.is_valid():
		serializer.save()

	return HttpResponse('updated')
@api_view(['GET'])
def getWinLossByUser (request, userId):
	user = Account.objects.get(id=userId)
	pair = {'wins': user.wins, 'losses':user.losses, 'ties': user.ties}
	return Response(pair)


#coding: UTF-8

def parceKey(line):
    cp_line = line
    if cp_line.strip().find(" ") != -1:
        return cp_line.strip().split(" ")[0]
    return cp_line.strip()

def parceVal(line):
    cp_line = line
    if cp_line.strip().find(" ") != -1:
        return cp_line.strip()[cp_line.strip().find(" "):].strip()
    return ""

def parceHost(line, hosts, count):
    if not line:
        pass
    elif(line.find("{") != -1):
        hosts.append(dict())
        hosts[count]["type"] = "host"
    elif(line.find("}") != -1):
        count += 1
    elif(line.strip()[0] != '#'):
        key = parceKey(line)
        var = parceVal(line.decode("UTF-8"))
        if key == "host_name":
            hosts[count]["host_name"] = var
        elif(key == 'alias'):
            hosts[count]["alias"] = var
        elif(key == 'parents'):
            hosts[count]["parents"] = var
        elif(key == 'address'):
            hosts[count]["address"] = var
    return count

def parceGroup(line, groups, count):
    if not line:
        pass
    elif(line.find("{") != -1):
        groups.append(dict())
        groups[count]["type"] = 'group'
    elif(line.find("}") != -1):
        count += 1
    elif(line.strip()[0] != '#'):
        key = parceKey(line)
        var = parceVal(line.decode("UTF-8"))
        if(key == 'hostgroup_name'):
            groups[count]["hostgroup_name"] = var
        elif(key == 'alias'):
            groups[count]["alias"] = var
        elif(key == 'members'):
            if var != "":
                groups[count]["members"] = var.split(',')
    return count

def parceService(line, services, count):
    if not line:
        pass
    elif(line.find("{") != -1):
        services.append(dict())
        services[count]["type"] = "service"
    elif(line.find("}") != -1):
        count += 1
    elif(line.strip()[0] != '#'):
        key = parceKey(line)
        var = parceVal(line.decode("UTF-8"))
        if(key == 'hostgroup_name'):
            services[count]["hostgroup_name"] = var
        elif(key == 'service_description'):
            services[count]["service_description"] = var
        elif(key == 'check_command'):
            services[count]["check_command"] = var
        elif(key == 'notification_interval'):
            services[count]["notification_interval"] = var
    return count

def parceType(line):
    if not (line.strip() == "}" or not line):
        cp_line = line.strip()
        if cp_line.strip().find(" ") != -1:
            return cp_line.split(" ")[1].replace("{", "")
    return ""

def choseType(line, function):
    typeDef = parceType(line)
    if typeDef == "host":
        return parceHost
    elif typeDef == "hostgroup":
        return parceGroup
    elif typeDef == "service":
        return parceService
    else:
        return function

def parceData(data, log):
    mass = []
    count = 0
    log['stages'].append('Парсинг парметров')
    try:
        function = parceHost
        for line in data:
            function = choseType(line, function)
            count = function(line, mass, count)
        log['errors'].append("Отсутствуют")
    except:
        log['errors'].append("Что-то пошло не так")
    return True, mass

def parceFilename(line):
    cp_line = line.strip()
    if(cp_line[len(cp_line)-1] == '/'):
        return ""
    elif(cp_line[len(cp_line)-4:] != '.cfg'):
        return ""
    return cp_line

def parceListOfFile(data):
    filename_list = []
    for line in data:
        line = parceFilename(line)
        if line:
            filename_list.append(line)
    return filename_list


from django.conf import settings
from django.shortcuts import render, loader, redirect
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from relight.models import UserInfo, Shop_Profile, Cus_Profile, Event
from relight.forms.change import Change_UserInfo_Form, Change_Cus_Form, Change_Shop_Form, Change_Event_Form
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
# Create your views here.

@login_required
def change_profile(request):
    user = request.user
    if user.s_or_c == "cus":
        profile = Cus_Profile.objects.get(cus=user.id)
    else:
        profile = Shop_Profile.objects.get(shop=user.id)

    if request.method == 'GET':
        initial_user = {
            'userid': user.userid,
            'email': user.email,
        }
        form_user = Change_UserInfo_Form(initial=initial_user)
        if user.s_or_c == "cus":
            initial_cus = {
                'name': profile.name,
                'gender': profile.gender,
                'self_introduction': profile.self_introduction,
                'cus': user.userid,
            }
            form_prof = Change_Cus_Form(initial=initial_cus)
        else:
            initial_shop = {
                'name': profile.name,
                'online_address': profile.online_address,
                'self_introduction': profile.self_introduction,
                'shop': user.userid,
            }
            form_prof = Change_Shop_Form(initial=initial_shop)

    else:
        form_user = Change_UserInfo_Form(request.POST, instance=user)

        if user.s_or_c == "cus":
            form_prof = Change_Cus_Form(
                request.POST, request.FILES or None, instance=profile)
        else:
            form_prof = Change_Shop_Form(
                request.POST, request.FILES or None, instance=profile)
        if form_prof.is_valid():
            if form_user.is_valid():
                user_changed = form_user.save(request.POST, user, commit=False)
                user_changed.save()
                changed_prof = form_prof.save(
                    request.POST, request.FILES or None, user_changed, profile, commit=False)
                changed_prof.save()
                login(request, user_changed)
                return redirect('/profile')
        else:
            print('user_regist false is_valid')

    template = loader.get_template('relight/change_profile.html')
    context = {
        'form_prof': form_prof,
        'form_user': form_user,
        'user': user,
        'profile': profile,
    }
    return HttpResponse(template.render(context, request))

@login_required
def change_event(request, event_title):
    user = request.user
    event = Event.objects.get(title=event_title)
    if user.s_or_c == "cus":
        profile = Cus_Profile.objects.get(cus=user.id)
    else:
        profile = Shop_Profile.objects.get(shop=user.id)

    if request.method == 'GET':
        initial_event = {
            'title': event_title,
            'detail': event.detail,
            'questionnaire_url': event.questionnaire_url,
        }
        form = Change_Event_Form(initial=initial_event)

    else:
        form = Change_Event_Form(request.POST, instance=event)

        if form.is_valid():
            event_changed = form.save(
                request.POST, request.FILES or None, event, commit=False)
            event_changed.save()
            url = '/event/'+event_changed.title
            return redirect(url)
        else:
            print('user_regist false is_valid')

    template = loader.get_template('relight/change_event.html')
    context = {
        'event': event,
        'form': form,
        'user': user,
        'profile': profile,
    }
    return HttpResponse(template.render(context, request))

def delete_event(request, event_title):
    user = request.user
    event = Event.objects.get(title=event_title)
    if user.s_or_c == "cus":
        profile = Cus_Profile.objects.get(cus=user.id)
    else:
        profile = Shop_Profile.objects.get(shop=user.id)

    if request.method == 'POST':
        print("post")
        if 'yes' in request.POST:
            print("post yes")
            event.delete()
        else:
            return redirect('/profile')
        return redirect('/profile')
    template = loader.get_template('relight/delete_event.html')
    context = {
        'event': event,
        'user': user,
        'profile': profile,
    }
    return HttpResponse(template.render(context, request))


####
# Copyright by Thomas Baquet
#
# (for this file:)
# Copyright by Mariano Iglesias
####

import Options, Utils
from os import unlink, symlink, chdir, environ
from os.path import exists

srcdir = "."
blddir = "build"
VERSION = "0.7.5"

def set_options(opt):
  opt.tool_options("compiler_cxx")
  opt.add_option('--debug', action='store_true', help='Run tests with nodeunit_g')
  opt.add_option('--warn', action='store_true', help='Enable extra -W* compiler flags')

def configure(conf):
  conf.check_tool("compiler_cxx")
  conf.check_tool("node_addon")

  # Enables all the warnings that are easy to avoid
  conf.env.append_unique('CXXFLAGS', ["-Wall"])
  if Options.options.warn:
    # Extra warnings
    conf.env.append_unique('CXXFLAGS', ["-Wextra"])
    # Extra warnings, gcc 4.4
    conf.env.append_unique('CXXFLAGS', ["-Wconversion", "-Wshadow", "-Wsign-conversion", "-Wunreachable-code", "-Wredundant-decls", "-Wcast-qual"])

  drizzle_include = environ.get("DRIZZLE_INCLUDE_DIR", "/usr/include/libdrizzle")
  if drizzle_include:
      conf.env.append_unique('CXXFLAGS', [ '-I' + drizzle_include ])

  drizzle_lib = environ.get("DRIZZLE_LIB_DIR", "/usr/lib")
  if drizzle_lib:
      conf.env.append_unique('LINKFLAGS', [ '-L' + drizzle_lib ])

  if not conf.check_cxx(lib='drizzle'):
    conf.fatal("Missing libdrizzle from drizzle package")

  if not conf.check_cxx(header_name='drizzle.h'):
    conf.fatal("Missing drizzle.h header from drizzle package")

  # c++11
  conf.env.append_unique('CXXFLAGS', ['-std=c++0x'])

def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon")
  obj.target = "drizzle-js"
  obj.source = "src/drizzle.cpp src/binding.cpp src/async.cpp"
  obj.includes = "."
  obj.uselib = "DRIZZLE"


'''
Created on Aug 4, 2015

@author: jivan
'''

import jsonpickle
from unittest import TestCase

from combine import test_program

jp_test_cases = [
    ]

class TestMyPreviouslyUntestedClass(TestCase):
    TestClass = test_program
    test_instance = test_program()

    @classmethod
    def get_method_name(cls, idx, method_args, method_kwargs):
        method_name, sequences, allele_lengths_list = method_args
	# Dynamically created method name
        mn = 'test_{:02}_{}_args_{}_kwargs_{}'.format(
                    idx, method_name, len(method_args), len(method_kwargs))
        return mn

    def perform_one_tc(self, tc):
        tested_method_name = tc[0]
        args = tc[1]
        kwargs = tc[2]
        expected_result = tc[3]

        result = getattr(self.test_instance, tested_method_name)(*args, **kwargs)
        self.assertEqual(result, expected_result)

    @classmethod
    def _add_method(cls, method_name, testcase):
        """ @brief: This is used to add a separate method for each of the test cases so they
                run individually instead of en masse.
        """
        def new_test_method(self, tc=testcase):
            self.perform_one_tc(tc)

        new_method.__name__ = method_name
        from types import MethodType
        m = MethodType(new_method, None, cls)
        setattr(cls, method_name, m)

for i, jp_testcase in enumerate(jp_test_cases):
    test_case = jsonpickle.decode(jp_testcase, keys=True)
    tested_method_args = test_case[1]
    tested_method_kwargs = test_case[2]

    test_method_name = \
        TestMyPreviouslyUntestedClass.get_method_name(i, tested_method_args, tested_method_kwargs)
    TestMyPreviouslyUntestedClass._add_method(test_method_name, test_case)


from blueServer import blueServer
from configParser import configParser,calibrationParser
from screenPrinter import screenPrinter
from unConnected import unConnected
import logging

if __name__ == '__main__':
    ## Set up logging
    logger = logging.getLogger('iTelescope')
    hdlr = logging.FileHandler('iTelescope.log')
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    #logger.setLevel(logging.WARNING)
    ######

    ## name config files
    cfgP = configParser("config.xml")
    calP = calibrationParser("instrumentCalibration.xml")
    ######
    while True:
        try:
            ## Start the unConnected thread
            basic = unConnected(cfgP,calP,logger)
            basic.start()

            ## Start the bluetooth server and listen
            theServer = blueServer(logger)
            theServer.listenForConnection()

            basic.endThread()## terminate the unConnected thread on connection
            ######

            ## On connection exchange config files and enter config mode
            theServer.configMode(cfgP,calP)
            ######
            theServer.closeConnection()
            screenPrinter().printToScreen("iTelescope is \n restarting...")
            logger.warning("iTelescope restarted due to running through")

        except Exception as e:

            screenPrinter().printToScreen("iTelescope is \n restarting...")
            logger.error("iTelescope restarted due to error: %s" % e.message)
            logger.exception("details:")


import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
parentdir = os.path.dirname(parentdir)
sys.path.insert(0,parentdir)

from abc import ABC, abstractmethod
from envs.base.abenv import ABEnv

class ABScenario(ABC, ABEnv):
    '''
        Abstract class for all Scenarios supported. A Scenario works like an environment, but uses it
        as a base to create a trainment pattern. For example, for an environment like DeepRTS, one can train an agent
        to learn how to collect specific resources, on a specific map.

        A scenario also offers a default RewardBuilder and ActionWrapper to help build an agent.
    '''

    '''
        Returns the default RewardBuilder
    '''
    @abstractmethod
    def get_default_reward_builder(self) -> RewardBuilder: ...

    '''
        Returns the default ActionWrapper
    '''
    @abstractmethod
    def get_default_action_wrapper(self) -> ActionWrapper: ...


class Car():

    def __init__(self, *arg, **kwargs):
        self.wheels = 4
        self.door = 4
        self.windows = 4
        self.seats = 4
        self.color = kwargs.get("color", "black")
        self.price = kwargs.get("price", "20$")

    def __str__(self):
        return f"Car with {self.wheels} wheels"

porche = Car(color = "green", price = "40$")
print (porche.color, porche.price)

mini = Car()
print(mini.color, mini.price)


import os, shutil, urllib, zlib

__author__ = "Derek"
os.system('title TFMDecompress - AulaMice')

print("TFMDecompress - AulaMice")
print("Digite 1 - Para fazer o download de todas as langues.")
print("Digite 2 - Para descriptografar todas as langues.")
print("Digite 3 - Para criptografar todas as langues.")

def main():
    langues = ["tfz_ar", "tfz_br", "tfz_cn", "tfz_de", "tfz_en", "tfz_es", "tfz_fr", "tfz_hu", "tfz_id", "tfz_nl", "tfz_no", "tfz_pl", "tfz_ro", "tfz_ru", "tfz_tr"]
    function = raw_input("> ")
    if function == "1": #Download
        os.system("mkdir langues")
        print("Criando pasta Langues... OK")
        for langue in langues:
            urllib.urlretrieve("http://transformice.com/langues/"+str(langue)+"", langue)
            shutil.move(langue,'langues')
            print("Baixando langue "+str(langue[4:])+"... OK")
    elif function in ["2", "3"]: #Decompress and Compress
        for langue in langues:
            try:
                fr = open("./langues/"+str(langue)+"", 'rb').read();
                if function == "2": fr = zlib.decompress(fr)
                elif function == "3": fr = zlib.compress(fr)
                fw = open("./langues/"+str(langue)+"", 'wb'); fw.write(fr)
                print(("Decompressing " if function == "2" else "Compressing ") + str(langue[4:]) + "... OK")
            except:
                print("Ops, houve um erro...")
                main()
    else:
        main()

    main()
if __name__=="__main__":
    main()


"""
HTTP Client Library Adapters

"""
import logging
import requests

try:
    import simplejson as json
except ImportError:
    import json

from consulate import api
from consulate import utils

LOGGER = logging.getLogger(__name__)

CONTENT_FORM = 'application/x-www-form-urlencoded; charset=UTF-8'
CONTENT_JSON = 'application/json; charset=UTF-8'

def prepare_data(fun):
    """Decorator for transforming the data being submitted to Consul

    :param function fun: The decorated function

    """
    def inner(*args, **kwargs):
        """Inner wrapper function for the decorator

        :param list args: positional arguments
        :param dict kwargs: keyword arguments

        """
        if kwargs.get('data') and not utils.is_string(kwargs.get('data')):
            kwargs['data'] = json.dumps(kwargs['data'])
        elif len(args) == 3 and not utils.is_string(args[2]):
            args = args[0], args[1], json.dumps(args[2])
        return fun(*args, **kwargs)
    return inner

class Request(object):
    """The Request adapter class"""
    def __init__(self):
        """Create a new request adapter instance"""
        self.session = requests.Session()

    def delete(self, uri):
        """Perform a HTTP delete

        :param src uri: The URL to send the DELETE to
        :rtype: consulate.api.Response

        """
        LOGGER.debug("DELETE %s", uri)
        response = self.session.delete(uri)
        return api.Response(response.status_code,
                            response.content,
                            response.headers)

    def get(self, uri):
        """Perform a HTTP get

        :param src uri: The URL to send the DELETE to
        :rtype: consulate.api.Response

        """
        LOGGER.debug("GET %s", uri)
        response = self.session.get(uri)
        return api.Response(response.status_code,
                            response.content,
                            response.headers)

    @prepare_data
    def put(self, uri, data=None):
        """Perform a HTTP put

        :param src uri: The URL to send the DELETE to
        :param str data: The PUT data
        :rtype: consulate.api.Response

        """
        LOGGER.debug("PUT %s with %r", uri, data)
        if utils.is_string(data):
            headers = {'Content-Type': CONTENT_FORM}
        else:
            headers = {'Content-Type': CONTENT_JSON}
        if not utils.PYTHON3 and data:
            data = data.encode('utf-8')
        response = self.session.put(uri, data=data, headers=headers)
        return api.Response(response.status_code,
                            response.content,
                            response.headers)


# -*- coding: utf-8 -*-

from flask import Flask, g, request, abort
import json
import tweepy
import urllib2

app = Flask(__name__)

def connect_twitter():
    twitter_auth = tweepy.OAuthHandler(app.config['TWITTER_CONSUMER_KEY'],
                                       app.config['TWITTER_CONSUMER_SECRET'])
    twitter_auth.set_access_token(app.config['TWITTER_ACCESS_TOKEN'],
                                  app.config['TWITTER_ACCESS_TOKEN_SECRET'])
    twitter_api = tweepy.API(twitter_auth)
    return twitter_api

def tweet(status):
    g.twitter_api.update_status(status=status)

@app.before_request
def init_twitter():
    g.twitter_api = connect_twitter()

def what3words(lat, lon):
    w3w_base_url = 'http://api.what3words.com'
    w3w_request_url = w3w_base_url + '/position?key=' + \
        app.config['W3W_API_KEY'] + '&position=' + str(lat) + \
        ',' + str(lon) + '&lang=ru'
    w3w_response = urllib2.urlopen(w3w_request_url)
    data = json.load(w3w_response)

    words = []
    for word in data['words']:
        words.append(word.encode('utf-8'))

    return words

def what3words_str(lat, lon):
    return '.'.join(what3words(lat, lon))

@app.route('/push', methods=['POST'])
def process_push():
    checkin = request.form.get('checkin', None)
    secret = request.form.get('secret', None)

    if checkin is not None and secret is not None:
        if secret == app.config['FOURSQUARE_SECRET']:
            checkin_data = json.loads(checkin)

            venue_name = checkin_data['venue']['name']
            lat = checkin_data['venue']['location']['lat']
            lon = checkin_data['venue']['location']['lng']

            status = u'Я зачекинился в ' + \
                     what3words_str(lat, lon).decode('utf-8') + \
                     u', более известном как ' + venue_name + '.'
            if len(status) > 140:
                status = status[:137] + '...'

            tweet(status)

            return 'ok'
        else:
            abort(403)
    else:
        abort(403)

@app.route('/', methods=['GET'])
def index():
    return '<img src="http://i.imgur.com/X2l8kc9.jpg">'

if __name__ == '__main__':
    app.run()


from flask import request
from flask_restful import Resource
from Model import db, Conference, ConferenceSchema, Talk, TalkSchema
from marshmallow import ValidationError
from sqlalchemy.orm import joinedload, subqueryload

talks_schema = TalkSchema(many=True)
talk_schema = TalkSchema()

response = {'status': 'success'}
error_response = {'status': 'error', 'message': 'Request failed.'}

class TalkResource(Resource):
    # To list all talk in a particular conference
    def get(self):
        conference_id = request.args.get('conference_id')
        if(not conference_id):
            error_response['message'] = 'No conference id passed.'

            return error_response, 400
        conference = Conference.query.filter_by(id=conference_id).first()
        if not conference:
            error_response['message'] = 'Conference does not exist.'

            return error_response, 400
        talks = talks_schema.dump(conference.talks)
        response['data'] = talks

        return response, 200

    # To add a talk
    def post(self):
        input_data = request.get_data()
        if not input_data:
            error_response['message'] = 'No input data'

            return error_response, 400
        try:
            data = talk_schema.loads(input_data)

            conference = Conference.query.filter_by(id=data['conference_id']).first()
            if not conference:
                error_response['message'] = 'Conference does not exist.'

                return error_response, 400
            talk = Talk(
                title=data['title'],
                description=data['description'] if 'description' in data else None,
                scheduled_at=data['scheduled_at'],
                duration_min=data['duration_min'],
                speakers=[],
                participants=[]
            )
            talk.conference_id = conference.id
            db.session.add(talk)
            db.session.commit()
            response['data'] = talk_schema.dump(talk)

            return response, 201
        except ValidationError as err:
            error_response['errors'] = err.messages

            return error_response, 400
        except:
            return error_response, 400

    # To edit a talk
    def patch(self):
        input_data = request.get_data()
        if not input_data:
            error_response['message'] = 'No input data.'

            return error_response, 400
        try:
            data = talk_schema.loads(input_data, partial=True)
            if(not 'id' in data):
                error_response['message'] = 'No talk id passed.'

                return error_response, 400
            talk = Talk.query.filter_by(id=data['id']).first()
            if not talk:
                error_response['message'] = 'Talk does not exist.'

                return error_response, 400
            if('conference_id' in data):
                conference = Conference.query.filter_by(id=data['conference_id']).first()
                if not conference:
                    error_response['message'] = 'Conference does not exist.'

                    return error_response, 400
            for key in data:
                setattr(talk, key, data[key])
            db.session.commit()
            response['data'] = talk_schema.dump(talk)

            return response, 201
        except ValidationError as err:
            error_response['errors'] = err.messages

            return error_response, 400
        except:
            return error_response, 400


#!/usr/bin/env python3

import numpy as np
from reinforcement import game
from network import Network
import mc_tree_search
from protocol import Protocol
from node import Node
import threading

class Thread(threading.Thread):
    def __init__(self, protocol):
        threading.Thread.__init__(self)
        self.protocol = protocol

    def run(self):
        while self.protocol.running[0]:
            self.protocol.nextCmd()

def play_turn(board, player, network):
    # ADD OWN TURN CALCULATION
    node = mc_tree_search.Node(0)
    mc_tree_search.expand(node, board, 0, network)
    (x, y), _, _, _, _ = mc_tree_search.turn(board, player, node, network)
    print(x + "," + y)

def piskvork_game():
    """
    play gomoku game using trained model and piskvork interface
    """
    board = np.zeros((1, 19, 19, 3), np.int8)
    running = [1]
    protocol = Protocol(board, running)
    thread = Thread(protocol)
    network = Network(-1)
    player = 0

    thread.start()
    while running[0]:
        args = protocol.pullCmd();
        cmd = args[0].lower()
        del args[0]
        if cmd == "none":
            pass
        elif cmd == "start":
            print("OK")
        elif cmd == "turn":
            try:
                pos = args[0].split(',')
                x = int(pos[0])
                y = int(pos[1])
                mc_tree_search.put_on_board(board, (x, y), player ^ 1, 0)
            except:
                print("ERROR")
            print("DEBUG", "Calculating the next move")
            play_turn(board, player, network)
        elif cmd == "begin":
            print("DEBUG", "Calculating the next move")
            play_turn(board, player, network)
            pass
        else:
            print("ERROR")
    thread.join()

def reinforcement():
    """
    train model against itself
    """

    # parameters
    number_of_games = 1
    network = Network(-1)

    for num_game in range(number_of_games):
        # play a game until the end
        game(network, num_game)

        # train network
        network.train()

if __name__ == '__main__':
    # training
    reinforcement()

    # real game
    # piskvork_game()


import pandas as pd
import argparse
from tokenization import BertTokenizer
from modeling import BertForSequenceClassification
import torch
import torch.nn.functional as F
import numpy as np
import sys
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
                    datefmt = '%m/%d/%Y %H:%M:%S',
                    level = logging.INFO)

def construct_context_gloss_pairs(input, target_start_id, target_end_id, lemma):
    """
    construct context gloss pairs like sent_cls_ws
    :param input: str, a sentence
    :param target_start_id: int
    :param target_end_id: int
    :param lemma: lemma of the target word
    :return: candidate lists
    """
    sent = input.split(" ")
    assert 0 <= target_start_id and target_start_id < target_end_id  and target_end_id <= len(sent)
    target = " ".join(sent[target_start_id:target_end_id])
    if len(sent) > target_end_id:
        sent = sent[:target_start_id] + ['"'] + sent[target_start_id:target_end_id] + ['"'] + sent[target_end_id:]
    else:
        sent = sent[:target_start_id] + ['"'] + sent[target_start_id:target_end_id] + ['"']

    sent = " ".join(sent)
    lemma = lemma

    sense_data = pd.read_csv("./wordnet/index.sense.gloss",sep="\t",header=None).values
    d = dict()
    for i in range(len(sense_data)):
        s = sense_data[i][0]
        pos = s.find("%")
        try:
            d[s[:pos + 2]].append((sense_data[i][0],sense_data[i][-1]))
        except:
            d[s[:pos + 2]]=[(sense_data[i][0], sense_data[i][-1])]

    # print(len(d))
    # print(len(d["happy%3"]))
    # print(d["happy%3"])

    candidate = []
    for category in ["%1", "%2", "%3", "%4", "%5"]:
        query = lemma + category
        try:
            sents = d[query]
            for sense_key, gloss in sents:
                candidate.append((sent, f"{target} : {gloss}", target, lemma, sense_key, gloss))
        except:
            pass
    assert len(candidate) != 0, f'there is no candidate sense of "{lemma}" in WordNet, please check'
    print(f'there are {len(candidate)} candidate senses of "{lemma}"')

    return candidate

class InputFeatures(object):
    """A single set of features of data."""

    def __init__(self, input_ids, input_mask, segment_ids):
        self.input_ids = input_ids
        self.input_mask = input_mask
        self.segment_ids = segment_ids

def convert_to_features(candidate, tokenizer, max_seq_length=512):

    candidate_results = []
    features = []
    for item in candidate:
        text_a = item[0] # sentence
        text_b = item[1] # gloss
        candidate_results.append((item[-2], item[-1])) # (sense_key, gloss)

        tokens_a = tokenizer.tokenize(text_a)
        tokens_b = tokenizer.tokenize(text_b)
        _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
        tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
        segment_ids = [0] * len(tokens)
        tokens += tokens_b + ["[SEP]"]
        segment_ids += [1] * (len(tokens_b) + 1)

        input_ids = tokenizer.convert_tokens_to_ids(tokens)

        # The mask has 1 for real tokens and 0 for padding tokens. Only real
        # tokens are attended to.
        input_mask = [1] * len(input_ids)

        # Zero-pad up to the sequence length.
        padding = [0] * (max_seq_length - len(input_ids))
        input_ids += padding
        input_mask += padding
        segment_ids += padding

        assert len(input_ids) == max_seq_length
        assert len(input_mask) == max_seq_length
        assert len(segment_ids) == max_seq_length

        features.append(
            InputFeatures(input_ids=input_ids,
                          input_mask=input_mask,
                          segment_ids=segment_ids))

    return features, candidate_results

def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length."""

    # This is a simple heuristic which will always truncate the longer sequence
    # one token at a time. This makes more sense than truncating an equal percent
    # of tokens from each, since if one sequence is very short then each token
    # that's truncated likely contains more information than a longer sequence.
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()

def infer(input, target_start_id, target_end_id, lemma, args):

    device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")

    label_list = ["0", "1"]
    num_labels = len(label_list)
    tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=True)
    model = BertForSequenceClassification.from_pretrained(args.bert_model,
                                                          num_labels=num_labels)
    model.to(device)

    print(f"input: {input}\nlemma: {lemma}")
    examples = construct_context_gloss_pairs(input, target_start_id, target_end_id, lemma)
    eval_features, candidate_results = convert_to_features(examples, tokenizer)
    input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
    input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
    segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)

    model.eval()
    input_ids = input_ids.to(device)
    input_mask = input_mask.to(device)
    segment_ids = segment_ids.to(device)
    with torch.no_grad():
        logits = model(input_ids=input_ids, token_type_ids=segment_ids, attention_mask=input_mask, labels=None)
    logits_ = F.softmax(logits, dim=-1)
    logits_ = logits_.detach().cpu().numpy()
    output = np.argmax(logits_, axis=0)[1]
    print(f"results:\nsense_key: {candidate_results[output][0]}\ngloss: {candidate_results[output][1]}")

if  __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("--bert_model", default="./Sent_CLS_WS", type=str)
    parser.add_argument("--no_cuda", default=False, action='store_true', help="Whether not to use CUDA when available")

    args = parser.parse_args()

    # demo input
    input = "U.N. group drafts plan to reduce emissions"
    target_start_id = 3
    target_end_id = 4
    lemma = "plan"

    infer(input, target_start_id, target_end_id, lemma, args)


import utime
from machine import Pin
import socket
import network

class Orwell():
    def __init__(self):
        self.sta_if = network.WLAN(network.STA_IF)
        self.pin_out = Pin(12, Pin.OUT)
        self.pin_in  = Pin(13, Pin.IN)

        self.threshold = 80
        self.target_ip = "192.168.12.23"
        self.debug_ip = "192.168.12.20"
        self.target_port = 5000
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.color = (255, 255, 255, 255)
        self.pixel_list = [i for i in range(58)] # num pixel
        # set interrupt
        self.pin_in.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.interrupt)

    def interrupt(self):
        self.s.sendto((bytes((255, 0, 255, 0, 55))+bytes(self.pixel_list)), (self.target_ip, self.target_port))
        self.s.sendto((bytes((255, 0, 255, 0, 55))+bytes(self.pixel_list)), (self.debug_ip, self.target_port))

    def main(self):
        while not self.sta_if.isconnected():
            pass
        while True:
            self.s.sendto((bytes((255, 255, 255, 255, 255))+bytes(self.pixel_list)), (self.target_ip, self.target_port))
            self.s.sendto((bytes((255, 255, 255, 255, 255))+bytes(self.pixel_list)), (self.debug_ip, self.target_port))
            utime.sleep(3)
            self.s.sendto((bytes((255, 0, 255, 0, 55))+bytes(self.pixel_list)), (self.target_ip, self.target_port))
            self.s.sendto((bytes((255, 0, 255, 0, 55))+bytes(self.pixel_list)), (self.debug_ip, self.target_port))
            utime.sleep(3)

#   def reboot(self):
#       rtc = machine.RTC()
#       rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
#       rtc.alarm(rtc.ALARM0, 1000)
#       machine.deepsleep()

"""

    def main(self):
        # Wait till interface is properly set up
        while not self.sta_if.isconnected():
            pass
        while True:
            self.pin_out.off()
            # send pulse to start meassurement
            self.pin_out.on()
            utime.sleep_us(10)
            self.pin_out.off()
            # wait before next one
            utime.sleep(.05)
            # Send if True

    # gets called on rising edge and waits until pin value is low again
    # -> calculates distance according to time of high phase
    def interrupt(self):
        start = utime.ticks_us()
        while self.pin_in.value() == 1:
            pass
        end = utime.ticks_us()
        if end > start:
            distance = (end - start)/10**6*34300/2
        else:
            distance = 0
        if distance <= self.threshold:
            self.s.sendto(bytes((255,200,200,200,200))+bytes(self.pix), (self.ip, self.port))
            utime.sleep(2)
            self.s.sendto(bytes((255,0,0,0,0))+bytes(self.pix), (self.ip, self.port))
            #self.s.sendto('Distance is {0} cm'.format(distance), (self.ip, self.port))

"""

if __name__ == '__main__':
    m = Orwell()
    m.main()


from time import sleep
from mininet.cli import CLI
from mininet.log import lg, info
from mininet.topo import SingleSwitchTopo
from mininet.net import Mininet
from mininet.util import pmonitor

def main():
    lg.setLogLevel( 'info')
    topo = SingleSwitchTopo(4)
    net = Mininet(topo=topo)

    net.start()

    h1 = net.get('h1')
    h2 = net.get('h2')
    h3 = net.get('h3')
    h4 = net.get('h4')

    popens = {}
    p1 = h1.popen('python3 tcp_server.py %s & ' %h1.IP())

    print(h2.cmd('python3 tcp_client.py 1 %s |& tee -a output.log &' %h1.IP()))
    print(h3.cmd('python3 tcp_client.py 2 %s |& tee -a output.log &' %h1.IP()))
    print(h4.cmd('python3 tcp_client.py 3 %s |& tee -a output.log &' %h1.IP()))

    sleep(5)
    p1.terminate()

    h3.cmd('chmod 777 output.log')
    with open('output.log', 'r') as fin:
        print(fin.read())

    h3.cmd('sudo rm output.log')

    net.stop()

if __name__ == '__main__':
    main()


from django.conf.urls import include, url

from django.contrib import admin

from blog import views

from blog.views import RSSFeed

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^blog/$', views.index, name='index'),
    url(r'^list/$', views.list_blog, name='list_blog'),
    url(r'^category/$', views.category, name='category'),
    url(r'^blog/(?P<id>(\d+))/$', views.detail, name='detail'),
    url(r'^post/$', views.post, name='post'),
    url(r'^times/$', views.times, name='times'),
    url(r'^blog_add/$', views.blog_add, name='blog_add'),
    url(r'^uploadImg/$', views.uploadImg, name='uploadImg'),
    url(r'^blog/sub_comment/$', views.sub_comment, name='sub_comment'),
    url(r'^tag_blog/(?P<id>(\d+))/$', views.tag_blog, name='tag_blog'),
    url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.archives, name='archives'),
    url(r'^login/$', views.login, name='login'),
    url(r'^acc_login/$', views.acc_login, name='acc_login'),
    url(r'^update(?P<id>(\d+))/$', views.update, name='update'),
    url(r'^delete(?P<id>(\d+))/$', views.delete, name='delete'),
    url(r'^blog_update(?P<id>(\d+))/$', views.blog_update, name='blog_update'),
    url(r'^feed/$', RSSFeed(), name='RSS'),
]


from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
api= IAMAuthenticator("EgSq9AWTvivbSCTr4rGW5TqIuLHjPTyQ0M7potH-9O9u")
text_2_speech = TextToSpeechV1(authenticator=api)
text_2_speech.set_service_url("https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/452c983e-9f0d-4878-822f-f0c8cc896d95")
with open("hi.wav","wb") as audiofile :
    audiofile.write(
        text_2_speech.synthesize("Hello, Good morning",accept="audio/wav").get_result().content
    )


from keras import applications, optimizers
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model, Sequential
from keras.layers import Input, Dropout, Flatten, Dense
import numpy as np

def triplet_loss(y_true, y_pred):
  alpha = 1
  embeddings = K.reshape(y_pred, (-1, 3))
  positive_distance = K.sqrt(K.sum((embeddings[:, 0] - embeddings[:, 1]) ** 2, axis = -1))
  negative_distance = K.sqrt(K.sum((embeddings[:, 0] - embeddings[:, 2]) ** 2, axis = -1))
  return K.sum(positive_distance - negative_distance + alpha)

img_width, img_height = 150, 150
top_model_weights_path = 'top_model_weights.h5'
train_data_dir = '../data/simulated_flight_1/train/'
valid_data_dir = '../data/simulated_flight_1/valid/'
nb_train_samples = 477
nb_valid_samples = 24
epochs = 24
batch_size = 15
input_tensor = Input(shape = (150, 150, 3))

vgg16_model = applications.VGG16(weights='imagenet', include_top=False, input_tensor=input_tensor)

train_data = np.load(open('top_model_features_train.npy', 'rb'))

top_model = Sequential()
top_model.add(Flatten(input_shape = vgg16_model.output_shape[1:]))
top_model.add(Dense(256, activation = 'relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(1, activation = 'sigmoid'))

top_model.load_weights(top_model_weights_path)

model = Sequential()
for l in vgg16_model.layers:
  model.add(l)
model.add(top_model)

# set some layers to be non trainable
for layer in model.layers[:25]:
  layer.trainable = False

model.compile(loss = triplet_loss, optimizer = optimizers.SGD(lr = 1e-4, momentum = 0.9), metrics=['accuracy'])

train_datagen = ImageDataGenerator(rescale = 1. / 255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
valid_datagen = ImageDataGenerator(rescale = 1. / 255)

train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_height, img_width), batch_size = batch_size, class_mode = 'binary')
valid_generator = valid_datagen.flow_from_directory(valid_data_dir, target_size = (img_height, img_width), batch_size = batch_size, class_mode = 'binary')

model.fit_generator(train_generator, samples_per_epoch = nb_train_samples, epochs = epochs, validation_data = valid_generator, nb_val_samples = nb_valid_samples)


#!/usr/bin/env python

import re
import sys
from cement.core.foundation import CementApp
from cement.utils.misc import init_defaults

defaults = init_defaults('auth-sheep')
defaults['auth-sheep']['debug'] = False

class AuthSheep(CementApp):
    class Meta:
        label = 'auth-sheep'
        config_defaults = defaults

def main(argv):
    with AuthSheep() as app:
        app.args.add_argument('--access-key', action='store', dest='access_key')
        app.args.add_argument('--secret-key', action='store', dest='secret_key')
        app.args.add_argument('--region', action='store', dest='region')
        app.args.add_argument('--name', action='store', dest='name')
        app.args.add_argument('--description', action='store', dest='description')
        app.args.add_argument('command')
        app.args.add_argument('input_config_file')
        app.args.add_argument('output_config_file')
        app.run()
        command = app.pargs.command
        input_config_file = app.pargs.input_config_file
        output_config_file = app.pargs.output_config_file
        if command == 'init':
            region = ''
            name = ''
            description = ''
            if app.pargs.region:
                region = app.pargs.region
            else:
                region = raw_input('Region: ')
            if app.pargs.name:
                name = app.pargs.name
            else:
                name = raw_input('Name: ')
            if app.pargs.description:
                description = app.pargs.description
            else:
                description = raw_input('Description: ')
            init(input_config_file, output_config_file, region, name, description)
        elif command == 'auth':
            access_key = ''
            secret_key = ''
            if app.pargs.access_key:
                access_key = app.pargs.access_key
            else:
                access_key = raw_input('Access Key: ')
            if app.pargs.secret_key:
                secret_key = app.pargs.secret_key
            else:
                secret_key = raw_input('Secret Key: ')
            auth(input_config_file, output_config_file, access_key, secret_key)

def init(input_config_file, output_config_file, region, name, description):
    lines = []
    with open(input_config_file) as f:
        for line in f.readlines():
            matches = re.findall(r'^(region:)|(function_name:)|(description:)', line)
            if (len(matches) > 0):
                match = matches[0]
                if (len(match[0]) > 0): # region
                    line = 'region: ' + region + '\n'
                if (len(match[1]) > 0): # function_name
                    line = 'function_name: ' + name + '\n'
                if (len(match[2]) > 0): # description
                    line = 'description: ' + description + '\n'
            lines.append(line)
    with open(output_config_file, 'w') as f:
        for line in lines:
            f.write(line)

def auth(input_config_file, output_config_file, access_key, secret_key):
    lines = []
    with open(input_config_file) as f:
        for line in f.readlines():
            matches = re.findall(r'^(aws_access_key_id:)|(aws_secret_access_key:)', line)
            if (len(matches) > 0):
                match = matches[0]
                if (len(match[0]) > 0): # aws_access_key
                    line = 'aws_access_key_id: ' + access_key + '\n'
                if (len(match[1]) > 0): # aws_secret_access_key
                    line = 'aws_secret_access_key: ' + secret_key + '\n'
            lines.append(line)
    with open(output_config_file, 'w') as f:
        for line in lines:
            f.write(line)

main(sys.argv)


import unittest
import requests

server_address = "http://127.0.0.1:5000"

class FeatureTest(unittest.TestCase):

    def test_page_exsits(self):
        pages = ["", "/register", "/login", "/spell_check"]
        for page in pages:
            req = requests.get(server_address + page)
            self.assertEqual(req.status_code, 200)


import numpy as np

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
import datetime as dt

from flask import Flask, jsonify

# Database Setup
engine = create_engine("sqlite:///Resources/hawaii.sqlite")

# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)

# Save references to each table
Measurement = Base.classes.measurement
Station=Base.classes.station

# Flask Setup
app = Flask(__name__)
#disable automatick key sort
app.config['JSON_SORT_KEYS'] = False

# Flask Routes

@app.route("/")
def welcome():
    """List all available api routes."""

    return (
        f"Welcome to the Hawaii Climate API

"
        f"Available Routes:
"
        f"Precipitation Data: /api/v1.0/precipitation
"
        f"Stations Data: /api/v1.0/stations
"
        f"Most Active Station Temperature Data: /api/v1.0/tobs
"
        f"Temperature Data from Start Date (yyyy-mm-dd): /api/v1.0/start
"
        f"Temperature Data from Start to End Date (yyyy-mm-dd): /api/v1.0/start/end"
    )

# Convert the query results to a dictionary using date as the key and prcp as the value.
# Return the JSON representation of your dictionary.

@app.route("/api/v1.0/precipitation")
def precipitation():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    # Query all passengers
    sel = [Measurement.date, Measurement.prcp]
    precip_data = session.query(*sel).order_by(Measurement.date).all()

    session.close()
    new_dict={}
    data_list=[]
    new_dict['precipitation data']=data_list

    precip_dict = {}
    for date, precip in precip_data:

        precip_dict[date] = precip

    data_list.append(precip_dict)
    return jsonify(new_dict)

# Return a JSON list of stations from the dataset.

@app.route("/api/v1.0/stations")
def stations():
    """Returns list of station data"""

    session = Session(engine)

    # Query
    sel=[Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation]
    station_data = session.query(*sel).all()

    session.close()

    #convert to dict
    #station_data = []
    new_dict={}
    station_list=[]
    station_dict={}

    for id, name, lat, long ,elevation in station_data:

        station_dict['id'] = id
        station_dict['name'] = name
        station_dict['lat'] = lat
        station_dict['long'] = long
        station_dict['elevation'] = elevation
        station_list.append(station_dict)
        station_dict={}

    new_dict['stations']=station_list
    return jsonify(new_dict)

@app.route("/api/v1.0/tobs")
def tobs():
    """Returns id of most active station in last year of data.
       Returns list of date and tobs of the last year of data for the station"""
    # Create our session (link) from Python to the DB
    session = Session(engine)

    #last date and year ago
    last_date=session.query(Measurement.date).order_by(Measurement.date.desc()).first()
    last_datetime=dt.datetime.strptime(last_date[0],'%Y-%m-%d')
    year_ago = (last_datetime - dt.timedelta(days=365)).strftime('%Y-%m-%d')

    #get the most active station in the last year of data
    active_stations= session.query(Measurement.station).filter(Measurement.date >= year_ago).\
        group_by(Measurement.station).\
        order_by(func.count(Measurement.id).desc()).all()

    #query date and prcp of the last year of the most active station in the last year
    sel = [Measurement.date, Measurement.prcp]
    station_precip_data = session.query(*sel).filter(Measurement.station==active_stations[0][0]).\
        filter(Measurement.date >= year_ago).order_by(Measurement.date).all()

    session.close()

    new_dict={}
    new_list=[]
    new_dict['station']=new_list
    station_precip_dict={}
    data_dict={}

    station_precip_dict['id']=active_stations[0][0]
    station_precip_dict['data']=data_dict
    for date, precip in station_precip_data:
        data_dict[date] = precip
        #station_data.append(station_dict)
    station_precip_dict['data']=data_dict
    new_list.append(station_precip_dict)

    return jsonify(station_precip_dict)

@app.route("/api/v1.0/<start>")
def start(start):
    # Create our session (link) from Python to the DB
    session = Session(engine)

    """When given only the start date, returns data_points, TMIN, TAVG, and TMAX
       for all dates greater than or equal to the start date"""

    # Query
    sel=[func.count(Measurement.tobs),func.min(Measurement.tobs), func.max(Measurement.tobs),func.avg(Measurement.tobs)]
    temp_start = session.query(*sel).filter(Measurement.date >= start).all()

    session.close()

    #convert to dict
    temp_dict= {}
    for points, min, max, avg in temp_start:
        temp_dict['data_points']=points
        temp_dict["TMIN"] = min
        temp_dict["TMAX"] = max
        temp_dict["TAVG"] = avg

    #return an error message if the date exceeds the latest date in the data
    if temp_dict["data_points"] ==0 or start < '2010-01-01':
        return jsonify({"error": "Invalid date. Please select a dates between 2010-01-01 and 2017-08-23. Make sure date entered matches format yyyy-mm-dd"}),404
    else:
        return jsonify(temp_dict)

@app.route("/api/v1.0/<start>/<end>")
def end(start,end):
    # Create our session (link) from Python to the DB
    session = Session(engine)

    """When given start and end date, returns data_points, TMIN, TAVG, and TMAX
       for all dates in the start-end range"""

    # Query
    sel=[func.count(Measurement.tobs),func.min(Measurement.tobs), func.max(Measurement.tobs),func.avg(Measurement.tobs)]
    temp_end = session.query(*sel).filter(Measurement.date >= start,Measurement.date <= end).all()

    session.close()

    #convert to dict
    temp_dict= {}
    for points, min, max, avg in temp_end:
        temp_dict['data_points']=points
        temp_dict["TMIN"] = min
        temp_dict["TMAX"] = max
        temp_dict["TAVG"] = avg

    #return an error message if the date exceeds the latest date in the data
    if temp_dict["data_points"] ==0 or start < '2010-01-01' or end > '2017-08-23':
        return jsonify({"error": "Invalid date. Please select a dates between 2010-01-01 and 2017-08-23. Make sure date entered matches format yyyy-mm-dd"}),404
    else:
        return jsonify(temp_dict)

if __name__ == '__main__':
    app.run(debug=True)

# Hints
# You will need to join the station and measurement tables for some of the queries.

# Use Flask jsonify to convert your API data into a valid JSON response object.


import csv
import pdb
from connection import connection

with open("data/rankings", "r") as file:
    reader = csv.reader(file)
    with connection.cursor() as cur:
        cur.execute("DELETE FROM pubmed_ranks;")
        connection.commit()
        count = 0

        for row in reader:
            count += 1
            if count % 10000 == 0:
                print(count)
                connection.commit()
            cur.execute("INSERT INTO pubmed_ranks VALUES (%s, %s, %s);", (row[0], row[1], row[2]))


import discord, os
client = discord.Client()
target = os.environ['target']
guild = os.environ['guild']
token = os.environ['token']

@client.event
async def on_message(message):
    if message.author != client.user or message.server.id != guild: return
    try: await client.send_message(message.channel, f"<@{target}>")
    except Exception as e: print(e)

@client.event
async def on_message_delete(message):
    try: await client.send_message(message.channel, message.content)
    except Exception as e:
        print(e)

@client.event
async def on_ready():
    print(client.user.name, ': ', client.user.id, '\n-------')

client.run(token)


i =1   #init
while i<10: #condition
     print(i)
     i +=1  # incrementer

#print in reverse
i =10
while i>0:
     print(i)
     i-=1

#for
for x in range(1,10): #from 1 to <10 , default incrmenter is 1
     print(x)

for x in range(1,10,2): #from 1 to <10 , default incrmenter is 1
     print(x)

#rev
for i in range(10,0,-1):
        print(i)

'''
example
test

'''

"""
"""


#-------------------------------------------------------------------------------
# Name:        Tailer
# Purpose:  Class used to imitate the Unix tail -f command
#           Allows to use this application cross-platform
#
# Author:      Rudy
#
# Created:     30/11/2013
#-------------------------------------------------------------------------------
"""
Create a Tailer to track the new lines in a file.
They are accessible through the follow() generator
"""

import time

class Tailer:

    def __init__(self,fileToTailPath,refreshFreq=1.0):
        """
        Create an Instance of the Tailer
        @param fileToTailPath: Path to the file that needs to be tail followed
        @param refreshFreq: Float indicating how much time before trying to read
                            again when we don't encounter any new line
        """
        self.toTail=fileToTailPath
        self.refreshFreq=refreshFreq

    def follow(self):
        """
        Yield the next line appended
        """
        with open(self.toTail,'r') as fileToTail:
            fileToTail.seek(0,2)
            while True:
                line=fileToTail.readline()
                if not line:
                    yield ""
                    time.sleep(self.refreshFreq)
                else:
                    yield line.strip("\n")


import xml.etree.ElementTree
import xml_funcs
import os
from itertools import zip_longest

def _check_list(to_check):
    """If a value is not a list, pack it into one and return it, else just returns the value"""
    if type(to_check) != list:
        return [to_check]
    else:
        return to_check

def _none_to_int(val):
    if val is None:
        return 0
    else:
        return val

def _e_check(to_check, conv_class=None):
    """
    :param to_check: the dictionary to check
    :param conv_class: Unused, used to convert the elements of the return to a class
    :return: to_check['E'] Or an empty list if that value isn't there
    """
    if "E" in to_check:
        to_check = _check_list(to_check['E'])
    else:
        return []

    if conv_class is not None:
        return [conv_class(a) for a in to_check]
    else:
        return to_check

def _xml_key_val_to_dict(xml: list[dict]):
    return {a["key"]: int(a["value"]) for a in xml}

class RunStats:
    """Holds a representation of both the 2 files that are saved"""

    def __init__(self, kills_xml: dict, stats_xml: dict):
        self.kills = XmlKills(kills_xml)
        self.stats = XmlStats(stats_xml)

class XmlKills:

    def __init__(self, xml: dict = None):
        if xml is None:
            return

        self.kills = int(xml['kills'])
        self.player_projectile_count = int(xml['player_projectile_count'])
        self.player_kill_count = int(xml['player_kills'])

        self.player_kills = xml['kill_map']
        self.player_kills = _xml_key_val_to_dict(_e_check(self.player_kills))
        self.player_kills = {" ".join(key.split('_')[::-1]): val for key, val in self.player_kills.items()}
        # Reverse order for adjectives

        self.death_map = xml['death_map']
        self.death_map = _xml_key_val_to_dict(_e_check(self.death_map))

class XmlStats:
    def __init__(self, xml: dict = None):
        if xml is None:
            return

        stats: dict = xml["stats"]

        self.biomes_visited_with_wands = int(_none_to_int(stats.get("biomes_visited_with_wands")))  # Not a clue
        self.damage_taken = float(_none_to_int(stats.get("damage_taken")))
        self.dead = bool(_none_to_int(stats.get("dead")))
        self.death_pos_x = float(_none_to_int(stats.get("death_pos.x")))
        self.death_pos_y = float(_none_to_int(stats.get("death_pos.y")))  # Same as depth
        self.enemies_killed = int(_none_to_int(stats.get("enemies_killed")))  # Same as player kill count I assume (maybe w/o friendly's)
        self.gold = int(_none_to_int(stats.get("gold")))
        self.gold_all = int(_none_to_int(stats.get("gold_all")))
        self.items = int(_none_to_int(stats.get("items")))
        self.kicks = int(_none_to_int(stats.get("kicks")))
        self.visited_count = int(_none_to_int(stats.get("places_visited")))
        self.playtime = float(_none_to_int(stats.get("playtime")))
        self.playtime_formatted = _none_to_int(stats.get("playtime_str"))
        self.shots_fired = int(_none_to_int(stats.get("projectiles_shot")))
        self.teleports = int(_none_to_int(stats.get("teleports")))
        self.wands_edited = int(_none_to_int(stats.get("wands_edited")))

        self.biomes_visited = xml["biomes_visited"]
        self.biomes_visited = _xml_key_val_to_dict(_e_check(self.biomes_visited))

STATS_PATH = os.path.abspath(os.environ.get('APPDATA') + "/../LocalLow/Nolla_Games_Noita/save00/stats/sessions") \
             + '\\'

def load_stats() -> dict[str, dict]:
    """:return: The players stats in the form dict[Filename: loaded stats]"""
    global STATS_PATH

    if not os.path.isdir(STATS_PATH):
        STATS_PATH = input(f"Stats not found at regular directory of {STATS_PATH}, provide a replacement directory?: ")

    files = os.listdir(STATS_PATH)

    data = {}
    for file in files:

        with open(STATS_PATH + file, 'r') as f:
            contents = f.read()
            contents = contents.replace(':', '')
        try:
            data[file] = xml_funcs.as_attr_dict(
                xml.etree.ElementTree.fromstring(contents)
            )
        except Exception as e:
            print(f"Failed to parse file: \"{file}\" with exception: {e!r}")

    data = {key: RunStats(kills, stats) for  # Stats are stored in 2 files per run by the game,
            kills, (key, stats) in
            zip_longest(
                list([val for key, val in data.items() if key.endswith("kills.xml")]),
                list([(key, val) for key, val in data.items() if key.endswith("stats.xml")])
            )
            }

    return data


import logging

###################
## logging
###################
def get_logger():

	def setup_logger(name, log_file, urllib3="urllib3"):

	    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
	    logging.getLogger(urllib3).setLevel("CRITICAL")

	    handler = logging.FileHandler(log_file)
	    handler.setFormatter(formatter)

	    logger = logging.getLogger(name)
	    logger.setLevel(logging.INFO)
	    logger.addHandler(handler)

	    return logger

	return setup_logger


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('products', '0017_auto_20150501_0934'),
    ]

    operations = [
        migrations.AlterField(
            model_name='variation',
            name='image',
            field=models.ImageField(default=1, upload_to=b'foodtruck/packages/'),
            preserve_default=False,
        ),
    ]