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

import glob
import os
import random
import re
import sys
from time import time

import numpy as np

from .sequence_noise import SequenceNoise
from .target_selection import SelectTargets

class RNNBase(object):
	"""Base for RNN object.
	"""
	def __init__(self,
		sequence_noise=SequenceNoise(),
		target_selection=SelectTargets(),
		active_f='tanh',
		max_length=30,
		batch_size=16,
		tying=False,
		temperature=10,
		gamma=0.5,
		iter=False,
		tying_new = False,
		attention=False):

		super(RNNBase, self).__init__()

		self.max_length = max_length
		self.batch_size = batch_size
		self.sequence_noise = sequence_noise
		self.target_selection = target_selection
		self.active_f=active_f
		self.tying = tying
		self.temperature = temperature
		self.gamma = gamma
		self.iter = iter
		self.tying_new = tying_new
		self.attention = attention

		self._input_type = 'float32'

		self.name = "RNN base"
		self.metrics = {'recall': {'direction': 1},
						'precision': {'direction': 1},
						'sps': {'direction': 1},
						'user_coverage': {'direction': 1},
						'item_coverage': {'direction': 1},
						'ndcg': {'direction': 1},
						'blockbuster_share': {'direction': -1}
						}

	def _common_filename(self, epochs):
		'''Common parts of the filename accros sub classes.
		'''
		filename = "ml"+str(self.max_length)+"_bs"+str(self.batch_size)+"_ne"+str(epochs)+"_"+self.recurrent_layer.name + "_" + self.updater.name + "_" + self.target_selection.name

		if self.sequence_noise.name != "":
			filename += "_" + self.sequence_noise.name

		if self.active_f != 'tanh':
			filename += "_act" + self.active_f[0].upper()
		if self.tying:
			filename += "_ty_tp" + str(self.temperature) + "_gm" + str(self.gamma)
			if self.tying_new:
				filename += "_new"
		if self.iter:
			filename += "_it"
		if self.attention:
			filename += "_att"
		return filename

	def top_k_recommendations(self, sequence, k=10):
		''' Recieves a sequence of (id, rating), and produces k recommendations (as a list of ids)
		'''

		seq_by_max_length = sequence[-min(self.max_length, len(sequence)):]  # last max length or all

		# Prepare RNN input
		if self.framework == 'tf' and self.recurrent_layer.embedding_size > 0:
			X = np.zeros((1, self.max_length), dtype=np.int32)  # tf embedding requires movie-id sequence, not one-hot
			X[0, :len(seq_by_max_length)] = np.array([item[0] for item in seq_by_max_length])
		else:
			X = np.zeros((1, self.max_length, self._input_size()), dtype=self._input_type) # input shape of the RNN
			X[0, :len(seq_by_max_length), :] = np.array(list(map(lambda x: self._get_features(x), seq_by_max_length)))

		# Run RNN
		if self.framework == 'tf':
			length = [min(self.max_length, len(sequence))]
			output = self.sess.run(self.softmax, feed_dict={self.X: X, self.length:length})
		elif self.framework == 'th':
			if not hasattr(self, 'predict_function'):
				self._compile_predict_function()
			mask = np.zeros((1, self.max_length))
			mask[0, :len(seq_by_max_length)] = 1
			output = self.predict_function(X, mask)
		else:
			output = self.model.predict_on_batch(X)

		# find top k according to output
		return list(np.argpartition(-output[0], list(range(k)))[:k])

	def set_dataset(self, dataset):
		self.dataset = dataset
		self.target_selection.set_dataset(dataset)

	def get_pareto_front(self, metrics, metrics_names):
		costs = np.zeros((len(metrics[metrics_names[0]]), len(metrics_names)))
		for i, m in enumerate(metrics_names):
			costs[:, i] = np.array(metrics[m]) * self.metrics[m]['direction']
		is_efficient = np.ones(costs.shape[0], dtype=bool)
		for i, c in enumerate(costs):
			if is_efficient[i]:
				is_efficient[is_efficient] = np.any(costs[is_efficient] >= c, axis=1)
		return np.where(is_efficient)[0].tolist()

	def train(self, dataset,
		max_time=np.inf,
		progress=2.0,
		autosave='All',
		save_dir='',
		min_iterations=0,
		max_iter=np.inf,
		load_last_model=False,
		early_stopping=None,
		validation_metrics=['sps']):
		'''Train the model based on the sequence given by the training_set

		max_time is used to set the maximumn amount of time (in seconds) that the training can last before being stop.
			By default, max_time=np.inf, which means that the training will last until the training_set runs out, or the user interrupt the program.

		progress is used to set when progress information should be printed during training. It can be either an int or a float:
			integer : print at linear intervals specified by the value of progress (i.e. : progress, 2*progress, 3*progress, ...)
			float : print at geometric intervals specified by the value of progress (i.e. : progress, progress^2, progress^3, ...)

		max_progress_interval can be used to have geometric intervals in the begining then switch to linear intervals.
			It ensures, independently of the progress parameter, that progress is shown at least every max_progress_interval.

		time_based_progress is used to choose between using number of iterations or time as a progress indicator. True means time (in seconds) is used, False means number of iterations.

		autosave is used to set whether the model should be saved during training. It can take several values:
			All : the model will be saved each time progress info is printed.
			Best : save only the best model so far
			None : does not save

		min_iterations is used to set a minimum of iterations before printing the first information (and saving the model).

		save_dir is the path to the directory where models are saved.

		load_last_model: if true, find the latest model in the directory where models should be saved, and load it before starting training.

		early_stopping : should be a callable that will recieve the list of validation error and the corresponding epochs and return a boolean indicating whether the learning should stop.
		'''

		self.dataset = dataset
		self.target_selection.set_dataset(dataset)

		if len(set(validation_metrics) & set(self.metrics.keys())) < len(validation_metrics):
			raise ValueError(
				'Incorrect validation metrics. Metrics must be chosen among: ' + ', '.join(self.metrics.keys()))

		if self.framework=='tf':
			self.sess.run(self.init)
		elif self.framework == 'th':
			if not hasattr(self, 'train_function'):
				self._compile_train_function()
			if not hasattr(self, 'test_function'):
				self._compile_test_function()

		# Load last model if needed
		iterations = 0
		epochs_offset = 0
		if load_last_model:
			epochs_offset = self.load_last(save_dir)

		# Make batch generator
		#batch_generator = threaded_generator(self._gen_mini_batch(self.sequence_noise(dataset.training_set())))

		batch_generator = self._gen_mini_batch(self.sequence_noise(self.dataset.training_set()))

		start_time = time()
		next_save = int(progress)
		#val_costs = []
		train_costs = []
		current_train_cost = []
		epochs = []
		metrics = {name: [] for name in self.metrics.keys()}
		filename = {}

		try:
			while time() - start_time < max_time and iterations < max_iter:

				# Train with a new batch
				try:
					batch = next(batch_generator)

					if self.framework == 'tf':
						if self.save_log:
							s, cost, _ = self.sess.run([self.summary, self.cost, self.training], feed_dict={self.X: batch[0], self.Y: batch[1], self.length: batch[2]})
							self.writer.add_summary(s, iterations)
						else:
							cost, _ = self.sess.run([self.cost, self.training, ], feed_dict={self.X: batch[0], self.Y: batch[1], self.length: batch[2]})

						# print("================================================")
						# print(np.shape(test))

					elif self.framework.startswith('k'):
						# self.model.fit(batch[0], batch[2])
						cost = self.model.train_on_batch(batch[0], batch[1])
						# outputs = self.model.predict_on_batch(batch[0])
						# print(outputs[0, :6])
						# print(batch[1])

					else:
						cost = self.train_function(*batch)
						# print(output)
						# print(cost)

					if np.isnan(cost):
						raise ValueError("Cost is NaN")

				except StopIteration:
					break

				current_train_cost.append(cost)
				#current_train_cost.append(0)

				# Check if it is time to save the model
				iterations += 1

				if iterations >= next_save:
					if iterations >= min_iterations:
						# Save current epoch
						epochs.append(epochs_offset + self.dataset.training_set.epochs)

						# Average train cost
						train_costs.append(np.mean(current_train_cost))
						current_train_cost = []

						# Compute validation cost
						metrics = self._compute_validation_metrics(metrics)

						# Print info
						self._print_progress(iterations, epochs[-1], start_time, train_costs, metrics,
											 validation_metrics)

						# Save model
						run_nb = len(metrics[list(self.metrics.keys())[0]]) - 1
						if autosave == 'All':
							filename[run_nb] = save_dir + self.framework + "/" + self._get_model_filename(round(epochs[-1], 3))
							self._save(filename[run_nb])
						elif autosave == 'Best':
							pareto_runs = self.get_pareto_front(metrics, validation_metrics)
							if run_nb in pareto_runs:
								filename[run_nb] = save_dir + self.framework + "/" + self._get_model_filename(round(epochs[-1], 3))
								self._save(filename[run_nb])
								to_delete = [r for r in filename if r not in pareto_runs]
								for run in to_delete:
									try:
										if self.framework == 'tf' :
											os.remove(filename[run] + ".data-00000-of-00001")
											os.remove(filename[run] + ".index")
											os.remove(filename[run] + ".meta")
										else:
											os.remove(filename[run])
									except OSError:
										print('Warning : Previous model could not be deleted')
									del filename[run]

						if early_stopping is not None:
							if all([early_stopping(epochs, metrics[m]) for m in validation_metrics]):
								break

					next_save += progress

		except KeyboardInterrupt:
			print('Training interrupted')

		best_run = np.argmax(
			np.array(metrics[validation_metrics[0]]) * self.metrics[validation_metrics[0]]['direction'])
		return ({m: metrics[m][best_run] for m in self.metrics.keys()}, time() - start_time, filename[best_run])

	def _compute_validation_metrics(self, metrics):
		"""
		add value to lists in metrics dictionary
		"""

	def _gen_mini_batch(self, sequence_generator, test=False):
		''' Takes a sequence generator and produce a mini batch generator.
		The mini batch have a size defined by self.batch_size, and have format of the input layer of the rnn.

		test determines how the sequence is splitted between training and testing
			test == False, the sequence is split randomly
			test == True, the sequence is split in the middle

		if test == False, max_reuse_sequence determines how many time a single sequence is used in the same batch.
			with max_reuse_sequence = inf, one sequence will be used to make the whole batch (if the sequence is long enough)
			with max_reuse_sequence = 1, each sequence is used only once in the batch
		N.B. if test == True, max_reuse_sequence = 1 is used anyway
		'''

		while True:
			j = 0
			sequences = []
			batch_size = self.batch_size
			if test:
				batch_size = 1
			while j < batch_size: # j : user order

				sequence, user_id = next(sequence_generator)

				# finds the lengths of the different subsequences
				if not test: # training set
					seq_lengths = sorted(
						random.sample(range(2, len(sequence)), #range
									  min([self.batch_size - j, len(sequence) - 2])) #population
					)
				elif self.iter:
					batch_size = len(sequence) -1
					seq_lengths = list(range(1, len(sequence)))
				else: #validating set
					seq_lengths = [int(len(sequence) / 2)] # half of len

				skipped_seq = 0
				for l in seq_lengths:
					# target is only for rnn with hinge, logit and logsig.
					target = self.target_selection(sequence[l:], test=test)
					if len(target) == 0:
						skipped_seq += 1
						continue
					start = max(0, l - self.max_length) # sequences cannot be longer than self.max_length
					#print(target)
					sequences.append([user_id, sequence[start:l], target])
					# print([user_id, sequence[start:l], target])

				j += len(seq_lengths) - skipped_seq #?????????

			if test:
				yield self._prepare_input(sequences), [i[0] for i in sequence[seq_lengths[0]:]]
			else:
				yield self._prepare_input(sequences)

	def _print_progress(self, iterations, epochs, start_time, train_costs, metrics, validation_metrics):
		'''Print learning progress in terminal
		'''
		print(self.name, iterations, "batchs, ", epochs, " epochs in", time() - start_time, "s")
		print("Last train cost : ", train_costs[-1])
		for m in self.metrics:
			print(m, ': ', metrics[m][-1])
			if m in validation_metrics:
				print('Best ', m, ': ',
					  max(np.array(metrics[m]) * self.metrics[m]['direction']) * self.metrics[m]['direction'])

		print('-----------------')

		# Print on stderr for easier recording of progress
		print(iterations, epochs, time() - start_time, train_costs[-1],
			  ' '.join(map(str, [metrics[m][-1] for m in self.metrics])), file=sys.stderr)

	def _get_model_filename(self, iterations):
		'''Return the name of the file to save the current model
		'''
		raise NotImplemented

	def prepare_networks(self):
		''' Prepares the building blocks of the RNN, but does not compile them:
		self.l_in : input layer
		self.l_mask : mask of the input layer
		self.target : target of the network
		self.l_out : last output of the network
		self.cost : cost function

		and maybe others
		'''
		raise NotImplemented

	def _compile_train_network(self):
		''' Compile self.train.
		self.train recieves a sequence and a target for every steps of the sequence,
		compute error on every steps, update parameter and return global cost (i.e. the error).
		'''
		raise NotImplemented

	def _compile_predict_network(self):
		''' Compile self.predict, the deterministic rnn that output the prediction at the end of the sequence
		'''
		raise NotImplemented

	def _save(self, filename):
		'''Save the parameters of a network into a file
		'''
		print('Save model in ' + filename)
		if not os.path.exists(os.path.dirname(filename)):
			os.makedirs(os.path.dirname(filename))

	def load_last(self, save_dir):
		'''Load last model from dir
		'''
		def extract_number_of_batches(filename):
			m = re.search('_nb([0-9]+)_', filename)
			return int(m.group(1))

		def extract_number_of_epochs(filename):
			m = re.search('_ne([0-9]+(\.[0-9]+)?)_', filename)
			return float(m.group(1))

		# Get all the models for this RNN
		file = save_dir + self._get_model_filename("*")
		file = np.array(glob.glob(file))

		if len(file) == 0:
			print('No previous model, starting from scratch')
			return 0

		# Find last model and load it
		last_batch = np.amax(np.array(map(extract_number_of_epochs, file)))
		last_model = save_dir + self._get_model_filename(last_batch)
		print('Starting from model ' + last_model)
		self.load(last_model)

		return last_batch

	def _load(self, filename):
		'''Load parameters values from a file
		'''

	def _input_size(self):
		''' Returns the number of input neurons
		'''
		return self.n_items

	def _get_features(self, item):
		'''Change a tuple (item_id, rating) into a list of features to feed into the RNN
		features have the following structure: [one_hot_encoding, personal_rating on a scale of ten, average_rating on a scale of ten, popularity on a log scale of ten]
		'''

		one_hot_encoding = np.zeros(self.n_items)
		one_hot_encoding[item[0]] = 1
		return one_hot_encoding


#!/usr/bin/env python3
from .read_colvars_traj import ReadSpaceSeparatedTraj, ReadColvarsTraj

class BuildHistogramFromTraj:

    def __init__(self, json_file, position_cols):
        import copy
        import logging
        from .histogram import HistogramScalar
        self.logger = logging.getLogger(self.__class__.__name__)
        if self.logger.hasHandlers():
            self.logger.handlers.clear()
        logging_handler = logging.StreamHandler()
        logging_formatter = logging.Formatter('[%(name)s %(levelname)s]: %(message)s')
        logging_handler.setFormatter(logging_formatter)
        self.logger.addHandler(logging_handler)
        self.logger.setLevel(logging.INFO)
        self.histogram = HistogramScalar.from_json_file(json_file)
        if position_cols is None:
            self.positionColumns = list(range(0, self.histogram.get_dimension()))
        else:
            self.positionColumns = copy.deepcopy(position_cols)
        # self.maxColumn = max(self.positionColumns)

    def read_traj(self, f_traj):
        total_lines = 0
        valid_lines = 0
        for line in f_traj:
            total_lines += 1
            tmp_position = [line[key] for key in self.positionColumns]
            if self.histogram.is_in_grid(tmp_position):
                self.histogram[tmp_position] += 1.0
                valid_lines += 1
            else:
                self.logger.warning(f'Position {tmp_position} is not in the boundary!')
        self.logger.info(f'Total data lines: {total_lines}')
        self.logger.info(f'Valid data lines: {valid_lines}')

    def read_pandas(self, df):
        total_lines = 0
        valid_lines = 0
        np_data = df[self.positionColumns].to_numpy()
        for row in range(0, df.shape[0]):
            total_lines += 1
            tmp_position = np_data[row]
            if self.histogram.is_in_grid(tmp_position):
                self.histogram[tmp_position] += 1.0
                valid_lines += 1
            else:
                self.logger.warning(f'Position {tmp_position} is not in the boundary!')
        self.logger.info(f'Total data lines: {total_lines}')
        self.logger.info(f'Valid data lines: {valid_lines}')

    def get_histogram(self):
        return self.histogram

if __name__ == '__main__':
    import argparse
    import pandas as pd
    parser = argparse.ArgumentParser(description='Build histogram from colvars trajectories')
    required_args = parser.add_argument_group('required named arguments')
    required_args.add_argument('--axis', help='json file to setup axes')
    parser.add_argument('--traj', nargs='*', help='Colvars trajectory files')
    parser.add_argument('--csv', nargs='*', help='CSV traj files')
    required_args.add_argument('--output', help='the output file with weights', required=True)
    parser.add_argument('--columns', type=str, nargs='+', help='columns in the trajectory (default to 0...Ndim)')
    args = parser.parse_args()
    build_histogram = BuildHistogramFromTraj(json_file=args.axis, position_cols=args.columns)
    if args.columns is None:
        if args.traj is not None:
            for traj_file in args.traj:
                with ReadSpaceSeparatedTraj(traj_file) as f_traj:
                    build_histogram.read_traj(f_traj=f_traj)
    else:
        if args.traj is not None:
            for traj_file in args.traj:
                with ReadColvarsTraj(traj_file) as f_traj:
                    build_histogram.read_traj(f_traj=f_traj)
    if args.csv is not None:
        for csv_file in args.csv:
            df = pd.read_csv(csv_file)
            build_histogram.read_pandas(df)
    with open(args.output, 'w') as f_output:
        build_histogram.get_histogram().write_to_stream(stream=f_output)


def solution(numbers, hand):
    answer = ''
    left, right='*','#'          # 현재 손의 위치
    lidx,ridx=0,2                # 현재 손이 arr 리스트에서 어느 열에 있는지, index() 함수에 사용
    arr=[['1','4','7','*'],['2','5','8','0'],['3','6','9','#']]

    for num in numbers:
        if str(num) in arr[0]:
            answer+='L'
            left=num
            lidx=0
        elif str(num) in arr[2]:
            answer+='R'
            right=num
            ridx=2
        else:
            L_dst=abs(arr[1].index(str(num))-arr[lidx].index(str(left)))
            if lidx!=1:
                L_dst+=1
            R_dst=abs(arr[1].index(str(num))-arr[ridx].index(str(right)))
            if ridx!=1:
                R_dst+=1
            if L_dst<R_dst:
                answer+='L'
                left=num
                lidx=1
            elif L_dst>R_dst:
                answer+='R'
                right=num
                ridx=1
            else:
                if hand=='left':
                    answer+='L'
                    left=num
                    lidx=1
                else:
                    answer+='R'
                    right=num
                    ridx=1

    return answer

프로그래머스/키패드 누르기.py


#Construir un script en python que acepte dos números como parámetros e imprima el resultado de la suma

import sys #

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Por favor, proporciona dos números como argumentos.")
    else:
        num1 = float(sys.argv[1])
        num2 = float(sys.argv[2])
        suma = num1 + num2
        print(f"La suma de {num1} y {num2} es: {suma}")


from __future__ import print_function

import os

from constants import hooks

setattr(hooks, "INSTRUMENTATION_DRIVER_PATH", os.path.abspath(__file__))
print("Python Instrumentor located at : {}".format(hooks.INSTRUMENTATION_DRIVER_PATH))

import sys
from setuptools.sandbox import _execfile
from utils.import_hook import enable_module_hook_on_load
from utils.instrumentation import instrument_system_api

# The magic happens behind the curtain.
enable_module_hook_on_load()
instrument_system_api()

# Manipulate the current argv to be used by user application code.
sys.argv = sys.argv[1:]
print("Python Instrumentor calling actual application")
# Transparently call the user code with all the given command line parameters.
if sys.argv[0].endswith(".py") :
    app_dir = sys.argv[0].rpartition("/")[0]
    if app_dir == '':
        app_dir = os.getcwd()

    sys.path.insert(0, app_dir)

    app_globals = globals()
    app_globals["__file__"] = sys.argv[0]
    app_locals = locals()
    app_locals["__file__"] = sys.argv[0]

    _execfile(sys.argv[0], app_globals, app_locals)

elif sys.argv[0] == "-m" :
    # Run with the -m switch
    import runpy
    mod_name = sys.argv[1]
    sys.argv = sys.argv[1:]
    if hasattr(runpy, '_run_module_as_main'):
        # Newer versions of Python actually use this when the -m switch is used.
        if sys.version_info[:2] <= (2, 6):
            runpy._run_module_as_main(mod_name, set_argv0=False)
        else:
            runpy._run_module_as_main(mod_name, alter_argv=False)
    else:
        runpy.run_module(sys.argv[1])
else:
    print("Unsupported file to execute.", file=sys.stderr)
    print("Sys args are : {}".format(sys.argv), file=sys.stderr)
print("Python Instrumentor exiting.")


# QUESTION
# Given a string s, find the longest palindromic substring in s.
# You may assume that the maximum length of s is 1000.
# Examples: "babad" -> "bab" or "aba", "cbbd" -> "bb"

# Time Complexity: O(N^2) [for each index, expand from center: O(N) * O(N)],
# Space Complexity: O(1)
class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        start_index = 0 # start index of the palindrome
        end_index = 0 # end index of the palindrome

        # Feel free to use Python function len() wherever as it only costs O(1)
        for cur_index in range(len(s)):
            odd_len = self.expand_from_center(cur_index, cur_index, s) # check for odd length palindrome
            even_len = self.expand_from_center(cur_index, cur_index + 1, s) # check for even length palindrome
            max_len = max(odd_len, even_len) # get the maximum length found of the two
            if max_len > end_index - start_index: # if new found palindrome length greater than before
                start_index = cur_index - int((max_len - 1)/2)  # set new start_index accordingly
                end_index = cur_index + int(max_len/2) # set new end_index accordingly

        return s[start_index:end_index+1] # return the longest palindrome found

    def expand_from_center(self, left, right, s):
        """Helper function to simulate a sliding window to
           compute length of palindrome substring.
        :type left: int -> representing the sliding left index
        :type right: int -> representing the sliding right index
        :type s: str -> input string as before
        :rtype: int -> return length of the palindrome substring
        """
        # Initialize left and right points as new variables to modify
        l = left
        r = right
        # Loop until 1) left point didn't exceed the beginning index (0),
        # 2) right point didn't exceed the last index (len(s)), and
        # 3) palindrome rule (s[l] == s[r]) still counts
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return r - l - 1
        # Normally we would have expected to return r - l + 1, but since
        # we decrement l and increment r while in, respectively, the first
        # and last index, we have added an additional length of 2
        # which we need to count for: r - l + 1 - 2 = r - l - 1

# TAKEAWAYS
# 1) A sliding window with two sliders that both expand from the center index in the
# case of a odd length palindrome, and one expanding from the left median while
# the other expanding from the right median in the case of an even length palindrome
# will give a good solution.
# 2) To notice how whilst calculating start_index we additionaly decrement max_len by 1,
# you will give to give test values. Be careful about indexing as a general rule!
# 3) Helper functions are always useful, both for modularizing your solution and
# recursive/iterative approaches.


import tkinter

window = tkinter.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)

# Label
my_label = tkinter.Label(text="I Am a Label", font=("Arial", 24, "bold"))
my_label.pack()

# Podemos configurar, atualizar ou alterar as propriedades de um componente que criamos
my_label["text"] = "New Text"
my_label.config(text="New Text 2")

# Button
def button_clicked():
    # my_label.config(text="I got clicked")
    my_label.config(text=entry_input.get())

button = tkinter.Button(text="Click Me!", command=button_clicked)
button.pack()

# Entry (basicamente um input)
entry_input = tkinter.Entry(width=50)
entry_input.pack()
print(entry_input.get())

window.mainloop()

Seção 27; Day 27 - Intermediate - Tkinter, args, kwargs and Creating GUI Programs/251. Buttons, Entry, and Setting Component Options/main.py


import datetime

import numpy as np
from mpi4py import MPI

def read_vector_from_file(filename: str):
    with open(filename) as f:
        n = int(f.readline())
        numbers = [int(number) for number in f.readline().split()]
    return n, numbers

def parent_process():
    comm = MPI.COMM_WORLD
    start_time = datetime.datetime.now()

    filename = "file_large.txt"
    n, numbers = read_vector_from_file(filename)
    numbers = np.array(numbers, dtype=np.int32)
    input_output_time = datetime.datetime.now()
    input_output_duration = (input_output_time - start_time).total_seconds() * (10 ** 6)  # microseconds
    print("Process rank #0: Reading the vector from file took {} microseconds".format(input_output_duration))

    total_no_processes = comm.Get_size() - 1  # eliminate parent process which doesn't process a chunk
    if total_no_processes == 0:
        exit(-1)  # no processes to compute

    chunk_length = n / total_no_processes
    current_process_rank = 1
    current_vector_starting_index = 0

    for i in range(total_no_processes):
        current_vector_ending_index = int(min(len(numbers) - 1, current_vector_starting_index + chunk_length))
        process_chunk_length = current_vector_ending_index - current_vector_starting_index + 1
        print("Starting index {}".format(current_vector_starting_index))
        print("Ending index {}".format(current_vector_ending_index))
        print("Sending length {}".format(process_chunk_length))

        # send values and so on
        comm.send(process_chunk_length, dest=current_process_rank, tag=0)
        comm.Send([numbers[current_vector_starting_index:current_vector_ending_index + 1], process_chunk_length, MPI.INT],
                  dest=current_process_rank, tag=0)

        current_process_rank += 1
        current_vector_starting_index += process_chunk_length

    total_sum = 0
    current_process_rank = 1
    for i in range(total_no_processes):
        received_sum = comm.recv(source=current_process_rank, tag=0)  # receive value
        total_sum += int(received_sum)

        current_process_rank += 1

    average_value = (1.0 * total_sum) / n
    print("Process rank #0: The average value of the vector is {}".format(average_value))

    final_time = datetime.datetime.now()
    computation_duration = (final_time - input_output_time).total_seconds() * (10 ** 6)
    total_duration = (final_time - start_time).total_seconds() * (10 ** 6)

    print("Process rank #0: Processing (computing time) took {} microseconds".format(computation_duration))
    print("Process rank #0: Total program duration was {} microseconds".format(total_duration))

def child_process(process_rank: int):
    comm = MPI.COMM_WORLD

    # receive length and then array
    length = comm.recv(source=0, tag=0)

    # initialize and receive array
    child_process_chunk = np.empty(length, dtype=np.int32)
    comm.Recv(child_process_chunk, source=0, tag=0)

    total_sum = 0
    for number in child_process_chunk:
        total_sum += int(number)

    print("Process with rank {} is sending back sum {}".format(process_rank, total_sum))
    comm.send(total_sum, dest=0, tag=0)

def main():
    comm = MPI.COMM_WORLD
    rank = comm.Get_rank()
    if rank == 0:
        parent_process()
    else:
        child_process(rank)

if __name__ == "__main__":
    main()


#coding:utf-8
import theano, random
import numpy as np
import theano.tensor as T
from collections import OrderedDict

def sharedX(value, name=None, borrow=False, dtype=None):
    if dtype is None:
        dtype = theano.config.floatX
    return theano.shared(theano._asarray(value, dtype=dtype),
                         name=name,
                         borrow=borrow)

def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-8):
    updates = []
    i = sharedX(0.)
    i_t = i + 1.
    fix1 = 1. - (1. - b1)**i_t
    fix2 = 1. - (1. - b2)**i_t
    lr_t = lr * (T.sqrt(fix2) / fix1)
    for p, g in grads.items():
        m = sharedX(p.get_value() * 0.)
        v = sharedX(p.get_value() * 0.)
        m_t = (b1 * g) + ((1. - b1) * m)
        v_t = (b2 * T.sqr(g)) + ((1. - b2) * v)
        g_t = m_t / (T.sqrt(v_t) + e)
        p_t = p - (lr_t * g_t)
        updates.append((m, m_t))
        updates.append((v, v_t))
        updates.append((p, p_t))
    updates.append((i, i_t))
    return updates

def compute_updates(training_cost, params, config):
    updates = []

    grads = T.grad(training_cost, params)
    grads = OrderedDict(zip(params, grads))

    # Clip stuff
    c = np.float32(1.)
    clip_grads = []

    norm_gs = T.sqrt(sum(T.sum(g ** 2) for p, g in grads.items()))
    normalization = T.switch(T.ge(norm_gs, c), c / norm_gs, np.float32(1.))
    notfinite = T.or_(T.isnan(norm_gs), T.isinf(norm_gs))

    for p, g in grads.items():
        clip_grads.append((p, T.switch(notfinite, np.float32(.1) * p, g * normalization)))

    grads = OrderedDict(clip_grads)

    updates = Adam(grads, config.learning_rate) #使用adam梯度更新策略

    return updates

def NormalInit(rng, sizeX, sizeY, scale=0.01, sparsity=-1):
    """
    Normal Initialization
    """
    sizeX = int(sizeX)
    sizeY = int(sizeY)

    if sparsity < 0:
        sparsity = sizeY

    sparsity = np.minimum(sizeY, sparsity)
    values = np.zeros((sizeX, sizeY), dtype=theano.config.floatX)
    for dx in xrange(sizeX):
        perm = rng.permutation(sizeY)
        new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,))
        values[dx, perm[:sparsity]] = new_vals

    return values.astype(theano.config.floatX)

def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1):
    """
    Orthogonal Initialization
    """

    sizeX = int(sizeX)
    sizeY = int(sizeY)

    assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY'

    if sparsity < 0:
        sparsity = sizeY
    else:
        sparsity = np.minimum(sizeY, sparsity)

    values = np.zeros((sizeX, sizeY), dtype=theano.config.floatX)
    for dx in xrange(sizeX):
        perm = rng.permutation(sizeY)
        new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,))
        values[dx, perm[:sparsity]] = new_vals

    # Use SciPy:
    if sizeX*sizeY > 20000000:
        import scipy
        u,s,v = scipy.linalg.svd(values)
    else:
        u,s,v = np.linalg.svd(values)
    values = u * scale
    return values.astype(theano.config.floatX)

def SoftMax(x):
    x = T.exp(x - T.max(x, axis=x.ndim-1, keepdims=True))
    return x / T.sum(x, axis=x.ndim-1, keepdims=True)

def add_to_params(params, new_param):
    params.append(new_param)
    return new_param


from __future__ import annotations

from typing import FrozenSet, Generic, Sequence
from instancelib.labels.encoder import DictionaryEncoder, MultilabelDictionaryEncoder
from instancelib.typehints.typevars import LT
import numpy as np

class OnnxLabelEncoder(MultilabelDictionaryEncoder[LT], Generic[LT]):
    def decode_matrix(self, matrix: np.ndarray) -> Sequence[FrozenSet[LT]]:
        if len(matrix.shape) == 1:
            return super(MultilabelDictionaryEncoder, self).decode_matrix(matrix)
        return super().decode_matrix(matrix)

    def decode_vector(self, vector: np.ndarray) -> FrozenSet[LT]:
        if vector.shape[0] > 1:
            return super(MultilabelDictionaryEncoder, self).decode_vector(vector)
        return super().decode_vector(vector)

    @classmethod
    def from_empty(cls) -> OnnxLabelEncoder[LT]:
        idxs = range(0,1000)
        return cls.from_list(idxs)


#Create a nesting list that prints out the color and the car brand

cars_color = ['White', 'Red', 'Green']
cars_name = ['Audi', 'Mazda', 'Lamboghini']

cars_details = zip(cars_color, cars_name)

cars = list(cars_details)

print(cars)


# show_rgb.py
# Show the three components of the RGB representation of a color image.
# The colors are ordered Blue, Green, Red.
# Each color channel is bright where that color is present in the image

import cv2

img = cv2.imread('books.jpg', 1)
# 1 means import image in color

print(type(img))
print(img.shape)	# number of rows and columns
print(img.dtype)	# data type

cv2.imshow('Original image', img)
cv2.imshow('Channel 0 (Blue)',  img[:, :, 0])
cv2.imshow('Channel 1 (Green)', img[:, :, 1])
cv2.imshow('Channel 2 (Red)',   img[:, :, 2])

print('Switch to images. Then press any key to quit')

# Write the image to a file
cv2.imwrite('books - blue channel.jpg',  img[:, :, 0])
cv2.imwrite('books - green channel.jpg', img[:, :, 1])
cv2.imwrite('books - red channel.jpg',   img[:, :, 2])

cv2.waitKey(0)   # wait until any keystroke
cv2.destroyAllWindows()

demo 22 - video (cv2)/D1 - images/show_rgb.py


import cv2
import numpy as np

#Kamera Kullanılacaksa Kamera Girişi
#kamera = cv2.VideoCapture(0)

video = cv2.VideoCapture('AracTanimaVeSaydirma.mp4') #Video Girişi

gelis_sol_serit = 0
gelis_sag_serit = 0

gidis_sol_serit = 0
gidis_sag_serit = 0

minimum_genislik = 75
minimum_yükseklik = 75

def AracTespit():
    global gelis_sol_serit
    global gelis_sag_serit

    global gidis_sol_serit
    global gidis_sag_serit

    for contour in contours:
        #Tespit edilen konturun yerlerini hesaplama
        (x, y, w, h) = cv2.boundingRect(contour)
        #Minimum genişlik ve yükseliğe göre kontrol
        contour_kontrol = (w >= minimum_genislik) and (h >= minimum_yükseklik)

        if not contour_kontrol:
            continue

        #Tespit edilen konturu dikdörtgen içerisine alma
        cv2.rectangle(frame2, (x, y), (x + w, y + h), (255, 0, 0), 2)
        #Araç üzerine tespit edilde yazdırma
        cv2.putText(frame2, 'Tespit Edildi', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 255), 1, cv2.LINE_AA)

        merkez = MerkezAl(x, y, w, h)
        merkezX = merkez[0]
        merkezY = merkez[1]

        cv2.circle(frame1, merkez, 3, (0, 0, 255), -1)

        #Şerit sistemine göre geçti geçmedi tespiti
        if(320<merkezX<=475 and 300<merkezY<330):
            gelis_sol_serit = gelis_sol_serit + 1
            cv2.line(frame2, (320,310), (455,310), (0,0,255), 2)

        elif(475<merkezX<=600 and 300<merkezY<336):
            gelis_sag_serit = gelis_sag_serit + 1
            cv2.line(frame2, (475,310), (600,310), (0,0,255), 2)

        elif(700<merkezX<=900 and 550<merkezY<580):
            gidis_sol_serit = gidis_sol_serit + 1
            cv2.line(frame2, (710,570), (880,570), (0,255,0), 2)

        elif(900<merkezX<=1100 and 530<merkezY<580):
            gidis_sag_serit = gidis_sag_serit + 1
            cv2.line(frame2, (900,570), (1100,570), (0,255,0), 2)

def MerkezAl(x, y, w, h):
    x1 = int(w / 2)
    y1 = int(h / 2)

    cx = x + x1
    cy = y + y1

    return (cx, cy)

while True:
    _, frame1 = video.read()
    _, frame2 = video.read()

    difference = cv2.absdiff(frame1, frame2) #Hareketi tespit etmek için arka plan kaldırma
    gray = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY) #Görüntüyü gri seviyeli görüntüye çevirme
    blur = cv2.GaussianBlur(gray, (9,9), 0) #Görüntüyü yumuşatma işlemi
    ret, thresh = cv2.threshold(blur, 10, 255, cv2.THRESH_BINARY) #Görüntüde ki hareketli kısımların beyazlaştırılması
    dilate = cv2.dilate(thresh, np.ones((3, 3))) #Dilate metodu ile beyaz alanların büyütülmesi
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)) #Matrisleri elips şeklinde almak
    closing = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel) #Siyah alanları küçültmek için closing metodu
    contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #Araçları tespit etmek için findContours metodu

    frame2 = frame1

    cv2.line(frame2,(320,310),(455,310),(255,255,255),2)
    cv2.putText(frame2, "{}".format(gelis_sol_serit), (445, 300),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    cv2.line(frame2,(475,310),(600,310),(255,255,255),2)
    cv2.putText(frame2, "{}".format(gelis_sag_serit), (590, 300),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    cv2.line(frame2,(710,570),(880,570),(255,255,255),2)
    cv2.putText(frame2, "{}".format(gidis_sol_serit), (710, 560),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    cv2.line(frame2,(900,570),(1100,570),(255,255,255),2)
    cv2.putText(frame2, "{}".format(gidis_sag_serit), (900, 560),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    cv2.putText(frame2, "Toplam Arac Sayisi: {}".format(gelis_sol_serit + gelis_sag_serit + gidis_sol_serit + gidis_sag_serit), (10, 250),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
    cv2.putText(frame2, "Gelen Arac Sayisi: {}".format(gelis_sol_serit + gelis_sag_serit), (10, 275),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
    cv2.putText(frame2, "Giden Arac Sayisi: {}".format(gidis_sol_serit + gidis_sag_serit), (10, 300),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

    AracTespit()

    cv2.imshow("Arac Takip ve Saydirma", frame2)
    #cv2.imshow("Frame2", frame2)
    #cv2.imshow("Difference", difference)
    #cv2.imshow("Blur", blur)
    #cv2.imshow("Thresh", thresh)

    key = cv2.waitKey(30)
    if key == 27:
        break

video.release()
cv2.destroyAllWindows()


import sys
sys.stdin = open('input (43).txt', 'r')

def first():

    for i in range(1, n+1):
        print('*' * i)

def second():

    for i in range(n, 0, -1):
        print('*' * i)

def third():

    m = (n - 1) * 2 + 1

    k = n - 1

    for j in range(1, m+1, 2):
        for i in range(m+1):

            if i == 0:
                print(end='')
            elif i < k + 1:
                print(end=' ')
            else:
                if j:
                    print('*', end='')
                    j -= 1
                else:
                    break
        k -= 1

        print()

n, m = map(int, input().split())

if 0 < n < 101 and 0 < m < 4:

    if m == 1:
        first()
    elif m == 2:
        second()
    else:
        third()

else:
    print("INPUT ERROR!")

algorithm/6월/6월 11일/도형만들기2/1523 별삼각형1.py


# 문제분석
# 시계 방향으로 푸는건데
# 시뮬레이션이네

n = int(input())
find = int(input())

# 북 동 남 서
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

board = [[0 for _ in range(n)] for _ in range(n)]

x, y = 0, 0
board[x][y] = n*n

# 남
direction = 2
number = (n*n)-1
ansX, ansY = 0, 0
while True:
	# nx, ny
	# 우선 direction 방향으로 x, y를 업데이트 해주고
	nx = x + dx[direction]
	ny = y + dy[direction]
	# 그럼 이 nx가 갈 수 잇는지 없는지 확인해야됨
	if nx > n-1 or nx < 0 or ny > n-1 or board[nx][ny] != 0:
		# 만약 이런 경우라면 방향을 바꿔야함
		direction -= 1
		if direction < 0:
			direction = 3
		# 방향을 바꾸고
		# nx, ny 값을 업데이트하고
		# 그럼 새로운 좌표로 설정되었으니까
		nx = x + dx[direction]
		ny = y + dy[direction]
	# x, y 업데이트
	# 만약 업데이트 한 값의 number 값이 우리가 찾던 find 값이라면
	# ansX, ansY 에 좌표를 업데이트 해준다
	x, y = nx, ny
	board[x][y] = number
	if board[x][y] == find:
		ansX, ansY = x, y
	number -= 1
	if number <= 0:
		for i in board:
			print(*i, end = "\n")
		print(ansX+1, ansY+1)
		break
	# 수를 저장해주고

# [[49, 0, 0, 0, 0, 0, 0],
# [48, 0, 0, 0, 0, 0, 0],
# [47, 0, 0, 0, 0, 0, 0],
# [46, 0, 0, 0, 0, 0, 0],
# [45, 0, 0, 0, 0, 0, 0],
# [44, 0, 0, 0, 0, 0, 36],
# [43, 42, 41, 40, 39, 38, 37]]

# [[49, 26, 27, 28, 29, 30, 31],
# [48, 25, 10, 11, 12, 13, 32],
# [47, 24, 9, 2, 3, 14, 33],
# [46, 23, 8, 1, 4, 15, 34],
# [45, 22, 7, 6, 5, 16, 35],
# [44, 21, 20, 19, 18, 17, 36],
# [43, 42, 41, 40, 39, 38, 37]]


from flask import Blueprint, current_app as app, request
from methods.validators import validate_job_format
from methods.utils import api_key_required, abort_json, submit_job

routes = Blueprint("routes", __name__)

@routes.route("/api", strict_slashes=False)
def version():
    return {
        "sha": app.config.get("GIT_SHA"),
    }

@routes.route("/submit", methods=["POST"])
@api_key_required
def submit():
    body = request.json
    if not body or "job" not in body:
        app.logger.error("Request body is not JSON or is invalid")
        abort_json(400, description="Request body is invalid or is missing required fields")

    err = validate_job_format(body['job'])
    if err:
        return {'error': err}, 400

    payload = submit_job(body['job'])
    return payload


from antlr4.RuleContext import RuleContext
from antlr4.Token import Token
from antlr4.error.ErrorListener import ProxyErrorListener, ConsoleErrorListener

# need forward delcaration
RecognitionException = None

class Recognizer(object):
    __slots__ = ('_listeners', '_interp', '_stateNumber')

    tokenTypeMapCache = dict()
    ruleIndexMapCache = dict()

    def __init__(self):
        self._listeners = [ ConsoleErrorListener.INSTANCE ]
        self._interp = None
        self._stateNumber = -1

    def extractVersion(self, version):
        pos = version.find(".")
        major = version[0:pos]
        version = version[pos+1:]
        pos = version.find(".")
        if pos==-1:
            pos = version.find("-")
        if pos==-1:
            pos = len(version)
        minor = version[0:pos]
        return major, minor

    def checkVersion(self, toolVersion):
        runtimeVersion = "4.13.1"
        rvmajor, rvminor = self.extractVersion(runtimeVersion)
        tvmajor, tvminor = self.extractVersion(toolVersion)
        if rvmajor!=tvmajor or rvminor!=tvminor:
            print("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion)

    def addErrorListener(self, listener):
        self._listeners.append(listener)

    def removeErrorListener(self, listener):
        self._listeners.remove(listener)

    def removeErrorListeners(self):
        self._listeners = []

    def getTokenTypeMap(self):
        tokenNames = self.getTokenNames()
        if tokenNames is None:
            from antlr4.error.Errors import UnsupportedOperationException
            raise UnsupportedOperationException("The current recognizer does not provide a list of token names.")
        result = self.tokenTypeMapCache.get(tokenNames, None)
        if result is None:
            result = zip( tokenNames, range(0, len(tokenNames)))
            result["EOF"] = Token.EOF
            self.tokenTypeMapCache[tokenNames] = result
        return result

    # Get a map from rule names to rule indexes.
    #
    #
Used for XPath and tree pattern compilation.

    #
    def getRuleIndexMap(self):
        ruleNames = self.getRuleNames()
        if ruleNames is None:
            from antlr4.error.Errors import UnsupportedOperationException
            raise UnsupportedOperationException("The current recognizer does not provide a list of rule names.")
        result = self.ruleIndexMapCache.get(ruleNames, None)
        if result is None:
            result = zip( ruleNames, range(0, len(ruleNames)))
            self.ruleIndexMapCache[ruleNames] = result
        return result

    def getTokenType(self, tokenName:str):
        ttype = self.getTokenTypeMap().get(tokenName, None)
        if ttype is not None:
            return ttype
        else:
            return Token.INVALID_TYPE

    # What is the error header, normally line/character position information?#
    def getErrorHeader(self, e:RecognitionException):
        line = e.getOffendingToken().line
        column = e.getOffendingToken().column
        return "line "+line+":"+column

    # How should a token be displayed in an error message? The default
    #  is to display just the text, but during development you might
    #  want to have a lot of information spit out.  Override in that case
    #  to use t.toString() (which, for CommonToken, dumps everything about
    #  the token). This is better than forcing you to override a method in
    #  your token objects because you don't have to go modify your lexer
    #  so that it creates a new Java type.
    #
    # @deprecated This method is not called by the ANTLR 4 Runtime. Specific
    # implementations of {@link ANTLRErrorStrategy} may provide a similar
    # feature when necessary. For example, see
    # {@link DefaultErrorStrategy#getTokenErrorDisplay}.
    #
    def getTokenErrorDisplay(self, t:Token):
        if t is None:
            return "<no token>"
        s = t.text
        if s is None:
            if t.type==Token.EOF:
                s = "<EOF>"
            else:
                s = "<" + str(t.type) + ">"
        s = s.replace("\n","\\n")
        s = s.replace("\r","\\r")
        s = s.replace("\t","\\t")
        return "'" + s + "'"

    def getErrorListenerDispatch(self):
        return ProxyErrorListener(self._listeners)

    # subclass needs to override these if there are sempreds or actions
    # that the ATN interp needs to execute
    def sempred(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):
        return True

    def precpred(self, localctx:RuleContext , precedence:int):
        return True

    @property
    def state(self):
        return self._stateNumber

    # Indicate that the recognizer has changed internal state that is
    #  consistent with the ATN state passed in.  This way we always know
    #  where we are in the ATN as the parser goes along. The rule
    #  context objects form a stack that lets us see the stack of
    #  invoking rules. Combine this and we have complete ATN
    #  configuration information.

    @state.setter
    def state(self, atnState:int):
        self._stateNumber = atnState

del RecognitionException


from torch.nn import functional as F
import random
def build_variant(variant, return_replay_buffer=True, return_collectors=True):
    env_args = {}
    alg_args = {}
    learn_args = {}
    log_args = {}

    log_args['log_dir'] = variant['log_dir']
    log_args['alg'] = variant['alg']
    learn_args['tb_log_name'] = variant['log_dir']

    res = {}

    domain = variant['domain']
    seed = variant['seed']
    env_args = {}
    if domain in ['riverswim']:
        env_args['dim'] = variant['dim']
        env_args['deterministic'] = False
        if 'deterministic_rs' in variant:
            env_args['deterministic'] = variant['deterministic_rs']
    if domain in ['lqg']:
        env_args['sigma_noise'] = variant['sigma_noise']
    if domain in ['point']:
        env_args['difficulty'] = variant['difficulty']
        env_args['clip_state'] = variant['clip_state']
        env_args['terminal'] = variant['terminal']
        env_args['sparse_reward'] = variant['sparse_reward']
        env_args['max_state'] = variant['max_state']
    if domain in ['ant_maze']:
        env_args['difficulty'] = variant['difficulty']
        env_args['clip_state'] = variant['clip_state']
        env_args['terminal'] = variant['terminal']
    if 'cliff' in domain:
        env_args['sigma_noise'] = variant['sigma_noise']
    if "hockey" in domain:
        env_args['env'] = variant['hockey_env']
        env_args['simple_reward'] = variant['simple_reward']
        env_args['shaped_reward'] = variant['shaped_reward']
        env_args['large_reward'] = variant['large_reward']
        env_args['large_penalty'] = variant['large_penalty']
        env_args['min_jerk'] = variant['min_jerk']
        env_args['max_jerk'] = variant['max_jerk']
        env_args['history'] = variant['history']
        env_args['use_atacom'] = variant['use_atacom']
        env_args['large_penalty'] = variant['large_penalty']
        env_args['alpha_r'] = variant['alpha_r']
        env_args['c_r'] = variant['c_r']
        env_args['high_level_action'] = variant['high_level_action']
        env_args['clipped_penalty'] = variant['clipped_penalty']
        env_args['include_joints'] = variant['include_joints']
        env_args['jerk_only'] = variant['jerk_only']
        env_args['delta_action'] = variant['delta_action']
        env_args['acceleration'] = variant['acceleration']
        env_args['delta_ratio'] = variant['delta_ratio']
        env_args['max_accel'] = variant['max_accel']
        env_args['gamma'] = variant['trainer_kwargs']['discount']
        env_args['horizon'] = variant['algorithm_kwargs']['max_path_length'] + 1
        env_args['stop_after_hit'] = variant['stop_after_hit']
        env_args['punish_jerk'] = variant['punish_jerk']
        env_args['interpolation_order'] = variant['interpolation_order']
        env_args['include_old_action'] = variant['include_old_action']
        env_args['use_aqp'] = variant['use_aqp']
        env_args['speed_decay'] = variant['speed_decay']
        env_args['clip_vel'] = variant['clip_vel']
        env_args['aqp_terminates'] = variant['aqp_terminates']
        env_args['whole_game_reward'] = variant['whole_game_reward']
        env_args['score_reward'] = variant['score_reward']
        env_args['fault_penalty'] = variant['fault_penalty']
        env_args['load_second_agent'] = variant['load_second_agent']
        env_args['dont_include_timer_in_states'] = variant['dont_include_timer_in_states']
        env_args['action_persistence'] = variant['action_persistence']
        env_args['stop_when_puck_otherside'] = variant['stop_when_puck_otherside']

        env_args['curriculum_learning_step1'] = variant['curriculum_learning_step1']
        env_args['curriculum_learning_step2'] = variant['curriculum_learning_step2']
        env_args['curriculum_learning_step3'] = variant['curriculum_learning_step3']

        env_args['start_from_defend'] = variant['start_from_defend']
        env_args['curriculum_transition'] = variant['curriculum_transition']

        env_args['original_env'] = True

    if variant['alg'] == 'ppo':
        alg_args['learning_rate'] = variant.lr
        try:
            alg_args['policy'] = variant.policy
        except Exception:
            alg_args['policy'] = 'MlpPolicy'
        alg_args['n_steps'] = variant.steps_per_update
        alg_args['batch_size'] = variant.batch_size
        alg_args['n_epochs'] = variant.n_epochs
        alg_args['gamma'] = variant.gamma
        alg_args['gae_lambda'] = variant.gae_lambda
        alg_args['clip_range'] = variant.clip_range
        alg_args['clip_range_vf'] = variant.clip_range_vf
        alg_args['normalize_advantage'] = variant.normalize_advantage
        alg_args['ent_coef'] = variant.ent_coef
        alg_args['vf_coef'] = variant.vf_coef
        alg_args['max_grad_norm'] = variant.max_grad_norm
        alg_args['use_sde'] = variant.use_sde
        alg_args['sde_sample_freq'] = variant.sde_sample_freq
        alg_args['target_kl'] = variant.target_kl
        alg_args['stats_window_size'] = variant.stats_window_size
        alg_args['tensorboard_log'] = variant.tensorboard_log
        alg_args['verbose'] = variant.verbose
        alg_args['seed'] = variant.seed
    elif variant['alg'] == 'sac':
        alg_args['policy'] = variant['policy']
        alg_args['learning_rate'] = variant['trainer_kwargs']['policy_lr']  # the same will be used for all networks
        alg_args['buffer_size'] = variant['replay_buffer_size']
        alg_args['learning_starts'] = variant['algorithm_kwargs']['min_num_steps_before_training']
        alg_args['batch_size'] = variant['algorithm_kwargs']['batch_size']
        alg_args['tau'] = variant['trainer_kwargs']['soft_target_tau']
        alg_args['gamma'] = variant['trainer_kwargs']['discount']
        alg_args['train_freq'] = variant['algorithm_kwargs']['num_expl_steps_per_train_loop']
        alg_args['gradient_steps'] = variant['algorithm_kwargs']['num_trains_per_train_loop']
        alg_args['action_noise'] = variant['trainer_kwargs']['action_noise']
        alg_args['replay_buffer_class'] = None
        alg_args['replay_buffer_kwargs'] = None
        alg_args['optimize_memory_usage'] = False
        alg_args['ent_coef'] = "auto"
        alg_args['target_update_interval'] = variant['trainer_kwargs']['target_update_period']
        alg_args['target_entropy'] = "auto"
        alg_args['use_sde'] = False
        alg_args['sde_sample_freq'] = -1
        alg_args['use_sde_at_warmup'] = True
        alg_args['stats_window_size'] = 100
        alg_args['tensorboard_log'] = variant['log_dir']
        alg_args['policy_kwargs'] = None
        alg_args['verbose'] = variant['verbose']
        if variant['seed'] == 0:
            variant['seed'] = random.randint(0, 999999)
        alg_args['seed'] = variant['seed']
        alg_args['device'] = "auto"
        alg_args['_init_setup_model'] = True
    elif variant['alg'] == 'dqn':
        alg_args['policy'] = variant.policy
        alg_args['learning_rate'] = variant.learning_rate
        alg_args['buffer_size'] = variant.buffer_size
        alg_args['learning_starts'] = variant.learning_starts
        alg_args['batch_size'] = variant.batch_size
        alg_args['tau'] = variant.tau
        alg_args['gamma'] = variant.gamma
        alg_args['train_freq'] = variant.train_freq
        alg_args['gradient_steps'] = variant.gradient_steps
        alg_args['replay_buffer_class'] = variant.replay_buffer_class
        alg_args['replay_buffer_kwargs'] = variant.replay_buffer_kwargs
        alg_args['optimize_memory_usage'] = variant.optimize_memory_usage
        alg_args['target_update_interval'] = variant.target_update_interval
        alg_args['exploration_fraction'] = variant.exploration_fraction
        alg_args['exploration_initial_eps'] = variant.exploration_initial_eps
        alg_args['exploration_final_eps'] = variant.exploration_final_eps
        alg_args['max_grad_norm'] = variant.max_grad_norm
        alg_args['stats_window_size'] = variant.stats_window_size
        alg_args['tensorboard_log'] = variant.tensorboard_log
        alg_args['policy_kwargs'] = variant.policy_kwargs
        alg_args['verbose'] = variant.verbose
        alg_args['seed'] = variant.seed
        alg_args['device'] = variant.device
        alg_args['_init_setup_model'] = variant._init_setup_model

    learn_args['total_timesteps'] = variant['total_timesteps']

    return env_args, alg_args, learn_args, log_args


#crie um programa que leia 7 valores e armazene em duas listas dentro de uma lista, os valores pares e impares
lista = [[],[]]
import os

for i in range(0,6):
    n = int(input('Digite um número: '))
    if n % 2 == 0:
        lista[0].append(n)
    elif n % 2 == 1:
        lista[1].append(n)

lista[0].sort()
lista[1].sort()
os.system('cls')
if len(lista[0]) == 0:
    print('Não foi digitado nenhum valor par')
else:
    print(f'Os números pares digitados foram: {lista[0]}')

if len(lista[1]) == 0:
    print('Não foi digitado nenhum valor ímpar')
else:
    print(f'Os números ímpares digitados foram: {lista[1]}')


from __future__ import absolute_import
from .format import decide, FormatSelector
from rdflib.graph import Graph
from six import BytesIO
import itertools

class Decorator(object):
	def __init__(self, format_selector=None):
		self.format_selector = format_selector
		if self.format_selector is None:
			self.format_selector = FormatSelector()

	@staticmethod
	def _is_graph(obj):
		return isinstance(obj, Graph)

	@staticmethod
	def _get_graph(output):
		""" Given a WSGI response, check for a rdflib Graph """
		if Decorator._is_graph(output):	# single graph object
			return output

	def output(self, output, accepts, set_http_code, set_content_type):
		""" Formats a response from a WSGI app to handle any RDF graphs
		    If a view function returns a single RDF graph, serialize it based on Accept header
		    If it's not an RDF graph, return it without any special handling
		"""

		graph = Decorator._get_graph(output)
		if graph is not None:
			# decide the format
			output_mimetype, output_format = self.format_selector.decide(accepts, graph.context_aware)
			# requested content couldn't find anything
			if output_mimetype is None:
				set_http_code("406 Not Acceptable")
				return ['406 Not Acceptable'.encode('utf-8')]
			# explicitly mark text mimetypes as utf-8
			if 'text' in output_mimetype:
				output_mimetype = output_mimetype + '; charset=utf-8'

			# format the new response
			serialized = graph.serialize(format=output_format)
			set_content_type(output_mimetype)
			return [serialized]
		else:
			return output

	def decorate(self, app):
		""" Wraps a WSGI application to return formatted RDF graphs
		    Uses content negotiation to serialize the graph to the client-preferred format
		    Passes other content through unmodified
		"""
		from functools import wraps

		@wraps(app)
		def decorated(environ, start_response):
			# capture any start_response from the app
			app_response = {}
			app_response['status'] = "200 OK"
			app_response['headers'] = []
			app_response['written'] = BytesIO()
			def custom_start_response(status, headers, *args, **kwargs):
				app_response['status'] = status
				app_response['headers'] = headers
				app_response['args'] = args
				app_response['kwargs'] = kwargs
				return app_response['written'].write
			returned = app(environ, custom_start_response)

			# callbacks from the serialization
			def set_http_code(status):
				app_response['status'] = str(status)
			def set_header(header, value):
				app_response['headers'] = [(h,v) for (h,v) in app_response['headers'] if h.lower() != header.lower()]
				app_response['headers'].append((header, value))
			def set_content_type(content_type):
				set_header('Content-Type', content_type)

			# do the serialization
			accept = environ.get('HTTP_ACCEPT', '')
			new_return = self.output(returned, accept, set_http_code, set_content_type)

			# set the Vary header
			vary_headers = (v for (h,v) in app_response['headers'] if h.lower() == 'vary')
			vary_elements = list(itertools.chain(*[v.split(',') for v in vary_headers]))
			vary_elements = list(set([v.strip() for v in vary_elements]))
			if '*' not in vary_elements and 'accept' not in (v.lower() for v in vary_elements):
				vary_elements.append('Accept')
				set_header('Vary', ', '.join(vary_elements))

			# pass on the result to the parent WSGI server
			parent_writer = start_response(app_response['status'],
			                               app_response['headers'],
			                               *app_response.get('args', []),
			                               **app_response.get('kwargs', {}))
			written = app_response['written'].getvalue()
			if len(written) > 0:
				parent_writer(written)
			return new_return
		return decorated

	def __call__(self, app):
		""" Enables this class to be used as the decorator directly """
		return self.decorate(app)

_implicit_instance = Decorator()

def output(output, accepts, set_http_code, set_content_type):
	return _implicit_instance.output(output, accepts, set_http_code, set_content_type)
def returns_rdf(view):
	return _implicit_instance.decorate(view)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Interpreter for the Pophery Programming Language v0.1 or something.

"""

LICENSE = """\
Copyright (c)2011 Chris Pressey, Cat's Eye Technologies.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

  1. Redistributions of source code must retain the above copyright
     notices, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notices, this list of conditions, and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
  3. Neither the names of the copyright holders nor the names of their
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

import sys
from optparse import OptionParser

class UndefinedLocatorError(Exception):
    """Indicates a given locator was not found in a MutableString."""
    pass

class MutableString(object):
    """String-like object which may be updated in place.

    A MutableString emulates a Python unicode datatype in many ways,
    with the most notable exception being that its contents may
    change over time.  In addition, it supports a rich set of operations
    for enacting these changes.

    Changes are often made relative to one or more locators.
    A locator string uniquely locates a position within a MutableString.
    A locator is a substring which is unique within the MutableString.
    If the locator is not unique, the behaviour of a change made
    relative to it is undefined.

    """
    def __init__(self, initial):
        self.string = initial

    def __str__(self):
        return self.__unicode__()

    def __unicode__(self):
        return self.string

    def __len__(self):
        return len(self.string)

    def __getitem__(self, index):
        return self.string[index]

    def __getslice__(self, i, j):
        return self.string[i:j]

    def find(self, sub):
        return self.string.find(sub)

    def set(self, string):
        self.string = string

    def pos_left(self, locator, delta):
        """Return the 0-based position within this MutableString of the
        first character of the given locator, plus the given offset.

        Note that the returned value is ephemeral and should not be
        stored, as it is subject to change at any time the MutableString
        is changed.

        >>> a = MutableString("Mom(*)entous")
        >>> print(a.pos_left("(*)", 0))
        3

        """
        pos = self.find(locator)
        if pos == -1:
            raise UndefinedLocatorError(locator)
        return pos - delta

    def pos_right(self, locator, delta):
        """Return the 0-based position within this MutableString of the
        first character to the right of the given locator, plus the given
        offset.

        Note that the returned value is ephemeral and should not be
        stored, as it is subject to change at any time the MutableString
        is changed.

        >>> a = MutableString("Mom(*)entous")
        >>> print(a.pos_right("(*)", 0))
        6

        """
        pos = self.find(locator)
        if pos == -1:
            raise UndefinedLocatorError(locator)
        return pos + len(locator) + delta

    def insert_locator(self, locator, pos):
        """Insert the given locator at the given position in this string.

        Note that this will blithely insert the new locator inside an
        existing locator.

        >>> a = MutableString("Momentous")
        >>> a.insert_locator("(*)", 3)
        >>> print(str(a))
        Mom(*)entous

        """
        self.set(self[:pos] + locator + self[pos:])

    def remove_locator(self, locator):
        """Remove the given locator from this string.

        >>> a = MutableString("Mom(*)entous")
        >>> a.remove_locator("(*)")
        >>> print(str(a))
        Momentous

        """
        posl = self.pos_left(locator, 0)
        posr = self.pos_right(locator, 0)
        self.set(self[:posl] + self[posr:])

    def move_locator(self, locator, delta):
        """Change the position of the given locator by the given delta.

        Note that this will not skip over intervening locators; i.e. it will
        allow the locator to end up inside another locator.

        >>> a = MutableString("Mom(*)entous")
        >>> a.move_locator("(*)", +3)
        >>> print(str(a))
        Moment(*)ous

        """
        posl = self.pos_left(locator, 0)
        posr = self.pos_right(locator, 0)
        self.set(self[:posl] + self[posr:])
        posl = posl + delta
        self.set(self[:posl] + locator + self[posl:])

    def slide_locator(self, locator, delta):
        """Slide the position of the given locator by the given delta.

        Note that this will skip over intervening locators; i.e. it will
        avoid having the locator end up inside another locator.

        Delta must be +1 or -1.

        >>> a = MutableString("Mom(*)en(+)tous")
        >>> a.slide_locator("(*)", +1)
        >>> print(str(a))
        Mome(*)n(+)tous
        >>> a.slide_locator("(*)", -1)
        >>> print(str(a))
        Mom(*)en(+)tous

        >>> b = MutableString("(-)Cassowary(+)")
        >>> b.slide_locator("(+)", +1)
        >>> print(str(b))
        (-)Cassowary(+)
        >>> b.slide_locator("(-)", -1)
        >>> print(str(b))
        (-)Cassowary(+)

        >>> c = MutableString("Imb(+)r(%)oglio")
        >>> c.slide_locator("(+)", +1)
        >>> print(str(c))
        Imbr(+)(%)oglio

        """
        if delta == +1:
            matching = True
            target = self.pos_right(locator, 0)
            advance = 1
            while matching is not None and target < len(self):
                matching = self.find_matching(target)
                if matching is not None:
                    advance += (matching - target) + 1
                    target = matching + 1
            if target < len(self):
                self.move_locator(locator, advance)
        elif delta == -1:
            matching = True
            target = self.pos_left(locator, 0) - 1
            advance = -1
            while matching is not None and target >= 0:
                matching = self.find_matching(target)
                if matching is not None:
                    advance -= (target - matching) + 1
                    target = matching - 1
            if target >= 0:
                self.move_locator(locator, advance)
        else:
            raise NotImplementedError

    def read(self, left, right):
        """Retrieve the substring between the two given locators.

        >>> a = MutableString("This is (a)my string(b) you know.")
        >>> print(a.read("(a)", "(b)"))
        my string

        """
        a = self.pos_right(left, 0)
        b = self.pos_left(right, 0)
        return self.string[a:b]

    def update(self, left, right, string):
        """Change the substring between the two given locators.

        >>> a = MutableString("This is (a)my string(b) you know.")
        >>> a.update("(a)", "(b)", "crazy talk")
        >>> print(str(a))
        This is (a)crazy talk(b) you know.

        """
        a = self.pos_right(left, 0)
        b = self.pos_left(right, 0)
        self.set(self.string[:a] + str(string) + self.string[b:])

    def find_matching(self, pos):
        """Find the parenthesis which matches the parenthesis at the given
        position.

        Returns the position of the matching parenthesis, or None if no
        matching parenthesis was found, or if the character at the given
        position isn't a parenthesis.

        >>> a = MutableString("This (is (my[))] string.")
        >>> a.find_matching(5)
        14
        >>> a.find_matching(9)
        13
        >>> a.find_matching(12) is None
        True
        >>> a.find_matching(14)
        5
        >>> a.find_matching(13)
        9
        >>> a.find_matching(15) is None
        True

        >>> a = MutableString("a(")
        >>> a.find_matching(0) is None
        True
        >>> a.find_matching(1) is None
        True

        """
        opener = self.string[pos]
        if opener == u'(':
            closer = u')'
            dir = +1
        elif opener == u')':
            closer = u'('
            dir = -1
        else:
            return None
        level = 0
        while pos < len(self.string):
            if self.string[pos] == opener:
                level += 1
            elif self.string[pos] == closer:
                level -= 1
                if level == 0:
                    return pos
            pos += dir
        return None

class SlottedString(MutableString):

    def __init__(self, initial):
        super(SlottedString, self).__init__(initial)

    def read_slot(self, slot_name):
        """

        >>> a = SlottedString("This is (^a)my slot(a$) you know.")
        >>> a.update_slot('a', 'good stuff')
        >>> print(str(a))
        This is (^a)good stuff(a$) you know.
        >>> a.update_slot('z', 'bad stuff')
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^z)

        """
        return self.read(u"(^%s)" % slot_name, u"(%s$)" % slot_name)

    def read_slot_indirect(self, slot_name):
        """
        >>> p = SlottedString("...(^A)M(A$)...(^R)A(R$)...")
        >>> print(p.read_slot_indirect('R'))
        M
        >>> print(p.read_slot_indirect('A'))
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^M)

        """
        slot_name = self.read_slot(slot_name)
        return self.read_slot(slot_name)

    def update_slot(self, slot_name, string):
        """

        >>> a = SlottedString("This is (^a)my slot(a$) you know.")
        >>> a.update_slot('a', 'good stuff')
        >>> print(str(a))
        This is (^a)good stuff(a$) you know.
        >>> a.update_slot('a', MutableString('mutable stuff'))
        >>> print(str(a))
        This is (^a)mutable stuff(a$) you know.
        >>> a.update_slot('z', 'bad stuff')
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^z)

        """
        return self.update(u"(^%s)" % slot_name, u"(%s$)" % slot_name, string)

    def update_slot_indirect(self, slot_name, string):
        """
        >>> p = SlottedString("Dolphin(^A)M(A$)Dolphin(^R)A(R$)Dolphin")
        >>> p.update_slot_indirect('R', 'Porphyry')
        >>> print(str(p))
        Dolphin(^A)Porphyry(A$)Dolphin(^R)A(R$)Dolphin

        """
        slot_name = self.read_slot(slot_name)
        self.update_slot(slot_name, string)

    def get_slot_name(self, slot_name):
        """

        >>> a = SlottedString("(^G)?(G$) (^P)_(P$) (^`P)Q(`P$) (^`K)(^/)Madge(/$)(`K$)")
        >>> print(a.get_slot_name('M'))
        M
        >>> print(a.get_slot_name('G'))
        G
        >>> print(a.get_slot_name('P'))
        Q
        >>> print(a.get_slot_name('K'))
        Madge

        """
        name_slot = u"`%s" % slot_name
        try:
            slot_name = self.read_slot(name_slot)
        except (UndefinedLocatorError):
            pass
        slot_name = self.strip_all_locators(slot_name)
        return slot_name

    def strip_all_locators(self, content):
        """
        >>> p = Program('')
        >>> print(p.strip_all_locators(''))
        None
        >>> print(p.strip_all_locators('X'))
        X
        >>> print(p.strip_all_locators('Well-tempered'))
        Well-tempered
        >>> print(p.strip_all_locators('(^8)(^7)(7$)CAT(8$)'))
        CAT
        >>> print(p.strip_all_locators('(^8(beat))D'))
        D
        >>> print(p.strip_all_locators('(^8)(^7)(7$)(8$)'))
        None

        """
        if len(content) == 0:
            return None
        else:
            pos = 0
            level = 0
            acc = ''
            while pos < len(content):
                if content[pos] == '(':
                    level += 1
                elif content[pos] == ')':
                    level -= 1
                elif level == 0:
                    acc += content[pos]
                pos += 1
            return acc or None

    def slide_slot(self, slot_name, delta):
        """

        >>> a = SlottedString("This is my (^a)slot(a$) (^b)y(b$)ou know.")
        >>> a.slide_slot('a', +1)
        >>> print(str(a))
        This is my s(^a)lot (a$)(^b)y(b$)ou know.
        >>> a.slide_slot('b', -1)
        >>> print(str(a))
        This is my s(^a)lot(^b) (a$)(b$)you know.

        """
        if delta > 0:
            self.slide_locator("(%s$)" % slot_name, delta)
            self.slide_locator("(^%s)" % slot_name, delta)
        else:
            self.slide_locator("(^%s)" % slot_name, delta)
            self.slide_locator("(%s$)" % slot_name, delta)

class Program(SlottedString):

    def __init__(self, initial):
        super(Program, self).__init__(initial)
        self.input = sys.stdin
        self.output = sys.stdout

    def load(self, filename):
        """Load the program source from a Tranzy file."""
        file = open(filename, 'r')
        done = False
        string = ''
        for line in file.readlines():
            if line.endswith('\n'):
                line = line[:-1]
            if line.startswith('#'):
                pass
            else:
                string += line
        self.set(string)
        file.close()

    def advance(self):
        """Slide the instruction slot rightward.

        >>> p = Program("(^!)A(!$)B(^M)C(M$)D")
        >>> p.advance()
        >>> print(str(p))
        A(^!)B(!$)(^M)C(M$)D
        >>> p.advance()
        >>> print(str(p))
        AB(^!)(^M)C(!$)(M$)D
        >>> p.advance()
        >>> print(str(p))
        AB(^M)C(^!)(M$)D(!$)
        >>> p.advance()
        >>> print(str(p))
        AB(^M)C(M$)D(^!)(!$)

        >>> p = Program("(^!)A(!$)(^Moo)(^Gar)(Gar$)B(Moo$)")
        >>> p.advance()
        >>> print(str(p))
        A(^!)(^Moo)(^Gar)(Gar$)B(!$)(Moo$)
        >>> p.advance()
        >>> print(str(p))
        A(^Moo)(^Gar)(Gar$)B(^!)(!$)(Moo$)

        """
        self.slide_slot(self.get_slot_name('!'), +1)

    def clean_instruction(self, instruction):
        """
        >>> p = Program('')
        >>> print(p.clean_instruction(''))
        None
        >>> print(p.clean_instruction('X'))
        X
        >>> print(p.clean_instruction('Well-tempered'))
        W
        >>> print(p.clean_instruction('(^8)(^7)(7$)CAT(8$)'))
        C
        >>> print(p.clean_instruction('(^8(beat))D'))
        D
        >>> print(p.clean_instruction('(^8)(^7)(7$)(8$)'))
        None

        """
        if len(instruction) == 0:
            return None
        else:
            pos = 0
            level = 0
            while instruction[pos] == '(':
                while True:
                    if instruction[pos] == '(':
                        level += 1
                    elif instruction[pos] == ')':
                        level -= 1
                    pos += 1
                    if level == 0 or pos >= len(instruction):
                        break
                if pos >= len(instruction):
                    return None
            return instruction[pos]

    def execute(self, instruction):
        raise NotImplementedError

    def step(self):
        """Execute one step of this Pophery program."""
        instruction = self.read_slot(self.get_slot_name('!'))
        instruction = self.clean_instruction(instruction)
        if instruction is None:
            return False
        else:
            self.execute(instruction)
            self.advance()
            return True

    def run(self):
        """Execute this Pophery program and return only when it terminates."""
        keep_going = self.step()
        while keep_going:
            keep_going = self.step()

class Semantics(Program):
    def deselect(self):
        locator_name = self.get_slot_name('/')
        try:
            self.remove_locator('(^%s)' % locator_name)
        except UndefinedLocatorError:
            pass
        try:
            self.remove_locator('(%s$)' % locator_name)
        except UndefinedLocatorError:
            pass

    def execute(self, instruction):
        """Apply the semantics of the given instruction to this Program.

        * 0 through 9 update the accumulator to the literal strings 0 through
          9, respectively.

        >>> p = Semantics("(^?)(?$)")
        >>> p.execute('0')
        >>> print(str(p))
        (^?)0(?$)

        * X ("cut") erases (updates with the zero-length string) the selection.

        >>> p = Semantics("(^/)hi(/$)")
        >>> p.execute('X')
        >>> print(str(p))
        (^/)(/$)
        >>> p = Semantics("(^`/)X(`/$)(^X)hi(X$)")
        >>> p.execute('X')
        >>> print(str(p))
        (^`/)X(`/$)(^X)(X$)

        * C ("copy") updates the contents of the clipboard with the contents
          of the selection.

        >>> p = Semantics("(^/)hi(/$)(^%)lo(%$)")
        >>> p.execute('C')
        >>> print(str(p))
        (^/)hi(/$)(^%)hi(%$)
        >>> p = Semantics("(^/)hi(/$)(^J)lo(J$)(^`%)J(`%$)")
        >>> p.execute('C')
        >>> print(str(p))
        (^/)hi(/$)(^J)hi(J$)(^`%)J(`%$)

        * V ("paste") updates the contents of the selection with the contents
          of the clipboard.

        >>> p = Semantics("(^/)hi(/$)(^%)lo(%$)")
        >>> p.execute('V')
        >>> print(str(p))
        (^/)lo(/$)(^%)lo(%$)
        >>> p = Semantics("(^C)lo(C$)(^J)hi(J$)(^`/)J(`/$)(^`%)C(`%$)")
        >>> p.execute('V')
        >>> print(str(p))
        (^C)lo(C$)(^J)lo(J$)(^`/)J(`/$)(^`%)C(`%$)

        * S ("select") selects the contents of the slot indirect by the
          accumulator.

        >>> p = Semantics("(^/)foo(/$)(^?)A(?$)(^A)Some text.(A$)")
        >>> p.execute('S')
        >>> print(str(p))
        foo(^?)A(?$)(^A)(^/)Some text.(/$)(A$)
        >>> p = Semantics("(^`/)k(`/$)(^k)foo(k$)(^?)A(?$)(^A)Some text.(A$)")
        >>> p.execute('S')
        >>> print(str(p))
        (^`/)k(`/$)foo(^?)A(?$)(^A)(^k)Some text.(k$)(A$)

        * A ("select all") selects the contents of the accumulator.

        >>> p = Semantics("(^/)foo(/$)(^?)A(?$)(^A)Some text.(A$)")
        >>> p.execute('A')
        >>> print(str(p))
        foo(^?)(^/)A(/$)(?$)(^A)Some text.(A$)
        >>> p = Semantics("(^`/)r(`/$)(^r)foo(r$)(^?)A(?$)(^A)Some text.(A$)")
        >>> p.execute('A')
        >>> print(str(p))
        (^`/)r(`/$)foo(^?)(^r)A(r$)(?$)(^A)Some text.(A$)

        * L ("left") slides the left locator of the selection leftward.

        >>> p = Semantics("foo(^/)bar(/$)")
        >>> p.execute('L')
        >>> print(str(p))
        fo(^/)obar(/$)
        >>> p = Semantics("(^/)foobar(/$)")
        >>> p.execute('L')
        >>> print(str(p))
        (^/)foobar(/$)
        >>> p = Semantics("foo(^C)bar(C$)(^`/)C(`/$)")
        >>> p.execute('L')
        >>> print(str(p))
        fo(^C)obar(C$)(^`/)C(`/$)
        >>> p = Semantics("The last time I saw Charlie")
        >>> p.execute('L')
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^/)

        * R ("right") slides the left locator of the selection rightward.

        >>> p = Semantics("foo(^/)bar(/$)")
        >>> p.execute('R')
        >>> print(str(p))
        foob(^/)ar(/$)
        >>> p = Semantics("foo(^/)(/$)bar")
        >>> p.execute('R')
        >>> print(str(p))
        foo(^/)(/$)bar
        >>> p = Semantics("foo(^C)bar(C$)(^`/)C(`/$)")
        >>> p.execute('R')
        >>> print(str(p))
        foob(^C)ar(C$)(^`/)C(`/$)
        >>> p = Semantics("The last time I saw Charlie")
        >>> p.execute('R')
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^/)

        * E ("end") moves the left locator of the selection to immediately
          to the left of the right locator of the selection, resulting in
          the selection containing the zero-length string.

        >>> p = Semantics("foo(^/)bar(/$)baz")
        >>> p.execute('E')
        >>> print(str(p))
        foobar(^/)(/$)baz
        >>> p = Semantics("foo(^a)b(^`/)a(`/$)r(a$)baz")
        >>> p.execute('E')
        >>> print(str(p))
        foob(^`/)a(`/$)r(^a)(a$)baz
        >>> p = Semantics("The last time I saw Charlie")
        >>> p.execute('E')
        Traceback (most recent call last):
        ...
        UndefinedLocatorError: (^/)

        * F ("find") searches everywhere in the contents of the accumulator
          for the contents of the clipboard. If found, that substring is
          selected.

        >>> p = Semantics("(^?)By hook or by crook, we will.(?$)(^%)ook(%$)")
        >>> p.execute('F')
        >>> print(str(p))
        (^?)By h(^/)ook(/$) or by crook, we will.(?$)(^%)ook(%$)

        * D ("drag-and-drop") moves the selection to the accumulator.

        >>> p = Semantics("(^/)hi(/$)(^?)lo(?$)")
        >>> p.execute('D')
        >>> print(str(p))
        hi(^?)(^/)hi(/$)(?$)
        >>> p = Semantics("(^C)lo(C$)(^J)hi(J$)(^`/)J(`/$)(^`?)C(`?$)")
        >>> p.execute('D')
        >>> print(str(p))
        (^C)(^J)hi(J$)(C$)hi(^`/)J(`/$)(^`?)C(`?$)

        * I ("input") waits for a line to appear on standard input, then
          places it (sans newline) in the accumulator.

        >>> from io import StringIO
        >>> p = Semantics("(^?)(?$)")
        >>> p.input = StringIO(chr(10).join(["Line.", "Line!", "LINE!"]))
        >>> p.execute('I')
        >>> print(str(p))
        (^?)Line.(?$)
        >>> p.execute('I')
        >>> print(str(p))
        (^?)Line!(?$)
        >>> p.execute('I')
        >>> print(str(p))
        (^?)LINE!(?$)
        >>> p.execute('I')
        >>> print(str(p))
        (^?)(?$)

        * O ("output") outputs the string in the accumulator to standard
          output, followed by a newline.

        >>> p = Semantics("(^?)Hello, world!(?$)")
        >>> p.execute('O')
        Hello, world!
        >>> print(str(p))
        (^?)Hello, world!(?$)

        Now we demonstrate some idioms.

        Assume the inital program defines some slots to contain initial
        data.  That data can then be loaded into the accumulator:

        >>> p = Semantics("(^0)data(0$)(^%)(%$)(^?)(?$)(^!)0(!$)SCAV")
        >>> p.run()
        >>> print(str(p))
        (^0)data(0$)(^%)data(%$)(^?)(^/)data(/$)(?$)0SCAV(^!)(!$)

        New data, say the literal string 1, can be stored into slot 0 with:

        >>> p = Semantics("(^0)data(0$)(^%)(%$)(^?)(?$)(^!)1(!$)AC0SV")
        >>> p.run()
        >>> print(str(p))
        (^0)(^/)1(/$)(0$)(^%)1(%$)(^?)0(?$)1AC0SV(^!)(!$)

        To copy from any arbitrary slot (say 0) to another (say 1), we can say:

        >>> p = Semantics("(^0)hi(0$)(^1)(1$)(^%)(%$)(^?)(?$)(^!)0(!$)SC1SV")
        >>> p.run()
        >>> print(str(p))
        (^0)hi(0$)(^1)(^/)hi(/$)(1$)(^%)hi(%$)(^?)1(?$)0SC1SV(^!)(!$)

        Accessing a slot with a longer name, such as (^123)xyz(123$), can be
        done with the help of a free slot like 0:

        >>> p = Semantics("(^0)(0$)(^123)xyz(123$)(^%)(%$)(^?)(?$)(^!)1(!$)AC0SV2AC0SEV3AC0SEV0SCAVSD")
        >>> p.run()
        >>> print(str(p))
        (^0)123(0$)(^123)xyz(123$)(^%)123(%$)(^?)(^/)xyz(/$)(?$)1AC0SV2AC0SEV3AC0SEV0SCAVSD(^!)(!$)

        To write data, say (^8)foo(8$), into a slot whose name is stored in
        another slot, such as (^9)jim(9$), we can say:

        >>> p = Semantics("(^8)foo(8$)(^9)jim(9$)(^jim)(jim$)(^%)(%$)(^?)(?$)(^!)8(!$)SC9SDSV")
        >>> p.run()
        >>> print(str(p))
        (^8)foo(8$)(^9)jim(9$)(^jim)(^/)foo(/$)(jim$)(^%)foo(%$)(^?)jim(?$)8SC9SDSV(^!)(!$)

        Finally, a complete, if simple, program:

        >>> p = Semantics("(^?)Hello, world!(?$)(^!)O(!$)")
        >>> p.run()
        Hello, world!

        """
        if instruction >= '0' and instruction <= '9':
            self.update_slot(self.get_slot_name('?'), instruction)
        elif instruction == 'X':
            self.update_slot(self.get_slot_name('/'), '')
        elif instruction == 'C':
            self.update_slot(self.get_slot_name('%'), self.read_slot(self.get_slot_name('/')))
        elif instruction == 'V':
            self.update_slot(self.get_slot_name('/'), self.read_slot(self.get_slot_name('%')))
        elif instruction == 'S':
            self.deselect()
            locator_name = self.get_slot_name('/')
            new_selection = '(^%s)%s(%s$)' % (
                locator_name,
                self.read_slot_indirect(self.get_slot_name('?')),
                locator_name
            )
            self.update_slot_indirect(self.get_slot_name('?'), new_selection)
        elif instruction == 'A':
            self.deselect()
            locator_name = self.get_slot_name('/')
            new_selection = '(^%s)%s(%s$)' % (
                locator_name,
                self.read_slot(self.get_slot_name('?')),
                locator_name
            )
            self.update_slot(self.get_slot_name('?'), new_selection)
        elif instruction == 'L':
            locator_name = self.get_slot_name('/')
            self.slide_locator('(^%s)' % locator_name, -1)
        elif instruction == 'R':
            locator_name = self.get_slot_name('/')
            if self.read_slot(locator_name) != '':
                self.slide_locator('(^%s)' % locator_name, +1)
        elif instruction == 'E':
            locator_name = self.get_slot_name('/')
            self.remove_locator('(^%s)' % locator_name)
            pos = self.pos_left('(%s$)' % locator_name, 0)
            self.insert_locator('(^%s)' % locator_name, pos)
        elif instruction == 'F':
            accumulator = self.read_slot(self.get_slot_name('?'))
            clipboard = self.read_slot(self.get_slot_name('%'))
            pos = accumulator.find(clipboard)
            if pos >= 0:
                self.deselect()
                locator_name = self.get_slot_name('/')
                accumulator = MutableString(accumulator)
                accumulator.insert_locator('(^%s)' % locator_name, pos)
                pos_right = accumulator.pos_right('(^%s)' % locator_name, 0)
                accumulator.insert_locator('(%s$)' % locator_name,
                    pos_right + len(clipboard))
                self.update_slot(self.get_slot_name('?'), accumulator)
            else:
                pass
        elif instruction == 'D':
            locator_name = self.get_slot_name('/')
            selection = self.read_slot(locator_name)
            self.deselect()
            new_selection = '(^%s)%s(%s$)' % (
                locator_name,
                selection,
                locator_name
            )
            self.update_slot(self.get_slot_name('?'), new_selection)
        elif instruction == 'O':
            line = self.read_slot('?') + "\n"
            self.output.write(line)
        elif instruction == 'I':
            text = self.input.readline()
            if text.endswith('\n'):
                text = text[:-1]
            self.update_slot(self.get_slot_name('?'), text)
        else:
            pass

    def step(self):
        """Execute one step of this Pophery program.

        """
        return super(Semantics, self).step()

    def run(self):
        """Execute this Pophery program and return only when it terminates.

        """
        return super(Semantics, self).run()

class TracedProgram(Semantics):
    """

    >>> p = TracedProgram("(^?)Hello, world!(?$)(^!)O(!$)OO")
    >>> p.run()
    [(^?)Hello, world!(?$)(^!)O(!$)OO]
    Hello, world!
    [(^?)Hello, world!(?$)O(^!)O(!$)O]
    Hello, world!
    [(^?)Hello, world!(?$)OO(^!)O(!$)]
    Hello, world!
    [(^?)Hello, world!(?$)OOO(^!)(!$)]

    """

    def __init__(self, initial):
        super(TracedProgram, self).__init__(initial)

    def run(self):
        print("[%s]" % str(self))
        super(TracedProgram, self).run()

    def step(self):
        result = super(TracedProgram, self).step()
        if result:
            print("[%s]" % str(self))
        return result

def main(argv):
    optparser = OptionParser("[python] %prog {options} {source.tranzy}\n" + __doc__)
    optparser.add_option("-e", "--evaluate",
                         action="store", type="string", dest="program", default=None,
                         help="evaluate Pophery program on command line")
    optparser.add_option("-l", "--show-license",
                         action="store_true", dest="show_license", default=False,
                         help="show product license and exit")
    optparser.add_option("-t", "--trace",
                         action="store_true", dest="trace", default=False,
                         help="trace execution during run")
    optparser.add_option("-T", "--run-tests",
                         action="store_true", dest="run_tests", default=False,
                         help="run self-tests and exit")
    (options, args) = optparser.parse_args(argv[1:])
    exit_code = None
    if options.show_license:
        print(sys.argv[0])
        print(__doc__)
        print(LICENSE)
        exit_code = 0
    if options.run_tests:
        import doctest
        (fails, something) = doctest.testmod(verbose=True)
        if fails == 0:
            print("All tests passed.")
            exit_code = 0
        else:
            exit_code = 1

    if exit_code is not None:
        sys.exit(exit_code)

    klass = Semantics
    if options.trace:
        klass = TracedProgram

    if options.program is not None:
        klass(options.program).run()

    for filename in args:
        program = klass('')
        program.load(filename)
        program.run()

if __name__ == "__main__":
    main(sys.argv)


import logging

from flask import Blueprint, render_template, redirect, request
from werkzeug import parse_options_header

from google.appengine.ext import ndb

# For photos
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.blobstore import BlobKey
from heroes.helpers import get_image_url #not used

# CLOUD STORAGE
import os
import cloudstorage
from google.appengine.api import app_identity
import ntpath

from heroes.positions.models import Position
from heroes.representatives.models import Rep
from heroes.roles.models import Role

from .models import Squadmember

squadmember_bp = Blueprint('squadmember', __name__)

# CLOUD STORAGE #
def get_bucket_name():
    bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
    return bucket_name

def is_local():
    """ Check if you are currently running on localhost or on GAE. """
    if os.environ.get('SERVER_NAME', '').startswith('localhost'):
        return True
    elif 'development' in os.environ.get('SERVER_SOFTWARE', '').lower():
        return True
    else:
        return False

@squadmember_bp.route('/<key>/')
def squadmember_view(key):
    """A squadmember PAGE."""
    squadmember_key = ndb.Key(urlsafe=key)
    squadmember = squadmember_key.get()

    #BREADCRUMB
    squad = squadmember_key.parent().get()
    team = squad.key.parent().get()
    country = squad.key.parent().parent().get()
    sport = squad.key.parent().parent().parent().get()

    breadcrumb_list = [sport, country, team, squad]
    title = squadmember.title
    #END BREADCRUMB

    role_entries = Role.query(ancestor=country.key).fetch()
    position_entries = Position.query(ancestor=country.key).fetch()

    form_action = "/admin/squadmember/update/" +  key
    upload_url = blobstore.create_upload_url(form_action)

    return render_template('/admin/squadmember.html',
        breadcrumb = breadcrumb_list,
        object_title=title,
        squadmember_object=squadmember,
        squad_object=squad,
        roles=role_entries,
        # photo_url=image_url,
        positions=position_entries,
        # upload_url=upload_url,
    )

# HANDLERS #

# ADD squadmember
@squadmember_bp.route('/add/<squad_key>/<rep_key>', methods=['GET'])
def add_entry(squad_key, rep_key):
    squad_key = ndb.Key(urlsafe=squad_key)
    rep_key = ndb.Key(urlsafe=rep_key)

    squadmember = Squadmember(rep=rep_key, parent=squad_key)
    squadmember.put()

    return redirect('/admin/squad/{}'.format(squad_key.urlsafe()))

# UPDATE squadmember
@squadmember_bp.route('/update/<key>', methods=['POST'])
def update_entry(key):

    squadmember_key = ndb.Key(urlsafe=key)
    squadmember = squadmember_key.get()

    if request.form['roleinput']:
        role_key = ndb.Key(urlsafe=request.form['roleinput'])
        squadmember.role = role_key

    if request.form['positioninput']:
        position_key = ndb.Key(urlsafe=request.form['positioninput'])
        squadmember.position = position_key

    #SQUADMEMBER PHOTO
    #define file name and path
    #   [bucket] /photos/[sport]/[country]/[division]/[squad(year)]/[first]-[last].jpg
    #   - crap if anything changes name (but not too hard to fix)
    #   - good for bulk upload
    #   - only works for jpgs
    uploaded_file = request.files['uploaded-file']
    file_content = uploaded_file.read()

    if file_content:
        logging.info(" THERE IS A PHOTO!")
        # check for jpg
        file_type = uploaded_file.content_type

        if file_type == "image/jpeg":
            filepath = generate_photo_filename(squadmember_key)

            # upload the file to Google Cloud Storage
            gcs_file = cloudstorage.open(
                filepath ,
                'w',
                content_type=file_type,
                retry_params=cloudstorage.RetryParams(backoff_factor=1.1)
                )
            gcs_file.write(file_content)
            gcs_file.close()

        else:
            logging.info("Wrong image type")

    else:
        logging.info("No photo uploaded")

    squadmember.put()

    return redirect('/admin/squadmember/{}'.format(squadmember.key.urlsafe()))

# REMOVE squadmember
@squadmember_bp.route('/remove/<squadmember_key>/', methods=['GET'])
def remove_entry(squadmember_key):
    squadmember_key = ndb.Key(urlsafe=squadmember_key)
    squad_key = squadmember_key.parent().get().key
    squadmember_key.delete()

    # TODO delete any photos

    return redirect('/admin/squad/{}'.format(squad_key.urlsafe()))

# DELETE PHOTO
@squadmember_bp.route('/deletephoto/<squadmember_key>/', methods=['GET'])
def delete_photo(squadmember_key):
    squadmember_key = ndb.Key(urlsafe=squadmember_key)
    squadmember = squadmember_key.get()
    filepath = generate_photo_filename(squadmember_key)
    try:
        cloudstorage.delete(filepath)
    except:
        logging.info("NO PHOTO TO DELETE")

    return redirect('/admin/squadmember/{}'.format(squadmember.key.urlsafe()))

# ================================================================================
# HELPERS
# ================================================================================

def generate_photo_filename(squadmember_key):
    bucket_name = get_bucket_name()
    #get parent objects
    squadmember = squadmember_key.get()
    squad_key = squadmember_key.parent()
    team_key = squad_key.parent()
    country_key = team_key.parent()
    sport_key = country_key.parent()
    # file path codes
    sport_code = sport_key.get().code
    country_code = country_key.get().code
    division_code = team_key.get().division.get().code
    squad_code = squad_key.get().code
    #bucket and folder
    bucket_and_folder = '/'+bucket_name+'/photos/'+sport_code+'/'+country_code+'/'+division_code+'/'+squad_code
    logging.info(bucket_and_folder)
    #file name
    file_name = str(squadmember.title).replace(" ", "-").lower()
    file_name = file_name+'.jpg'

    return bucket_and_folder + '/' + file_name