                                                      #LEETCODE STRING PROBLEMS

#QUESTION NUMBER :: 844. Backspace String Compare  'Easy'
'''-------------------------------------------------------------------------------------------------------------------------------------'''
class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        def process_string(s: str) -> str:
            stack = []
            for char in s:
                if char != '#':
                    stack.append(char)
                elif stack:
                    stack.pop()
            return ''.join(stack)

        return process_string(s) == process_string(t)
'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER :: 917. Reverse Only Letters

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        alpha_chars = [ char for char in s if char.isalpha()]
        reversed_chars = []
        for char in s:
            if char.isalpha():
                reversed_chars.append(alpha_chars.pop())
            else:
                reversed_chars.append(char)
        return ''.join(reversed_chars)

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER : 2810. Faulty Keyboard

class Solution:
    def finalString(self, s: str) -> str:
       rev_str = ""
       for i in range(len(s)):
           if s[i] == "i":
               rev_str = rev_str[:i][::-1]
           else:
               rev_str += s[i]
       return rev_str

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER : 1185. Day of the Week

from collections import Counter
from datetime import datetime
import calendar
from itertools import accumulate
import math
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        date = ""
        if day < 10:
            date += "0"
        date += str(day) + "/"
        if month < 10:
            date += "0"
        date += str(month) + "/"
        date += str(year)
        return calendar.day_name[datetime.strptime(date,"%d/%m/%Y").weekday()]

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER : 2744. Find Maximum Number of String Pairs

class Solution:
    def maximumNumberOfStringPairs(self, words: List[str]) -> int:
        count = 0
        for i in range(len(words)-1):
            for j in range(i+1,len(words)):
                if words[i]==words[j][::-1]:
                    count += 1

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER :  1332. Remove Palindromic Subsequences

# Method : 1

class Solution:
    def removePalindromeSub(self, s: str) -> int:
       return 1 if s == s [::-1] else 2

# Method Number: 2
class Solution:
    def removePalindromeSub(self, s: str) -> int:
        if not s: return 0
        l,r = 0,len(s)-1
        while l<r:
            if s[l] != s[r]:
                return 2
            l += 1
            r -= 1
        return 1

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER : 2788. Split Strings by Separator

class Solution:
    def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
        ls = []
        for data in words:
            word = data.split(separator)
            for data in word:
                if(data != ""):
                    ls.append(data)
        return ls

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER :      2710. Remove Trailing Zeros From a String

class Solution:
    def removeTrailingZeros(self, num: str) -> str:
       while(num[-1] == '0'):
           num = num[:-1]
       return num

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1021. Remove Outermost Parentheses

class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        res = []
        count = 0
        for i in s :
            if i == '(' and count > 0:
                res.append(i)
            if i == ')' and count > 1:
                res.append(i)
            count += 1 if i == '(' else -1
        return "".join(res)

'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER : 1678. Goal Parser Interpretation

class Solution:
    def interpret(self, command: str) -> str:
         command = command.replace("()","o")
         command = command.replace("(al)", "al")
         return command
'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1528. Shuffle String

class Solution:
    def restoreString(self, s: str, indices: List[int]) -> str:
        res = ''
        for i in range(len(indices)):
           res += s[indices.index(i)]
        return res

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1221. Split a String in Balanced Strings
class Solution:
    def balancedStringSplit(self, s: str) -> int:
       return list(accumulate(1 if c =='R' else -1 for c in s)).count(0)
'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1592. Rearrange Spaces Between Words

class Solution:
    def reorderSpaces(self, text: str) -> str:
        space = text.count(" ")
        words = text.split()
        wordlen = len(words)
        if wordlen-1>0:
            c = space//(wordlen-1)
        else:
            c = space
        res = ""
        for i in words:
            res += i
            if space >= c:
                res += " "*c
                space -= c

        if space>0:
            res += " "*space
        return res

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 2325. Decode the Message
class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
       dic = {' ':' '}
       c = 97
       for i in range(len(key)):
           if key[i] not in dic:
               dic[key[i]] = chr(c)
               c += 1

       result = ''
       for i in range(len(message)):
            result += dic[message[i]]
       return result

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 2160. Minimum Sum of Four Digit Number After Splitting Digits

class Solution:
    def minimumSum(self, num: int) -> int:
        nums = list(str(num))
        nums.sort()
        return int(nums[0] + nums[-1]) + int(nums[1] + nums[2])

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1859. Sorting the Sentence
class Solution:
    def sortSentence(self, s: str) -> str:
        words = s.split()

        sorted_words = sorted(words, key=lambda x: int(''.join(filter(str.isdigit, x))))

        words_without_numbers = [''.join(filter(str.isalpha, word)) for word in sorted_words]

        result = ' '.join(words_without_numbers)

        return result
'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER : 1844. Replace All Digits with Characters
class Solution:
    def replaceDigits(self, s: str) -> str:
        result =''
        for i in range(len(s)):
            if s[i].isnumeric() == True:
                result += chr(ord(s[i-1])+int(s[i]))
            else:
                result +=s[i]
        return result

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 1812. Determine Color of a Chessboard Square

class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        alpha = ['a','b','c','d','e','f','g','h']
        for i in range(len(alpha)):
            for j in range(1,9):
                if alpha[i] + str(j) == coordinates:
                    if (i+j) %  2 == 0:
                        return True
        else:
            return False

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 1374. Generate a String With Characters That Have Odd Counts

class Solution:
    def generateTheString(self, n: int) -> str:
        return "a" * n if  n % 2 else "a" * (n-1) +"b"

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 2000. Reverse Prefix of Word
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        reverse = ""
        if ch not in word:
            return word
        for i in range(len(word)):
            if word[i] == ch:
                reverse += word[0:i+1]
                reverse = reverse[::-1]
                reverse += word[i+1:]
                break
        return reverse

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  :1941. Check if All Characters Have Equal Number of Occurrences

#Method 1
class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        sets = set()
        for i in range(len(s)):
            count = 0
            for j in range(len(s)):
                if s[i] == s[j]:
                    count += 1
            sets.add(count)

        return True if len(sets) == 1 else False

#Mehtod 2
class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        lst=[]
        for i in s:
            c=s.count(i)
            lst.append(c)
        if min(lst)==max(lst):
            return True
        else:
            return False

#Method 3
class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        char_count = {}
        for char in s:
            char_count[char] = char_count.get(char, 0) + 1

        return len(set(char_count.values())) == 1

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 1309. Decrypt String from Alphabet to Integer Mapping

#Method 1
class Solution:
    def freqAlphabets(self, s: str) -> str:
        for i in range(26,0,-1):
            s = s.replace(str(i)+"#", chr(ord("a")+i-1)) if i>9 else s.replace(str(i), chr(ord("a")+i-1))
        return s

#Method 2
class Solution:
    def freqAlphabets(self, s: str) -> str:
        ans = ""
        i = len(s)-1
        while i>=0:
            if s[i]=="#":
                ans = ans + chr(int(s[i-2:i])+96)
                i=i-2
            else:
                ans = ans + chr(int(s[i])+96)
            i -= 1
        return ans[::-1]
'''--------------------------------------------------------------------------------------------------------------------------------------'''

#QUESTION NUMBER  : 2278. Percentage of Letter in String

class Solution:
    def percentageLetter(self, s: str, letter: str) -> int:
        count = s.count(letter)
        percentage = (count / len(s)) * 100
        return math.floor(percentage)

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 2351. First Letter to Appear Twice
class Solution:
    def repeatedCharacter(self, s: str) -> str:
        res = ''
        for i in range(len(s)):
            if s[i] in res:
                return s[i]
            else:
                res += s[i]
        return res

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 1684. Count the Number of Consistent Strings

#Method 1
class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        count = 0
        for word in words:
            if all(char in allowed for char in word):
                count += 1
        return count

#Method 2
class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        res = 0
        allow = Counter(allowed)
        for word in words:
            flag = 1
            for letter in word:
                if letter not in allow:
                    flag = 0
                else:
                    continue
            if flag:
                res += 1
        return res
'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 2108. Find First Palindromic String in the Array
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        for i in range(len(words)):
            current_word = words[i]
            if current_word == current_word[::-1]:
                return current_word
        return ""

'''--------------------------------------------------------------------------------------------------------------------------------------'''
#QUESTION NUMBER  : 2185. Counting Words With a Given Prefix

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        count = 0
        for i in range(len(words)):
            current_word = words[i]
            if current_word[:len(pref)] == pref:
                count += 1
        return count


from collections import defaultdict
from typing import Any

def reformat_emissions(emissions: list[dict], subsector: str) -> list[dict]:
    """Select `subsector` emissions and simplify format.

    Expected format of `emissions` arg is:
    `emissions = [country_a, country_b ...]`, where
    `country_a =  {"name": country_code, "data": subsector_data}`, where
    `subsector_data =  {"name": subsector, "emissions": subs_emissions}`, where
    `subs_emissions =  ["year": y, ghg: value_in_tonnes ...]`

    Format returned by this function is:
    `emissions = [yearly_emissions_a ...]`, where
    `yearly_emissions_a = {"year": y, country_code: co2e_in_tonnes ...}`
    for the requested subsector.

    Warning! Only the "co2100" attribute (CO2 equivalent after 100 years)
    is selected.

    Args:
        emissions: Data received from Climate TRACE. See format above.
        subsector: Name of subsector to select the data for.

    Returns:
    """
    # Keys are years, value is dict like `yearly_emissions_a` from docstring
    country_emissions = defaultdict(dict)

    for country in emissions:
        country_code = country["name"]

        for subsector_data in country["data"]:
            if subsector_data["name"] != subsector:
                continue

            # Add each year of emissions for this country
            for yearly_e in subsector_data["emissions"]:
                year = yearly_e["year"]
                # Convert to million tonnes
                million_co2 = yearly_e["co2100"] / 1000000
                country_emissions[year][country_code] = million_co2

    # Add year attribute to each dict
    country_emissions = {
        y: dict(data, **{"year": y})
        for y, data in country_emissions.items()
    }
    # Drop the keys and return as list of yearly emissions
    parsed = list(country_emissions.values())
    return parsed


"""
    Step-Based
    REPS algorithm on Pendulum Environment
    Gaussian Policy, Linear Mean.
    RBF Features
"""
import gym
# from gym.envs.classic_control.pendulum import PendulumEnv
from rl.featurizer.rbf_featurizer import RBFFeaturizer
from rl.trash.value_estimator_np import ValueEstimatorNP
from rl.trash.gaussian_policy_np import GaussianPolicyNP
#
import numpy as np

#
env = gym.make('Pendulum-v0')
# env = RandomJumpEnv()
print("Action space : ", env.action_space)
print("Action space low : ", env.action_space.low)
print("Action space high: ", env.action_space.high)
print("Observation space : ", env.observation_space)
print("Observation space low : ", env.observation_space.low)
print("Observation space high: ", env.observation_space.high)

def calculate_Return(rewards, gamma=0.95):
    R = np.zeros_like(rewards)
    R_sum = 0
    for t in reversed(range(0, rewards.shape[0])):
        R_sum = R_sum * gamma + rewards[t]
        R[t] = R_sum
    # R -= np.mean(R)
    # R = np.exp( (R - np.min(R)) / (np.max(R) - np.min(R)) )
    # beta = 3. / (np.max(rewards) - np.min(rewards))
    # weights = np.exp((rewards-np.max(rewards)) * beta)
    # weights = weights / sum(weights)
    return R
#
def step_reps(env, featurizer, policy_fn, num_episodes, num_steps, num_samples, value_fn, eta_init, v_init, epsilon, gamma=1.0):
    H = 20
    m = featurizer.num_features
    T = 200
    n = env.action_space.shape[0]
    for i_eposide in range(num_episodes):
        # samples
        Phi_n = np.zeros(shape=(T,H,m))
        A = np.zeros(shape=(T,H,n))
        Q = np.zeros(shape=(T,H,1))
        for h in range(H):
            state = env.reset()
            rewards = np.zeros(shape=(T,1))
            # rollouts
            for t in range(T):
                action = policy_fn.predict_step(state)
                next_state, reward, done, _ = env.step(action)
                #
                Phi_n[t, h, :] = featurizer.transform(state)
                A[t, h, :] = action
                rewards[t] = reward
                # Q[t, h, :] = reward
                #
                state = next_state
            Returns = calculate_Return(rewards)
            #
            Q[:, h, :] = Returns
        # norm_Q = np.zeros(shape=(H, T, 1))
        # for h in range(H):
        #     norm_Q[h, :, :] = (Q[h,:,:] - np.min(Q, axis=1)) / (np.max(Q, axis=1) - np.min(Q, axis=1))
        #
        policy_fn.update_step(weights=Q,
                              Phi=Phi_n,
                              Actions=A)
        print(np.sum(Q))

def episode_reps(env, featurizer, policy_fn, num_episodes, num_samples, num_steps):
    for i_episodes in range(num_episodes):
        # init_state = env.reset()
        theta_samples = policy_fn.samples_theta(num_samples)
        rewards = np.zeros(num_samples)
        for i_samples in range(num_samples):
            state = env.reset()
            # state = init_state
            rewards_rollout = np.zeros(shape=num_steps)
            theta = theta_samples[i_samples]
            for t in range(num_steps):
                action = policy_fn.predict_episode(state, theta)
                next_state, reward, done, _ = env.step(action)
                rewards_rollout[t] = reward
                state = next_state
                if done:
                    break
            # Returns = calculate_Return(re)
            rewards[i_samples] = np.sum(rewards_rollout)
        beta = 5. / (np.max(rewards) - np.min(rewards))
        weights = np.exp((rewards-np.max(rewards)) * beta)
        weights = weights / sum(weights)
        policy_fn.update_episode(weights=weights, theta_samples=theta_samples)
        print("episode, ", i_episodes, np.mean(rewards))
        if i_episodes >= 700:
            obs = env.reset()
            while True:
                env.render()
                action = policy_fn.predict_step(obs)
                next_obs, reward, done, _ = env.step(action)
                obs = next_obs
                if done:
                    break

#
dim_featuries = 5
rbf_featurizer = RBFFeaturizer(env=env, dim_features=dim_featuries, beta=50)
# rbf_featurizer.plot_examples()
# time.sleep(1)
# plt.close()
#
policy_fn = GaussianPolicyNP(env, rbf_featurizer)
value_fn = ValueEstimatorNP(rbf_featurizer)
param_v = value_fn.param_v
param_eta = 3
epsilon = 5e-1
#
num_samples = 10
num_steps = 200
num_episodes = 10000
#
# step_reps(env=env,
#           featurizer=rbf_featurizer,
#           policy_fn = policy_fn,
#           value_fn = value_fn,
#           num_episodes = num_episodes,
#           num_steps = num_steps,
#           num_samples=num_samples,
#           eta_init=param_eta,
#           v_init=param_v,
#           epsilon=epsilon,
#           gamma=1.0)
episode_reps(env=env,
             featurizer=rbf_featurizer,
             policy_fn = policy_fn,
             num_episodes=num_episodes,
             num_samples = num_samples,
             num_steps=num_steps)


from replay_buffer import PriorityExperienceReplay
from ExperienceBuffer import DdpgBuffer
from actor import SacActor, DdpgActor
from critic import SacCritic, DdpgCritic
from Dataloader import Dataloader
from EnvironmentSimulator import EnvironmentSimulator
from RepresentationModel import RepresentationModel
from RecommendSystem import RecommendSystem

'''生成推荐系统所需要的:
1.环境
2.状态表示模块
3.actor
4.critic
5.经历重放的容器
'''

def RecommenderInitialization():
    dataloader = Dataloader()
    users_history_dict_train = dataloader.users_history_dict_train
    lens_list_train = dataloader.lens_list_train
    positive_lens_list_train = dataloader.positive_lens_list_train
    movies_id_to_movies = dataloader.movies_id_to_movies

    users_history_dict_eval = dataloader.users_history_dict_eval
    lens_list_eval = dataloader.lens_list_eval
    positive_lens_list_eval = dataloader.positive_lens_list_eval

    # 训练环境
    environment_train = EnvironmentSimulator(short_term_state_size=10, users_history_dict=users_history_dict_train,
                                             lens_list=lens_list_train,
                                             positive_lens_list=positive_lens_list_train,
                                             movies_information=movies_id_to_movies)
    # 验证环境
    environment_eval = EnvironmentSimulator(short_term_state_size=10, users_history_dict=users_history_dict_eval,
                                            lens_list=lens_list_eval,
                                            positive_lens_list=positive_lens_list_eval,
                                            movies_information=movies_id_to_movies,top_k=10)

    # 状态标识模块
    representationModel = RepresentationModel(short_term_state_size=10)

    # actor
    sac_actor = SacActor(state_dim=300, hidden_dim=128, action_dim=100, learning_rate=0.001,
                         target_network_update_rate=0.001)
    # critic
    sac_critic = SacCritic(state_dim=300, action_dim=100, hidden_dim=128, learning_rate=0.001,
                           target_network_update_rate=0.001)
    # 经历重放容器
    sac_buffer = PriorityExperienceReplay(buffer_size=1000000, embedding_dim=100)

    # actor
    ddpg_actor = DdpgActor(state_dim=300, hidden_dim=128, action_dim=100, learning_rate=0.001,
                         target_network_update_rate=0.001)
    # critic
    ddpg_critic = DdpgCritic(state_dim=300, action_dim=100, hidden_dim=128, learning_rate=0.001,
                           target_network_update_rate=0.001)
    # 经历重放容器
    ddpg_buffer = DdpgBuffer(buffer_size=1000000, embedding_dim=100)

    return environment_train, environment_eval, representationModel, sac_critic, sac_actor, sac_buffer,ddpg_critic, ddpg_actor, ddpg_buffer

# 状态表示模块两个网络，actor四个网络，critic两个网络，总共八个网络
environment_train, environment_eval, representationModel, sac_critic, sac_actor, sac_buffer,ddpg_critic, ddpg_actor, ddpg_buffer = RecommenderInitialization()

recommend_system = RecommendSystem(env=environment_train, representation_model=representationModel, sac_actor=sac_actor,
                                   sac_critic=sac_critic, sac_buffer=sac_buffer, ddpg_actor=ddpg_actor,
                                   ddpg_critic=ddpg_critic, ddpg_buffer=ddpg_buffer)

recommend_system_eval = RecommendSystem(env=environment_eval, representation_model=representationModel, sac_actor=sac_actor,
                                   sac_critic=sac_critic, sac_buffer=sac_buffer, ddpg_actor=ddpg_actor,
                                   ddpg_critic=ddpg_critic, ddpg_buffer=ddpg_buffer)

recommend_system.ddpg_critic.load_weights(r'actor_critic_weights/ddpg/critic_5000.h5')
recommend_system.ddpg_actor.load_weights(r'actor_critic_weights/ddpg/actor_5000.h5')
recommend_system.sac_critic.load_weights(r'actor_critic_weights/sac/critic_5000.h5')
recommend_system.sac_actor.load_weights(r'actor_critic_weights/sac/actor_mean5000.h5',r'actor_critic_weights/sac/actor_logvar5000.h5')

recommend_system_eval.ddpg_critic.load_weights(r'actor_critic_weights/ddpg/critic_5000.h5')
recommend_system_eval.ddpg_actor.load_weights(r'actor_critic_weights/ddpg/actor_5000.h5')
recommend_system_eval.sac_critic.load_weights(r'actor_critic_weights/sac/critic_5000.h5')
recommend_system_eval.sac_actor.load_weights(r'actor_critic_weights/sac/actor_mean5000.h5',r'actor_critic_weights/sac/actor_logvar5000.h5')

print("已加载ddpg")
recommend_system_eval.evaluation(max_user_id=6400,top_k=10)
recommend_system.train(max_episode_num=8000)
print("shit")


#Daniel Durham 1851947

import csv

input1 = input()

uppercase_freq = {}
lowercase_freq = {}

with open(input1, 'r') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        for word in row:
            word = word.strip()

            if word.isupper():
                uppercase_freq[word] = uppercase_freq.get(word, 0) + 1
            else:
                lowercase_freq[word] = lowercase_freq.get(word, 0) + 1

for word, frequency in lowercase_freq.items():
    print(f'{word} {frequency}')
for word, frequency in uppercase_freq.items():
    print(f'{word} {frequency}')


#!/usr/bin/env python
from __future__ import unicode_literals, print_function
import ffmpeg
import sys
import praw

def submissionHandling(submission):
	url = submission.url

	if (url.endswith('mp4') or url.endswith('.webm')):
		print('Direct Link Provided')
	elif "imgur" in url:
	  url = (url.rstrip("gifv") + "mp4")
	else:
		print('Not a gif')
		return

	try:
		probe = ffmpeg.probe(url)
	except ffmpeg.Error as e:
		print(e.stderr, file=sys.stderr)
		sys.exit(1)

	video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
	if video_stream is None:
		print('No video stream found', file=sys.stderr)
		sys.exit(1)

	if ("mp4" in url):
		flair = (video_stream['duration']).strip('0')         # FOR MP4
	elif ('webm' in url):
		flair = (video_stream['tags']['DURATION']).strip('0:') # FOR WEBM

	flair = (str(round(float(flair),2)) + ' seconds')
	print(flair)
	submission.mod.flair(flair)
	return


"""
Contains operations regarding token model
"""

import uuid
from datetime import datetime, timedelta
from django.core.exceptions import ObjectDoesNotExist

from rest_framework.response import Response

from ..models import User,User_token
from .user import authenticate

def insert_token(*, request):
    """
    Inserts token in user_token table with row user_id.
    """

    auth = authenticate(request=request)
    if auth is not True:
        return auth

    token = str(uuid.uuid4())
    expiration_time= datetime.now() + timedelta(seconds=3600)
    user = User.objects.get(email=request.data.get('email'))

    try:
        user_token = User_token.objects.get(user=user)
        user_token.token=token
        user_token.expiration_time = expiration_time
        user_token.save()

    except ObjectDoesNotExist:
        User_token.objects.create(user=user, token=token, expiration_time=expiration_time)

    return Response(data={"token":token},status=200,content_type="application/json")

def validate_token(*, request):
    """
    Validates token and returns if user is admin
    """
    token= request.headers.get("Authorization")
    status=True

    error=''

    if not token:
        error+=  "Token is required"
        status = False

    if not isinstance(token , str):
        error = "Token should be str"
        status = False

    if not token.startswith("Bearer"):
        error= "Invalid Token"
        status = False

    try:
        token=token.split(' ')[1]

    except IndexError:
        error= "Invalid Token"
        status = False

    if status is False:
        return Response(data={"message":error},status=400)

    current_time = datetime.now().time()

    try:
        user_token= User_token.objects.get(token=token)

    except ObjectDoesNotExist:
        return None

    if user_token.expiration_time<current_time:
        return None

    user=User.objects.get(id=user_token.user_id)
    return user


"""
Valid Palindrome:

take aways:

isalnum() ->

isalpha() ->

"""

def valid_palindrome(string):
    start = 0
    last = len(string) - 1
    while start <= last:
        if string[start].isalnum() and string[last].isalnum():
            if string[start].lower() != string[last].lower():
                return False
            start += 1
            last -= 1
        elif not string[start].isalnum():
            start += 1
        elif not string[last].isalnum():
            last -= 1

    return True


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math
import time
import numpy as np
import tensorflow as tf

from tensorflow.contrib.distributions import Normal

def data_type():
    return tf.float32

def inv_soft_plus(x):
    return math.log(math.exp(x) - 1.0)

def get_KL_divergence_Sample(shape, mu, sigma, prior, Z):

    """
    Compute KL divergence between posterior and prior.
    Instead of computing the real KL distance between the Prior and Variatiational
    posterior of the weights, we will jsut sample its value of the specific values
    of the sampled weights  W.

    In this case:
        - Posterior: Multivariate Independent Gaussian.
        - Prior: Mixture model

    The sample of the posterior is:
        KL_sample = log(q(W|theta)) - log(p(W|theta_0)) where
         p(theta) = pi*N(0,sigma1) + (1-pi)*N(0,sigma2)

    Input:
        - mus,sigmas:
        - Z: Samples weights values, the hidden variables !
    shape = shape of the sample we want to compute the KL of
    mu = the mu variable used when sampling
    sigma= the sigma variable used when sampling
    prior = the prior object with parameters
    sample = the sample from the posterior

    """

    # Flatten the hidden variables (weights)
    Z = tf.reshape(Z, [-1])

    #Get the log probability distribution of your sampled variable

    # Distribution of the Variational Posterior
    VB_distribution = Normal(mu, sigma)
    # Distribution of the Gaussian Components of the prior
    prior_1_distribution = Normal(0.0, prior.sigma1)
    prior_2_distribution = Normal(0.0, prior.sigma2)

    # Now we compute the log likelihood of those Hidden variables for their
    # prior and posterior.

    #get: sum( log[ q( theta | mu, sigma ) ] )
    q_ll = tf.reduce_sum(VB_distribution.log_prob(Z))

    #get: sum( log[ p( theta ) ] ) for mixture prior
    mix1 = tf.reduce_sum(prior_1_distribution.log_prob(Z)) + tf.log(prior.pi_mix)
    mix2 = tf.reduce_sum(prior_2_distribution.log_prob(Z)) + tf.log(1.0 - prior.pi_mix)
    p_ll = tf.reduce_logsumexp([mix1,mix2])

    #Compute the sample of the KL distance as the substaction ob both
    KL = q_ll -  p_ll

    return KL

class Prior(object):

    """
        Class in order to store the parameters fo the prior.
        When initialized it just stores the values to be used later.
        Input:
            -

    """

    def __init__(self, pi, log_sigma1, log_sigma2):
        self.pi_mix = pi
        self.log_sigma1 = log_sigma1
        self.log_sigma2 = log_sigma2
        self.sigma1 = tf.exp(log_sigma1)
        self.sigma2 = tf.exp(log_sigma2)
        sigma_one, sigma_two = math.exp(log_sigma1), math.exp(log_sigma2)
        self.sigma_mix = np.sqrt(pi * np.square(sigma_one) + (1.0 - pi) * np.square(sigma_two))

def sample_posterior(shape, name, prior, is_training):

    """
        In order to initialize the weights of our network we need to sample from
        the Variational Posterior.

        This function will be called for any element of the Model that used Bayesian weights.

        Since we are using TF, we have to adapt the way we treat the variables.
        In this case we want to optimize the parameters of the Variational Inference.
        There parameters will be optimized automatically by TF.

        In order to create and retrieve such wanderful variables we use the same function:
        tf.get_variable() to which we can indicate the variable to retrieve indicating:
          - Its name: In this case provided externally to avoid collisions
          - Its shape: We could obtain a subset of the original variable ?
          - Its type: The datatype of the variable
          - An initializer: The first time we use tf.get_variable() if the variable does
            not exist it will be created. If nothing specified it will be created with all 0s
            with a shape given by the parameter shape. We can also specify an initilizer that will
            initialize the variable the first time.

        The first time we want to sample from the posterior during training, the variable
        will not exist and it will be sampled from the Prior. The next times it will just be obtained.

        In this case the variables are the parameters of the posterior :), the mus and stds.

    """

    ## Initializer for the weights with the prior for the first sampling
    rho_max_init = inv_soft_plus(prior.sigma_mix / 2.0)
    rho_min_init = inv_soft_plus(prior.sigma_mix / 4.0)
    init = tf.random_uniform_initializer(rho_min_init, rho_max_init, dtype=data_type())

    ## Retrieve (and create in the first execution) the mus and rhos
    with tf.variable_scope("BBB", reuse = not is_training):
        mus = tf.get_variable(name + "_mean", shape = shape, dtype=data_type(),initializer=init)

#    print (shape)
#    print (is_training)
#    print (mus.dtype)
#    print (mus.shape)
#    print (data_type())

    with tf.variable_scope("BBB", reuse = not is_training):
        rhos = tf.get_variable(name + "_rho", shape = shape, dtype=data_type())

    # Sample a set of weights from the posterior.
    # Or if we are not training, sample the MAP weights which are the mean.

    if is_training:
        epsilon = Normal(0.0, 1.0).sample(shape)
        sigmas = tf.nn.softplus(rhos) + 1e-10
        Samples = mus + sigmas * epsilon
    else:
        Samples = mus

    ## Gather information for tensorflow if we are sampling while training
    if (is_training):
        # Save the values of the rhos, mus and sigmas of the posteior
        tf.summary.histogram(name + '_rho_hist', rhos)
        tf.summary.histogram(name + '_mu_hist', mus)
        tf.summary.histogram(name + '_sigma_hist', sigmas)

        # Save the KL divergence of these sampled weights
        kl = get_KL_divergence_Sample(shape, tf.reshape(mus, [-1]), tf.reshape(sigmas, [-1]), prior, Samples)
        tf.add_to_collection('KL_layers', kl)

    """
    TODO: So this function will only be called specifically once when the architecture is set
    and then we do not execute it again ? Tensorflow will only execute the parts that are used when we run
    a session in which we feed and fetch data ?
    At every session run, only the connecting part will be executed, so for the LSTM what we have to do is:
        - The very first time it is executed, it self.w = null then execute the normal initializer, the rest of
        times just sample the posterior, but just once, then do nothing. For each of the Batches.
    """
    print ("Posterior Sampling: %s"% name)
    return Samples

############################################################################
############ Alternative Versions of Sampling and KL ###########################
############################################################################

#def Independent_MultiGaussian_Sampling(name, mus, stds, shape):
#    """
#    This function will draw samples of the given Independent Multivariate Distribution
#    Using TensorFlow with a name so we can track them later.
#    The parameters are:
#            - name: Name of this operation for tensorboard
#            - mus: Vector with the means of the Independent Multivatiate Gaussian.
#            - stds: Vector with the standard deviation of the independent components
#    Output:
#        -
#    the given multivatiate distribution
#
#    """
#    with tf.variable_scope("Independent_MultiGaussian_Sampling"):
#
#        ## TODO: I have no idea why we multiply by 1
#        rhos = tf.multiply(inv_soft_plus(stds), tf.ones(shape))
#        mus = tf.multiply(mus,tf.ones(shape))
#
#        ## Create TensorFlow variables for the mean and the rhos
#        mus = tf.get_variable(name + "_mean", initializer = mus, dtype=tf.float32)
#        rhos = tf.get_variable(name + "_rho", initializer=rhos, dtype=tf.float32)
#
#        # Revert back to std for sampling I guess
#        stds = tf.nn.softplus(rhos)
#
#        # Sample as many parameters as shape says.
#        epsilon = tf.random_normal(mean=0.0, stddev=1.0, name="epsilon", shape=shape, dtype=tf.float32)
#
#        #random_var = mean + standard_deviation*epsilon
#        samples = tf.add(mus, tf.multiply(stds,epsilon))
#
#        return samples, mus, stds


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov  5 10:46:37 2018

@author: rodrigo
"""

#Multiples exones d eun fragmento de ADN

# open the genomic dna file and read the contents #LE DI LA DIRECCION DEL ARCHIVO
genomic_dna = open("/home/rodrigo/Descargas/Python-libros/lists_loops/genomic_dna.txt").read()
# open the exons locations file
exon_locations = open("/home/rodrigo/Descargas/Python-libros/lists_loops/exons.txt")
# create a variable to hold the coding sequence
coding_sequence = ""
# go through each line in the exon locations file
for line in exon_locations:
    # split the line using a comma
    positions = line.split(',')
    # get the start and stop positions
    start = int(positions[0])
    stop = int(positions[1])
    # extract the exon from the genomic dna
    exon = genomic_dna[start:stop]
    # append the exon to the end of the current coding sequence
    coding_sequence = coding_sequence + exon
# write the coding sequence to an output file
output = open("coding_sequence.txt", "w")
output.write(coding_sequence)
output.close()


from utils.app.const import OPENAI_API_HOST, OPENAI_API_TYPE, OPENAI_API_VERSION, OPENAI_ORGANIZATION
from types.openai import OpenAIModel, OpenAIModelID, OpenAIModels
from trpc import procedure, router
from trpc.errors import TRPCError
import requests
from typing import Optional
from zod import z

async def get_models(ctx, input):
    """
    Retrieve a list of OpenAI models.

    Args:
        ctx (dict): The TRPC context.
        input (dict): The input parameters.

    Returns:
        list: The list of OpenAI models.
    """
    key = input.get('key')

    url = f"{OPENAI_API_HOST}/v1/models"
    if OPENAI_API_TYPE == 'azure':
        url = f"{OPENAI_API_HOST}/openai/deployments?api-version={OPENAI_API_VERSION}"

    headers = {
        'Content-Type': 'application/json',
    }
    if OPENAI_API_TYPE == 'openai':
        headers['Authorization'] = f"Bearer {key or os.environ['OPENAI_API_KEY']}"
    elif OPENAI_API_TYPE == 'azure':
        headers['api-key'] = f"{key or os.environ['OPENAI_API_KEY']}"
    if OPENAI_API_TYPE == 'openai' and OPENAI_ORGANIZATION:
        headers['OpenAI-Organization'] = OPENAI_ORGANIZATION

    response = requests.get(url, headers=headers)

    if response.status_code == 401:
        raise TRPCError(code='UNAUTHORIZED', message='Unauthorized')
    elif response.status_code != 200:
        print(f"OpenAI API returned an error {response.status_code}: {response.text}")
        raise TRPCError(code='INTERNAL_SERVER_ERROR', message='OpenAI API returned an error')

    json_data = response.json()

    models = []
    for model in json_data['data']:
        model_name = model['model'] if OPENAI_API_TYPE == 'azure' else model['id']
        for key, value in OpenAIModelID.items():
            if value == model_name:
                model_info = OpenAIModels[value]
                model_obj = OpenAIModel(
                    id=model['id'],
                    name=model_info['name'],
                    maxLength=model_info['maxLength'],
                    tokenLimit=model_info['tokenLimit'],
                )
                models.append(model_obj)
                break

    return models

models = router({
    'list': procedure.input(z.object({
        'key': z.string().optional()
    })).query(get_models),
})


# 689. 三个无重叠子数组的最大和
# 给你一个整数数组 nums 和一个整数 k ，找出三个长度为 k 、互不重叠、且 3 * k 项的和最大的子数组，并返回这三个子数组。

# 以下标的数组形式返回结果，数组中的每一项分别指示每个子数组的起始位置（下标从 0 开始）。如果有多个结果，返回字典序最小的一个。

# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
from typing import List

class Solution:
    def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        preSum = [0]
        for i in nums:
            preSum.append(preSum[-1]+i)
        dp=[[0]*4 for _ in range(n+5)]
        for i in range(n-k+1,0,-1):
            for j in range(1,4):
                dp[i][j]=max(dp[i+1][j],dp[i+k][j-1]+preSum[i+k-1]-preSum[i-1])
        res = []
        i,j = 1,3
        while j>0:
            if dp[i+1][j]>dp[i+k][j-1]+preSum[i+k-1]-preSum[i-1]:
                i+=1
            else:
                res.append(i-1)
                i+=k
                j-=1
        return res

sol = Solution()
nums = [1,2,1,2,6,7,5,1]
k = 2
print(sol.maxSumOfThreeSubarrays(nums,k))


"""List of prime numbers generator."""
"""ENTER YOUR SOLUTION HERE!"""

def primes(number_of_primes):
    list = []
    curr = 2

    while (len(list) < number_of_primes):
        prime = True

        for i in range(2, curr):
            if (curr % i == 0):
                prime = False
                break

        if (prime):
            list.append(curr)

        curr += 1

    return list


# Split csv matrix into csv vectors for pytorch traning
import os
os.chdir("/root/workspace/code/midas/")
import os.path as path
from os.path import join as pj
import argparse
import sys
sys.path.append("modules")
import utils
import csv
import math
from glob import glob
from tqdm import tqdm

parser = argparse.ArgumentParser()
parser.add_argument('--task', type=str, default="ct1_tp1")
o = parser.parse_args()

base_dirs = glob(pj("data", "processed", o.task, "subset_*"))
for base_dir in base_dirs:
    # Specify directories
    in_dir = pj(base_dir, "mat")
    out_dir = pj(base_dir, "vec")
    utils.mkdirs(out_dir, remove_old=True)
    print("\nDirectory: %s" % (in_dir))

    # Load and save data
    mat_names = glob(pj(in_dir, '*.csv'))  # get filenames
    for i, mat_name in enumerate(mat_names):
        # load
        mat = utils.load_csv(mat_name)
        # mat = utils.transpose_list(mat)
        mod = path.splitext(path.basename(mat_name))[0]
        cell_num = len(mat) - 1
        feat_num = len(mat[0]) - 1
        print("Spliting %s matrix: %d cells, %d features" % (mod, cell_num, feat_num))

        # save
        out_mod_dir = pj(out_dir, mod)
        utils.mkdirs(out_mod_dir, remove_old=True)
        vec_name_fmt = utils.get_name_fmt(cell_num) + ".csv"
        vec_name_fmt = pj(out_mod_dir, vec_name_fmt)
        for cell_id in tqdm(range(cell_num)):
            vec_name = vec_name_fmt % cell_id
            utils.save_list_to_csv([mat[cell_id+1][1:]], vec_name)


import sys
sys.stdin = open('input.txt')

def solution(N):
    global total
    result = 0
    r_number = sorted(number, reverse=True)

    if number == r_number:
        return 0
    else:
        for i in range(N):
            maximum = max(number)
            if number[i] != maximum:
                total.append(number[i])
            elif number[i] == maximum:
                for j in range(len(total)):
                    result += abs(total[j] - number[i])
                total = []
            number[i] = 0
        return result

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    number = list(map(int, input().split()))
    print(number)
    total = []

    print('#{} {}'.format(tc, solution(N)))


import sys
import traceback

import opentracing
from opentracing.ext import tags

from signalfx_tracing.utils import padded_hex

SCOPE_KEY = "_signalfx_scope_key"

class TraceMiddleware(object):
    def __init__(self, tracer=None, attributes=None, trace_response_header_enabled=False):
        self.tracer = tracer or opentracing.tracer
        self.attributes = attributes or []
        self.trace_response_header_enabled = trace_response_header_enabled

    def process_request(self, req, resp):
        operation_name = req.path

        try:
            span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS, req.headers)
            scope = self.tracer.start_active_span(operation_name, child_of=span_ctx)
        except (
            opentracing.InvalidCarrierException,
            opentracing.SpanContextCorruptedException,
        ):
            scope = self.tracer.start_active_span(operation_name)

        span = scope.span
        span.set_tag(tags.COMPONENT, "Falcon")
        span.set_tag(tags.HTTP_METHOD, req.method)
        span.set_tag(tags.HTTP_URL, req.uri.split("?")[0])
        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)
        for attr in self.attributes:
            attr_val = getattr(req, attr, None)
            if attr_val:
                span.set_tag(attr, attr_val)

        setattr(req, SCOPE_KEY, scope)

    def process_resource(self, req, resp, resource, params):
        scope = getattr(req, SCOPE_KEY, None)
        if scope is None:
            return
        resource_name = resource.__class__.__name__
        scope.span.set_tag("falcon.resource", resource_name)
        scope.span.set_operation_name(
            "{0}.on_{1}".format(resource_name, req.method.lower())
        )

    def process_response(self, req, resp, resource, req_succeeded=None):
        scope = getattr(req, SCOPE_KEY, None)
        if scope is None:
            return

        status = resp.status

        if resource is None:
            status = "404"

        err_type, exc, tb = sys.exc_info()
        if err_type is not None:
            if not req_succeeded:
                if "HTTPNotFound" in err_type.__name__:
                    status = "404"
                else:
                    status = "500"
                    scope.span.set_tag(tags.ERROR, True)
                    scope.span.set_tag("sfx.error.message", str(exc))
                    scope.span.set_tag("sfx.error.object", str(exc.__class__))
                    scope.span.set_tag("sfx.error.kind", exc.__class__.__name__)
                    if tb:
                        scope.span.set_tag(
                            "sfx.error.stack", "".join(traceback.format_tb(tb))
                        )

        scope.span.set_tag(tags.HTTP_STATUS_CODE, status.split(" ")[0])

        if self.trace_response_header_enabled:
            trace_id = getattr(scope.span.context, "trace_id", 0)
            span_id = getattr(scope.span.context, "span_id", 0)
            if trace_id and span_id:
                resp.append_header("Access-Control-Expose-Headers", "Server-Timing")
                resp.append_header(
                    "Server-Timing", 'traceparent;desc="00-{trace_id}-{span_id}-01"'.format(
                        trace_id=padded_hex(trace_id),
                        span_id=padded_hex(span_id),
                    ),
                )
        scope.close()


#!/usr/bin/env python3

# parse_treks.3.py

# Shu-Ting Cho <vivianlily6@hotmail.com>
# Read T-REKS's result and output tsv

# v1 2022/04/21
# v2 2022/03/02
# v3 2022/05/12 Use argparse

# Usage:
# python3 parse_treks.3.py --in_file=~/project/TR02/TR02.23/aa_TREKS/K24263.out --out_file=~/project/TR02/TR02.23/aa_tsv/K24263.tsv

## import modules
import os
import sys
import re
import argparse

# parsing arguments
def parse_args():
	parser = argparse.ArgumentParser(description="Read T-REKS's result and output tsv.")
	parser.add_argument('-i', '--in_file', help="T-REKS's result")
	parser.add_argument('-o', '--out_file', help="output .tsv file")
	return parser.parse_args()

args = parse_args()

out_f = open(str(args.out_file), "w")
out_f.write("seqID\tstart\tend\tscore\n")

# Opening result file
with open(str(args.in_file)) as in_f:
	lines = in_f.readlines()
	for line in lines:
		if line[0] == '>':
			line = line.rstrip()
			seqID = line[1:]

		elif line[:6] == 'Length':
			line = line.rstrip()
			list_info = re.findall(r'from[\s]+([0-9]+)[\s]+to[\s]+([0-9]+)[\s]+-[\s]+Psim:([\S]+)', line)
			start = int(list_info[0][0])
			end = int(list_info[0][1])
			score = float(list_info[0][2])
			out_f.write('%s\t%i\t%i\t%f\n' % (seqID, start, end, score))
			#print('%s\t%i\t%i\t%f' % (seqID, start, end, score))
out_f.close()


class LogReader:
    iter_loss_log = {}
    activations_log = {}
    weight_log = {}

    def process_iter_log_line(self, line):
        iter_num = int(line.split()[1].rstrip(','))
        iter_loss = float(line.split()[-1])
        self.iter_loss_log[iter_num] = iter_loss

    def process_activation_log_line(self, line):
        info_line, value_line = line.split('\t')
        unit_type = info_line.split()[2]
        unit_idx = int(info_line.split()[4])

        unit_char = info_line.split()[7].rstrip(')') if "represents char" in info_line else None

        input_char = info_line.split()[-1]
        value = float(value_line)

        if unit_type not in self.activations_log.keys():
            self.activations_log[unit_type] = {}

        if unit_idx not in self.activations_log[unit_type].keys():
            self.activations_log[unit_type][unit_idx] = {}

        self.activations_log[unit_type][unit_idx][input_char] = (
            {
                "unit_char": unit_char,
                "input_char": input_char,
                "value": value
            }
        )

    def process_weight_log_line(self, line):
        info_line, value_line = line.split('\t')
        source_unit_line, target_unit_line = line.split(" to ")

        source_unit_line = source_unit_line.lstrip("weight ")

        source_unit_type = source_unit_line.split()[0]
        source_unit_idx = int(source_unit_line.split()[2])
        source_unit_char = source_unit_line.split()[-1].rstrip(')') if "represents" in source_unit_line else None

        target_unit_type = target_unit_line.split()[0]
        target_unit_idx = target_unit_line.split()[2]
        target_unit_char = target_unit_line.split()[-1].rstrip(')') if "represents" in source_unit_line else None

        value = float(value_line)

        if source_unit_type not in self.weight_log.keys():
            self.weight_log[source_unit_type] = {}

        if source_unit_idx not in self.weight_log[source_unit_type].keys():
            self.weight_log[source_unit_type][source_unit_idx] = {}

        if target_unit_type not in self.weight_log[source_unit_type][source_unit_idx].keys():
            self.weight_log[source_unit_type][source_unit_idx][target_unit_type] = {}

        self.weight_log[source_unit_type][source_unit_idx][target_unit_type][target_unit_idx] = {
            "source_unit_char": source_unit_char,
            "target_unit_char": target_unit_char,
            "value": value
        }

    def parse_log_file(self, log_file):
        for line in log_file:
            line = line.rstrip()
            if line is None:
                continue
            elif line.startswith("iter"):
                self.process_iter_log_line(line)
            elif line.startswith("activation"):
                self.process_activation_log_line(line)
            elif line.startswith("weight"):
                self.process_weight_log_line(line)


"""
Referencia:
https://www.hashtagtreinamentos.com/enumerate-no-python?gclid=CjwKCAiAoL6eBhA3EiwAXDom5nu0Q61RfdOwzHIVMPIf7IJEfD3RJKNIyGbbLOA7ictHjh3vpVc8SRoCMdsQAvD_BwE
"""

vendedores = ['Marcus', 'Amanda', 'Ale', 'Carol']
vendas = [15, 20, 10, 30]

def forma_convencional():
    tamanho_lista = len(vendedores)
    for i in range(tamanho_lista):
        print(vendedores[1])
        print(vendas[i])

# Caso 2 com Enumerate
def forma_enumerate():
    for i, vendedor in enumerate(vendedores):
        print(vendedor)
        print(vendas[i])

# Caso 3: Com zip
def forma_zip():
    for vendedor, venda, in zip(vendedores, vendas):
        print(vendedor)
        print(venda)

forma_convencional()


#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

# connect to DB and create a session
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
Session = sessionmaker(bind=engine)
session = Session()

class webserverHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            if self.path.endswith('/restaurants'):
                restaurants = session.query(Restaurant).all()
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                list = '
'
                for r in restaurants:
                    # if type(r.name)!='str':
                    #     session.delete(r)
                    #     session.commit()
                    list += '
' + r.name + '
'
                    list += "Edit
".format(r.id)
                    list += "Delete

".format(r.id)
                list += '
'
                output = "
Make a New Restaurant Here !
"
                output += list
                output += ''
                self.wfile.write(output.encode('utf-8'))
                return
            if self.path.endswith('/restaurants/new'):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                output = ""
                output += ""
                output += "
Make a New Restaurant
"
                output += """
                             <form method='POST' action='/restaurants/new'' enctype='multipart/form-data'>
                                <input name='newRestaurantName' type='text'>
                                <input type='submit' value='Create'>
                             </form>
                """
                output += ""
                self.wfile.write(output.encode('utf-8'))
                return
            if self.path.endswith('/edit'):
                id = self.path.split('/')[2]
                restaurant = session.query(Restaurant).filter_by(id=id).one()
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                output = ""
                output += ""
                output += "
" + restaurant.name + "
"
                output += """
                             <form method='POST' action='/restaurants/{}/edit'' enctype='multipart/form-data'>
                                <input name='restaurantName' value='{}' type='text'>
                                <input type='submit' value='Update'>
                             </form>
                """.format(id, restaurant.name)
                output += ""
                self.wfile.write(output.encode('utf-8'))
                return
            if self.path.endswith('/delete'):
                id = self.path.split('/')[2]
                restaurant = session.query(Restaurant).filter_by(id=id).one()
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                output = ""
                output += ""
                output += "
Are you sure you want to delete {} ?
".format(restaurant.name)
                output += """
                             <form method='POST' action='/restaurants/{}/delete'' enctype='multipart/form-data'>
                                <input type='submit' value='Delete'>
                             </form>
                """.format(id)
                output += ""
                self.wfile.write(output.encode('utf-8'))
                return
        except IOError:
            self.send_error(404, 'File not found {}'.format(self.path))

    def do_POST(self):
        # try:
        if self.path.endswith('/restaurants/new'):
            ctype, pdict = cgi.parse_header(self.headers.get('content-type', ''))
            pdict['boundary'] = pdict['boundary'].encode()
            if ctype=='multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict) # DEALS with bytes
                messagecontent = fields.get('newRestaurantName')[0].decode()
            new_restaurant = Restaurant(name=messagecontent)
            session.add(new_restaurant)
            session.commit()
            self.send_response(301)
            self.send_header('location', '/restaurants')
            self.end_headers()
            return
        if self.path.endswith('/edit'):
            ctype, pdict = cgi.parse_header(self.headers.get('content-type', ''))
            pdict['boundary'] = pdict['boundary'].encode()
            if ctype=='multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict) # DEALS with bytes
                messagecontent = fields.get('restaurantName')[0].decode()
            id = self.path.split('/')[2]
            restaurant = session.query(Restaurant).filter_by(id=id).one()
            restaurant.name = messagecontent
            session.add(restaurant)
            session.commit()
            self.send_response(301)
            self.send_header('location', '/restaurants')
            self.end_headers()
            return
        if self.path.endswith('/delete'):
            id = self.path.split('/')[2]
            restaurant = session.query(Restaurant).filter_by(id=id).one()
            session.delete(restaurant)
            session.commit()
            self.send_response(301)
            self.send_header('location', '/restaurants')
            self.end_headers()
            return
        # except:
            # pass

def main():
    try:
        port = 8080
        server = HTTPServer(('', port), webserverHandler)
        print("The server is running on port {}".format(port))
        server.serve_forever()
    except KeyboardInterrupt:
        print('^C entered, stopping the web server ...')
        server.socket.close()

if __name__ == '__main__':
    main()


import unittest
from mock import Mock, patch

import foundations_contrib.helpers.shell as shell

from foundations_spec.helpers.spec import Spec
from foundations_spec.helpers import let

class TestShell(Spec):

    @let
    def winreg(self):
        # hack to deal with testing on non-windows machines
        module_callback = self.patch('foundations_contrib.helpers.shell._winreg_module')
        module_callback.return_value = Mock()
        return module_callback.return_value

    def test_find_bash_returns_default_bash(self):
        self.assertEqual('/bin/bash', shell.find_bash())

    @patch('os.name', 'nt')
    def test_queries_correct_registry_on_windows(self):
        self.winreg.HKEY_CLASSES_ROOT = 'HKEY_CLASSES_ROOT'
        self.winreg.QueryValue.return_value = 'null 0 0'
        shell.find_bash()
        self.winreg.QueryValue.assert_called_with('HKEY_CLASSES_ROOT', 'Directory\shell\git_shell\command')

    @patch('os.name', 'nt')
    def test_find_bash_returns_bash_on_windows(self):
        self.winreg.QueryValue.return_value = '"C:\\path to\\git-bash.exe" 0 0'
        self.assertEqual('C:\\path to\\bin\\bash.exe', shell.find_bash())

    @patch('os.name', 'nt')
    def test_find_bash_returns_bash_on_windows_different_path(self):
        self.winreg.QueryValue.return_value = '"C:\\Program Files\\git\\git-bash.exe" 3 2'
        self.assertEqual('C:\\Program Files\\git\\bin\\bash.exe', shell.find_bash())


# https://www.hackerrank.com/challenges/py-set-mutations/problem
# Score: 10

number_of_elements = int(input())
set_elements = set(map(int, input().split()))
number_of_operations = int(input())
for _ in range(number_of_operations):
    operation_command, set_length = input().split()
    operation_set = set(map(int, input().split()))
    exec(f"set_elements.{operation_command}({operation_set})")
print(sum(set_elements))


# coding: utf-8
## Resize an image (either from  external apps' share-sheet, or via photo-roll)
import photos, appex, sys, console

if appex.is_running_extension():
    im = appex.get_image()
else:
    im = photos.pick_image()

if im is None:
    console.hud_alert("No image chosen", "error", 1.0)
    sys.exit(0)
else:
    assert str(type(im))[8:-2][4:].partition("ImagePlugin")[0] in ("Bmp", "Gif", "Jpeg", "Png", "Ppm", "Tiff")

    width, height = im.size
    percentage = int(console.input_alert("Resize image to _%", "Enter number"))
    fraction = percentage / 100.0
    new_width = int(round(width*float(fraction)))
    new_height = int(round(height*float(fraction)))
    im2 = im.resize((new_width, new_height))
    saved = photos.save_image(im2)

    if saved:
        console.hud_alert("Successfully saved resized image ({0}%)".format(int(percentage)))
    else:
        console.hud_alert("Unsuccessfully saved resized image ({0}%)".format(int(percentage)), "error")


# base64 라이브러리 사용
# from base64 import b64decode
#
# T = int(input())
#
# for t in range(T):
#     word = input()
#     ans = b64decode(word).decode('UTF-8')
#     print(f'#{t+1} {ans}')

T = int(input())

decode = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
          'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
          '0','1','2','3','4','5','6','7','8','9','+','/']

for t in range(T):
    s = list(input())
    w = ''
    origin = ''
    for i in range(len(s)):
        idx = decode.index(s[i])        # 알파벳 -> 표1 숫자로 변환
        binN = str(bin(idx))[2:]        # 표1 숫자 -> 2진수로 변환 + 0b 제거
        while len(binN) < 6:            # 앞에 0추가해 6bit 2진수로!
            binN = '0' + binN
        w += binN                       # 6자리가 되면 w에 추가
    for x in range(0, len(w), 8):       # 8bit 씩 잘라보기
        e = int(w[x:x+8], 2)            # 8bit의 2진수 -> 10진수로 변환
        origin += chr(e)                # 10진수의 아스키코드 값 -> 문자로 변환
    print(f'#{t+1} {origin}')


import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff

def main():
    st.title("Laadpaal Data")
    st.header("Importeren, opschonen en filteren van data")
    paalData = pd.read_csv('laadpaaldata.csv')
    paalData.head()
    st.code("paalData = pd.read_csv('laadpaaldata.csv')"
    "\npaalData.head()")
    fig = px.scatter(x=paalData['ChargeTime'],y=paalData['ConnectedTime'],labels={'x':'Laadtijd','y':'Aansluit tijd'})
    st.plotly_chart(fig)
    st.caption("Er is hier te zien dat er duidelijke outliers zijn in de laadtijd, deze worden gefilterd door middel van:")
    st.code("paalData = paalData[paalData['ChargeTime'] > 0]"
            "\npaalData = paalData[paalData['ChargeTime'] < 7]")
    paalData = paalData[paalData['ChargeTime'] > 0]
    paalData = paalData[paalData['ChargeTime'] < 7]

    st.caption("We houden nu het volgende DataFrame over:")
    st.dataframe(paalData)

    with st.echo():
        st.write(type(paalData.loc[0]['Started']))

    st.caption("Het type data in de Started en Ended kolommen zijn nu nog String. Dit is te fixen door pd.to_datetime te gebruiken:")
    st.code("paalData = paalData.assign(Started = lambda x: pd.to_datetime(x['Started'],errors='coerce'))"
            "\npaalData = paalData.assign(Ended = lambda x: pd.to_datetime(x['Ended'],errors='coerce'))")
    paalData = paalData.assign(Started=lambda x: pd.to_datetime(x['Started'], errors='coerce'))
    paalData = paalData.assign(Ended=lambda x: pd.to_datetime(x['Ended'], errors='coerce'))
    paalData = paalData[paalData['Started'] >= "2017-01-01 08:45:26"]
    paalData = paalData[paalData['Ended'] >= "2017-01-01 08:45:26"]

    st.caption("Nu kan deze functie gebruikt worden om te checken of er geen ")
    with st.echo():
        st.write(paalData.isna().sum())

    winter = paalData[paalData['Started'] <= "2018-03-21 23:59:59"]
    lente = paalData[paalData['Started'] <= "2018-06-21 23:59:59"]
    lente = lente[lente['Started'] > "2018-03-21 23:59:59"]
    zomer = paalData[paalData['Started'] > "2018-06-21 23:59:59"]
    zomer = zomer[zomer['Started'] <= "2018-09-21 23:59:59"]
    herfst = paalData[paalData['Started'] > "2018-09-21 23:59:59"]
    herfst = herfst[herfst['Started'] <= "2018-12-21 23:59:59"]

    st.caption("Nu de kolommen de juiste datatypes hebben, kan het dataframe per seizoen gefilterd worden:")
    st.code("winter = paalData[paalData['Started'] <= '2018-03-21 23:59:59']"
            "\n"
            "\nlente = paalData[paalData['Started'] <= '2018-06-21 23:59:59']"
            "\nlente = lente[lente['Started'] > '2018-03-21 23:59:59']")

    st.header("Laadtijd plots")

    st.caption('Als eerste is een histogram gemaakt met de verdeling van laadtijden in 2018, die te filteren is op seizoen. Het gemiddelde en de mediaan zijn weergegeven met pijlen in elke plot.')

    fig = go.Figure()

    # Add traces of charge time for the different seasons
    fig.add_trace(go.Histogram(x=paalData['ChargeTime'], name='2018 totaal', nbinsx=10, ))
    fig.add_trace(go.Histogram(x=winter['ChargeTime'], name='winter', nbinsx=10))
    fig.add_trace(go.Histogram(x=lente['ChargeTime'], name='lente', nbinsx=10))
    fig.add_trace(go.Histogram(x=zomer['ChargeTime'], name='zomer', nbinsx=10))
    fig.add_trace(go.Histogram(x=herfst['ChargeTime'], name='herfst', nbinsx=10))

    # Add annotation for the mean
    laadMean = str(paalData['ChargeTime'].mean())[:3]
    laadMedian = str(paalData['ChargeTime'].median())[:3]
    annotationMean = {'x': paalData['ChargeTime'].mean(),
                      'y': 400,
                      'showarrow': True,
                      'arrowhead': 4,
                      'font': {'size': 15, 'color': 'red'},
                      'text': 'Gemiddelde laadtijd = ' + laadMean + " uur"}
    annotationMedian = {'x': paalData['ChargeTime'].median(),
                        'y': 800,
                        'showarrow': True,
                        'arrowhead': 2,
                        'font': {'size': 15, 'color': 'green'},
                        'text': 'Mediaan van laadtijd = ' + laadMedian + " uur"}
    fig.update_layout({'annotations': [annotationMean, annotationMedian]})

    my_legend = {'x': 1, 'y': 0, 'bgcolor': 'rgb(0, 0, 0)', 'borderwidth': 5}
    fig.update_layout({'showlegend': True, 'legend': my_legend},
                      title="Verdeling van laadtijden in 2018",
                      xaxis_title_text='Laad tijd (uur)',
                      yaxis_title_text='Aantal waarnemingen', )

    sliders = [
        {'steps': [
            {'method': 'update', 'label': '2018 totaal', 'args': [{'visible': [True, False, False, False, False]}]},
            {'method': 'update', 'label': 'winter', 'args': [{'visible': [False, True, False, False, False]}]},
            {'method': 'update', 'label': 'lente', 'args': [{'visible': [False, False, True, False, False]}]},
            {'method': 'update', 'label': 'zomer', 'args': [{'visible': [False, False, False, True, False]}]},
            {'method': 'update', 'label': 'herfst', 'args': [{'visible': [False, False, False, False, True]}]}]}]

    fig.update_layout({'sliders': sliders})

    st.plotly_chart(fig)
    st.caption("Zoals te zien is is de gemiddelde laadtijd 2.3 uur, en is de mediaan 2.2 uur. Ook is te zien dat de laadtijden niet veranderen per seizoen.")
    st.caption("")
    st.caption("De volgende plot geeft de kansdichtheidsfunctie weer van de laadtijden in 2018. Er is een piek te zien bij het gemiddelde van 2.3 uur.")
    # Add histogram data
    x1 = paalData['ChargeTime']

    # Group data together
    hist_data = [x1]

    group_labels = ["2018 laadtijd kansdichtheidsfunctie"]

    # Create distplot with custom bin_size
    fig = ff.create_distplot(hist_data, group_labels, bin_size=.2)
    st.plotly_chart(fig)


import math
import numbers
import torch

from torch import nn
from torch.nn import functional as F

import time
import numpy as np
from scipy.ndimage import gaussian_filter

import pdb

class GaussianSmoothing(nn.Module):
    def __init__(self, num_kps):
        super(GaussianSmoothing, self).__init__()
        num_kps = int(num_kps)
        self.heatmaps = nn.Sequential(
            nn.Conv2d(num_kps, num_kps, kernel_size = 5, padding=2, bias=None)
        )
        self.weights_init()

    def weights_init(self):
        n= np.zeros((5,5))
        n[0, 0], n[0, 1], n[0, 2], n[0, 3], n[0, 4] = 1, 4, 7, 4, 1
        n[1, 0], n[1, 1], n[1, 2], n[1, 3], n[1, 4] = 4, 16, 26, 16, 4
        n[2, 0], n[2, 1], n[2, 2], n[2, 3], n[2, 4] = 7, 26, 41, 26, 7
        n[3, 0], n[3, 1], n[3, 2], n[3, 3], n[3, 4] = 4, 16, 26, 16, 4
        n[4, 0], n[4, 1], n[4, 2], n[4, 3], n[4, 4] = 1, 4, 7, 4, 1

        n /= 41

        for name, f in self.named_parameters():
            f.data.copy_(torch.from_numpy(n))

    def make_sparseHeat(self, j2d, vis_idx, heatmapSize = 64):
        """
        Arguments:
            j2d (Torch.Tensor | batch x num_kps x 2): Input 2D joint normalized coordinate (-1 ~ 1)
            heatmapSize (Torch.Tensor | 1,): Heatmap size, default = 224
        Returns:
            sparseHeatmap (Torch.Tensor | batch x 14 x ):
        """
        batch = j2d.size(0)
        num_kps = j2d.size(1)

        # 1. rescale the normalized keypoints by image resolution (-1 ~ 1) --> (0 ~ 223)
        j2d_resized = torch.round((j2d + 1) / 2 * (heatmapSize - 1)).long()

        # 2. make the heatmap using the indices of rescaled keypoints (batch x 14 x 2) --> heatmap: (batch x 14 x 224 x 224)
        heatmap = torch.zeros((batch, num_kps, heatmapSize, heatmapSize)).cuda()

        # There are some GT kps whose value is equal or exceeds the 224. We don't make any heatmap on that kps.
        batch_over_idx, kps_over_idx, _ = torch.where(j2d_resized >= heatmapSize)
        batch_under_idx, kps_under_idx, _ = torch.where(j2d_resized < 0)

        # make values to be zero.
        j2d_resized[torch.cat((batch_over_idx, batch_under_idx)), torch.cat((kps_over_idx, kps_under_idx)), :] = 0

        batch_idx, kps_idx= torch.where(j2d_resized[:, :, 0])
        heatmap[batch_idx, kps_idx, j2d_resized[batch_idx, kps_idx, 1], j2d_resized[batch_idx, kps_idx, 0]] = 1

        # 3. make the entire values of invisible keypoint channel to be zeros
        heatmap[torch.cat((batch_over_idx, batch_under_idx)), torch.cat((kps_over_idx, kps_under_idx)), :, :] = 0

        if vis_idx:
            vis_batch, vis_kps = vis_idx
            heatmap[vis_batch, vis_kps, :, :] = 0

        return heatmap

    def forward(self, x, vis_idx):
        sparseHeat = self.make_sparseHeat(x, vis_idx)
        heatmap = self.heatmaps(sparseHeat)
        return heatmap

if __name__ == '__main__':
    smoothing = GaussianSmoothing(4).cuda()
    for i in range(5):
        input = torch.rand(3, 4, 2).cuda()
        input[0, 0, 0] += 2
        input[2, 0, 1] += 2
        input[1, 0, 0] += 2
        input[1, 0, 1] += 2
        start = time.time()
        output = smoothing(input, None)
        print(f'time {time.time() - start}')


import datetime
import cgi

import app.model
import app.web

class ThreadAtom (app.web.RequestHandler):

    def get (self, pasty_slug):
        self.set_module(__name__ + ".__init__")
        pasties = app.model.Pasty.all()
        pasties.filter("slug =", pasty_slug)

        self.pasty = pasties.get()
        self.pasty_slug = pasty_slug
        self.forks = []

        if self.pasty == None:
            self.get_404()
        else:
            self.get_200()

    def get_200 (self):
        self.get_forks()

        self.content["paste_title"] = self.pasty.get_title()
        self.content["paste_code"] = self.pasty.get_code()

        self.content["u_thread"] = app.url("threads/%s", self.pasty.slug)
        self.content["u_thread_self"] = app.url("threads/%s.atom", self.pasty.slug)
        self.content["paste_username"] = self.pasty.posted_by_user_name
        self.content["paste_posted_at"] = self.pasty.posted_at.strftime("%Y-%m-%dT%H:%M:%SZ")
        self.content["forks"] = self.forks

        self.set_header("Content-Type", "application/atom+xml")
        self.write_out("page/threads/thread_atom/200.html")

    def get_404 (self):
        self.content["paste_slug"] = self.pasty_slug
        self.content["u_thread"] = app.url("threads/%s", self.pasty_slug)
        self.content["u_thread_self"] = app.url("threads/%s.atom", self.pasty_slug)
        self.content["date"] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")

        self.set_header("Content-Type", "application/atom+xml")
        self.error(404)
        self.write_out("page/threads/thread_atom/404.html")

    def get_forks (self):
        qry_forks = app.model.Pasty.all()
        qry_forks.filter("thread =", self.pasty.slug)
        qry_forks.order("-posted_at")
        db_forks = qry_forks.fetch (10)

        if db_forks:
            for db_fork in db_forks:
                tpl_fork = {}
                tpl_fork["u"] = db_fork.get_url()
                tpl_fork["slug"] = db_fork.slug
                tpl_fork["title"] = db_fork.get_title()
                tpl_fork["published_at"] = db_fork.posted_at.strftime("%Y-%m-%dT%H:%M:%SZ")
                tpl_fork["updated_at"] = db_fork.edited_at.strftime("%Y-%m-%dT%H:%M:%SZ")
                tpl_fork["author_name"] = db_fork.posted_by_user_name
                tpl_fork["summary"] = db_fork.get_snippet()
                self.forks.append(tpl_fork)


import os
import unittest
from pyunitreport import HTMLTestRunner
from time import sleep
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from __Logging import log
from __Utils import parseCapabilities

class Login(unittest.TestCase):

    def setUp(self):
        ueCap = parseCapabilities()
        appiumserverurl = 'http://'+ueCap[3]+':'+ueCap[4]+'/wd/hub'
        log.info("Using Appium Server Url" + appiumserverurl)

        desired_caps = {'platformName': ueCap[0], 'platformVersion': ueCap[1], 'deviceName': ueCap[2],
                        'appPackage': 'com.google.android.youtube', 'appActivity': '.HomeActivity'}

        log.info(desired_caps)
        self.driver = webdriver.Remote(appiumserverurl, desired_caps)
        sleep(10)

    def test_login(self):
        log.starttestcase("test_login")
        ell = self.driver.find_element_by_xpath("//android.widget.ImageView[@content-desc='Account']")
        actions = TouchAction(self.driver)
        actions.tap(ell)
        actions.perform()

        log.debug("Account page is Visiable")
        sleep(5)
        self.driver.save_screenshot(log.screenshotpath("Accoun page"))
        w = self.driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.support.v7.widget.RecyclerView").is_displayed()
        sleep(5)
        log.debug("Switch Account")
        self.driver.save_screenshot(log.screenshotpath("Switch account"))

        sw = self.driver.find_element_by_xpath("	/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.support.v7.widget.RecyclerView/android.widget.LinearLayout[4]/android.widget.RelativeLayout/android.widget.TextView")
        actions = TouchAction(self.driver)
        actions.tap(sw)
        actions.perform()
        sleep(5)
        log.debug("Added accounts visiable")
        self.driver.save_screenshot(log.screenshotpath("Added accounts"))
        #Select Added Account

        #(1) Atleast 2 Account should be added in You Tube app for account switching.
        #(2) Change the content-desc in xpath below with your Account channel name Ex: "Eshan varma"

        ac = self.driver.find_element_by_xpath("//android.widget.LinearLayout[@content-desc='Eshan varma']")
        actions = TouchAction(self.driver)
        actions.tap(ac)
        actions.perform()
        log.debug("selected the added accout, account changed")
        sleep(5)
        self.driver.save_screenshot(log.screenshotpath("Account changed screenshot"))

        #Sign Out
        ell= self.driver.find_element_by_xpath("//android.widget.ImageView[@content-desc='Account']")
        actions = TouchAction(self.driver)
        actions.tap(ell)
        actions.perform()
        log.debug("Switch Account")
        sleep(5)
        self.driver.save_screenshot(log.screenshotpath("Switch account"))
        w = self.driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.support.v7.widget.RecyclerView").is_displayed()
        log.debug("Account page displayed")
        sw = self.driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.support.v7.widget.RecyclerView/android.widget.LinearLayout[4]")
        actions = TouchAction(self.driver)
        actions.tap(sw)
        actions.perform()
        sleep(5)
        sg = self.driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.TextView")
        actions = TouchAction(self.driver)
        actions.tap(sg)
        actions.perform()
        log.debug("Account is in sign out mode")
        sleep(5)
        self.driver.save_screenshot(log.screenshotpath("sign out mode"))
        log.stoptestcase(self)

    def tearDown(self):
        self.driver.quit()


# run with: python manage.py runserver --settings=platform.settings.local

from .base import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# serve static files (e.g. js locally)
# so that collecstatic does not need to be run
# each time a .js file is edited

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    'static/',
)


#!/usr/bin/env python

'''
Print matplotlib colors to standard output.
Some inspiration taken from Matplotlib documentation
https://matplotlib.org/stable/gallery/color/named_colors.html
for getting color names and values.
'''

import argparse
from collections import OrderedDict
from os import get_terminal_size

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib as mpl
from matplotlib import cm

def FormatRGB( rgb ):
    """
    Take output of mpl.colors.to_rgb and format for use in print.
    input is (r, g, b) in decimal form (e.g., values range from 0.0 to 1.0)
    Output is a string with ANSI escape sequences.
    """

    rgb = [ round(i*255) for i in rgb  ]

    # ANSI escape sequence mess
    return "\x1b[48;2;" + str(rgb[0]) + ";" + str(rgb[1]) + ";" + str(rgb[2]) + "m"

def PrintColor( rgb, name, endline ):
    """
    Print output for a single color (rbg, name).
    endline is a control to send a newline character
    """

    # Set the length of an entry as 25 spaces
    num_spaces = 25 - 5 - len(name)
    print( FormatRGB( mcolors.to_rgb(name) ) + "      "
           + "\x1b[0;0m", name, num_spaces*" ", end=endline )

def PrintColors( colors=mcolors.CSS4_COLORS ):
    """
    Print the standard matplotlib colors to screen.
    """

    by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
                         name)
                        for name, color in colors.items())
    names = [name for hsv, name in by_hsv]

    n     = len( names  )

    # NOTE: You may edit the number of printed columns here
    ncols = 3
    nrows = n // ncols + int( n % ncols > 0 )

    for i, name in enumerate(names):
        col = i % ncols

        # print color.
        # If we're at the end of a row, send in a newline.
        if ( col == ncols - 1 ):
            PrintColor( mcolors.to_rgb(name), name, "\n"  )
        else:
            PrintColor( mcolors.to_rgb(name), name, " "  )

def GetColormap( name ):
    """
    Load a colormap into a useable object.
    Easy to do with e.g., cm.Blues but we only have a string

    Create a scalarMap object that can return rgb values with
    scalarMap.to_rgba(0...255)
    """

    norm = mpl.colors.Normalize(vmin=0.0, vmax=256)
    scalarMap = cm.ScalarMappable(norm=norm, cmap=name)

    return scalarMap

def GetStep( cols ):
    """
    Given the size of the terminal window,
    set the striding for printing colors
    """

    step = 5
    if ( cols > 55 ):
        step = 5
    if ( cols > 69 ):
        step = 4
    if ( cols > 91 ):
        step = 3
    if ( cols > 136 ):
        step = 2

    return step

def PrintColorbar( name ):
    """
    Print a single colorbar
    """

    scalarMap = GetColormap( name )

    n = 17 # length for text
    print( (n-len(name))*" " + name, end = " " )

    # get the length of the terminal window.
    # used for adjusting amount of colors printed
    cols   = get_terminal_size().columns

    step = GetStep( cols )

    # Print every 5th color. The colorbar is massive if we print all 256
    for i in range(0, 256, step):
        print( FormatRGB(scalarMap.to_rgba(i)[:-1]) + " " + "\033[0;0m",end=""  )
    print("\n")

def PrintColorbars( cmaps ):
    """
    Print a set of colorbars from dictionary cmap
    """

    for cmap_category, cmap_list in cmaps.items():

        cols = get_terminal_size().columns
        size = int( (256 + 17) / GetStep( cols ) - 1 )

        title = " = " + cmap_category + " = "
        print( str( (len(title)+1)*"=" ).center(size ) )
        print(title.center(size))
        print( str( (len(title)+1)*"=" ).center(size ) )
        print("\n")
        for cmap in cmap_list:
            PrintColorbar( cmap )

def main( args ):

    if ( args.colorbars == False and args.all == False ):
        PrintColors()
    elif ( args.colorbars == False and args.all == True ):
        PrintColors( colors=mcolors.XKCD_COLORS )
    else:
        cmaps = OrderedDict()

        # Help us organize the colormaps

        cmaps['Perceptually Uniform Sequential'] = [
            'viridis', 'plasma', 'inferno', 'magma', 'cividis']

        cmaps['Sequential'] = [
            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']

        cmaps['Sequential2'] = [
            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
            'hot', 'afmhot', 'gist_heat', 'copper']

        cmaps['Diverging'] = [
            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']

        cmaps['Cyclic'] = ['twilight', 'twilight_shifted', 'hsv']

        cmaps['Qualitative'] = ['Pastel1', 'Pastel2', 'Paired', 'Accent',
                        'Dark2', 'Set1', 'Set2', 'Set3',
                        'tab10', 'tab20', 'tab20b', 'tab20c']

        cmaps['Miscellaneous'] = [
            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
            'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
            'gist_ncar']

        PrintColorbars(cmaps)
    return 0
if __name__ == "__main__":

    # parse any args
    parser = argparse.ArgumentParser()
    parser.add_argument("-b", "--colorbars", action="store_true",
                    help="display colorbars")
    parser.add_argument( "-a", "--all", action="store_true", help="Print all xkcd colors" )

    args = parser.parse_args()

    main( args  )


import matplotlib.pyplot as plt

supervectors_dir = "/Users/lmatayoshi/Documents/Projects/tesis_notebooks/main_experiments/scatter-plots/data/heldout/supervectors/supervectors_single_phonemes/"
dct_dir = "/Users/lmatayoshi/Documents/Projects/tesis_notebooks/main_experiments/scatter-plots/data/heldout/dct/dct_single_phonemes/"
output_dir = "/Users/lmatayoshi/Documents/Projects/tesis_notebooks/main_experiments/scatter-plots/data/heldout/output_dct/"

all_phonemes = ["Y", "f", "c", "x", "G", "d", "b", "g", "z", "w", "N", "B", "rr", "u", "p", "D", "y", "k", "m", "t", "l", "i", "r", "n", "s", "o", "a", "e"]
positive_values = [9, 172, 89, 137, 37, 176, 115, 226, 29, 148, 205, 84, 107, 436, 332, 222, 559, 326, 677, 623, 744, 1094, 811, 1594, 1683, 1725, 2305, 2314]
negative_values = [1, 4, 38, 37, 149, 16, 91, 27, 220, 106, 112, 299, 391, 125, 261, 473, 143, 417, 168, 376, 362, 277, 597, 118, 115, 555, 479, 826]
positives_dict = dict(zip(all_phonemes, positive_values))
negatives_dict = dict(zip(all_phonemes, negative_values))

for phoneme in all_phonemes:
    original_phoneme = phoneme
    if phoneme in ['g', 'y', 'd', 'b', 'n']:
        phoneme = phoneme + "_lowercase"
    supervectors_filename = supervectors_dir + phoneme
    dct_filename = dct_dir + phoneme
    with open(supervectors_filename, "r") as f_supervectors:
        lines = f_supervectors.readlines()
        logids_supervectors = [line.split(" ")[0] for line in lines]
        scores_supervectors = [float(line.split(" ")[4]) for line in lines]
    with open(dct_filename, "r") as f_dct:
        lines = f_dct.readlines()
        logids_dct = [line.split(" ")[0] for line in lines]
        scores_dct = [float(line.split(" ")[4]) for line in lines]
    if not logids_supervectors == logids_dct:
        raise Exception(phoneme + " instances problem")
    plt.clf()
    plt.plot(scores_supervectors, scores_dct, marker=".", linestyle="", color="blue")
    title = phoneme + " heldout, positives: " + str(positives_dict[original_phoneme]) + ", negatives: " + str(negatives_dict[original_phoneme])
    plt.xlabel("supervectors score")
    plt.ylabel("dct score")
    plt.title(title)
    plt.savefig(output_dir + phoneme)


#!/usr/bin/env python3

with open('input.txt') as f:
    numbers = set([int(x) for x in f.readlines()])

print('part 1')

def sum_of_two(ns):
    for n in ns:
        if 2020 - n in ns:
            return (n, 2020 - n, n * (2020 - n))
    return None

print(sum_of_two(numbers))

print('part 2')

def sum_of_three(ns_s):
    ns = sorted(list(ns_s), reverse=True)
    for i in range(len(ns) - 2):
        for j in range(i + 1, len(ns) - 1):
            for k in range(j + 1, len(ns)):
                if ns[i] + ns[j] + ns[k] == 2020:
                    return (ns[i], ns[j], ns[k], ns[i] * ns[j] * ns[k])
    return None

print(sum_of_three(numbers))


from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator

from app.models import GoodsInfo, TypeInfo

def index(request):
    if request.method =='GET':
        return render(request,'backadmin/index.html')

# 分页展示
def productlist(request):
    if request.method == 'GET':
        num = request.GET.get('page_num',1)
        good = GoodsInfo.objects.filter(is_delete=0)
        paginator = Paginator(good,1)
        page = paginator.page(num)
        data={'goods':page}
        return render(request,'backadmin/product_list.html',data)

# 删除
def deletegood(request):
    if request.method == 'GET':
        gid = request.GET.get('gid')
        good = GoodsInfo.objects.filter(id=gid).first()
        good.is_delete = 1
        good.save()
        msg = '删除成功'
        return HttpResponseRedirect(reverse('backadmin:productlist'),{'msg':msg})

# 增加和修改
def productdetail(request):
    gtypes = TypeInfo.objects.all()
    gid = request.GET.get('gid')
    good = GoodsInfo.objects.filter(id=gid).first()
    if request.method == 'GET':
        if gid:
            data={'goods':good, 'gtypes':gtypes}
        else:
            data = {'gtypes': gtypes}
        return render(request,'backadmin/product_detail.html', data )

    if request.method == 'POST':
        gname = request.POST.get('gname')
        gprice = request.POST.get('gprice')
        gpic = request.FILES.get('gpic')
        gstock = request.POST.get('gstock')
        tname = request.POST.get('tname')
        gtype_id = TypeInfo.objects.filter(tname=tname).first().id

        gid = request.POST.get('gid')

        if gid:
            if  all([gname, gprice, gpic ,gstock, gtype_id]):
                good.gname  = gname
                good.gprice = gprice
                good.gpic   = gpic
                good.gstock = gstock
                good.gtype_id = gtype_id
                good.save()
                msg = '修改成功'
                return HttpResponseRedirect(reverse('backadmin:productlist'), {'msg': msg})
            elif all([gname, gprice, gstock, gtype_id]):
                good.gname = gname
                good.gprice = gprice
                good.gstock = gstock
                good.gtype_id = gtype_id
                good.save()
                msg = '修改成功'
                return HttpResponseRedirect(reverse('backadmin:productlist'), {'msg': msg})
            else:
                msg = '请将数据填写完整'
                data = {'gtypes': gtypes, 'msg': msg, 'goods': good}
                return render(request, 'backadmin/product_detail.html', data)

        else:
            if not all([gname, gprice, gpic, gstock, gtype_id]):
                msg = '请将数据填写完整'
                data ={'gtypes':gtypes,'msg': msg}
                return render(request, 'backadmin/product_detail.html', data)
            else:
                GoodsInfo.objects.create(gname=gname,gprice=gprice,gpic=gpic,gstock=gstock,gtype_id=gtype_id)
                msg = '添加成功'
                return HttpResponseRedirect(reverse('backadmin:productlist'),{'msg': msg})

def recyclebin(request):
    if request.method =='GET':
        num = request.GET.get('page_num',1)
        good = GoodsInfo.objects.filter(is_delete=1)
        paginator = Paginator(good,1)
        page = paginator.page(num)
        data={'goods':page}
        return render(request,'backadmin/recycle_bin.html',data)

# 恢复
def recovergood(request):
    if  request.method == 'GET':
        gid = request.GET.get('gid')
        good = GoodsInfo.objects.filter(id=gid).first()
        good.is_delete = 0
        good.save()
        msg = '恢复成功'
        return HttpResponseRedirect(reverse('backadmin:recyclebin'),{'msg':msg})

def login(request):
    if request.method =='GET':
        return render(request,'backadmin/login.html')


import numpy as np

def read_embedding_file(file_path, nodelist=None, file_type="txt"):

    if file_type == "text":

        with open(file_path, 'r') as f:
            # Read the first line
            N, dim = (int(v) for v in f.readline().strip().split())
            if nodelist is None:
                nodelist = list(range(N))
            embs = np.zeros(shape=(len(nodelist), dim), dtype=float) #node2embedding=[[] for _ in range(len(nodelist))]
            mapping = {node: nodeIdx for nodeIdx, node in enumerate(nodelist)}
            # Read embeddings
            for line in f.readlines():
                tokens = line.strip().split()
                if int(tokens[0]) in nodelist:
                    embs[mapping[int(tokens[0])], :] = [float(value) for value in tokens[1:]]
                    # node2embedding[mapping[int(tokens[0])]] = [float(value) for value in tokens[1:]]
        return embs

    elif file_type == "binary":

        def _int2boolean(num):

            binary_repr = []
            for _ in range(8):

                binary_repr.append(True if num % 2 else False )
                num = num >> 1

            return binary_repr[::-1]

        with open(file_path, 'rb') as f:

            num_of_nodes = int.from_bytes(f.read(4), byteorder='little')
            dim = int.from_bytes(f.read(4), byteorder='little')

            if nodelist is None:
                nodelist = list(range(num_of_nodes))
            embs = [[] for _ in range(len(nodelist))]
            mapping = {node: nodeIdx for nodeIdx, node in enumerate(nodelist)}

            dimInBytes = int(dim / 8)

            for i in range(num_of_nodes):
                emb = []
                for _ in range(dimInBytes):
                    emb.extend(_int2boolean(int.from_bytes(f.read(1), byteorder='little')))

                if i in nodelist:
                    embs[mapping[i]] = emb

        return np.asarray(embs, dtype=bool)

    else:

        raise ValueError("Invalid file type!")

# def read_emb_file(file_path, file_type="binary"):
#
#     if file_type == "binary":
#
#         def _int2boolean(num):
#             binary_repr = []
#             for _ in range(8):
#                 binary_repr.append(False if num % 2 else True )
#                 num = num >> 1
#             return binary_repr
#
#         with open(file_path, 'rb') as f:
#
#             num_of_nodes = int.from_bytes(f.read(4), byteorder='little')
#             dim = int.from_bytes(f.read(4), byteorder='little')
#
#             print("{} {}".format(num_of_nodes, dim));
#             dimInBytes = int(dim / 8)
#
#             embs = []
#             for i in range(num_of_nodes):
#                 emb = []
#                 for _ in range(dimInBytes):
#                     emb.extend( _int2boolean(int.from_bytes(f.read(1), byteorder='little')) )
#
#                 embs.append(emb)
#
#             embs = np.asarray(embs, dtype=bool)
#
#     elif file_type == "text":
#
#         with open(file_path, 'r') as fin:
#             # Read the first line
#             num_of_nodes, dim = ( int(token) for token in fin.readline().strip().split() )
#
#             # read the embeddings
#             embs = [[] for _ in range(num_of_nodes)]
#
#             for line in fin.readlines():
#                 tokens = line.strip().split()
#                 vect = [float(v) for v in tokens[1:]]
#                 embs[int(tokens[0])] = vect
#
#             embs = np.asarray(embs, dtype=np.float)
#
#     else:
#         raise ValueError("Invalid method!")
#
#     return embs


x = int(input('Quantas pessoas serão digitadas :'))
vet = [0 for x in range(x)]
ida = [0 for x in range(x)]
alt = [0 for x in range(x)]
soma = 0
soma2 = 0

for i in range(0,x):
    print(f'Dados da {i+1}a pessoa :')
    vet[i] = input('Nome :')
    ida[i] = int(input('Idade:'))
    alt[i] = float(input('Altura:'))
print()

for i in range(0,x):
    soma = soma + alt[i]
    media = soma/x
print(f'Altura media : {media : .2f}')

for i in range(0,x):
    if ida[i] < 16:
        soma2 = soma2 + 1
        porcento = (soma2 * 100)/x
print(f'Pessoas com menos de 16 anos : {porcento : .1f}%')
for i in range(0,x):
    if ida[i]<16:
        print(f'{vet[i]:{x}}')


import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import StandardScaler

from sklearn.neighbors import KNeighborsClassifier

from sklearn.metrics import accuracy_score

data = pd.read_excel('KNN.xlsx')
print(data)

x_fitur = data.iloc[:, 1:5]
y_label = data.iloc[:, -1]

#print(x_fitur)
#print(y_label)

x_training, x_testing, y_training, y_testing = train_test_split(x_fitur , y_label, train_size = 0.8, test_size = 0.2, random_state = 2)

scaller = StandardScaler()
x_training_sc = scaller.fit_transform(x_training)
x_testing_sc = scaller.transform(x_testing)

classifier = KNeighborsClassifier(n_neighbors = 3)
classifier.fit(x_training_sc, y_training)

y_prediksi = classifier.predict(x_testing_sc)

akurasi = accuracy_score(y_testing, y_prediksi)
print('akurasi model adalah', format(akurasi*100),'%')