import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn import linear_model
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras import models
from keras import layers

f  = pd.read_csv('complete.csv', encoding='utf-8')
X = f[['age', 'height_cm', 'weight_kg', 'eur_release_clause', 'overall', 'potential', 'pac','sho','pas','dri','def','phy','international_reputation','skill_moves','weak_foot','crossing','finishing','heading_accuracy','short_passing','volleys','dribbling','curve','free_kick_accuracy','long_passing','ball_control','acceleration','sprint_speed','agility','reactions','balance','shot_power','jumping','stamina','strength','long_shots','aggression','interceptions','positioning','vision','penalties','composure','marking','standing_tackle','sliding_tackle','gk_diving','gk_handling','gk_kicking','gk_positioning','gk_reflexes','rs','rw','rf','ram','rcm','rm','rdm','rcb','rb','rwb','st','lw','cf','cam','cm','lm','cdm','cb','lb','lwb','ls','lf','lam','lcm','ldm','lcb','gk']]
Y = f[['eur_value', 'eur_wage']]

sc = StandardScaler()

X[0:].fillna(0, inplace=True)
#print (X, Y)

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20)

X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

kfold = KFold(n_splits=10, shuffle=True)
cvloss = []
cvaccuracy = []
for train, test in kfold.split(X, Y):
	# Start neural network
	network = models.Sequential()

# Add fully connected layer with a ReLU activation function
	network.add(layers.Dense(units=1024, activation='relu', input_shape=(X_train.shape[1],)))

# Add fully connected layer with a ReLU activation function
	network.add(layers.Dense(units=1024, activation='relu'))
	network.add(layers.Dense(units=1024, activation='relu'))

# Add fully connected layer with no activation function
	network.add(layers.Dense(units=2))

	network.compile(loss='mean_squared_error', # Mean squared error
                	optimizer='RMSprop', # Optimization algorithm
                	metrics=['accuracy']) # Mean squared error

	history = network.fit(X.iloc[train], # Features
                      	Y.iloc[train], # Target vector
                      	epochs=10, # Number of epochs
                      	verbose=0, # No output
		      	batch_size=100) #Batch size
                      	#validation_data=(X[][test], y[][test])) # Data for evaluation
	loss, accuracy = network.evaluate(X.iloc[test], Y.iloc[test], batch_size=100)
	cvloss.append((loss)**0.5)
	cvaccuracy.append(accuracy)
	print (loss**0.5)
print("%.2f%% (+/- %.2f%%)" % (np.mean(cvloss), np.std(cvloss)))
print("%.2f%% (+/- %.2f%%)" % (np.mean(cvaccuracy), np.std(cvaccuracy)))

al = [0.001, 0.01, 0.1, 1 , 10, 100, 1000, 10000, 100000, 100000]
for a in al :
	reg = linear_model.Ridge(alpha=a, normalize=True)
	reg.fit(X_train, y_train)

	print ("alpha = ", a)
	print ("RMSE Train: ", np.mean((reg.predict(X_train)-y_train)**2) ** 0.5)
	print ("RMSE Test: ", np.mean((reg.predict(X_test)-y_test)**2) ** 0.5)
	#print ("L2 Norm weight Vector: ", np.sum((reg.coef_)**2)** 0.5)
	#print ("Regresssion Intercept ", (reg.intercept_))
	#print ("Regression Weights ", (reg.coef_))
	print ("Regression Score ", reg.score(X_test, y_test))


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

import scrapy
from pyquery import PyQuery as pq

from hebei.items import HebeiItem
import copy

class MuseumSpider(scrapy.Spider):
    name = 'museum'
    allowed_domains = ['www.hebeimuseum.org']
    start_urls = ['http://www.hebeimuseum.org/channels/175.html']
    base_url = "http://www.hebeimuseum.org"

    def parse(self, response):
        doc = pq(response.text)
        class_list = doc('.inner .bd ul li').items()
        item = HebeiItem()
        for cls in class_list:
            item['cls'] = cls.text()                                    # 类名
            item['classUrl'] =  self.base_url + cls('a').attr('href')   # 类URL
            yield scrapy.Request(
                item['classUrl'],
                callback=self.class_detail,
                meta={'item':copy.deepcopy(item)})

    def class_detail(self, response):
        item = response.meta["item"]
        doc = pq(response.text)
        item_list = doc('.pgwSlideshow li').items()
        for i in item_list:
            item['title'] = i('img').attr('alt')                        # 标题
            item['img'] = self.base_url + i('img').attr('src')          # imgURL
            print(item)

    # def parse(self, response):
    #     li_list = response.xpath("//div[@class='bd']/ul/li")
    #     for li in li_list:
    #         item = HebeiItem()
    #         usrl = li.xpath("./a/@href").extract_first()
    #
    #         if 'http://www.hebeimuseum.org' in usrl:
    #             tt_url = usrl
    #         else:
    #             tt_url = self.base_url + usrl
    #
    #         print(tt_url)
    #         item['tt_url'] = tt_url
    #         yield scrapy.Request(
    #             tt_url,
    #             callback=self.parse_deal,
    #             meta={'item': item}
    #         )
    #
    # def parse_deal(self, response):
    #     # href_list = response.xpath("//div[@class='ps-current']")
    #
    #     img_url = response.xpath("//ul[@class='pgwSlideshow']/li/img/@src").extract()
    #
    #     for url in img_url:
    #         if 'http://www.hebeimuseum.org' in url:
    #             img = url
    #         else:
    #             img = self.base_url + url
    #
    #             item = response.meta['item']
    #             # item['content'] = response.xpath("//ul[@class='pgwSlideshow']/li/img/@data-description").extract()
    #             item['title'] = response.xpath("//ul[@class='pgwSlideshow']/li/img/@alt").extract_first()
    #             item['img'] = img
    #
    #             yield item


def solution(name, yearning, photo):
    answer = []

    d = {}
    for i in range(len(name)):
        d[name[i]] = yearning[i]

    for p in photo:
        point = 0
        for i in range(len(p)):
            if p[i] in d:
                point += d[p[i]]
        answer.append(point)

    return answer


import twitter, json, csv
from urllib.parse import unquote

q = 'homepod'
count = 100
loop = 120

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''

# Set the key and secret of your twitter developer
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
						   CONSUMER_KEY, CONSUMER_SECRET)

# Get twitter API
twitter_api = twitter.Twitter(auth=auth)

# Create or open a csv file and write
# Set the csv delimiter with '|'
csvfile = open('tweets_7days.csv', 'a')
csvwriter = csv.writer(csvfile, delimiter='|')

# This function receive a string and replace its charater of '|', carriage return and line feed with black.
def getVal(val):
	clean = ""
	if val:
		val = val.replace('|', ' ')
		val = val.replace('\n', ' ')
		val = val.replace('\r', ' ')
		clean = val
	return clean

# This function receive a list of tweets, then write them into csv file.
def tweetsWriter(tweets):
	for tweet in tweets:
		# if the field of coordinates is not none, then convert its value to a string
		if tweet['coordinates']:
			geocode = ",".jion(tweet['coordinates']['coordinates'])
		else:
			geocode = tweet['coordinates']

		# write the values to file
		csvwriter.writerow([
			tweet['id_str'],
			tweet['created_at'],
			geocode,
			getVal(tweet['user']['screen_name']),
			getVal(tweet['full_text']),
			getVal(tweet['user']['location']),
			tweet['user']['statuses_count'],
			tweet['user']['followers_count'],
			tweet['user']['friends_count'],
			tweet['user']['created_at']])

print ('Filtering the public timeline for track="%s"' % (q,))

# Search the tweets which inculde 'q', and the number is limited to 'count'.
search_results = twitter_api.search.tweets(q=q, count=count, tweet_mode='extended')
statuses = search_results['statuses']
tweetsWriter(statuses)
# Iterate through 'loop' more batches of results by following the cursor
number = 0
for _ in range(loop):
	number += len(statuses)
	print('Length of statuses', number)
	try:
		next_results = search_results['search_metadata']['next_results']
	except KeyError as e: # No more results when next_results doesn't exist
		break
	# Create a dictionary from next_results, which has the following form:
	# ?max_id=847960489447628799&q=%23RIPSelena&count=100&include_entities=1
	kwargs = dict([ kv.split('=') for kv in unquote(next_results[1:]).split("&") ])
	kwargs["tweet_mode"] = "extended"
	search_results = twitter_api.search.tweets(**kwargs)
	tweetsWriter(search_results['statuses'])


import geojson

from dataviz import parse, MY_FILE

def create_map(data_file):

    geo_map = {"type": "FeatureCollection"}     # Type of GeoJSON

    item_list = []      # List to collect each point to graph

    for index, line in enumerate(data_file):     # Iterate data using enumerate to get line and index
        if line['X'] == "0" or line['Y'] == "0":        # Skip 0,0 coordinate outliers that throw off map
            continue
        data = {}       # New dict for each iteration

#       # Assign line items to appropriate GeoJSON fields.
        data['type'] = 'Feature'
        data['id'] = index
        data['properties'] = {'title': line['Category'],
                              'description': line['Descript'],
                              'date': line['Date']}
        data['geometry'] = {'type': 'Point',
                            'coordinates': (line['X'], line['Y'])}

        item_list.append(data)      # Append to list

    for point in item_list:
        geo_map.setdefault('features', []).append(point)        # Add point to dict from item_list

    with open('file_sf.geojson', 'w') as f:
        f.write(geojson.dumps(geo_map))     # Write to file

def main():
    data = parse(MY_FILE, ",")

    return create_map(data)

if __name__ == "__main__":
    main()


# coding=utf-8

import logging
import traceback
import re
import types

from qfcommon.thriftclient.presms import PreSmsThriftServer
from qfcommon.server.client import ThriftClient

presmsClient_log = logging.getLogger("presmslog")

class PreSms():

    _MOBILESS_RE = '^(1\d{10},)*(1\d{10},?)$'

    def __init__(self, server, batch_mode=True):
        '''
        batch_mode是否是批量模式。True为批量模式，放在服务器端进行批量发送
        '''
        self.server = server
        self.batch_mode = batch_mode

    def _ping(self):
        '''
        检查服务接口
        '''
        try:
            self.thriftClient.call('ping')
        except:
            presmsClient_log.error(traceback.format_exc())

    def _checkphones(self, phones):
        '''
        检查手机号码是否正确
        '''
        phonestr = ""
        # 类型检查
        if type(phones) in (types.ListType, types.TupleType) :
            phonestr = ','.join(phones)
        elif type(phones) in (types.StringType, types.IntType):
            phonestr = str(phones)
        elif type(phones) == types.UnicodeType:
            phonestr = phones.encode("utf-8")
        else:
            return False, None

        # 格式检查
        if re.match(self._MOBILESS_RE, phonestr):
            return True, phonestr

        return False, None

    def sendSms(self, mobile, content, tag, source, target):
        '''
        发送短信
        mobile，短信的发送对象，可以是元组或者数组，也可以是单一的字符串，如果是字符串，必须符合手机格式
        content：短信内容，
        tag：标签，分类，
        source: 哪里调用
        target:作用是什么
        '''
        if not mobile or not content:
            return False, "参数为空"

        checkresult, phone = self._checkphones(mobile)
        if not checkresult:
            return False, "手机号码格式不合法"
        # 转编码，统一使用utf-8
        if isinstance(content, types.UnicodeType):
            content = content.encode('utf-8')
        if isinstance(tag, types.UnicodeType):
            tag = tag.encode('utf-8')
        if isinstance(source, types.UnicodeType):
            source = source.encode('utf-8')
        if isinstance(target, types.UnicodeType):
            target = target.encode('utf-8')

        try:
            flag = 0
            if self.batch_mode:
                flag = ThriftClient(self.server, PreSmsThriftServer).call('sendsms', phone, content, tag, source, target)
            else:
                phonelist = phone.split(",")
                for p in phonelist:
                    ThriftClient(self.server, PreSmsThriftServer).call('sendsms', p, content, tag, source, target)
                flag = 1
            if flag >= 0:
                return True, "成功"
        except:
            presmsClient_log.error(traceback.format_exc())

        return False, "发送失败"

    def reportSms(self, mobile, jsoncontent, source="payserver", target="receipt"):
        '''
        发送短信
        mobile，短信的发送对象，可以是元组或者数组，也可以是单一的字符串，如果是字符串，必须符合手机格式
        json：短信内容，json结构
        source: 哪里调用,默认是payserver
        target:作用是什么，默认是receipt
        '''
        if not mobile or not jsoncontent:
            return False, "参数为空"

        checkresult, phone = self._checkphones(mobile)
        if not checkresult:
            return False, "手机号码格式不合法"

        try:
            flag = 0
            if self.batch_mode:
                flag = ThriftClient(self.server, PreSmsThriftServer).call('sendcustomersms', phone, jsoncontent, source, target)
            else:
                phonelist = phone.split(",")
                for p in phonelist:
                    ThriftClient(self.server, PreSmsThriftServer).call('sendcustomersms', p, jsoncontent, source, target)
                flag = 1
            if flag >= 0:
                return True, "成功"
        except:
            presmsClient_log.error(traceback.format_exc())

        return False, "发送失败"


import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split

from Algorithms.KNN import KNN
from Algorithms.Naive_Bayes import Naive_Bayes

def main():

    # open the dataset
    Data_set = pd.read_csv("Data_Sets/bodyPerformance.csv", delimiter=",")

    # number of rows and columns in the data_set
    rows, cols = Data_set.shape

    # features name of the train set
    features_names = Data_set.columns[0:11]

    # the target set
    target = Data_set["class"].tolist()

    # get the unique value of the target -> remove redundancy
    target = list(set(target))

    # the training set
    data_training_set = Data_set[features_names].values

    # the target set
    target_set = Data_set["class"]

    # Data Preprocessing
    label_gender = preprocessing.LabelEncoder()
    label_gender.fit(["F", "M"])
    data_training_set[:, 1] = label_gender.transform(data_training_set[:, 1])

    # splitting the sets
    data_train, data_test, target_train, target_test = train_test_split(
        data_training_set, target_set, test_size=0.4, random_state=5
    )

    # KNN algorithm
    KNN_Accuracy = KNN(data_train, data_test, target_train, target_test, rows)

    # Naive algorithm
    Naive_Accuracy = Naive_Bayes(data_train, data_test, target_train, target_test)

    # print the accuracy of the KNN algorithm
    print(f"\nKNN Accuracy: {KNN_Accuracy}")

    # print the accuracy of the naive algorithm
    print(f"\nNaive Accuracy: {Naive_Accuracy}")

if __name__ == "__main__":
    main()


import sys
input = lambda: sys.stdin.readline().strip()

def sol():
    n = int(input())
    wine = [0] * 10001
    for i in range(n):
        wine[i+1] = int(input())
    dp = [0] * 10001
    dp[1] = wine[1]
    dp[2] = wine[1] + wine[2]
    for i in range(3, n+1):
        dp[i] = max(dp[i-1], dp[i-3] + wine[i-1] + wine[i], dp[i-2] + wine[i])
    print(dp[n])

sol()


from operator import itemgetter
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import RFE
import numpy as np
from scipy.stats.stats import pearsonr
from numpy import zeros
from myFunctions import cv2NN
from myFunctions import cv2NM
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
import statistics

#region GetData

with open('i.csv') as f:
    lines = f.readlines()

formattedList = []
for line in lines:
    formattedList.append(line.split(';'))

converted = []
counter = 0
for fl in formattedList:
    converted.append(
        [float(fl[0]), fl[1] == 'yes', fl[2] == 'yes', fl[3] == 'yes', fl[4] == 'yes', fl[5] == 'yes', fl[6] == 'yes',
         fl[7] == 'yes', int(fl[8])])

npArray = np.array(converted)

#endregion

#region GetBestFeatures
correlations = []

for i in range(6):
    corr, _ = pearsonr(npArray[:, i], npArray[:, 8])
    correlations.append([i, corr.__abs__()])

npCorrelations = np.array(correlations)
sortedCorrelations = sorted(npCorrelations, key=itemgetter(1), reverse=True)
print("\nKorelacja cech z decyzja: ")
print(np.array(sortedCorrelations))

bestAttributes1 = np.ravel(np.array(sortedCorrelations)[:, 0]).astype(int)

chi2Features = SelectKBest(chi2, k=6)
x_kbest_features = chi2Features.fit_transform(npArray[:,[0,1,2,3,4,5]],npArray[:, 8])

print("\nPunkty cech w Chi2 test")
print(chi2Features.scores_)

bestAttributes1 = [3, 2, 4, 1, 5, 0]
#endregion

###################KNN
print("\n###ALGORYTM KNN###\n")
###################klasa 1

howmanytimes = 5

#array dimemnsions : test, k-nn value, featureCount, metrics, non/normalized
results = zeros([howmanytimes, 11, len(bestAttributes1), 2, 2])

#                #testCount, featureCount, metrics
resultsNM = zeros([howmanytimes, len(bestAttributes1), 2, 2])
metrics = ['euclidean', 'manhattan']

X = npArray[:, 0:6]
y = npArray[:, 8]
print("Ostre zapalenie drog moczowych, poprawnosc klasyfikacji:")

kValues = [1, 5, 10]
nonNormalizedIndex = 0
normalizedIndex = 1

for testCount in range(howmanytimes):
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)

    for metricIndex in [0,1]:
        for atrIndex in range(0, len(bestAttributes1)):

            score = cv2NM(X_train[:, bestAttributes1[0:atrIndex + 1]], X_test[:, bestAttributes1[0:atrIndex + 1]], y_train, y_test, metric=metrics[metricIndex])
            resultsNM[testCount][atrIndex][metricIndex][nonNormalizedIndex] = score

            normalizedDataScore = cv2NM(X_train[:, bestAttributes1[0:atrIndex + 1]], X_test[:, bestAttributes1[0:atrIndex + 1]], y_train, y_test, metric=metrics[metricIndex], scalling=True)
            resultsNM[testCount][atrIndex][metricIndex][normalizedIndex] = normalizedDataScore

            for k in kValues:
                score = cv2NN(X_train[:, bestAttributes1[0:atrIndex + 1]], X_test[:, bestAttributes1[0:atrIndex + 1]], y_train, y_test, kneighbors=k, metric=metrics[metricIndex])
                results[testCount][k][atrIndex][metricIndex][nonNormalizedIndex] = score

                normalizedDataScore = cv2NN(X_train[:, bestAttributes1[0:atrIndex + 1]], X_test[:, bestAttributes1[0:atrIndex + 1]], y_train, y_test, kneighbors=k, metric=metrics[metricIndex], scalling= True)
                results[testCount][k][atrIndex][metricIndex][normalizedIndex] = normalizedDataScore

#print(resultsNM) #macierz wynikow

for metricIndex in [0,1]:
    print("\nMetryka: {}".format(metrics[metricIndex]))
    for k in kValues:
        print("\nK: {}".format(k))

        for atrIndex in range(0, len(bestAttributes1)):
            nnor =  results[:,k, atrIndex, metricIndex, nonNormalizedIndex]
            nor =  results[:,k, atrIndex, metricIndex, normalizedIndex]
            print("{} atrybutow: {}, odchylenie std. : {}, normalizowane: {}, odchylenie std. : {}".format(atrIndex+1, nnor.mean(), statistics.stdev(nnor),nor.mean(), statistics.stdev(nor)))

print("\n Algorytm NM")
for metricIndex in [0,1]:
    print("\nMetryka: {}".format(metrics[metricIndex]))
    for atrIndex in range(0, len(bestAttributes1)):
        nnor = resultsNM[:, atrIndex, metricIndex, nonNormalizedIndex]
        nor = resultsNM[:, atrIndex, metricIndex, normalizedIndex]
        print("{} atrybutow: {}, odchylenie std. : {}, normalizowane: {}, odchylenie std. : {}".format(atrIndex+1, nnor.mean(), statistics.stdev(nnor),nor.mean(), statistics.stdev(nor)))


def caesarCipher(s, k):
    # Write your code here
    l_s = [chr(i) for i in range(ord('a'),ord('z')+1)]
    u_s = [chr(i) for i in range(ord('A'),ord('Z')+1)]
    str = ''
    for i in s:
        if i in l_s:
            str += l_s[(l_s.index(i) + k) % 26]
        elif i in u_s:
            str += u_s[(u_s.index(i) + k) % 26]
        else:
            str += i
    return str


'''
'''

def is_good_data_event(event) :

    if not event.isSingle1Trigger() : return False

    if not event.isSvtBiasOn() : return False

    if not event.isSvtClosed() : return False

    if event.hasSvtBurstModeNoise() : return False

    if event.hasSvtEventHeaderErrors() : return False

    return True

def get_good_cluster_pair(event) :

    cluster_pair = []

    for first_cluster_n in xrange(event.getNumberOfEcalClusters()) :

        first_cluster = event.getEcalCluster(first_cluster_n)

        for second_cluster_n in xrange(event.getNumberOfEcalClusters()) :

            second_cluster = event.getEcalCluster(second_cluster_n)

            if first_cluster.getPosition()[1]*second_cluster.getPosition()[1] > 0 : continue

            cluster_pair_dt = first_cluster.getClusterTime() - second_cluster.getClusterTime()

            if cluster_pair_dt < -1.6 or cluster_pair_dt > 1.7 : continue

            cluster_pair = [first_cluster, second_cluster]

    return cluster_pair


import os
import sys

path = str(sys.argv[1])
print("Folder file Path {0}".format(path))

for filename in os.listdir(path):
    input_path = os.path.join(path,filename)
    output_name = filename[:-4]
    output_path = os.path.join(path,output_name)

    if filename.endswith(".mp4"):
        os.system("ffmpeg -i {0} -c:v prores_ks -profile:v -1 -c:a pcm_s32le {1}.mov".format(input_path, output_path))
        print(filename)
    else:
        continue

print("complete.")


import numpy as np
# edited code from Corrfunc code to allow Peebles estimator of correlation function

def convert_counts_to_cf(ND1, ND2, NR1, NR2,
							D1D2, D1R2, D2R1, R1R2,
							estimator='Peebles'):

	pair_counts = dict()

	fields = ['D1D2', 'D1R2', 'D2R1', 'R1R2']
	arrays = [D1D2, D1R2, D2R1, R1R2]
	for (field, array) in zip(fields, arrays):
		try:

			if np.max(array['weightavg']) > 0:
				npairs = array['npairs'] * array['weightavg']

			else:
				npairs = array['npairs']
			pair_counts[field] = npairs

		except IndexError:
			pair_counts[field] = array

	nbins = len(pair_counts['D1D2'])
	if (nbins != len(pair_counts['D1R2'])) or \
	   (nbins != len(pair_counts['D2R1'])) or \
	   (nbins != len(pair_counts['R1R2'])):
		msg = 'Pair counts must have the same number of elements (same bins)'
		raise ValueError(msg)

	nonzero = pair_counts['R1R2'] > 0
	if 'LS' in estimator or 'Landy' in estimator:
		fN1 = np.float(NR1) / np.float(ND1)
		fN2 = np.float(NR2) / np.float(ND2)
		cf = np.zeros(nbins)
		cf[:] = np.nan
		cf[nonzero] = (fN1 * fN2 * pair_counts['D1D2'][nonzero] -
					   fN1 * pair_counts['D1R2'][nonzero] -
					   fN2 * pair_counts['D2R1'][nonzero] +
					   pair_counts['R1R2'][nonzero]) / pair_counts['R1R2'][nonzero]
		if len(cf) != nbins:
			msg = 'Bug in code. Calculated correlation function does not '\
				  'have the same number of bins as input arrays. Input bins '\
				  '={0} bins in (wrong) calculated correlation = {1}'.format(
					  nbins, len(cf))
			raise RuntimeError(msg)
	elif estimator == 'Peebles':
		fN1 = np.float(NR1) / np.float(ND1)

		cf = np.zeros(nbins)
		cf[:] = np.nan
		cf[nonzero] = (fN1 * pair_counts['D1D2'][nonzero]) / pair_counts['D1R2'][nonzero] - 1
	else:
		return

	return cf

def convert_counts_to_wp(ND1, ND2, NR1, NR2,
							   D1D2, D1R2, D2R1, R1R2,
							   nrpbins, pimax, dpi=1.0,
							   estimator='Peebles'):

	import numpy as np
	if dpi <= 0.0:
		msg = 'Binsize along the line of sight (dpi) = {0}'\
			  'must be positive'.format(dpi)
		raise ValueError(msg)

	xirppi = convert_counts_to_cf(ND1, ND2, NR1, NR2,
									 D1D2, D1R2, D2R1, R1R2,
									 estimator=estimator)
	wp = np.empty(nrpbins)
	npibins = len(xirppi) // nrpbins
	if ((npibins * nrpbins) != len(xirppi)):
		msg = 'Number of pi bins could not be calculated correctly.'\
			  'Expected to find that the total number of bins = {0} '\
			  'would be the product of the number of pi bins = {1} '\
			  'and the number of rp bins = {2}'.format(len(xirppi),
													   npibins,
													   nrpbins)
		raise ValueError(msg)

	# Check that dpi/pimax/npibins are consistent
	# Preventing issue #96 (https://github.com/manodeep/Corrfunc/issues/96)
	# where npibins would be calculated incorrectly, and the summation would
	# be wrong.
	if (dpi*npibins != pimax):
		msg = 'Pimax = {0} should be equal to the product of '\
			  'npibins = {1} and dpi = {2}. Check your binning scheme.'\
			  .format(pimax, npibins, dpi)
		raise ValueError(msg)

	for i in range(nrpbins):
		wp[i] = 2.0 * dpi * np.sum(xirppi[i * npibins:(i + 1) * npibins])

	return wp


from playwright.sync_api import expect

def test_go_to_api_page_from_main_page(browser):
    context = browser.new_context()
    page = context.new_page()

    page.goto("https://cloud.ru")
    page.wait_for_selector("//li[normalize-space(.)='Сервисы']").click()
    page.wait_for_selector("//div[@id='portal']//div[normalize-space(.)='Инфраструктура']").click()
    page.wait_for_selector(
        "//div[@id='portal']//h2[normalize-space(.)='Инфраструктура']/following-sibling::a[contains(@href, "
        "'api-gateway')]").click()
    page.wait_for_url("https://cloud.ru/ru/products/oblachnyj-api-gateway-hosting")

    expect(page).to_have_title("API Gateway")


"""
Finone API Controller

Processes XML response from Mortech, parses, and stores into database.
Returns response object for user consumption as JSON.
"""
import requests
import xmltodict

from requests import ConnectionError, HTTPError, RequestException, Timeout

from finone import db, app
from finone.constants import (
    AUTH_EMAIL, AUTH_ID, AUTH_LICENSEKEY, AUTH_NAME,
    PROPERTY_TYPE_MAP, LOAN_PURPOSE_MAP,
    PRODUCT_FIXED, PRODUCT_ARM,
    PRODUCT_5_ARM, PRODUCT_7_ARM, PRODUCT_15_FIXED, PRODUCT_30_FIXED,
    DEFAULT_TARGET_PRICE, DEFAULT_LOCKIN,
    ServiceConstants as sc)
from finone.factories import lender_factory, request_factory
from finone.utils import underscoreize
from sqlalchemy.exc import ProgrammingError

class ApiRequest(object):
    """
    Creates and formats a request to the service.
    """

    valid_args = ['state', 'county', 'loan_amount', 'zipcode',
                  'appraised_value', 'property_type', 'loan_purpose']

    def __init__(self, params):
        """
        Builds service request object.
        :param params: data from the submitted form
        """
        self.session = self.create_session()
        params = underscoreize(params)
        self.status_code = ''
        # TODO: Figure out what options would possibly be and where to use them
        self.options = {}
        for key, value in params.items():
            if key in self.valid_args:
                setattr(self, key, value)
            else:
                self.options.update({key: value})

    def _get_property_type(self):
        return PROPERTY_TYPE_MAP.get(self.options.get('property_type'))

    def _get_loan_purpose(self):
        return LOAN_PURPOSE_MAP.get(self.options.get('loan_purpose'))

    def build_request(self):
        return {
            sc.LICENSEKEY: AUTH_LICENSEKEY,
            sc.THIRD_PARTY_NAME: AUTH_NAME,
            sc.CUSTOMER_ID: AUTH_ID,
            sc.EMAIL_ADDRESS: AUTH_EMAIL,
            sc.REQUEST_ID: 1,
            sc.PROPERTY_STATE: self.state,
            sc.PROPERTY_COUNTY: self.county,
            sc.LOAN_AMOUNT: self.loan_amount,
            sc.PROPERTY_TYPE: self._get_property_type(),
            sc.LOAN_PURPOSE: self._get_loan_purpose(),
            sc.LOAN_PRODUCT1: PRODUCT_30_FIXED,
            sc.LOAN_PRODUCT2: PRODUCT_15_FIXED,
            sc.LOAN_PRODUCT3: PRODUCT_5_ARM,
            sc.LOAN_PRODUCT4: PRODUCT_7_ARM,
            sc.APPRAISED_VALUE: self.appraised_value,
            sc.TARGET_PRICE: DEFAULT_TARGET_PRICE,
            sc.LOCKIN_DAYS: DEFAULT_LOCKIN
        }

    @staticmethod
    def create_session():
        """Return an HTTP session."""
        session = requests.Session()
        return session

    def send_request(self):
        """Sends a request to mortech with data."""
        app.logger.info("Sending request...")
        # session = self.create_session()
        try:
            data = self.build_request()
            res = self.session.get(app.config['MORTECH_ENDPOINT'], params=data)
        except (HTTPError, ConnectionError, Timeout, RequestException, Exception) as exc:
            app.logger.exception("RQS-REQUEST-EXCEPTION: %s", exc)
            self.status_code = '500'
            raise
        else:
            app.logger.info("Request successful: {0}".format(res.status_code))
            self.status_code = res.status_code
            parser = ApiResponse(res.content, request_factory())
            return parser.get_results()

class ApiResponse(object):
    """
    Manages API responses from Mortech by:

    * Parsing response
    * Storing XML response
    * Storing parsed lenders to database

    Accepts and parses XML responses from the API.

    :param response: XML response from Mortech API
    :param request: An instance of :class:`Request`
    """

    def __init__(self, response, request):
        self.xml = response
        self.data = self.get_data()
        self.request = request

    def is_valid(self):
        return "results" in self.data['mortech']

    def parse(self, data):
        """
        Parses XML to dict. Returns process logs during process.
        To hide these dense logs, move the parsing function to a separate
        method.
        """
        if app.debug:
            self.save_xml()
        return xmltodict.parse(data)

    def get_data(self):
        """Parses elements of an XML document and returns a list of quotes."""
        return self.parse(self.xml)

    def result_count(self):
        count = 0
        for result in self.data['mortech']['results']:
            count += int(result['@size'])
        service.logger.info("Result count: %s", count)
        return count

    @staticmethod
    def _get_fees(fee_list):
        """Accepts list and returns dictionary of fees."""
        fees = {}
        for fee in fee_list:
            fees.update({
                fee.get('@description'): fee.get('@feeamount')
            })
        return fees

    @staticmethod
    def _get_amortization(obj):
        """Evaluates presence of intial arm tem to determine amortization."""
        if obj:
            return PRODUCT_ARM
        else:
            return PRODUCT_FIXED

    def _get_lenders(self):
        """Return a list of RateQuote instances."""
        lenders = []
        data = self.parse(self.xml)
        results = data['mortech']['results']
        app.logger.info(data.get('mortech').keys())

        for product in results:
            app.logger.info("==> BEGIN: Processing rate quotes for %s products ...",
                            product.get('@product_name'))
            for lender in product['quote']:
                lenders.append(lender_factory(lender))
            app.logger.info("==> END: Processing for %s", product.get('@product_name'))
        return lenders

    def bulk_store(self):
        # TODO: Move to ModelManager
        lenders = self._get_lenders()
        app.logger.info("==> BEGIN: Saving lenders ...")
        try:
            db.session.add_all(lenders)
            db.session.commit()
        except (ProgrammingError, Exception) as exc:
            app.logger.info("BULK STORE EXCEPTION: {}".format(exc))
            raise exc
        else:
            app.logger.info("==> END: %s Lenders saved successfully!", len(lenders))

    def save_xml(self):
        """Debug. Stores parsed data to tmp/data."""
        with open('response.xml', 'w+') as doc:
            doc.write(self.xml)

    def get_results(self):
        data = self.get_data()
        self.bulk_store()
        app.logger.info("RESULTS DATA: %s", dict(data['mortech']['header']))

        return to_list(data['mortech']['results'])

def to_list(data):
    # Move to Utils
    if not isinstance(data, list):
        return [data]


#!/usr/bin/env python
# coding: utf-8

# In[18]:

lista = [1, 2, 3, 15, 12, 10, 8]

# In[19]:

for numero in lista:
       if (numero % 2 == 0):
            print(numero)

# In[ ]:


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

# Learn more: https://github.com/kennethreitz/setup.py

from setuptools import setup

with open('README.md') as f:
    readme = f.read()

with open('LICENSE.md') as f:
    license = f.read()

setup(
    name='BERRYBEEF',
    version='0.1',
    description='Softbeef for Raspberry ..',
    long_description=readme,
    author='Valter Ferlete',
    author_email='ferlete@gmail.com',
    url='https://github.com/ferlete/BERRYBEEF',
    license=license,
    #packages=find_packages(exclude=('tests', 'docs'))
    packages=['BEEF'],
    #install_requires=['array-split==0.5.0',
    #      'markdown'
     # ],
    zip_safe=False, install_requires=['nipals'])


from os import urandom

SECRET_KEY = urandom(50)

PROPAGATE_ECEPTIONS = True

# Database Configuration

SQLALCHEMY_DATABASE_URI = 'sqlite:///crews.sqlite'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SHOW_SQLALCHEMY_LOG_MESSAGES = False

ERROR_404_HELP = False


import os
import random
import shutil

from django.views.decorators.csrf import csrf_exempt
from django.http import (
    HttpResponse,
    HttpResponseForbidden,
    HttpResponseServerError
)
from django.conf import settings

from license_protected_downloads.models import APIKeyStore, APILog
from license_protected_downloads.common import safe_path_join

def upload_target_path(path, key, public):
    """Quick path handling function.

    Checks that the generated path doesn't end up outside the target directory,
    so you can't set path to start with "/" and upload to anywhere.
    """
    if public:
        base_path = os.path.join(settings.SERVED_PATHS[0])
    else:
        base_path = os.path.join(settings.UPLOAD_PATH, key)
    return safe_path_join(base_path, path)

@csrf_exempt
def file_server_post(request, path):
    """ Handle post requests.

    All post requests must be accompanied by a valid key. If not, the upload
    will be ignored.

    Files are stored in a private directory that can not be accessed via the
    web interface unless you have the same key.
    """
    if not ("key" in request.POST and
            APIKeyStore.objects.filter(key=request.POST["key"])):
        APILog.mark(request, 'INVALID_KEY')
        return HttpResponseServerError("Invalid key")

    api_key = APIKeyStore.objects.get(key=request.POST["key"])

    if 'file' not in request.FILES or not path:
        APILog.mark(request, 'INVALID_ARGUMENTS', api_key)
        return HttpResponseServerError("Invalid call")

    APILog.mark(request, 'FILE_UPLOAD', api_key)

    path = upload_target_path(
        path, request.POST["key"], public=api_key.public)

    # Create directory if required
    dirname = os.path.dirname(path)
    if not os.path.isdir(dirname):
        os.makedirs(dirname)

    with open(path, "wb") as destination:
        for chunk in request.FILES["file"].chunks():
            destination.write(chunk)

    return HttpResponse("OK")

def api_request_key(request):
    APILog.mark(request, 'REQUEST_KEY')
    if("key" in request.GET and
       request.GET["key"] == settings.MASTER_API_KEY and
       settings.MASTER_API_KEY):

        # Generate a new, random key.
        key = "%030x" % random.randrange(256 ** 15)
        while APIKeyStore.objects.filter(key=key):
            key = "%030x" % random.randrange(256 ** 15)

        # Look for a hint of sanity in the value given to public, but don't
        # care about it too much.
        yes = ["", "y", "yes", "true", "1"]
        if "public" in request.GET:
            public = request.GET["public"].lower() in yes
        else:
            public = False

        api_key = APIKeyStore(key=key, public=public)
        api_key.save()
        return HttpResponse(key)

    return HttpResponseForbidden()

def api_delete_key(request):
    APILog.mark(request, 'DELETE_KEY')
    if "key" not in request.GET:
        return HttpResponseServerError("Invalid key")

    key = request.GET["key"]
    api_key = APIKeyStore.objects.filter(key=key)

    if not api_key:
        return HttpResponseServerError("Invalid key")

    # Delete key from database and all files associated with it
    api_key.delete()
    shutil.rmtree(os.path.join(settings.UPLOAD_PATH, key))

    return HttpResponse("OK")

def api_push_to_server(request):
    # TODO: Upload files from this machine to another linaro-licence-protection
    # node.
    """
    Something like:

    if request.GET["target"] in settings.REMOTE_SERVERS:
        remote_server = settings.REMOTE_SERVERS[request.GET["target"]]

        remote_server should contain:
        {
            "key": "...",
            "url": "...",
        }

        now just POST files from this machine to the specified URL/KEY.

        Possibly add some magic to POST endpoint (file_server_post) to allow
        (some users??) uploads to a public path:

        POST snapshots.linaro.org/path/to/file?key="key"&public=true

    """
    pass


import numpy as np
from utils.text_analyzer import TextStats
from utils.text_analyzer import compute_score
from utils.dictionary import Dictionary
from itertools import permutations as permutations

def crack_transposition(stats: TextStats, dictionary: Dictionary, verbose: bool=False):
    """
    Method to crack table transpositions. It assumes that ciphertext was obtained by writing plaintext to rows of given
    size and then read by columns. If there are empty spaces in the table, they are filled by fake letters. This cracker
    identifies the correct plaintext by counting identical letters at it's end, and by comparing it to the dictionary.
    All possible table sizes are evaluated, as it doesn't take much time and size detection function that was used to
    get one table size can be confused if the filler uses random characters instead of all Xs.
    :param stats: TextStats object of the text to be cracked
    :param dictionary: Dictionary constructed from the language of the plaintext
    :param verbose: True to print some outputs, eg other candidates for plaintext
    :return: plaintext, cipher name ("transposition_table"), parameters (table height)
    """
    solutions = []

    # this doesn't work all that well, and it is found later on anyway
    #    likely_size = guess_table_size(stats)
    # if likely_size:
    #    solution = read_from_table(stats, likely_size)
    #    language_score = compute_score(solution, dictionary)
    #    solutions.append((language_score, solution, "guessed"+str(likely_size)))

    # try all possible table dimensions
    for size in range(2, stats.N):
        # table size must be divisible by the dimensions
        if not stats.N % size:
            solution = read_from_table(stats, size)
            # how many characters repeat at the end of the plaintext
            tail_score = count_tailing_letters(solution)
            language_score = compute_score(solution, dictionary)
            solutions.append((tail_score, language_score, solution, "transposition_table", [size]))

    # sort by language, but use tail_score for primary sorting
    solutions.sort(key=lambda s: s[1], reverse=True)
    solutions.sort(key=lambda s: s[0], reverse=True)

    if verbose:
        for i in range(0, len(solutions)):
            print(solutions[i][0], solutions[i][3], solutions[i][2])

    return solutions[0][2], solutions[0][3], solutions[0][4]

def read_from_table(stats: TextStats, table_width: int):
    # take the string from stats, feed it to an array and then read it along different axis to get plaintext
    m = int(stats.N/table_width)
    f = np.array(list(stats.text))
    cipher_table = np.transpose(np.reshape(f, (m, table_width)))
    table = np.reshape(cipher_table, (1, stats.N)).tolist()
    return "".join(table[0])

def crack_transposition_with_column_scrambling(stats: TextStats, dictionary: Dictionary, verbose: bool=False):
    """
    Method to crack table transpositions with column shuffling. The cipher is the same as table transposition above, but
    the columns are shuffled before message is read. The method will try all permutations of columns for tables with 7
    or less columns. Larger tables are skipped, because it would take ages to compute.
    :param stats: TextStats object of the text to be cracked
    :param dictionary: Dictionary constructed from the language of the plaintext
    :param verbose: True to print some outputs, eg other candidates for plaintext
    :return: plaintext, cipher name ("transposition_table_shuffled"), parameters: [table height, permutation]
    """
    solutions = []
    for size in range(2, stats.N):
        if not stats.N % size:
            n_cols = int(stats.N / size)
            if n_cols > 7:
                if verbose:
                    print("Can't guess with table size", size, "- too many column permutations, skipping")
                continue
            from math import factorial
            if verbose:
                print(n_cols, factorial(n_cols))

            # prepare a table to be shuffled
            cipher_table = generate_table(stats, size)
            # create permutations of [0, 1, ..., n_cols]
            for permutation in permutations(list(range(0, n_cols))):
                # apply permutation and read message
                shuffled_table = cipher_table[:, permutation]
                table = np.reshape(shuffled_table, (1, stats.N)).tolist()
                solution = "".join(table[0])
                language_score = compute_score(solution, dictionary)
                solutions.append((language_score, solution, size, permutation))

    solutions.sort(key=lambda s: s[0], reverse=True)
    if verbose:
        for i in range(0, min(len(solutions), 50)):
            print(solutions[i][0], solutions[i][1], solutions[i][2], solutions[i][3])

    return solutions[0][1], "transposition_table_shuffled", [solutions[0][2], solutions[0][3]]

def generate_table(stats: TextStats, table_width: int):
    m = int(stats.N/table_width)
    f = np.array(list(stats.text))
    cipher_table = np.transpose(np.reshape(f, (m, table_width)))
    return cipher_table

def guess_table_size(text: TextStats, filler: int="X"):
    """
    Finds how often filler characters appear. This can be used to detect table size, but turned out to be useless.
    :param text: ciphertext
    :param filler: character to work with
    :return: Likely table size
    """
    last_filler_pos = 0
    distances = {}
    best_size = -1
    best_size_value = -1
    for i in range(0, text.N):
        c = text.text[i]
        if c == filler:
            distance = i - last_filler_pos
            if distance not in distances:
                distances[distance] = 1
            else:
                distances[distance] += 1
            last_filler_pos = i
            if distances[distance] > best_size_value:
                best_size = distance
                best_size_value = distances[distance]

    if text.N % best_size:
        return False
    return best_size

def count_tailing_letters(text: str):
    if len(text) == 0:
        return 0
    last_char = text[-1]
    i = 1
    for i in range(1, len(text)):
        if text[-i] != last_char:
            break
    return i-1


import logging
import subprocess as sp

import numpy as np

from t2v.config.root import RootConfig

class VideoInput:
    def __init__(self, cfg: RootConfig, video_path: str):
        """
        VideoInput reads frames from a given video file which can be used as init images for individual frame generation
        """
        command = ["ffmpeg",
                   '-i', video_path,
                   '-f', 'image2pipe',
                   '-pix_fmt', 'rgb24',
                   '-vcodec', 'rawvideo', '-']
        self.pipe = sp.Popen(command, stdout=sp.PIPE, bufsize=10 ** 8)
        w, h = get_vid_dims(video_path)
        if w != cfg.width or h != cfg.height:
            raise RuntimeError(f"Actual width {w} and height {h} of the video file {video_path} are not matching "
                               f"the scenario width {cfg.width} and height {cfg.height}. Crop the video or make sure the settings are correct.")
        self.fps = get_vid_fps(video_path)
        self.w = w
        self.h = h
        self.video_path = video_path

    def next_frame(self):
        raw_image = self.pipe.stdout.read(self.w * self.h * 3)
        # transform the byte read into a numpy array
        image = np.frombuffer(raw_image, dtype='uint8')
        image = image.reshape((self.h, self.w, 3))
        # throw away the data in the pipe's buffer.
        self.pipe.stdout.flush()
        return image

    def skip_frame(self, n=1):
        logging.info(f"Skipping {n} frames of video file {self.video_path}")
        for i in range(0, n):
            # scroll the stdin buffer
            self.pipe.stdout.read(self.w * self.h * 3)
            # throw away the data in the pipe's buffer.
            self.pipe.stdout.flush()

def get_vid_dims(video_path):
    """
    Returns width,height as tuple for a given video file.
    Requires ffprobe in PATH

    :param video_path: path to video file
    :return: w,h tuple
    """
    line = ffprobe_params(video_path, "width,height")
    w, h = line.split("x")
    return int(w), int(h)

def ffprobe_params(video_path, param):
    command = ["ffprobe",
               '-v', 'error',
               '-select_streams', 'v',
               '-show_entries', f'stream={param}',
               '-of', 'csv=p=0:s=x',
               video_path]
    pipe = sp.Popen(command, stdout=sp.PIPE, bufsize=10 ** 8)
    line = pipe.stdout.readline(1024).decode("utf-8")
    return line

def get_vid_fps(video_path):
    """
    Returns frame rate of a given video file.
    Requires ffprobe in PATH

    :param video_path: path to video file
    :return: fps number
    """
    line = ffprobe_params(video_path, "r_frame_rate")
    num, den = line.split("/")
    return int(num)/int(den)


# 더 효율적인 로직으로 풀어보기
from collections import defaultdict,deque; import copy
n, q = map(int, input().split())
n2 = 2**n
g = [ list(map(int,input().split())) for _ in range(n2)]
qrr = list( map(int, input().split()) )
visit = [ [False]*n2 for _ in range( n2)]

# 2L × 2L --> 회전 90도
dir = [(-1,0),(1,0),(0,-1),(0,1)]
summ = 0
group = 0

def play( sy, sx, sizee ):
    global g
    start_val = g[sy+sizee-1][sx]; end_val = g[sy][sx]
    y = sy; x = sx; nrr = [0]*sizee; srr = []; srr2 = []
    nrr[0] = g[sy+sizee-1][sx+sizee-1]
    if sx + sizee + 1 >= n2: srr2 = g[sy+sizee-1][sx:]; srr = g[sy][ sx : ]
    else:srr2 = g[sy+sizee-1][sx: sx + sizee ]; srr = g[sy][ sx : sx+sizee]
    for i in range(4):
        if i == 2 : y = sy+sizee-1; x = sx
        if i%2 == 0:# 시작이 가로인 경우
            ssy = sy+sizee-1; ssx = sx+sizee-1
            if i>0 : ssx = sx
            for j in range(sizee):
                nrr[j] = g[ ssy - j][ssx]
                if i == 0: g[ssy - j][ssx] = srr[ sizee-1-j]
                else: g[ssy - j][ssx] = srr2[ sizee-1-j]
        else: #시작이 세로인 경우 1 3
            if i == 3 : nrr[sizee-1] = end_val; nrr[0] = start_val
            ssx = sx; ssy = sy
            if i == 1 : ssy = sy + sizee-1
            for j in range(sizee) : g[ssy][ssx + j] = nrr[j]

def firestorm(sizee):
    for se in range(n2 //sizee):
        y = se * sizee
        for ga in range(n2 // sizee):
            x = ga*sizee
            sy = y; sx = x
            for i in range( sizee // 2): #8 -> 6
                play(sy,sx, sizee -2*i )
                sy += 1;  sx+= 1

for qq in qrr:
    firestorm( 2**qq )

    summ = 0
    before = copy.deepcopy(g)
    for i in range(n2):
        for j in range(n2):
            cnt = 0
            if before[i][j] == 0: continue
            for d in dir:
                ny, nx = i+d[0], j+d[1]
                if ny< 0 or ny>=n2 or nx<0 or nx>=n2 : continue
                if before[ny][nx]>0: cnt += 1
            if cnt < 3 : g[i][j] -= 1
            summ += g[i][j]

def bfs(i,j):
    global dir,visit
    q = deque(); q.append( (i, j) ) ; visit[i][j] = True; cnt = 1
    while q:
        y,x = q.popleft()
        for d in dir:
            ny, nx = y+d[0], x+d[1]
            if ny<0 or ny>=n2 or nx<0 or nx>=n2: continue
            if 0 < g[ny][nx] and visit[ny][nx] == False:
                cnt+=1; visit[ny][nx] = True; q.append((ny,nx))
    return 0 if cnt <= 1 else cnt

for i in range(n2):
    for j in range(n2):
        if visit[i][j] == False and g[i][j] > 0 : group = max(bfs(i, j), group)

print( summ )
print( group )

#남아있는 얼음 중 가장 큰 덩어리가 차지하는 칸의 개수

b20058_마법상어와파이어스톰.py


from typing import List
from collections import defaultdict, deque

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def verticalOrder(self, root: TreeNode) -> List[List[int]]:
        nodes = defaultdict(list)
        q = deque([(root, 0)])
        while len(q) > 0:
            node, col = q.popleft()
            if not node:
                continue
            nodes[col].append(node.val)
            q.append((node.left, col - 1))
            q.append((node.right, col + 1))

        return [nodes[x] for x in sorted(nodes.keys())]

Python/Binary Tree Vertical Order Traversal.py


import numpy
import numpy as np

def load_matrix(filename: str):
    matrix = []
    with open(filename, 'r') as matrix_file:
        for line in matrix_file:
            matrix.append([int(x) for x in line.split()])

    return matrix

def matrix_comparison(m1: np.ndarray, m2: np.ndarray):
    if (m1.shape[0] != m2.shape[0]) or (m1.shape[1] != m2.shape[1]):
        return False

    for i in range(m1.shape[0]):
        for j in range(m1.shape[1]):
            if not m1[i][j] == m2[i][j]:
                return False

    return True

if __name__ == "__main__":
    # c = 50
    # while c <= 1600:
    #     matrix_a = load_matrix(f'entire output/m{c}/a.txt')
    #     matrix_b = load_matrix(f'entire output/m{c}/b.txt')
    #     matrix_c = load_matrix(f'entire output/m{c}/c.txt')
    #     matrix_c_check = np.dot(np.asarray(matrix_a), np.asarray(matrix_b))
    #
    #     print(matrix_c[0][0])
    #     print(matrix_c_check[0][0])
    #     print("\n")
    #
    #     if not matrix_comparison(matrix_c_check, np.asarray(matrix_c)):
    #         print("FALSE")
    #     else:
    #         print("TRUE")
    #     c *= 2
    matrix_a = load_matrix(f'../a.txt')
    matrix_b = load_matrix(f'../b.txt')
    matrix_c = load_matrix(f'../result.txt')
    matrix_c_check = np.dot(matrix_a, matrix_b)
    print(matrix_c[0][0])
    print(matrix_c_check[0][0])
    print(matrix_comparison(matrix_c_check, np.asarray(matrix_c)))


import turtle
import random
import math
from tkinter.simpledialog import*

inStr=''
swidth,sheight=500,500
tX,tY,txtSize=[0]*3
val=0
r=1

turtle.title('거북이 나선형으로 글쓰기')
turtle.shape('turtle')
turtle.setup(width=swidth+50,height=sheight+50)
turtle.screensize(swidth,sheight)
turtle.penup()

inStr=askstring('문자열 입력','거북이 쓸 문자열을 입력')

for ch in inStr:
    tX=r*math.cos(math.pi*(val/180))
    tY=r*math.sin(math.pi*(val/180))
    r=random.random();g=random.random();b=random.random()
    txtSize=20

    turtle.goto(tX,tY)

    turtle.pencolor((r,g,b))
    turtle.write(ch,font=('맑은고딕',txtSize,'bold'))
    val+=30
    r+=30

turtle.done()


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

import asyncio
import gi
gi.require_version("GUPnP", "1.0")
from gi.repository import GUPnP
import urllib.request
import urllib.parse
from xml.etree.ElementTree import XML, XMLParser
from xmlutils import StripNamespace

from cameraremoteapi import CameraRemoteApi
# from utils import debug_trace

class CameraRemoteControl(object):

    def __init__(self, friendly_name, callback):
        self.__friendly_name = friendly_name
        self.__device_available_callback = callback

        ctx = GUPnP.Context.new(None, None, 0)
        # caution : keep cp as an attribute !
        self.cp = GUPnP.ControlPoint.new(ctx, "upnp:rootdevice")
        self.cp.set_active(True)
        self.cp.connect("device-proxy-available", self.__device_available)

    def __device_available(self, cp, proxy):
        proxy_friendly_name = proxy.get_friendly_name()
        # print("Found " + proxy_friendly_name)
        if proxy_friendly_name.startswith(self.__friendly_name):
            service = proxy.get_service("urn:schemas-sony-com:service:ScalarWebAPI:1")
            if service is not None:

                # browse the xml location file and search for the camera service
                # and set the action list uri
                location = proxy.get_location()
                xd = urllib.request.urlopen(location)
                s = xd.read()

                target = StripNamespace()
                parser = XMLParser(target=target)
                root = XML(s, parser=parser)

                sl = root.findall("device/X_ScalarWebAPI_DeviceInfo/X_ScalarWebAPI_ServiceList/X_ScalarWebAPI_Service")
                for s in sl:
                    service_type = s.find("X_ScalarWebAPI_ServiceType").text
                    if service_type == CameraRemoteApi.SERVICE_NAME:
                        camera_action_list = s.find("X_ScalarWebAPI_ActionList_URL").text
                        if not camera_action_list.endswith('/'):
                            camera_action_list += '/'
                        endpoint_url = urllib.parse.urljoin(camera_action_list, CameraRemoteApi.SERVICE_NAME)
                        asyncio.ensure_future(self.__device_available_callback(proxy_friendly_name, endpoint_url))
                        break


# -*- coding: utf-8 -*-
import config
import telebot
from room import Room
from functools import partial
from random import shuffle

bot = telebot.TeleBot(config.token)
imagi_room = Room

@bot.message_handler(commands=['start'])
def start(message):
    # kb = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    # kb.add('Новая игровая', 'Выбрать существующую игровую')
    text = '\n'.join(['/1 Новая игровая', '/2 Выбрать существующую игровую'])
    selected = bot.send_message(message.chat.id, text=text)
    bot.register_next_step_handler(selected, get_select)

def get_select(message):
    if message.text == '/1':
        new_room(message)
    elif message.text == '/2':
        choosing_room(message)
    else:
        start(message)

def new_room(message):
    imagi_room.new(chat_id=message.chat.id)
    photo = bot.send_message(message.chat.id, 'Отправьте фото с подписью')
    bot.register_next_step_handler(photo, add_master_photo)

def choosing_room(message):
    try:
        rooms = []
        for room_id in imagi_room.get_room_ids():
            room = imagi_room.get_room_by_id(room_id)
            if room['status'] == 'wait':
                rooms.append(' '.join(['/' + str(room_id), room['master_name']]))
        if not rooms:
            bot.send_message(message.chat.id, text='Нет игровых /start')
        rooms_str = '\n'.join(rooms)
        message = bot.send_message(message.chat.id, text=rooms_str)
        bot.register_next_step_handler(message, room_selected)
    except Exception as e:
        print(e)

def room_selected(message):
    try:
        room_id = int(message.text.strip('/'))
        room = imagi_room.get_room_by_id(room_id)
        photo_mess = bot.send_message(message.chat.id, text='Отправьте фото ассоциирующееся с "{}"'.format(room['img_mess']))
        bot.register_next_step_handler(photo_mess, partial(add_player_photo, room_id))
    except Exception as e:
        raise e

def add_master_photo(message):
    if message.content_type != 'photo':
        bot.send_message(message.chat.id, 'Это не фото!')
        new_room(message)

    elif not message.caption or not message.caption.strip():
        bot.send_message(message.chat.id, 'Подпись та забыли!')
        new_room(message)

    else:
        user_name = ' '.join([message.chat.first_name, message.chat.last_name])
        imagi_room.add_master_photo(message.chat.id,
                                    message.photo[-1].file_id,
                                    message.caption,
                                    user_name
                                    )
        bot.send_message(message.chat.id, text='Ваша игровая создана')

def add_player_photo(room_id, message):
    if message.content_type == 'photo':
        user_name = ' '.join([message.chat.first_name, message.chat.last_name])
        imagi_room.add_player(room_id, message.chat.id, user_name, message.photo[-1].file_id)
        if len(imagi_room.get_room_by_id(room_id)['players']) > 0:
            in_game(room_id, user_name)

    else:
        bot.send_message(message.chat.id, 'Это не фото!')
        message.text = str(room_id)
        room_selected(message)

def in_game(room_id, user_name):
    room = imagi_room.get_room_by_id(room_id)
    message = bot.send_message(room_id,
                               text='В Вашу игровую зашел {}. Всего в игровой {} игроков. Начать игру?/{}'
                               .format(user_name, len(room['players']), room_id))
    stat = 'Игра началась'
    bot.register_next_step_handler(message, partial(run_game, room_id, stat))

def run_game(room_id, stat, message):
    if message.text.strip('/') == str(room_id):
        imagi_room.change_status(room_id, 'in_game')
        room = imagi_room.get_room_by_id(room_id)
        photo_ids = [room['master_photo_id']] + [room['players'][player_id]['photo_id'] for player_id in list(room['players'])]
        shuffle(photo_ids)
        for chat_id in list(room['players']):
            bot.send_message(chat_id, text=stat)
            for i, photo_id in enumerate(photo_ids):
                bot.send_photo(chat_id, photo=photo_id, caption='/{}'.format(i), )
        bot.register_next_step_handler(message, partial(check, room_id, photo_ids))

def check(room_id, photo_ids, message):
    room = imagi_room.get_room_by_id(room_id)
    if message.text.strip('/') in [str(i) for i, _ in enumerate(photo_ids)]:
        photo_id = photo_ids[int(message.text.strip('/'))]
        if room['master_photo_id'] == photo_id:
            bot.send_message(message.chat.id, text='Правильно! Молодец!')
        else:
            bot.send_message(message.chat.id, text='Не угадал')
            bot.send_photo(message.chat.id, photo=room['master_photo_id'], caption='Верная картинка')
    else:
        message.text = str(room_id)
        stat = 'Выберите фото'
        bot.register_next_step_handler(message, partial(run_game, room_id, stat))

if __name__ == '__main__':
    bot.polling(none_stop=True)


# coding:utf-8

from Tkinter import *

root = Tk()
root.title("Entry")
root.minsize(400, 300)

e=Entry(root)
e.pack(padx=20,pady=20)

e.delete(0, END)
e.insert(0, "默认文本....")

mainloop()


import glob
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

def plot_figure(data, x, y, filename, figsize=(24, 9), log_scale=False):
    sns.set(font_scale=1.5)
    plt.style.use("seaborn-poster")

    fig, ax = plt.subplots(figsize=figsize, dpi=300)
    g = sns.barplot(x=x, y=y, hue="Method", data=data, errwidth=2, ax=ax, palette=colors)
    if log_scale:
        g.set_yscale("log")
    plt.legend(loc='upper left', bbox_to_anchor=(1.0, 1.0))
    plt.tight_layout()
    plt.savefig(f"./bandits/figures/{filename}.png")
    plt.show()

def read_data(dataset_name):
    *_, filename = sorted(glob.glob(f"./bandits/results/{dataset_name}_results*.csv"))
    df = pd.read_csv(filename)
    if dataset_name=="mnist":
        linear_df = df[(df["Method"]=="Lin-KF") | (df["Method"]=="Lin")].copy()
        linear_df["Model"] = "MLP2"
        df = df.append(linear_df)
        linear_df["Model"] = "LeNet5"
        df = df.append(linear_df)

    by = ["Rank"] if dataset_name=="tabular" else ["Rank", "AltRank"]

    data_up = df.sort_values(by=by).copy()
    data_down = df.sort_values(by=by).copy()

    data_up["Reward"] = data_up["Reward"] + data_up["Std"]
    data_down["Reward"] = data_down["Reward"] - data_down["Std"]
    data = pd.concat([data_up, data_down])
    return data

def plot_subspace_figure(df, filename=None):
    df = df.reset_index().drop(columns=["index"])
    plt.style.use("seaborn-darkgrid")
    fig, ax = plt.subplots(figsize=(12, 8))
    sns.lineplot(x="Subspace Dim", y="Reward", hue="Method", marker="o", data=df)
    lines, labels = ax.get_legend_handles_labels()
    for line, method in zip(lines, labels):
        data = df[df["Method"]==method]
        color = line.get_c()
        y_lower_bound =  data["Reward"] -  data["Std"]
        y_upper_bound = data["Reward"] + data["Std"]
        ax.fill_between(data["Subspace Dim"],  y_lower_bound, y_upper_bound, color=color, alpha=0.3)

    ax.set_ylabel("Reward", fontsize=16)
    plt.setp(ax.get_xticklabels(), fontsize=16)
    plt.setp(ax.get_yticklabels(), fontsize=16)
    ax.set_xlabel("Subspace Dimension(d)", fontsize=16)
    dataset = df.iloc[0]["Dataset"]
    ax.set_title(f"{dataset.title()} - Subspace Dim vs. Reward", fontsize=18)
    legend = ax.legend(loc="lower right", prop={'size': 16},frameon=1)
    frame = legend.get_frame()
    frame.set_color('white')
    frame.set_alpha(0.6)

    file_path = "./bandits/figures/"
    file_path = file_path + f"{dataset}_sub_reward.png" if filename is None else file_path + f"{filename}.png"
    plt.savefig(file_path)

method_ordering = {"EKF-Sub-SVD": 0,
                   "EKF-Sub-RND": 1,
                   "EKF-Sub-Diag-SVD": 2,
                   "EKF-Sub-Diag-RND": 3,
                   "EKF-Orig-Full": 4,
                   "EKF-Orig-Diag": 5,
                   "NL-Lim": 6,
                   "NL-Unlim": 7,
                   "Lin": 8,
                   "Lin-KF": 9,
                   "Lin-Wide": 9,
                   "Lim2": 10,
                   "NeuralTS": 11}

colors = {k : sns.color_palette("Paired")[v]
          if k!="Lin-KF" else  sns.color_palette("tab20")[8]
          for k,v in method_ordering.items()}

dataset_info = {
    "mnist": {
        "elements": ["EKF-Sub-SVD", "EKF-Sub-RND", "EKF-Sub-Diag-SVD",
                    "EKF-Sub-Diag-RND", "EKF-Orig-Diag", "NL-Lim",
                    "NL-Unlim", "Lin"],
        "x": "Model",
    },

    "tabular": {
        "elements": ["EKF-Sub-SVD", "EKF-Sub-RND", "EKF-Sub-Diag-SVD",
                    "EKF-Sub-Diag-RND", "EKF-Orig-Diag", "NL-Lim",
                    "NL-Unlim", "Lin"],
        "x": "Dataset"
    },

    "movielens": {
        "elements": ["EKF-Sub-SVD", "EKF-Sub-RND", "EKF-Sub-Diag-SVD",
                    "EKF-Sub-Diag-RND", "EKF-Orig-Diag", "NL-Lim",
                    "NL-Unlim", "Lin"],
        "x": "Model"
        },
}

plot_configs = [
    {"metric": "Reward", "log_scale":False},
    {"metric": "Time", "log_scale":True},

]

def main():
    # Create reward / runnnig time experiments
    print("Plotting reward / running time")
    for dataset_name in dataset_info:
        print(dataset_name)
        info = dataset_info[dataset_name]
        methods = info["elements"]
        x = info["x"]

        df = read_data(dataset_name)
        df = df[df["Method"].isin(methods)]

        for config in plot_configs:
            metric = config["metric"]
            use_log_scale = config["log_scale"]

            filename = f"{dataset_name}_{metric.lower()}"
            plot_figure(df, x, metric, filename, log_scale=use_log_scale)

    # Plot subspace-dim v.s. reward
    print("Plotting subspace dim v.s. reward")
    *_, filename = sorted(glob.glob(f"./bandits/results/tabular_subspace_results*.csv"))
    tabular_sub_df = pd.read_csv(filename)

    datasets = ["shuttle", "adult", "covertype"]
    for dataset_name in datasets:
        print(dataset_name)
        subdf = tabular_sub_df.query("Dataset == @dataset_name")
        plot_subspace_figure(subdf)

if __name__ == "__main__":
    main()


from typing import Optional

from fastapi import APIRouter, Form

from Deployment.ConsumerServices.GeneralService import DownloadImageFromURLServiceTask, ParseImageFromBase64ServiceTask
from Deployment.ConsumerServices.RecaptchaService import Captcha1RecognizeServiceTask
from Deployment.server_config import IS_MOCK
from Utils.DAG import DAG
from Utils.Exceptions import InputParameterAbsentException, InputParameterAbnormalException
from Utils.InterfaceUtils import base_interface_result_decorator, DictInterfaceResult

router = APIRouter()

@router.post('/captcha1_recognize')
@base_interface_result_decorator()
async def general_ocr(
        image_url: Optional[str] = Form(None),
        image_base64: Optional[str] = Form(None),
):
    dag = DAG()
    # 如果mock数据过长，可以写在其他文件，然后这边引用
    mock_result = {
        'text': '',
    }
    with DictInterfaceResult(mock_result) as to_return_result:
        if IS_MOCK:
            return to_return_result
        if not (image_url or image_base64):
            raise InputParameterAbsentException('至少有一个参数image_url或者image_base64')
        if image_url and image_base64:
            raise InputParameterAbnormalException('只能有一个image_url或者image_base64')
        if image_url:
            download_image_task = DownloadImageFromURLServiceTask(_dag=dag)
            download_image_task.add_dependency_from_value('_image_url', image_url)
            image_info = (await download_image_task).service_result['image_info']
        elif image_base64:
            decode_image_task = ParseImageFromBase64ServiceTask(_dag=dag)
            decode_image_task.add_dependency_from_value('_base64_string', image_base64)
            image_info = (await decode_image_task).service_result['image_info']
        captcha1_recognize_task = Captcha1RecognizeServiceTask(_dag=dag)
        captcha1_recognize_task.add_dependency_from_value('_image_info', image_info)
        recognize_result = (await captcha1_recognize_task).service_result['text']
        to_return_result.add_sub_result('text', recognize_result)
        return to_return_result


# -*- coding: utf-8 -*-
# @Author: solicucu

import sys
sys.path.append('..')
import os
import argparse
import logging
import time
import openpyxl as xl
import torch
import torch.nn as nn

from config import cfg
from torch.backends import cudnn
from utils import setup_logger, R1_mAP
from data import make_data_loader
from model import build_model, CDNetwork, CNetwork
from optims import make_optimizer, make_lr_scheduler, make_loss
from utils.utils import count_parameters, infer_count_parameters
from utils.metrics import *
from utils.flop_benchmark import get_model_infos

"""
Args:
	res: a list of elem like [scores, feats]
	labels: ground truth of the imgs class
	loss_fn: type of loss function to compute the loss
Returns:
	loss: summation of each loss
	acc: avg of each loss
"""
def compute_loss_acc(res, labels, loss_fn):

	loss, acc = 0. , 0.
	num = len(res)

	for scores, feats in res:
		ls = loss_fn(scores, feats, labels)
		loss += ls

		ac = (scores.max(1)[1] == labels).float().mean()
		acc += ac

	return loss, acc / num

def parse_config():

	# create the parser
	parser = argparse.ArgumentParser(description = "CDNet training")

	parser.add_argument("--config_file", default = '', help = "path to specify config file", type = str)

	#remainder parameters in a list
	parser.add_argument("opts", default = None, help = 'modify some value for the config file in command line', nargs = argparse.REMAINDER)

	args = parser.parse_args()

	if args.config_file != "":
		# use config file to update the default config value
		cfg.merge_from_file(args.config_file)
	# note that opts is a list
	cfg.merge_from_list(args.opts)
	# cfg.freeze() if use this, the cfg can not be revised

	output_dir = cfg.OUTPUT.DIRS
	if output_dir != "":
		if not os.path.exists(output_dir):
			os.makedirs(output_dir)
	else:
		print("ERROR:please specify an output path")
		exit(1)

	# config the logger
	logger = setup_logger("CDNet", output_dir, 0, cfg.OUTPUT.LOG_NAME)

	use_gpu = cfg.MODEL.DEVICE == "cuda"
	if use_gpu:
		logger.info("Train with GPU: {}".format(cfg.MODEL.DEVICE_IDS))
	else:
		logger.info("Train with CPU")

	#print the all arguments
	logger.info(args)
	#read the config file
	if args.config_file != "":
		logger.info("load configuration file {}".format(args.config_file))

	# print the configuration
	logger.info("running with config:\n{}".format(cfg))

	if use_gpu:
		os.environ["CUDA_VISIBLE_DEVICES"] = cfg.MODEL.DEVICE_IDS

	#this setup will facilitate the training
	cudnn.benchmark = True

def train():

	# 1、make dataloader
	# prepare train,val img_info list, elem is tuple;
	train_loader, val_loader, num_query, num_class = make_data_loader(cfg)

	# 2、make model
	model = build_model(cfg, num_class)

	# 3、 make optimizer
	optimizer = make_optimizer(cfg, model)

	# 4、 make lr_scheduler
	scheduler = make_lr_scheduler(cfg, optimizer)

	# 5、make loss
	loss_fn = make_loss(cfg, num_class)

	# get parameters
	device = cfg.MODEL.DEVICE
	use_gpu = device == "cuda"
	pretrained = cfg.MODEL.PRETRAIN_PATH != ""
	parallel = cfg.MODEL.PARALLEL

	log_period = cfg.OUTPUT.LOG_PERIOD
	ckpt_period = cfg.OUTPUT.CKPT_PERIOD
	eval_period = cfg.OUTPUT.EVAL_PERIOD
	output_dir = cfg.OUTPUT.DIRS
	ckpt_save_path = output_dir + cfg.OUTPUT.CKPT_DIRS

	epochs = cfg.SOLVER.MAX_EPOCHS
	batch_size = cfg.SOLVER.BATCH_SIZE
	grad_clip = cfg.SOLVER.GRAD_CLIP

	batch_num = len(train_loader)
	log_iters = batch_num // log_period

	if not os.path.exists(ckpt_save_path):
		os.makedirs(ckpt_save_path)

	# create *_result.xlsx
	# save the result for analyze
	name = (cfg.OUTPUT.LOG_NAME).split(".")[0] + ".xlsx"
	result_path = cfg.OUTPUT.DIRS + name

	wb = xl.Workbook()
	sheet = wb.worksheets[0]
	titles = ['size/M','speed/ms','final_planes', 'acc', 'mAP', 'r1', 'r5', 'r10', 'loss',
			  'acc', 'mAP', 'r1', 'r5', 'r10', 'loss','acc', 'mAP', 'r1', 'r5', 'r10', 'loss']
	sheet.append(titles)
	check_epochs = [40, 80, 120, 160, 200, 240, 280, 320, 360, epochs]
	values = []

	logger = logging.getLogger("CDNet.train")
	size = count_parameters(model)
	values.append(format(size, '.2f'))
	values.append(model.final_planes)

	logger.info("the param number of the model is {:.2f} M".format(size))
	infer_size = infer_count_parameters(model)
	logger.info("the infer param number of the model is {:.2f}M".format(infer_size))

	shape = [1, 3]
	shape.extend(cfg.DATA.IMAGE_SIZE)

	# if cfg.MODEL.NAME == 'cdnet' :
	# 	infer_model = CDNetwork(num_class, cfg)
	# elif cfg.MODEL.NAME == 'cnet':
	# 	infer_model = CNetwork(num_class, cfg)
	# else:
	# 	infer_model = model

	# for scaling experiment
	flops, _ = get_model_infos(model, shape)
	logger.info("the total flops number of the model is {:.2f} M".format(flops))

	logger.info("Starting Training CDNetwork")

	best_mAP, best_r1 = 0., 0.
	is_best = False
	avg_loss, avg_acc = RunningAverageMeter(),RunningAverageMeter()
	avg_time, global_avg_time = AverageMeter(), AverageMeter()

	if parallel:
		model = nn.DataParallel(model)

	if use_gpu:
		model = model.to(device)

	for epoch in range(epochs):

		scheduler.step()
		lr = scheduler.get_lr()[0]
		# if save epoch_num k, then run k+1 epoch next
		if pretrained and epoch < model.start_epoch:
			continue

		# rest the record
		model.train()
		avg_loss.reset()
		avg_acc.reset()
		avg_time.reset()

		for i, batch in enumerate(train_loader):

			t0 = time.time()
			imgs, labels = batch

			if use_gpu:
				imgs = imgs.to(device)
				labels = labels.to(device)

			res = model(imgs)

			loss, acc = compute_loss_acc(res, labels, loss_fn)
			loss.backward()

			if grad_clip != 0:
				nn.utils.clip_grad_norm_(model.parameters(), grad_clip)

			optimizer.step()
			optimizer.zero_grad()

			t1 = time.time()
			avg_time.update((t1 - t0) / batch_size)
			avg_loss.update(loss)
			avg_acc.update(acc)

			# log info
			if (i+1) % log_iters == 0:
				logger.info("epoch {}: {}/{} with loss is {:.5f} and acc is {:.3f}".format(
					epoch+1, i+1, batch_num, avg_loss.avg, avg_acc.avg))

		logger.info("end epochs {}/{} with lr: {:.5f} and avg_time is: {:.3f} ms".format(epoch+1, epochs, lr, avg_time.avg * 1000))
		global_avg_time.update(avg_time.avg)

		# test the model
		if (epoch + 1) % eval_period == 0 or (epoch + 1) in check_epochs:

			model.eval()
			metrics = R1_mAP(num_query, use_gpu = use_gpu)

			with torch.no_grad():
				for vi, batch in enumerate(val_loader):

					imgs, labels, camids = batch
					if use_gpu:
						imgs = imgs.to(device)

					feats = model(imgs)
					metrics.update((feats, labels, camids))

				#compute cmc and mAP
				cmc, mAP = metrics.compute()
				logger.info("validation results at epoch {}".format(epoch + 1))
				logger.info("mAP:{:2%}".format(mAP))
				for r in [1,5,10]:
					logger.info("CMC curve, Rank-{:<3}:{:.2%}".format(r, cmc[r-1]))

				# determine whether current model is the best
				if mAP > best_mAP:
					is_best = True
					best_mAP = mAP
					logger.info("Get a new best mAP")
				if cmc[0] > best_r1:
					is_best = True
					best_r1 = cmc[0]
					logger.info("Get a new best r1")

				# add the result to sheet
				if (epoch + 1) in check_epochs:
					val = [avg_acc.avg, mAP, cmc[0], cmc[4], cmc[9]]
					change = [format(v * 100, '.2f') for v in val]
					change.append(format(avg_loss.avg, '.3f'))
					values.extend(change)

		# whether to save the model
		if (epoch + 1) % ckpt_period == 0 or is_best:
			torch.save(model.state_dict(), ckpt_save_path + "checkpoint_{}.pth".format(epoch + 1))
			logger.info("checkpoint {} was saved".format(epoch + 1))

			if is_best:
				torch.save(model.state_dict(), ckpt_save_path + "best_ckpt.pth")
				logger.info("best_checkpoint was saved")
				is_best = False

	values.insert(1, format(global_avg_time.avg * 1000, '.2f'))
	values.append(format(infer_size, '.2f'))
	sheet.append(values)
	wb.save(result_path)
	logger.info("best_mAP:{:.2%}, best_r1:{:.2%}".format(best_mAP, best_r1))
	logger.info("Ending training CDNetwork")

def main():

	parse_config()
	train()

if __name__ == "__main__":

	main()


import sys
import datetime

configFile = open(sys.argv[1], 'r')
symbolList = []

for line in configFile:
    symbol = line.split(';', 1)
    symbol[1] = symbol[1][:-1] #remove trailing \n
    symbol[0] = symbol[0].replace('\\n', '\n'); #remove escaping \\n
    symbol[1] = symbol[1].replace('\\n', '\n'); #remove escaping \\n
    symbolList.append(symbol)

XMONTH = datetime.datetime.now().strftime("%m")
XYEAR = datetime.datetime.now().strftime("%Y")
XNUMBER = 0

for line in sys.stdin:
    for symbol in symbolList:
        line = line.replace(symbol[0], symbol[1])

    line = line.replace("XMONTH", XMONTH)
    line = line.replace("XYEAR", XYEAR)
    if (line.find("XNUMBER") != -1):
        line = line.replace("XNUMBER", str(XNUMBER))
        XNUMBER = XNUMBER + 1

    sys.stdout.write(line)


import time
import RPi.GPIO as GPIO
# import torch
# import torchvision.transforms as transforms

import math
from src.rmd_x8 import RMD_X8
# from rmd_x8 import RMD_X8
import time
from huskylib import HuskyLensLibrary
import math
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN)

GPIO.setup(26, GPIO.OUT)

GPIO.setup(19, GPIO.OUT)

# GPIO.setwarnings(False)

pwm = GPIO.PWM(26, 100)
pwm.start(0)

pwm2 = GPIO.PWM(19, 100)
pwm2.start(0)

GPIO.setup(13, GPIO.IN) #learn
GPIO.setup(6, GPIO.IN) #forget
GPIO.setup(5, GPIO.IN) #shoot
GPIO.setup(21, GPIO.IN) #stop

# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_v3_large", device).to(device)
#
# # Define image transforms
# midas_transforms = transforms.Compose(
#     [
#         transforms.Resize(256),
#         transforms.CenterCrop(256),
#         transforms.ToTensor(),
#         transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
#     ]
# )

# robot = RMD_X8(0x141)
# robot.setup()
FRAME_W = 320
FRAME_H = 240
cam_pan = 90

hl = HuskyLensLibrary("I2C", "", address=0x32)

def printObjectNicely(obj):
    count = 1
    if (type(obj) == list):
        for i in obj:
            print("\t " + ("BLOCK_" if i.type == "BLOCK" else "ARROW_") + str(count) + " : " + json.dumps(i.__dict__))
            count += 1
    else:
        print("\t " + ("BLOCK_" if obj.type == "BLOCK" else "ARROW_") + str(count) + " : " + json.dumps(obj.__dict__))

# pwm.stop()

# def set_duty_cycle(distance):
#     # Map the distance to a duty cycle
#     duty_cycle = (distance / 10) + 5
#     pwm.ChangeDutyCycle(duty_cycle)

# while True:
#     absoluteduty_cycle = 100
#     actual_duty_cycle = 45
#     max_duty_cycle = actual_duty_cycle * 0.45
#     min_duty_cycle = actual_duty_cycle * 0.3
#
#     pwm.ChangeDutyCycle(actual_duty_cycle)
#     time.sleep(0.1)
#     voltage = (actual_duty_cycle / 100) * (4.5 - 0.3) + 0.3
#     print(voltage)

# GPIO.cleanup()

def printObjectNicely(obj):
    count = 1
    if (type(obj) == list):
        for i in obj:
            print("\t " + ("BLOCK_" if i.type == "BLOCK" else "ARROW_") + str(count) + " : " + json.dumps(i.__dict__))
            count += 1
    else:
        print("\t " + ("BLOCK_" if obj.type == "BLOCK" else "ARROW_") + str(count) + " : " + json.dumps(obj.__dict__))

def set_duty_cycle(distance):
    # Map the distance to a duty cycle
    # duty_cycle = ((distance / 10) + 20)
    duty_cycle = float(distance) / float(320 * 240) * 30000
    # duty_cycle = float(distance) / float(320 * 240) * 90000

    voltage = (duty_cycle / 100) * (10 - 0.3) + 0.3
    # duty =

    pwm.ChangeDutyCycle(duty_cycle)
    return duty_cycle,voltage

def calculate_distance(width, height):

    # Camera parameters

    distance =   math.sqrt(width ** 2 + height ** 2)
    print(distance)
    # distance = (FRAME_H * focal_length) / FRAME_W

    return distance

# def calculate_Distance_Pro(x, y, width, height, camera_height, image):
#     x1 = x
#     y1 = y
#     x2 = x + width
#     y2 = y + height
#
#     cropped_image = image[y1:y2, x1:x2]
#
#     # Apply transforms to the cropped image
#     input_tensor = midas_transforms(cropped_image).unsqueeze(0).to(device)
#
#     # Run the image through the MiDaS model
#     with torch.no_grad():
#         depth_map = midas(input_tensor)
#
#     # Calculate the distance from the depth map
#     distance = camera_height * 0.1 / depth_map[0, 0, height // 2, width // 2]
#
#     return distance

# Example usage
# camera_height = 2.0 # meters
# x, y, width, height = hl.blocks().x, hl.blocks().y, hl.blocks().w, hl.blocks().h
# image = hl.image()
# distance = calculate_distance(x, y, width, height, camera_height, image)

#
# while True:
#     try:
#         if (hl.learnedObjCount() > 0):
#             wData = hl.blocks().width
#             hData = hl.blocks().height
#
#
#             calculate_distance(wData,hData)
#     except:
#         print("Target Lost!")

# print("jhio")
#GPIO.setup(13, GPIO.IN) #learn
# GPIO.setup(6, GPIO.IN) #forget
# GPIO.setup(5, GPIO.IN) #shoot
# GPIO.setup(21, GPIO.IN) #stop
while True:
    try:

        if hl.learnedObjCount() > 0:
            w = hl.blocks().width
            h = hl.blocks().height
            distance = 120 - calculate_distance(w, h)

            # print(hl.blocks())
            # print(hl.blocks().width)
            # w = hl.blocks().width
            # h = hl.blocks().height
            # distance = 120 - calculate_distance(w,h)
            # distance = 60

            print("Detected Distance:",distance,'duty_cycle&voltage',set_duty_cycle(distance))
            set_duty_cycle(distance)
            if (GPIO.input(17) == True):
                print("Ball Detected!")
                pwm2.ChangeDutyCycle(100)
            else:
                pwm2.ChangeDutyCycle(0)
        else:
            print('lost')
            pwm2.ChangeDutyCycle(0)

            set_duty_cycle(0)
            # pwm.ChangeDutyCycle(30)

            # set_duty_cycle(distance)
            # print(set_duty_cycle(distance))

            # absolute_duty_cycle = 100
            # actual_duty_cycle = absolute_duty_cycle * 0.45
            # max_duty_cycle = absolute_duty_cycle * 0.45
            # min_duty_cycle = absolute_duty_cycle * 0.3
            #
            # if (GPIO.input(17) == True):
            #     print("Ball Detected!")
            #     pwm2.ChangeDutyCycle(100)
            #
            #     actual_duty_cycle = 60
            #     actual_duty_cycle = actual_duty_cycle * 0.45
            #
            #
            #
            #
            #     # pwm.ChangeDutyCycle(actual_duty_cycle)
            #     time.sleep(0.1)
            #     voltage = (actual_duty_cycle / 100) * (10 - 0.3) + 0.3
            #     print('current V:',voltage)
            # else:
            #     print("STOP!!!!")
            #     pwm2.ChangeDutyCycle(0)
            #
            #     actual_duty_cycle = 0
            #     pwm.ChangeDutyCycle(actual_duty_cycle)
    except:
        print("Target Lost")
        set_duty_cycle(0)
        pwm2.ChangeDutyCycle(0)

        None

        # print(hl.blocks().width)

        # print('hi')
    # try:
        # print("here")
        # printObjectNicely(hl)
        # w = hl.blocks().width
        # h = hl.blocks().height
        # if (hl.learnedObjCount() > 0):
        #
        #
        # # if (hl.learnedObjCount() > 0):
        #     distance = calculate_distance(calculate_distance(w,h))
        #     print('distance:',distance)
        # absolute_duty_cycle = 100
        # actual_duty_cycle = absolute_duty_cycle * 0.45
        # max_duty_cycle = absolute_duty_cycle * 0.45
        # min_duty_cycle = absolute_duty_cycle * 0.3
        #
        # if (GPIO.input(17) == False):
        #     print("Running Detected!")
        #     pwm2.ChangeDutyCycle(100)
        #
        #     actual_duty_cycle = 60
        #     actual_duty_cycle = actual_duty_cycle * 0.45
        #
        #
        #
        #
        #     pwm.ChangeDutyCycle(actual_duty_cycle)
        #     time.sleep(0.1)
        #     voltage = (actual_duty_cycle / 100) * (10 - 0.3) + 0.3
        #     print('current V:',voltage)
        # else:
        #     print("STOP!!!!")
        #     pwm2.ChangeDutyCycle(0)
        #
        #     actual_duty_cycle = 0
        #     pwm.ChangeDutyCycle(actual_duty_cycle)

    # except:
    #     None

# while(True):
#     try:
#
#
#         w = hl.blocks().width
#         h = hl.blocks().height
#         print('pass')
#         # if (hl.learnedObjCount() > 0):
#         #     distance = calculate_distance(calculate_distance(w,h))
#         #     print('distance:',distance)
#         #     absolute_duty_cycle = 100
#         #     actual_duty_cycle = absolute_duty_cycle * 0.45
#         #     max_duty_cycle = absolute_duty_cycle * 0.45
#         #     min_duty_cycle = absolute_duty_cycle * 0.3
#         #
#         #     if (GPIO.input(17) == True):
#         #         print("Running Detected!")
#         #         pwm2.ChangeDutyCycle(100)
#         #
#         #         actual_duty_cycle = 60
#         #         actual_duty_cycle = actual_duty_cycle * 0.45
#         #
#         #
#         #
#         #
#         #         pwm.ChangeDutyCycle(actual_duty_cycle)
#         #         time.sleep(0.1)
#         #         voltage = (actual_duty_cycle / 100) * (10 - 0.3) + 0.3
#         #         print('current V:',voltage)
#         #     else:
#         #         print("STOP!!!!")
#         #         pwm2.ChangeDutyCycle(0)
#         #
#         #         actual_duty_cycle = 0
#         #         pwm.ChangeDutyCycle(actual_duty_cycle)
#         # if(hl.learnedObjCount() == 0):
#         #     print("Nothing")
#
#
#     except:
#         # None
#         # print('Here')
#         pwm.stop()
#         GPIO.cleanup()


import logging
import numpy

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')

from matplotlib import pyplot as plt

def plot_pixels(file_name, candidate_data_single_band,
                reference_data_single_band, limits=None, fit_line=None):

    logging.info('Display: Creating pixel plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hexbin(
        candidate_data_single_band, reference_data_single_band, mincnt=1)
    if not limits:
        min_value = 0
        _, ymax = plt.gca().get_ylim()
        _, xmax = plt.gca().get_xlim()
        max_value = max([ymax, xmax])
        limits = [min_value, max_value]
    plt.plot(limits, limits, 'k-')
    if fit_line:
        start = limits[0] * fit_line.gain + fit_line.offset
        end = limits[1] * fit_line.gain + fit_line.offset
        plt.plot(limits, [start, end], 'g-')
    plt.xlim(limits)
    plt.ylim(limits)
    plt.xlabel('Candidate DNs')
    plt.ylabel('Reference DNs')
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig)

def plot_histograms(file_name, candidate_data_multiple_bands,
                    reference_data_multiple_bands=None,
                    # Default is for Blue-Green-Red-NIR:
                    colour_order=['b', 'g', 'r', 'y'],
                    x_limits=None, y_limits=None):
    logging.info('Display: Creating histogram plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hold(True)
    for colour, c_band in zip(colour_order, candidate_data_multiple_bands):
        c_bh, c_bins = numpy.histogram(c_band, bins=256)
        plt.plot(c_bins[:-1], c_bh, color=colour, linestyle='-', linewidth=2)
    if reference_data_multiple_bands:
        for colour, r_band in zip(colour_order, reference_data_multiple_bands):
            r_bh, r_bins = numpy.histogram(r_band, bins=256)
            plt.plot(
                r_bins[:-1], r_bh, color=colour, linestyle='--', linewidth=2)
    plt.xlabel('DN')
    plt.ylabel('Number of pixels')
    if x_limits:
        plt.xlim(x_limits)
    if y_limits:
        plt.ylim(y_limits)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig)


# pedra = 0
# papel = 1
# tesoura = 2
# lagarto = 3
# spock = 4
stuff = {"pedra" : 0, "papel" : 1, "tesoura" : 2, "lagarto" : 3, "spock" : 4}

results = [
    [0, -1, 1, 1, -1],
    [1, 0, -1, -1, 1],
    [-1, 1, 0, 1, -1],
    [-1, 1, -1, 0, 1],
    [1, -1, 1, -1, 0]
    ]

n = int(input())

for i in range(n):
    inp = input().split(" ")
    r, s = stuff[inp[0]], stuff[inp[1]]
    if results[r][s] == 1:
        print("rajesh")
    elif results[r][s] == 0:
        print("empate")
    else:
        print("sheldon")


# -*- coding: utf-8 -*-
"""
Created on Thu Jul  9 08:39:51 2020

@author: AAYUSH pc
"""

import numpy as np

l=[1,2,3,4]
arr=np.array(l)

print('elements')
for i in arr:
    print(i)

#only one type of data can be stored in numpy


#!/usr/bin/env python3
import rospy
from std_msgs.msg import Float64, Bool

# Creating a publisher

def talker(poly):
     # Defining the publisher, with the name of the topic, type of message, and number of queue
     pub_x2 = rospy.Publisher('x2', Float64, queue_size=10)
     pub_x1 = rospy.Publisher('x1', Float64, queue_size=10)
     pub_x0 = rospy.Publisher('x0', Float64, queue_size=10)

     # Initiating the node
     rospy.init_node('talker', anonymous=True)

     # Rate of messasges
     rate = rospy.Rate(10) # 10hz

     # While it's not shutdown, publish and wait to publish again
     while not rospy.is_shutdown():
         pub_x2.publish(poly[0])
         pub_x1.publish(poly[1])
         pub_x0.publish(poly[2])
         rate.sleep()

def callback(butn):
     # Defining the publisher
     pub_x2 = rospy.Publisher('x2', Float64, queue_size=10)
     pub_x1 = rospy.Publisher('x1', Float64, queue_size=10)
     pub_x0 = rospy.Publisher('x0', Float64, queue_size=10)
     rate = rospy.Rate(10) # 10hz
     # If btnm is true
     if butn.data:
         pub_x2.publish(poly[0])
         pub_x1.publish(poly[1])
         pub_x0.publish(poly[2])
         rate.sleep()

# Creating a subscriber

def listener(fit):
     # Creating a global variable to use on the callback function
     global poly
     poly = fit

     # Initiating the node
     rospy.init_node('phonetopc', anonymous=True)

     # Subscribing to the node used on ROS Mobile
     rospy.Subscriber("btn_press", Bool, callback)

     # Keep subscribing until the program is stoped
     rospy.spin()


satir =0
sutun =0

satir = int(input("Satir sayınısı giriniz"))
sutun = int(input("Sutun sayısını giriniz"))
matriks = []
matriks2 = []
matriksToplam = []
for i in range(satir):
    matriks += [[satir] * sutun]

# 1. matriksi doldurma

for i in range(satir):
    for j in range(sutun):
        sayi = int(input("Matriksin %s satırının %s sutunun değerini giriniz" %(i+1,j+1)))
        matriks[i][j] = sayi

print("İkinci matriks için değerleri giriniz")

# ikinci matriks oluşturalım
for i in range(satir):
    matriks2 += [[satir] * sutun]

# 2. matriksi dolduralım
for i in range(satir):
    for j in range(sutun):
        sayi = int(input("2 . Matriksin %s satırının %s sutunun değerini giriniz" %(i+1,j+1)))
        matriks2[i][j] = sayi

for i in range(satir):
    matriksToplam += [[satir] * sutun]

for i in range(satir):
    print("\n")
    for j in range(sutun):
        matriksToplam[i][j] = matriks[i][j] + matriks2[i][j]

print("Sonuçları yazalım")

print(" Sonuç" ,matriksToplam)


from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

def create_app() -> "FastAPI":
    from prisma import Prisma

    from app.api.v1 import api
    from app.core import settings

    @asynccontextmanager
    async def lifespan(_app: FastAPI):
        prisma = Prisma(auto_register=True)
        await prisma.connect()
        yield
        await prisma.disconnect()

    app = FastAPI(
        lifespan=lifespan,
        title=settings.PROJECT_NAME,
        openapi_url=f"{settings.BASE_URL}/openapi.json",
        version=settings.VERSION,
        redoc_url=f"{settings.BASE_URL}/redoc",
        docs_url=f"{settings.BASE_URL}/docs",
    )
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.include_router(api.router, prefix=settings.API_V1_STR)

    return app


def shopdirect():
    global activity
    if activity==8:
        shoplist=[]
        sdol=18
        for a in range(1,6):
            dol=int(sdol**a)
            shoplist.append(('Shop Entry #'+str(a),dol))
        b=0
        render('rect', arg=((20,40,w-300,h-80), (50,50,50), False),borderradius=10)
        for a in shoplist:
            render('rect', arg=((40,60+(100*b),w-330,80), (50,50,80), False),borderradius=10)
            render('text', text=a[0], arg=((50,70+(100*b)), forepallete))
            render('text', text=format(a[1],',')+'$', arg=((50,90+(100*b)), forepallete))
            b+=1

        for event in pygame.event.get():
            if event.type  ==  pygame.QUIT:
                stopnow()

            if event.type  ==  pygame.KEYDOWN:
                if event.key  ==  pygame.K_q or event.key  ==  pygame.K_ESCAPE:
                    transitionprep(1)


from domain.index_finder import find_index

examples = [
    ['A'],
    ['A', 'B', 'C', 'A', 'C'],
    ['A', 'A', 'B', 'B', 'C'],
    ['A', 'B', 'A', 'C', 'A'],
    ['A', 'B', 'B', 'B'],
    ['B', 'B', 'B', 'A']
]

for example in examples:
    print("-" * 100)
    print(example)
    print(find_index(example))


import curses
import io
import time

from rich.console import Console
from rich.table import Table
from rich.text import Text
from rich import box

def main():

    # initialize curses
    screen = curses.initscr()
    curses.noecho() # turn off key echoing
    curses.cbreak() # respond to keys immediately (don't wait for Enter)
    # screen.keypad(True) # enable arrow keys

    # # set up initial position of character
    # row, col = 10, 10
    #
    # while True:
    #     # draw the character at its current position
    #     screen.addch(row, col, '@')
    #
    #     # get user input
    #     key = screen.getch()
    #
    #     # move the character based on input
    #     if key == curses.KEY_UP:
    #         row -= 1
    #     elif key == curses.KEY_DOWN:
    #         row += 1
    #     elif key == curses.KEY_LEFT:
    #         col -= 1
    #     elif key == curses.KEY_RIGHT:
    #         col += 1
    #     elif key == ord('q'):
    #         break
    #
    #     # clear the screen and move the cursor back to the top left
    #     screen.clear()
    #     screen.move(0, 0)

    for i in range(10):
        console = Console(file=io.StringIO())
        table = Table(
            title="My 4x4 Table",
            style="bright_white",
            caption_style="bright_white",
            box=box.ROUNDED,
            padding=0,
            show_header=False,
            show_footer=False,
            show_lines=True
        )

        # Add four columns with a minimum width of 14 characters
        for i in range(4):
            table.add_column(justify="center", min_width=14)

        # Add four rows to the table
        for i in range(4):
            row = table.add_row("'   _____ __ __\n  / ___// // /\n / __ \\/ // /_\n/ /_/ /__  __/\n\\____/  /_/   \n              \n'", "", "", "")
            # for cell in row.cells:
            #     cell.min_height = 5
        # Print the table
        console.print(table)
        output = console.file.getvalue()
        screen.addstr(f"size of output: {len(output)}")
        screen.addstr(output)
        screen.refresh()
        time.sleep(5)

    # console.print(table)
    #
    # # print("\n\n======\n")
    # screen.addstr("\n\n======\n")
    # with console.capture() as capture:
    #     console.print(table)
    # capture_str = capture.get()
    # # print("capture string length: ", len(capture_str))
    # screen.addstr("capture string length: ", len(capture_str))
    # # for i in range(10):
    # #     print("a")
    # # print("capture string type: ", type(capture_str))
    # # print("num returns: ", len(capture_str.split("\n")))
    # # print("printing line by line seprarated by ==========")
    # for line in capture_str.split("\n"):
    #     # print(line)
    #     screen.addstr(line)
    #     # print("==========")

    # # clean up curses before exiting
    curses.nocbreak()
    # screen.keypad(False)
    curses.echo()
    curses.endwin()

if __name__ == "__main__":
    main()