# Definition for a binary tree node.
from typing import List

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        indexes = {val:idx for idx,val in enumerate(inorder)}
        def helper(l: int, r:int, hashmap):
            if l > r:
                return None
            val = preorder.pop(0)
            index = hashmap[val]
            node = TreeNode(val)
            node.left = helper(l, index-1, hashmap)
            node.right = helper(index+1, r, hashmap)
            return node
        root = helper(0, len(inorder)-1, indexes)
        return root


import pandas as pd
import pycnnum as cnn
import numpy as np

## prepare the dataframe "df_all"
dir_input="D:\\"
#dtype_all={"交易年月日":str, "建築完成年月":str, "建物現況格局-房":int, "建物現況格局-廳":int, "建物現況格局-衛":int}
dtype_all={"交易年月日":str, "建築完成年月":str}
df_a=pd.read_csv(dir_input+"a_lvr_land_a.csv", header=[0,1], dtype=dtype_all)
df_b=pd.read_csv(dir_input+"b_lvr_land_a.csv", header=[0,1], dtype=dtype_all)
df_e=pd.read_csv(dir_input+"e_lvr_land_a.csv", header=[0,1], dtype=dtype_all)
df_f=pd.read_csv(dir_input+"f_lvr_land_a.csv", header=[0,1], dtype=dtype_all)
df_h=pd.read_csv(dir_input+"h_lvr_land_a.csv", header=[0,1], dtype=dtype_all)
df_all=pd.concat([df_a,df_b,df_e,df_f,df_h], axis=0, ignore_index=True)

## filter_a
# 主要用途為住家用
bool_fa=df_all.loc[:,"主要用途"] == "住家用"
df_fa=df_all.loc[bool_fa["main use"]]

# 建物型態包含"住宅大樓"四字
sr_fa=pd.Series(df_fa["建物型態"].values.flatten())
bool_fa=sr_fa.str.contains("住宅大樓")
bool_fa=bool_fa[bool_fa].index      # only "True" indices left
df_fa=df_fa.iloc[bool_fa,:]

# 總樓層數大於等於十三層
sr_fa=pd.Series(df_fa["總樓層數"].values.flatten())
sr_fa=sr_fa.replace(np.nan,"零層").str.slice(0,-1)    # to deal with nan values
for i in range(sr_fa.shape[0]):
    sr_fa[i]=cnn.cn2num(sr_fa[i])   # Chinese number to Arabic number
bool_fa=sr_fa>=13
bool_fa=bool_fa[bool_fa].index      # only "True" indices left
df_fa=df_fa.iloc[bool_fa,:]

## filter b
# 總件數
tot_num=df_all.shape[0]
# 總車位數
sr_fb=pd.Series(df_all["交易筆棟數"].values.flatten())
li_fb=pd.Series.tolist(sr_fb.str.split("車位").str.slice(-1))     # 取"車位"後面的數字
li_fb=[s for sub in li_fb for s in sub]     # 2d list to 1d list
tot_pl=sum([int(s) for s in li_fb])
# 平均總價元
avg_pr=df_all["總價元"].mean()
avg_pr=avg_pr.map('${:,.2f}'.format)[0]
# 平均車位總價元
avg_bpr=df_all["車位總價元"].replace(0, np.NaN).mean()
avg_bpr=avg_bpr.map('${:,.2f}'.format)[0]
arr_fb=[["總件數",tot_num],["總車位數",tot_pl],["平均總價元",avg_pr],["平均車位總價元",avg_bpr]]
df_fb=pd.DataFrame(arr_fb)

## export the target dataframes to csv files
df_fa.to_csv("filter_a.csv", sep=",", index=False, encoding="utf-8-sig")
df_fb.to_csv("filter_b.csv", sep=",", index=False, encoding="utf-8-sig", header=False)


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

from django.db import models, migrations
import uuid
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Account',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('number', models.PositiveSmallIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='AccountCategory',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('name', models.CharField(unique=True, max_length=50)),
            ],
        ),
        migrations.CreateModel(
            name='AccountMembership',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('role', models.CharField(choices=[('normal', 'Normal'), ('owner', 'Owner')], default='normal', max_length=10)),
                ('account', models.ForeignKey(to='membership.Account')),
            ],
        ),
        migrations.CreateModel(
            name='Department',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('shortname', models.CharField(max_length=4)),
                ('name', models.CharField(max_length=255)),
                ('allow_webmembers', models.BooleanField(default=True)),
                ('contact', models.CharField(max_length=255)),
            ],
        ),
        migrations.CreateModel(
            name='DepartmentInvitation',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('email', models.EmailField(max_length=254)),
                ('accepted', models.BooleanField(default=False)),
                ('accepted_at', models.DateTimeField(null=True)),
                ('verification_key', models.UUIDField(unique=True, default=uuid.uuid4, editable=False)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('account_category', models.ForeignKey(to='membership.AccountCategory')),
                ('department', models.ForeignKey(to='membership.Department')),
                ('invited_by', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'permissions': (('can_invite', 'Can send invitation'),),
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='DepartmentMembership',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('start', models.DateTimeField(auto_now_add=True)),
                ('exit', models.DateTimeField(null=True, default=None)),
                ('active', models.BooleanField(default=True)),
                ('account', models.ForeignKey(to='membership.Account')),
                ('department', models.ForeignKey(to='membership.Department')),
            ],
        ),
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('middle_name', models.CharField(null=True, max_length=30)),
                ('address', models.TextField(max_length=255)),
                ('postcode', models.CharField(max_length=30)),
                ('city', models.CharField(max_length=50)),
                ('tel', models.CharField(max_length=15)),
                ('tel2', models.CharField(null=True, max_length=15)),
                ('sex', models.CharField(choices=[('f', 'female'), ('m', 'male')], max_length=1)),
                ('date_of_birth', models.DateField(null=True)),
                ('privacy', models.BooleanField(default=False)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('changed', models.DateTimeField(auto_now=True)),
                ('account', models.ManyToManyField(through='membership.AccountMembership', to='membership.Account')),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, editable=False)),
            ],
        ),
        migrations.AddField(
            model_name='accountmembership',
            name='user_profile',
            field=models.ForeignKey(to='membership.UserProfile'),
        ),
        migrations.AddField(
            model_name='account',
            name='category',
            field=models.ForeignKey(to='membership.AccountCategory'),
        ),
        migrations.AddField(
            model_name='account',
            name='department',
            field=models.ForeignKey(to='membership.Department'),
        ),
        migrations.AlterUniqueTogether(
            name='departmentmembership',
            unique_together=set([('account', 'department')]),
        ),
    ]


from Context import Context
from ConcreteStrategyA import ConcreteStrategyA
from ConcreteStrategyB import ConcreteStrategyB

if __name__ == "__main__":
    # The client code picks a concrete strategy and passes it to the context.
    # The client should be aware of the differences between strategies in order
    # to make the right choice.

    context = Context(ConcreteStrategyA())
    print("Client: Strategy is set to normal sorting.")
    context.do_some_business_logic()
    print()

    print("Client: Strategy is set to reverse sorting.")
    context.strategy = ConcreteStrategyB()
    context.do_some_business_logic()


from asyncio import get_event_loop
from azure.appconfiguration.aio import AzureAppConfigurationClient

def _to_list(ait):
    async def lst():
        result = []
        async for item in ait:
            result.append(item)
        return result

    return get_event_loop().run_until_complete(lst())

class AzureAppConfigurationClientProxy(object):
    @classmethod
    def from_connection_string(
        cls,
        connection_string,  # type: str
        **kwargs
    ):
        return cls(
            AzureAppConfigurationClient.from_connection_string(
                connection_string, **kwargs
            )
        )

    def __init__(self, obj):
        self.obj = obj

    def get_configuration_setting(
        self, key, label=None, accept_datetime=None, **kwargs
    ):
        return get_event_loop().run_until_complete(
            self.obj.get_configuration_setting(
                key, label=label, accept_datetime=accept_datetime, **kwargs
            )
        )

    def add_configuration_setting(self, configuration_setting, **kwargs):
        return get_event_loop().run_until_complete(
            self.obj.add_configuration_setting(configuration_setting, **kwargs)
        )

    def delete_configuration_setting(self, key, label=None, etag=None, **kwargs):
        return get_event_loop().run_until_complete(
            self.obj.delete_configuration_setting(key, label=label, etag=etag, **kwargs)
        )

    def list_configuration_settings(
        self, label_filter=None, key_filter=None, accept_datetime=None, fields=None, **kwargs
    ):
        paged = self.obj.list_configuration_settings(
            label_filter=label_filter,
            key_filter=key_filter,
            accept_datetime=accept_datetime,
            fields=fields,
            **kwargs
        )
        return _to_list(paged)

    def list_revisions(
        self, label_filter=None, key_filter=None, accept_datetime=None, fields=None, **kwargs
    ):
        paged = self.obj.list_revisions(
            label_filter=label_filter,
            key_filter=key_filter,
            accept_datetime=accept_datetime,
            fields=fields,
            **kwargs
        )
        return _to_list(paged)

    def set_configuration_setting(self, configuration_setting, **kwargs):
        return get_event_loop().run_until_complete(
            self.obj.set_configuration_setting(configuration_setting, **kwargs)
        )

    def set_read_only(self, configuration_setting, read_only=True, **kwargs):
        return get_event_loop().run_until_complete(
            self.obj.set_read_only(configuration_setting, read_only, **kwargs)
        )


import os
import allure
from behave import use_fixture
from behave.log_capture import capture
from page_object.driver_factory_fixture import browser_chrome, browser_firefox, browser_ie, base_page, \
    browser_chrome_headless, browser_firefox_headless
from page_object.global_objects import blueprint_dashboard_page, admin_dashboard_page, architect_dashboard_page

"""
before all is called in order to execute before any tests starts executing
its parameters can ve either provided in ini file or from the command line
We are using before_feature here to use different instances for each feature level testing
"""

def before_feature(context, feature):
    if context.config.userdata.get('browser') == "chrome":
        if context.config.userdata.get('headless').lower() == "true":
            use_fixture(browser_chrome_headless, context)
        else:
            use_fixture(browser_chrome, context)
    if context.config.userdata.get('browser') == "firefox":
        if context.config.userdata.get('headless').lower() == "true":
            use_fixture(browser_firefox_headless, context)
        else:
            use_fixture(browser_firefox, context)
    if context.config.userdata.get('browser') == "ie":
        use_fixture(browser_ie, context)

@capture
def after_scenario(context, scenario):
    # Take screenshot if scenario fails
    if scenario.status == 'failed':
        allure.attach(base_page.driver.get_screenshot_as_png(), name='screenshot',
                      attachment_type=allure.attachment_type.PNG)
        url = context.web.get_current_url()
        if "admin" in url.split("/"):
            admin_dashboard_page.logout()
        elif "blueprint" in url.split("/"):
            blueprint_dashboard_page.logout()
        elif "architect" in url.split("/") or "organize" in url.split("/") or "ingest" in url.split("/"):
            architect_dashboard_page.logout()
        else:
            blueprint_dashboard_page.logout()

def make_dir(directories):
    """
    Checks if directory exists, if not make a directory, given the directory path
    :param: <string>dir: Full path of directory to create
    """
    if not os.path.exists(directories):
        os.makedirs(directories)


'''
Question 2.2 Skeleton Code
Here you should implement and evaluate the Conditional Gaussian classifier.
'''

from __future__ import division
import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import matplotlib.pyplot as plt

def compute_mean_mles(train_data, train_labels):
    '''
    Compute the mean estimate for each digit class
    Should return a numpy array of size (10,64)
    The ith row will correspond to the mean estimate for digit class i
    '''
    #version 1
    means = []
    for i in range(0, 10):
        i_digits = data.get_digits_by_label(train_data, train_labels, i)
        # Compute mean of class i
        means.append(np.mean(i_digits, axis=0))
    means = np.reshape(means,(10,64))
    return means

def compute_sigma_mles(train_data, train_labels):
    '''
    Compute the covariance estimate for each digit class
    Should return a three dimensional numpy array of shape (10, 64, 64)
    consisting of a covariance matrix for each digit class
    '''
    covariances = np.zeros((10, 64, 64))
    means = compute_mean_mles(train_data, train_labels)
    for i in range(10):
        for j in range(64):
            for k in range(64):
                i_indx = []
                for indx in range(len(train_data)):
                    if (train_labels[indx] ==i):
                        i_indx.append(indx)
                N = len(i_indx)
                X_j = [train_data[indx][j] for indx in i_indx]
                X_k = [train_data[indx][k] for indx in i_indx]
                cov_j_k = (1/N)*sum([(X_j[n]-means[i][j])*(X_k[n]-means[i][k]) for n in range(N)])
                covariances[i][j][k] = cov_j_k
    for label in range(10):
        covariances[label] = covariances[label] + 0.01*np.identity(64)
    return covariances

def plot_cov_diagonal(covariances):
    # Plot the log-diagonal of each covariance matrix side by side
    cov_diagonals = []
    for i in range(10):
        cov_diag = np.diag(covariances[i])
        cov_diagonals.append(np.reshape(cov_diag, (8, 8)))
    all_concat = np.concatenate(np.log(cov_diagonals),1)
    plt.imshow(all_concat, cmap='gray')
    plt.show()

def generative_likelihood(digits, means, covariances):
    '''
    Compute the generative log-likelihood:
        log p(x|y,mu,Sigma)
    Should return an n x 10 numpy array
    '''
    result = []
    for digit in digits:
        log_lik = []
        for k in range(10):
            exp_part = np.exp((-1 / 2) * np.linalg.multi_dot([np.transpose(digit - means[k]), np.linalg.inv(covariances[k] + 0.01 * np.identity(64)),digit - means[k]]))
            log_lik.append(np.log(((2*np.pi)**(-64/2)) * (np.linalg.det(covariances[k] + 0.01*np.identity(64)) ** (-1/2)) * exp_part))
        result.append(log_lik)
    return result

def conditional_likelihood(digits, means, covariances):
    '''
    Compute the conditional likelihood:
        log p(y|x, mu, Sigma)
    This should be a numpy array of shape (n, 10)
    Where n is the number of datapoints and 10 corresponds to each digit class
    '''
    result = []
    prob_y = 1/10
    generative_log_lik = generative_likelihood(digits, means, covariances)
    for gen in generative_log_lik:
        log_prob_x = np.log(sum(np.exp(gen_feature_d) for gen_feature_d in gen)*prob_y)
        digit_cond_lik = []
        for gen_feature_d in gen:
            digit_cond_lik.append(gen_feature_d + np.log(prob_y) - log_prob_x)
        result.append(digit_cond_lik)
    return result

    #generative = generative_likelihood(digits, means, covariances)
    #px = np.sum(np.exp(generative - np.log(10)), axis=1).reshape((digits.shape[0], )) # 700 x 1
    #px = np.full((10, digits.shape[0]), px).T
    #log_px = np.log(px)
    #results = (generative - np.log(10)) - log_px
    #return results

def avg_conditional_likelihood(digits, labels, means, covariances):
    '''
    Compute the average conditional likelihood over the true class labels
        AVG( log p(y_i|x_i, mu, Sigma) )
    i.e. the average log likelihood that the model assigns to the correct class label
    '''
    #cond_likelihoods = conditional_likelihood(digits, means, covariances)
    #total_likelihoods = 0
    #for n_indx, cond_like in enumerate(cond_likelihoods):
    #    total_likelihoods += cond_like[int(labels[n_indx])]
    #return total_likelihoods / len(digits)

    cond_likelihood = conditional_likelihood(digits, means, covariances)
    temp = np.zeros(cond_likelihood.shape)
    for i in range(temp.shape[0]):
        j = int(labels[i])
        temp[i, j] = 1
    result = np.sum(temp * cond_likelihood) / temp.shape[0]
    return result

def classify_data(digits, means, covariances):
    '''
    Classify new points by taking the most likely posterior class
    '''
    #cond_likelihood = conditional_likelihood(digits, means, covariances)
    #result = []
    #for indx, cond_l in enumerate(cond_likelihood):
    #    result.append(max([(k, prob) for k, prob in enumerate(cond_l)], key=lambda x: x[1])[0])
    #return result

    cond_likelihood = conditional_likelihood(digits, means, covariances)
    # Compute and return the most likely class
    classes = np.arange(10)
    indices = np.argmax(cond_likelihood, axis=1)
    return classes[indices]

def main():
    train_data, train_labels, test_data, test_labels = data.load_all_data('data')

    # Fit the model
    means = compute_mean_mles(train_data, train_labels)
    covariances = compute_sigma_mles(train_data, train_labels)

    #Part (1)
    plot_cov_diagonal(covariances)

    # Evaluation

    #Part(2)
    avg_cond_like_train = avg_conditional_likelihood(train_data, train_labels, means, covariances)
    avg_cond_like_test = avg_conditional_likelihood(test_data, test_labels, means, covariances)

    print("when k is 1, the training accuracy is",classification_accuracy(knn, 1, train_data, train_labels))
    print("when k is 1, the test accuracy is",classification_accuracy(knn, 1, test_data, test_labels))

    #Part(3)
    classes_train = classify_data(train_data, means, covariances)
    classes_test = classify_data(test_data, means, covariances)
    class_accuracy_train = sum(1 for indx, k in enumerate(classes_train) if train_labels[indx] == k)/len(train_data)
    class_accuracy_test = sum(1 for indx, k in enumerate(classes_test) if test_labels[indx] == k)/len(test_data)
    print("Average conditional likelihood ->", "\nTrain: ", avg_cond_like_train, "\nTest: ", avg_cond_like_test)
    print("Classification accuracy->", "\nTrain: ", class_accuracy_train, "\nTest: ", class_accuracy_test)

if __name__ == '__main__':
    main()


import dockerpty
import docker
import os

from proxy_handler import manageproxy

import remote_vm_task as remote_machine
from log_handler import logger
from helper import get_context_path , get_docker_daemon_address , get_nginx_server_address

def proxieddomain (name) :
    alias = '.apps.iitd.ac.in'
    address = name +alias;
    return address[1:];         # required name contains '/' at start

class Container:

    client = None;
    propvalues = ['imageid','created','path','args','exposedports','environment','publishall','ports','hostname',
            'ipaddress','cmd' ,'entrypoint','bindings','volumes','sysinitpath','state']

    def __init__(self,_id,setProp = True,**keywords):
        self.id = _id;
        self.properties = {

        }
        print("new file updation successful");
        if not (Container.client) :
            cert_path = os.path.join(get_context_path(), 'modules/certs/')
            tls_config = docker.tls.TLSConfig(client_cert=(cert_path+'cert.pem', cert_path+'key.pem'),verify=cert_path+'ca.pem')
            docker_machine = get_docker_daemon_address();
            client = docker.Client(base_url='https://'+docker_machine[0]+':'+docker_machine[1],version='auto', tls=tls_config)

            Container.setclient(client);
            logger.debug(client);

        logger.debug(Container.client);
        self.update = Container.client.update_container;
        for key in keywords:
            self.properties[key] = keywords[key];
        if setProp :
            self.updatedetails();

    def stop(self):
        response = Container.client.stop(container = self.id,timeout=3);
        return response;
        # update the db status ...

    def rename(self,newname):
        response = Container.client.rename(container = self.id,name = newname);
        return response;
        # update container name

    def start(self):

        response = Container.client.start(container = self.id);
        self.updatedetails();
        self.addipbyconf();
        return response;
        # update the db status ...

    def restart(self,timeout=10):
        response = Container.client.restart(self.id,timeout=timeout);
        #~ self.deleteipconf();
        #~ self.addipconf();
        self.updatedetails();
        self.addipbyconf();
        return response;

    def kill(self,signal='SIGKILL'):
        response = Container.client.kill(container=self.id,signal=signal);
        return response;
        # update the db status ...

    def resume(self):
        response = Container.client.unpause(self.id);
        return response;
        # update the db status ...

    def logs(self,stdout=True,stderr=True,stream=False,timestamps=9999,follow = False):
        response = Container.client.logs(self.id,stdout=stdout,stream=stream,stderr=stderr,timestamps=timestamps,follow=follow)
        return response;

    def remove(self,v=True,link=False,force=False):
        self.stop();
        #container = Container(containerid);
        #~ self.deleteipconf();
        self.updatedetails();
        self.deleteipbyconf();
        #os.system(cmd);
        response = Container.client.remove_container(self.id,v=v,link=link,force=force);
        return response;
        # update the db status ...

    def pause(self):
        response = Container.client.pause(self.id);
        return response;
        # update the db status ...

    def stats(self,decode = True ,stream = False):
        response = Container.client.stats(self.id,decode,stream);
        return response;

    def top(self,pidargs='aux'):
        response = Container.client.top(self.id,pidargs);
        return response;

    def inspect(self):
        response = Container.client.inspect_container(self.id);
        return response;

    def updatedetails(self):
        response = self.inspect();
        try:

            self.properties['Created'] = response.get('Created');
            self.properties['Path'] = response.get('Path');
            self.properties['Args'] = response.get('Args');
            if (response.get('State')):
                self.properties['State'] =response['State'].get('Status');
            else:
                self.properties['State'] = None;
            self.properties['ImageId'] = response.get('Image');
            self.properties['Name'] = response.get('Name');
            self.properties['Hostname'] = response.get('Config')['Hostname'];
            self.properties['Domainname'] = response.get('Config')['Domainname'];
            self.properties['IPAddress'] = response.get('NetworkSettings')['IPAddress'];
            self.properties['MacAddress'] = response.get('NetworkSettings')['MacAddress'];
            if(response.get('NetworkSettings')):
                self.properties['Ports'] = response['NetworkSettings'].get('Ports');
            else:
                self.properties['Ports'] = None;
            self.properties['Cmd'] = response.get('Config')['Cmd'];
            self.properties['Environment'] = response.get('Config')['Env'];
            self.properties['EntryPoint'] = response.get('Config')['Entrypoint'];
            self.properties['Volumes'] = response.get('Config')['Volumes'];
            self.properties['Bindings'] = response.get('HostConfig')['Binds'];
            self.properties['ImageName'] = response.get('Config')['Image'];
            self.properties['Memory'] = response.get('HostConfig').get('Memory');
            self.properties['CPUCore'] = response.get('HostConfig').get('CpusetCpus');
            self.properties['WorkingDir'] = response.get('Config').get("WorkingDir");
            self.properties['ExposedPorts'] =response.get('HostConfig').get('ExposedPorts');
            self.properties['RestartPolicy']=response.get('HostConfig').get('RestartPolicy');
            self.properties['ExecIDs'] = response.get('ExecIDs');
            portdict = response['NetworkSettings'].get('Ports');
            if (portdict):
                for key in portdict:
                    if(portdict[key]):
                        self.properties['ConnectionPath'] = portdict[key][0]["HostIp"] + ":" + portdict[key][0]["HostPort"]

        except Exception as e:
            logger.debug(e);
            #traceback.print_exc()

    def export(self):
        strm = Container.client.export(self.id);
        return strm;

    def get_archive(self,path):
        strm,stats = Container.client.get_archive(self.id,path)  # @UnusedVariable
        return strm

    # monitor changes in the filesystem
    def diff(self):
        response = Container.client.diff(self.id);
        return response;

    def recreate(self,commited = True,refresh = False):
        if not refresh :
            imageid = self.save_template("container restart","Docker automatic api","","temp","");
            print(imageid)
            containerid = Container.client.create_container(image=imageid['Id'],detach = True);
            #Update the db container created ;
            Container.client.start(containerid);
            #Update the db container started;
            #self.stop();
            self.remove();
            #Deleting image created if not commited .....
            if not commited :
                Container.client.remove_image(imageid['Id']);
            return containerid;

    def save_template(self,message,author,changes,tag,repository):
        #docker commit will used. Data in volumes will not be saved.Only changes in applications will be reflected.
        logger.debug(repository);
        if (not repository) :
            repository = self.properties['ImageName'];
        response = Container.client.commit(self.id,tag=tag,message=message,author = author ,changes = changes , repository = repository);
        return response;

    def backup(self,user):
        logger.debug(user);
        self.save_template(message='backup_at',author=user,changes={},tag="backup",repository=self.properties['Name'][1:]);
        return None

    def execcmdgenerator(self,cmd='bash'):
        # terminal will be opened ... generator will be returned;
        execid = Container.client.exec_create(container=self.id,cmd=cmd,tty=True,stdout=True,stderr=True);
        generator = Container.client.exec_start(exec_id = execid , detach = False , stream =True , tty = True);
        return generator;

    def execidgenerator(self,cmd='bash'):
        execid = Container.client.exec_create(container=self.id,cmd=cmd,tty=True,stdout=True,stderr=True,stdin=True);
        return execid;

    def execresize(self,execid,height=80,width=100):
        Container.client.exec_resize(exec_id = execid,height = height , width = width);

    def execcmd(self,cmd):
        execid = Container.client.exec_create(container=self.id,cmd=cmd,tty=False,stdout=True,stderr=True);
        output = Container.client.exec_start(exec_id = execid , detach = False , stream =True , tty = False);
        string ='';
        for x in output:
            string = string + x;
        return string;

    def deleteipbyconf(self):
        filepath = "/etc/nginx/conf.d/" + self.properties['Name'] +".conf";
        cmd = 'rm -f ' + filepath;
        nginx_server = get_nginx_server_address()
        output = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])
        print(output)
        cmd = '/etc/init.d/nginx reload';
        output = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])
        print(output)

    def upload(self,path,data):
        return Container.client.put_archive(container=self.id,path=path,data=data)

    def addipbyconf(self,updatetc=False):
#         ipaddress = self.properties['IPAddress'];

        name = self.properties['Name'];
        envvars = self.properties['Environment'];
        domainname=None;
        for x in envvars:
            sstrings = x.split("=");
            if (sstrings[0] == "HostName") :
                domainname=sstrings[1];
        if not domainname :
            domainname = proxieddomain(name);
        nginx_server = get_nginx_server_address()
        fulladdress = self.properties.get('ConnectionPath');
        logger.debug("check true");
        logger.debug(fulladdress);
        if (not fulladdress):
            return;

        filepath = "/etc/nginx/conf.d/" + self.properties['Name'] +".conf";
        reverser = manageproxy('');
        reverser.add(reverser.render({'x' : domainname , 'y' : fulladdress}));
        print(reverser.filedit);
        reverser.filedit = reverser.filedit.replace('$' ,'\$');
        cmd = 'echo -e "' + reverser.filedit  + '" > '+ filepath;
        out2 = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])
        print("Output : " +out2);
        cmd = '/etc/init.d/nginx reload';
        output = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])
        print(output)
        if(updatetc):
            hostadd = self.properties['ConnectionPath'].split(':')[0] + ' '  + domainname ;
            cmd ='echo " ' + hostadd + ' " >> /etc/hosts';
            logger.debug('Command=> '+cmd)
            #logger.debug('Host IP=> ' +hostadd)
            output = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])
            #logger.debug(output)

    def execstream(self,cmd='bash',stdout=None,stdin=None,stderr=None):
        self.removeoldexecid();
        dockerpty.exec_command(Container.client,self.id,cmd,True,stdout,stderr,stdin);

    def removeoldexecid(self):
        print("called");

    @classmethod
    def setclient(cls,cli):
        cls.client = cli;

def addip(name,uuids):
    filepath = "/etc/nginx/conf.d/" + name +".conf";
    addresses=[];
    nginx_server = get_nginx_server_address()
    for uuid in uuids:
        container = Container(uuid);
        addresses.append(container.properties.get('ConnectionPath'));
    reverser = manageproxy('');
    domainname = proxieddomain("/"+name);
    reverser.addmultiple(domainname,addresses);
    reverser.filedit = reverser.filedit.replace('$' ,'\$');
    cmd = 'echo -e "' + reverser.filedit  + '" > '+ filepath;
    out2 = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])  # @UnusedVariable
    cmd = '/etc/init.d/nginx reload';
    output = remote_machine.execute_remote_cmd(nginx_server[0],nginx_server[1],cmd,nginx_server[2])  # @UnusedVariable

#some functions raise docker.errors.APIError take them in try catch block.....


import keras

import numpy as np
import tensorflow as tf

class Agent:
    def __init__(self, action_size, database_limit, file_path):
        self.action_size = action_size
        self.database_limit = database_limit
        self.file_path = './student_weights/' + file_path

        # init_op = tf.initialize_all_variables()
        #
        # sess = tf.InteractiveSession()
        # sess.run(init_op)

    def fit_student(self, master, student, env, logger, tensorboard):

        labels = np.zeros((self.database_limit, 1), dtype=np.float32)
        observations = np.zeros((self.database_limit, 1, 200, 200), dtype=np.float32)

        for j in range(0, 100000):

            for i in range(0, self.database_limit):
                observation = env.reset()
                observation = np.expand_dims(np.expand_dims(observation, axis=0), axis=0)

                q_values = master.model.predict(observation, batch_size=1)

                labels[i] = np.argmax(q_values, axis=1)
                observations[i][0] = observation[0][0]

            one_hot_labels = keras.utils.to_categorical(labels, self.action_size)
            student.model.fit(observations, one_hot_labels, epochs=1, batch_size=64, callbacks=[logger, tensorboard], verbose=2)

            if j % 50 == 0:
                student.model.save_weights(filepath=self.file_path + '.h5f', overwrite=True)


import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F

from model.models import FewShotModel

class ScaledDotProductAttention(nn.Module):
    ''' Scaled Dot-Product Attention '''

    def __init__(self, temperature, attn_dropout=0.1):
        super().__init__()
        self.temperature = temperature
        self.dropout = nn.Dropout(attn_dropout)
        self.softmax = nn.Softmax(dim=2)

    def forward(self, q, k, v):

        attn = torch.bmm(q, k.transpose(1, 2))
        attn = attn / self.temperature
        log_attn = F.log_softmax(attn, 2)
        attn = self.softmax(attn)
        attn = self.dropout(attn)
        output = torch.bmm(attn, v)
        return output, attn, log_attn

class MultiHeadAttention(nn.Module):
    ''' Multi-Head Attention module '''

    def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
        super().__init__()
        self.n_head = n_head
        self.d_k = d_k
        self.d_v = d_v

        self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
        self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
        self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
        nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
        nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
        nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))

        self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))
        self.layer_norm = nn.LayerNorm(d_model)

        self.fc = nn.Linear(n_head * d_v, d_model)
        nn.init.xavier_normal_(self.fc.weight)
        self.dropout = nn.Dropout(dropout)

    def forward(self, q, k, v):
        d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
        sz_b, len_q, _ = q.size()
        sz_b, len_k, _ = k.size()
        sz_b, len_v, _ = v.size()

        residual = q
        q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
        k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
        v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)

        q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk
        k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk
        v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv

        output, attn, log_attn = self.attention(q, k, v)

        output = output.view(n_head, sz_b, len_q, d_v)
        output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)

        output = self.dropout(self.fc(output))
        output = self.layer_norm(output + residual)

        return output

class FEAT(FewShotModel):
    def __init__(self, args):
        super().__init__(args)
        if args.backbone_class == 'ConvNet':
            hdim = 64
        elif args.backbone_class == 'Res12':
            hdim = 640
        elif args.backbone_class == 'Res18':
            hdim = 512
        elif args.backbone_class == 'WRN':
            hdim = 640
        else:
            raise ValueError('')

        self.slf_attn = MultiHeadAttention(1, hdim, hdim, hdim, dropout=0.5)

    def _forward(self, instance_embs, support_idx, query_idx):
        emb_dim = instance_embs.size(-1)

        # organize support/query data
        support = instance_embs[support_idx.contiguous().view(-1)].contiguous().view(*(support_idx.shape + (-1,)))
        query   = instance_embs[query_idx.contiguous().view(-1)].contiguous().view(  *(query_idx.shape   + (-1,)))

        # get mean of the support
        proto = support.mean(dim=1) # Ntask x NK x d
        num_batch = proto.shape[0]
        num_proto = proto.shape[1]
        num_query = np.prod(query_idx.shape[-2:])

        # query: (num_batch, num_query, num_proto, num_emb)
        # proto: (num_batch, num_proto, num_emb)
        proto = self.slf_attn(proto, proto, proto)
        if self.args.use_euclidean:
            query = query.view(-1, emb_dim).unsqueeze(1) # (Nbatch*Nq*Nw, 1, d)
            proto = proto.unsqueeze(1).expand(num_batch, num_query, num_proto, emb_dim).contiguous()
            proto = proto.view(num_batch*num_query, num_proto, emb_dim) # (Nbatch x Nq, Nk, d)

            logits = - torch.sum((proto - query) ** 2, 2) / self.args.temperature
        else:
            proto = F.normalize(proto, dim=-1) # normalize for cosine distance
            query = query.view(num_batch, -1, emb_dim) # (Nbatch,  Nq*Nw, d)

            logits = torch.bmm(query, proto.permute([0,2,1])) / self.args.temperature
            logits = logits.view(-1, num_proto)

        # for regularization
        if self.training:
            aux_task = torch.cat([support.view(1, self.args.shot, self.args.way, emb_dim),
                                  query.view(1, self.args.query, self.args.way, emb_dim)], 1) # T x (K+Kq) x N x d
            num_query = np.prod(aux_task.shape[1:3])
            aux_task = aux_task.permute([0, 2, 1, 3])
            aux_task = aux_task.contiguous().view(-1, self.args.shot + self.args.query, emb_dim)
            # apply the transformation over the Aug Task
            aux_emb = self.slf_attn(aux_task, aux_task, aux_task) # T x N x (K+Kq) x d
            # compute class mean
            aux_emb = aux_emb.view(num_batch, self.args.way, self.args.shot + self.args.query, emb_dim)
            aux_center = torch.mean(aux_emb, 2) # T x N x d

            if self.args.use_euclidean:
                aux_task = aux_task.permute([1,0,2]).contiguous().view(-1, emb_dim).unsqueeze(1) # (Nbatch*Nq*Nw, 1, d)
                aux_center = aux_center.unsqueeze(1).expand(num_batch, num_query, num_proto, emb_dim).contiguous()
                aux_center = aux_center.view(num_batch*num_query, num_proto, emb_dim) # (Nbatch x Nq, Nk, d)

                logits_reg = - torch.sum((aux_center - aux_task) ** 2, 2) / self.args.temperature2
            else:
                aux_center = F.normalize(aux_center, dim=-1) # normalize for cosine distance
                aux_task = aux_task.permute([1,0,2]).contiguous().view(num_batch, -1, emb_dim) # (Nbatch,  Nq*Nw, d)

                logits_reg = torch.bmm(aux_task, aux_center.permute([0,2,1])) / self.args.temperature2
                logits_reg = logits_reg.view(-1, num_proto)

            return logits, logits_reg
        else:
            return logits


user_input = input()

N, M = map(int, user_input.split(' '))
numbers = list(range(1, N + 1))

def track(depth, ans):
    if depth == M:
        result = list(map(str, ans))

        print(' '.join(result))
        return
    for number in numbers:
        ans.append(number)
        track(depth + 1, ans)
        ans.pop()
track(0,[])


import django
from django.db import models

from healthnet.core.enumfield import EnumField

LogLevel = EnumField('Info', 'Warning', 'Error')

class LogEntry(models.Model):
    """
    A log entry which is logged by the log, and created automatically through system interactions
    """
    datetime = models.DateTimeField()
    level = models.IntegerField(choices=LogLevel.get_choices(), default=LogLevel.Info)
    message = models.TextField()

    def get_level_str(self):
        """
        Gets the level of the log entry
        :return: level of the log entry
        """
        if self.level == 0:
            return 'Info'
        if self.level == 1:
            return 'Warning'
        if self.level == 2:
            return 'Error'
        else:
            return 'Unknown'

class Logging(object):
    """
    The log
    """

    @staticmethod
    def log(level, msg, print_stdout=True):
        """
        Log a message into the database
        :param print_stdout: print to stdout
        :param level: level of the log
        :param msg: message being logged
        """
        time = django.utils.timezone.now()
        entry = LogEntry(message=msg, level=level, datetime=time)
        if print_stdout:
            print('%s: [%s] %s' % (entry.datetime.strftime("%Y-%m-%d %H:%M"), entry.get_level_display(), entry.message))
        entry.save()

    @staticmethod
    def error(msg, print_stdout=True):
        """
        Log an error
        :param print_stdout:
        :param msg: message to log
        """
        Logging.log(LogLevel.Error, msg, print_stdout=print_stdout)

    @staticmethod
    def warning(msg, print_stdout=True):
        """
        Log a warning
        :param print_stdout:
        :param msg: message to log
        """
        Logging.log(LogLevel.Warning, msg, print_stdout=print_stdout)

    @staticmethod
    def info(msg, print_stdout=True):
        """
        Log info
        :param print_stdout:
        :param msg: message to log
        """
        Logging.log(LogLevel.Info, msg, print_stdout=print_stdout)


### *cnn2* cnn using libstarid
###
import time
import random
import numpy as np
import tensorflow as tf
import libstarid.libstarid as ls
libstarid = ls.libstarid()
stars = 100
batch = 100
batches = 300

def inputs(batch, stars):
    images = np.zeros((batch, 28, 28, 1), dtype=np.float32)
    labels = np.zeros((batch), dtype=np.int32)
    for cnt in range(batch):
        starndx = random.randint(0, stars-1)
        images[cnt, :, :, 0] = libstarid.image(starndx)
        labels[cnt] = starndx
    return images, labels

data = tf.placeholder(tf.float32, [batch, 28, 28, 1])
target = tf.placeholder(tf.int32, [batch])
w1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(tf.constant(0.1, shape=[32]), dtype=tf.float32)
w2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1), dtype=tf.float32)
b2 = tf.Variable(tf.constant(0.1, shape=[64]), dtype=tf.float32)
w3 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1), dtype=tf.float32)
b3 = tf.Variable(tf.constant(0.1, shape=[1024]), dtype=tf.float32)
w4 = tf.Variable(tf.truncated_normal([1024, stars], stddev=0.1), dtype=tf.float32)
b4 = tf.Variable(tf.constant(0.1, shape=[stars]), dtype=tf.float32)

conv1 = tf.nn.conv2d(data, w1, strides=[1, 1, 1, 1], padding='SAME') + b1
pool1 = tf.nn.max_pool(tf.nn.relu(conv1), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
conv2 = tf.nn.conv2d(pool1, w2, strides=[1, 1, 1, 1], padding='SAME') + b2
pool2 = tf.nn.max_pool(tf.nn.relu(conv2), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
full3 = tf.matmul(tf.reshape(pool2, [-1, 7 * 7 * 64]), w3) + b3
logits = tf.matmul(full3, w4) + b4

loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=target))
train = tf.train.AdamOptimizer().minimize(loss)
prediction = tf.cast(tf.arg_max((logits), 1), tf.int32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, target), tf.float32))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
t0 = time.time()
for batchndx in range(batches):
    trainin, trainlab = inputs(batch, stars)
    sess.run(train, {data: trainin, target: trainlab})
    if batchndx % 10 == 0:
        testin, testlab = inputs(batch, stars)
        testcost, testacc = sess.run([loss, accuracy], {data: testin, target: testlab})
        print('%s, %.1f, %d, %.2f, %.2f' % (time.strftime('%H%M%S'), time.time()-t0, batchndx, testcost, testacc))


# Program Name: Movie Trailer Website
# Module Name: entertainment_center
# Programmer: Jon Tudor
# Purpose: This module provides movie data that is then used via the
# media.Movie class to create the Movie Trailer Website.
import fresh_tomatoes
import media

# Provide data needed to display movies on the Movie Trailer Website
monty_python = media.Movie("Monty Python",
                           "A king goes on a quest to find the Holy Grail",
                           "http://ecx.images-amazon.com/images/I/91wtzn69sGL._SY606_.jpg",
                           "https://www.youtube.com/watch?v=hKNDml12Big")

cloud_atlas = media.Movie("Cloud Atlas",
                          "A connection between two souls over six lifetimes",
                          "http://cdn.wegotthiscovered.com/wp-content/uploads/cloud-atlas-poster.jpg",
                          "https://www.youtube.com/watch?v=ByehYal_cCs")

django = media.Movie("Django",
                     "A man gets retribution and freedom",
                     "http://upload.wikimedia.org/wikipedia/en/8/8b/Django_Unchained_Poster.jpg",
                     "https://www.youtube.com/watch?v=eUdM9vrCbow")

space_jam = media.Movie("Space Jam",
                        "Michael Jordan kicks alien butt " +
                        "in basketball with the Looney Toons",
                        "http://assets.nydailynews.com/polopoly_fs/1.1678204!/img/httpImage/image.jpg_gen/derivatives/article_970/article-spacejamweb-0221.jpg",
                        "https://www.youtube.com/watch?v=xMOE5OVwWDE")

the_hangover = media.Movie("The Hangover",
                           "Four guys on a trip to Las Vegas " +
                           "for the bachelor party of a lifetime ",
                           "http://upload.wikimedia.org/wikipedia/en/b/b9/Hangoverposter09.jpg",
                           "https://www.youtube.com/watch?v=tcdUhdOlz9M")

the_lego_movie = media.Movie("The Lego Movie",
                             "An adventure in the world of Lego",
                             "http://upload.wikimedia.org/wikipedia/en/1/10/The_Lego_Movie_poster.jpg",
                             "https://www.youtube.com/watch?v=fZ_JOBCLF-I")

# Pass the required movie data values to the movie class to be displayed.
movies = [monty_python, cloud_atlas, django,
    space_jam, the_hangover, the_lego_movie]
fresh_tomatoes.open_movies_page(movies)


from app import mongo
from flask import (Blueprint, flash, jsonify, abort, request)
from app.util import serialize_doc

bp = Blueprint('slack_settings', __name__, url_prefix='/slack')

@bp.route('/settings', methods=["PUT", "GET"])
def tms_setings():
    if request.method == "GET":
        slack = mongo.db.slack_settings.find_one({},{"_id":0})
        return jsonify(slack)

    if request.method == "PUT":
        slack_token = request.json.get("slack_token")
        slack_notification = request.json.get("slack_notification")
        send_email = request.json.get("send_email")
        mobile_message = request.json.get("mobile_message")
        ret = mongo.db.slack_settings.update({}, {
            "$set": {
                "slack_token": slack_token,
                "slack_notification":slack_notification,
                "send_email":send_email,
                "mobile_message":mobile_message
            }
        },upsert=True)
        return jsonify(str(ret))


import tkinter as tk
import os
import platform
import pygame
import time

class Window(object):
    def __init__(self):
        self.root = tk.Tk()  # Main window
        self.root.title("SquareScape")
        # self.root.iconbitmap(r'C:\Users\17_es\PycharmProjects\square_puzzle\images\icon.ico')
        self.root.configure(background='#9b9b9b')

        # Large Frame
        self.win_frame = tk.Frame(self.root, width=670, height=520, highlightbackground='#595959', highlightthickness=2)

        # menu (left side)
        self.menu = tk.Frame(self.win_frame, width=150, height=516, highlightbackground='#595959', highlightthickness=2)
        self.menu_label = tk.Label(self.menu, text="Settings", bg='#8a8a8a', font=("Courier", "16", "bold roman"))
        self.mute = tk.Button(self.menu, text="XXXX", font="Courier", bg='#bcbcbc', activebackground='#cdcdcd')

        tk.Button(self.menu, text="<->", command=lambda: setattr(self, "direction", (-self.direction[0], self.direction[1]))).pack()
        tk.Button(self.menu, text="^", command=lambda: setattr(self, "direction", (self.direction[0], -self.direction[1]))).pack()

        # pygame
        self.pygame_frame = tk.Frame(self.win_frame, width=514, height=514, highlightbackground='#595959', highlightthickness=2)
        self.embed = tk.Frame(self.pygame_frame, width=512, height=512,)

        # Packing
        self.win_frame.pack(expand=True)
        self.win_frame.pack_propagate(0)

        self.menu.pack(side="left")
        self.menu.pack_propagate(0)
        self.menu_label.pack(ipadx=60, ipady=2)
        self.mute.pack(ipadx=40, ipady=2, pady=5)

        self.pygame_frame.pack(side="left")
        self.embed.pack()

        #This embeds the pygame window
        os.environ['SDL_WINDOWID'] = str(self.embed.winfo_id())
        system = platform.system()
        if system == "Windows":
            os.environ['SDL_VIDEODRIVER'] = 'windib'
        elif system == "Linux":
            os.environ['SDL_VIDEODRIVER'] = 'x11'

        self.root.update_idletasks()
        #Start pygame
        pygame.init()
        self.win = pygame.display.set_mode((512, 512))

        self.bg_color = (255, 255, 255)
        self.win.fill(self.bg_color)
        self.pos = 0, 0
        self.direction = 10, 10
        self.size = 40
        self.color = (0, 255, 0)
        self.root.after(30, self.update)

        self.root.mainloop()

    def update(self):

        first_move = True
        pygame.draw.rect(self.win, self.bg_color, self.pos + (self.size, self.size))

        self.pos = self.pos[0] + self.direction[0], self.pos[1] + self.direction[1]

        if self.pos[0] < 0 or self.pos[0] > 512 - self.size:
            self.direction = -self.direction[0], self.direction[1]
            self.pos = self.pos[0] + 2 * self.direction[0], self.pos[1] + self.direction[1]
        if self.pos[1] < 0 or self.pos[1] > 512 - self.size:
            self.direction = self.direction[0], -self.direction[1]
            self.pos = self.pos[0] + self.direction[0], self.pos[1] + 2 * self.direction[1]

        pygame.draw.rect(self.win, self.color, self.pos + (self.size, self.size))
        pygame.display.flip()
        self.root.after(30, self.update)

if __name__ == '__main__':
    screen = Window()
    tk.mainloop()


import udt
import util
import config
import time
import collections
import threading

# Stop-And-Wait reliable transport protocol.
class StopAndWait:
  # "msg_handler" is used to deliver messages to application layer
  # when it's ready.
  def __init__(self, local_port, remote_port, msg_handler):
    self.network_layer = udt.NetworkLayer(local_port, remote_port, self)
    self.msg_handler = msg_handler
    self.msg_buffer = collections.deque(maxlen = 8)
    self.buffer_lock = threading.Lock()
    self.send_seq_number = 0
    self.recv_seq_number = 0
    self.send_seq_number_lock = threading.Lock()
    self.recv_seq_number_lock = threading.Lock()

  # "send" is called by application. Return true on success, false
  # otherwise.
  def send(self, msg):
    # TODO: impl protocol to send packet from application layer.
    # call self.network_layer.send() to send to network layer.
    msg_size = len(msg)
    bytes_sent = 0
    start = 0
    end = 0
    try:
      while bytes_sent < msg_size:
        if msg_size - bytes_sent < config.MAX_MESSAGE_SIZE:
          end = msg_size
        else:
          end += config.MAX_MESSAGE_SIZE

        with self.send_seq_number_lock:
          seq_number = self.send_seq_number
        pkt = util.make_pkt(config.MSG_TYPE_DATA, seq_number, msg[start:end])
        ack_pkt = None
        while ack_pkt is None:
          print("Sending pkt: ", pkt)
          self.network_layer.send(pkt)
          ack_pkt = self.start_timer_and_wait_for_ack(seq_number)

        bytes_sent += (end - start)
        start = end
        with self.send_seq_number_lock:
          self.send_seq_number ^= 1
    except:
      raise
      # return False
    return True

  # "handler" to be called by network layer when packet is ready.
  def handle_arrival_msg(self):
    msg = self.network_layer.recv()
    print("Received packet: ", msg)

    if util.is_corrupt_pkt(msg):
      print("Received corrupt packet: ", msg)
      return

    received_msg = False
    if util.is_ack_pkt(msg):
      while not received_msg:
        with self.buffer_lock:
          if len(self.msg_buffer) < self.msg_buffer.maxlen:
            self.msg_buffer.append(msg)
            received_msg = True
    else:
      seq_number = util.pkt_seq_number(msg)
      print("Received seq number: ", seq_number)
      with self.recv_seq_number_lock:
        print("Expected seq number: ", self.recv_seq_number)
        if seq_number == self.recv_seq_number:
          received_msg = True
          self.recv_seq_number ^= 1

      if received_msg:
        self.msg_handler(util.pkt_data(msg))

      ack_pkt = util.make_pkt(config.MSG_TYPE_ACK, seq_number)
      self.network_layer.send(ack_pkt)

    # TODO: impl protocol to handle arrived packet from network layer.
    # call self.msg_handler() to deliver to application layer.

  def start_timer_and_wait_for_ack(self, seq_number):
    timer_expiry = time.time() + config.TIMEOUT_MSEC/1000.0
    while time.time() < timer_expiry:
      time.sleep(0.001)
      with self.buffer_lock:
        if len(self.msg_buffer) > 0 and util.pkt_seq_number(self.msg_buffer[0]) == seq_number:
          return self.msg_buffer.popleft()
    return None

  # Cleanup resources.
  def shutdown(self):
    # TODO: cleanup anything else you may have when implementing this
    # class.
    self.network_layer.shutdown()


import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
import os

input_dir = "../data/cube"
files = {
        "60kV": "60kV-fine-fr30-80-ept1200-ict50-b200-bf3-30-30-coeffs.csv",
        "70kV": "70kV-fine-fr30-80-ept1200-ict50-b200-bf3-30-30-coeffs.csv"
        }

style.use('ggplot')
fig, axes = plt.subplots(1,2)

for voltage, fname in files.items():
    frames, intercepts, slopes = np.genfromtxt(
            os.path.join(input_dir, fname),
            delimiter=';',
            skip_header=1,
            usecols = (0,1,3),
            unpack=True
            )
    axes[0].plot(
            frames,
            slopes,
            label=voltage
            )
    axes[1].plot(
            frames,
            intercepts,
            label=voltage
            )
for ax in axes:
    ax.set_xlabel("Frame index")
axes[0].set_ylabel(r"Slope $a$")
axes[1].set_ylabel(r"Intercept $b$")
axes[1].yaxis.tick_right()
axes[1].yaxis.set_label_position("right")
axes[1].legend(loc="center left")
plt.grid(True)
plt.tight_layout()

plt.show(); import sys; sys.exit()

from utils import save_tex
save_tex(
        __file__,
        addFigureDims=True,
        extra=set([
            r"legend style={font=\tiny}",
            r"ticklabel style={font=\tiny}"
            ])
            )


__author__ = 'wangys'

import sys

# public method
def test():
    args = sys.argv
    if len(args) == 1:
        print('Hello world!')
    elif len(args) == 2:
        print('Hello, %s!'% args[1])
    else:
        print('Too many arguments!')
# private method
def __private_method():
    print('private method')

# unittest
if __name__=='__main__':
    test()


#!/usr/bin/python3
from wsgiref.simple_server import make_server
import subprocess
import json
import threading

KEY = ''

def deploy():
    subprocess.run(
        ['sudo', 'bash', '/home/ubuntu/deploy.sh'],
        cwd="/home/ubuntu"
        )

def webhook(environ, start_response):
    print('Get Request!')
    status = '200'
    headers = [
        ('Content-type', 'application/json; charset=utf-8'),
        ('Access-Control-Allow-Origin', '*'),
    ]
    message = ""
    is_fail = False
    try:
        content_length = environ.get('CONTENT_LENGTH', 0)
        body = environ.get('wsgi.input').read(int(content_length)).decode()
        data = json.loads(body)
    except Exception as e:
        is_fail = True
        message = str(e)
        data = {'key': ''}
        print(e)

    if not is_fail and data['key'] == KEY:
        # auth
        message = "OK"
        print("Authorized.")
        deploy_thread = threading.Thread(target=deploy)
        deploy_thread.start()
    else:
        message = f"Fail\n{message}"
        print("Failed.")
    start_response(f"{status} {message}", headers)
    return [json.dumps(
        {'message': message}
    ).encode("utf-8")]

httpd = make_server('', 55544, webhook)
print("Serving on port 55544...")
httpd.serve_forever()


from django.db import models
from datetime import datetime, date, timedelta
from apps.users.models import Group
from apps.items.models import Item
from apps.recipes.models import Recipe, Recipe_Ingredients
from apps.shop.models import Shopping_Entry

STATUS_SYNCHED = 'synched'
STATUS_NEW = 'new'
STATUS_DELETED = 'deleted'

class PlanEntryManager(models.Manager):
    def addPlanEntry(self, postData, group):
        if (len(postData['recipe_id']) == 0):
            if (len(postData['item_id']) == 0):
                return None
            else:
                item = Item.objects.get(id=postData['item_id'])
                recipe = None
                type = "item"
        else:
            item = None
            recipe = Recipe.objects.get(id=postData['recipe_id'])
            type = "recipe"
        return PlanEntry.objects.create(date=postData['date'],
                                        quantity=postData['quantity'],
                                        status=STATUS_NEW,
                                        entry_type=type,
                                        group=group,
                                        recipe=recipe,
                                        item=item)

    def deletePlanEntry(self, postData):
        planEntry = PlanEntry.objects.get(id=postData['entry_id'])
        if (planEntry.status == STATUS_NEW):
            # if new (not synched) can just delete it
            planEntry.delete()
            return True
        if (planEntry.status == STATUS_SYNCHED):
            # if previously synched, need to remove from shopping lists
            # so set to deleted for next sync
            planEntry.status = STATUS_DELETED
            planEntry.save()
            return True
        # any other status is an error, so return False
        return False

    def plus1PlanEntry(self, postData):
        planEntry = PlanEntry.objects.get(id=postData['entry_id'])
        planEntry.quantity += 1
        planEntry.save()
        return True

# example:
# days = [
#     {
#         'day' : "2018-10-25",
#         'entries' : [
#             {
#                 'id' : 4,
#                 'name' : 'Bean Burritos',
#                 'quantity' : 1
#             }
#         ]
#     }
# ]

    def getPlanDays(self, startDate, numDays, group):
        planDays = []
        theStartDate = datetime.strptime(startDate, "%Y-%m-%d")
        for x in range(numDays):
            day = {}
            curDate = theStartDate + timedelta(days=x)
            # day['day'] = curDate.strftime("%Y-%m-%d")
            day['day'] = curDate
            entries = []
            planEntries = PlanEntry.objects.filter(date=curDate, group=group).exclude(status=STATUS_DELETED).order_by('-entry_type')
            for planEntry in planEntries:
                if planEntry.entry_type == "item":
                    name = planEntry.item.name
                    recipeId = None
                else:
                    name = planEntry.recipe.name
                    recipeId = planEntry.recipe.id
                entry = {
                    'id' : planEntry.id,
                    'name' : name,
                    'quantity' : planEntry.quantity,
                    'entry_type' : planEntry.entry_type,
                    'recipeId' : recipeId,
                }
                entries.append(entry)
            day['entries'] = entries
            planDays.append(day)
        return planDays

    def getSyncItems(self, group):
        planEntries = PlanEntry.objects.filter(group=group).filter(status=STATUS_NEW) | PlanEntry.objects.filter(group=group).filter(status=STATUS_DELETED)
        # Consolidate adds/deletes for each item using a dictionary
        consolidatedItems = {}
        for planEntry in planEntries:
            change = planEntry.quantity
            if planEntry.status == STATUS_DELETED:
                 change = -planEntry.quantity
            if planEntry.entry_type == "item":
                if planEntry.item.id in consolidatedItems:
                    consolidatedItems[planEntry.item.id]['change'] += change
                else:
                    consolidatedItems[planEntry.item.id] = {
                        'name' : planEntry.item.name,
                        'change' : change
                    }
            else:
                # Recipe - need to address all the ingredients
                recipe = Recipe.objects.get(id=planEntry.recipe.id)
                ingredients = Recipe_Ingredients.objects.filter(recipe=recipe)
                for ingredient in ingredients:
                    if ingredient.item.id in consolidatedItems:
                        consolidatedItems[ingredient.item.id]['change'] += change * ingredient.quantity
                    else:
                        consolidatedItems[ingredient.item.id] = {
                            'name' : ingredient.item.name,
                            'change' : change * ingredient.quantity
                        }
        # Now output the consolided list
        out = []
        for key, value in consolidatedItems.items():
            out.append({
                'name' : value['name'],
                'item_id' : key,
                'change' : value['change']
            })

        return out

    def syncToShoppingItems(self, postData, group):
        for key, value in postData.items():
            if key.startswith("item_id_"):
                itemId = int(key[8:])
                item = Item.objects.get(id=itemId)
                quantity = int(value)
                # See if there's an existing entry for the same item
                existingEntries = Shopping_Entry.objects.filter(item=item)
                if len(existingEntries) == 0:
                    if quantity > 0:
                        # No existing entry for item, create new
                        Shopping_Entry.objects.create(  group=group,
                                                        item=item,
                                                        quantity=int(value))
                else:
                    # update existing entry (should only be one, so use index 0)
                    existingEntries[0].quantity += quantity
                    if existingEntries[0].quantity > 0:
                        existingEntries[0].save()
                    else:
                        existingEntries[0].delete()
        # Update the status of plan entries after sync
        newEntries = PlanEntry.objects.filter(group=group).filter(status=STATUS_NEW)
        for newEntry in newEntries:
            newEntry.status = STATUS_SYNCHED
            newEntry.save()
        deletedEntries = PlanEntry.objects.filter(group=group).filter(status=STATUS_DELETED)
        deletedEntries.delete()

class PlanEntry(models.Model):
    date = models.DateField()
    quantity = models.IntegerField()
    # status can by 'new', 'synched', or 'deleted'
    status = models.CharField(max_length=45)
    entry_type = models.CharField(max_length=45)
    group = models.ForeignKey(Group, related_name="plan_entries")
    recipe = models.ForeignKey(Recipe, related_name="plan_entries", null=True)
    item = models.ForeignKey(Item, related_name="plan_entries", null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = PlanEntryManager()


# Copyright 2017, Goethe University
#
# This library is free software; you can redistribute it and/or
# modify it either under the terms of:
#
#   the EUPL, Version 1.1 or – as soon they will be approved by the
#   European Commission - subsequent versions of the EUPL (the
#   "Licence"). You may obtain a copy of the Licence at:
#   https://joinup.ec.europa.eu/software/page/eupl
#
# or
#
#   the terms of the Mozilla Public License, v. 2.0. If a copy of the
#   MPL was not distributed with this file, You can obtain one at
#   http://mozilla.org/MPL/2.0/.
#
# If you do not alter this notice, a recipient may use your version of
# this file under either the MPL or the EUPL.
import argparse
import deromanize
from .server import start_server

def main():
    parser = argparse.ArgumentParser()
    add = parser.add_argument
    add('config_file', help='a yaml config file for deromanize')
    add('-p', '--port', type=int, default=4891)
    add('-s', '--host', default='localhost')
    add('--path', help='path for a Unix socket')

    args = parser.parse_args()
    if args.path:
        args.host, args.port = None, None

    start_server(args.config_file,
                 deromanize.front_mid_end_decode,
                 auto_reload=True,
                 host=args.host,
                 port=args.port,
                 path=args.path)

if __name__ == '__main__':
    main()


full_names = {
    "vince": {"first_name": "Vince", "last_name": "Kamar"},
    "seneca": {"first_name": "Seneca", "last_name": "Yunger"},
    "han": {"first_name": "Han", "last_name": "Khalifa"},
    "siegelord": {"first_name": "Siegelord", "last_name": "Kalara"},
    "cato": {"first_name": "Cato", "last_name": "Yunger"},
    "marcus": {"first_name": "Marcus", "last_name": "Aurelieus"},
    "augustus": {"first_name": "Augustus", "last_name": "Octavian"},
    "lucius": {"first_name": "Lucius", "last_name": "Vorenus"},
    "titus": {"first_name": "Titus", "last_name": "Pullo"},
    "anthony": {"first_name": "Anthony", "last_name": "Zophrano"},
}

usernames = [
    "vincekamar",
    "senecatheyounger",
    "hankhalifa",
    "siegelordkalara",
    "catotheyounger",
    "marcusaurelieus",
    "augustusoctavian",
    "luciusvorenus",
    "tituspullo",
    "anthonyzophrano",
]

passwords = [
    "guioio1223",
    "wefwe6757tgy",
    "67TGufhhgf6",
    "jfht5yrf7t5f",
    "sojdf8s998yh",
    "wefh7sy7887hi",
    "sdi7g76sjbywg7",
    "89h8ferfxbjbh",
    "gw6uetfgbknjns",
    "87sgjdhbjsj7DF",
    "DFGH7gusdf87h",
    "nsb56yrtfddfdfg",
]


# Define a player object by extending pygame.sprite.Sprite
# The surface drawn on the screen is now an attribute of 'player'
from CONSTANTS import *
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pygame.Surface((75, 25))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect()

    # # Move the sprite based on user keypresses
    # def update(self, pressed_keys):
    #     if pressed_keys[K_UP]:
    #         self.rect.move_ip(0, -5)
    #     if pressed_keys[K_DOWN]:
    #         self.rect.move_ip(0, 5)
    #     if pressed_keys[K_LEFT]:
    #         self.rect.move_ip(-5, 0)
    #     if pressed_keys[K_RIGHT]:
    #         self.rect.move_ip(5, 0)
    #
    #     # Keep player on the screen
    #     if self.rect.left < 0:
    #         self.rect.left = 0
    #     if self.rect.right > SCREEN_WIDTH:
    #         self.rect.right = SCREEN_WIDTH
    #     if self.rect.top <= 0:
    #         self.rect.top = 0
    #     if self.rect.bottom >= SCREEN_HEIGHT:
    #         self.rect.bottom = SCREEN_HEIGHT


from __future__ import division
from builtins import str
from builtins import zip
from builtins import range
import copy
import hashlib
import itertools
import numpy
from ektelo.mixins import Marshallable
from ektelo.mixins import CartesianInstantiable
from ektelo.query_nd_union import ndRangeUnion
from ektelo import util
from scipy import sparse
from scipy.sparse import linalg
from functools import reduce

"""
These classes define workloads
"""

class Workload(Marshallable):

    def __init__(self, query_list, domain_shape):
        """ Basic constructor takes list of ndQuery instances and a domain shape
        """
        self.domain_shape = domain_shape
        self.query_list = query_list
        self._matrix = {}

    def compile(self):
        return self

    def get_matrix(self, matrix_format = 'sparse'):
        """
        Produces the matrix represenation of this workload on the flatten domain.
        Note that W.evaluate(X) = W.get_matrix().dot(X.flatten()) where X is a ndarray
        with shape = W.domain_shape.

        :param matrix_format: 'sparse' or 'dense' or 'linop'
            'sparse' --> for a scipy sparse matrix (e.g., csr, bsr)
            'dense' --> for a 2d numpy array
            'linop' --> for a scipy sparse LinearOperator
        :returns: the matrix represenation of this workload

        Notes for Practical Usage:
        * All three return types support dot product and transpose dot product Wx and W^T x
        * It's best to never materialize the matrix unless it is necessary to do so
        * matrix_format='linop' should be used if the workload cannot be efficiently represented as a sparse matrix (e.g., prefix workload)
        * matrix_format='sparse' should be used if the workload is sparse (e.g., Identity, AllMarginals) and you need matrix operations that are not supported by 'linop' such as indexing
        * matrix_format='dense' should not be used unless the domain is small (<= 8192)
        """
        if matrix_format in self._matrix:
            pass
        elif matrix_format == 'dense':
            self._matrix['dense'] = self.compute_matrix_dense()
        elif matrix_format == 'sparse':
            self._matrix['sparse'] = self.compute_matrix_sparse()
        elif matrix_format == 'linop':
            self._matrix['linop'] = self.compute_matrix_linop()
        return self._matrix[matrix_format]

    matrix = property(get_matrix)

    @property
    def size(self):
        return len(self.query_list)

    def __add__(self, other):
        """
        Add two workloads defined on the same domain by concatenating their queries

        :param other: the other workload to add
        :returns: a new workload with queries from this workload and other workload

        Notes:
        * It is preferable to use the Concatenate class instead of this operation
        * Information about how to efficiently compute the workload matrix is lost
            when using this operation.
        * It's okay to use this operation if you will never need the workload matrix,
            the domain size is small, or you prefer elegance to performance
        """

        assert self.domain_shape == other.domain_shape, 'domain shapes must match'
        return Workload(self.query_list + other.query_list, self.domain_shape)

    def compute_matrix_sparse(self):
        rows = len(self.query_list)
        cols = numpy.prod(self.domain_shape)
        flatidx = numpy.arange(cols).reshape(self.domain_shape)
        matrix = sparse.lil_matrix((rows, cols))
        for q, query in enumerate(self.query_list):
            for lb, ub, wgt in query.ranges:
                s = [slice(l, u+1) for l, u in zip(lb, ub)]
                idx = flatidx[s].flatten()
                matrix[q, idx] += numpy.repeat(wgt, idx.size)
        return matrix.tocsr()

    def compute_matrix_dense(self):
        rows = [r.asArray(self.domain_shape).flatten() for r in self.query_list]
        n = rows[0].size
        m = len(rows)
        matrix = numpy.empty(shape=(m,n))
        for (i,row) in enumerate(rows):
            matrix[i,:] = row
        return matrix

    # this is a default implemenation
    # subclasses can optionally make it more efficient
    def compute_matrix_linop(self):
        return linalg.aslinearoperator(self.matrix)

    def sensitivity(self):
        # copied from utilities.py
        ''' Compute sensitivity of a collection of ndRangeUnion queries '''
        maxShape = tuple( [max(l) for l in zip(*[q.impliedShape for q in self.query_list])] )
        array = numpy.zeros(maxShape)
        for q in self.query_list:
            array += q.asArray(maxShape)
        return numpy.max(array)

    def sensitivity_from_matrix(self):
        """Return the L1 sensitivity of input matrix A: maximum L1 norm of the columns."""
        return numpy.abs(self.matrix).sum(axis=0).max()

    def evaluate_matrix(self, x):
        return self.matrix.dot(x.ravel())

    def evaluate(self,x):
        '''evaluating the workload without materializing it
        :param x: data to be evaluated, expressed in flattened form
        :return : a list of queries answers'''
        assert numpy.prod(self.domain_shape) == x.size
        x= numpy.array(x, copy=True).reshape(self.domain_shape)
        return numpy.array([q.eval(x) for q in self.query_list])

    @property
    def key(self):
        """ Using leading 8 characters of hash as key for now """
        return self.hash[:8]

    def asDict(self):
        d = util.class_to_dict(self, ignore_list=['matrix', 'query_list', '_matrix'])
        return d

    def analysis_payload(self):
        return util.class_to_dict(self, ignore_list=['matrix', 'query_list', '_matrix'])

class Prefix1D(Workload, CartesianInstantiable):
    """ Workload of all 1D range queries with left bound equal to 0
        (Prefix is not well-defined in higher dimensions)
    """

    def __init__(self, domain_shape_int, pretty_name='prefix 1D'):
        self.init_params = util.init_params_from_locals(locals())

        self.pretty_name = pretty_name

        queries = [ndRangeUnion().add1DRange(0, c, 1.0) for c in range(domain_shape_int)]
        super(self.__class__,self).__init__(queries, (domain_shape_int,))

    def __repr__(self):
        r = self.__class__.__name__ + '('
        r += 'domain_shape_int=' + str(self.domain_shape[0]) + ')'
        return r

    def compute_matrix_linop(self):
        n = numpy.prod(self.domain_shape)
        def matvec(x):
            return x.cumsum()
        def rmatvec(x):
            return x[::-1].cumsum()[::-1].astype(numpy.float64)
        return linalg.LinearOperator((n,n), matvec, rmatvec, dtype=numpy.float64)

    @staticmethod
    def instantiate(params):
        return Prefix1D(params['domain'])

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        return m.hexdigest()

class RandomRange(Workload, CartesianInstantiable):
    ''' Generate m random n-dim queries, selected uniformly from list of shapes and placed randomly in n-dim domain
        shape_list: list of shape tuples
        domain_shape: a shape tuple describing domain
        m: number of queries in result
        Note: for 1-dim, shapes must be unary tuples, e.g. (2,) (or see convenience method below)
    '''

    def __init__(self, shape_list, domain_shape, size, seed=9001, pretty_name='random range'):
        self.init_params = util.init_params_from_locals(locals())

        self.shape_list = copy.deepcopy(shape_list)
        self.seed = seed
        self.pretty_name = pretty_name
        self._size = size

        prng = numpy.random.RandomState(seed)
        if shape_list == None:
            shapes = randomQueryShapes(domain_shape, prng)
        else:
            prng.shuffle(self.shape_list)
            shapes = itertools.cycle(self.shape_list) # infinite iterable over shapes in shape_list
        queries = []
        for i in range(size):
            lb, ub = placeRandomly(next(shapes), domain_shape, prng)       # seed must be None or repeats
            queries.append( ndRangeUnion().addRange(lb,ub,1.0) )
        super(RandomRange,self).__init__(queries, domain_shape)

    @staticmethod
    def instantiate(params):
        domain = params['domain']

        try:
            int(params['domain'])
            domain = [domain]
        except:
            pass

        shape_list = params['shape_list'] if 'shape_list' in params else None

        return RandomRange(shape_list, domain, params['query_size'], params['work_seed'])

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(self._size)))
        m.update(util.prepare_for_hash(str(util.standardize(self.shape_list))))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        return m.hexdigest()

    @classmethod
    def oneD(cls, shape_list, domain_shape_int, size, seed=9001):
        ''' Convenience method allowing ints to be submitted in 1D case '''
        if shape_list == None:
            return cls(None,(domain_shape_int,), size, seed)
        return cls([(i,) for i in shape_list], (domain_shape_int,), size, seed)

def randomQueryShapes(domain_shape, prng):
    ''' Generator that produces a list of range shapes; can be passed as iterator
        domain_shape: is the shape tuple of the domain
        prng: is numpy RandomState object
    '''
    while True:
        shape = [prng.randint(1, dim+1, None) for dim in domain_shape]
        yield tuple(shape)

def placeRandomly(query_shape, domain_shape, prng=None):
    ''' Place a n-dim query randomly in n-dim domain
        Return lb tuple and ub tuple which can be used to construct a range query object
    '''
    if not prng:
        prng = numpy.random.RandomState()

    lb, ub = [], []
    for i, val in enumerate(query_shape):
        lower = prng.randint(0, domain_shape[i] - query_shape[i] + 1, None)
        lb.append(lower)
        ub.append(lower + query_shape[i] - 1)
    return tuple(lb), tuple(ub)

class Identity(Workload, CartesianInstantiable):
    """ Identity workload for in k-dimensional domain """

    def __init__(self, domain_shape, weight=1.0, pretty_name='identity'):
        self.init_params = util.init_params_from_locals(locals())
        self.weight = weight
        self.pretty_name = pretty_name
        if type(domain_shape) is int:
            domain_shape = (domain_shape,)
        indexes = itertools.product(*[list(range(i)) for i in domain_shape])   # generate index tuples
        queries = [ndRangeUnion().addRange(i,i,weight) for i in indexes]
        super(self.__class__,self).__init__(queries, domain_shape)

    def compute_matrix_sparse(self):
        return sparse.identity(numpy.prod(self.domain_shape))

    @classmethod
    def oneD(cls, domain_shape_int, weight=1.0):
        return cls((domain_shape_int,), weight)

    @staticmethod
    def instantiate(params):
        return Identity(params['domain'])

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(self.weight)))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        return m.hexdigest()

class Total(Workload, CartesianInstantiable):
    def __init__(self, domain_shape, pretty_name = 'total'):
        self.pretty_name = pretty_name
        if type(domain_shape) is int:
            domain_shape = (domain_shape,)
        lb = tuple(0 for _ in domain_shape)
        ub = tuple(x-1 for x in domain_shape)
        q = ndRangeUnion().addRange(lb, ub, 1.0)
        super(self.__class__, self).__init__([q], domain_shape)

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        return m.hexdigest()

class Concatenate(Workload):
    """
    A class for constructing workloads of the same shape by concatenating their queries.
    """
    def __init__(self, workloads, pretty_name = 'concat'):
        """
        :param workloads: a list of workoads defined on the same domain
        :param pretty_name: name of this workload (default = 'concat')
        :returns: A new workload with all the queries from the given workloads

        Note: this class provides an efficient implementation of W.get_matrix
        for matrix_format='sparse', 'dense', and 'linop' assuming there is an
        efficient implementation in each of the given workloads.
        """
        self.pretty_name = pretty_name
        self.workloads = workloads
        assert len(workloads) >= 1, 'must have at least 1 workload'
        domain_shape = workloads[0].domain_shape
        assert all(w.domain_shape == domain_shape for w in workloads), 'shape mismatch'
        query_list = []
        for w in workloads:
            query_list.extend(w.query_list)
        super(Concatenate, self).__init__(query_list, domain_shape)

    # TODO(ryan): if the purpose of overriding is for efficiency
    # should we even worry about dense matrices?
    def compute_matrix_dense(self):
        matrices = [w.compute_matrix_dense() for w in self.workloads]
        return numpy.vstack(matrices)

    # overridden for efficiency
    def compute_matrix_sparse(self):
        matrices = [w.compute_matrix_sparse() for w in self.workloads]
        return sparse.vstack(matrices).tocsr() # TODO(ryan): should we convert to csr?

    def compute_matrix_linop(self):
        linops = [w.compute_matrix_linop() for w in self.workloads]
        sizes = [L.shape[0] for L in linops]
        indices = numpy.cumsum(sizes)
        n = numpy.prod(self.domain_shape)
        m = sum(sizes)
        def matvec(x):
            return numpy.concatenate([L.matvec(x) for L in linops])
        def rmatvec(x):
            return sum(L.rmatvec(v) for L,v in zip(linops, numpy.split(x, indices)))
        return linalg.LinearOperator((m,n), matvec, rmatvec, dtype=numpy.float64)

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        for w in self.workloads:
            m.update(util.prepare_for_hash(w.hash))
        return m.hexdigest()

class Kronecker(Workload):
    """
    A class for constructing high dimensional workloads from low dimensional building blocks.

    Roughly speaking, this class constructs a new workload by taking the cartesian product of
    queries from the input workloads.
    """
    def __init__(self, workloads, pretty_name = 'kronecker'):
        """
        :param workloads: a list of workoads defined on any combination of domains
        :param pretty_name: name of this workload (default = 'kronecker')
        :returns: A new high dimensional workload constructed by taking the
            cartesian product of queries from the given workloads

        Note: this class provides an efficient implementation of W.get_matrix
        for matrix_format='sparse', 'dense', and 'linop' assuming there is an
        efficient implementation in each of the given workloads.  Thus it is
        preferable to use this over the (lowercase) function kronecker.
        """
        self.pretty_name = pretty_name
        self.workloads = workloads
        this = kronecker(workloads)
        super(Kronecker, self).__init__(this.query_list, this.domain_shape)

    def compute_matrix_dense(self):
        matrices = [w.compute_matrix_dense() for w in self.workloads]
        return reduce(numpy.kron, matrices)

    # overridden for efficiency
    def compute_matrix_sparse(self):
        matrices = [w.compute_matrix_sparse() for w in self.workloads]
        return reduce(sparse.kron, matrices)

    # overridden for efficiency
    # note that the linear operator will always be space efficient
    # it will be most time efficient if the true LinearOperators are
    # on the last dimension (sparse matrices come first)
    # if workloads = [S,S,S,L,S,S,S,L] --> [S,S,S,L,L,L,L,L] (bad)
    # if workloads = [S,S,S,S,S,S,L,L] --> [S,S,S,S,S,S,L,L] (good)
    # since reduce is left associative, the first linear operator it sees
    # will cause all subsequent objects to be linear operators too
    # kron for linear operators is lazy, so there is some overhead to that
    def compute_matrix_linop(self):
        linops = [w.compute_matrix_linop() for w in self.workloads]
        return reduce(linop_kron, linops)

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        for w in self.workloads:
            m.update(util.prepare_for_hash(w.hash))
        return m.hexdigest()

class KWayMarginals(Concatenate, CartesianInstantiable):
    """ Workload consisting of all K-way marginals where 0 <= k <= number of dimensions"""

    def __init__(self, domain_shape, k, pretty_name = 'k-way marginals'):
        self.init_params = util.init_params_from_locals(locals())
        self.pretty_name = pretty_name
        if type(domain_shape) is int:
            domain_shape = (domain_shape,)
        assert 0 <= k <= len(domain_shape), 'invalid k'
        self.k = k
        D = len(domain_shape)

        idents = [Identity.oneD(n) for n in domain_shape]
        totals = [Total(n) for n in domain_shape]

        workloads = []
        for c in itertools.combinations(list(range(D)), k):
            oned = [idents[i] if i in c else totals[i] for i in range(D)]
            workloads.append(Kronecker(oned))
        super(self.__class__, self).__init__(workloads)

    @staticmethod
    def instantiate(params):
        return KWayMarginals(params['domain'],params['k'])

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(self.k)))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        return m.hexdigest()

class PrefixMarginals(Kronecker, CartesianInstantiable):
    """ Workload consisting of Prefix queries on dimensions identified by prefix_axes
        and marginals on all other axes
    """

    def __init__(self, domain_shape, prefix_axes=(0,), pretty_name='prefix marginals'):
        self.init_params = util.init_params_from_locals(locals())
        self.pretty_name = pretty_name
        self.prefix_axes = prefix_axes
        if type(domain_shape) is int:
            domain_shape = (domain_shape,)

        if len(domain_shape) - len(prefix_axes) > min(prefix_axes):
            import warnings
            warnings.warn('It is not recommended to construct PrefixMarginals this way.  Transpose the data so that the prefix workloads are on the last dimensions')

        oned = []
        for i, n in enumerate(domain_shape):
            if i in self.prefix_axes:
                oned.append( Prefix1D(n) )
            else:
                oned.append(Identity.oneD(n) + Total(n))
        super(self.__class__, self).__init__(oned)

    @staticmethod
    def instantiate(params):
        return PrefixMarginals(params['domain'], params['prefix_axes'])

    @property
    def hash(self):
        m = hashlib.sha1()
        m.update(util.prepare_for_hash(self.__class__.__name__))
        m.update(util.prepare_for_hash(str(util.standardize(self.domain_shape))))
        m.update(util.prepare_for_hash(str(util.standardize(self.prefix_axes))))
        return m.hexdigest()

def merge(q1, q2):
    ''' merge an n dimensional query and an m dimensional query into an (n+m) dimensional query '''
    ans = ndRangeUnion()
    for (lb1, ub1, wgt1) in q1.ranges:
        for (lb2, ub2, wgt2) in q2.ranges:
            ans.addRange(lb1 + lb2, ub1 + ub2, wgt1 * wgt2)
    return ans

def kron(W1, W2):
    ''' merge an n dimensional workload and an m dimensional workload into an (n+m) dimensional workl
oad '''
    dom1, dom2 = W1.domain_shape, W2.domain_shape
    queries = [merge(q1, q2) for q1 in W1.query_list for q2 in W2.query_list]
    return Workload(queries, dom1 + dom2)

# (Workload, kron) is a monoid with identity element zero
def kronecker(workloads):
    ''' merge a list of low dimensional workloads into a single high dimensional workload '''
    zq = ndRangeUnion().addRange(tuple(), tuple(), 1.0)
    zero = Workload([zq], tuple())
    return reduce(kron, workloads, zero)

def linop_kron(A, B):
    """
    Compute the kron product between two scipy.sparse.LinearOperators

    :param A: A m1 x n1 linear operator
    :param B: A m2 x n2 linear operator
    :returns: A new linear operator of size m1*m2 x n1*n2 representing the matrix kron(A,B)

    """
    # if A and B are both sparse matrices, we are better off explicitly computing kron product
    if isinstance(A, linalg.interface.MatrixLinearOperator) and \
        isinstance(B, linalg.interface.MatrixLinearOperator) and \
        sparse.isspmatrix(A.A) and sparse.issparse(B.A):
        return linalg.aslinearoperator(sparse.kron(A.A,B.A))

    am, an = A.shape
    bm, bn = B.shape
    shape = (am*bm, an*bn)
    # These expressions are derived from the matrix equations
    # vec(A X B) = kron(A, B^T) vec(X) where vec(Z) is Z.flatten()
    def matvec(x):
        X = x.reshape(an, bn, order='C')
        return B.matmat(A.matmat(X).T).T.flatten(order='C')
    def rmatvec(x):
        X = x.reshape(am, bm, order='C')
        return B.H.matmat(A.H.matmat(X).T).T.flatten(order='C')
    return linalg.LinearOperator(shape, matvec, rmatvec, dtype=numpy.float64)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Answer2',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('index_1', models.IntegerField(editable=False)),
                ('index_2', models.IntegerField(editable=False)),
                ('score', models.IntegerField(editable=False)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Image2',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=255)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='User2',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('code', models.CharField(unique=True, max_length=8)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('answer_number', models.IntegerField(default=0)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='answer2',
            name='user',
            field=models.ForeignKey(editable=False, to='q2.User2'),
            preserve_default=True,
        ),
    ]


from django import forms
from django.forms import ModelForm

from .models import Genre, Track

class GenreForm(ModelForm):
	class Meta:
		model = Genre
		fields = ["name"]

class TrackForm(ModelForm):
	updated_genre = forms.CharField(max_length=30, required=False)
	class Meta:
		model = Track
		fields = ["title", "genre", "rating"]

	def __init__(self, *args, **kwargs):
		super(TrackForm, self).__init__(*args, **kwargs)
		self.fields['genre'].required = False

	def clean(self):
		genre = self.cleaned_data.get('updated_genre')
		if genre:
			genre, created = Genre.objects.get_or_create(name=genre)
			self.cleaned_data['genre'] = genre
		else:
			raise forms.ValidationError('Must specify a genre!')
		return super(TrackForm, self).clean()


from conans import ConanFile, tools
import os
import re

class ProtobufConan(ConanFile):
    name = "protobuf"
    version = "3.9.1"
    license = "https://raw.githubusercontent.com/google/protobuf/master/LICENSE"
    url = "https://github.com/kmaragon/conan-protobuf"
    settings = "os", "compiler", "build_type", "arch"
    options = {
        "shared": [True, False],
        "with_zlib": [True, False]
    }

    default_options = "shared=False","with_zlib=True"
    generators = "virtualbuildenv"
    description = "*nix only (for now) implementation of protobuf that can be used as a dep for other libs"

    def configure(self):
        if self.options.with_zlib:
            self.requires("zlib/1.2.11")

    def source(self):
        tools.download("https://github.com/google/protobuf/archive/v%s.tar.gz" % self.version,
                       "protobuf.tar.gz")

        tools.unzip("protobuf.tar.gz")
        os.unlink("protobuf.tar.gz")

        # autogen
        self.run("chmod +x protobuf-%s/autogen.sh" % self.version)
        self.run("cd protobuf-%s && ./autogen.sh" % self.version)

    def build(self):
        flags = "--enable-shared" if self.options.shared else "--disable-shared CXXFLAGS=-fPIC" # + \
                # ("--disable-static" if self.options.shared else "--enable-static")

        make_options = os.getenv("MAKEOPTS") or ""
        if not re.match("/[^A-z-a-z_-]-j", make_options):
            cpucount = tools.cpu_count()
            make_options += " -j %s" % cpucount

        cdir = os.getcwd()
        image_location = os.path.join(cdir, "buildimg")

        # configure
        self.run("chmod +x protobuf-%s/configure" % self.version)
        self.run(". ./activate_build.* && cd protobuf-%s && ./configure --prefix=%s %s" % (self.version, image_location, flags))

        # build
        self.run(". ./activate_build.* && cd protobuf-%s && make %s" % (self.version, make_options))

    def package(self):
        self.run("cd protobuf-%s && make install" % self.version)
        if self.options.shared:
            if self.settings.os == "Windows":
                self.copy("*.lib", dst="lib", src="buildimg/lib")
                self.copy("*.dll", dst="lib", src="buildimg/lib")
            elif self.settings.os == "Macos":
                self.copy("*.dylib*", dst="lib", src="buildimg/lib", links=True)
            else:
                self.copy("*.so*", dst="lib", src="buildimg/lib", links=True)
        else:
            if self.settings.os == "Windows":
                self.copy("*.lib", dst="lib", src="buildimg/lib")
            else:
                self.copy("*.a", dst="lib", src="buildimg/lib")

        self.copy("*", dst="include", src="buildimg/include")
        self.copy("*", dst="bin", src="buildimg/bin")

    def package_info(self):
        self.cpp_info.libs = ["protobuf"]
        self.cpp_info.libdirs = ["lib"]
        self.cpp_info.includedirs = ["include"]
        self.cpp_info.bindirs = ["bin"]


class Solution(object):
    #unable to solve but will work on correcting error by Fri
    def fn(s):
        words = []
        for char in s:
            if char.isalpha() or char.isdigit():
                words.append(char.lower())

        reverse = words.copy()
        reverse.reverse()

        print(reverse)
        print(words)

        #return words == reverse

    story = "A man, a plan, a canal: Panama"
    story1 = "race a car"
    print(fn(story1))


# coding: utf-8
# @author: hongxin
# @date: 9/16/18

"""
二分查找

来源：算法图解

优缺点：
- 查找速度快，不过应该没哈希表快
- n个元素的列表，简单查找n步， 二分查找log2n步。

注意事项：
- 列表必须有序

二分查找 VS 直接查找:
列表长度为100： 7次 VS 100次
列表长度为1亿： 32次 VS 1亿次
"""

def binary_search(arr, item):
    """
    假设序列从小到大
    """
    low = 0
    high = len(arr)-1
    while low <= high:
        # 元素找不到的话, low 会增加到和high一致, 如果这时候还是找不到, low会大于high, 返回None
        # high的情况与low一致
        mid = (low + high) // 2  #
        guess = arr[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

arr_test = [1, 2, 3, 4, 5]
print(binary_search(arr_test, 7))